From bd39abc8839cfeb094264d8ebbcfdd21c23c4fe3 Mon Sep 17 00:00:00 2001 From: devin davis Date: Sun, 22 Nov 2026 00:18:13 -0500 Subject: [PATCH] Nexus governance hardening, Quantinuum CI job, claims register update (E-46..E-50) nexus_sdk / osiris nexus: - Remote side effects need explicit operator approval: preflight (upload, compile, costing) and Tier 2 emulator jobs refuse without approve_remote; the CLI asks [y/N] with what will be sent, or takes --approve-remote, and refuses when not interactive. Nothing is called before the check. - circuits.cost(...) now gets project=. - Preflight is ledgered as PREFLIGHT_CHECKED, not SIMULATED. - HARDWARE_ATTESTED only after an attestation step that asks Nexus again: jobs.status COMPLETED, the job record fetched by id names the requested QPU, and every result's backend info names it. Otherwise the run is recorded HARDWARE_UNVERIFIED with hardware=false and the reason. CI: new `quantinuum` job installs .[quantinuum,nexus] (pytket + qnexus) and runs test_nexus_sdk, test_quantinuum_client and test_tket_and_quantinuum_nexus; any skip fails the job (38 tests, 0 skips locally). claims.py: CRSM_ARCH -> REFUTED, "FAIL under Amendment 3 (N=2, adopted after seed 200); incomplete against 8-seed pre-registration", citing the result and Amendment 3. New entries XTOP005_DD (SUPPORTED), XTOP005_ENCODING (NULL), ADV0_PEAKED (REFUTED, offline, not preregistered). Full suite (pytket + qnexus installed): 3106 passed, 26 skipped, 0 failed. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 27 ++++++ docs/quantinuum/NEXUS_SDK_QUICKSTART.md | 14 ++- osiris_cli/claims.py | 57 +++++++++-- osiris_cli/providers/nexus_sdk.py | 72 ++++++++++++-- osiris_cli/quantinuum_cli.py | 29 +++++- tests/test_claims.py | 24 ++++- tests/test_nexus_sdk.py | 122 +++++++++++++++++++----- 7 files changed, 295 insertions(+), 50 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f6ff32ff..73457493 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -69,6 +69,33 @@ jobs: /tmp/wv/bin/osiris --help > /dev/null /tmp/wv/bin/python -c "import osiris_cli, osiris_termux_console, protege, osiris_bench; print('console', osiris_cli.__version__); print('bench tasks', len(osiris_bench.load_tasks()))" + quantinuum: + # Runs the real pytket compile path and the qnexus-SDK adapter, which the matrix above skips or + # sends to the static fallback because it installs neither. Any skip here fails the job. + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install osiris-cli with the quantinuum and nexus extras + run: | + python -m pip install --upgrade pip + pip install numpy scipy requests PyYAML rich networkx cryptography pytest + pip install -e ".[quantinuum,nexus]" + python -c "import pytket, qnexus; print('pytket', pytket.__version__, '| qnexus', qnexus.__version__ if hasattr(qnexus, '__version__') else 'installed')" + + - name: Quantinuum and Nexus tests (no skips allowed) + run: | + set -o pipefail + pytest tests/test_nexus_sdk.py tests/test_quantinuum_client.py tests/test_tket_and_quantinuum_nexus.py \ + -v --tb=short --strict-markers -rfEs | tee /tmp/quantinuum.log + if grep -E "^SKIPPED|[0-9]+ skipped" /tmp/quantinuum.log; then echo "::error::a Quantinuum/Nexus test was skipped"; exit 1; fi + lint: runs-on: ubuntu-24.04 # 26.04 has no Python 3.9 steps: diff --git a/docs/quantinuum/NEXUS_SDK_QUICKSTART.md b/docs/quantinuum/NEXUS_SDK_QUICKSTART.md index e0f0b59b..06d80bde 100644 --- a/docs/quantinuum/NEXUS_SDK_QUICKSTART.md +++ b/docs/quantinuum/NEXUS_SDK_QUICKSTART.md @@ -11,6 +11,10 @@ pip install 'osiris-cli[nexus]' # installs qnexus==0.51.4 qnx login # interactive; tokens are stored by qnexus, not by OSIRIS ``` +## Approval + +Nothing is sent to Nexus until the operator approves it. Every `preflight` and `run` shows what it will upload and run (circuits, project, target, estimated HQC) and asks `[y/N]`. In scripts, pass `--approve-remote`. Without a terminal and without the flag, the command refuses. Hardware runs also need the signed token described below. + ## 1. Preflight (Tier 1, free) ```bash @@ -24,7 +28,7 @@ This command: 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`. +5. writes a Tier 1 `PREFLIGHT_CHECKED` 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. @@ -54,7 +58,13 @@ The run refuses to start in any of these cases: - 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. +`HARDWARE_ATTESTED` is written only after an attestation step that asks Nexus again how the job ran, separately from the submit call. All three checks must pass: + +- `jobs.status` reports `COMPLETED`; +- the job record, fetched again by ID, names the requested QPU; +- every result's backend info names the same QPU. + +If any check fails, the run is recorded as `HARDWARE_UNVERIFIED` with `hardware=false`, and the diagnostics say why. ## Ledger diff --git a/osiris_cli/claims.py b/osiris_cli/claims.py index 6c644abb..f8826933 100644 --- a/osiris_cli/claims.py +++ b/osiris_cli/claims.py @@ -478,7 +478,7 @@ def standing(self) -> str: r"(attention|torsion)[^.\n]{0,40}?\bt-lock\b", r"phase[\s-]*conjugat\w*[\s-]+positional", r"non[\s-]*local[\s,]+non[\s-]*causal|non[\s-]*causal[\s-]+living|\bncllm\b|\bnc-lm\b", r"information[\s-]*manifold collapse|non[\s-]*local correlation factor"), - testable="Whether these parts help as architecture is CRSM_ARCH (NCLM-ARCH-1, pre-registered); the " + testable="Whether these parts help as architecture is CRSM_ARCH (NCLM-ARCH-1: FAIL under Amendment 3, N=2); the " "physics names would need a measured physical quantity, which none of them has.", checks=(("phi_positional", (128, 51.843, 0.946)),)), Claim("NCLM_PC_CORRECTOR", "The core's phase-conjugate error correction detects decoherence (Γ > 0.3) and " @@ -500,16 +500,55 @@ def standing(self) -> str: "the rest of the CRSM block); alone it needs a leave-one-out follow-up."), Claim("CRSM_ARCH", "The CRSM components (torsion-locked attention, pilot-wave factor, phase-conjugate corrector, " "1/φ FFN scale, φ position table) make the core a better byte model than a standard transformer of " - "the same size", "UNTESTED", - "Pre-registered 2026-10-08 as NCLM-ARCH-1, not run: the live core against pre-norm blocks with base-10000 " - "positions and the FFN widened to 384 (725,760 vs 726,304 parameters), 8 paired seeds, best held-out " - "documents bits/byte, minimum effect 0.05, PASS / FAIL / NO-DIFFERENCE fixed in advance. It compares the " - "bundle, not single components. One-seed checks made before registration (in the pre-registration) " - "hint that the corrector may not help; they are not a result.", - (("file", "osiris-cli/experiments/nclm_arch1/PRE_REGISTRATION.md", "NCLM-ARCH-1 pre-registration"),), + "the same size", "REFUTED", + "FAIL under Amendment 3 (N=2, adopted after seed 200); incomplete against 8-seed pre-registration. " + "NCLM-ARCH-1 was registered 2026-10-08 with 8 paired seeds (200-207), best held-out documents " + "bits/byte, minimum effect 0.05. Amendment 3 (2026-11-01, recorded before seed 201 finished) bounded " + "the run to seeds 200 and 201. On those two pairs the standard arm won both: mean paired gain " + "(standard - crsm) -0.595 bits/byte, SD 0.026, one-sided 95 % bounds [-0.712, -0.478]; held-out chat " + "+0.728 bpb worse for crsm. All four runs hit the 12,000-step cap before early stopping. Seeds 202-207 " + "were never run, so the registered 8-seed test is incomplete; the direction and size of the gap on the " + "two pairs run are not in doubt.", + (("file", "osiris-cli/experiments/nclm_arch1/PRE_REGISTRATION.md", "NCLM-ARCH-1 pre-registration"), + ("file", "osiris-cli/experiments/nclm_arch1/RESULT.md", "NCLM-ARCH-1 result, seeds 200-201"), + ("file", "osiris-cli/experiments/nclm_arch1/EXECUTION.md", "Amendment 3: scope bounded to N=2")), (r"\bcrsm[\s-]+(architecture|components?|blocks?|mechanics)\b", r"\bnclm[\s-]*arch[\s-]*1\b", r"sovereign[\s-]*(block|mechanics)\b[^.\n]{0,40}?(better|improv\w*|helps?|beats?|outperform\w*)"), - testable="Run NCLM-ARCH-1 as registered: experiments/nclm_arch1/run.py."), + testable="Seeds 202-207 of NCLM-ARCH-1 as registered (experiments/nclm_arch1/run.py) would complete " + "the 8-seed test.", + caveats=("N=2 of 8 registered seed pairs (Amendment 3)", "all runs hit the step cap")), + Claim("XTOP005_DD", "Dynamical decoupling protects an idle code-space register on IBM Heron r2 " + "(XTOP-005 H2, H3)", "SUPPORTED", + "Pre-registered (10.5281/zenodo.24425416) and run on ibm_marrakesh, job dc0uhdts2omc7389tmt0, 216 " + "circuits x 1,000 shots. H2 and H3 (decoupling against bare idling) are supported at both depths, " + "Holm-adjusted p = 0.002: H2 +0.122 (depth 1) and +0.176 (depth 3), H3 +0.135 and +0.102.", + (("doi", "10.5281/zenodo.24425416", "XTOP-005 pre-registration"), + ("doi", "10.5281/zenodo.24425627", "XTOP-005 paper"), + ("file", "osiris-cli/docs/xtop005/qpu/results.json", "XTOP-005 hypothesis tests, job dc0uhdts2omc7389tmt0")), + (r"\bxtop[\s-]*0*05\b", r"\bdynamical[\s-]+decoupling\b[^.\n]{0,60}?\b(heron|marrakesh|heavy[\s-]*hex)\b"), + testable="Scope: one device (ibm_marrakesh), one session, depths 1 and 3."), + Claim("XTOP005_ENCODING", "[[4,2,2]] error-detection encoding protects the register on heavy-hex " + "(XTOP-005 H1, H4)", "NULL", + "Pre-registered with H2 and H3 on the same job (dc0uhdts2omc7389tmt0). H1 is not supported at either " + "depth (+0.021, Holm p = 0.34; +0.043, Holm p = 0.031, above the registered threshold); H4 is not " + "supported (-0.054 at depth 1, CI entirely below zero; +0.015 at depth 3, Holm p = 0.34). On heavy-hex " + "the routing the code needs costs more than the detection gains.", + (("doi", "10.5281/zenodo.24425416", "XTOP-005 pre-registration"), + ("doi", "10.5281/zenodo.24425627", "XTOP-005 paper"), + ("file", "osiris-cli/docs/xtop005/qpu/results.json", "XTOP-005 hypothesis tests, job dc0uhdts2omc7389tmt0")), + (r"\[\[\s*4\s*,\s*2\s*,\s*2\s*\]\][^.\n]{0,60}?\b(heron|marrakesh|heavy[\s-]*hex|protect\w*)\b",), + testable="The H2-1 design (docs/xtop005/quantinuum) tests the same code with all-to-all connectivity; " + "not yet run."), + Claim("ADV0_PEAKED", "Twirled-mirror peaked circuits on a heavy-hex region (up to 56 qubits, depth 16) are " + "beyond classical simulation", "REFUTED", + "ADV-0 (offline, no QPU, not pre-registered) scanned 30 cells, n = 12-56, depth 2-16, on FakeMarrakesh " + "regions. In every cell at least one laptop-scale attack (Pauli propagation, exact light-cone " + "statevector, or MPS sampling) recovered the hidden string. At n = 56, depth 16 the predicted hardware " + "peak is 0.041; MPS at bond dimension 64 fails (0.005) but bond dimension 256 wins (0.165 in 1,274 s).", + (("file", "osiris-cli/docs/adv0/ADV0_REPORT.md", "ADV-0 report and 30-cell scan"),), + (r"\badv[\s-]*0\b", r"\bpeaked[\s-]+circuits?\b[^.\n]{0,60}?\b(advantage|classical(ly)?|simulat\w*)\b"), + testable="ADV-1 (looped regions, non-mirror construction, structure-aware attack) with the gate in the " + "ADV-0 report: MPS at bond dimension 1024, Pauli propagation and light-cone must all fail."), Claim("RQC_ADVANTAGE", "Recursive Quantum Circuits with adaptive feedback outperform random circuit sampling " "(p < 0.05); research-grade and ready for peer review", "UNTESTED", "RQC_RESEARCH_METHODOLOGY.md is a proposal: its p-values (0.024, 0.018, 0.009) are listed under " diff --git a/osiris_cli/providers/nexus_sdk.py b/osiris_cli/providers/nexus_sdk.py index 9cfc3389..8c4bd3d9 100644 --- a/osiris_cli/providers/nexus_sdk.py +++ b/osiris_cli/providers/nexus_sdk.py @@ -164,11 +164,18 @@ def _record(self, **kw: Any) -> Dict[str, Any]: 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.""" + timeout: float = 900.0, approve_remote: bool = False) -> PreflightResult: + """Compile on Nexus for ``target`` (an H2 QPU name) and price it with that QPU's syntax checker. + + This uploads circuits and starts a compile job on Nexus, so it needs ``approve_remote=True`` + (the CLI asks the operator, or takes ``--approve-remote``). Nothing is sent before that check. + """ 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}") + if not approve_remote: + raise GovernanceError("preflight uploads and compiles on Quantinuum Nexus: explicit operator approval " + "is required (approve_remote=True / --approve-remote)") checker = f"{spec.name}SC" proj = self.project() src = [tket_sha256(c) for c in circuits] @@ -184,7 +191,7 @@ def preflight(self, circuits: Sequence[Any], target: str = "H2-1", shots: int = 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) + backend_config=self._config(spec.name), syntax_checker=checker, project=proj) 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", "")) @@ -192,7 +199,7 @@ def preflight(self, circuits: Sequence[Any], target: str = "H2-1", shots: int = 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", + target=checker, tier=1, disposition="PREFLIGHT_CHECKED", 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", @@ -205,11 +212,19 @@ def preflight(self, circuits: Sequence[Any], target: str = "H2-1", shots: int = 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).""" + verify_token: Optional[Callable[..., Any]] = None, approve_remote: bool = False) -> Dict[str, Any]: + """Execute the pre-flighted circuits on ``target`` (H2-1E/H2-2E emulator, or H2-1/H2-2 hardware). + + Emulator jobs need ``approve_remote=True``; hardware jobs need a signed Tier 3 token, which is + itself the operator's approval. ``HARDWARE_ATTESTED`` is written only after Nexus confirms the job + completed on the requested QPU (see ``_attest_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") + if spec.tier == 2 and not approve_remote: + raise GovernanceError(f"{spec.name} jobs use the Nexus emulator quota: explicit operator approval is " + "required (approve_remote=True / --approve-remote)") 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] @@ -238,13 +253,50 @@ def run(self, pre: PreflightResult, target: str, shots: Optional[int] = None, 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 + metrics: Dict[str, Any] = {"circuits": len(counts), "max_cost_per_circuit": caps} + diagnostics: List[str] = [] + if spec.tier == 3: + attestation, problems = self._attest_hardware(job, spec, results) + metrics["attestation"] = attestation + diagnostics.extend(problems) + disposition, hw = ("HARDWARE_ATTESTED", True) if not problems else ("HARDWARE_UNVERIFIED", False) + else: + disposition, hw = "SIMULATED", False receipt = self._record( - target=spec.name, tier=spec.tier, disposition="HARDWARE_ATTESTED" if hw else "SIMULATED", + target=spec.name, tier=spec.tier, disposition=disposition, 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}, + preflight_passed=True, metrics=metrics, diagnostics=diagnostics, compiler_options={"qnexus": QNEXUS_VERSION}) return {"target": spec.name, "job_id": job_id, "shots": shots, "hqc_estimate": str(total), - "counts": counts, "receipt": receipt} + "disposition": disposition, "diagnostics": diagnostics, "counts": counts, "receipt": receipt} + + def _attest_hardware(self, job: Any, spec: Any, results: Sequence[Any]) -> Tuple[Dict[str, Any], List[str]]: + """Ask Nexus, independently of the submit call, where and how the job ran. + + Checks: the job status is COMPLETED; the job record fetched again by id names ``spec.name`` as its + device; every result's backend info names the same device. Any failure is returned as a problem and + the run is recorded as HARDWARE_UNVERIFIED, never HARDWARE_ATTESTED. + """ + problems: List[str] = [] + st = self._call("jobs.status", job=job) + status = str(getattr(getattr(st, "status", None), "value", getattr(st, "status", ""))) + if status != "COMPLETED": + problems.append(f"Nexus job status is {status or 'unknown'}, not COMPLETED") + fresh = self._call("jobs.get", id=getattr(job, "id", None)) + cfg = getattr(fresh, "backend_config_store", None) + job_device = getattr(cfg, "device_name", None) + if job_device != spec.name: + problems.append(f"Nexus job record names device {job_device!r}, expected {spec.name!r}") + result_devices = [] + for r in results: + bi = r.download_backend_info() + result_devices.append(getattr(bi, "device_name", None)) + if not result_devices or any(d != spec.name for d in result_devices): + problems.append(f"result backend devices {sorted(set(map(str, result_devices)))} != {spec.name!r}") + completed = getattr(st, "completed_time", None) + evidence = {"job_status": status, "job_device": job_device, "result_devices": result_devices, + "completed_time": completed.isoformat() if hasattr(completed, "isoformat") else completed, + "nexus_cost": getattr(st, "cost", None)} + return evidence, problems diff --git a/osiris_cli/quantinuum_cli.py b/osiris_cli/quantinuum_cli.py index 5a8437ea..8be70ef5 100644 --- a/osiris_cli/quantinuum_cli.py +++ b/osiris_cli/quantinuum_cli.py @@ -457,6 +457,19 @@ def cmd_ledger(argv: Sequence[str]) -> int: return 0 if summary["valid"] else 2 +def _approve_remote(what: str, flag: bool) -> bool: + """Operator approval for Nexus side effects: the --approve-remote flag, or an interactive [y/N].""" + if flag: + return True + if not sys.stdin.isatty(): + return False + try: + answer = input(f"osiris nexus will {what}. Proceed? [y/N] ") + except EOFError: + return False + return answer.strip().lower() in ("y", "yes") + + 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") @@ -471,6 +484,8 @@ def cmd_nexus(argv: Sequence[str]) -> int: 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") + sp.add_argument("--approve-remote", action="store_true", + help="Approve uploading, compiling and (for run) emulator jobs on Nexus without a prompt") 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)") @@ -504,18 +519,26 @@ def cmd_nexus(argv: Sequence[str]) -> int: circuits = [c for c in circuits if re.search(args.match, c.name or "")] if args.limit: circuits = circuits[: args.limit] + if not circuits: + raise ValueError("no circuits selected") + from .providers.nexus_sdk import local_hqc + est = sum(local_hqc(c, args.shots) for c in circuits) + what = (f"upload {len(circuits)} circuit(s) to Nexus project {args.project!r}, compile and price them" + + (f", then run {args.shots} shots each on {args.target} (local estimate ~{est} HQC)" + if args.action == "run" else "")) + approved = _approve_remote(what, args.approve_remote) 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) + optimisation_level=args.optimisation_level, approve_remote=approved) 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) + optimisation_level=args.optimisation_level, approve_remote=approved) 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)} + max_emulator_hqc=args.max_emulator_hqc, approve_remote=approved)} except Exception as exc: print(f"NEXUS_ERROR: {type(exc).__name__}: {exc}", file=sys.stderr) return 2 diff --git a/tests/test_claims.py b/tests/test_claims.py index 3c8f736a..0adef3ad 100644 --- a/tests/test_claims.py +++ b/tests/test_claims.py @@ -209,7 +209,7 @@ def test_legit_command(): NEW_V452 = {"F_MAX": "REFUTED", "COHERENCE_QUANTIZATION": "OVERCLAIM", "NCLM_MECHANICS": "NOT_MEASURED", "NCLM_PC_CORRECTOR": "NOT_MEASURED", "QUANTUM_LM": "NO_EVIDENCE", "QEC_LLM_SAFETY": "RULED_OUT", - "CRSM_ARCH": "UNTESTED"} + "CRSM_ARCH": "REFUTED"} def test_v452_entries_and_verdicts(): @@ -345,9 +345,25 @@ def test_the_users_own_framing_gets_the_verdict(): def test_crsm_arch_points_at_its_pre_registration(): c = claims.by_id("CRSM_ARCH") - [(kind, ref, _)] = c.evidence - assert kind == "file" and ref == "osiris-cli/experiments/nclm_arch1/PRE_REGISTRATION.md" - assert (Path(__file__).resolve().parents[1] / "experiments" / "nclm_arch1" / "PRE_REGISTRATION.md").exists() + assert c.evidence[0] == ("file", "osiris-cli/experiments/nclm_arch1/PRE_REGISTRATION.md", + "NCLM-ARCH-1 pre-registration") + assert c.verdict == "REFUTED" and c.finding.startswith("FAIL under Amendment 3 (N=2, adopted after seed 200)") + root = Path(__file__).resolve().parents[1] + for kind, ref, _ in c.evidence: + assert kind == "file" and (root / ref.removeprefix("osiris-cli/")).exists(), ref + + +def test_xtop005_and_adv0_are_registered_with_their_records(): + root = Path(__file__).resolve().parents[1] + assert claims.by_id("XTOP005_DD").verdict == "SUPPORTED" + assert claims.by_id("XTOP005_ENCODING").verdict == "NULL" + assert claims.by_id("ADV0_PEAKED").verdict == "REFUTED" + for cid in ("XTOP005_DD", "XTOP005_ENCODING", "ADV0_PEAKED"): + for kind, ref, _ in claims.by_id(cid).evidence: + if kind == "file": + assert (root / ref.removeprefix("osiris-cli/")).exists(), ref + assert {c.id for c in claims.match("what did XTOP-005 find?")} >= {"XTOP005_DD"} + assert "ADV0_PEAKED" in {c.id for c in claims.match("are peaked circuits beyond classical simulation?")} def test_the_chsh_shell_command_is_not_the_chsh_test(): diff --git a/tests/test_nexus_sdk.py b/tests/test_nexus_sdk.py index 53d42e57..bdc6eb42 100644 --- a/tests/test_nexus_sdk.py +++ b/tests/test_nexus_sdk.py @@ -51,17 +51,38 @@ def get_counts(self): return Counter({(0, 0): 51, (1, 1): 49}) +class _BackendInfo: + def __init__(self, device_name): + self.device_name = device_name + + class _ExecItem: + def __init__(self, device_name): + self._device = device_name + def download_result(self): return _Result() + def download_backend_info(self): + return _BackendInfo(self._device) + + +class _Status: + def __init__(self, status="COMPLETED"): + self.status = type("E", (), {"value": status})() + self.completed_time = None + self.cost = 7.5 + class FakeQnexus: """Minimal stand-in with the same call shapes as qnexus 0.51.4 (keyword arguments only).""" - def __init__(self): + def __init__(self, report_device=None, report_status="COMPLETED"): self.projects = self.circuits = self.jobs = self self._jobs = {} + self._devices = {} + self.report_device = report_device # simulate Nexus reporting a different device than requested + self.report_status = report_status def QuantinuumConfig(self, *, device_name, **kw): return {"type": "QuantinuumConfig", "device_name": device_name, **kw} @@ -79,14 +100,23 @@ def start_compile_job(self, *, programs, backend_config, name, project=None, opt def cost(self, *, circuit_ref, n_shots, backend_config, syntax_checker=None, project=None, timeout=None): assert syntax_checker == backend_config["device_name"] + "SC" + assert project is not None 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] + dev = self.report_device or backend_config["device_name"] + self._devices[j.id] = dev + self._jobs[j.id] = [_ExecItem(dev) for _ in programs] return j + def status(self, *, job, **kw): + return _Status(self.report_status) + + def get(self, *, id=None, **kw): + return type("JobRecord", (), {"backend_config_store": type("Cfg", (), {"device_name": self._devices[id]})()})() + def wait_for(self, *, job, timeout=None, **kw): return None @@ -102,52 +132,88 @@ def runner(tmp_path, monkeypatch): return N.NexusSdkRunner(qnx=FakeQnexus(), ledger=NexusAuditLedger(tmp_path)) +def _pre(runner, **kw): + return runner.preflight([_bell()], target="H2-1", approve_remote=True, **kw) + + 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) +def test_preflight_prices_with_syntax_checker_and_records_preflight_checked(runner): + res = runner.preflight([_bell("a"), _bell("b")], target="H2-1", shots=500, approve_remote=True) 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" + assert body["disposition"] == "PREFLIGHT_CHECKED" + cost_calls = [kw for name, kw in runner.calls if name == "circuits.cost"] + assert len(cost_calls) == 2 and all(kw["project"] is not None for kw in cost_calls) v = runner.ledger.verify() assert v["valid"] is True and v["entries"] == 1, v with pytest.raises(GovernanceError): - runner.preflight([_bell()], target="H2-1E") + runner.preflight([_bell()], target="H2-1E", approve_remote=True) + + +def test_remote_side_effects_need_operator_approval(runner): + with pytest.raises(GovernanceError, match="operator approval"): + runner.preflight([_bell()], target="H2-1") + assert runner.calls == [] # nothing uploaded, no project created + pre = _pre(runner) + n = len(runner.calls) + with pytest.raises(GovernanceError, match="operator approval"): + runner.run(pre, target="H2-1E", shots=100) + assert len(runner.calls) == n # no emulator job started 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) + pre = _pre(runner, shots=100) + out = runner.run(pre, target="H2-1E", shots=100, approve_remote=True) 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) + pre = _pre(runner, shots=500) with pytest.raises(GovernanceError, match="max_emulator_hqc"): - runner.run(pre, target="H2-1E", max_emulator_hqc=1.0) + runner.run(pre, target="H2-1E", max_emulator_hqc=1.0, approve_remote=True) with pytest.raises(GovernanceError, match="approval token"): - runner.run(pre, target="H2-1") + runner.run(pre, target="H2-1", approve_remote=True) 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): +def _token(pre, tmp_path, batch=None): 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) + return mint_tier3_token(circuit_sha256=batch or N.batch_sha256(pre.compiled_sha256), target="H2-1", + max_shots=500, max_hqc="20", osiris_home=tmp_path) + + +def test_hardware_attested_only_after_nexus_confirms_device_and_status(runner, tmp_path): + pre = _pre(runner, shots=500) + out = runner.run(pre, target="H2-1", approval_token=_token(pre, tmp_path)) 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) + assert body["disposition"] == "HARDWARE_ATTESTED" and body["hardware"] is True + assert body["tier"] == 3 and body["job_id"] == out["job_id"] + att = body["metrics"]["attestation"] + assert att["job_status"] == "COMPLETED" and att["job_device"] == "H2-1" and att["result_devices"] == ["H2-1"] + assert {"jobs.status", "jobs.get"} <= {c[0] for c in runner.calls} with pytest.raises(Exception): - runner.run(pre, target="H2-1", approval_token=wrong) + runner.run(pre, target="H2-1", approval_token=_token(pre, tmp_path, batch="0" * 64)) + + +@pytest.mark.parametrize("kw, why", [({"report_device": "H2-1E"}, "device"), + ({"report_status": "ERROR"}, "status")]) +def test_hardware_run_not_attested_when_nexus_disagrees(tmp_path, monkeypatch, kw, why): + monkeypatch.setenv("OSIRIS_HOME", str(tmp_path)) + runner = N.NexusSdkRunner(qnx=FakeQnexus(**kw), ledger=NexusAuditLedger(tmp_path)) + pre = _pre(runner, shots=500) + out = runner.run(pre, target="H2-1", approval_token=_token(pre, tmp_path)) + body = runner.ledger.list_entries()[-1]["body"] + assert out["disposition"] == body["disposition"] == "HARDWARE_UNVERIFIED" + assert body["hardware"] is False and any(why in d for d in body["diagnostics"]) def test_load_circuits_reads_xtop005_style_list(tmp_path): @@ -157,16 +223,28 @@ def test_load_circuits_reads_xtop005_style_list(tmp_path): 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): +def test_every_sdk_call_binds_to_the_real_qnexus_signature(runner, tmp_path): """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) + pre = _pre(runner, shots=500) + runner.run(pre, target="H2-1E", shots=100, approve_remote=True) + runner.run(pre, target="H2-1", approval_token=_token(pre, tmp_path)) 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"} + "jobs.wait_for", "jobs.results", "circuits.cost", "start_execute_job", + "jobs.status", "jobs.get"} 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") + + +def test_cli_refuses_without_approval_when_not_interactive(tmp_path, monkeypatch, capsys): + from osiris_cli import quantinuum_cli as Q + p = tmp_path / "c.json" + p.write_text(json.dumps([{"name": "q0", "tket": _bell().to_dict()}])) + monkeypatch.setattr(N, "load_qnexus", lambda: FakeQnexus()) + monkeypatch.setattr("sys.stdin.isatty", lambda: False, raising=False) + assert Q.cmd_nexus(["preflight", str(p)]) == 2 + assert "operator approval" in capsys.readouterr().err