diff --git a/docs/quantinuum/NEXUS_SDK_QUICKSTART.md b/docs/quantinuum/NEXUS_SDK_QUICKSTART.md new file mode 100644 index 00000000..e0f0b59b --- /dev/null +++ b/docs/quantinuum/NEXUS_SDK_QUICKSTART.md @@ -0,0 +1,63 @@ +# Quantinuum Nexus with osiris-cli (qnexus SDK) + +`osiris nexus` drives Quantinuum Nexus through the official `qnexus` SDK, pinned to 0.51.4. Every call it makes is tested against that version's real function signatures (`tests/test_nexus_sdk.py`). + +The older `QuantinuumNexusClient` in `providers/quantinuum_nexus.py` sends hand-written REST calls to `/api/v1/backends`, `/api/v1/targets` and `/api/v1/jobs`. Those paths are not part of the Nexus API, so use `osiris nexus` for real runs. + +## Once access is granted + +```bash +pip install 'osiris-cli[nexus]' # installs qnexus==0.51.4 +qnx login # interactive; tokens are stored by qnexus, not by OSIRIS +``` + +## 1. Preflight (Tier 1, free) + +```bash +osiris nexus preflight docs/xtop005/quantinuum/circuits_h2_1_tket.json --target H2-1 --shots 500 \ + --out preflight.json +``` + +This command: + +1. uploads the circuits to the Nexus project `OSIRIS`; +2. compiles them for H2-1 on Nexus at `-O 0`; +3. prices each compiled circuit with Quantinuum's syntax checker (`circuits.cost(..., syntax_checker="H2-1SC")`); +4. cross-checks that price against the local HQC formula; +5. writes a Tier 1 receipt to `$OSIRIS_HOME/quantum/nexus_dispositions.jsonl`. + +The preflight output includes the compiled-batch SHA-256. A hardware approval token is bound to that hash. + +**First check:** compare Nexus's HQC total with the offline design figure for the XTOP-005 decisive comparison (1,336 HQC at 500 shots). Any difference shows exactly where the local model is wrong. + +## 2. Emulate (Tier 2, emulator quota) + +```bash +osiris nexus run docs/xtop005/quantinuum/circuits_h2_1_tket.json --target H2-1E --shots 100 \ + --max-emulator-hqc 200 --match '_(Q0|Q3)_L3_' --out h2-1e.json +``` + +The run refuses to start if the estimated cost is above `--max-emulator-hqc`. Each circuit is also submitted with its own `max_cost` cap. Results are recorded as `SIMULATED` with `hardware=false`. + +Circuit names follow `xtop005q__L_`, so `--match '_(Q0|Q3)_L3_'` selects the decisive comparison: bare against fully encoded with checks at depth 3, 18 circuits in total. + +## 3. Hardware (Tier 3, only after an explicit decision) + +```bash +osiris nexus grant --compiled-sha --target H2-1 --shots 500 --budget-hqc 1400 +osiris nexus run --target H2-1 --shots 500 --approval-token +``` + +The run refuses to start in any of these cases: + +- there is no token; +- the token was signed for a different compiled batch, target, shot count or HQC budget; +- Nexus compiles the circuits to a different batch than the one the token names. + +`HARDWARE_ATTESTED` is written only for a completed Tier 3 job with a real job ID. + +## Ledger + +```bash +osiris nexus status # verifies the hash chain and lists recent receipts +``` diff --git a/osiris_cli/providers/nexus_sdk.py b/osiris_cli/providers/nexus_sdk.py new file mode 100644 index 00000000..9cfc3389 --- /dev/null +++ b/osiris_cli/providers/nexus_sdk.py @@ -0,0 +1,250 @@ +"""Quantinuum Nexus transport built on the official ``qnexus`` SDK (pinned 0.51.4). + +Why this module exists: ``quantinuum_nexus.QuantinuumNexusClient`` speaks a hand-written REST dialect +(``/api/v1/backends``, ``/api/v1/targets``, ``/api/v1/jobs``) that the Nexus service does not expose; the +real API is versioned per resource (``/api/circuits/v1beta2``, ``/api/jobs/v1beta3``, ...) and authenticates +with ``qnx.login()`` tokens. Rather than re-implement that API, this module calls the SDK, so request shapes +and auth come from Quantinuum's own client. Every SDK call goes through ``NexusSdkRunner._call`` so tests +can record the exact keyword arguments and check them against the real ``qnexus`` signatures. + +Flow (each step writes a ``NexusDisposition`` to the hash-chained ``NexusAuditLedger``): + + preflight upload -> compile on Nexus (``start_compile_job``) -> price every compiled circuit with + Quantinuum's syntax checker (``circuits.cost(..., syntax_checker="H2-1SC")``) and cross-check + against the local HQC formula. Tier 1, costs nothing. + run execute compiled circuits (``start_execute_job``) with a per-circuit ``max_cost`` cap. + Tier 2 (emulators, e.g. H2-1E) is capped by ``max_emulator_hqc``; Tier 3 (H2-1, H2-2) refuses + to start without a signed Tier 3 token bound to the compiled-circuit SHA-256, target, shots + and HQC (``quantinuum_gate.verify_tier3_token``). + +Login is interactive and is the operator's job: ``python -c "import qnexus; qnexus.login()"``. +""" + +from __future__ import annotations + +import hashlib +import json +from dataclasses import dataclass, field +from decimal import Decimal +from pathlib import Path +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple + +from .quantinuum import compute_hqc, resolve_quantinuum_target +from .quantinuum_nexus import GovernanceError, NexusDisposition + +QNEXUS_VERSION = "0.51.4" + + +class NexusSdkUnavailable(RuntimeError): + pass + + +def load_qnexus(): + try: + import qnexus # type: ignore[import-not-found] + except ImportError as exc: # pragma: no cover - exercised only without the extra + raise NexusSdkUnavailable( + f"qnexus is not installed. Install the extra: pip install 'osiris-cli[nexus]' (qnexus=={QNEXUS_VERSION})" + ) from exc + return qnexus + + +def tket_sha256(circ: Any) -> str: + """SHA-256 of a pytket circuit's canonical JSON (sorted keys, no whitespace).""" + return hashlib.sha256(json.dumps(circ.to_dict(), sort_keys=True, separators=(",", ":")).encode()).hexdigest() + + +def batch_sha256(hashes: Sequence[str]) -> str: + return hashlib.sha256("\n".join(hashes).encode()).hexdigest() + + +def local_hqc(circ: Any, shots: int) -> Decimal: + """Local HQC formula on a compiled pytket circuit: Rz is virtual (free); PhasedX/other 1q gates count 1, + 2q gates 10, measurements + resets + one preparation per qubit count 5.""" + from pytket import OpType + n1 = n2 = nm = 0 + for cmd in circ.get_commands(): + op = cmd.op + while op.type == OpType.Conditional: + op = op.op + t = op.type + if t in (OpType.Measure, OpType.Reset): + nm += 1 + elif t in (OpType.Barrier, OpType.Rz) or not cmd.qubits: + continue + elif len(cmd.qubits) == 1: + n1 += 1 + elif len(cmd.qubits) == 2: + n2 += 1 + return compute_hqc(n1, n2, nm + circ.n_qubits, shots) + + +def load_circuits(path: Path) -> List[Any]: + """Read circuits from .qasm (OpenQASM 2.0), pytket JSON (one dict), or a list of {"name", "tket"} + entries such as docs/xtop005/quantinuum/circuits_h2_1_tket.json.""" + from pytket import Circuit + p = Path(path) + if p.suffix.lower() == ".qasm": + from pytket.qasm import circuit_from_qasm + c = circuit_from_qasm(str(p)) + c.name = c.name or p.stem + return [c] + data = json.loads(p.read_text()) + items = data if isinstance(data, list) else [data] + out = [] + for i, it in enumerate(items): + d = it.get("tket", it) if isinstance(it, dict) else it + c = Circuit.from_dict(d) + c.name = (it.get("name") if isinstance(it, dict) else None) or c.name or f"{p.stem}_{i}" + out.append(c) + return out + + +@dataclass +class PreflightResult: + target: str + shots: int + project_id: str + compile_job_id: str + compiled_refs: List[Any] + compiled_sha256: List[str] + source_sha256: List[str] + nexus_hqc: List[Optional[float]] + local_hqc: List[str] + receipt: Dict[str, Any] = field(default_factory=dict) + + @property + def total_nexus_hqc(self) -> Optional[float]: + return None if any(v is None for v in self.nexus_hqc) else round(sum(self.nexus_hqc), 6) + + @property + def total_local_hqc(self) -> str: + return str(sum((Decimal(v) for v in self.local_hqc), Decimal("0"))) + + def summary(self) -> Dict[str, Any]: + return {"target": self.target, "shots": self.shots, "circuits": len(self.compiled_refs), + "project_id": self.project_id, "compile_job_id": self.compile_job_id, + "compiled_batch_sha256": batch_sha256(self.compiled_sha256), + "nexus_hqc_total": self.total_nexus_hqc, "local_hqc_total": self.total_local_hqc, + "receipt_sha256": self.receipt.get("receipt_sha256")} + + +class NexusSdkRunner: + def __init__(self, qnx: Any = None, ledger: Any = None, project_name: str = "OSIRIS", + project_description: str = "OSIRIS governed experiments (osiris-cli)") -> None: + self._qnx = qnx if qnx is not None else load_qnexus() + if ledger is None: + from ..nexus_ledger import NexusAuditLedger + ledger = NexusAuditLedger() + self.ledger = ledger + self.project_name = project_name + self.project_description = project_description + self.calls: List[Tuple[str, Dict[str, Any]]] = [] + self._project = None + + # Every SDK call goes through here (recorded for signature tests; positional args are never used). + def _call(self, dotted: str, **kwargs: Any) -> Any: + self.calls.append((dotted, kwargs)) + fn: Any = self._qnx + for part in dotted.split("."): + fn = getattr(fn, part) + return fn(**kwargs) + + def _config(self, device_name: str): + return self._qnx.QuantinuumConfig(device_name=device_name) + + def project(self): + if self._project is None: + self._project = self._call("projects.get_or_create", name=self.project_name, + description=self.project_description) + return self._project + + def _record(self, **kw: Any) -> Dict[str, Any]: + return self.ledger.append_disposition(NexusDisposition(**kw)) + + def preflight(self, circuits: Sequence[Any], target: str = "H2-1", shots: int = 500, + optimisation_level: int = 0, job_name: str = "osiris-preflight", + timeout: float = 900.0) -> PreflightResult: + """Compile on Nexus for ``target`` (an H2 QPU name) and price it with that QPU's syntax checker.""" + spec = resolve_quantinuum_target(target) + if spec.family != "H2" or spec.role != "qpu": + raise GovernanceError(f"preflight takes an H2 QPU name (H2-1, H2-2) to compile and price for; got {target}") + checker = f"{spec.name}SC" + proj = self.project() + src = [tket_sha256(c) for c in circuits] + refs = [self._call("circuits.upload", circuit=c, project=proj, name=c.name or f"{job_name}-{i}") + for i, c in enumerate(circuits)] + job = self._call("start_compile_job", programs=refs, backend_config=self._config(spec.name), + name=job_name, project=proj, optimisation_level=optimisation_level) + self._call("jobs.wait_for", job=job, timeout=timeout) + results = self._call("jobs.results", job=job) + compiled_refs = [r.get_output() for r in results] + compiled = [r.download_circuit() for r in compiled_refs] + comp_sha = [tket_sha256(c) for c in compiled] + nexus_cost: List[Optional[float]] = [] + for r in compiled_refs: + v = self._call("circuits.cost", circuit_ref=r, n_shots=shots, + backend_config=self._config(spec.name), syntax_checker=checker) + nexus_cost.append(None if v is None else float(v)) + local = [str(local_hqc(c, shots)) for c in compiled] + job_id = str(getattr(job, "id", "")) + res = PreflightResult(target=spec.name, shots=shots, project_id=str(getattr(proj, "id", "")), + compile_job_id=job_id, compiled_refs=compiled_refs, compiled_sha256=comp_sha, + source_sha256=src, nexus_hqc=nexus_cost, local_hqc=local) + res.receipt = self._record( + target=checker, tier=1, disposition="SIMULATED", hardware=False, status="COMPLETED", + job_id=job_id, shots=shots, + estimated_hqc=float(res.total_nexus_hqc if res.total_nexus_hqc is not None else res.total_local_hqc), + source_sha256=batch_sha256(src), compiled_sha256=batch_sha256(comp_sha), compiler_backend="nexus-sdk", + preflight_target=checker, preflight_job_id=job_id, preflight_passed=True, + metrics={"nexus_hqc": nexus_cost, "local_hqc": local, "circuits": len(compiled), + "compiled_for": spec.name, "optimisation_level": optimisation_level}, + compiler_options={"qnexus": QNEXUS_VERSION, "optimisation_level": optimisation_level}) + return res + + def run(self, pre: PreflightResult, target: str, shots: Optional[int] = None, + approval_token: Optional[str] = None, max_emulator_hqc: float = 200.0, + job_name: str = "osiris-run", timeout: float = 3600.0, + verify_token: Optional[Callable[..., Any]] = None) -> Dict[str, Any]: + """Execute the pre-flighted circuits on ``target`` (H2-1E/H2-2E emulator, or H2-1/H2-2 hardware).""" + spec = resolve_quantinuum_target(target) + if spec.tier == 1: + raise GovernanceError("run needs an emulator or QPU target; the syntax checker ran in preflight") + shots = int(shots or pre.shots) + if shots == pre.shots and pre.total_nexus_hqc is not None: + per_circ = [Decimal(str(v)) for v in pre.nexus_hqc] + else: + scale = Decimal(shots) / Decimal(pre.shots) + per_circ = [Decimal("5") + (Decimal(v) - Decimal("5")) * scale for v in pre.local_hqc] + total = sum(per_circ, Decimal("0")) + compiled_batch = batch_sha256(pre.compiled_sha256) + if spec.tier == 2 and total > Decimal(str(max_emulator_hqc)): + raise GovernanceError(f"emulator run would cost ~{total} HQC, above max_emulator_hqc={max_emulator_hqc}") + if spec.tier == 3: + if not approval_token: + raise GovernanceError(f"{spec.name} is live hardware: a signed Tier 3 approval token is required") + if verify_token is None: + from ..quantinuum_gate import verify_tier3_token as verify_token + verify_token(approval_token, compiled_batch, spec, shots, total, compiled_sha256=compiled_batch) + caps = [float(v) + 1.0 for v in per_circ] + job = self._call("start_execute_job", programs=pre.compiled_refs, n_shots=[shots] * len(pre.compiled_refs), + backend_config=self._config(spec.name), name=job_name, project=self.project(), + max_cost=caps) + self._call("jobs.wait_for", job=job, timeout=timeout) + results = self._call("jobs.results", job=job) + counts = [] + for r in results: + br = r.download_result() + c = br.get_counts() + counts.append({"".join(str(b) for b in k): int(v) for k, v in sorted(c.items())}) + job_id = str(getattr(job, "id", "")) + hw = spec.tier == 3 + receipt = self._record( + target=spec.name, tier=spec.tier, disposition="HARDWARE_ATTESTED" if hw else "SIMULATED", + hardware=hw, status="COMPLETED", job_id=job_id, shots=shots, estimated_hqc=float(total), + source_sha256=batch_sha256(pre.source_sha256), compiled_sha256=compiled_batch, + compiler_backend="nexus-sdk", preflight_target=f"{pre.target}SC", preflight_job_id=pre.compile_job_id, + preflight_passed=True, metrics={"circuits": len(counts), "max_cost_per_circuit": caps}, + compiler_options={"qnexus": QNEXUS_VERSION}) + return {"target": spec.name, "job_id": job_id, "shots": shots, "hqc_estimate": str(total), + "counts": counts, "receipt": receipt} diff --git a/osiris_cli/quantinuum_cli.py b/osiris_cli/quantinuum_cli.py index b88adaea..5a8437ea 100644 --- a/osiris_cli/quantinuum_cli.py +++ b/osiris_cli/quantinuum_cli.py @@ -10,6 +10,10 @@ - `osiris run --target H2-1 --shots 500 --budget-hqc 25 --approval-token TOKEN` - `osiris ledger verify [--home DIR] [--json]` - `osiris ledger upload [--url URL] [--dry-run] [--home DIR] [--json]` + - `osiris nexus preflight --target H2-1 --shots 500 [-O 0] [--out FILE]` (qnexus SDK, Tier 1) + - `osiris nexus run --target H2-1E --compile-for H2-1 --shots 100 [--max-emulator-hqc 200]` + - `osiris nexus grant --compiled-sha SHA --target H2-1 --shots 500 --budget-hqc 1400` + - `osiris nexus run --target H2-1 --shots 500 --approval-token TOKEN` (live QPU, Tier 3) """ from __future__ import annotations @@ -453,6 +457,75 @@ def cmd_ledger(argv: Sequence[str]) -> int: return 0 if summary["valid"] else 2 +def cmd_nexus(argv: Sequence[str]) -> int: + """Quantinuum Nexus via the official qnexus SDK (see osiris_cli/providers/nexus_sdk.py).""" + parser = argparse.ArgumentParser(prog="osiris nexus", description="Quantinuum Nexus via the qnexus SDK") + sub = parser.add_subparsers(dest="action", required=True) + pre = sub.add_parser("preflight", help="Compile on Nexus and price with the H2 syntax checker (free)") + run = sub.add_parser("run", help="Preflight, then execute on an emulator (H2-1E) or QPU (H2-1, token required)") + for sp in (pre, run): + sp.add_argument("circuits", help=".qasm (OpenQASM 2.0), pytket JSON, or a JSON list of {name, tket}") + sp.add_argument("--shots", type=int, default=500) + sp.add_argument("-O", "--optimisation-level", type=int, default=0) + sp.add_argument("--project", default="OSIRIS") + sp.add_argument("--limit", type=int, default=None, help="Use only the first N circuits") + sp.add_argument("--match", default=None, help="Keep circuits whose name matches this regex") + sp.add_argument("--out", default=None, help="Write the JSON summary here") + pre.add_argument("--target", default="H2-1", help="H2 QPU to compile and price for (H2-1, H2-2)") + run.add_argument("--target", required=True, help="H2-1E / H2-2E emulator, or H2-1 / H2-2 hardware") + run.add_argument("--compile-for", default=None, help="QPU to compile for (default: target without the E)") + run.add_argument("--max-emulator-hqc", type=float, default=200.0) + run.add_argument("--approval-token", default=None) + gr = sub.add_parser("grant", help="Mint a Tier 3 token bound to a compiled batch SHA-256 from preflight") + gr.add_argument("--compiled-sha", required=True) + gr.add_argument("--target", required=True) + gr.add_argument("--shots", type=int, required=True) + gr.add_argument("--budget-hqc", required=True) + gr.add_argument("--ttl", type=int, default=3600) + st = sub.add_parser("status", help="Verify the Nexus disposition ledger and list recent entries") + st.add_argument("--last", type=int, default=5) + args = parser.parse_args(list(argv)) + + try: + if args.action == "grant": + print(mint_tier3_token(circuit_sha256=args.compiled_sha, target=args.target, max_shots=args.shots, + max_hqc=args.budget_hqc, ttl_seconds=args.ttl)) + return 0 + if args.action == "status": + led = NexusAuditLedger() + rows = led.list_entries()[-args.last:] + print(json.dumps({"ledger": str(led.path), "verify": led.verify(), + "recent": [r.get("body", {}) for r in rows]}, indent=2, default=str)) + return 0 + from .providers.nexus_sdk import NexusSdkRunner, load_circuits + circuits = load_circuits(Path(args.circuits)) + if args.match: + import re + circuits = [c for c in circuits if re.search(args.match, c.name or "")] + if args.limit: + circuits = circuits[: args.limit] + runner = NexusSdkRunner(project_name=args.project) + if args.action == "preflight": + res = runner.preflight(circuits, target=args.target, shots=args.shots, + optimisation_level=args.optimisation_level) + out = res.summary() + else: + compile_for = args.compile_for or (args.target[:-1] if args.target.upper().endswith("E") else args.target) + res = runner.preflight(circuits, target=compile_for, shots=args.shots, + optimisation_level=args.optimisation_level) + out = {"preflight": res.summary(), + "run": runner.run(res, target=args.target, shots=args.shots, approval_token=args.approval_token, + max_emulator_hqc=args.max_emulator_hqc)} + except Exception as exc: + print(f"NEXUS_ERROR: {type(exc).__name__}: {exc}", file=sys.stderr) + return 2 + body = json.dumps(out, indent=2, default=str) + if args.out: + Path(args.out).write_text(body + "\n", encoding="utf-8") + print(body) + return 0 + + def handle_repl_quantinuum(arg_str: str = "", osiris_home: Optional[str] = None) -> str: """Read-only `/quantinuum` REPL summary and deterministic pre-flight dispatcher.""" tokens = shlex.split(arg_str.strip()) if arg_str.strip() else ["targets"] @@ -518,6 +591,8 @@ def dispatch_quantinuum_argv(argv: List[str]) -> Optional[int]: return cmd_run(rest) if head == "ledger": return cmd_ledger(rest) + if head == "nexus": + return cmd_nexus(rest) if head in ("quantinuum", "/quantinuum"): try: print(handle_repl_quantinuum(" ".join(rest))) diff --git a/pyproject.toml b/pyproject.toml index e9f0d70c..4ca857aa 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -51,6 +51,10 @@ quantum = [ quantinuum = [ "pytket>=1.28.0", ] +# Quantinuum Nexus via the official SDK (osiris nexus ...); pinned to the version the adapter was checked against. +nexus = [ + "qnexus==0.51.4", +] tui = [ "textual>=0.40.0", ] diff --git a/tests/test_nexus_sdk.py b/tests/test_nexus_sdk.py new file mode 100644 index 00000000..53d42e57 --- /dev/null +++ b/tests/test_nexus_sdk.py @@ -0,0 +1,172 @@ +"""Offline tests for the qnexus-SDK Nexus transport (osiris_cli/providers/nexus_sdk.py).""" + +import inspect +import json +import uuid +from collections import Counter + +import pytest + +pytket = pytest.importorskip("pytket") +from pytket import Circuit, OpType # noqa: E402 + +from osiris_cli.nexus_ledger import NexusAuditLedger # noqa: E402 +from osiris_cli.providers import nexus_sdk as N # noqa: E402 +from osiris_cli.providers.quantinuum_nexus import GovernanceError # noqa: E402 + + +def _bell(name="bell"): + c = Circuit(2, 2, name=name) + c.add_gate(OpType.PhasedX, [0.5, 0.0], [0]) + c.add_gate(OpType.Rz, [0.25], [0]) + c.add_gate(OpType.ZZPhase, [0.5], [0, 1]) + c.add_gate(OpType.PhasedX, [0.5, 0.5], [1]) + c.Measure(0, 0) + c.Measure(1, 1) + return c + + +class _Ref: + def __init__(self, kind, payload=None): + self.id = uuid.uuid4() + self.kind = kind + self.payload = payload + + +class _CircRef(_Ref): + def download_circuit(self): + return self.payload.copy() + + +class _CompileItem: + def __init__(self, ref): + self._ref = ref + + def get_output(self): + return self._ref + + +class _Result: + def get_counts(self): + return Counter({(0, 0): 51, (1, 1): 49}) + + +class _ExecItem: + def download_result(self): + return _Result() + + +class FakeQnexus: + """Minimal stand-in with the same call shapes as qnexus 0.51.4 (keyword arguments only).""" + + def __init__(self): + self.projects = self.circuits = self.jobs = self + self._jobs = {} + + def QuantinuumConfig(self, *, device_name, **kw): + return {"type": "QuantinuumConfig", "device_name": device_name, **kw} + + def get_or_create(self, *, name, description=None, properties=None): + return _Ref("project") + + def upload(self, *, circuit, project=None, name=None, description=None, properties=None): + return _CircRef("circuit", circuit) + + def start_compile_job(self, *, programs, backend_config, name, project=None, optimisation_level=2, **kw): + j = _Ref("compile") + self._jobs[j.id] = [_CompileItem(_CircRef("circuit", r.payload)) for r in programs] + return j + + def cost(self, *, circuit_ref, n_shots, backend_config, syntax_checker=None, project=None, timeout=None): + assert syntax_checker == backend_config["device_name"] + "SC" + return float(N.local_hqc(circuit_ref.payload, n_shots)) + + def start_execute_job(self, *, programs, n_shots, backend_config, name, project=None, max_cost=(), **kw): + assert len(max_cost) == len(programs) == len(n_shots) + j = _Ref("execute") + self._jobs[j.id] = [_ExecItem() for _ in programs] + return j + + def wait_for(self, *, job, timeout=None, **kw): + return None + + def results(self, *, job, **kw): + return self._jobs[job.id] + + +@pytest.fixture +def runner(tmp_path, monkeypatch): + monkeypatch.setenv("OSIRIS_HOME", str(tmp_path)) + monkeypatch.delenv("OSIRIS_NEXUS_DISPOSITIONS_LOG", raising=False) + monkeypatch.delenv("OSIRIS_TIER3_HMAC_SECRET", raising=False) + return N.NexusSdkRunner(qnx=FakeQnexus(), ledger=NexusAuditLedger(tmp_path)) + + +def test_local_hqc_counts_rz_as_free(): + # 2 PhasedX + 10 x 1 ZZPhase + 5 x (2 measure + 2 prep) = 32 units; 5 + 500*32/5000 = 8.2 + assert str(N.local_hqc(_bell(), 500)) == "8.2000" + + +def test_preflight_prices_with_syntax_checker_and_records_tier1(runner): + res = runner.preflight([_bell("a"), _bell("b")], target="H2-1", shots=500) + assert res.nexus_hqc == [8.2, 8.2] + assert res.total_nexus_hqc == 16.4 + assert res.compiled_sha256 == res.source_sha256 # fake compile is the identity + body = runner.ledger.list_entries()[-1]["body"] + assert body["tier"] == 1 and body["hardware"] is False and body["target"] == "H2-1SC" + v = runner.ledger.verify() + assert v["valid"] is True and v["entries"] == 1, v + with pytest.raises(GovernanceError): + runner.preflight([_bell()], target="H2-1E") + + +def test_emulator_run_records_simulated_and_counts(runner): + pre = runner.preflight([_bell()], target="H2-1", shots=100) + out = runner.run(pre, target="H2-1E", shots=100) + assert out["counts"] == [{"00": 51, "11": 49}] + body = runner.ledger.list_entries()[-1]["body"] + assert body["tier"] == 2 and body["disposition"] == "SIMULATED" and body["hardware"] is False + + +def test_emulator_cap_and_hardware_token_fail_closed_before_dispatch(runner): + pre = runner.preflight([_bell()], target="H2-1", shots=500) + with pytest.raises(GovernanceError, match="max_emulator_hqc"): + runner.run(pre, target="H2-1E", max_emulator_hqc=1.0) + with pytest.raises(GovernanceError, match="approval token"): + runner.run(pre, target="H2-1") + assert not [c for c in runner.calls if c[0] == "start_execute_job"] + + +def test_hardware_run_with_signed_token_bound_to_compiled_batch(runner, tmp_path): + from osiris_cli.quantinuum_gate import mint_tier3_token + pre = runner.preflight([_bell()], target="H2-1", shots=500) + batch = N.batch_sha256(pre.compiled_sha256) + tok = mint_tier3_token(circuit_sha256=batch, target="H2-1", max_shots=500, max_hqc="20", osiris_home=tmp_path) + out = runner.run(pre, target="H2-1", approval_token=tok) + body = runner.ledger.list_entries()[-1]["body"] + assert body["disposition"] == "HARDWARE_ATTESTED" and body["tier"] == 3 and body["job_id"] == out["job_id"] + wrong = mint_tier3_token(circuit_sha256="0" * 64, target="H2-1", max_shots=500, max_hqc="20", osiris_home=tmp_path) + with pytest.raises(Exception): + runner.run(pre, target="H2-1", approval_token=wrong) + + +def test_load_circuits_reads_xtop005_style_list(tmp_path): + p = tmp_path / "c.json" + p.write_text(json.dumps([{"name": "q0", "tket": _bell().to_dict()}, {"name": "q1", "tket": _bell().to_dict()}])) + cs = N.load_circuits(p) + assert [c.name for c in cs] == ["q0", "q1"] and cs[0].n_qubits == 2 + + +def test_every_sdk_call_binds_to_the_real_qnexus_signature(runner): + """Guards against invented APIs: each recorded call must bind to qnexus 0.51.4's real function.""" + qnx = pytest.importorskip("qnexus") + pre = runner.preflight([_bell()], target="H2-1", shots=100) + runner.run(pre, target="H2-1E", shots=100) + assert {c[0] for c in runner.calls} >= {"projects.get_or_create", "circuits.upload", "start_compile_job", + "jobs.wait_for", "jobs.results", "circuits.cost", "start_execute_job"} + for dotted, kwargs in runner.calls: + fn = qnx + for part in dotted.split("."): + fn = getattr(fn, part) + inspect.signature(fn).bind(**kwargs) + qnx.QuantinuumConfig(device_name="H2-1E")