{
  "base_commit": "6db4e2c1bcd4ebe52ffecc63695df55b54536c54",
  "files": {
    "benchmarks/atom_loss/README.md": "# Atom-loss correctness and benchmark evidence\n\nThis suite tests the persistent-loss semantics used by RustQEC's Mid-SWAP\nwalkthrough, then measures sampling and decoding on explicitly stated workloads.\nIt is an initial benchmark, not a threshold study or a claim of optimal decoding.\nThe generated publication bundle is in `site/static/data/atom-loss/` and is served\nunchanged at `data/atom-loss/` on the documentation site.\n\n## Reproduce\n\nFreeze all experiment source changes in a source commit **S**, then generate the\nentire bundle from a fresh, clean detached checkout of S. Use output and work\ndirectories outside that checkout. The entry point builds all five release\nbinaries from scratch with `--locked`, runs correctness, sampling, the 16-case\ndecoding experiment and the separate 48-case seed experiment serially, then\npacks, renders and verifies the complete bundle.\n\n```sh\n# Run from the main checkout after committing the experiment sources.\npython3 -m venv drafts/atom-loss-venv\ndrafts/atom-loss-venv/bin/pip install -r benchmarks/atom_loss/requirements.txt\nPYTHON=\"$(pwd)/drafts/atom-loss-venv/bin/python\"\nOUTPUT=\"$(pwd)/drafts/atom-loss-clean-results\"\nWORK=\"$(pwd)/drafts/atom-loss-clean-work\"\ngit worktree add --detach ../rustqec-evidence-source HEAD\ncd ../rustqec-evidence-source\n\"$PYTHON\" -m benchmarks.atom_loss.evidence_run --work \"$WORK\" --out \"$OUTPUT\"\n\"$PYTHON\" -m benchmarks.atom_loss.decoder_replay --root \"$OUTPUT\"\n```\n\nCopy the resulting bundle into `site/static/data/atom-loss/` and commit artifacts\nin a subsequent commit **E**. `source_commit` means S, not E: requiring an artifact\nto contain its own commit hash would be circular. The verifier independently\nreconstructs the complete input inventory from Git and Cargo workspace members.\nAll files in every workspace member, benchmark code/fixtures/requirements,\nworkspace manifests/lockfile, toolchain/configuration and the evidence CI workflow\nmust match S at the current checkout. New, missing or changed inputs fail; only\nchanges outside that declared source scope, such as site artifacts, can follow S\nwithout invalidating evidence. Source S must be an ancestor of the current HEAD.\nThis deliberately conservative inventory can require regeneration even for\nnon-computational changes within a workspace member.\n\n`source-manifest.json` records S, the complete Git blob/mode inventory and digest,\nexact build commands, compiler/Cargo versions and all five measured binary hashes.\nBuilds and measurement subprocesses receive an allowlisted environment with a\nfresh isolated Cargo home. Inherited Cargo profile/target options, Rust flags,\nnative compiler flags and loader overrides are not forwarded. External ancestor\n`.cargo/config` files are rejected; checkout-local Cargo configuration is source\nbound. The effective build environment is recorded (network credentials are\nexcluded). A regression executes the real entry point with optimization disabled\nin the parent environment and requires an optimized release binary without debug\nassertions; an ancestor profile override must be rejected before building.\nEvery original and independent-seed case records the fixed Pauli probability\n0.001. Both bundle and standalone archive validators reject changed or missing\nnoise metadata; generator replay uses the declared value and requires an exact\ncircuit match. Coherently resealing JSON, archive indices and checksums cannot\nmake a false noise setting valid.\n\nEvery stage provenance and source snapshot must agree with that manifest and the\ncurrent source files. Clean builds and clean source state are checked before and\nafter measurement. Python packages are pinned in `requirements.txt` and actual\nversions, CPU, OS, threading environment and timing boundaries are recorded.\nThe verifier compares recorded dependencies with the source-bound pins, compiler\nidentity with the build manifest, and CPU/OS/Python identity across all stages.\nRecorded thread settings must match the single-thread measurement policy. These\nchecks reject contradictory metadata; they do not authenticate historical timings\nor require the verification machine to match the measurement host.\n`bundle.json` seals all required artifacts with SHA-256; source binding is an\nadditional check, not inferred from those checksums.\n\nWorkload metadata is also checked independently: loss-flag positions are derived\nfrom the archived circuit and unique patterns are counted from public shot bytes.\nOffline graph builds, PyMatching batch calls, fixed-weight controls, shot/circuit\nidentities, adapter API/policy labels and the declared cyclic run order must agree\nwith those inputs and the fixed experiment definition. Current-code decoder replay\nadditionally compares exported graph dimensions and all retained non-time compiler,\ncache and decoder counters against each original repetition. Approximate native\npattern estimates keep their explicit flag; they are not treated as exact unique\ncounts. These checks validate reproducible work, not historical wall-clock time.\n\nThe full verifier then redraws all eight charts from the validated JSON in a\nfresh temporary directory, using the source-bound renderer. SVG IDs are fixed and timestamps omitted. Anonymous path coordinates may differ\nby at most 0.000001 pt (one serialized decimal unit) because platform math\nlibraries can round an endpoint differently. The bound is absolute, never\nrelative; path commands/separators and all other bytes, including text, styles,\ntransforms, IDs, references, viewBox and font glyphs, must match exactly. Every\nPNG must match in decoded pixels, dimensions, mode and metadata (compression\nbytes alone may differ). No perceptual image tolerance or skipped platform check is used. The renderer resets ambient plotting styles, uses bundled DejaVu fonts,\nand requires the pinned plotting dependency stack and the wheel's bundled\nFreeType 2.6.1. A rendering-environment mismatch fails explicitly; it is not\naccepted as evidence equivalence. Published `methodology.md` must also equal this\nsource-bound README. Replaced SVGs, changed PNG pixels, accidentally swapped\nfigures and altered methodology must fail even after their checksums are updated,\nin both normal and optimized Python. The standalone archive rescorer remains a\nstdlib-only numerical check; it does not validate website figures.\n\nCI fetches S, builds the current code and regenerates public samples/private keys\nfor all 64 corpora. `decoder_replay` separately re-decodes every backend/corpus\ncombination (213 combinations, covering all 345 archived prediction files), with\nonly public inputs in each decoder work directory. It compares prediction bytes\nand hashes, failure counts, Wilson intervals and recorded paired discordances.\nAn executable mutation that flips a current native prediction while retaining the\nold archive must fail. Missing manifest inputs and a changed decoder/build input\nmust also fail, including under optimized Python.\n\nCI prediction replay validates results, **not historical performance**. It does\nnot compare machine-dependent binary hashes or timing values across platforms.\nAny change in the measured source scope requires a new clean source commit and\nfresh evidence generation; replay alone cannot justify retaining old timings.\nNeither Git hashes nor CI provide protection against an author deliberately\nrewriting both the experiment and its checks; the source contract remains\nreviewable code.\n\nThe recorded measurements use serial processes on one machine without explicit\nCPU affinity. The three cyclic timing rotations do not completely balance all\nbackend order positions. Small differences are not evidence of a stable ranking;\ntiming repeats reuse each corpus and do not increase its accuracy sample size.\nBoth decoders receive the same public corpus at each point, with scoring keys\nused only afterward. A shared seed does not imply row-identical samples between\nStim and RustQEC; independent sampler checks compare distributions.\n\n### Download and rescore without building Rust\n\n`shot-data-v1.zip` contains all 16 synthetic corpora, public/private manifests,\ncircuits, scoring keys and **all 198 prediction files** (three repetitions of\nevery backend), plus the decoding/tradeoff result JSON, per-file hashes and a\nstandalone `rescore.py`. The private keys are published for auditing, but are\nnever supplied to either decoder during measurement. After downloading the ZIP,\nextract `rescore.py` and run with any Python 3.10+ installation:\n\n```sh\npython3 rescore.py rescore shot-data-v1.zip\n```\n\nExpected: `PASS: 16 corpora; 198 prediction files rescored`. No third-party\nPython packages or native binaries are needed. The checker verifies completeness, public/private schema and row formats,\ncorpus/prediction hashes, scoring answers derived independently from measurement\nobservable parity XOR input mask, failure rates and paired disagreements. Repository\nverification additionally requires the archived results to match the public JSON.\nChecksums detect inconsistency, not authenticity against rewriting all evidence;\nuse the Git commit for the versioned source of the bundle.\nThe standalone tool requires the fixed 16 settings, four sweep comparators and\nsix tradeoff comparators, three complete repetitions and all 198 prediction files. It rejects\nomitted comparisons or paired fields, stale Wilson intervals, incorrect workload\nmetadata and non-integer count fields, even when the ZIP index is resealed and\nPython optimization is enabled. It validates scoring evidence; historical timing\nand build/source provenance require the full repository verifier.\n\n\n## Correctness reference\n\n`reference.py` independently parses the supported circuit subset, samples loss\nonset histories and lowers each history into an ordinary Stim circuit. Gates and\nPauli noise touching an absent wire are skipped until its reset. A lost wire is\nleft unobserved; retaining its inaccessible state gives the same surviving-wire\nstatistics as tracing it out. `ML` / `MRL` produce a loss flag followed by the value\n(or the documented placeholder). Reset and measurement-reset restore the wire.\nDistinct histories are compiled separately; only identical histories are batched.\nThis Python implementation is deliberately simple and is **not** an optimized\nStim atom-loss implementation.\n\nSupported operations: Z-basis reset and measurement (including inverted and\nloss-visible measurement), H/S/S_DAG/X/Y/Z, CX/CZ, one/two-qubit depolarization and Pauli\nerrors, LOSS and nested REPEAT. Sampling ignores coordinate/detector annotations.\nUnsupported operations and inline measurement noise raise an error. This is not\na reference for every circuit accepted by RustQEC.\n\n`correctness.py` compares complete joint output distributions for 12 small\ncircuits, with 32,768 shots per implementation per case. Four circuits additionally\nhave hand-computed deterministic answers. A conservative Hoeffding union bound\ncovers all histogram bins at alpha <= 5e-7. Another 5e-7 is allocated to\nthe analytic channel checks below: 4e-7 for the original 16 events and 1e-7 for\nall joint bins and marginals of the 26 distribution probes (combined healthy-check\nbound <= 1e-6 before the low-probability checks below). Removing skipped-gate\nsemantics must fail a known answer; an unsupported operation must be rejected.\nThese statistical checks cannot prove equality or validate arbitrarily rare\nfault probabilities.\n\n`noise_controls.py` adds 16 analytic single-bit/parity cases at p = 0.17,\ncovering X/Y/Z errors and one/two-qubit depolarization on live, absent and\nreset-restored wires, plus noise before loss. A live DEPOLARIZE2 channel flips\nZ parity for 8 of its 15 equiprobable nonidentity Pauli pairs: the expected\nprobability is `8p/15 = 0.0906667`. Both implementations must match the analytic\nprobabilities; zero-probability controls require exactly zero events. The same\nacceptance checks are actually rerun with each of the five native-input channels\ndeleted. All five mutations must fail. A regression deletes DEPOLARIZE2 from\nall native inputs and requires the **overall** correctness report to fail.\n\n`channel_probes.py` adds 26 analytic distribution probes. Bell preparation and\ninverse Bell readout resolve all four single-qubit and all sixteen two-qubit\nPauli labels, including identity, at p = 0, 0.17, 0.6 and 1. Nonidentity bins\nhave probability p/3 or p/15. Higher-noise probes make an omitted component\nresolvable at the chosen sample size; the check does not rely solely on p=0.17.\nNine X/Y/Z product-basis combinations check complete two-bit distributions and\nboth individual marginals. For a two-qubit product eigenstate, the ideal-outcome\nprobability is 1-4p/5 and each of the other three outcomes has probability 4p/15;\neach bit flips with probability 8p/15. Both loss directions, reset restoration,\nnoise before loss and single-qubit X/Y/Z probes are also covered.\n\nEach probe uses 32,768 samples per implementation, with one-sample Hoeffding\nbounds unioned over every joint bin and marginal for both implementations.\nZero/one probabilities must hold exactly. Tests resolve each deterministic\nPauli label against hand-derived Bell syndromes. Five actual replacement\nmutations must fail: IX-only, XI-only, independent X errors on both wires, and\nX-only or Z-only single-qubit depolarization. An IX-only regression requires\nthe **overall** sampling report to fail using the same acceptance criteria.\nThis is finite statistical evidence for the specified stochastic Pauli channels,\nnot a proof for arbitrary noise channels or arbitrarily small probability biases.\n\n`low_probability.py` adds fifteen **unamplified** probes: each of the five Pauli\nchannels at p = 0.001 and LOSS at 0.0001, 0.0003, 0.001, 0.003 and 0.01.\nThe five half-rate primitive LOSS probabilities used at two-qubit operations\nare included too, down to 0.00005. Each uses at least 262,144 shots per\nimplementation (520,000 at p = 0.00005). Exact equal-tail binomial count\nintervals cover joint bins, individual marginals and nonidentity events, with\nBonferroni allocation over both implementations (family alpha <= 1e-7).\nThis avoids applying a high-probability absolute tolerance to rare events.\nThe smallest LOSS probability has about 26 expected events; zero events are\noutside its acceptance interval. These probes resolve channel deletion, not\narbitrarily small relative biases or every possible low-rate Pauli component.\n\nThe same module independently checks the actual d=3, rounds=2 Mid-SWAP fixture\n(pPauli=0.001, pLoss=0.003) through `dataset export --mode measurements_blinded`,\nusing 65,536 shots per implementation. It prepares the two logical inputs in\nStim using the native export's private input masks; it does not use the envelope compiler. A separate deterministic check reads\nthe private answers and verifies every one against observable parity XOR input\nmask; private answers still never enter either decoder. Within each input stratum, 50 measurement\nbits (including loss flags), 16 detector parities, the observable and 15 adjacent\ndetector joints are compared. Another 16 detector marginals conditioned on no\nvisible loss separate the Pauli signal from loss-induced syndromes. The 196\npreselected two-sample Fisher tests use Bonferroni alpha <= 1e-7. This is a\nfinite set of marginal/joint checks, not the full 50-bit joint distribution.\n\nThree actual input mutations delete only low-rate Pauli noise, only low-rate\nLOSS, or both (`0 < p < 0.01`). Every affected analytic probe must reject its\nmutation; the real export-path comparison must independently reject all three.\nThe real fixture loses 12, 19 or 31 instructions respectively. A separate\nregression corrupts only the exporter, leaving ordinary circuit sampling intact.\nThe combined healthy sampling-check familywise bound is <= 1.2e-6. These larger\ncorrectness samples are separate from the 5,000-shot accuracy benchmark and do\nnot increase its statistical sample size.\n\n`summary.csv` is regenerated from raw counts and phase times: every field,\nall 66 rows and the exact header are checked, including rate, Wilson interval\nand median workflow time. Missing, duplicate or extra rows and resealed changes\nto any field must fail. Wilson intervals in the source JSON are also recomputed.\n\nAll executed noise deletion/replacement controls retain their measured negative\nobservations, including the real-circuit Fisher event counts. The independent\nreport checker recomputes their decisions and failure lists, checks unchanged\nreference observations, and verifies the instruction counts and complete affected\nprobe inventory. Low-probability controls must reject every affected probe;\n`LOSS_0.01` is outside the deletion range and cannot substitute for one. Changing\na failure summary or reusing healthy counts as negative evidence fails verification\neven after checksums are resealed and with optimized Python.\n\nThe updated correctness report is linked to `provenance-correctness.json` and\n`source-snapshot-correctness.json`. All sampling, correctness, decoding and seed records are regenerated from the same clean source commit. The fixed workload configurations and declared seeds are retained; timings are newly measured.\n\n`decoder_reference.py` independently specifies three- and five-wire parity-check\ngraphs, their base weights log(9), and loss-conditioned weights. It checks the\nexported graphs and loss-to-edge mapping against hand-derived values, enumerates\nall correction masks for all 64 + 1,024 flag/value rows, and checks native and\nPyMatching predictions against the full set of minimum-weight answers (including\nties). Altering lost-value placeholders must leave predictions unchanged.\n\nThe five-wire witness has two compatible corrections, 11100 and 00011. With the\nfirst three wires lost, fixed costs 3 versus 2 uniquely prefer logical 0;\nconditioned costs 1.5 versus 2 uniquely prefer logical 1. An actual PyMatching\nadapter that ignores conditioning is run through the same acceptance rule and\nmust fail this witness. A deliberately flipped native prediction must also fail.\nA regression additionally substitutes the broken adapter for the healthy one\nand requires the overall correctness report to fail. This covers the matching\nobjective and public-row transformation, not the general loss-envelope compiler\nor Bayes-optimal logical-class decoding.\n\nThe three/five-wire report retains the exported graph, every public syndrome and\nloss pattern, and all healthy and deliberately defective predictions. A separate\nstandard-library checker derives the two complementary repetition-code corrections\nand checks their logical costs, graph/loss mappings, all rejection lists and the\nstrict witness. Missing backends, failed case flags and contradictory witness\npredictions are rejected even after resealing checksums, including under `python -O`.\nCI reruns this oracle and validates the published observations against the same\nhand-derived definition; legal choices among tied optima remain acceptable.\n\n`chain_reference.py` adds a finite, real Mid-SWAP d=3, two-round chain check\nusing the committed `fixtures/midswap_d3_r2.stim` (16 detectors). It covers four\nprivate onset histories (none, early, middle, late), enumerates every single\nPauli-fault choice on each physically lowered circuit and takes one canonical\n`reference_sample()` measurement witness per trace. Unlike seeded compiled\nsampling, this is independent of the host SIMD random stream. This produces\n2,998 traces including no-fault controls; duplicate records are removed and\npaired alternative lost-value placeholders are added. These enriched inputs are\nnot IID samples and are never used to estimate a logical failure rate.\n\nStim independently constructs the correlated Pauli distribution, propagates 897\nPauli probes to build loss-envelope candidate sets, and transforms public rows\nto canonical syndromes. The declared envelope model resolves CX as H-CZ-H,\nincluding both target-basis boundaries. The Rust compiler's full correlated\nPauli distribution (coalescing identical effects), candidate sets and row\ntransformation must match. Altered compiler weights and missing candidates must\nbe rejected. Exact min-plus dynamic programming over all 131,072 detector/logical\nparity states checks matching predictions against the independently constructed\ngraph. All 752 rows run through native streaming matching, native MLE, and\nboth actual exported-graph batch adapters (PyMatching and native offline). Each\noutput is scored against the independent allowed answers, rather than agreement\nwith another backend. Constant-zero, constant-one and flipped predictions must\nfail; changing lost-value placeholders must not change any backend's output.\n\nBoth batch adapters also execute three deliberately corrupted exports: empty\nedges, empty loss-to-edge mappings, and all observable-labelled edge weights\nmultiplied by 1e-6 with the mean recomputed. Empty topology may cause an explicit\ndecoder error; the other mutations must complete and produce oracle-rejected\nanswers. The report retains row-level allowed answers, predictions and rejection\nindices. The verifier recomputes their summaries and requires every backend and\nnegative control; CI reruns the full chain, compares its independently recomputed\noracle definitions and measurement-row hash with the published artifact, and revalidates both sets of\nobservations. Different choices among equally optimal logical answers are allowed. These checks cover this finite fixture and four\nloss histories, not arbitrary graph exports or all combinations of loss flags.\n\nFor MLE, different equivalent Bernoulli decompositions can have different\nmost-likely **fault configurations**. After independently validating its physical\ndistribution and candidates, we enumerate the native model's representation\nwithout using ILP and check MLE predictions against all minimum-cost answers.\nThus the MLE objective check uses a **validated native representation**, not an\nindependently chosen Stim fault decomposition. This is compositional evidence\nfor this finite fixture and the stated envelope objective; it neither proves\narbitrary compiler inputs correct nor establishes physical logical-class Bayes\noptimality. This independent physical oracle covers d=3, two rounds and four loss\nhistories; replay agreement on d=5/7 and multiple losses is not independent proof\nof those broader physical models. The feature-gated model exporter reads public inputs only and is\nseparate from the timed matching exporter.\n\n## Evidence contract\n\nThe verifier treats raw observations as evidence and recomputes derived fields;\na checksum or stored PASS is not an authority for internal consistency.\n\n| Artifact | Required observations and relationships |\n| --- | --- |\n| Public/private corpus | Version, mode, shot count, row width/stride/bit order, circuit measurement/detector/observable counts, exact byte lengths, zero padding, file hashes and recomputed dataset identity agree. Masks and answers contain exactly one binary value per shot. |\n| Scoring key | Independently parse observable record indices, calculate parity from each public measurement row, and XOR its private input mask. Every resulting bit equals the scoring answer, both during real export checks and standalone archive rescoring. |\n| Small-circuit report | Complete Rust/reference histogram counts cover every shot; recompute joint delta, declared tolerance and deterministic known answers. |\n| Analytic/distribution reports | Complete named cases and both backends; expected probabilities come from hand-derived probe specifications. Marginals, event rates and tolerances agree with observations and verdicts. |\n| Low-probability reports | Both backends have complete joint counts. Marginal/nonidentity counts follow from that joint histogram. Recompute exact binomial intervals from probability and sample size. |\n| Real-circuit report | All 196 preselected events and consistent stratum sizes are present. Recompute Fisher p-values from raw counts, the Bonferroni threshold and the verdict; scoring-key coverage equals the full shot count. |\n| Summary/timing tables | Every field and row matches underlying counts and phase timings; Wilson intervals and totals are recomputed. |\n\nThe report verifier uses a separate standard-library implementation of binomial\nquantiles (normalized PMF recurrence) and Fisher tests (hypergeometric sums).\nSciPy produces the original statistics; tests compare the independent formulas.\nFloating-point comparisons allow numerical roundoff, but acceptance is decided\nfrom recomputed statistics. The standalone download remains Python 3.10+ with\nno external dependencies. Its updated script is included in the shot archive;\noriginal corpus and existing prediction bytes remain unchanged; decoder timing JSON is replaced by fresh measurements.\n\nRegression matrices delete fields and observations, corrupt formats, truncate\npacked data, alter padding, flip one/all answers and masks with coherent file\nchecksums, and change derived values/verdicts. Actual exporter answer corruption\nmust fail the independent check. These are consistency checks, not authenticity\nagainst someone deliberately replacing every source and all evidence together.\n\n## Three experiments\n\n1. **Sampling time:** Mid-SWAP d = 3, 5, 7, rounds = d, Pauli probability\n   0.001, operation and pre-measurement loss probabilities both 0.003. Both\n   implementations return loss-visible rows and pack b8, in batches of 256.\n   Rust parses once; auto-sampler preparation is timed on each call. The Python\n   reference includes parsing, grouping and per-history Stim compilation.\n   Imports, process startup and file I/O are excluded. Rust uses two warmups;\n   the Python reference uses one. The page compares their recorded milliseconds per\n   256-shot batch in a table, with medians and min/max over three runs calculated\n   directly from `sampling.json`. A prominent note above the table explains\n   that the Python reference is unoptimized and includes parsing, loss-history\n   circuit construction and Stim compilation, while Rust parsing is excluded.\n   These costs have different boundaries: this is **not native Stim performance**\n   and no backend speedup ratio is inferred. The separate Rust absolute-throughput\n   and reference-cost figures remain available in the evidence bundle.\n2. **Loss sweep:** d = 3, 5, 7, rounds = d; Pauli probability 0.001; each loss\n   probability in 0.0001, 0.0003, 0.001, 0.003, 0.01. Each point uses 5,000 shared\n   blinded shots with seed 20260911. Compare native envelope matching, PyMatching\n   with the same envelope-conditioned graph, and PyMatching with fixed base\n   weights. The last is a loss-conditioning ablation: it still receives the same\n   canonical syndromes, so it does not remove every use of loss flags.\n   `timing-sweep.svg` also shows all 15 settings, with three-run medians/ranges,\n   individual panel log y-ranges and no omitted timing points. `timing-sweep.csv`\n   exposes all 180 decoder repetitions, exact input-pattern counts, graph builds,\n   and native streaming cache hits (blank for offline groups). Native offline\n   and PyMatching use the same group policy; native streaming remains separate.\n   Compare all settings and their repeat ranges, not a universal kernel ranking.\n3. **Accuracy / time:** d = 3, rounds = 2, Pauli 0.001, loss 0.003, 5,000 shared\n   shots, seed 20260912. Add envelope MLE with a 500 ms per-shot timeout. Plot\n   logical failure probability against amortized compilation + decoding time,\n   with fresh decoder caches in each of three repetitions. The main PyMatching\n   comparators use `from_check_matrix` and `decode_batch`; fixed-weight per-shot calls are also retained\n   as an API control and must produce identical predictions to the batch path.\n   Backend order rotates each repetition, with serial execution and no concurrent\n   build/test workload. Each repetition reruns and remeasures the common Rust compiler and public-row\n   transformation. Python decode time includes sparse topology/weight preparation\n   once per invocation, array conversion, loss-pattern\n   grouping, graph construction, batched decoding, reordering predictions, and b8 output write/flush.\n   Startup, scoring and JSON transport/loading are excluded. Native decode time\n   includes buffered public-row reads and output packing/flush; the exporter's\n   transformation stage also includes public-row reads. Both offline adapters use the same public model exporter and exclude JSON transport/loading; both include output b8 encoding, writing and flush (without fsync). The native streaming CLI remains a separate policy comparison.\n   Each batch repetition separately records sparse topology/weight preparation,\n   array/group/selection, bulk graph construction,\n   decode_batch API calls, output reordering, and remaining adapter/timer overhead.\n   The supplementary stage chart uses additive means of these phases plus the\n   shared compiler/transform stages. Its graph-construction percentage uses\n   Python adapter time as the denominator; native decode remains an aggregate.\n   Instrumentation overhead is retained, not subtracted.\n   These are adapter/workflow timings, not isolated matching-kernel timings or\n   online p99 latency. Do not infer a universal backend speed ranking.\n\nThe horizontal coordinate pLoss is the **configured loss parameter**, passed\nto both operation loss and pre-measurement loss. Single-qubit and measurement\nopportunities use pLoss; each target of a two-qubit operation uses pLoss/2. It is not the total\nprobability that a wire is lost during an experiment. The exact generated circuit\nhash, initial logical-X support derived from its coordinates, public-row hash,\nprivate-answer hash and dataset ID are retained at every decoding point.\n\nLogical error bars are pointwise 95% Wilson intervals. The default loss-sweep\nfigure shows all 15 settings at d = 3, 5, 7 on logarithmic axes. Zero-event points\nuse downward arrows at the exact one-sided 95% binomial upper bound\n`1 - 0.05**(1/N)` (about 0.000599 for N = 5,000), not a positive measured rate.\nNonzero points retain Wilson intervals. The optional d = 3/5 detail omits\nzero-failure points, with no lines joining across those gaps. Both figures use\nthe same complete raw JSON and summary CSV; display omissions do not change\nscoring. Timing ranges are observed min/max, not confidence intervals.\nThe curves report failure per entire memory experiment; rounds vary with distance.\nTiming repeats reuse one corpus; they do not turn 5,000 shots into 15,000\nindependent accuracy samples. Many low-loss points have only 0\u20135 failures and\ncannot resolve small differences. At the d=3 two-round tradeoff point, conditioned\nversus fixed weights have 0 conditioned-only and 13 fixed-only failures; this\npaired evidence supports improvement at that setting only. MLE's 1/5,000 has\nlarge relative uncertainty and remains tied to its fault-configuration objective.\nThere is no threshold fit, accuracy ranking by overlapping intervals, or\nextrapolation to other circuits or larger distances.\n\n## Backend adapter and failures\n\nThe feature-gated exporter reads **only** the public dataset and shares RustQEC's\ncompiler. It emits canonical syndromes, visible loss patterns, base graph edges,\nloss-to-edge mappings and weights. Python applies exactly the native rule:\nactive time-like edges get 0.25 times the mean base weight; active space/boundary\nedges get 0.5 times that mean; all weights share the native scale normalization.\nParallel edges are permitted only with identical logical labels by the native\ncompiler. PyMatching keeps the smallest parallel weight, preserving this\nnonnegative minimum-weight objective rather than combining independent errors.\n\nThe native adapter caches at most 1,024 patterns FIFO and enforces a work budget.\nThe batch Python adapter groups all shots by visible loss pattern, builds one\ngraph per group with the official `from_check_matrix` interface, calls `decode_batch` and restores input\norder. The sparse check/fault matrices and base/conditioned weight arrays are\nprepared once inside each measured invocation; each pattern copies and conditions\nits weights. Parallel edges use `smallest-weight` and boundary edges use a virtual\nboundary node. No topology preparation is amortized across timing repetitions.\nGrouping and reordering costs are included; this offline batch policy\nrequires retaining the batch and differs from the native streaming cache policy.\nOnly the per-shot Python API control uses the 1,024-entry FIFO cache. Graph builds,\nbatch calls and available cache statistics are recorded. Backend integer weight\nquantization and tie choices can produce prediction differences. The run retains\nprediction disagreements and paired native-only / Python-only failure counts;\nmatching predictions are not assumed identical.\n\nA nonzero exit, timeout or unsupported circuit is recorded as an incomplete run.\nNo logical error rate is reported from its successful prefix. The publication\nstep requires all four sweep comparators at all 15 settings; a missing/failed\ncomparator blocks curve publication rather than silently joining across a gap. The all-shot MLE\nsuccess requirement is separate from the matching runs. Any missing graph export\nis recorded at case level. This first suite does not benchmark QEC-Playground or\na paper implementation of delayed-erasure decoding.\n\nPrimary implementation sources:\n\n- [Stim gates](https://github.com/quantumlib/Stim/blob/main/doc/gates.md#HERALDED_ERASE):\n  heralded erasure alone is not persistent absent-wire evolution.\n- [Stim DEPOLARIZE2 definition](https://github.com/quantumlib/Stim/blob/main/doc/gates.md#the-depolarize2-instruction):\n  each of the 15 nonidentity Pauli pairs has probability p/15; eight flip Z parity.\n- [PyMatching bulk graph construction](https://pymatching.readthedocs.io/en/stable/api.html#pymatching.Matching.from_check_matrix):\n  sparse parity-check and fault matrices with explicit weights and edge merge policy.\n- [PyMatching batch decoding](https://pymatching.readthedocs.io/en/stable/#decoding-stim-circuits):\n  official `decode_batch` interface for reducing per-shot Python overhead;\n  the pinned package version is in `requirements.txt` and the run provenance.\n- `rstim/src/codegen/midswap.rs`, `rstim/src/executor.rs`,\n  `rustqec-cli/src/decode/compiler.rs`, `rustqec-cli/src/decode/matching.rs`:\n  generated workload and the production semantics being tested.\n\n\n## Deterministic origin and optimized-mode validation\n\n`validate_dataset` reconstructs the private mask from the declared seed and\nbatch size, including domain-separated SHA-256 keys, ChaCha12 words, rand 0.8\nboolean sampling and the per-batch 64-bit `usize` shuffle. The standalone ZIP\nchecker implements this independently in Python. All 16 original masks match.\nThis replay is explicitly tied to rand 0.8 / rand_chacha 0.3 on a 64-bit host;\nit does not assume future versions of Rust `StdRng` preserve their stream.\nA regression changes masks and answers together to force a chosen decoder to\nzero failures, reseals the private manifest, and requires rejection.\n\n`python -m benchmarks.atom_loss.replay` also regenerates the original circuits\nand public/private sample bytes using the declared configuration. All 16 match.\nThe fixed seeds are 20260911 for the sweep and 20260912 for tradeoff. CI repeats\nthis check. Checksums alone establish internal integrity, not an authenticated\nsource or immunity to an author changing the generator and the experiment plan.\n\nEvery production Python evidence check uses explicit exceptions. CI runs the\nverifier both normally and with `python -O`; resealed corrupted chain metadata\nmust fail in both modes. Tests may still use unittest assertions.\n\n## Matched offline policy and new timing measurements\n\nThe additional `envelope-matching-offline` executable is a feature-gated\nbenchmark adapter using rmatching. Both offline adapters consume the same\nexported public graph, group the whole batch in first-appearance pattern order,\nbuild one graph per distinct loss pattern, decode each group in batch, restore\noriginal shot order and write/flush the b8 predictions. They retain the batch\nand only one group's matching graph at a time. Preparation and grouping are\ninside their measured intervals. JSON transport/loading and process startup\nare excluded on both sides; each repetition freshly measures the same compiler\nand public-row transformation. There is no output fsync on either side.\n\nThe original streaming CLI remains in the charts, explicitly as a different\nFIFO/work-budget policy. Its output still includes buffered writes and flush.\nOffline native predictions must equal streaming predictions on every retained\ncorpus; graph build counts must equal the number of distinct input patterns.\nThe three repetitions on each original corpus are fresh measurements with\nrotated serial backend order. Previous prediction values and sample bytes are\nunchanged. These are measured adapters, not language or kernel rankings.\n\n## Prospectively fixed multi-seed accuracy check\n\nBefore sampling, the additional seeds were fixed to **2026091401, 2026091402,\n2026091403**, with 5,000 shots each at all 15 sweep settings and the tradeoff\nsetting. No seed is replaced or sample count extended based on observed errors.\nEach seed compares native envelope matching, conditioned PyMatching and fixed\nPyMatching on identical public rows; tradeoff also includes MLE. All 48 corpora\nand 147 predictions are downloadable in `accuracy-seeds.zip`, together with\n`rescore.py`. Run `python -I -S rescore.py rescore-seeds accuracy-seeds.zip`.\n\n`accuracy-seeds.json` retains each seed's counts, Wilson intervals and paired\ndiscordant counts, plus pooled differences on 15,000 independently generated\nshots per setting. The paired difference is native failure probability minus\nthe comparator's: negative values favor native. Its conservative pointwise 95%\ninterval subtracts opposite ends of 97.5% Clopper-Pearson intervals for the two\ndiscordant probabilities (Bonferroni). It does not pretend the paired outcomes\nare independent. The independent checker inverts binomial CDFs using the Python\nstandard library; regression values are checked against SciPy beta quantiles.\nThese are pointwise intervals, not simultaneous coverage across all settings.\nThree seeds still do not establish a threshold or universal accuracy ranking.\nThe old three timing repetitions remain only 5,000 accuracy shots; the new\n15,000-shot data are a separate experiment, not pooled with the original corpus.\n\n\nThe clean `evidence_run` entry point above runs the additional accuracy experiment\nafter timing has finished. Its sources and measured binaries are bound to the\nsame source commit in `provenance-seeds.json`. To verify the retained seed corpus:\n\n```sh\npython -m benchmarks.atom_loss.replay --archive site/static/data/atom-loss/accuracy-seeds.zip\npython -m benchmarks.atom_loss.decoder_replay\npython -O -m benchmarks.atom_loss.verify\n```\n\nHistorical timings remain available in Git history. Current figures show the\nfresh output-inclusive workflow measurements and the native offline comparator.\n",
    "benchmarks/atom_loss/accuracy_seeds.py": "\"\"\"Prospectively fixed three-seed accuracy experiment; no timing claims.\"\"\"\nimport argparse\nimport json\nfrom pathlib import Path\nimport zipfile\nfrom .run import ROOT, generate, checked, logical_x, digest, save, score, native_decode, export_graph, python_decode\nfrom .shot_data import SEEDS, validate_dataset, seed_summaries, rescore_seeds\nimport numpy as np\n\n\ndef pack(work,out):\n    report=json.loads((out/'accuracy-seeds.json').read_text())\n    payload={'accuracy-seeds.json':(out/'accuracy-seeds.json').read_bytes(),\n             'rescore.py':(ROOT/'benchmarks/atom_loss/shot_data.py').read_bytes()}\n    for case in report['cases']:\n        prefix=f\"{case['setting']}-s{case['seed']}\"\n        for name in ['public/circuit.stim','public/manifest.json','public/shots.b8','private/manifest.json','private/answers.b8','private/masks.b8']+[name+'.b8' for name in case['decoders']]:\n            payload[prefix+'/'+name]=(work/prefix/name).read_bytes()\n    import hashlib\n    payload['index.json']=json.dumps({'sha256':{n:hashlib.sha256(v).hexdigest() for n,v in payload.items()}},indent=2).encode()\n    with zipfile.ZipFile(out/'accuracy-seeds.zip','w',compression=zipfile.ZIP_DEFLATED) as z:\n        for name,value in sorted(payload.items()):\n            info=zipfile.ZipInfo(name,(2026,1,1,0,0,0));info.compress_type=zipfile.ZIP_DEFLATED;z.writestr(info,value)\n    print(rescore_seeds(out/'accuracy-seeds.zip',out))\n\n\ndef capture_sources(out):\n    from .source_contract import capture\n    capture(out, 'seeds', {'seeds': SEEDS, 'shots_per_seed': 5000,\n                           'timing': 'Accuracy only; no timing inference.'})\n\n\ndef run(work,out):\n    capture_sources(out)\n    binary=ROOT/'target/release/rustqec';exporter=ROOT/'target/release/examples/export_matching_benchmark'\n    report={'seeds':SEEDS,'shots_per_seed':5000,'cases':[]}\n    settings=[(f'd{d}-p{p}',d,d,p) for d in [3,5,7] for p in [.0001,.0003,.001,.003,.01]]+[('tradeoff',3,2,.003)]\n    for label,d,rounds,p in settings:\n        for seed in SEEDS:\n            path=work/f'{label}-s{seed}';path.mkdir(parents=True,exist_ok=False)\n            circuit=path/'circuit.stim';generate(binary,circuit,d,rounds,p)\n            checked([binary,'dataset','export','--circuit',circuit,'--shots',5000,'--seed',seed,\n                     '--mode','measurements_blinded','--logical-x-qubits',logical_x(circuit.read_text(),d),\n                     '--public-out',path/'public','--private-out',path/'private'])\n            answers=np.frombuffer(validate_dataset(lambda n:(path/n).read_bytes()),dtype=np.uint8)\n            public=json.loads((path/'public/manifest.json').read_text())\n            case={'setting':label,'distance':d,'rounds':rounds,'loss_probability':p,'pauli_probability':.001,'shots':5000,'seed':seed,\n                  'dataset_id':public['dataset_id'],'circuit_sha256':digest(path/'public/circuit.stim'),\n                  'public_rows_sha256':digest(path/'public/shots.b8'),'answers_sha256':digest(path/'private/answers.b8'),\n                  'decoders':{},'paired':{}}\n            native,record=native_decode(binary,path,'envelope-matching',0)\n            if record['status']!='ok':raise ValueError(record)\n            predictions={'envelope-matching':native}\n            graph=export_graph(exporter,path,'accuracy')\n            for name in ['pymatching-envelope','pymatching-fixed']:\n                predictions[name]=python_decode(graph,name=='pymatching-envelope')[0]\n            if label=='tradeoff':\n                mle,record=native_decode(binary,path,'envelope-mle',0)\n                if record['status']!='ok':raise ValueError(record)\n                predictions['envelope-mle']=mle\n            for name,pred in predictions.items():\n                (path/(name+'.b8')).write_bytes(pred.tobytes());case['decoders'][name]=score(pred,answers)\n                if name!='envelope-matching':\n                    case['paired'][name]={'native_only_wrong':int(np.count_nonzero((native!=answers)&(pred==answers))),\n                                          'other_only_wrong':int(np.count_nonzero((native==answers)&(pred!=answers)))}\n            report['cases'].append(case);save(out/'accuracy-seeds.json',report)\n            print(label,seed,{n:r['errors'] for n,r in case['decoders'].items()},flush=True)\n    report['pooled']=seed_summaries(report['cases']);save(out/'accuracy-seeds.json',report);pack(work,out)\n\n\nif __name__=='__main__':\n    p=argparse.ArgumentParser();p.add_argument('--work',type=Path,required=True);p.add_argument('--out',type=Path,required=True)\n    a=p.parse_args();a.out.mkdir(parents=True,exist_ok=True);run(a.work,a.out)\n",
    "benchmarks/atom_loss/artifacts.py": "\"\"\"Shared publication contract and authoritative native timing boundary.\"\"\"\nimport math\nimport json\nimport statistics\n\nFIGURE_NAMES = ('accuracy-seeds', 'sampling-throughput', 'logical-error-rate',\n                'logical-error-rate-full', 'accuracy-time', 'adapter-stages',\n                'sampling-reference-cost', 'timing-sweep')\nFIGURE_INPUTS = ('accuracy-seeds.json', 'sampling.json', 'decoding.json', 'tradeoff.json')\n\nREQUIRED_FILES = frozenset([\n    'source-manifest.json', 'chain-correctness.json', 'midswap_d3_r2.stim', 'correctness.json',\n    'decoder-correctness.json', 'sampling.json', 'decoding.json', 'tradeoff.json',\n    'provenance-all.json', 'methodology.md', 'summary.csv', 'source-snapshot.json',\n    'shot-data-v1.zip', 'timing-sweep.csv', 'accuracy-seeds.json', 'accuracy-seeds.zip',\n    'provenance-seeds.json', 'source-snapshot-seeds.json',\n] + [f'{name}.{ext}' for name in FIGURE_NAMES for ext in ['svg', 'png']])\nTIMING_FILES = frozenset(['provenance-timing.json', 'source-snapshot-timing.json'])\n\n\nCORRECTNESS_FILES = frozenset(['provenance-correctness.json', 'source-snapshot-correctness.json'])\nREQUIRED_FILES = REQUIRED_FILES | TIMING_FILES | CORRECTNESS_FILES\n\n\ndef required_files(root):\n    \"\"\"Either member on disk makes both retiming provenance files mandatory.\"\"\"\n    retimed = any((root/name).exists() for name in TIMING_FILES)\n    for name in ['decoding.json', 'tradeoff.json']:\n        if (root/name).exists():\n            data = json.loads((root/name).read_text())\n            cases = data if isinstance(data, list) else [data]\n            retimed |= any(case.get('baseline_predictions_unchanged', False) for case in cases)\n    correctness = any((root/name).exists() for name in CORRECTNESS_FILES)\n    if (root/'correctness.json').exists():\n        correctness |= json.loads((root/'correctness.json').read_text()).get('provenance_file') == 'provenance-correctness.json'\n    return REQUIRED_FILES | (TIMING_FILES if retimed else set()) | (CORRECTNESS_FILES if correctness else set())\n\n\ndef native_total(run):\n    if run.get('status') != 'ok' or run.get('exit_code') != 0 or 'stats' not in run:\n        raise ValueError('Missing successful native timing stats')\n    phases = [run['stats'][key] for key in ['compile_seconds', 'decode_seconds']]\n    if any(not math.isfinite(value) or value < 0 for value in phases):\n        raise ValueError('Invalid native phase time')\n    return sum(phases)\n\n\ndef timing_rows(decoding):\n    \"\"\"All measured sweep repetitions, with explicitly different cache policies.\"\"\"\n    for case in decoding:\n        for name,result in case['decoders'].items():\n            for rep,(record,total) in enumerate(zip(result['runs'],result['total_seconds'])):\n                native=not name.startswith('pymatching')\n                stats=record['stats'] if native else record\n                yield {**{k:case[k] for k in ['distance','rounds','loss_probability']},\n                    'decoder':name,'repetition':rep,'microseconds_per_shot':total/case['shots']*1e6,\n                    'input_loss_patterns':case['graph']['loss_patterns'],\n                    'graph_builds':stats['matching_graph_builds'] if native else stats['graph_builds'],\n                    'cache_hits':stats['cache_hits'] if name=='envelope-matching' else '',\n                    'policy':'FIFO/work-budget streaming' if name=='envelope-matching' else 'offline batch groups'}\n\n\nSUMMARY_FIELDS = ['experiment','distance','rounds','loss_probability','decoder','status',\n                  'shots','errors','logical_error_rate','ci95_low','ci95_high',\n                  'median_microseconds_per_shot']\n\n\ndef wilson(errors, shots):\n    z = 1.959963984540054\n    p = errors / shots\n    center = (p + z*z/(2*shots))/(1+z*z/shots)\n    delta = z*math.sqrt(p*(1-p)/shots+z*z/(4*shots*shots))/(1+z*z/shots)\n    return [max(0., center-delta), min(1., center+delta)]\n\n\ndef summary_rows(decoding, tradeoff):\n    \"\"\"Derive downloads from counts and raw phase timings, not cached summaries.\"\"\"\n    for experiment, cases in [('loss_sweep', decoding), ('accuracy_time', [tradeoff])]:\n        for case in cases:\n            for name, result in case['decoders'].items():\n                row = dict.fromkeys(SUMMARY_FIELDS, '')\n                row.update({k:case[k] for k in ['distance','rounds','loss_probability','shots']})\n                row.update(experiment=experiment, decoder=name, status=result['status'])\n                if result['status'] == 'ok':\n                    shots, errors = result['shots'], result['errors']\n                    if shots != case['shots'] or not 0 <= errors <= shots:\n                        raise ValueError('Invalid summary counts')\n                    lo, hi = wilson(errors, shots)\n                    times = [sum(run[k] for k in ['compile_seconds','transform_seconds','decode_seconds'])\n                             if name.startswith('pymatching') else native_total(run) for run in result['runs']]\n                    row.update(errors=errors, logical_error_rate=errors/shots, ci95_low=lo, ci95_high=hi,\n                               median_microseconds_per_shot=statistics.median(times)/shots*1e6)\n                yield row\n\n\ndef require_complete_sweep(cases):\n    expected={(d,p) for d in [3,5,7] for p in [.0001,.0003,.001,.003,.01]}\n    if len(cases)!=15 or {(c['distance'],c['loss_probability']) for c in cases}!=expected:\n        raise ValueError('Loss sweep is incomplete; keep raw failures and do not publish a partial curve')\n    for case in cases:\n        decoders=case.get('decoders',{})\n        if set(decoders)!={'envelope-matching','pymatching-fixed','pymatching-envelope','envelope-matching-offline'}:\n            raise ValueError('Missing loss-sweep comparator')\n        if any(r.get('status')!='ok' for r in decoders.values()):\n            raise ValueError('Loss sweep includes failed runs; retain raw records without publishing a partial curve')\n",
    "benchmarks/atom_loss/chain_contract.py": "\"\"\"Standard-library validation of retained physical-chain oracle observations.\n\nRecompute every prediction summary and mutation rejection from the recorded\nbinary rows and allowed logical answers. Independent physical derivation is the\nproducer's job; CI also compares a fresh producer run to the published report.\n\"\"\"\nimport hashlib\n\n\nROWS = 752\nOBJECTIVES = ('envelope-matching', 'envelope-mle')\nGRAPH_BACKENDS = ('pymatching-envelope', 'envelope-matching-offline')\nBACKENDS = OBJECTIVES + GRAPH_BACKENDS\nMUTATIONS = ('empty_edges', 'empty_loss_mapping', 'relative_weights')\nSUMMARY_FIELDS = {\n    'predictions', 'checked_rows', 'rejected_rows', 'unique_optimum_rows',\n    'predicted_ones', 'constant_zero_rejected', 'constant_one_rejected',\n    'flipped_prediction_rejected', 'placeholder_invariance', 'prediction_sha256',\n}\n\n\ndef require(condition, message):\n    if not condition:\n        raise ValueError('Chain report contract: '+message)\n\n\ndef mapping(value, names, label, *, exact=True):\n    require(type(value) is dict, label+' must be an object')\n    require(set(value) == set(names) if exact else set(names) <= set(value),\n            label+' fields are incomplete or unexpected')\n\n\ndef bits(values, label):\n    require(type(values) is list and len(values) == ROWS, f'{label} must contain {ROWS} rows')\n    require(all(type(value) is int and value in (0, 1) for value in values),\n            label+' must contain integer binary predictions')\n\n\ndef rejected_rows(predictions, choices):\n    return [index for index, (value, answers) in enumerate(zip(predictions, choices))\n            if value not in answers]\n\n\ndef verify_chain(report):\n    \"\"\"Reject incomplete, internally inconsistent or failed chain evidence.\"\"\"\n    required = {\n        'status', 'fixture_sha256', 'measurement_sha256', 'witness_generation',\n        'distance', 'rounds', 'detectors', 'rows',\n        'physical_fault_traces', 'patterns', 'stim_pauli_probes',\n        'independent_effects', 'independent_graph_edges', 'native_graph_edges',\n        'independent_effects_candidates_and_m2d_pass',\n        'compiler_output_mutations_rejected', 'backends', 'allowed_answers',\n        'graph_adapter_controls', 'method', 'mle_objective', 'scope',\n    }\n    mapping(report, required, 'report', exact=False)\n    require(report['status'] == 'PASS', 'report did not pass')\n    for name, expected in {\n        'distance': 3, 'rounds': 2, 'detectors': 16, 'rows': ROWS,\n        'physical_fault_traces': 2998, 'patterns': 4,\n    }.items():\n        require(type(report[name]) is int and report[name] == expected,\n                'incorrect fixed workload '+name)\n    # Raw graph counts depend on valid DEM decomposition and are diagnostics,\n    # not an assertion that the native and independent edge lists are identical.\n    for name in ('stim_pauli_probes', 'independent_effects',\n                 'independent_graph_edges', 'native_graph_edges'):\n        require(type(report[name]) is int and report[name] > 0, 'invalid diagnostic '+name)\n    for field in ('fixture_sha256', 'measurement_sha256'):\n        digest = report[field]\n        require(type(digest) is str and len(digest) == 64\n                and all(c in '0123456789abcdef' for c in digest), 'invalid '+field)\n    require(report['witness_generation'] == 'stim-reference-sample',\n            'incorrect witness_generation')\n    for name in ('method', 'mle_objective', 'scope'):\n        require(type(report[name]) is str and bool(report[name].strip()), 'missing '+name)\n    require(report['independent_effects_candidates_and_m2d_pass'] is True,\n            'independent physical model did not pass')\n    compiler = report['compiler_output_mutations_rejected']\n    mapping(compiler, ('pauli_weight', 'loss_candidate'), 'compiler mutations')\n    require(all(value is True for value in compiler.values()), 'compiler mutation was not rejected')\n\n    answers = report['allowed_answers']\n    mapping(answers, OBJECTIVES, 'allowed answers')\n    for objective, choices in answers.items():\n        require(type(choices) is list and len(choices) == ROWS,\n                f'{objective} allowed answers must contain {ROWS} rows')\n        for row in choices:\n            require(type(row) is list and row and all(type(v) is int and v in (0, 1) for v in row)\n                    and row == sorted(set(row)), objective+' invalid allowed answer set')\n        require(choices[:ROWS//2] == choices[ROWS//2:], objective+' placeholder answer mismatch')\n        require(any(len(row) == 1 for row in choices), objective+' lacks unique optimum witnesses')\n        require(any(0 not in row for row in choices) and any(1 not in row for row in choices),\n                objective+' cannot reject constant predictions')\n\n    backends = report['backends']\n    mapping(backends, BACKENDS, 'backends')\n    for name, record in backends.items():\n        mapping(record, SUMMARY_FIELDS, name+' prediction record')\n        predictions = record['predictions']\n        bits(predictions, name)\n        choices = answers[name if name in OBJECTIVES else 'envelope-matching']\n        rejected = rejected_rows(predictions, choices)\n        singleton = [i for i, row in enumerate(choices) if len(row) == 1]\n        expected = {\n            'checked_rows': ROWS, 'rejected_rows': rejected,\n            'unique_optimum_rows': len(singleton), 'predicted_ones': sum(predictions),\n            'constant_zero_rejected': any(0 not in row for row in choices),\n            'constant_one_rejected': any(1 not in row for row in choices),\n            'flipped_prediction_rejected': (predictions[singleton[0]] ^ 1) not in choices[singleton[0]],\n            'placeholder_invariance': predictions[:ROWS//2] == predictions[ROWS//2:],\n            'prediction_sha256': hashlib.sha256(bytes(predictions)).hexdigest(),\n        }\n        for field, value in expected.items():\n            require(type(record[field]) is type(value) and record[field] == value,\n                    name+' inconsistent '+field)\n        require(not rejected, name+' predictions fail the independent oracle')\n        require(expected['placeholder_invariance'] and expected['flipped_prediction_rejected'],\n                name+' failed positive-control invariance or sensitivity')\n\n    controls = report['graph_adapter_controls']\n    mapping(controls, MUTATIONS, 'graph mutations')\n    for mutation, adapters in controls.items():\n        mapping(adapters, GRAPH_BACKENDS, mutation+' adapters')\n        for name, record in adapters.items():\n            label = mutation+'/'+name\n            mapping(record, ('outcome', 'predictions', 'rejected_rows'), label)\n            if record['outcome'] == 'decoder_error':\n                require(mutation == 'empty_edges', label+' requires a real oracle rejection')\n                require(record['predictions'] is None and type(record['rejected_rows']) is list\n                        and record['rejected_rows'] == [], label+' invalid decoder-error evidence')\n            else:\n                require(record['outcome'] == 'oracle_rejected', label+' mutation was accepted')\n                bits(record['predictions'], label)\n                rejected = rejected_rows(record['predictions'], answers['envelope-matching'])\n                require(type(record['rejected_rows']) is list\n                        and all(type(i) is int for i in record['rejected_rows'])\n                        and record['rejected_rows'] == rejected, label+' inconsistent rejected rows')\n                require(bool(rejected), label+' has no rejected oracle witness')\n\n\ndef compare_reports(fresh, published):\n    \"\"\"Require the same oracle definitions while allowing legal tied optima.\"\"\"\n    verify_chain(fresh)\n    verify_chain(published)\n    observations = {'backends', 'graph_adapter_controls'}\n    fresh_definitions = {key: value for key, value in fresh.items() if key not in observations}\n    published_definitions = {key: value for key, value in published.items() if key not in observations}\n    changed = sorted(key for key in fresh_definitions.keys() | published_definitions.keys()\n                     if key not in fresh_definitions or key not in published_definitions\n                     or fresh_definitions[key] != published_definitions[key])\n    require(not changed, 'Fresh chain oracle definitions differ from published evidence: '+', '.join(changed))\n",
    "benchmarks/atom_loss/chain_reference.py": "\"\"\"Independent Stim fault propagation and exact finite-state decoder objectives.\n\nStim constructs independent noise distributions and loss candidate sets. Native\ncompiler outputs must pass those checks before their representation-dependent\nMLE fault-configuration objective is evaluated by exact dynamic programming.\n\"\"\"\nfrom .shot_data import require\nimport argparse\nimport copy\nfrom collections import defaultdict\nimport hashlib\nimport json\nimport math\nfrom pathlib import Path\nimport subprocess\nimport tempfile\nimport numpy as np\nimport stim\nfrom . import reference\nfrom .run import ROOT, save, digest\n\nFIXTURE = ROOT/'benchmarks/atom_loss/fixtures/midswap_d3_r2.stim'\n\n\ndef normalized(text):\n    circuit=stim.Circuit(); probes=[]; onsets=defaultdict(list); bases=defaultdict(list)\n    for op in reference.parse(text):\n        name=op.name\n        if name=='LOSS':\n            for q in map(int,op.targets): onsets[q].append(len(circuit))\n        elif name=='CX':\n            targets=list(map(int,op.targets)); changed=targets[1::2]\n            # The declared envelope model resolves CX into H-CZ-H, including\n            # both target-basis boundaries as possible Pauli randomizations.\n            circuit.append('H',changed)\n            for q in changed: bases[q].append(len(circuit))\n            circuit.append('CZ',targets)\n            circuit.append('H',changed)\n            for q in changed: bases[q].append(len(circuit))\n        elif name in ['ML','MRL']:\n            for q in map(int,op.targets):\n                flag=circuit.num_measurements\n                circuit.append('MPAD',[0])\n                probes.append({'qubit':q,'flag':flag,'onsets':onsets[q].copy(),\n                               'bases':bases[q].copy(),'readout':len(circuit)})\n                circuit.append('MR' if name=='MRL' else 'M',[q])\n                if name=='MRL': onsets[q].clear();bases[q].clear()\n        else:\n            args='('+','.join(map(str,op.args))+')' if op.args else ''\n            circuit += stim.Circuit(name+args+' '+' '.join(op.targets))\n            if name=='R':\n                for q in map(int,op.targets): onsets[q].clear();bases[q].clear()\n            elif name=='H':\n                for q in map(int,op.targets): bases[q].append(len(circuit))\n    return circuit,probes\n\n\ndef mask_of(targets, detectors):\n    mask=0\n    for t in targets:\n        if t.is_relative_detector_id(): mask ^= 1<<t.val\n        elif t.is_logical_observable_id(): mask ^= 1<<(detectors+t.val)\n    return mask\n\n\ndef independent_model(text, require_shape=(16,1)):\n    circuit,probes=normalized(text)\n    count=circuit.num_detectors\n    if require_shape is not None:\n        require((count==require_shape[0] and circuit.num_observables==require_shape[1]), 'chain_reference: count==16 and circuit.num_observables==1')\n    coords=circuit.get_detector_coordinates()\n    dem=circuit.detector_error_model(decompose_errors=True).flattened()\n    effects=[];edges=[]\n    for instruction in dem:\n        if instruction.type!='error': continue\n        probability=instruction.args_copy()[0]\n        weight=math.log((1-probability)/probability)\n        targets=instruction.targets_copy()\n        effects.append((mask_of(targets,count),weight))\n        components=[[]]\n        for t in targets:\n            if t.is_separator(): components.append([])\n            else: components[-1].append(t)\n        for component in components:\n            ds=sorted(t.val for t in component if t.is_relative_detector_id())\n            if not ds: continue\n            require((len(ds)<=2), 'chain_reference: len(ds)<=2')\n            factor=.25 if len(ds)==2 and coords[ds[0]][:2]==coords[ds[1]][:2] else .5\n            edges.append({'mask':mask_of(component,count),'ds':tuple(ds),'weight':weight,'factor':factor})\n    # Determine disconnected detector sectors without relying on Rust labels.\n    sector=list(range(count))\n    def find(q):\n        while sector[q]!=q: q=sector[q]\n        return q\n    for e in edges:\n        if len(e['ds'])==2: sector[find(e['ds'][0])]=find(e['ds'][1])\n    memo={}\n    def effect(site,q,pauli):\n        key=(site,q,pauli)\n        if key not in memo:\n            injected=circuit[:site].without_noise()\n            injected.append(pauli+'_ERROR',[q],.125)\n            injected += circuit[site:].without_noise()\n            terms=[i for i in injected.detector_error_model().flattened() if i.type=='error']\n            require((len(terms)<=1), 'chain_reference: len(terms)<=1')\n            memo[key]=mask_of(terms[0].targets_copy(),count) if terms else 0\n        return memo[key]\n    candidates=[];loss_edges=[]\n    for p in probes:\n        union=set(); primitive=set()\n        for onset in p['onsets']:\n            sites=sorted({onset,p['readout'],*(s for s in p['bases'] if onset<=s<=p['readout'])})\n            states={0}\n            for site in sites:\n                choices={0,*(effect(site,p['qubit'],pauli) for pauli in 'XYZ')}\n                primitive.update(choices)\n                states={a^b for a in states for b in choices}\n            union.update(states)\n        require((union), 'chain_reference: union')\n        candidates.append(sorted(union))\n        mapped=set()\n        for fault in primitive:\n            sectors=defaultdict(list)\n            for d in range(count):\n                if fault>>d&1: sectors[find(d)].append(d)\n            selected=[]; recovered=0\n            for ds in sectors.values():\n                matching=[i for i,e in enumerate(edges) if e['ds']==tuple(ds)]\n                require((matching), f'Unrepresented independent primitive {fault}')\n                require((len({edges[i]['mask'] for i in matching})==1), \"chain_reference: len({edges[i]['mask'] for i in matching})==1\")\n                recovered ^= edges[matching[0]]['mask']\n                selected += matching\n            require((recovered==fault), f'Primitive logical label mismatch: {fault}')\n            mapped.update(selected)\n        loss_edges.append(mapped)\n    return circuit,probes,effects,edges,candidates,loss_edges,len(memo)\n\n\ndef costs(terms, bits):\n    # Exhaust all binary fault choices by min-plus dynamic programming, keeping\n    # the cheapest history for every detector+logical parity state (not MWPM/ILP).\n    indices=np.arange(1<<bits)\n    values=np.full(1<<bits,np.inf);values[0]=0.\n    for mask,weight in terms:\n        values=np.minimum(values,values[indices^mask]+weight)\n    return values\n\n\ndef allowed(values,syndrome,detectors):\n    pair=np.array([values[syndrome],values[syndrome|(1<<detectors)]])\n    best=pair.min()\n    if not np.isfinite(best): raise ValueError('Unreachable oracle syndrome')\n    return {int(i) for i,v in enumerate(pair) if abs(v-best)<1e-7}\n\n\ndef write_bundle(path,text,rows,circuit):\n    path.mkdir()\n    payload=np.packbits(rows,axis=1,bitorder='little').tobytes()\n    sha=lambda data: hashlib.sha256(data).hexdigest()\n    csha,rsha=sha(text.encode()),sha(payload)\n    bits=rows.shape[1];shots=len(rows);stride=(bits+7)//8\n    identity=f'format=rstim_decoder_dataset\\nschema_version=1\\nmode=measurements_blinded\\ncircuit_sha256={csha}\\nshots={shots}\\nrow_bits={bits}\\nshots_b8_sha256={rsha}\\n'\n    (path/'circuit.stim').write_text(text);(path/'shots.b8').write_bytes(payload)\n    save(path/'manifest.json',{'format':'rstim_decoder_dataset','schema_version':1,'dataset_id':sha(identity.encode()),\n         'mode':'measurements_blinded','shots':shots,'row':{'kind':'measurements','bits':bits,'encoding':'b8','bit_order':'lsb_first','bytes_per_shot':stride},\n         'circuit':{'file':'circuit.stim','sha256':csha,'measurements':bits,'detectors':circuit.num_detectors,'observables':1,'sweep_bits':0},\n         'shots_file':{'file':'shots.b8','sha256':rsha,'bits':bits,'bytes_per_shot':stride}})\n\n\ndef native_mask(e, count):\n    return sum(1<<d for d in e['detectors']) | sum(1<<(count+o) for o in e['observables'])\n\n\ndef coalesce(terms):\n    products=defaultdict(lambda:1.)\n    for mask,weight in terms: products[mask] *= 1-2/(1+math.exp(weight))\n    return {mask:(1-value)/2 for mask,value in products.items() if mask}\n\n\ndef validate_model(model, effects, candidates, count):\n    native=coalesce([(native_mask(e,count),e['weight']) for e in model['independent_effects']])\n    expected=coalesce(effects)\n    if native.keys()!=expected.keys() or any(abs(native[k]-expected[k])>1e-9 for k in expected):\n        raise ValueError('Independent Pauli distribution mismatch')\n    if any(e['weight']!=0 for es in model['loss_candidates'] for e in es):\n        raise ValueError('Independent loss candidate weight mismatch')\n    if [{native_mask(e,count) for e in es} for es in model['loss_candidates']]!=list(map(set,candidates)):\n        raise ValueError('Independent loss candidate mismatch')\n\n\nGRAPH_BACKENDS = ('pymatching-envelope', 'envelope-matching-offline')\nGRAPH_MUTATIONS = ('empty_edges', 'empty_loss_mapping', 'relative_weights')\n\n\ndef graph_predictions(graph, backend, exporter, work):\n    \"\"\"Execute the same public-graph adapters as the timing experiment.\"\"\"\n    if backend == 'pymatching-envelope':\n        from .run import python_decode\n        predictions, _ = python_decode(graph, True)\n        values = predictions.tolist()\n    elif backend == 'envelope-matching-offline':\n        path = work/'adapter-graph.json'\n        out = work/'adapter-predictions.b8'\n        save(path, graph)\n        subprocess.run([exporter.parent/'offline_matching_benchmark', path, out,\n                        work/'adapter-stats.json'], check=True, capture_output=True, timeout=120)\n        values = list(out.read_bytes())\n    else:\n        raise ValueError('Unknown graph adapter: '+backend)\n    require(len(values) == len(graph['syndromes']) and all(type(v) is int and v in (0,1) for v in values),\n            'Incomplete or invalid graph-adapter predictions')\n    return values\n\n\ndef corrupt_graph(graph, mutation):\n    defective = copy.deepcopy(graph)\n    if mutation == 'empty_edges':\n        defective['edges'] = []\n        defective['loss_edges'] = [[] for _ in graph['loss_edges']]\n        defective['mean_weight'] = 0.\n    elif mutation == 'empty_loss_mapping':\n        defective['loss_edges'] = [[] for _ in graph['loss_edges']]\n    elif mutation == 'relative_weights':\n        # Change all logically labelled edges by a fixed factor, not a searched\n        # single edge or a harmless uniform rescaling of the entire objective.\n        for edge in defective['edges']:\n            if edge['observables']:\n                edge['weight'] *= 1e-6\n        defective['mean_weight'] = sum(e['weight'] for e in defective['edges']) / len(defective['edges'])\n    else:\n        raise ValueError('Unknown graph mutation: '+mutation)\n    return defective\n\n\ndef prediction_record(predictions, choices):\n    require(len(predictions) == len(choices) and all(type(v) is int and v in (0,1) for v in predictions),\n            'Incomplete or invalid oracle predictions')\n    rejected = [i for i,(value,answers) in enumerate(zip(predictions,choices,strict=True)) if value not in answers]\n    singleton = [i for i,a in enumerate(choices) if len(a)==1]\n    require(bool(singleton), 'Oracle has no unique optimum witness')\n    mutated = predictions.copy(); mutated[singleton[0]] ^= 1\n    return {'predictions': predictions, 'checked_rows': len(choices), 'rejected_rows': rejected,\n            'unique_optimum_rows': len(singleton), 'predicted_ones': sum(predictions),\n            'constant_zero_rejected': any(0 not in a for a in choices),\n            'constant_one_rejected': any(1 not in a for a in choices),\n            'flipped_prediction_rejected': mutated[singleton[0]] not in choices[singleton[0]],\n            'placeholder_invariance': predictions[:len(choices)//2] == predictions[len(choices)//2:],\n            'prediction_sha256': hashlib.sha256(bytes(predictions)).hexdigest()}\n\n\ndef run(binary,exporter):\n    text=FIXTURE.read_text()\n    circuit,probes,effects,edges,candidates,loss_edges,probe_count=independent_model(text)\n    count=circuit.num_detectors; indices=np.arange(1<<(count+1))\n    # External physical samples: fixed private onset histories at early/middle/late\n    # opportunities. Enumerate every single Pauli fault on the lowered circuit.\n    ops=reference.parse(text)\n    nloss=sum(len(op.targets) for op in ops if op.name=='LOSS')\n    # A canonical, physically allowed noiseless reference witness avoids the\n    # architecture-dependent RNG streams of Stim compiled sampling. These are\n    # finite correctness witnesses, never IID accuracy observations.\n    rows=[]\n    for site in [None,0,nloss//2,nloss-1]:\n        history=np.zeros(nloss,dtype=bool)\n        if site is not None: history[site]=1\n        lowered=reference.lower(ops,history)\n        rows.append(lowered.without_noise().reference_sample())\n        for position,instruction in enumerate(lowered):\n            if instruction.name not in ['X_ERROR','Y_ERROR','Z_ERROR','DEPOLARIZE1','DEPOLARIZE2']: continue\n            targets=[t.value for t in instruction.targets_copy()]\n            if instruction.name=='DEPOLARIZE2':\n                faults=[[(a,q),(b,r)] for q,r in zip(targets[::2],targets[1::2]) for a in 'IXYZ' for b in 'IXYZ' if a+b!='II']\n            else:\n                paulis='XYZ' if instruction.name=='DEPOLARIZE1' else instruction.name[0]\n                faults=[[(pauli,q)] for q in targets for pauli in paulis]\n            for fault in faults:\n                injected=lowered[:position].without_noise()\n                for pauli,q in fault:\n                    if pauli!='I': injected.append(pauli,[q])\n                injected += lowered[position+1:].without_noise()\n                rows.append(injected.reference_sample())\n    fault_traces=len(rows)\n    rows=np.unique(np.array(rows,dtype=np.uint8),axis=0)\n    flags=[p['flag'] for p in probes]\n    # Include alternate placeholders, which must not affect decoder outputs.\n    alternate=rows.copy()\n    for flag in flags: alternate[alternate[:,flag]==1,flag+1]^=1\n    rows=np.concatenate([rows,alternate])\n    canonical=rows.copy()\n    for flag in flags: canonical[canonical[:,flag]==1,flag+1]=1\n    detections=circuit.compile_m2d_converter().convert(measurements=canonical.astype(bool),separate_observables=True)[0]\n    patterns=[tuple(np.flatnonzero(row[flags])) for row in rows]\n    syndromes=[sum(int(v)<<i for i,v in enumerate(row)) for row in detections]\n    mean=np.mean([e['weight'] for e in edges])\n    expected={'envelope-matching':[]}; cache={}\n    for pattern,syndrome in zip(patterns,syndromes):\n        if pattern not in cache:\n            active=set().union(*(loss_edges[i] for i in pattern))\n            matching=costs([(e['mask'],e['factor']*mean if i in active else e['weight']) for i,e in enumerate(edges)],count+1)\n            cache[pattern]=matching\n        expected['envelope-matching'].append(allowed(cache[pattern],syndrome,count))\n    with tempfile.TemporaryDirectory(prefix='midswap-oracle-') as tmp:\n        work=Path(tmp);write_bundle(work/'public',text,rows,circuit)\n        subprocess.run([exporter,work/'public',work/'graph.json'],check=True,capture_output=True)\n        graph=json.loads((work/'graph.json').read_text())\n        require((graph['syndromes']==detections.astype(int).tolist()), 'Independent m2d mismatch')\n        require((graph['losses']==[list(p) for p in patterns]), 'Independent visible-loss mapping mismatch')\n        # DEM decomposition is not unique; compare full correlated Pauli\n        # effects after coalescing equal parity masks, not a raw edge count.\n        oracle_export=exporter.parent/'export_decoder_oracle'\n        subprocess.run([oracle_export,work/'public',work/'models.json'],check=True,capture_output=True)\n        model=json.loads((work/'models.json').read_text())\n        validate_model(model,effects,candidates,count)\n        mutations={}\n        for name in ['pauli_weight','loss_candidate']:\n            defective=copy.deepcopy(model)\n            if name=='pauli_weight': defective['independent_effects'][0]['weight']+=.25\n            else:\n                envelope=next(es for es in defective['loss_candidates'] if len(es)>1)\n                envelope.pop()\n            try:\n                validate_model(defective,effects,candidates,count)\n                mutations[name]=False\n            except ValueError:\n                mutations[name]=True\n        # Most-likely FAULT CONFIGURATION depends on how equal physical effects\n        # are split into Bernoulli variables. Stim and Rust use different valid\n        # decompositions. First prove distribution equivalence above; only then\n        # exhaust the validated native representation with a non-ILP algorithm.\n        native_base=costs([(native_mask(e,count),e['weight']) for e in model['independent_effects']],count+1)\n        native_costs={}\n        expected['envelope-mle']=[]\n        for pattern,syndrome in zip(patterns,syndromes):\n            if pattern not in native_costs:\n                values=native_base.copy()\n                for i in pattern: values=np.minimum.reduce([values[indices^candidate] for candidate in candidates[i]])\n                native_costs[pattern]=values\n            expected['envelope-mle'].append(allowed(native_costs[pattern],syndrome,count))\n\n        results={}\n        for backend in expected:\n            out=work/(backend+'.b8')\n            subprocess.run([binary,'decode','--decoder',backend,'--dataset',work/'public','--out',out,\n                            '--stats-out',work/(backend+'.json')],check=True,capture_output=True,timeout=120)\n            predictions=list(out.read_bytes())\n            results[backend] = prediction_record(predictions, expected[backend])\n        for backend in GRAPH_BACKENDS:\n            predictions = graph_predictions(graph, backend, exporter, work)\n            results[backend] = prediction_record(predictions, expected['envelope-matching'])\n        graph_controls = {}\n        for mutation in GRAPH_MUTATIONS:\n            graph_controls[mutation] = {}\n            for backend in GRAPH_BACKENDS:\n                try:\n                    predictions = graph_predictions(corrupt_graph(graph, mutation), backend, exporter, work)\n                    rejected = [i for i,(v,a) in enumerate(zip(predictions,expected['envelope-matching'],strict=True)) if v not in a]\n                    control = {'outcome': 'oracle_rejected' if rejected else 'accepted',\n                               'predictions': predictions, 'rejected_rows': rejected}\n                except (ValueError, subprocess.CalledProcessError):\n                    # Empty topology may be rejected by the adapter itself. The\n                    # valid topology/weight mutants must produce wrong answers.\n                    control = {'outcome': 'decoder_error', 'predictions': None, 'rejected_rows': []}\n                graph_controls[mutation][backend] = control\n    controls_pass = all(c['outcome']=='oracle_rejected' or (m=='empty_edges' and c['outcome']=='decoder_error')\n                        for m,backends in graph_controls.items() for c in backends.values())\n    passed=controls_pass and all(mutations.values()) and all(not r['rejected_rows'] and r['flipped_prediction_rejected'] and r['placeholder_invariance'] and r['constant_zero_rejected'] and r['constant_one_rejected'] for r in results.values())\n    return {'status':'PASS' if passed else 'FAIL','fixture_sha256':digest(FIXTURE),'distance':3,'rounds':2,\n            'measurement_sha256':hashlib.sha256(rows.tobytes()).hexdigest(),'witness_generation':'stim-reference-sample',\n            'detectors':count,'rows':len(rows),'physical_fault_traces':fault_traces,'patterns':len(cache),'stim_pauli_probes':probe_count,\n            'independent_effects':len(effects),'independent_graph_edges':len(edges),\n            'independent_effects_candidates_and_m2d_pass':True,'compiler_output_mutations_rejected':mutations,'native_graph_edges':len(graph['edges']),'backends':results,\n            'allowed_answers': {name:[sorted(a) for a in choices] for name,choices in expected.items()},\n            'graph_adapter_controls': graph_controls,\n            'method':'Stim-derived DEM and Pauli fault propagation; exact min-plus enumeration of detector/logical states; external persistent-loss measurement records',\n            'mle_objective':'minimum-weight fault configuration in an independently distribution-validated native DEM representation; zero-cost loss-envelope choices',\n            'scope':'finite Mid-SWAP fixture and declared envelope model, including MLE; not proof of arbitrary compiler inputs or physical logical-class Bayes optimality'}\n\n\nif __name__=='__main__':\n    p=argparse.ArgumentParser();p.add_argument('--out',type=Path,default=Path('drafts/midswap-oracle.json'))\n    p.add_argument('--compare', type=Path, help='Revalidate published observations against the freshly recomputed oracle')\n    a=p.parse_args();r=run(ROOT/'target/release/rustqec',ROOT/'target/release/examples/export_matching_benchmark');save(a.out,r)\n    if a.compare is not None:\n        from .chain_contract import compare_reports\n        compare_reports(r, json.loads(a.compare.read_text()))\n    print(r['status'])\n    raise SystemExit(r['status']!='PASS')\n",
    "benchmarks/atom_loss/channel_probes.py": "\"\"\"Analytic distribution probes for the specified stochastic Pauli channels.\n\nBell readout maps I,Z,X,Y on each data wire to 00,10,01,11 measurement\nbits (little endian). It resolves all Pauli components, unlike one parity.\nThis finite statistical check is not tomography of arbitrary quantum channels.\n\"\"\"\nimport itertools\nimport math\nfrom pathlib import Path\nimport re\nimport tempfile\nimport numpy as np\nfrom . import reference\n\nALPHA = 1e-7\n\n\nfrom .probe_specs import bell_text, basis_ops, distribution_specs as specifications\n\n\ndef observed_probabilities(rows, columns):\n    selected = rows[:, columns].astype(np.uint64)\n    ids = (selected * (1 << np.arange(len(columns), dtype=np.uint64))).sum(axis=1).astype(int)\n    joint = np.bincount(ids, minlength=1 << len(columns)) / len(rows)\n    return joint, selected.mean(axis=0)\n\n\ndef evaluate(binary, sampler, shots=32768):\n    probes = specifications()\n    events = sum(len(p['expected']) + len(p['columns']) for p in probes)\n    tolerance = math.sqrt(math.log(4*events/ALPHA)/(2*shots))\n    records = []\n    with tempfile.TemporaryDirectory(prefix='pauli-channel-') as tmp:\n        for probe in probes:\n            expected = np.array(probe['expected'])\n            expected_marginal = np.array([sum(prob for i,prob in enumerate(expected) if i & (1 << bit))\n                                          for bit in range(len(probe['columns']))])\n            observations = {}\n            passed = True\n            for name, rows in [('rust', sampler(binary, probe['text'], shots, 991, Path(tmp))),\n                               ('reference', reference.sample(probe['text'], shots, 773))]:\n                joint, marginal = observed_probabilities(rows, probe['columns'])\n                for actual, target in [(joint,expected),(marginal,expected_marginal)]:\n                    passed &= bool(np.all(np.abs(actual-target) <= tolerance))\n                    passed &= bool(np.all(actual[target == 0] == 0) and np.all(actual[target == 1] == 1))\n                observations[name] = {'joint':joint.tolist(), 'marginals':marginal.tolist()}\n            records.append({'case':probe['name'], 'channel':probe['channel'],\n                            'expected_joint':expected.tolist(), 'expected_marginals':expected_marginal.tolist(),\n                            **observations, 'shots_per_sampler':shots, 'tolerance':tolerance,\n                            'status':'PASS' if passed else 'FAIL'})\n    return records\n\n\nMUTATIONS = ('DEPOLARIZE2_ix_only', 'DEPOLARIZE2_xi_only',\n             'DEPOLARIZE2_independent_x', 'DEPOLARIZE1_x_only', 'DEPOLARIZE1_z_only')\n\n\ndef replace_channel(text, mutation):\n    \"\"\"Actual input mutation, preserving forced-loss skipping in these probes.\"\"\"\n    if mutation not in MUTATIONS:\n        raise ValueError(f'Unknown channel mutation: {mutation}')\n    lost, output = set(), []\n    channel = mutation.split('_', 1)[0]\n    for line in text.splitlines():\n        loss = re.fullmatch(r'LOSS\\(1\\) (.*)', line)\n        if loss: lost.update(map(int, loss[1].split()))\n        if line.startswith('R '): lost.difference_update(map(int, line[2:].split()))\n        noise = re.fullmatch(channel + r'\\(([^)]+)\\) (.*)', line)\n        if not noise:\n            output.append(line)\n            continue\n        p = float(noise[1]); targets = list(map(int, noise[2].split()))\n        if channel == 'DEPOLARIZE2':\n            for first, second in zip(targets[::2], targets[1::2]):\n                if first in lost or second in lost: continue\n                chosen = [second] if mutation.endswith('ix_only') else (\n                    [first] if mutation.endswith('xi_only') else [first, second])\n                output.extend(f'X_ERROR({8*p/15}) {q}' for q in chosen)\n        else:\n            axis = 'Z' if mutation.endswith('z_only') else 'X'\n            output.extend(f'{axis}_ERROR({2*p/3}) {q}' for q in targets if q not in lost)\n    return '\\n'.join(output)\n\n\ndef run(binary, sampler, shots=32768):\n    records = evaluate(binary, sampler, shots)\n    mutations = {}\n    for name in MUTATIONS:\n        def defective(binary, text, shots, seed, work):\n            return sampler(binary, replace_channel(text, name), shots, seed, work)\n        observations = evaluate(binary, defective, shots)\n        failed = [r['case'] for r in observations if r['status'] == 'FAIL']\n        mutations[name] = {'rejected':bool(failed), 'failed_cases':failed,\n                           'observations':observations}\n    return {'status':'PASS' if all(r['status']=='PASS' for r in records) and all(m['rejected'] for m in mutations.values()) else 'FAIL',\n            'method':'Bell Pauli-component readout; X/Y/Z product-basis joints and marginals; both loss directions',\n            'familywise_alpha_bound':ALPHA, 'cases':records, 'channel_replacement_mutations':mutations}\n",
    "benchmarks/atom_loss/correctness.py": "\"\"\"Distribution and known-answer controls for independent persistent-loss sampling.\"\"\"\nimport argparse\nimport itertools\nimport json\nimport math\nfrom pathlib import Path\nimport subprocess\nimport tempfile\nimport numpy as np\nfrom . import reference, noise_controls, low_probability\n\nfrom .probe_specs import CASES, KNOWN\n\n\ndef rust_rows(binary, text, shots, seed, work):\n    circuit = work / 'input.stim'\n    output = work / 'shots.01'\n    circuit.write_text(text + '\\n')\n    subprocess.run([str(binary), 'circuit', 'sample', '--in', str(circuit), '--shots', str(shots),\n                    '--seed', str(seed), '--out', str(output), '--out-format', '01'],\n                   check=True, capture_output=True, timeout=120)\n    rows = output.read_text().splitlines()\n    return np.array([[int(x) for x in row] for row in rows], dtype=np.bool_)\n\n\ndef histogram(rows):\n    values = (rows.astype(np.uint64) * (1 << np.arange(rows.shape[1], dtype=np.uint64))).sum(axis=1).astype(int)\n    return np.bincount(values, minlength=2**rows.shape[1]) / len(rows)\n\n\ndef run(binary, shots=32768):\n    records = []\n    # Union bound for every bin in every two-sample small-circuit comparison.\n    bins = 64 * len(CASES)\n    tolerance = 2 * math.sqrt(math.log(4 * bins / 5e-7) / (2 * shots))\n    with tempfile.TemporaryDirectory(prefix='loss-correctness-') as tmp:\n        for name, text in CASES.items():\n            observed = rust_rows(binary, text, shots, 173, Path(tmp))\n            independent = reference.sample(text, shots, 827)\n            delta = float(np.max(np.abs(histogram(observed) - histogram(independent))))\n            known_ok = name not in KNOWN or (np.all(observed == KNOWN[name]) and np.all(independent == KNOWN[name]))\n            records.append({'histogram_counts':{key:np.rint(histogram(rows)*shots).astype(int).tolist() for key,rows in [('rust',observed),('reference',independent)]}, 'case': name, 'shots_per_sampler': shots, 'max_bin_difference': delta,\n                            'tolerance': tolerance, 'known_answer_pass': bool(known_ok),\n                            'status': 'PASS' if delta <= tolerance and known_ok else 'FAIL'})\n        text = CASES['lost_control_skips_cx']\n        bad = reference.sample(text, 32, skip_lost_gates=False)\n        negative = not np.all(bad == KNOWN['lost_control_skips_cx'])\n        # Unsupported operations must fail explicitly, rather than silently disappear.\n        try:\n            reference.sample('R 0\\nT 0\\nM 0', 4)\n            rejected = False\n        except ValueError:\n            rejected = True\n    analytic = noise_controls.run(binary, rust_rows, shots)\n    low = low_probability.run(binary, rust_rows, shots)\n    return {'low_probability_controls': low, 'status': 'PASS' if all(r['status'] == 'PASS' for r in records) and negative and rejected and analytic['status']=='PASS' and low['status']=='PASS' else 'FAIL',\n            'analytic_noise_controls': analytic,\n            'method': 'independent Stim circuit lowering; joint output distributions and hand-computed controls',\n            'familywise_alpha_bound': 1.2e-6, 'negative_skipped_gate_mutation_rejected': bool(negative),\n            'unsupported_reference_operation_rejected': rejected, 'cases': records}\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--binary', type=Path, required=True)\n    parser.add_argument('--shots', type=int, default=32768)\n    parser.add_argument('--out', type=Path, required=True)\n    args = parser.parse_args()\n    result = run(args.binary.resolve(), args.shots)\n    args.out.parent.mkdir(parents=True, exist_ok=True)\n    args.out.write_text(json.dumps(result, indent=2) + '\\n')\n    print(result['status'])\n    raise SystemExit(0 if result['status'] == 'PASS' else 1)\n",
    "benchmarks/atom_loss/decoder_contract.py": "\"\"\"Independently validate retained three/five-wire decoder observations.\n\nOnly the standard library is used. Adjacent repetition parity checks have two\ncomplementary corrections, so their costs can be derived without the producer's\nexhaustive enumeration, graph exporter, or a matching backend.\n\"\"\"\nimport math\n\nRAW_BACKENDS = ('native', 'pymatching', 'ignored_conditioning', 'flipped_native')\nCASE_FIELDS = {\n    'wires', 'rows_checked', 'status', 'hand_derived_graph_pass', 'loss_mapping_pass',\n    'placeholder_invariance_pass', 'rejected_rows', 'ignored_conditioning_rejected_rows',\n    'flipped_prediction_rejected_rows', 'strict_witness', 'graph', 'raw_predictions',\n}\nGRAPH_FIELDS = {'edges', 'loss_edges', 'mean_weight', 'syndromes', 'losses'}\n\n\ndef require(condition, message):\n    if not condition:\n        raise ValueError('Decoder report contract: '+message)\n\n\ndef mapping(value, fields, label):\n    require(type(value) is dict and set(value) == set(fields),\n            label+' fields are incomplete or unexpected')\n\n\ndef integer_list(values, expected, label):\n    require(type(values) is list and all(type(v) is int for v in values)\n            and values == expected, label+' differs from independent calculation')\n\n\ndef numeric(value, expected, label):\n    require(type(value) in (int, float) and math.isfinite(value)\n            and math.isclose(value, expected, rel_tol=1e-12, abs_tol=1e-12),\n            label+' differs from independent calculation')\n\n\ndef row_objective(raw, wires, conditioned):\n    \"\"\"Return visible flags, canonical syndrome, and costs in logical [0,1] order.\"\"\"\n    flags = [(raw >> (2*q)) & 1 for q in range(wires)]\n    values = [1 if flags[q] else (raw >> (2*q+1)) & 1 for q in range(wires)]\n    syndrome = [a ^ b for a, b in zip(values, values[1:])]\n    # Given adjacent differences, choosing the first correction bit determines\n    # every other bit. Twice-costs stay integral, including exact optimum ties.\n    costs = [sum((1 if conditioned and flags[q] else 2)\n                 * (values[q] ^ values[0] ^ logical) for q in range(wires))/2\n             for logical in (0, 1)]\n    return flags, syndrome, costs\n\n\ndef allowed(costs):\n    best = min(costs)\n    return [logical for logical, cost in enumerate(costs) if cost == best]\n\n\ndef verify_graph(graph, wires):\n    mapping(graph, GRAPH_FIELDS, 'graph')\n    edges = graph['edges']\n    require(type(edges) is list and len(edges) == wires, 'incorrect graph edge count')\n    # Wire q flips detector q-1 and q, except for the two boundary wires.\n    expected = [(0, None, (0,))] + [(q-1, q, ()) for q in range(1, wires-1)] + [(wires-2, None, ())]\n    observed = []\n    for edge in edges:\n        mapping(edge, ('u', 'v', 'observables', 'weight', 'loss_factor'), 'edge')\n        require(type(edge['u']) is int and 0 <= edge['u'] < wires-1, 'invalid edge u')\n        require(edge['v'] is None or (type(edge['v']) is int and 0 <= edge['v'] < wires-1), 'invalid edge v')\n        obs = edge['observables']\n        require(type(obs) is list and all(type(v) is int for v in obs) and obs in ([], [0]), 'invalid edge observables')\n        numeric(edge['weight'], math.log(9), 'edge weight')\n        numeric(edge['loss_factor'], .5, 'edge loss factor')\n        u, v = edge['u'], edge['v']\n        observed.append((u, v, tuple(obs)) if v is None else (min(u, v), max(u, v), tuple(obs)))\n    require(set(observed) == set(expected), 'incorrect graph topology or logical labels')\n    numeric(graph['mean_weight'], math.log(9), 'graph mean weight')\n    numeric(graph['mean_weight'], math.fsum(e['weight'] for e in edges)/wires, 'mean of edge weights')\n    mapping_rows = graph['loss_edges']\n    require(type(mapping_rows) is list and len(mapping_rows) == wires, 'incomplete loss mapping')\n    for q, indices in enumerate(mapping_rows):\n        integer_list(indices, [observed.index(expected[q])], 'loss mapping for wire '+str(q))\n    count = 1 << (2*wires)\n    require(type(graph['syndromes']) is list and len(graph['syndromes']) == count, 'incomplete syndrome rows')\n    require(type(graph['losses']) is list and len(graph['losses']) == count, 'incomplete loss rows')\n    for raw in range(count):\n        flags, syndrome, _ = row_objective(raw, wires, True)\n        integer_list(graph['syndromes'][raw], syndrome, 'syndrome row '+str(raw))\n        integer_list(graph['losses'][raw], [q for q, flag in enumerate(flags) if flag], 'loss row '+str(raw))\n\n\ndef verify_case(case, wires):\n    mapping(case, CASE_FIELDS, 'case')\n    count = 1 << (2*wires)\n    require(type(case['wires']) is int and case['wires'] == wires, 'incorrect wire count or order')\n    require(type(case['rows_checked']) is int and case['rows_checked'] == count, 'incorrect row count')\n    require(case['status'] == 'PASS', 'case did not pass')\n    for field in ('hand_derived_graph_pass', 'loss_mapping_pass', 'placeholder_invariance_pass'):\n        require(case[field] is True, 'case failed '+field)\n    verify_graph(case['graph'], wires)\n    predictions = case['raw_predictions']\n    mapping(predictions, RAW_BACKENDS, 'raw predictions')\n    for name, values in predictions.items():\n        require(type(values) is list and len(values) == count\n                and all(type(v) is int and v in (0, 1) for v in values),\n                name+' requires complete integer binary predictions')\n    conditioned = [allowed(row_objective(raw, wires, True)[2]) for raw in range(count)]\n    fixed = [allowed(row_objective(raw, wires, False)[2]) for raw in range(count)]\n    rejected = {name: [raw for raw, prediction in enumerate(values) if prediction not in conditioned[raw]]\n                for name, values in predictions.items()}\n    mapping(case['rejected_rows'], ('native', 'pymatching'), 'rejected rows')\n    for name in ('native', 'pymatching'):\n        integer_list(case['rejected_rows'][name], rejected[name], name+' rejected rows')\n        require(not rejected[name], name+' predictions fail the independent objective')\n    require(all(value in fixed[raw] for raw, value in enumerate(predictions['ignored_conditioning'])),\n            'ignore-conditioning control does not solve the fixed objective')\n    flipped = predictions['native'].copy()\n    flipped[0] ^= 1\n    require(predictions['flipped_native'] == flipped, 'flipped control must change only native row zero')\n    integer_list(case['flipped_prediction_rejected_rows'], rejected['flipped_native'], 'flipped rejected rows')\n    require(0 in rejected['flipped_native'], 'flipped prediction was not rejected')\n    integer_list(case['ignored_conditioning_rejected_rows'], rejected['ignored_conditioning'], 'ignore-conditioning rejected rows')\n    for raw in range(count):\n        flags = row_objective(raw, wires, True)[0]\n        canonical = raw | sum(1 << (2*q+1) for q, flag in enumerate(flags) if flag)\n        require(all(predictions[name][raw] == predictions[name][canonical] for name in ('native', 'pymatching')),\n                'placeholder invariance fails')\n    witness = case['strict_witness']\n    if wires == 3:\n        require(witness is None, 'three-wire strict witness must be absent')\n        return\n    mapping(witness, ('packed_row', 'logical_order', 'fixed_optimum', 'conditioned_optimum',\n                     'fixed_decoder_prediction', 'native_prediction', 'pymatching_prediction',\n                     'fixed_costs', 'conditioned_costs'), 'strict witness')\n    require(type(witness['packed_row']) is int and witness['packed_row'] == 21, 'incorrect strict witness row')\n    integer_list(witness['logical_order'], [0, 1], 'witness logical order')\n    for name, objective, conditioning in [('fixed', fixed, False), ('conditioned', conditioned, True)]:\n        integer_list(witness[name+'_optimum'], objective[21], name+' witness optimum')\n        costs = witness[name+'_costs']\n        require(type(costs) is list and len(costs) == 2, 'incomplete witness costs')\n        for value, expected in zip(costs, row_objective(21, wires, conditioning)[2]):\n            numeric(value, expected, name+' witness cost')\n    for field, backend in [('fixed_decoder_prediction', 'ignored_conditioning'),\n                           ('native_prediction', 'native'), ('pymatching_prediction', 'pymatching')]:\n        require(type(witness[field]) is int and witness[field] == predictions[backend][21],\n                field+' differs from raw witness prediction')\n    require(fixed[21] == [0] and conditioned[21] == [1] and 21 in rejected['ignored_conditioning'],\n            'strict conditioning witness did not reject fixed weights')\n\n\ndef verify_decoder(report):\n    \"\"\"Require complete, successful observations consistent with the fixed oracle.\"\"\"\n    mapping(report, ('status', 'method', 'scope', 'cases'), 'report')\n    require(report['status'] == 'PASS', 'report did not pass')\n    for key in ('method', 'scope'):\n        require(type(report[key]) is str and bool(report[key].strip()), 'missing '+key)\n    require(type(report['cases']) is list and len(report['cases']) == 2, 'requires both wire cases')\n    for case, wires in zip(report['cases'], (3, 5)):\n        verify_case(case, wires)\n\n\ndef compare_reports(fresh, published):\n    \"\"\"Revalidate both reports against the same fixed oracle, allowing legal ties.\n\n    Graph permutations (with consistent loss mappings), tiny weight roundoff,\n    and alternative equally optimal predictions do not change this experiment.\n    \"\"\"\n    verify_decoder(fresh)\n    verify_decoder(published)\n    require(all(fresh[key] == published[key] for key in ('method', 'scope')),\n            'Fresh decoder oracle definitions differ from published evidence')\n",
    "benchmarks/atom_loss/decoder_reference.py": "\"\"\"Independent repetition-graph objectives, including a strict conditioning witness.\"\"\"\nfrom .shot_data import require\nimport argparse\nimport hashlib\nimport itertools\nimport json\nimport math\nfrom pathlib import Path\nimport subprocess\nimport tempfile\nimport numpy as np\nfrom .run import build_matching, save\n\n\ndef circuit_for(wires):\n    lines=[f'QUBIT_COORDS({q},0) {q}' for q in range(wires)]\n    targets=' '.join(map(str,range(wires)))\n    lines += [f'R {targets}',f'X_ERROR(0.1) {targets}',f'LOSS(0.2) {targets}',f'ML {targets}']\n    for q in range(wires-1):\n        lines.append(f'DETECTOR({q},0,0) rec[{2*q+1-2*wires}] rec[{2*q+3-2*wires}]')\n    lines.append(f'OBSERVABLE_INCLUDE(0) rec[{1-2*wires}]')\n    return '\\n'.join(lines)+'\\n'\n\n\ndef sha(data):\n    return hashlib.sha256(data).hexdigest()\n\n\ndef bundle(path, wires):\n    path.mkdir()\n    bits=2*wires; count=1<<bits; stride=(bits+7)//8\n    text=circuit_for(wires)\n    payload=b''.join(row.to_bytes(stride,'little') for row in range(count))\n    circuit_sha, shots_sha=sha(text.encode()),sha(payload)\n    identity=f'format=rstim_decoder_dataset\\nschema_version=1\\nmode=measurements_blinded\\ncircuit_sha256={circuit_sha}\\nshots={count}\\nrow_bits={bits}\\nshots_b8_sha256={shots_sha}\\n'\n    manifest={'format':'rstim_decoder_dataset','schema_version':1,'dataset_id':sha(identity.encode()),\n              'mode':'measurements_blinded','shots':count,\n              'row':{'kind':'measurements','bits':bits,'encoding':'b8','bit_order':'lsb_first','bytes_per_shot':stride},\n              'circuit':{'file':'circuit.stim','sha256':circuit_sha,'measurements':bits,'detectors':wires-1,'observables':1,'sweep_bits':0},\n              'shots_file':{'file':'shots.b8','sha256':shots_sha,'bits':bits,'bytes_per_shot':stride}}\n    (path/'circuit.stim').write_text(text); (path/'shots.b8').write_bytes(payload)\n    save(path/'manifest.json',manifest)\n\n\ndef oracle_costs(raw, conditioned=True, wires=3):\n    flags=[(raw>>(2*q))&1 for q in range(wires)]\n    values=[1 if flags[q] else (raw>>(2*q+1))&1 for q in range(wires)]\n    syndrome=[a^b for a,b in zip(values,values[1:])]\n    weights=[.5 if flag and conditioned else 1. for flag in flags]\n    candidates=[]\n    for correction in itertools.product([0,1],repeat=wires):\n        if [a^b for a,b in zip(correction,correction[1:])]==syndrome:\n            candidates.append((sum(w*x for w,x in zip(weights,correction)),correction[0]))\n    return [min(cost for cost,logical in candidates if logical==i) for i in (0,1)],syndrome,flags\n\n\ndef oracle(raw, conditioned=True, wires=3):\n    costs,syndrome,flags=oracle_costs(raw,conditioned,wires)\n    minimum=min(costs)\n    return {logical for logical,cost in enumerate(costs) if abs(cost-minimum)<1e-9},syndrome,flags\n\n\ndef rejected_rows(predictions, allowed):\n    \"\"\"The same acceptance rule is used for healthy and deliberately broken outputs.\"\"\"\n    if len(predictions)!=len(allowed): raise ValueError('Incomplete oracle predictions')\n    return [i for i,(p,a) in enumerate(zip(predictions,allowed)) if p not in a]\n\n\ndef check_case(binary, exporter, work, wires):\n    bundle(work/'public',wires)\n    subprocess.run([exporter,work/'public',work/'graph.json'],check=True,capture_output=True)\n    graph=json.loads((work/'graph.json').read_text())\n    expected={(0,None,(0,)),(wires-2,None,())}\n    expected.update((q,q+1,()) for q in range(wires-2))\n    actual={(e['u'],e['v'],tuple(e['observables'])) for e in graph['edges']}\n    require((actual==expected and len(graph['edges'])==wires), 'Hand-derived graph mismatch')\n    require((all(abs(e['weight']-math.log(9))<1e-9 and e['loss_factor']==.5 for e in graph['edges'])), \"decoder_reference: all(abs(e['weight']-math.log(9))<1e-9 and e['loss_factor']==.5 for e in graph['edges'])\")\n    require((len(graph['loss_edges'])==wires and all(len(es)==1 for es in graph['loss_edges'])), \"decoder_reference: len(graph['loss_edges'])==wires and all(len(es)==1 for es in graph['loss_edges'])\")\n    subprocess.run([binary,'decode','--decoder','envelope-matching','--dataset',work/'public',\n                    '--out',work/'predictions.b8','--stats-out',work/'stats.json'],check=True,capture_output=True)\n    native=list((work/'predictions.b8').read_bytes()); python=[]; broken=[]; allowed=[]; canonical=[]\n    for raw in range(1<<(2*wires)):\n        acceptable,syndrome,flags=oracle(raw,wires=wires)\n        allowed.append(acceptable)\n        require((graph['syndromes'][raw]==syndrome), \"decoder_reference: graph['syndromes'][raw]==syndrome\")\n        mapped={i for loss in graph['losses'][raw] for i in graph['loss_edges'][loss]}\n        expected_edges={i for i,e in enumerate(graph['edges']) if\n                        (e['v'] is None and e['u']==0 and flags[0]) or\n                        (e['v'] is not None and flags[e['u']+1]) or\n                        (e['v'] is None and e['u']==wires-2 and flags[-1])}\n        require((mapped==expected_edges), 'decoder_reference: mapped==expected_edges')\n        values=np.array(syndrome,dtype=np.uint8)\n        python.append(int(build_matching(graph,graph['losses'][raw]).decode(values)[0]))\n        # Execute a real defective decoder, not merely compare two oracle sets.\n        broken.append(int(build_matching(graph,[]).decode(values)[0]))\n        canonical.append(raw | sum(1<<(2*q+1) for q in range(wires) if flags[q]))\n    failures={'native':rejected_rows(native,allowed),'pymatching':rejected_rows(python,allowed)}\n    mutated=native.copy();mutated[0]^=1\n    flipped=rejected_rows(mutated,allowed)\n    ignored=rejected_rows(broken,allowed)\n    placeholder_ok=all(native[i]==native[c] and python[i]==python[c] for i,c in enumerate(canonical))\n    witness=21 if wires==5 else None  # Lost first three wires; raw values all zero.\n    if witness is not None:\n        require((oracle(witness,False,wires)[0]=={0} and oracle(witness,True,wires)[0]=={1}), 'decoder_reference: oracle(witness,False,wires)[0]=={0} and oracle(witness,True,wires)[0]=={1}')\n        require((witness in ignored), 'Ignore-conditioning decoder escaped strict witness')\n    passed=not any(failures.values()) and placeholder_ok and 0 in flipped and (wires!=5 or bool(ignored))\n    return {'wires':wires,'rows_checked':len(allowed),'status':'PASS' if passed else 'FAIL',\n            'hand_derived_graph_pass':True,'loss_mapping_pass':True,'placeholder_invariance_pass':placeholder_ok,\n            'graph':{key:graph[key] for key in ['edges','loss_edges','mean_weight','syndromes','losses']},\n            'raw_predictions':{'native':native,'pymatching':python,'ignored_conditioning':broken,'flipped_native':mutated},\n            'rejected_rows':failures,'ignored_conditioning_rejected_rows':ignored,\n            'flipped_prediction_rejected_rows':flipped,\n            'strict_witness':None if witness is None else {'packed_row':witness,'fixed_optimum':[0],\n                 'conditioned_optimum':[1],'fixed_decoder_prediction':broken[witness],\n                 'native_prediction':native[witness],'pymatching_prediction':python[witness],\n                 'logical_order':[0,1], 'fixed_costs':oracle_costs(witness,False,wires)[0],\n                 'conditioned_costs':oracle_costs(witness,True,wires)[0]}}\n\n\ndef run(binary, exporter):\n    cases=[]\n    with tempfile.TemporaryDirectory(prefix='loss-decoder-reference-') as tmp:\n        for wires in [3,5]:\n            work=Path(tmp)/str(wires);work.mkdir()\n            cases.append(check_case(binary,exporter,work,wires))\n    return {'status':'PASS' if all(c['status']=='PASS' for c in cases) else 'FAIL',\n            'method':'hand-derived three/five-wire graphs; exhaustive correction enumeration; identical acceptance for healthy and mutated decoder outputs',\n            'scope':'matching objective and public-row/loss transformation; not an independent general envelope compiler or physical Bayes-optimal decoder',\n            'cases':cases}\n\n\nif __name__=='__main__':\n    p=argparse.ArgumentParser()\n    p.add_argument('--binary',type=Path,default=Path('target/release/rustqec'))\n    p.add_argument('--exporter',type=Path,default=Path('target/release/examples/export_matching_benchmark'))\n    p.add_argument('--out',type=Path,default=Path('site/static/data/atom-loss/decoder-correctness.json'))\n    p.add_argument('--compare',type=Path,help='Validate published observations against the same hand-derived oracle')\n    a=p.parse_args();result=run(a.binary.resolve(),a.exporter.resolve());save(a.out,result)\n    if a.compare is not None:\n        from .decoder_contract import compare_reports\n        compare_reports(result,json.loads(a.compare.read_text()))\n    print(result['status']);raise SystemExit(result['status']!='PASS')\n",
    "benchmarks/atom_loss/decoder_replay.py": "\"\"\"Re-decode every archived corpus using current code; never replay old timings.\"\"\"\nimport argparse\nimport hashlib\nimport json\nfrom pathlib import Path\nimport tempfile\nimport zipfile\nimport numpy as np\nfrom .run import ROOT, checked, export_graph, native_decode, python_decode, python_decode_loop, score\nfrom .shot_data import cases_from, validate_dataset, rescore, rescore_seeds\n\n\n\ndef without_timings(record):\n    return {key:value for key,value in record.items() if not key.endswith('_seconds')}\n\n\ndef verify_work_observations(case, observations, graph_metadata, label):\n    \"\"\"Compare reproducible work counters, never replay historical durations.\"\"\"\n    def same(actual,expected,context):\n        # Preserve JSON scalar types: bool/float cannot substitute for integer counters.\n        if json.dumps(actual,sort_keys=True) != json.dumps(expected,sort_keys=True):\n            raise ValueError('Current workload metadata differs from archive: '+context)\n    same(graph_metadata,without_timings(case['graph']),label+'/graph')\n    for name,current in observations.items():\n        for rep,run in enumerate(case['decoders'][name]['runs']):\n            if name=='envelope-matching-offline':\n                historical=without_timings(run['batch'])\n            elif name.startswith('pymatching'):\n                historical=without_timings(run)\n                historical.pop('export_repetition',None)\n            else:\n                historical=without_timings(run['stats'])\n            same(current,historical,f'{label}/{name}/run{rep}')\n\n\ndef decode_current(work, binary, exporter, names):\n    \"\"\"Only public files exist in work; private keys are loaded after decoding.\"\"\"\n    graph = export_graph(exporter, work, 'replay')\n    predictions = {}; observations = {}\n    for name in names:\n        if name in {'envelope-matching', 'envelope-mle'}:\n            pred, record = native_decode(binary, work, name, 'replay')\n            if record['status'] != 'ok':\n                raise ValueError('Current decoder failed: '+name+' '+str(record))\n            observations[name] = without_timings(record['stats'])\n        elif name == 'envelope-matching-offline':\n            path = work/(name+'.b8')\n            checked([exporter.parent/'offline_matching_benchmark', work/'graph-replay.json', path, work/'offline-stats.json'])\n            pred = np.frombuffer(path.read_bytes(), dtype=np.uint8)\n            observations[name] = without_timings(json.loads((work/'offline-stats.json').read_text()))\n        elif name == 'pymatching-fixed-loop':\n            pred, stats = python_decode_loop(graph, False)\n            observations[name] = without_timings(stats)\n        elif name in {'pymatching-fixed', 'pymatching-envelope'}:\n            pred, stats = python_decode(graph, name == 'pymatching-envelope')\n            observations[name] = without_timings(stats)\n        else:\n            raise ValueError('Unknown comparator: '+name)\n        predictions[name] = pred\n    graph_metadata = {key:graph[key] for key in ['source','num_observables']}\n    manifest = json.loads((work/'public/manifest.json').read_text())\n    graph_metadata.update(edges=len(graph['edges']), detectors=manifest['circuit']['detectors'],\n                          loss_patterns=len(set(map(tuple,graph['losses']))))\n    return predictions, observations, graph_metadata\n\n\ndef replay_case(z, label, case, work, binary, exporter, seeded):\n    public = work/'public'\n    public.mkdir(parents=True)\n    for name in ['manifest.json', 'circuit.stim', 'shots.b8']:\n        (public/name).write_bytes(z.read(f'{label}/public/{name}'))\n    predictions, observations, graph_metadata = decode_current(work, binary, exporter, case['decoders'])\n    if not seeded:\n        verify_work_observations(case, observations, graph_metadata, label)\n    # Scoring keys and historical predictions have not been given to a decoder.\n    answers = np.frombuffer(validate_dataset(lambda n: z.read(f'{label}/{n}'), case), dtype=np.uint8)\n    native = predictions['envelope-matching']\n    for name, pred in predictions.items():\n        result = score(pred, answers)\n        expected = case['decoders'][name]\n        for field in ['prediction_sha256', 'errors', 'shots', 'logical_error_rate', 'wilson_95']:\n            if result[field] != expected[field]:\n                raise ValueError(f'Current decoder differs from archive: {label}/{name}/{field}')\n        members = [name+'.b8'] if seeded else [f'{name}-{rep}.b8' for rep in range(3)]\n        for member in members:\n            if pred.tobytes() != z.read(label+'/'+member):\n                raise ValueError(f'Current prediction bytes differ: {label}/{member}')\n        if name != 'envelope-matching':\n            paired = {'native_only_wrong': int(np.count_nonzero((native != answers) & (pred == answers))),\n                      'other_only_wrong': int(np.count_nonzero((native == answers) & (pred != answers)))}\n            if seeded:\n                historical = case['paired'].get(name)\n            elif 'paired_native_only_wrong' in expected:\n                historical = {'native_only_wrong': expected['paired_native_only_wrong'],\n                              'other_only_wrong': expected['paired_python_only_wrong']}\n            else:\n                historical = None  # Some native comparators have no archived paired field.\n            if historical is not None and historical != paired:\n                raise ValueError(f'Current paired errors differ: {label}/{name}')\n    return len(predictions)\n\n\ndef replay(archive, binary, exporter):\n    seeded = archive.name == 'accuracy-seeds.zip'\n    # Enforce the complete case/backend inventory before running anything.\n    (rescore_seeds if seeded else rescore)(archive)\n    counts = []\n    with zipfile.ZipFile(archive) as z, tempfile.TemporaryDirectory() as tmp:\n        cases = ([(f\"{c['setting']}-s{c['seed']}\", c) for c in json.loads(z.read('accuracy-seeds.json'))['cases']]\n                 if seeded else cases_from(z.read))\n        for label, case in cases:\n            count = replay_case(z, label, case, Path(tmp)/label, binary, exporter, seeded)\n            counts.append(count)\n            print(f'{label}: {count} current decoders match all archived repetitions and scores', flush=True)\n    return {'corpora': len(counts), 'decoder_cases': sum(counts)}\n\n\nif __name__ == '__main__':\n    p = argparse.ArgumentParser()\n    p.add_argument('--root', type=Path, default=ROOT/'site/static/data/atom-loss')\n    p.add_argument('--binary', type=Path, default=ROOT/'target/release/rustqec')\n    p.add_argument('--exporter', type=Path, default=ROOT/'target/release/examples/export_matching_benchmark')\n    a = p.parse_args()\n    from .verify import verify\n    verify(a.root)\n    for name in ['shot-data-v1.zip', 'accuracy-seeds.zip']:\n        print('PASS', name, replay(a.root/name, a.binary, a.exporter), flush=True)\n",
    "benchmarks/atom_loss/evidence_run.py": "\"\"\"Build and regenerate the entire publication from a clean source commit.\n\nRun in a fresh detached worktree. Output/work directories must be outside it.\nA later artifact commit may change site outputs, but must retain identical\nsource/build inputs. This avoids an impossible artifact-to-own-commit hash cycle.\n\"\"\"\nimport argparse\nimport json\nimport os\nfrom pathlib import Path\nimport subprocess\nimport sys\nfrom .source_contract import ROOT, BUILD_COMMANDS, BINARIES, clean_source, capture, verify_bundle_source, build_environment, NETWORK_ENV_KEYS\nfrom .run import save, digest\n\n\ndef main():\n    p = argparse.ArgumentParser()\n    p.add_argument('--out', type=Path, required=True)\n    p.add_argument('--work', type=Path, required=True)\n    a = p.parse_args()\n    a.out = a.out.resolve(); a.work = a.work.resolve()\n    for path in [a.out, a.work]:\n        if path.is_relative_to(ROOT) or path.exists():\n            raise ValueError('Use fresh output/work directories outside the source checkout')\n    if (ROOT/'target').exists():\n        raise ValueError('Use a fresh source checkout without target/ to prevent stale builds')\n    env = build_environment(ROOT, a.work/'cargo-home')\n    for key in ['OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'RAYON_NUM_THREADS']:\n        os.environ[key] = '1'\n    import importlib.metadata\n    for line in (ROOT/'benchmarks/atom_loss/requirements.txt').read_text().splitlines():\n        if line.strip() and not line.startswith('#'):\n            package, version = line.strip().split('==')\n            if importlib.metadata.version(package) != version:\n                raise ValueError('Install the pinned requirements before measuring: '+package)\n    binding = clean_source()\n    a.out.mkdir(parents=True); a.work.mkdir(parents=True)\n    for command in BUILD_COMMANDS:\n        subprocess.run(command, cwd=ROOT, env=env, check=True)\n    if clean_source() != binding:\n        raise ValueError('Source changed during build')\n    binding.update(binaries={name: digest(ROOT/name) for name in BINARIES},\n                   build_environment={key: value for key, value in env.items() if key not in NETWORK_ENV_KEYS},\n                   rustc=subprocess.check_output(['rustc', '-Vv'], text=True, env=env),\n                   cargo=subprocess.check_output(['cargo', '-V'], text=True, env=env))\n    save(a.out/'source-manifest.json', binding)\n    subprocess.run([sys.executable, '-m', 'benchmarks.atom_loss.run', '--work', str(a.work/'timing'),\n                    '--out', str(a.out)], cwd=ROOT, env=env, check=True)\n    from .shot_data import pack\n    print(pack(a.work/'timing', a.out), flush=True)\n    subprocess.run([sys.executable, '-m', 'benchmarks.atom_loss.accuracy_seeds', '--work', str(a.work/'seeds'),\n                    '--out', str(a.out)], cwd=ROOT, env=env, check=True)\n    # These stage links now refer to the same complete clean run, not old data.\n    for stage in ['timing', 'correctness']:\n        capture(a.out, stage, {'run': 'Complete clean regeneration; see provenance-all.json for start and timing boundaries.'})\n    verify_bundle_source(a.out)\n    if {name: digest(ROOT/name) for name in BINARIES} != binding['binaries']:\n        raise ValueError('Binaries changed during evidence generation')\n    clean_source()\n    from .publish import publish\n    publish(a.out)\n    from .verify import verify\n    print(verify(a.out), flush=True)\n\n\nif __name__ == '__main__':\n    main()\n",
    "benchmarks/atom_loss/figure_contract.py": "\"\"\"Bind the reader-facing figures and methodology to validated data and source.\n\nChecksums alone cannot reject an incorrectly generated but coherently resealed\nfigure. Regenerate in temporary storage, never overwrite the evidence being\nchecked. SVG permits only one serialization unit of absolute roundoff in path\ncoordinates; all other bytes are exact. PNG compression is ignored but pixels\nand metadata must match exactly. No perceptual image similarity tolerance.\n\"\"\"\nfrom decimal import Decimal\nimport importlib.metadata\nfrom pathlib import Path\nimport re\nimport shutil\nimport tempfile\n\nfrom .artifacts import FIGURE_INPUTS, FIGURE_NAMES\n\n\ndef same_svg(actual, expected):\n    \"\"\"Matplotlib writes six decimal places; platform libm can round a tie apart.\n\n    Only anonymous path d coordinates may differ by <= 0.000001 pt, absolutely.\n    Commands, separators, number counts and every byte outside these coordinates\n    remain exact. In particular no tolerance applies to transforms, text, style,\n    viewBox, IDs/references or font glyph definitions (which have an id first).\n    \"\"\"\n    if actual == expected:\n        return True\n    number = re.compile(rb'[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][-+]?\\d+)?')\n    def split(data):\n        coordinates = []\n        def path(match):\n            structure = number.sub(b'#', match[1])\n            if not set(re.findall(rb'[A-Za-z]', structure)) <= {b'M', b'L', b'Q', b'C', b'Z', b'z'}:\n                # No tolerance for relative-coordinate accumulation or arc flags.\n                return match[0]\n            values = number.findall(match[1])\n            coordinates.extend(Decimal(value.decode('ascii')) for value in values)\n            return b'<path d=\"'+structure+b'\"'\n        return re.sub(rb'<path d=\"([^\"]*)\"', path, data), coordinates\n    actual_structure, a = split(actual)\n    expected_structure, b = split(expected)\n    return (actual_structure == expected_structure and len(a) == len(b)\n            and all(abs(x-y) <= Decimal('0.000001') for x, y in zip(a, b)))\n\n\ndef require_renderer():\n    from matplotlib import ft2font\n    requirements = Path(__file__).with_name('requirements.txt').read_text().splitlines()\n    for line in requirements:\n        if line.split('==')[0] in {'matplotlib', 'numpy', 'pillow', 'contourpy', 'cycler',\n                                  'fonttools', 'kiwisolver', 'packaging', 'pyparsing',\n                                  'python-dateutil', 'six'}:\n            package, version = line.split('==')\n            if importlib.metadata.version(package) != version:\n                raise ValueError('Install the pinned figure renderer: '+line)\n    if ft2font.__freetype_version__ != '2.6.1':\n        raise ValueError('Figure verification requires the Matplotlib wheel with bundled FreeType 2.6.1')\n\n\ndef compare_figures(root, redrawn):\n    from PIL import Image\n    for name in FIGURE_NAMES:\n        svg = name+'.svg'\n        if not same_svg((root/svg).read_bytes(), (redrawn/svg).read_bytes()):\n            raise ValueError('Figure differs from validated JSON: '+svg)\n        png = name+'.png'\n        try:\n            with Image.open(root/png) as encoded:\n                encoded.verify()  # Check chunk CRCs as well as decoded content.\n        except (OSError, SyntaxError, ValueError) as error:\n            raise ValueError('Invalid published PNG: '+png) from error\n        with Image.open(root/png) as actual, Image.open(redrawn/png) as expected:\n            # PNG permits metadata after IDAT; Pillow discovers it during load.\n            # In particular trailing EXIF orientation can change displayed pixels.\n            actual.load()\n            expected.load()\n            if (actual.format != 'PNG' or actual.n_frames != 1\n                    or actual.mode != expected.mode or actual.size != expected.size\n                    or actual.info != expected.info or actual.tobytes() != expected.tobytes()):\n                raise ValueError('Figure differs from validated JSON: '+png)\n\n\ndef verify_presentation(root):\n    methodology = Path(__file__).with_name('README.md')\n    if (root/'methodology.md').read_bytes() != methodology.read_bytes():\n        raise ValueError('Published methodology differs from source README')\n    from .plot import render\n    with tempfile.TemporaryDirectory(prefix='atom-loss-figure-check-') as temp:\n        redrawn = Path(temp)\n        for name in FIGURE_INPUTS:\n            shutil.copyfile(root/name, redrawn/name)\n        render(redrawn)\n        compare_figures(root, redrawn)\n",
    "benchmarks/atom_loss/fixtures/midswap_d3_r2.stim": "# Generated natively by RStim's Mid-SWAP builder.\n# Loss-visible measurement records are ordered loss_flag,value_bit.\n# Logical CNOT schedule: paper_alternating_ab.\nQUBIT_COORDS(1,1) 1\nQUBIT_COORDS(2,0) 2\nQUBIT_COORDS(3,1) 3\nQUBIT_COORDS(5,1) 5\nQUBIT_COORDS(1,3) 8\nQUBIT_COORDS(2,2) 9\nQUBIT_COORDS(3,3) 10\nQUBIT_COORDS(4,2) 11\nQUBIT_COORDS(5,3) 12\nQUBIT_COORDS(6,2) 13\nQUBIT_COORDS(0,4) 14\nQUBIT_COORDS(1,5) 15\nQUBIT_COORDS(2,4) 16\nQUBIT_COORDS(3,5) 17\nQUBIT_COORDS(4,4) 18\nQUBIT_COORDS(5,5) 19\nQUBIT_COORDS(4,6) 25\nR 1 3 5 8 10 12 15 17 19\nTICK[rstim:logical_flip_point]\nLOSS(0.003) 1 3 5 8 10 12 15 17 19\nR 2 9 11 13 14 16 18 25\nLOSS(0.003) 2 9 11 13 14 16 18 25\nTICK\nH 2 11 16 25\nDEPOLARIZE1(0.001) 2 11 16 25\nLOSS(0.003) 2 11 16 25\nTICK\nCX 2 1 8 9 11 10 12 13 16 15 17 18\nDEPOLARIZE2(0.001) 2 1 8 9 11 10 12 13 16 15 17 18\nLOSS(0.0015) 2 1 8 9 11 10 12 13 16 15 17 18\n# MIDSWAP_SHUTTLE round=0 logical_pairs=2 1 9 8 11 10 13 12 16 15 18 17\nTICK\nCX 1 3 2 8 10 13 5 12 15 18 11 17\nDEPOLARIZE2(0.001) 1 3 2 8 10 13 5 12 15 18 11 17\nLOSS(0.0015) 1 3 2 8 10 13 5 12 15 18 11 17\nTICK\nCX 11 8 10 3 16 14 15 9 19 17 25 18\nDEPOLARIZE2(0.001) 11 8 10 3 16 14 15 9 19 17 25 18\nLOSS(0.0015) 11 8 10 3 16 14 15 9 19 17 25 18\nTICK\nCX 3 8 10 5 9 14 15 11 13 17 25 19\nDEPOLARIZE2(0.001) 3 8 10 5 9 14 15 11 13 17 25 19\nLOSS(0.0015) 3 8 10 5 9 14 15 11 13 17 25 19\nTICK\nH 1 10 15 25\nDEPOLARIZE1(0.001) 1 10 15 25\nLOSS(0.003) 1 10 15 25\nTICK\nLOSS(0.003) 1 8 10 12 14 15 17 25\nMRL 1 8 10 12 14 15 17 25\nLOSS(0.003) 1 8 10 12 14 15 17 25\nDETECTOR(2,2,0) rec[-13]\nDETECTOR(6,2,0) rec[-9]\nDETECTOR(0,4,0) rec[-7]\nDETECTOR(4,4,0) rec[-3]\nTICK\nH 1 10 15 25\nDEPOLARIZE1(0.001) 1 10 15 25\nLOSS(0.003) 1 10 15 25\nTICK\nCX 3 8 10 5 9 14 15 11 13 17 25 19\nDEPOLARIZE2(0.001) 3 8 10 5 9 14 15 11 13 17 25 19\nLOSS(0.0015) 3 8 10 5 9 14 15 11 13 17 25 19\n# MIDSWAP_SHUTTLE round=1 logical_pairs=9 3 11 5 14 8 16 10 18 12 25 19\nTICK\nCX 15 3 5 8 16 9 11 14 25 13 19 18\nDEPOLARIZE2(0.001) 15 3 5 8 16 9 11 14 25 13 19 18\nLOSS(0.0015) 15 3 5 8 16 9 11 14 25 13 19 18\nTICK\nCX 1 8 2 3 5 17 10 12 11 18 15 13\nDEPOLARIZE2(0.001) 1 8 2 3 5 17 10 12 11 18 15 13\nLOSS(0.0015) 1 8 2 3 5 17 10 12 11 18 15 13\nTICK\nCX 1 2 14 3 5 15 17 12 11 16 18 13\nDEPOLARIZE2(0.001) 1 2 14 3 5 15 17 12 11 16 18 13\nLOSS(0.0015) 1 2 14 3 5 15 17 12 11 16 18 13\nTICK\nH 1 5 11 19\nDEPOLARIZE1(0.001) 1 5 11 19\nLOSS(0.003) 1 5 11 19\nTICK\nLOSS(0.003) 1 3 5 12 9 11 13 19\nMRL 1 3 5 12 9 11 13 19\nLOSS(0.003) 1 3 5 12 9 11 13 19\nDETECTOR(2,0,1) rec[-15] rec[-31]\nDETECTOR(2,2,1) rec[-13] rec[-29]\nDETECTOR(4,2,1) rec[-11] rec[-27]\nDETECTOR(6,2,1) rec[-9] rec[-25]\nDETECTOR(0,4,1) rec[-7] rec[-23]\nDETECTOR(2,4,1) rec[-5] rec[-21]\nDETECTOR(4,4,1) rec[-3] rec[-19]\nDETECTOR(4,6,1) rec[-1] rec[-17]\nLOSS(0.003) 2 8 10 14 15 17 16 18 25\nML 2 8 10 14 15 17 16 18 25\nDETECTOR(2,2,2) rec[-11] rec[-9] rec[-17] rec[-15] rec[-31]\nDETECTOR(6,2,2) rec[-7] rec[-13] rec[-27]\nDETECTOR(0,4,2) rec[-5] rec[-11] rec[-25]\nDETECTOR(4,4,2) rec[-3] rec[-1] rec[-9] rec[-7] rec[-21]\nOBSERVABLE_INCLUDE(0) rec[-17] rec[-15] rec[-13]\n",
    "benchmarks/atom_loss/low_probability.py": "\"\"\"Finite-power checks at the benchmark's actual primitive noise probabilities.\n\nUnit probes use exact binomial acceptance, not an absolute-error tolerance.\nThe real-circuit check exercises the blinded dataset exporter; its independent\nreference sees the private input mask only to prepare the same logical input.\nNo decoder, envelope compiler, or private answer is used here.\n\"\"\"\nfrom .shot_data import require\nimport hashlib\nimport json\nimport math\nfrom pathlib import Path\nimport re\nimport subprocess\nimport tempfile\nimport numpy as np\nfrom scipy.stats import binom, fisher_exact\nfrom . import reference, channel_probes\nfrom .shot_data import validate_dataset\n\nALPHA = 1e-7  # Each of the analytic and real-circuit families.\nfrom .probe_specs import LOSS_RATES, low_specs as specifications\n\nMUTATIONS = ('pauli', 'loss', 'both')\nFIXTURE = Path(__file__).parent/'fixtures/midswap_d3_r2.stim'\n\n\ndef remove_low_noise(text, kind):\n    \"\"\"Actual input mutation; preserve all p=0 and p>=.01 instructions.\"\"\"\n    lines, removed = [], 0\n    for line in text.splitlines():\n        match = re.match(r'^\\s*(X_ERROR|Y_ERROR|Z_ERROR|DEPOLARIZE1|DEPOLARIZE2|LOSS)\\(([^)]+)\\)', line)\n        affected = (match and 0 < float(match[2]) < .01 and\n                    (kind == 'both' or (match[1] == 'LOSS') == (kind == 'loss')))\n        if affected:\n            removed += 1\n        else:\n            lines.append(line)\n    return '\\n'.join(lines), removed\n\n\n\n\ndef event_counts(rows, columns):\n    selected = rows[:,columns].astype(np.uint64)\n    ids = (selected * (1 << np.arange(len(columns),dtype=np.uint64))).sum(axis=1).astype(int)\n    # Full joint distribution, individual bits, and total nonidentity probability.\n    return np.concatenate([np.bincount(ids,minlength=1<<len(columns)), selected.sum(axis=0),\n                           [np.count_nonzero(ids)]]).astype(int)\n\n\ndef analytic(binary, sampler, shots):\n    # At least 26 expected LOSS events; deleting the channel cannot sit in the\n    # accepted zero-count tail. No amplification changes the primitive channel.\n    shots = max(shots, 262144)\n    probes = specifications()\n    events = sum(len(expected)+len(columns)+1 for _,_,columns,expected in probes)\n    tail = ALPHA/(4*events)  # two tails, two healthy implementations\n    records, mutations = [], {k:[] for k in MUTATIONS}\n    affected = {kind:{name for name,text,_,_ in probes if remove_low_noise(text,kind)[1]}\n                for kind in MUTATIONS}\n    with tempfile.TemporaryDirectory(prefix='low-noise-') as tmp:\n        for name,text,columns,expected in probes:\n            count = max(shots, math.ceil(26/float(name[5:]))) if name.startswith('LOSS') else shots\n            probabilities = expected + [sum(p for i,p in enumerate(expected) if i & (1<<bit))\n                                          for bit in range(len(columns))] + [1-expected[0]]\n            intervals = [[int(binom.ppf(tail,count,p)),int(binom.ppf(1-tail,count,p))] for p in probabilities]\n            bounds = np.array(intervals)\n            observations = {}\n            for backend,rows in [('rust',sampler(binary,text,count,991,Path(tmp))),\n                                 ('reference',reference.sample(text,count,773))]:\n                counts = event_counts(rows,columns)\n                observations[backend] = counts.tolist()\n            passed = all(np.all((bounds[:,0] <= counts) & (counts <= bounds[:,1])) for counts in observations.values())\n            records.append(dict(case=name,primitive_probability=.001 if not name.startswith('LOSS') else float(name[5:]),\n                                shots_per_sampler=count,expected_probabilities=probabilities,\n                                accepted_counts=intervals,counts=observations,status='PASS' if passed else 'FAIL'))\n            for kind in MUTATIONS:\n                changed,removed = remove_low_noise(text,kind)\n                if not removed:\n                    continue\n                counts = event_counts(sampler(binary,changed,count,991,Path(tmp)),columns)\n                mutations[kind].append(dict(case=name, counts=counts.tolist(),\n                                            removed_instructions=removed))\n    intervals = {r['case']:r['accepted_counts'] for r in records}\n    controls = {}\n    for kind,observations in mutations.items():\n        failed = [r['case'] for r in observations\n                  if any(k<lo or k>hi for k,(lo,hi) in zip(r['counts'],intervals[r['case']],strict=True))]\n        controls[kind] = dict(rejected=bool(affected[kind]) and set(failed)==affected[kind],\n                              failed_cases=failed, observations=observations)\n    return dict(status='PASS' if all(r['status']=='PASS' for r in records) and all(m['rejected'] for m in controls.values()) else 'FAIL',\n                familywise_alpha_bound=ALPHA,method='Exact binomial equal-tail count intervals; joint bins, marginals, nonidentity',\n                cases=records,low_probability_deletion_mutations=controls)\n\n\ndef export_rows(binary,text,shots,seed,work):\n    circuit = work/'input.stim'\n    circuit.write_text(text+'\\n')\n    public,private = work/'public',work/'private'\n    subprocess.run([str(binary),'dataset','export','--circuit',str(circuit),'--shots',str(shots),\n                    '--seed',str(seed),'--mode','measurements_blinded','--logical-x-qubits','1,8,15',\n                    '--public-out',str(public),'--private-out',str(private)],check=True,capture_output=True,timeout=120)\n    manifest = json.loads((public/'manifest.json').read_text())\n    packed = np.frombuffer((public/'shots.b8').read_bytes(),dtype=np.uint8).reshape(shots,-1)\n    rows = np.unpackbits(packed,axis=1,bitorder='little')[:,:manifest['row']['bits']].astype(bool)\n    masks = np.frombuffer((private/'masks.b8').read_bytes(),dtype=np.uint8).astype(bool)\n    return rows,masks\n\n\ndef indicators(text, rows):\n    cursor,flags,detectors,observable = 0,[],[],[]\n    for op in reference.parse(text):\n        if op.name in {'M','MZ','MR','MRZ'}:\n            cursor += len(op.targets)\n        elif op.name in {'ML','MZL','MRL','MRZL'}:\n            flags.extend(range(cursor,cursor+2*len(op.targets),2))\n            cursor += 2*len(op.targets)\n        elif op.name in {'DETECTOR','OBSERVABLE_INCLUDE'}:\n            indices = [cursor+int(re.fullmatch(r'rec\\[(-\\d+)\\]',t)[1]) for t in op.targets]\n            parity = np.logical_xor.reduce(rows[:,indices],axis=1)\n            (detectors if op.name=='DETECTOR' else observable).append(parity)\n    require((cursor == rows.shape[1] == 50 and len(detectors)==16 and len(observable)==1), 'low_probability: cursor == rows.shape[1] == 50 and len(detectors)==16 and len(observable)==1')\n    columns = list(rows.T) + detectors + observable\n    names = [f'measurement_{i}' for i in range(rows.shape[1])] + [f'detector_{i}' for i in range(len(detectors))] + ['observable']\n    columns += [a & b for a,b in zip(detectors,detectors[1:])]\n    names += [f'adjacent_detector_joint_{i}' for i in range(len(detectors)-1)]\n    no_loss = ~rows[:,flags].any(axis=1)\n    return names,np.stack(columns,axis=1),no_loss,np.stack(detectors,axis=1)\n\n\ndef compare_real(text, observed, independent, masks):\n    names,a,clean_a,da = indicators(text,observed)\n    _,b,clean_b,db = indicators(text,independent)\n    # Two logical input strata. No-visible-loss detector statistics additionally\n    # isolate the Pauli channel from the much larger loss-induced syndrome rate.\n    records=[]\n    for mask in [0,1]:\n        selected = masks == mask\n        for label,x,y in [('all',a[selected],b[selected]),\n                          ('no_visible_loss',da[selected & clean_a],db[selected & clean_b])]:\n            labels = names if label=='all' else [f'detector_{i}' for i in range(16)]\n            for name,kx,ky in zip(labels,x.sum(axis=0),y.sum(axis=0)):\n                pvalue = float(fisher_exact([[int(kx),len(x)-int(kx)],[int(ky),len(y)-int(ky)]]).pvalue)\n                records.append(dict(event=f'input_{mask}/{label}/{name}',rust_events=int(kx),reference_events=int(ky),\n                                    rust_shots=len(x),reference_shots=len(y),pvalue=pvalue))\n    threshold=ALPHA/len(records)\n    failed=[r['event'] for r in records if r['pvalue'] < threshold]\n    return dict(status='FAIL' if failed else 'PASS',threshold=threshold,failed_events=failed,events=records)\n\n\ndef real_circuit(binary, shots, exporter=export_rows):\n    text = FIXTURE.read_text()\n    shots=max(shots,65536)\n    with tempfile.TemporaryDirectory(prefix='low-noise-export-') as tmp:\n        work=Path(tmp)\n        (work/'healthy').mkdir()\n        observed,masks=exporter(binary,text,shots,179,work/'healthy')\n        checked_answers=validate_dataset(lambda name:(work/'healthy'/name).read_bytes())\n        independent=np.empty_like(observed)\n        marker='TICK[rstim:logical_flip_point]'\n        require((text.count(marker)==1), 'low_probability: text.count(marker)==1')\n        for mask in [0,1]:\n            selected=masks==mask\n            prepared=text.replace(marker,marker+'\\nX 1 8 15') if mask else text\n            independent[selected]=reference.sample(prepared,int(selected.sum()),827+mask)\n        healthy=compare_real(text,observed,independent,masks)\n        controls={}\n        for kind in MUTATIONS:\n            changed,removed=remove_low_noise(text,kind)\n            (work/kind).mkdir()\n            bad,bad_masks=exporter(binary,changed,shots,179,work/kind)\n            validate_dataset(lambda name:(work/kind/name).read_bytes())\n            # Mask RNG stream is independent of physical sampling.\n            if not np.array_equal(masks,bad_masks):\n                raise ValueError('Input mask stream changed across physical-noise mutation')\n            result=compare_real(text,bad,independent,masks)\n            controls[kind]=dict(rejected=removed>0 and result['status']=='FAIL',removed_instructions=removed,\n                                failed_events=result['failed_events'],comparison=result)\n    return dict(status='PASS' if healthy['status']=='PASS' and all(c['rejected'] for c in controls.values()) else 'FAIL',\n                fixture_sha256=hashlib.sha256(text.encode()).hexdigest(),shots_per_sampler=shots,\n                scoring_key_check={'status':'PASS','checked_shots':len(checked_answers)},\n                familywise_alpha_bound=ALPHA,mode='measurements_blinded',pauli_probability=.001,loss_probability=.003,\n                method='Independent Stim lowering, logical-input strata, exact Fisher tests with Bonferroni correction',\n                comparison=healthy,low_probability_deletion_mutations=controls)\n\n\ndef run(binary,sampler,shots):\n    unit=analytic(binary,sampler,shots)\n    actual=real_circuit(binary,shots)\n    return dict(status='PASS' if unit['status']==actual['status']=='PASS' else 'FAIL',\n                analytic=unit,real_circuit=actual,familywise_alpha_bound=2*ALPHA)\n",
    "benchmarks/atom_loss/mle_candidate_resources.py": "\"\"\"MLE candidate-domain workload campaign (issue #722).\n\nExecutes the finite real-circuit MLE workload matrix declared by the scope\nplan (``docs/envelope-mle-scope.json``, issue #721) against the real CLI:\nthe measured d=3/r=2 loss-0.002 points, the bounded follow-up d=3/r=1\nloss-0.01 points that complete the declared cross-product, the synthetic\ncache-eviction corpus (cache behavior only, never real-circuit coverage) and\nthe MLE failure-semantics controls. Budgets are fixed before measurement and\nmirrored by the release gate, which fails loudly when they drift.\n\nCampaign (a few minutes after build):\n\n    python3 -m benchmarks.atom_loss.mle_candidate_resources \\\n      --binary target/release/rustqec \\\n      --plan docs/envelope-mle-scope.json \\\n      --out drafts/envelope-mle-candidate/mle-resources.json\n\nFast replay of a produced report:\n\n    python3 -m benchmarks.atom_loss.mle_candidate_resources \\\n      --verify drafts/envelope-mle-candidate/mle-resources.json\n\"\"\"\nfrom .shot_data import require\nimport argparse\nimport hashlib\nimport json\nfrom pathlib import Path\nimport sys\nimport tempfile\nimport time\n\nfrom .output_rules import evaluate_run\n\nROOT = Path(__file__).resolve().parents[2]\n\n\ndef save(path, value):\n    path = Path(path)\n    path.parent.mkdir(parents=True, exist_ok=True)\n    path.write_text(json.dumps(value, indent=2) + '\\n', encoding='utf-8')\n\n\ndef digest(path):\n    return hashlib.sha256(Path(path).read_bytes()).hexdigest()\n\n\ndef runtime_resources():\n    \"\"\"Load numeric/Stim dependencies only for a real campaign, not gate replay.\"\"\"\n    from . import readiness_resources\n    return readiness_resources\n\nSCHEMA = 'rustqec.envelope-mle-candidate-resources.v1'\nPASS_LINE = 'PASS envelope MLE candidate resources'\nPLAN_PATH = ROOT/'docs/envelope-mle-scope.json'\n\n# Budgets declared before any measurement; the release gate mirrors these\n# values and fails when the report's declared budget drifts from them.\nBUDGET = {'per_case_wall_seconds': 900, 'total_wall_seconds': 3600,\n          'peak_rss_bytes': 4 * 1024**3}\n\n# The declared finite workload matrix; nothing is measured outside it. The\n# d=3/r=2 points reuse the issue #715 seeds so the candidate measurements are\n# directly comparable to the retained full report; the d=3/r=1 points are the\n# bounded follow-up this plan adds (issue #721).\nWORKLOADS = (\n    {'id': 'mle-d3r2-p002-b1024', 'kind': 'repeated-patterns', 'real_circuit': True,\n     'distance': 3, 'rounds': 2, 'loss': 0.002, 'shots': 1024, 'seed': 715_401},\n    {'id': 'mle-d3r2-p002-b16384', 'kind': 'repeated-patterns', 'real_circuit': True,\n     'distance': 3, 'rounds': 2, 'loss': 0.002, 'shots': 16384, 'seed': 715_402},\n    {'id': 'mle-d3r1-p010-b1024', 'kind': 'repeated-patterns', 'real_circuit': True,\n     'distance': 3, 'rounds': 1, 'loss': 0.01, 'shots': 1024, 'seed': 721_401},\n    {'id': 'mle-d3r1-p010-b16384', 'kind': 'repeated-patterns', 'real_circuit': True,\n     'distance': 3, 'rounds': 1, 'loss': 0.01, 'shots': 16384, 'seed': 721_402},\n    {'id': 'mle-eviction-wires24', 'kind': 'cache-eviction', 'real_circuit': False,\n     'distance': None, 'rounds': None, 'loss': None, 'shots': None, 'seed': None},\n)\n\nFAILURE_CASE_IDS = ('fail-mle-candidate-limit', 'fail-mle-solve-timeout', 'fail-mle-infeasible')\nEXPECTED_FAILURE_CODES = {\n    'fail-mle-candidate-limit': ('unsupported_circuit', 2),\n    'fail-mle-solve-timeout': ('decode_timeout', 3),\n    'fail-mle-infeasible': ('decode_infeasible', 3),\n}\n\nEXCLUSIONS = [\n    {'case': 'mle-batches-above-16384',\n     'reason': 'not measured in this campaign; the supported batch ceiling is the largest '\n               'measured successful batch on each declared circuit shape'},\n    {'case': 'mle-scales-beyond-d3',\n     'reason': 'larger distances/rounds widen the ILP model per pattern; only the declared '\n               'd=3 points are measured, so larger scales stay outside the candidate domain'},\n    {'case': 'synthetic-eviction-as-real-circuit-coverage',\n     'reason': 'the 24-wire synthetic corpus is cache-behavior evidence only and never '\n               'counts as real-circuit MLE coverage'},\n]\n\n\ndef measure_workload(binary, work, spec):\n    \"\"\"Execute one declared workload and return its raw observation record.\"\"\"\n    resources = runtime_resources()\n    if spec['kind'] == 'cache-eviction':\n        case = {'id': spec['id'], 'decoder': 'envelope-mle', 'kind': spec['kind'],\n                'circuit_text': resources.decoder_reference.circuit_for(24),\n                'source': 'benchmarks.atom_loss.decoder_reference.circuit_for(24)',\n                'loss_rate': None, 'corpus': 'synthetic-eviction'}\n    else:\n        text, source = resources.generated_circuit(\n            binary, work, spec['distance'], spec['rounds'], spec['loss'])\n        case = {'id': spec['id'], 'decoder': 'envelope-mle', 'kind': spec['kind'],\n                'circuit_text': text, 'source': source, 'loss_rate': spec['loss'],\n                'shots': spec['shots'], 'seed': spec['seed']}\n    record = resources.measure_case(binary, work, case)\n    record['real_circuit'] = spec['real_circuit']\n    record['circuit_params'] = {\n        'distance': spec['distance'], 'rounds': spec['rounds'],\n        'loss_rate': spec['loss'], 'batch': spec['shots']}\n    return record\n\n\ndef mle_failure_cases(binary, work):\n    \"\"\"The MLE failure-semantics controls from the shared failure runner.\"\"\"\n    resources = runtime_resources()\n    records = [r for r in resources.failure_cases(binary, work)\n               if r['id'] in FAILURE_CASE_IDS]\n    require(len(records) == len(FAILURE_CASE_IDS),\n            'shared failure runner no longer produces the MLE controls: '\n            + ', '.join(FAILURE_CASE_IDS))\n    return records\n\n\ndef run_campaign(binary, plan_path, out_path):\n    resources = runtime_resources()\n    plan = json.loads(Path(plan_path).read_text())\n    require(plan.get('schema_version') == 'rustqec.envelope-mle-scope.v1',\n            'MLE candidate campaign requires the scope plan schema')\n    budget = dict(BUDGET)\n    started = time.perf_counter()\n    records = []\n    with tempfile.TemporaryDirectory(prefix='envelope-mle-candidate-') as tmp:\n        work = Path(tmp)\n        for spec in WORKLOADS:\n            records.append(measure_workload(binary, work, spec))\n        records += mle_failure_cases(binary, work)\n    total_wall = time.perf_counter() - started\n    problems = validate_records(records, budget, total_wall)\n    result = {\n        'schema_version': SCHEMA,\n        'checkout_revision': resources.checkout_revision(),\n        'generated_at': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),\n        'machine': resources.machine_identity(),\n        'build': resources.build_identity(binary),\n        'scope_plan': {'path': str(plan_path), 'sha256': digest(Path(plan_path)),\n                       'source_revision': plan.get('applies_to', {}).get('source_revision')},\n        'stress_budget': {'declared_before_run': True, 'values': budget},\n        'total_wall_seconds': total_wall,\n        'cases': records,\n        'exclusions': EXCLUSIONS,\n        'problems': problems,\n        'status': 'pass' if not problems else 'fail',\n    }\n    save(out_path, result)\n    return result\n\n\ndef validate_records(records, budget, total_wall):\n    \"\"\"Budget/output-rule/coverage validation shared by run and verify.\"\"\"\n    problems = []\n    for record in records:\n        # Never trust the producer's cached verdict: replay the output contract\n        # from the raw file-state/exit fields so an edited report cannot hide a\n        # newly installed partial prediction or a missing diagnostic report.\n        try:\n            output_problems = evaluate_run(record)\n        except (KeyError, TypeError) as error:\n            problems.append(\n                f\"{record.get('id', '<missing-id>')}: malformed output-semantics \"\n                f\"record ({error})\"\n            )\n            output_problems = []\n        if record.get('output_rule_problems') != output_problems:\n            problems.append(\n                f\"{record.get('id', '<missing-id>')}: recorded output_rule_problems \"\n                \"do not match replayed output semantics\"\n            )\n        problems += [f\"{record.get('id', '<missing-id>')}: {p}\"\n                     for p in output_problems]\n        if record['wall_seconds'] > budget['per_case_wall_seconds']:\n            problems.append(f\"{record['id']}: wall {record['wall_seconds']:.1f}s \"\n                            'exceeds the declared budget')\n        if record['peak_rss_watermark_bytes'] > budget['peak_rss_bytes']:\n            problems.append(f\"{record['id']}: peak RSS exceeds the declared budget\")\n    if total_wall > budget['total_wall_seconds']:\n        problems.append(f'total wall {total_wall:.1f}s exceeds the declared budget')\n    workloads = {r['id']: r for r in records if r['kind'] != 'failure-semantics'}\n    for spec in WORKLOADS:\n        record = workloads.get(spec['id'])\n        if record is None:\n            problems.append(f\"missing declared workload {spec['id']}\")\n            continue\n        if record['exit_code'] != 0:\n            problems.append(f\"{spec['id']}: declared workload did not succeed\")\n        if record.get('real_circuit') != spec['real_circuit']:\n            problems.append(f\"{spec['id']}: real_circuit flag drifted\")\n        if spec['real_circuit']:\n            params = record.get('circuit_params') or {}\n            if (params.get('distance'), params.get('rounds')) != (spec['distance'], spec['rounds']):\n                problems.append(f\"{spec['id']}: measured circuit shape drifted from the plan\")\n            if record['completed_shots'] != spec['shots']:\n                problems.append(f\"{spec['id']}: completed shots != declared batch\")\n    eviction = workloads.get('mle-eviction-wires24')\n    if eviction and eviction['cache']['eviction_rebuilds_observed'] <= 0:\n        problems.append('mle-eviction-wires24: cache-eviction case recorded no eviction')\n    repeated = [r for r in workloads.values() if r['kind'] == 'repeated-patterns']\n    for record in repeated:\n        if record['cache']['hits'] <= 0:\n            problems.append(f\"{record['id']}: repeated-pattern case recorded no cache hits\")\n    failures = {r['id']: r for r in records if r['kind'] == 'failure-semantics'}\n    for case_id, (code, exit_code) in EXPECTED_FAILURE_CODES.items():\n        record = failures.get(case_id)\n        if record is None:\n            problems.append(f'missing failure-semantics case {case_id}')\n        elif record['error_code'] != code or record['exit_code'] != exit_code \\\n                or record['completed_shots'] != 0:\n            problems.append(f'{case_id}: expected {code} (exit {exit_code}) with zero '\n                            'completed shots')\n    timeout = failures.get('fail-mle-solve-timeout')\n    if timeout and not timeout.get('compilation_outside_timeout'):\n        problems.append('fail-mle-solve-timeout: compilation must stay outside the '\n                        'solve-phase timeout (compile_seconds recorded, one attempted shot)')\n    return problems\n\n\ndef verify_document(report, plan_path=PLAN_PATH):\n    \"\"\"Fast structural replay of a report already loaded in memory.\"\"\"\n    problems = []\n    if report.get('schema_version') != SCHEMA:\n        return [f\"unsupported report schema: {report.get('schema_version')!r}\"]\n    for field in ('machine', 'build', 'scope_plan', 'stress_budget', 'cases', 'status'):\n        if field not in report:\n            problems.append(f'report missing {field}')\n    if problems:\n        return problems\n    if not report['stress_budget'].get('declared_before_run'):\n        problems.append('stress budget was not declared before the run')\n    if report['stress_budget'].get('values') != BUDGET:\n        problems.append('declared budget drifted from the campaign constants')\n    if not report['build'].get('sha256') or not report['machine'].get('platform'):\n        problems.append('machine/build identity incomplete')\n    plan_path = Path(plan_path)\n    if not plan_path.is_file():\n        problems.append(f'scope plan is missing: {plan_path}')\n    else:\n        plan = json.loads(plan_path.read_text())\n        binding = report.get('scope_plan') or {}\n        if binding.get('sha256') != digest(plan_path):\n            problems.append('report scope-plan SHA-256 does not match the consumed plan')\n        if binding.get('source_revision') != \\\n                plan.get('applies_to', {}).get('source_revision'):\n            problems.append('report scope-plan source revision does not match the consumed plan')\n    problems += validate_records(report['cases'], report['stress_budget']['values'],\n                                 report['total_wall_seconds'])\n    if report.get('status') != 'pass' or report.get('problems'):\n        problems.append('report does not record a passing campaign')\n    return problems\n\n\ndef verify_report(report_path, plan_path=PLAN_PATH):\n    \"\"\"Fast structural replay of a produced report; no decoder execution.\"\"\"\n    report = json.loads(Path(report_path).read_text())\n    return verify_document(report, plan_path)\n\n\ndef main():\n    parser = argparse.ArgumentParser(description=__doc__)\n    parser.add_argument('--binary', type=Path, default=ROOT/'target/release/rustqec')\n    parser.add_argument('--plan', type=Path, default=PLAN_PATH)\n    parser.add_argument('--out', type=Path)\n    parser.add_argument('--verify', type=Path)\n    args = parser.parse_args()\n    if args.verify is not None:\n        problems = verify_report(args.verify, args.plan)\n        if not problems:\n            print(f'{PASS_LINE} verify')\n            raise SystemExit(0)\n        print('FAIL envelope MLE candidate resources verify', file=sys.stderr)\n        for problem in problems:\n            print('  - ' + problem, file=sys.stderr)\n        raise SystemExit(1)\n    binary = args.binary.resolve()\n    require(binary.is_file(), f'missing binary: {binary}')\n    require(args.out is not None, '--out is required for a campaign run')\n    result = run_campaign(binary, args.plan, args.out)\n    if result['status'] == 'pass':\n        print(f\"{PASS_LINE} cases={len(result['cases'])} \"\n              f\"wall={result['total_wall_seconds']:.1f}s\")\n        raise SystemExit(0)\n    print('FAIL envelope MLE candidate resources', file=sys.stderr)\n    for problem in result['problems']:\n        print('  - ' + problem, file=sys.stderr)\n    raise SystemExit(1)\n\n\nif __name__ == '__main__':\n    main()\n",
    "benchmarks/atom_loss/noise_controls.py": "\"\"\"Analytic channel checks: known probabilities, independent of either sampler.\"\"\"\nimport math\nimport tempfile\nfrom pathlib import Path\nimport numpy as np\nfrom . import reference, channel_probes\n\nfrom .probe_specs import noise_specs as cases\n\n\ndef evaluate(binary, sampler, shots=32768):\n    specifications=list(cases())\n    # One-sample two-sided Hoeffding bound, unioned over BOTH samplers and all events.\n    tolerance=math.sqrt(math.log(4*len(specifications)/4e-7)/(2*shots))\n    records=[]\n    with tempfile.TemporaryDirectory(prefix='analytic-noise-') as tmp:\n        for name,text,columns,expected,channel in specifications:\n            native=sampler(binary,text,shots,991,Path(tmp))\n            independent=reference.sample(text,shots,773)\n            rates=[float(np.logical_xor.reduce(rows[:,columns],axis=1).mean()) for rows in [native,independent]]\n            passed=all(abs(rate-expected)<=tolerance for rate in rates)\n            # Zero-probability controls are exact and must not admit a single event.\n            if expected==0: passed=all(rate==0 for rate in rates)\n            records.append({'case':name,'channel':channel,'expected_probability':expected,\n                            'rust_probability':rates[0],'reference_probability':rates[1],\n                            'shots_per_sampler':shots,'tolerance':tolerance,'status':'PASS' if passed else 'FAIL'})\n    return records\n\n\ndef run(binary, sampler, shots=32768):\n    records=evaluate(binary,sampler,shots)\n    mutations={}\n    for channel in ['X_ERROR','Y_ERROR','Z_ERROR','DEPOLARIZE1','DEPOLARIZE2']:\n        def defective(binary,text,shots,seed,work):\n            altered='\\n'.join(line for line in text.splitlines() if not line.startswith(channel+'('))\n            return sampler(binary,altered,shots,seed,work)\n        # Execute the same acceptance test with a real defective native input.\n        observations=evaluate(binary,defective,shots)\n        failed=[r['case'] for r in observations if r['status']=='FAIL']\n        mutations[channel]={'rejected':bool(failed),'failed_cases':failed,\n                            'observations':observations}\n    distributions = channel_probes.run(binary, sampler, shots)\n    return {'distribution_probes':distributions, 'status':'PASS' if all(r['status']=='PASS' for r in records) and all(m['rejected'] for m in mutations.values()) and distributions['status']=='PASS' else 'FAIL',\n            'method':'analytic single-bit/parity probabilities; one-sample bounds; live, absent, reset-restored and pre-loss controls',\n            'familywise_alpha_bound':5e-7,'cases':records,'channel_deletion_mutations':mutations}\n",
    "benchmarks/atom_loss/output_rules.py": "\"\"\"Standard-library-only replay of decoder output publication semantics.\"\"\"\n\n\ndef evaluate_run(record):\n    \"\"\"Derive output-rule problems from raw fields in one executed case.\"\"\"\n    problems = []\n    expected = record['expected']\n    if expected['outcome'] == 'success':\n        if record['exit_code'] != 0:\n            problems.append('expected success, observed exit ' + str(record['exit_code']))\n        if not record['predictions']['installed']:\n            problems.append('predictions missing for a successful run')\n        if record['completed_shots'] != record['shots']:\n            problems.append(\n                f\"completed shots {record['completed_shots']} != declared {record['shots']}\"\n            )\n    else:\n        if record['exit_code'] != expected['exit_code']:\n            problems.append(\n                f\"expected exit {expected['exit_code']}, observed {record['exit_code']}\"\n            )\n        if record.get('error_code') != expected['error_code']:\n            problems.append(\n                f\"expected error {expected['error_code']}, \"\n                f\"observed {record.get('error_code')!r}\"\n            )\n        if record['completed_shots'] != 0:\n            problems.append('a rejected/incomplete run must report zero completed shots')\n        if record['predictions']['installed'] and not record['predictions'].get('pre_existing'):\n            problems.append(\n                'a failed run installed a prediction file that did not exist before; '\n                'truncated or partial predictions must never be published'\n            )\n        if (record['predictions'].get('pre_existing')\n                and not record['predictions'].get('unchanged')):\n            problems.append('a pre-existing prediction file was modified by a failed run')\n        want_stats = expected.get('stats_written', False)\n        if record['stats_written'] != want_stats:\n            problems.append(\n                f\"stats_written expected {want_stats}, observed {record['stats_written']}\"\n            )\n    return problems\n",
    "benchmarks/atom_loss/plot.py": "\"\"\"Render publication figures directly from recorded runs, never fitted data.\"\"\"\nimport argparse\nimport csv\nimport json\nfrom pathlib import Path\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom .artifacts import require_complete_sweep\nfrom .artifacts import timing_rows\n\nSTYLE = {\n    'envelope-matching-offline': ('RustQEC offline batch', '#247554','v','-.'),\n    'envelope-matching': ('RustQEC streaming', '#b95428','o','-'),\n    'pymatching-envelope': ('PyMatching + envelope (batch)', '#386b80','s','--'),\n    'pymatching-fixed': ('PyMatching, fixed weights (batch)', '#797471','^',':'),\n    'pymatching-fixed-loop': ('PyMatching, fixed weights (loop)', '#a99374','x',':'),\n    'envelope-mle': ('RustQEC envelope MLE', '#754c91','D','-'),\n}\nRENDER_STYLE = {'font.family':'DejaVu Sans','font.size':11,'axes.titlesize':13,\n                     'axes.labelsize':11,'axes.spines.top':False,'axes.spines.right':False,\n                     'axes.edgecolor':'#a5a19c','axes.labelcolor':'#292522','text.color':'#292522',\n                     'xtick.color':'#605b56','ytick.color':'#605b56','grid.color':'#e5e0da',\n                     'svg.fonttype':'path','svg.hashsalt':'rustqec-atom-loss-v1',\n                     'font.sans-serif':['DejaVu Sans'], 'savefig.facecolor':'white'}\n\n\ndef emit(fig, out, name):\n    for ext in ['svg','png']:\n        fig.savefig(out/f'{name}.{ext}',dpi=180,bbox_inches='tight',metadata={'Creator':'RustQEC atom-loss benchmark','Date':None} if ext=='svg' else {})\n    svg=out/f'{name}.svg'\n    svg.write_text('\\n'.join(line.rstrip() for line in svg.read_text().splitlines())+'\\n')\n    plt.close(fig)\n\n\ndef render(out):\n    # Reset ambient matplotlibrc/previous figures and use bundled font files.\n    # The wheel's FreeType renderer is checked, rather than accepting fuzzy images.\n    from .figure_contract import require_renderer\n    from matplotlib import font_manager\n    require_renderer()\n    for font in sorted((Path(matplotlib.get_data_path())/'fonts/ttf').glob('DejaVuSans*.ttf')):\n        font_manager.fontManager.addfont(str(font))\n    with matplotlib.rc_context(rc={**matplotlib.rcParamsDefault, **RENDER_STYLE}):\n        _render(out)\n\n\ndef _render(out):\n    seed_report=json.loads((out/'accuracy-seeds.json').read_text())\n    fig,axes=plt.subplots(1,3,figsize=(12.4,5.2),layout='constrained')\n    for ax,distance in zip(axes,[3,5,7]):\n        interval_bounds=[]\n        for backend,color,offset in [('pymatching-envelope','#386b80',-.06),('pymatching-fixed','#797471',.06)]:\n            cases=[c for c in seed_report['pooled'] if c['setting'].startswith(f'd{distance}-') and c['comparator']==backend]\n            cases.sort(key=lambda c:float(c['setting'].split('-p')[1]))\n            y=np.array([c['difference'] for c in cases]);lo=np.array([c['paired_95'][0] for c in cases]);hi=np.array([c['paired_95'][1] for c in cases])\n            interval_bounds.extend(lo);interval_bounds.extend(hi)\n            ax.errorbar(np.arange(5)+offset,y,yerr=[y-lo,hi-y],color=color,marker='o',ls='none',capsize=3,label=STYLE[backend][0])\n        ax.axhline(0,color='#aaa',lw=1)\n        ax.set(xticks=range(5),xticklabels=['.0001','.0003','.001','.003','.01'],title=f'd = {distance}, rounds = {distance}',\n               xlabel='Configured loss parameter pLoss',ylabel='Native \u2212 comparator failure probability')\n        ax.set_yscale('symlog',linthresh=.0005)\n        lower=min(interval_bounds)*1.5;upper=max(interval_bounds)*1.8\n        ticks=[v for v in [-.1,-.01,-.001,0.,.001] if lower<=v<=upper]\n        ax.set_yticks(ticks)\n        ax.set_ylim(lower,upper)\n        ax.tick_params(axis='x',labelsize=9);ax.grid(axis='y',alpha=.5)\n    handles,labels=axes[0].get_legend_handles_labels();fig.legend(handles,labels,loc='upper center',ncol=2,frameon=False)\n    fig.get_layout_engine().set(rect=(0,.19,1,.64))\n    fig.text(.5,.015,'Three predeclared independent seeds \u00d7 5,000 shots / setting \u00b7 negative favors native \u00b7 symmetric-log y-axis\\nConservative pointwise 95% paired intervals (Clopper\u2013Pearson + Bonferroni); no simultaneous or universal ranking claim.\\nAll per-seed results and the additional tradeoff/MLE comparison are retained in JSON and the shot archive.',ha='center',fontsize=9,color='#605b56')\n    emit(fig,out,'accuracy-seeds')\n    sampling=json.loads((out/'sampling.json').read_text())\n    decoding=json.loads((out/'decoding.json').read_text())\n    require_complete_sweep(decoding)\n    tradeoff=json.loads((out/'tradeoff.json').read_text())\n    # Absolute Rust throughput is the main result. The deliberately unoptimized\n    # reference has a separate cost figure, without a backend speedup ratio.\n    for key, name in [('rust','sampling-throughput'), ('reference','sampling-reference-cost')]:\n        fig,ax=plt.subplots(figsize=(8.4,4.4),layout='constrained')\n        x,y,lower,upper=[],[],[],[]\n        for case in sampling:\n            durations=np.array([r['sample_seconds']+r['packing_seconds'] for r in case[key]['records']])\n            values=case['shots']/durations if key=='rust' else durations*1000\n            median=np.median(values)\n            x.append(case['distance']);y.append(median);lower.append(median-values.min());upper.append(values.max()-median)\n        color='#b95428' if key=='rust' else '#386b80'\n        ax.errorbar(x,y,yerr=[lower,upper],color=color,marker='o',capsize=4,lw=1.8)\n        ax.set(yscale='log',xlabel='Code distance d (rounds = d)',\n               ylabel='Samples / second' if key=='rust' else 'Reference cost (ms / batch)',xticks=[3,5,7],\n               title='RustQEC loss-visible sampling and b8 packing' if key=='rust' else 'Unoptimized correctness-reference cost')\n        ax.grid(axis='y',which='major')\n        fig.get_layout_engine().set(rect=(0,0.15,1,1))\n        boundary=('Rust parsing excluded; sampler preparation and b8 packing included.' if key=='rust' else\n                  'Includes Python parsing, history lowering, Stim compilation and b8 packing.\\nNOT native Stim performance; no competitive backend speed comparison.')\n        fig.text(.5,.015,f\"{sampling[0]['shots']} shots / batch \u00b7 pPauli = 0.001 \u00b7 pLoss = 0.003 (two-qubit targets: pLoss/2) \u00b7 median and range of 3 runs\\n{boundary}\",\n                 ha='center',fontsize=9,color='#605b56')\n        emit(fig,out,name)\n    displayed_cases=[c for c in decoding if c['distance'] in (3,5)]\n    fig,axes=plt.subplots(1,2,figsize=(11.2,4.7),sharey=True,layout='constrained')\n    for ax,distance in zip(axes,[3,5]):\n        cases=sorted([c for c in decoding if c['distance']==distance],key=lambda c:c['loss_probability'])\n        for name in ['envelope-matching','pymatching-envelope','pymatching-fixed']:\n            label,color,marker,line=STYLE[name]\n            xs,ys,lower,upper=[],[],[],[]\n            for case in cases:\n                result=case['decoders'].get(name,{})\n                if result.get('status')!='ok': continue\n                xs.append(case['loss_probability'])\n                if result['errors'] == 0:\n                    # Omit zero-failure points without joining across their gaps.\n                    ys.append(np.nan);lower.append(np.nan);upper.append(np.nan)\n                else:\n                    ys.append(result['logical_error_rate'])\n                    lower.append(ys[-1]-result['wilson_95'][0]);upper.append(result['wilson_95'][1]-ys[-1])\n            ax.errorbar(xs,ys,yerr=[lower,upper],label=label,color=color,marker=marker,ls=line,lw=1.5,markersize=4,capsize=2)\n        ax.set(xscale='log',yscale='log',title=f'd = {distance}, rounds = {distance}',xlabel='Configured loss parameter pLoss')\n        ax.grid(axis='y')\n        visible_x=sorted({c['loss_probability'] for c in cases\n                          if any(r['status']=='ok' and r['errors']>0 for r in c['decoders'].values())})\n        tick_labels=[]\n        for value in visible_x:\n            coefficient,exponent=f'{value:.0e}'.split('e')\n            prefix='' if coefficient=='1' else coefficient + r'\\times '\n            tick_labels.append('$' + prefix + '10^{' + str(int(exponent)) + '}$')\n        ax.set_xticks(visible_x,labels=tick_labels)\n        # Equal fractional margins in log space, using only displayed points.\n        log_min,log_max=np.log10([visible_x[0],visible_x[-1]])\n        padding=.05*(log_max-log_min)\n        ax.set_xlim(10**(log_min-padding),10**(log_max+padding))\n    axes[0].set_ylabel('Logical failure probability')\n    ymax=max(r['wilson_95'][1] for c in displayed_cases for r in c['decoders'].values())*1.1\n    ymin=min(r['wilson_95'][0] for c in displayed_cases for r in c['decoders'].values() if r['errors'] > 0)*.7\n    axes[0].set_ylim(ymin,ymax)\n    handles,labels=axes[0].get_legend_handles_labels()\n    fig.legend(handles,labels,loc='upper center',bbox_to_anchor=(.5,1.0),ncol=3,frameon=False,fontsize=10)\n    fig.get_layout_engine().set(rect=(0,.07,1,.80))\n    fig.text(.5,.01,f\"{decoding[0]['shots']:,} shared shots / point \u00b7 pPauli = 0.001 \u00b7 95% Wilson intervals \u00b7 no threshold fit\\nDisplay: d = 3, 5 only; zero-failure points omitted. Full data retained in CSV.\",ha='center',fontsize=9,color='#605b56')\n    emit(fig,out,'logical-error-rate')\n    # All distances and opportunities remain visible; zero observations are limits.\n    fig,axes=plt.subplots(1,3,figsize=(12.4,4.8),sharey=True,layout='constrained')\n    for ax,distance in zip(axes,[3,5,7]):\n        cases=sorted([c for c in decoding if c['distance']==distance],key=lambda c:c['loss_probability'])\n        for name in ['envelope-matching','pymatching-envelope','pymatching-fixed']:\n            label,color,marker,line=STYLE[name]\n            xs=[c['loss_probability'] for c in cases]\n            rates=[c['decoders'][name]['logical_error_rate'] if c['decoders'][name]['errors'] else np.nan for c in cases]\n            ax.plot(xs,rates,label=label,color=color,marker=marker,ls=line,markersize=4)\n            for c in cases:\n                r=c['decoders'][name]; x=c['loss_probability']\n                if r['errors']:\n                    p=r['logical_error_rate'];lo,hi=r['wilson_95']\n                    ax.errorbar(x,p,yerr=[[p-lo],[hi-p]],color=color,capsize=2)\n                else:\n                    upper=-np.expm1(np.log(.05)/r['shots'])\n                    ax.errorbar(x,upper,yerr=upper*.3,uplims=True,color=color,marker=marker,markersize=4)\n        ax.set(xscale='log',yscale='log',title=f'd = {distance}, rounds = {distance}',\n               xlabel='Configured loss parameter pLoss',xlim=(.00008,.0125))\n        ax.set_xticks([.0001,.001,.01],labels=['$10^{-4}$','$10^{-3}$','$10^{-2}$'])\n        ax.grid(axis='y')\n    axes[0].set_ylabel('Logical failure probability / upper limit')\n    handles,labels=axes[0].get_legend_handles_labels()\n    fig.legend(handles,labels,loc='upper center',ncol=3,frameon=False,fontsize=9)\n    fig.get_layout_engine().set(rect=(0,.10,1,.86))\n    fig.text(.5,.015,'All 15 settings \u00b7 5,000 shared shots / point \u00b7 nonzero: 95% Wilson intervals\\nDown arrows: zero failures, one-sided exact 95% upper limit (not an estimated failure rate). Coincident limits overlap.',\n             ha='center',fontsize=9,color='#605b56')\n    emit(fig,out,'logical-error-rate-full')\n    fig,axes=plt.subplots(1,3,figsize=(12.4,4.8),layout='constrained')\n    for ax,distance in zip(axes,[3,5,7]):\n        cases=sorted([c for c in decoding if c['distance']==distance],key=lambda c:c['loss_probability'])\n        for name in ['envelope-matching','envelope-matching-offline','pymatching-envelope','pymatching-fixed']:\n            label,color,marker,line=STYLE[name]\n            xs,ys,lower,upper=[],[],[],[]\n            for case in cases:\n                result=case['decoders'][name]\n                times=np.array(result['total_seconds'])/result['shots']*1e6\n                median=np.median(times)\n                xs.append(case['loss_probability']);ys.append(median)\n                lower.append(median-times.min());upper.append(times.max()-median)\n            ax.errorbar(xs,ys,yerr=[lower,upper],label=label,color=color,marker=marker,ls=line,capsize=3,markersize=4)\n        ax.set(xscale='log',yscale='log',title=f'd = {distance}, rounds = {distance}',\n               xlabel='Configured loss parameter pLoss',ylabel='Workflow time (\u00b5s / shot)',xlim=(.00008,.0125))\n        ax.set_xticks([.0001,.0003,.001,.003,.01],labels=['$10^{-4}$','$3\\\\cdot10^{-4}$','$10^{-3}$','$3\\\\cdot10^{-3}$','$10^{-2}$'])\n        ax.tick_params(axis='x',labelsize=8)\n        ax.grid(axis='y')\n    handles,labels=axes[0].get_legend_handles_labels()\n    fig.legend(handles,labels,loc='upper center',ncol=3,frameon=False,fontsize=9)\n    fig.get_layout_engine().set(rect=(0,.20,1,.63))\n    fig.text(.5,.01,'All 15 settings \u00b7 5,000 shared shots / setting \u00b7 medians and observed ranges of 3 runs\\n'\n             'Panel y-ranges differ. Streaming FIFO vs offline groups. Offline adapters share input transformation and include output write/flush.\\n'\n             'Adapter/workflow costs, NOT matching-kernel rankings. Timing repetitions reuse the same shots.',\n             ha='center',fontsize=9,color='#605b56')\n    emit(fig,out,'timing-sweep')\n    with (out/'timing-sweep.csv').open('w') as f:\n        writer=csv.DictWriter(f,lineterminator='\\n',fieldnames=[\n            'distance','rounds','loss_probability','decoder','repetition','microseconds_per_shot',\n            'input_loss_patterns','graph_builds','cache_hits','policy'])\n        writer.writeheader()\n        writer.writerows(timing_rows(decoding))\n    fig,ax=plt.subplots(figsize=(8.4,4.8),layout='constrained')\n    failed=[]\n    for i,(name,result) in enumerate(tradeoff['decoders'].items()):\n        label,color,marker,_line=STYLE[name]\n        label = {\n            'envelope-matching': 'RustQEC envelope matching (streaming)',\n            'envelope-matching-offline': 'RustQEC envelope matching (batch)',\n        }.get(name, label)\n        if result['status']!='ok':\n            failed.append(label+': incomplete (no accuracy point)');continue\n        times=np.array(result['total_seconds'])/result['shots']*1e6\n        median=np.median(times);p=result['logical_error_rate'];lo,hi=result['wilson_95']\n        ax.errorbar(median,p,xerr=[[median-times.min()],[times.max()-median]],yerr=[[p-lo],[hi-p]],\n                    color=color,marker=marker,markersize=8,capsize=4,ls='none',label=label)\n        timing_label = f'{median:.2f} \u00b5s' if median < 10 else f'{median:,.0f} \u00b5s'\n        offset = (-8,9) if name=='envelope-mle' else ((8,-15) if name=='envelope-matching' else (8,3))\n        ax.annotate(timing_label, (median,p), xytext=offset,\n                    textcoords='offset points', ha='right' if name=='envelope-mle' else 'left',\n                    fontsize=9, color=color)\n    ax.set(xscale='log',xlabel='Amortized workflow time (\u00b5s / shot)',ylabel='Logical failure probability / experiment',\n           title=f\"Accuracy, offline adapters and streaming policy on {tradeoff['shots']:,} shots\",ylim=(0,None))\n    ax.grid(axis='y');ax.legend(loc='best',frameon=False,fontsize=10)\n    fig.get_layout_engine().set(rect=(0,.17,1,1))\n    fig.text(.5,.035,f\"Mid-SWAP d = 3, rounds = 2 \u00b7 pPauli = 0.001 \u00b7 pLoss = 0.003\\n95% Wilson intervals; timing median and range of 3 cold-cache runs\\nBulk graph construction + topology preparation included; NOT a matching-kernel comparison.\",ha='center',fontsize=9,color='#605b56')\n    if failed: fig.text(.5,.005,'; '.join(failed),ha='center',fontsize=8,color='#9c392a')\n    emit(fig,out,'accuracy-time')\n    # Means of stage durations add exactly to the mean workflow total. Do not\n    # describe native aggregate decode time as an isolated matching kernel.\n    stages=[('compile_seconds','Shared compiler','#aaa29a'),\n            ('transform_seconds','Public-row transform','#d8cbb8'),\n            ('topology_seconds','Sparse topology / weights','#9d855c'),\n            ('preprocess_seconds','Array / group / select','#c89464'),\n            ('graph_build_seconds','Python graph construction','#b95428'),\n            ('matching_seconds','decode_batch call','#386b80'),\n            ('output_seconds','Reorder + write/flush','#76998e'),\n            ('adapter_overhead_seconds','Bookkeeping / timers','#dadfdb')]\n    fig,ax=plt.subplots(figsize=(9.4,4.4),layout='constrained')\n    for row,name in enumerate(['pymatching-fixed','pymatching-envelope']):\n        result=tradeoff['decoders'][name];left=0.\n        for key,label,color in stages:\n            value=np.mean([r[key] for r in result['runs']])/result['shots']*1e6\n            ax.barh(row,value,left=left,color=color,label=label if row==0 else None,height=.45)\n            left+=value\n        graph_share=np.mean([r['graph_build_seconds'] for r in result['runs']])/np.mean([r['decode_seconds'] for r in result['runs']])\n        ax.text(left+.08,row,f'{left:.2f} \u00b5s / shot',va='center',fontsize=10)\n        ax.text(0,row+.31,f\"{result['runs'][0]['graph_builds']} graph(s); construction = {graph_share:.0%} of Python adapter time\",fontsize=9,color='#605b56')\n    ax.set(yticks=[0,1],yticklabels=['PyMatching fixed weights','PyMatching + envelope'],\n           xlabel='Amortized workflow time (\u00b5s / shot)',title='Where the Python batch adapter spends time',ylim=(1.65,-.55))\n    ax.set_xlim(0,max(np.mean(r['total_seconds'])/r['shots']*1e6 for n,r in tradeoff['decoders'].items() if n in ['pymatching-fixed','pymatching-envelope'])*1.23)\n    ax.grid(axis='x');ax.set_axisbelow(True)\n    fig.legend(loc='lower center',bbox_to_anchor=(.5,.10),ncol=3,frameon=False,fontsize=9)\n    fig.get_layout_engine().set(rect=(0,.31,1,1))\n    fig.text(.5,.015,'Same 5,000 shots \u00b7 d = 3, rounds = 2 \u00b7 additive means of 3 instrumented runs\\nfrom_check_matrix + decode_batch; topology rebuilt each run. Startup / JSON / scoring excluded.',ha='center',fontsize=9,color='#605b56')\n    emit(fig,out,'adapter-stages')\n    from .artifacts import summary_rows, SUMMARY_FIELDS\n    with (out/'summary.csv').open('w') as f:\n        writer=csv.DictWriter(f,lineterminator='\\n',fieldnames=SUMMARY_FIELDS)\n        writer.writeheader()\n        writer.writerows(summary_rows(decoding, tradeoff))\n\n\nif __name__=='__main__':\n    p=argparse.ArgumentParser();p.add_argument('--out',type=Path,default=Path('site/static/data/atom-loss'))\n    render(p.parse_args().out)\n",
    "benchmarks/atom_loss/probe_specs.py": "\"\"\"Hand-derived probe definitions shared by sampling and report validation.\n\nPure Python data/formulas: no sampler, decoder or scientific runtime imports.\n\"\"\"\nimport itertools\n\nCASES = {\n    'lost_control_skips_cx': 'R 0 1\\nX 0\\nLOSS(1) 0\\nCX 0 1\\nML 0 1',\n    'lost_target_skips_cx': 'R 0 1\\nH 0\\nLOSS(1) 1\\nCX 0 1\\nH 0\\nML 0 1',\n    'reset_restores_wire': 'R 0 1\\nLOSS(1) 0\\nR 0\\nX 0\\nCX 0 1\\nML 0 1',\n    'readout_reset_restores_wire': 'R 0\\nLOSS(1) 0\\nMRL 0\\nML 0',\n    'bell_partner_marginal': 'R 0 1\\nH 0\\nCX 0 1\\nLOSS(1) 0\\nML 0 1',\n    'loss_at_two_times': 'R 0 1\\nH 0\\nLOSS(0.2) 0\\nCX 0 1\\nLOSS(0.3) 1\\nML 0 1',\n    'two_losses': 'R 0 1\\nLOSS(0.3) 0 1\\nCX 0 1\\nML 0 1',\n    'pauli_and_loss': 'R 0 1\\nH 0\\nCX 0 1\\nDEPOLARIZE2(0.17) 0 1\\nLOSS(0.2) 0\\nX_ERROR(0.11) 1\\nML 0 1',\n    'persistent_loss_multiple_gates': 'R 0 1 2\\nX 0\\nLOSS(0.4) 0\\nCX 0 1\\nCX 0 2\\nML 0 1 2',\n    'repeat_delayed_readout': 'R 0 1\\nREPEAT 3 {\\nH 0\\nCX 0 1\\nLOSS(0.1) 0\\n}\\nML 0 1',\n    'ordinary_lost_measurement': 'R 0 1\\nX 0\\nLOSS(0.4) 0\\nCX 0 1\\nM 0 1',\n    'no_loss_bell': 'R 0 1\\nH 0\\nCX 0 1\\nLOSS(0) 0\\nM 0 1',\n}\nKNOWN = {\n    'lost_control_skips_cx': [1, 1, 0, 0],\n    'lost_target_skips_cx': [0, 0, 1, 1],\n    'reset_restores_wire': [0, 1, 0, 1],\n    'readout_reset_restores_wire': [1, 1, 0, 0],\n}\n\n\ndef bell_text(noise, wires):\n    data = list(range(wires))\n    pairs = ' '.join(f'{q} {q+wires}' for q in data)\n    return '\\n'.join(['R ' + ' '.join(map(str, range(2*wires))),\n                      'H ' + ' '.join(map(str, data)), 'CX ' + pairs, noise,\n                      'CX ' + pairs, 'H ' + ' '.join(map(str, data)),\n                      'M ' + pairs])\n\n\ndef basis_ops(bases, inverse=False):\n    lines = []\n    for q, basis in enumerate(bases):\n        if basis == 'X': lines.append(f'H {q}')\n        elif basis == 'Y':\n            lines.extend([f'S_DAG {q}', f'H {q}'] if inverse else [f'H {q}', f'S {q}'])\n    return '\\n'.join(lines)\n\n\ndef distribution_specs():\n    probes = []\n    def add(name, text, columns, expected, channel):\n        probes.append(dict(name=name, text=text, columns=columns, expected=expected, channel=channel))\n    for wires in [1, 2]:\n        channel = f'DEPOLARIZE{wires}'\n        for p in [0., .17, .6, 1.]:\n            noise = f'{channel}({p}) ' + ' '.join(map(str, range(wires)))\n            size = 4**wires\n            add(f'{channel}_bell_p{p}', bell_text(noise, wires), list(range(2*wires)),\n                [1-p] + [p/(size-1)]*(size-1), channel)\n    p = .17\n    for bases in itertools.product('XYZ', repeat=2):\n        text = '\\n'.join(['R 0 1', basis_ops(bases), f'DEPOLARIZE2({p}) 0 1',\n                          basis_ops(bases, inverse=True), 'M 0 1'])\n        add('DEPOLARIZE2_product_' + ''.join(bases), text, [0,1],\n            [1-4*p/5] + [4*p/15]*3, 'DEPOLARIZE2')\n    # Both loss directions, restoration, and noise before loss. Only surviving\n    # bits are scored after loss; placeholders are not physical outcomes.\n    for q in [0, 1]:\n        for state in ['lost', 'restored', 'before_loss']:\n            noise = f'DEPOLARIZE2({p}) 0 1'\n            loss = f'LOSS(1) {q}'\n            body = [noise, loss] if state == 'before_loss' else [loss] + ([f'R {q}'] if state == 'restored' else []) + [noise]\n            columns = [0,1] if state == 'restored' else [1-q]\n            expected = [1-4*p/5] + [4*p/15]*3 if state == 'restored' else (\n                [1.,0.] if state == 'lost' else [1-8*p/15,8*p/15])\n            add(f'DEPOLARIZE2_{state}_{q}', '\\n'.join(['R 0 1', *body, 'M 0 1']), columns, expected, 'DEPOLARIZE2')\n    for basis in 'XYZ':\n        text = '\\n'.join(['R 0', basis_ops(basis), f'DEPOLARIZE1({p}) 0',\n                          basis_ops(basis, inverse=True), 'M 0'])\n        add(f'DEPOLARIZE1_product_{basis}', text, [0], [1-2*p/3,2*p/3], 'DEPOLARIZE1')\n    return probes\n\n\nP = .17\n\n\ndef noise_specs():\n    # Observed event is a value bit, except DEPOLARIZE2 where it is Z parity.\n    for name, probability, basis in [('X_ERROR',P,''),('Y_ERROR',P,''),\n                                     ('Z_ERROR',P,'H 0\\n'),('DEPOLARIZE1',2*P/3,''),\n                                     ('DEPOLARIZE2',8*P/15,'')]:\n        target='0 1' if name=='DEPOLARIZE2' else '0'\n        noise=f'{name}({P}) {target}\\n'\n        for state in ['alive','lost','restored']:\n            before='LOSS(1) 0\\n' if state!='alive' else ''\n            if state=='restored': before+='R 0\\n'\n            text='R 0 1\\n'+before+basis+noise+basis+'ML 0 1'\n            # For a lost wire inspect the surviving wire: noise touching loss must skip.\n            columns=[3] if state=='lost' else ([1,3] if name=='DEPOLARIZE2' else [1])\n            yield f'{name}_{state}',text,columns,0. if state=='lost' else probability,name\n    # Nonzero channel before loss must still affect its surviving partner.\n    yield 'DEPOLARIZE2_before_loss','R 0 1\\nDEPOLARIZE2(0.17) 0 1\\nLOSS(1) 0\\nML 0 1',[3],8*P/15,'DEPOLARIZE2'\n\n\nCONFIGURED_LOSS_RATES = [.0001, .0003, .001, .003, .01]\n# Mid-SWAP splits a two-qubit operation loss rate between its two targets.\nLOSS_RATES = sorted({p for rate in CONFIGURED_LOSS_RATES for p in [rate, rate/2]})\n\ndef low_specs():\n    probes = []\n    for channel in ['X_ERROR','Y_ERROR','Z_ERROR','DEPOLARIZE1','DEPOLARIZE2']:\n        wires = 2 if channel == 'DEPOLARIZE2' else 1\n        size = 4**wires\n        expected = [0.]*size\n        expected[0] = .999\n        if channel.startswith('DEPOLARIZE'):\n            expected[1:] = [.001/(size-1)]*(size-1)\n        else:\n            expected[{'Z_ERROR':1,'X_ERROR':2,'Y_ERROR':3}[channel]] = .001\n        text = bell_text(f'{channel}(0.001) ' + ' '.join(map(str,range(wires))), wires)\n        probes.append((channel, text, list(range(2*wires)), expected))\n    for p in LOSS_RATES:\n        probes.append((f'LOSS_{p}', f'R 0\\nLOSS({p}) 0\\nML 0', [0], [1-p,p]))\n    return probes\n",
    "benchmarks/atom_loss/publish.py": "\"\"\"Render and seal a completed evidence bundle for the static documentation site.\"\"\"\nimport argparse\nfrom datetime import datetime,timezone\nimport hashlib\nimport json\nfrom pathlib import Path\nimport shutil\nfrom .plot import render\nfrom .artifacts import required_files\nfrom .run import ROOT, save\n\n\ndef publish(out):\n    from .source_contract import verify_bundle_source\n    verify_bundle_source(out)\n    render(out)\n    shutil.copyfile(ROOT/'benchmarks/atom_loss/README.md',out/'methodology.md')\n    shutil.copyfile(ROOT/'benchmarks/atom_loss/fixtures/midswap_d3_r2.stim',out/'midswap_d3_r2.stim')\n    files = sorted(required_files(out))\n    save(out/'bundle.json',{'completed_utc':datetime.now(timezone.utc).isoformat(),\n                           'sha256':{name:hashlib.sha256((out/name).read_bytes()).hexdigest() for name in files}})\n\n\nif __name__=='__main__':\n    p=argparse.ArgumentParser();p.add_argument('--out',type=Path,default=Path('site/static/data/atom-loss'))\n    publish(p.parse_args().out)\n",
    "benchmarks/atom_loss/readiness/resources/report.md": "# Envelope decoder operating envelope\n\nMeasured 2026-09-18T05:10:27Z on `macOS-26.6.2-arm64-arm-64bit-Mach-O` (arm64, 10 CPUs, 32.00 GiB).\nBinary `rustqec 0.3.3` sha256 `0580590d3e7eb36b\u2026`.\n\nThese are workload- and machine-specific measurements, not universal latency guarantees. The stress budget was declared before the run: per-case wall \u2264 900 s, total \u2264 3600 s, peak RSS \u2264 4.00 GiB.\n\n| Case | Decoder | Kind | Loss | Shots | Wall (s) | Compile (s) | Decode (s) | Patterns | Cache builds | Cache hits | Eviction rebuilds | Peak RSS watermark |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| matching-d3r2-p002-b1024 | envelope-matching | batch-scale | 0.002 | 1024 | 0.01 | 0.001 | 0.00 | 49 | 49 | 975 | 0 | 7.2 MiB |\n| matching-d3r2-p002-b16384 | envelope-matching | batch-scale | 0.002 | 16384 | 0.03 | 0.001 | 0.02 | 245 | 245 | 16139 | 0 | 12.8 MiB |\n| matching-d3r2-p002-b65536 | envelope-matching | batch-scale | 0.002 | 65536 | 0.08 | 0.001 | 0.07 | 433 | 433 | 65103 | 0 | 17.0 MiB |\n| matching-d3r2-p020-b1024 | envelope-matching | batch-scale | 0.02 | 1024 | 0.02 | 0.001 | 0.01 | 598 | 598 | 426 | 0 | 22.1 MiB |\n| matching-d3r2-p020-b16384 | envelope-matching | batch-scale | 0.02 | 16384 | 0.17 | 0.001 | 0.15 | 4684 | 7219 | 9165 | 2535 | 41.5 MiB |\n| matching-d3r2-p020-b65536 | envelope-matching | batch-scale | 0.02 | 65536 | 0.62 | 0.001 | 0.61 | 11669 | 28107 | 37429 | 16438 | 42.0 MiB |\n| matching-d3r2-p100-b1024 | envelope-matching | batch-scale | 0.1 | 1024 | 0.04 | 0.001 | 0.03 | 1024 | 1024 | 0 | 0 | 42.0 MiB |\n| matching-d3r2-p100-b16384 | envelope-matching | batch-scale | 0.1 | 16384 | 0.41 | 0.001 | 0.40 | 16244 | 16381 | 3 | 137 | 43.7 MiB |\n| matching-d3r2-p100-b65536 | envelope-matching | batch-scale | 0.1 | 65536 | 1.60 | 0.001 | 1.59 | 65536 | 65519 | 17 | 0 | 43.8 MiB |\n| matching-d3r3-p020-b16384 | envelope-matching | circuit-scale | 0.02 | 16384 | 0.47 | 0.002 | 0.45 | 9059 | 12326 | 4058 | 3267 | 68.2 MiB |\n| matching-d5r3-p020-b16384 | envelope-matching | circuit-scale | 0.02 | 16384 | 2.01 | 0.005 | 1.97 | 16314 | 16384 | 0 | 70 | 201.5 MiB |\n| matching-eviction-wires24 | envelope-matching | cache-eviction | synthetic | 1601 | 0.02 | 0.000 | 0.01 | 1401 | 1402 | 199 | 1 | 201.5 MiB |\n| mle-d3r2-p002-b1024 | envelope-mle | repeated-patterns | 0.002 | 1024 | 2.35 | 0.003 | 2.33 | 45 | 45 | 979 | 0 | 201.5 MiB |\n| mle-d3r2-p002-b16384 | envelope-mle | repeated-patterns | 0.002 | 16384 | 37.98 | 0.003 | 37.97 | 267 | 267 | 16117 | 0 | 201.5 MiB |\n| mle-eviction-wires24 | envelope-mle | cache-eviction | synthetic | 1601 | 1.04 | 0.000 | 1.02 | 1401 | 1402 | 199 | 1 | 201.5 MiB |\n\n## Failure semantics (tested against the real CLI)\n\n| Case | Decoder | Exit | Error code | Stats written | Predictions |\n| --- | --- | --- | --- | --- | --- |\n| fail-mle-candidate-limit | envelope-mle | 2 | unsupported_circuit | no | none installed |\n| fail-mle-solve-timeout | envelope-mle | 3 | decode_timeout | yes | none installed |\n| fail-mle-infeasible | envelope-mle | 3 | decode_infeasible | yes | none installed |\n| fail-stale-output-overwrite | envelope-matching | 2 | output_error | no | none installed |\n\n## Recommended operating ranges (this machine, this workload)\n\n### envelope-matching\n- Shots per batch: \u2264 65536 measured.\n- Loss rate: \u2264 0.1 measured.\n- decode stays near-linear in shots at fixed pattern count; cache eviction rebuilds were measured and remained within budget.\n\n### envelope-mle\n- Shots per batch: \u2264 16384 measured.\n- Loss rate: \u2264 0.002 measured.\n- cost is dominated by ILP build+solve per distinct loss pattern; use --shot-timeout-ms so a slow pattern stops the batch with decode_timeout instead of running unbounded.\n\n### Exact failure semantics\n- Compilation rejection (`unsupported_circuit`, exit 2): neither predictions nor statistics are published; compilation is outside `--shot-timeout-ms`.\n- MLE solve timeout (`decode_timeout`, exit 3): diagnostic statistics are written (including `compile_seconds`, `attempted_shot_count`, `timeout_count=1`) and no prediction file is published; completed shots count as zero.\n- MLE infeasible shot (`decode_infeasible`, exit 3): same output rule as timeout, with `infeasible_shot_count=1`.\n- Pre-existing outputs: the CLI refuses to overwrite (`output_error`, exit 2) and leaves stale files byte-identical; never read a stale prediction as this run\u2019s success. Counts after timeout/infeasible are attempts, never completed shots.\n\n## Exclusions\n\n- mle-d3r2-p020/p100-batches: ILP model build+solve per distinct loss pattern (~1.4e-1 s each on the reference machine) times tens of thousands of patterns exceeds the declared stress budget; no timing is invented for these omitted points\n- mle-scale-beyond-d3r2-real-circuits: larger real circuits widen the ILP model per pattern; only the synthetic 24-wire eviction corpus is measured at scale for MLE in this campaign\n- matching-batches-above-65536: not measured in this campaign; the recommended range stops at the largest measured successful batch\n\n## Hard code limits (separate from measurements)\n\n- `max_envelope_candidates` = 100000\n- `max_primitive_probes` = 100000\n- `max_primitive_symptom_terms` = 10000000\n- `max_conditioned_decoder_artifacts` = 1024\n- `observables` = 1..=64\n- `sweep_bits` = 0\n",
    "benchmarks/atom_loss/readiness_correctness.py": "\"\"\"Bounded, independently checked correctness suite for the proposed envelope support domain (issue #714).\n\nEvery support promise in docs/envelope-support.json gets a stated evidence\nlevel here. Expected answers come from the independent Stim oracle (private\nloss histories, Stim-derived DEM and Pauli fault propagation, exact min-plus\nenumeration of the validated native representation) \u2014 never from cached native\npredictions. The decoder under test only sees the public\n``measurements_blinded`` bundle; scoring stays private.\n\nSmoke profile (a few minutes after build):\n\n    python3 -m benchmarks.atom_loss.readiness_correctness \\\n      --binary target/release/rustqec \\\n      --matrix docs/envelope-support.json \\\n      --profile smoke \\\n      --out drafts/envelope-readiness/correctness.json\n\nThe full profile widens fault injection and randomized differential sampling:\n\n    python3 -m benchmarks.atom_loss.readiness_correctness \\\n      --binary target/release/rustqec \\\n      --matrix docs/envelope-support.json \\\n      --profile full \\\n      --out drafts/envelope-readiness/correctness-full.json\n\"\"\"\nfrom .shot_data import require\nimport argparse\nfrom collections import defaultdict\nimport hashlib\nimport json\nfrom pathlib import Path\nimport subprocess\nimport sys\nimport tempfile\nimport numpy as np\n\nfrom . import reference, chain_reference\nfrom .run import ROOT, save, digest, generate\n\nSCHEMA = 'rustqec.envelope-readiness-correctness.v1'\nPASS_LINE = 'PASS envelope readiness correctness'\nFIXTURE = ROOT/'benchmarks/atom_loss/fixtures/midswap_d3_r2.stim'\nMATRIX_PATH = ROOT/'docs/envelope-support.json'\nMAX_EXACT_STATES = 1 << 18\nREQUIRED_HISTORY_CATEGORIES = (\n    'no_loss', 'multiple_simultaneous_losses', 'loss_in_different_rounds', 'reset_restoring_wire')\nREQUIRED_CHANNELS = ('X_ERROR', 'DEPOLARIZE1', 'DEPOLARIZE2')\nINDEPENDENT_SOURCE = ('independent Stim oracle: private loss histories lowered without RustQEC code, '\n                      'Stim-derived DEM and Pauli fault propagation, exact min-plus enumeration')\n\n\ndef sha_text(text):\n    return hashlib.sha256(text.encode()).hexdigest()\n\n\ndef checkout_revision():\n    try:\n        result = subprocess.run(['git', 'rev-parse', 'HEAD'], capture_output=True,\n                                text=True, cwd=ROOT, check=False)\n    except OSError:\n        return None\n    return result.stdout.strip() or None\n\n\ndef binary_record(binary):\n    version = subprocess.run([str(binary), '--version'], capture_output=True, text=True).stdout.strip()\n    return {'path': str(binary), 'sha256': digest(binary), 'version': version}\n\n\ndef advertised_decoders(binary):\n    result = subprocess.run([str(binary), 'capabilities', '--format', 'json'],\n                            capture_output=True, text=True, check=False)\n    require(result.returncode == 0, 'capabilities failed: ' + result.stderr.strip())\n    commands = json.loads(result.stdout)['commands']\n    decode = next((c for c in commands if c.get('name') == 'decode'), {})\n    return list(decode.get('decoders', []))\n\n\ndef resolve_exporters(binary):\n    examples = binary.parent/'examples'\n    exporters = {'matching': examples/'export_matching_benchmark',\n                 'oracle': examples/'export_decoder_oracle'}\n    missing = [str(p) for p in exporters.values() if not p.is_file()]\n    require(not missing,\n            'missing exporter example binaries: ' + ', '.join(missing) +\n            '; build with: cargo build --release --locked -p rustqec-cli --features benchmark-tools,ilp'\n            ' --bin rustqec --example export_matching_benchmark --example export_decoder_oracle')\n    return exporters\n\n\ndef loss_events(ops):\n    \"\"\"Ordered per-qubit LOSS/reset/terminal events with TICK segment indices.\"\"\"\n    events = defaultdict(list)\n    width = 0\n    segment = 0\n    for position, op in enumerate(ops):\n        if op.name == 'TICK':\n            segment += 1\n        elif op.name == 'LOSS':\n            for target in op.targets:\n                events[int(target)].append({'kind': 'loss', 'index': width,\n                                            'segment': segment, 'position': position})\n                width += 1\n        elif op.name in ('MRL', 'MRZL', 'R', 'RZ'):\n            for target in op.targets:\n                events[int(target)].append({'kind': 'reset', 'segment': segment, 'position': position})\n        elif op.name in ('ML', 'MZL'):\n            for target in op.targets:\n                events[int(target)].append({'kind': 'terminal', 'segment': segment, 'position': position})\n    return events, width\n\n\ndef targeted_histories(text):\n    \"\"\"Named private loss histories exercising the required coverage categories.\"\"\"\n    ops = reference.parse(text)\n    events, width = loss_events(ops)\n    histories = []\n\n    def record(name, indices, category):\n        history = np.zeros(width, dtype=bool)\n        for index in indices:\n            history[index] = True\n        histories.append({'name': name, 'indices': sorted(indices),\n                          'category': category, 'history': history})\n\n    record('no_loss', [], 'no_loss')\n    if width:\n        record('single_early', [0], 'single_loss')\n        record('single_middle', [width//2], 'single_loss')\n        record('single_late', [width - 1], 'single_loss')\n    by_segment = defaultdict(dict)\n    for qubit, qevents in events.items():\n        for event in qevents:\n            if event['kind'] == 'loss':\n                by_segment[event['segment']].setdefault(qubit, event['index'])\n    for segment in sorted(by_segment):\n        chosen = sorted(by_segment[segment].values())\n        if len(chosen) >= 3:\n            record('multi_simultaneous', chosen[:3], 'multiple_simultaneous_losses')\n            break\n    rounds_done = reset_done = False\n    for qubit, qevents in sorted(events.items()):\n        losses = [e for e in qevents if e['kind'] == 'loss']\n        resets = [e for e in qevents if e['kind'] == 'reset']\n        if not rounds_done and len({e['segment'] for e in losses}) >= 2:\n            record(f'different_rounds_q{qubit}', [losses[0]['index'], losses[-1]['index']],\n                   'loss_in_different_rounds')\n            rounds_done = True\n        if not reset_done:\n            for first in losses:\n                mid = [r for r in resets if r['position'] > first['position']]\n                later = [b for b in losses if mid and b['position'] > mid[0]['position']]\n                if mid:\n                    indices = [first['index']] + ([later[0]['index']] if later else [])\n                    record(f'reset_restore_q{qubit}', indices, 'reset_restoring_wire')\n                    reset_done = True\n                    break\n    return histories\n\n\ndef single_fault_rows(lowered):\n    \"\"\"Every single Pauli fault at every noise instruction of a lowered circuit.\"\"\"\n    rows = []\n    channels = set()\n    for position, instruction in enumerate(lowered):\n        if instruction.name not in ['X_ERROR', 'Y_ERROR', 'Z_ERROR', 'DEPOLARIZE1', 'DEPOLARIZE2']:\n            continue\n        channels.add(instruction.name)\n        targets = [t.value for t in instruction.targets_copy()]\n        if instruction.name == 'DEPOLARIZE2':\n            faults = [[(a, q), (b, r)] for q, r in zip(targets[::2], targets[1::2])\n                      for a in 'IXYZ' for b in 'IXYZ' if a + b != 'II']\n        else:\n            paulis = 'XYZ' if instruction.name == 'DEPOLARIZE1' else instruction.name[0]\n            faults = [[(pauli, q)] for q in targets for pauli in paulis]\n        for fault in faults:\n            injected = lowered[:position].without_noise()\n            for pauli, qubit in fault:\n                if pauli != 'I':\n                    injected.append(pauli, [qubit])\n            injected += lowered[position + 1:].without_noise()\n            rows.append(injected.reference_sample())\n    return rows, channels\n\n\ndef randomized_rows(ops, width, count, seed, loss_rate=0.15):\n    \"\"\"Reproducible randomized differential rows with a recorded seed.\"\"\"\n    rng = np.random.default_rng(seed)\n    rows = []\n    for _ in range(count):\n        history = rng.random(width) < loss_rate\n        lowered = reference.lower(ops, history)\n        rows.append(lowered.without_noise().reference_sample())\n    return rows\n\n\ndef build_rows(text, *, seed, fault_histories=('no_loss',), random_histories=8):\n    \"\"\"Targeted-history witnesses plus injected faults and randomized rows.\"\"\"\n    ops = reference.parse(text)\n    _, width = loss_events(ops)\n    histories = targeted_histories(text)\n    rows, channels, row_provenance = [], set(), []\n    targeted_rows = {}\n    for entry in histories:\n        lowered = reference.lower(ops, entry['history'])\n        noiseless = lowered.without_noise().reference_sample()\n        rows.append(noiseless)\n        targeted_rows[entry['name']] = noiseless\n        if entry['name'] in fault_histories:\n            faulted, used = single_fault_rows(lowered)\n            rows += faulted\n            channels |= used\n    rows += randomized_rows(ops, width, random_histories, seed)\n    merged = np.unique(np.array(rows, dtype=np.uint8), axis=0)\n    exercised = {name: any(np.array_equal(row, kept) for kept in merged)\n                 for name, row in targeted_rows.items()}\n    return merged, histories, exercised, channels\n\n\ndef native_costs_per_pattern(model, candidates, patterns, count):\n    indices = np.arange(1 << (count + 1))\n    base = chain_reference.costs(\n        [(chain_reference.native_mask(e, count), e['weight']) for e in model['independent_effects']],\n        count + 1)\n    per_pattern = {}\n    for pattern in set(patterns):\n        values = base.copy()\n        for i in pattern:\n            values = np.minimum.reduce([values[indices ^ candidate] for candidate in candidates[i]])\n        per_pattern[pattern] = values\n    return per_pattern\n\n\ndef matching_costs_per_pattern(edges, loss_edges, patterns, count):\n    mean = np.mean([e['weight'] for e in edges])\n    per_pattern = {}\n    for pattern in set(patterns):\n        active = set().union(*(loss_edges[i] for i in pattern)) if pattern else set()\n        per_pattern[pattern] = chain_reference.costs(\n            [(e['mask'], e['factor']*mean if i in active else e['weight'])\n             for i, e in enumerate(edges)], count + 1)\n    return per_pattern\n\n\ndef check_predictions(predictions, choices):\n    \"\"\"Predictions must stay inside the independently derived allowed optima.\"\"\"\n    require(len(predictions) == len(choices)\n            and all(type(v) is int and v in (0, 1) for v in predictions),\n            'Incomplete or invalid decoder predictions')\n    rejected = [i for i, (value, answers) in enumerate(zip(predictions, choices, strict=True))\n                if value not in answers]\n    singleton = [i for i, answers in enumerate(choices) if len(answers) == 1]\n    require(bool(singleton), 'Oracle has no unique optimum witness')\n    flipped = predictions.copy()\n    flipped[singleton[0]] ^= 1\n    half = len(choices)//2\n    return {'predictions': predictions, 'checked_rows': len(choices), 'rejected_rows': rejected,\n            'unique_optimum_rows': len(singleton), 'allowed_tie_rows': len(choices) - len(singleton),\n            'flipped_prediction_rejected': flipped[singleton[0]] not in choices[singleton[0]],\n            'placeholder_invariance': predictions[:half] == predictions[half:],\n            'prediction_sha256': hashlib.sha256(bytes(predictions)).hexdigest()}\n\n\ndef decode_public(binary, decoder, public, work, timeout=300):\n    out = work/(decoder + '.b8')\n    result = subprocess.run([str(binary), 'decode', '--decoder', decoder, '--dataset', str(public),\n                             '--out', str(out), '--stats-out', str(work/(decoder + '.json'))],\n                            capture_output=True, text=True, timeout=timeout, check=False)\n    require(result.returncode == 0,\n            f'{decoder} decode failed: {result.stderr.strip() or result.stdout.strip()}')\n    return list(out.read_bytes())\n\n\ndef oracle_case(name, text, *, binary, exporters, work, seed, source,\n                circuit_params, end_to_end=True, fault_histories=('no_loss',),\n                random_histories=8):\n    \"\"\"One independently checked case; returns its evidence record.\"\"\"\n    record = {'name': name, 'source': source, 'circuit_sha256': sha_text(text),\n              'expected_answer_source': INDEPENDENT_SOURCE if end_to_end else\n              'independent Stim compiler-output validation only (no end-to-end enumeration)',\n              'evidence_level': 'independent-end-to-end' if end_to_end else 'compiler-output-only',\n              'seed': seed, 'circuit_params': circuit_params}\n    case_work = work/name\n    case_work.mkdir()\n    circuit, probes, effects, edges, candidates, loss_edges, probe_count = \\\n        chain_reference.independent_model(text, require_shape=None)\n    count = circuit.num_detectors\n    record['detectors'] = count\n    record['observables'] = circuit.num_observables\n    rows, histories, exercised, channels = build_rows(\n        text, seed=seed, fault_histories=fault_histories, random_histories=random_histories)\n    record['histories'] = [{'name': h['name'], 'category': h['category'],\n                            'active_loss_indices': h['indices'],\n                            'exercised': exercised[h['name']]} for h in histories]\n    record['noise_channels_exercised'] = sorted(channels)\n    require(all(exercised.values()),\n            f'{name}: targeted histories dropped by deduplication: '\n            + ', '.join(k for k, v in exercised.items() if not v))\n    flags = [p['flag'] for p in probes]\n    alternate = rows.copy()\n    for flag in flags:\n        alternate[alternate[:, flag] == 1, flag + 1] ^= 1\n    full_rows = np.concatenate([rows, alternate])\n    canonical = full_rows.copy()\n    for flag in flags:\n        canonical[canonical[:, flag] == 1, flag + 1] = 1\n    detections = circuit.compile_m2d_converter().convert(\n        measurements=canonical.astype(bool), separate_observables=True)[0]\n    patterns = [tuple(np.flatnonzero(row[flags])) for row in full_rows]\n    syndromes = [sum(int(v) << i for i, v in enumerate(row)) for row in detections]\n    record['rows'] = len(full_rows)\n    record['distinct_rows_before_placeholders'] = len(rows)\n    record['placeholder_pairs'] = len(rows)\n    record['patterns'] = len(set(patterns))\n    record['measurement_sha256'] = hashlib.sha256(full_rows.tobytes()).hexdigest()\n    chain_reference.write_bundle(case_work/'public', text, full_rows, circuit)\n    public = case_work/'public'\n    manifest = json.loads((public/'manifest.json').read_text())\n    require(manifest['mode'] == 'measurements_blinded' and not (public/'answers.b8').exists(),\n            f'{name}: public bundle must stay blinded (public/private scoring separation)')\n    graph_path = case_work/'graph.json'\n    subprocess.run([str(exporters['matching']), str(public), str(graph_path)],\n                   check=True, capture_output=True)\n    graph = json.loads(graph_path.read_text())\n    require(graph['syndromes'] == detections.astype(int).tolist(),\n            f'{name}: independent m2d mismatch')\n    require(graph['losses'] == [list(p) for p in patterns],\n            f'{name}: independent visible-loss mapping mismatch')\n    model_path = case_work/'models.json'\n    subprocess.run([str(exporters['oracle']), str(public), str(model_path)],\n                   check=True, capture_output=True)\n    model = json.loads(model_path.read_text())\n    chain_reference.validate_model(model, effects, candidates, count)\n    record['compiler_output_check'] = 'pass'\n    record['independent_effects'] = len(effects)\n    record['independent_graph_edges'] = len(edges)\n    record['stim_pauli_probes'] = probe_count\n    if not end_to_end:\n        record['exclusion'] = (f'exact enumeration over 2^{count + 1} detector/logical states is '\n                               'infeasible for this case; compiler output is independently validated '\n                               'but end-to-end replay is a separate evidence level and is not claimed')\n        return record\n    require(count + 1 <= 18, f'{name}: exact enumeration budget exceeded')\n    matching_values = matching_costs_per_pattern(edges, loss_edges, patterns, count)\n    mle_values = native_costs_per_pattern(model, candidates, patterns, count)\n    expected = {\n        'envelope-matching': [chain_reference.allowed(matching_values[p], s, count)\n                              for p, s in zip(patterns, syndromes)],\n        'envelope-mle': [chain_reference.allowed(mle_values[p], s, count)\n                         for p, s in zip(patterns, syndromes)],\n    }\n    record['allowed_answers'] = {name_: [sorted(a) for a in choices]\n                                 for name_, choices in expected.items()}\n    backends = {}\n    mismatches = []\n    for decoder, choices in expected.items():\n        predictions = decode_public(binary, decoder, public, case_work)\n        outcome = check_predictions(predictions, choices)\n        backends[decoder] = outcome\n        mismatches += [{'decoder': decoder, 'row': row, 'predicted': predictions[row],\n                        'allowed': sorted(choices[row])} for row in outcome['rejected_rows']]\n        require(outcome['flipped_prediction_rejected'],\n                f'{name}: flipped known-answer control was not rejected by the oracle')\n        require(outcome['placeholder_invariance'],\n                f'{name}: placeholder bits changed a {decoder} prediction')\n    record['backends'] = backends\n    record['mismatches'] = mismatches\n    record['status'] = 'pass' if not mismatches else 'fail'\n    record['public_private_separation'] = True\n    return record\n\n\ndef generate_circuit(binary, work, distance, rounds, loss, pauli=0.001):\n    path = work/f'midswap_d{distance}_r{rounds}.stim'\n    generate(binary, path, distance, rounds, loss, pauli)\n    # Exercise the X_ERROR channel as well: --noise only sets depolarization.\n    from .run import checked\n    checked([binary, 'circuit', 'gen', '--code', 'surface_code', '--task',\n             'rotated_memory_z_midswap', '--distance', distance, '--rounds', rounds,\n             '--noise', pauli, '--operation-loss-probability', loss,\n             '--measurement-loss-probability', loss,\n             '--before-measure-flip-probability', pauli,\n             '--after-reset-flip-probability', pauli, '--out', path])\n    return path.read_text(), (f'rustqec circuit gen --code surface_code --task '\n                              f'rotated_memory_z_midswap --distance {distance} --rounds {rounds} '\n                              f'--noise {pauli} --operation-loss-probability {loss} '\n                              f'--measurement-loss-probability {loss} '\n                              f'--before-measure-flip-probability {pauli} '\n                              f'--after-reset-flip-probability {pauli}')\n\n\nPROFILES = {\n    'smoke': {'random_histories': 8, 'fault_histories': ('no_loss',)},\n    'full': {'random_histories': 64,\n             'fault_histories': ('no_loss', 'multi_simultaneous', 'different_rounds')},\n}\n\n\ndef run_suite(binary, matrix_path, profile, out_path=None):\n    require(profile in PROFILES, f'unknown profile: {profile}')\n    params = PROFILES[profile]\n    matrix = json.loads(Path(matrix_path).read_text())\n    require(matrix.get('schema_version') == 'rustqec.envelope-support.v1',\n            'readiness correctness requires the envelope support matrix schema')\n    decoders = set(matrix['decoders'])\n    missing = decoders - set(advertised_decoders(binary))\n    require(not missing,\n            'binary does not advertise matrix decoder(s): ' + ', '.join(sorted(missing)))\n    exporters = resolve_exporters(binary)\n    cases = []\n    exclusions = []\n    with tempfile.TemporaryDirectory(prefix='envelope-readiness-correctness-') as tmp:\n        work = Path(tmp)\n        fault_histories = tuple(h for h in params['fault_histories'])\n        fixture_text = FIXTURE.read_text()\n        cases.append(oracle_case(\n            'midswap-d3-r2-fixture', fixture_text, binary=binary, exporters=exporters,\n            work=work, seed=714_001, source=str(FIXTURE.relative_to(ROOT)),\n            circuit_params={'distance': 3, 'rounds': 2, 'loss_rate': 0.003},\n            fault_histories=fault_histories,\n            random_histories=params['random_histories']))\n        for distance, rounds, loss, seed, name in (\n            (3, 2, 0.002, 721_000, 'midswap-d3-r2-p002-generated'),\n            (3, 1, 0.01, 714_002, 'midswap-d3-r1-generated'),\n        ):\n            text, command_text = generate_circuit(binary, work, distance, rounds, loss)\n            cases.append(oracle_case(\n                name, text, binary=binary,\n                exporters=exporters, work=work, seed=seed, source=command_text,\n                circuit_params={'distance': distance, 'rounds': rounds,\n                                'loss_rate': loss},\n                fault_histories=fault_histories,\n                random_histories=max(4, params['random_histories']//2)))\n        text, command_text = generate_circuit(binary, work, 3, 3, 0.01)\n        case = oracle_case(\n            'midswap-d3-r3-generated', text, binary=binary, exporters=exporters,\n            work=work, seed=714_003, source=command_text, end_to_end=False,\n            circuit_params={'distance': 3, 'rounds': 3, 'loss_rate': 0.01},\n            fault_histories=(), random_histories=4)\n        cases.append(case)\n        exclusions.append({'case': case['name'], 'reason': case['exclusion']})\n    exclusions.append({\n        'case': 'conventional-family-end-to-end',\n        'reason': 'conventional circuits are isolated checked examples in the support matrix; '\n                  'envelope-mle rejects the pinned fixture at the candidate limit, so no '\n                  'conventional MLE end-to-end domain is claimed'})\n    coverage = defaultdict(int)\n    channels = set()\n    points = []\n    mismatches = []\n    for case in cases:\n        for history in case['histories']:\n            if history['exercised']:\n                coverage[history['category']] += 1\n        channels |= set(case['noise_channels_exercised'])\n        points.append({'case': case['name'], 'detectors': case['detectors'],\n                       'evidence_level': case['evidence_level']})\n        coverage['placeholder_pairs'] += case['placeholder_pairs']\n        coverage['rows'] += case['rows']\n        if case['evidence_level'] == 'independent-end-to-end':\n            for outcome in case['backends'].values():\n                coverage['allowed_tie_rows'] += outcome['allowed_tie_rows']\n                coverage['checked_rows'] += outcome['checked_rows']\n        mismatches += case.get('mismatches', [])\n    coverage_report = {\n        'history_categories': {category: coverage[category]\n                               for category in REQUIRED_HISTORY_CATEGORIES},\n        'single_loss_histories': coverage['single_loss'],\n        'noise_channels': sorted(channels),\n        'circuit_points': points,\n        'placeholder_pairs': coverage['placeholder_pairs'],\n        'total_rows': coverage['rows'],\n        'checked_rows': coverage['checked_rows'],\n        'allowed_tie_rows': coverage['allowed_tie_rows'],\n        'randomized_differential_seeds': [case['seed'] for case in cases],\n    }\n    problems = validate_coverage(coverage_report, cases)\n    problems += [f\"mismatch: {m}\" for m in mismatches]\n    status = 'pass' if not problems else 'fail'\n    result = {\n        'schema_version': SCHEMA,\n        'profile': profile,\n        'checkout_revision': checkout_revision(),\n        'binary': binary_record(binary),\n        'matrix': {'path': str(matrix_path), 'sha256': digest(Path(matrix_path)),\n                   'source_revision': matrix.get('applies_to', {}).get('source_revision')},\n        'method': ('Independent Stim lowering of private loss histories; Stim-derived DEM, '\n                   'primitive Pauli propagation and loss candidates validated against native '\n                   'compiler output; exact min-plus enumeration of allowed optima per decoder '\n                   'objective. Matching is checked against its minimum-weight objective with '\n                   'explicit allowed ties; MLE against its fault-configuration objective. '\n                   'Neither check claims logical-class Bayes optimality nor that every noisy '\n                   'shot must decode correctly.'),\n        'cases': cases,\n        'coverage': coverage_report,\n        'exclusions': exclusions,\n        'mismatches': mismatches,\n        'problems': problems,\n        'status': status,\n    }\n    if out_path is not None:\n        save(out_path, result)\n    return result\n\n\ndef validate_coverage(coverage, cases):\n    problems = []\n    for category, count in coverage['history_categories'].items():\n        if count <= 0:\n            problems.append(f'missing required loss-history coverage: {category}')\n    missing_channels = [c for c in REQUIRED_CHANNELS if c not in coverage['noise_channels']]\n    if missing_channels:\n        problems.append('missing required noise-channel coverage: ' + ', '.join(missing_channels))\n    if len(coverage['circuit_points']) < 2:\n        problems.append('missing required circuit size/round coverage')\n    if coverage['placeholder_pairs'] <= 0:\n        problems.append('missing placeholder-invariance coverage')\n    end_to_end = [c for c in cases if c['evidence_level'] == 'independent-end-to-end']\n    if not end_to_end:\n        problems.append('no independent end-to-end case ran')\n    for case in cases:\n        source = case.get('expected_answer_source', '')\n        if case['evidence_level'] == 'independent-end-to-end' and not source.startswith('independent'):\n            problems.append(f\"{case['name']}: expected answers are not independently derived ({source!r}); \"\n                            'cached native predictions cannot satisfy the independent checks')\n        if case.get('status') == 'fail':\n            problems.append(f\"{case['name']}: case failed\")\n    return problems\n\n\ndef self_test(binary):\n    \"\"\"Prove the runner rejects corrupted oracle inputs, flipped answers and removed coverage.\"\"\"\n    exporters = resolve_exporters(binary)\n    matrix = json.loads(MATRIX_PATH.read_text())\n    mini = next(c for c in matrix['controls'] if c['id'] == 'mini-circuit-known-answer')\n    text = mini['dataset']['circuit']\n    observations = []\n\n    with tempfile.TemporaryDirectory(prefix='envelope-correctness-selftest-') as tmp:\n        work = Path(tmp)\n        case = oracle_case('self-test-mini', text, binary=binary, exporters=exporters,\n                           work=work, seed=714_900, source='matrix inline control',\n                           circuit_params={'distance': 1, 'rounds': 1, 'loss_rate': 0.01},\n                           random_histories=2)\n        require(case['status'] == 'pass', 'self-test baseline case must pass')\n\n        # Tamper 1: corrupt the compiled loss-to-edge mapping and a Pauli effect.\n        model = json.loads((work/'self-test-mini'/'models.json').read_text())\n        circuit, probes, effects, edges, candidates, loss_edges, _ = \\\n            chain_reference.independent_model(text, require_shape=None)\n        count = circuit.num_detectors\n        rejected = []\n        for name, mutate in (\n                ('pauli_effect_weight', lambda m: m['independent_effects'][0].__setitem__('weight', m['independent_effects'][0]['weight'] + .25)),\n                ('loss_candidate_mapping', lambda m: next(es for es in m['loss_candidates'] if len(es) > 1).pop())):\n            defective = json.loads(json.dumps(model))\n            mutate(defective)\n            try:\n                chain_reference.validate_model(defective, effects, candidates, count)\n                rejected.append(False)\n            except ValueError:\n                rejected.append(True)\n        first = all(rejected)\n        observations.append({'mutation': 'corrupted-compiled-mapping-or-pauli-effect', 'rejected': first})\n\n        # Tamper 2: flip a logical prediction on a known-answer row.\n        outcome = case['backends']['envelope-mle']\n        flipped = outcome['predictions'].copy()\n        unique_row = next(i for i, answers in enumerate(case['allowed_answers']['envelope-mle'])\n                          if len(answers) == 1)\n        flipped[unique_row] ^= 1\n        checked = check_predictions(flipped, [set(a) for a in case['allowed_answers']['envelope-mle']])\n        second = bool(checked['rejected_rows'])\n        observations.append({'mutation': 'flipped-known-answer-prediction', 'rejected': second,\n                             'rejected_rows': checked['rejected_rows']})\n\n        # Tamper 3: remove the multi-loss coverage cases.\n        coverage = {'history_categories': {'no_loss': 1, 'multiple_simultaneous_losses': 0,\n                                           'loss_in_different_rounds': 1, 'reset_restoring_wire': 1},\n                    'noise_channels': list(REQUIRED_CHANNELS),\n                    'circuit_points': [{'case': 'a'}, {'case': 'b'}],\n                    'placeholder_pairs': 1}\n        third = any('multiple_simultaneous_losses' in p\n                    for p in validate_coverage(coverage, []))\n        observations.append({'mutation': 'multi-loss-coverage-removed', 'rejected': third})\n\n        # Tamper 4: cached native predictions as both expected and observed.\n        fake_case = {'name': 'cached', 'evidence_level': 'independent-end-to-end',\n                     'expected_answer_source': 'native-cli prediction cache',\n                     'status': 'pass', 'histories': [], 'noise_channels_exercised': [],\n                     'placeholder_pairs': 1, 'detectors': 2}\n        fourth = any('cached native predictions' in p or 'not independently derived' in p\n                     for p in validate_coverage(coverage_ok(), [fake_case]))\n        observations.append({'mutation': 'cached-native-predictions-as-expected', 'rejected': fourth})\n\n    passed = all(o['rejected'] for o in observations)\n    print(json.dumps({'self_test_mutations': observations}, indent=2))\n    if passed:\n        print('PASS envelope readiness correctness self-test')\n        return 0\n    print('FAIL envelope readiness correctness self-test: a mutation was not rejected', file=sys.stderr)\n    return 1\n\n\ndef coverage_ok():\n    return {'history_categories': {category: 1 for category in REQUIRED_HISTORY_CATEGORIES},\n            'noise_channels': list(REQUIRED_CHANNELS),\n            'circuit_points': [{'case': 'a'}, {'case': 'b'}],\n            'placeholder_pairs': 1}\n\n\ndef main():\n    parser = argparse.ArgumentParser(description=__doc__)\n    parser.add_argument('--binary', type=Path, default=ROOT/'target/release/rustqec')\n    parser.add_argument('--matrix', type=Path, default=MATRIX_PATH)\n    parser.add_argument('--profile', default='smoke', choices=sorted(PROFILES))\n    parser.add_argument('--out', type=Path)\n    parser.add_argument('--self-test', action='store_true')\n    args = parser.parse_args()\n    binary = args.binary.resolve()\n    require(binary.is_file(), f'missing binary: {binary}')\n    if args.self_test:\n        raise SystemExit(self_test(binary))\n    result = run_suite(binary, args.matrix, args.profile, args.out)\n    if result['status'] == 'pass':\n        checked = result['coverage']['checked_rows']\n        print(f\"{PASS_LINE} cases={len(result['cases'])} rows={result['coverage']['total_rows']} \"\n              f\"checked_rows={checked}\")\n        raise SystemExit(0)\n    print('FAIL envelope readiness correctness', file=sys.stderr)\n    for problem in result['problems']:\n        print('  - ' + str(problem), file=sys.stderr)\n    raise SystemExit(1)\n\n\nif __name__ == '__main__':\n    main()\n",
    "benchmarks/atom_loss/readiness_resources.py": "\"\"\"Operating-envelope measurements for the proposed envelope decoder domain (issue #715).\n\nMeasures the real CLI on declared corpora: batch scale, loss rates, repeated\npatterns and genuine cache eviction, peak process memory, compile/decode time\nand completed/attempted shots \u2014 Matching and MLE independently \u2014 plus the\nexact failure semantics (candidate-limit rejection, solve timeout, infeasible,\npre-existing outputs). A declared stress budget is recorded before the stress\nrun; recommendations are workload/machine-specific, never universal latency\nguarantees.\n\nSmoke (a few minutes after build):\n\n    python3 -m benchmarks.atom_loss.readiness_resources \\\n      --binary target/release/rustqec \\\n      --matrix docs/envelope-support.json \\\n      --profile smoke --out drafts/envelope-readiness/resources.json\n\nFull campaign (writes the versioned retained report):\n\n    python3 -m benchmarks.atom_loss.readiness_resources \\\n      --binary target/release/rustqec \\\n      --matrix docs/envelope-support.json \\\n      --profile full --out benchmarks/atom_loss/readiness/resources\n\nVerify the retained report (fast):\n\n    python3 -m benchmarks.atom_loss.readiness_resources \\\n      --verify benchmarks/atom_loss/readiness/resources/manifest.json\n\"\"\"\nfrom .shot_data import require\nimport argparse\nimport json\nimport os\nfrom pathlib import Path\nimport platform\nimport resource\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nimport time\nimport numpy as np\n\nfrom . import chain_reference, decoder_reference\nfrom .output_rules import evaluate_run\nfrom .run import ROOT, save, digest\n\nSCHEMA = 'rustqec.envelope-readiness-resources.v1'\nMANIFEST_SCHEMA = 'rustqec.envelope-resources-manifest.v1'\nPASS_LINE = 'PASS envelope operating envelope'\nFIXTURE_D3R2 = ROOT/'benchmarks/atom_loss/fixtures/midswap_d3_r2.stim'\nCONVENTIONAL = ROOT/'rustqec-cli/tests/fixtures/current_rstim_atom_loss/conventional'\nMATRIX_PATH = ROOT/'docs/envelope-support.json'\nRESOURCES_DIR = ROOT/'benchmarks/atom_loss/readiness/resources'\n\nMINI_CIRCUIT = (\n    \"QUBIT_COORDS(0,0) 0\\nQUBIT_COORDS(1,0) 1\\nR 0 1\\nTICK[rstim:logical_flip_point]\\n\"\n    \"X_ERROR(0.1) 0\\nX_ERROR(0.01) 1\\nLOSS(0.1) 0\\nH 0\\nH 0\\nCX 0 1\\nX_ERROR(0.02) 0\\n\"\n    \"LOSS(0.1) 1\\nML 0 1\\nDETECTOR(0,0,0) rec[-3]\\nDETECTOR(1,0,0) rec[-1]\\n\"\n    \"OBSERVABLE_INCLUDE(0) rec[-3]\\n\")\nINFEASIBLE_CIRCUIT = MINI_CIRCUIT.replace(\"X_ERROR(0.01) 1\\n\", \"\").replace(\"X_ERROR(0.02) 0\\n\", \"\")\n\n# Declared stress budgets, chosen and recorded before any stress run.\nBUDGETS = {\n    'smoke': {'per_case_wall_seconds': 240, 'total_wall_seconds': 1200,\n              'peak_rss_bytes': 2 * 1024**3},\n    'full': {'per_case_wall_seconds': 900, 'total_wall_seconds': 3600,\n             'peak_rss_bytes': 4 * 1024**3},\n}\n\nBATCH_SIZES_FULL = (1024, 16384, 65536)\nLOSS_RATES_FULL = (0.002, 0.02, 0.1)\n\nEXCLUSIONS_FULL = [\n    {'case': 'mle-d3r2-p020/p100-batches',\n     'reason': 'ILP model build+solve per distinct loss pattern (~1.4e-1 s each on the reference '\n               'machine) times tens of thousands of patterns exceeds the declared stress budget; '\n               'no timing is invented for these omitted points'},\n    {'case': 'mle-scale-beyond-d3r2-real-circuits',\n     'reason': 'larger real circuits widen the ILP model per pattern; only the synthetic 24-wire '\n               'eviction corpus is measured at scale for MLE in this campaign'},\n    {'case': 'matching-batches-above-65536',\n     'reason': 'not measured in this campaign; the recommended range stops at the largest '\n               'measured successful batch'},\n]\n\n\ndef checkout_revision():\n    try:\n        result = subprocess.run(['git', 'rev-parse', 'HEAD'], capture_output=True,\n                                text=True, cwd=ROOT, check=False)\n    except OSError:\n        return None\n    return result.stdout.strip() or None\n\n\ndef machine_identity():\n    memory = None\n    if sys.platform == 'darwin':\n        try:\n            memory = int(subprocess.run(['sysctl', '-n', 'hw.memsize'],\n                                        capture_output=True, text=True).stdout.strip())\n        except (ValueError, OSError):\n            memory = None\n    elif Path('/proc/meminfo').exists():\n        for line in Path('/proc/meminfo').read_text().splitlines():\n            if line.startswith('MemTotal'):\n                memory = int(line.split()[1]) * 1024\n    return {'platform': platform.platform(), 'machine': platform.machine(),\n            'python': platform.python_version(), 'cpu_count': os.cpu_count(),\n            'memory_bytes': memory}\n\n\ndef build_identity(binary):\n    version = subprocess.run([str(binary), '--version'], capture_output=True, text=True).stdout.strip()\n    capabilities = subprocess.run([str(binary), 'capabilities', '--format', 'json'],\n                                  capture_output=True, text=True)\n    decoders = []\n    if capabilities.returncode == 0:\n        commands = json.loads(capabilities.stdout)['commands']\n        decode = next((c for c in commands if c.get('name') == 'decode'), {})\n        decoders = list(decode.get('decoders', []))\n    return {'path': str(binary), 'sha256': digest(binary), 'version': version,\n            'advertised_decoders': decoders}\n\n\ndef rss_watermark():\n    \"\"\"Cumulative maximum resident set over finished child processes, in bytes.\"\"\"\n    usage = resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss\n    return int(usage if sys.platform == 'darwin' else usage * 1024)\n\n\ndef run_cli(argv, work, timeout=1800):\n    start = time.perf_counter()\n    result = subprocess.run([str(a) for a in argv], capture_output=True, text=True,\n                            cwd=work, timeout=timeout, check=False)\n    return result, time.perf_counter() - start, rss_watermark()\n\n\ndef generate_corpus(binary, work, *, circuit_text, circuit_name, shots, seed):\n    \"\"\"Sample rows with the native sampler and package a public decoder dataset.\"\"\"\n    circuit_path = work/(circuit_name + '.stim')\n    circuit_path.write_text(circuit_text)\n    sample_out = work/(circuit_name + '.01')\n    result = subprocess.run([str(binary), 'circuit', 'sample', '--in', str(circuit_path),\n                             '--shots', str(shots), '--seed', str(seed),\n                             '--out', str(sample_out), '--out-format', '01'],\n                            capture_output=True, text=True, check=False)\n    require(result.returncode == 0, f'sampling failed for {circuit_name}: {result.stderr.strip()}')\n    rows = np.array([[int(x) for x in line]\n                     for line in sample_out.read_text().splitlines()], dtype=np.uint8)\n    require(rows.shape == (shots, rows.shape[1]), f'{circuit_name}: sampled row count mismatch')\n    circuit, probes = chain_reference.normalized(circuit_text)\n    require(rows.shape[1] == circuit.num_measurements,\n            f'{circuit_name}: sampler/native layout mismatch')\n    public = work/(circuit_name + '-public')\n    chain_reference.write_bundle(public, circuit_text, rows, circuit)\n    flags = [p['flag'] for p in probes]\n    patterns = {tuple(np.flatnonzero(row[flags])) for row in rows}\n    return public, {'shots': int(shots), 'seed': seed, 'rows_sha256':\n                    __import__('hashlib').sha256(rows.tobytes()).hexdigest(),\n                    'distinct_patterns_in_corpus': len(patterns),\n                    'sampler': f'rustqec circuit sample --shots {shots} --seed {seed} (workload generation)'}\n\n\ndef generated_circuit(binary, work, distance, rounds, loss):\n    path = work/f'midswap_d{distance}_r{rounds}_p{loss}.stim'\n    result = subprocess.run([str(binary), 'circuit', 'gen', '--code', 'surface_code', '--task',\n                             'rotated_memory_z_midswap', '--distance', str(distance),\n                             '--rounds', str(rounds), '--noise', '0.001',\n                             '--operation-loss-probability', str(loss),\n                             '--measurement-loss-probability', str(loss),\n                             '--before-measure-flip-probability', '0.001',\n                             '--after-reset-flip-probability', '0.001',\n                             '--out', str(path)], capture_output=True, text=True, check=False)\n    require(result.returncode == 0, f'circuit gen failed: {result.stderr.strip()}')\n    return path.read_text(), (f'rustqec circuit gen --task rotated_memory_z_midswap '\n                              f'--distance {distance} --rounds {rounds} --noise 0.001 '\n                              f'--operation-loss-probability {loss} '\n                              f'--measurement-loss-probability {loss} '\n                              f'--before-measure-flip-probability 0.001 '\n                              f'--after-reset-flip-probability 0.001')\n\n\ndef synthetic_eviction_corpus(work, name):\n    \"\"\"Deterministic corpus that forces real FIFO cache eviction.\n\n    200 repeats of the empty pattern (cache hits), then 1,401 distinct loss\n    patterns (24 singles + 276 pairs + 1,100 triples > the 1,024-artifact\n    cache bound), then the empty pattern once more: it was evicted meanwhile,\n    so the final shot must rebuild it (builds > distinct patterns).\n    \"\"\"\n    import hashlib\n    import itertools\n    text = decoder_reference.circuit_for(24)\n    circuit, probes = chain_reference.normalized(text)\n    flags = [p['flag'] for p in probes]\n    patterns = ([()] * 200 + [(i,) for i in range(24)]\n                + list(itertools.combinations(range(24), 2))\n                + list(itertools.combinations(range(24), 3))[:1100] + [()])\n    rows = np.zeros((len(patterns), circuit.num_measurements), dtype=np.uint8)\n    for row, pattern in zip(rows, patterns):\n        for index in pattern:\n            row[flags[index]] = 1\n    public = work/(name + '-public')\n    chain_reference.write_bundle(public, text, rows, circuit)\n    return public, {'shots': len(patterns), 'seed': None,\n                    'rows_sha256': hashlib.sha256(rows.tobytes()).hexdigest(),\n                    'distinct_patterns_in_corpus': 1401,\n                    'sampler': 'deterministic synthetic loss-flag patterns on '\n                               'decoder_reference.circuit_for(24); engineered to exceed the '\n                               '1024-artifact cache bound and force an eviction rebuild'}\n\n\ndef measure_case(binary, work, case):\n    \"\"\"Execute one workload case and return its raw observation record.\"\"\"\n    if case.get('corpus') == 'synthetic-eviction':\n        public, corpus = synthetic_eviction_corpus(work, case['id'])\n    else:\n        public, corpus = generate_corpus(binary, work, circuit_text=case['circuit_text'],\n                                         circuit_name=case['id'], shots=case['shots'],\n                                         seed=case['seed'])\n    out = work/(case['id'] + '.b8')\n    stats_out = work/(case['id'] + '.json')\n    argv = [binary, 'decode', '--decoder', case['decoder'], '--dataset', public,\n            '--out', out, '--stats-out', stats_out]\n    if case.get('shot_timeout_ms') is not None:\n        argv += ['--shot-timeout-ms', str(case['shot_timeout_ms'])]\n    result, wall, peak = run_cli(argv, work)\n    require(result.returncode == 0,\n            f\"{case['id']}: decode failed: {result.stderr.strip() or result.stdout.strip()}\")\n    stats = json.loads(stats_out.read_text())\n    predictions = out.read_bytes()\n    builds = stats['matching_graph_builds'] if case['decoder'] == 'envelope-matching' \\\n        else stats['mle_model_builds']\n    distinct = stats['distinct_loss_patterns']\n    record = {\n        'id': case['id'], 'decoder': case['decoder'], 'kind': case['kind'],\n        'expected': {'outcome': 'success'},\n        'circuit': {'source': case['source'], 'sha256':\n                    __import__('hashlib').sha256(case['circuit_text'].encode()).hexdigest()},\n        'loss_rate': case.get('loss_rate'), 'shots': corpus['shots'], 'seed': corpus['seed'],\n        'corpus': corpus,\n        'exit_code': result.returncode, 'wall_seconds': wall, 'peak_rss_watermark_bytes': peak,\n        'compile_seconds': stats['compile_seconds'], 'decode_seconds': stats['decode_seconds'],\n        'attempted_shots': stats['attempted_shot_count'], 'completed_shots': stats['shot_count'],\n        'observed_pattern_count': distinct,\n        'distinct_loss_patterns_exact': stats['distinct_loss_patterns_exact'],\n        'cache': {'builds': builds, 'hits': stats['cache_hits'],\n                  'eviction_rebuilds_observed': max(0, builds - distinct)},\n        'timeout_count': stats['timeout_count'], 'infeasible_shot_count': stats['infeasible_shot_count'],\n        'predictions': {'installed': True, 'sha256': __import__('hashlib').sha256(predictions).hexdigest(),\n                        'bytes': len(predictions)},\n        'stats_written': True,\n    }\n    record['output_rule_problems'] = evaluate_run(record)\n    return record\n\n\ndef mini_dataset(work, circuit_text, shots_hex):\n    import hashlib\n    dataset = work/f'mini-dataset-{abs(hash((circuit_text, shots_hex))) % 10**8}'\n    dataset.mkdir(exist_ok=True)\n    (dataset/'circuit.stim').write_text(circuit_text)\n    shots = bytes.fromhex(shots_hex)\n    (dataset/'shots.b8').write_bytes(shots)\n    csha = hashlib.sha256(circuit_text.encode()).hexdigest()\n    ssha = hashlib.sha256(shots).hexdigest()\n    bits = 4\n    identity = (f'format=rstim_decoder_dataset\\nschema_version=1\\nmode=measurements_blinded\\n'\n                f'circuit_sha256={csha}\\nshots={len(shots)}\\nrow_bits={bits}\\nshots_b8_sha256={ssha}\\n')\n    save(dataset/'manifest.json', {\n        'format': 'rstim_decoder_dataset', 'schema_version': 1,\n        'dataset_id': hashlib.sha256(identity.encode()).hexdigest(),\n        'mode': 'measurements_blinded', 'shots': len(shots),\n        'row': {'kind': 'measurements', 'bits': bits, 'encoding': 'b8',\n                'bit_order': 'lsb_first', 'bytes_per_shot': 1},\n        'circuit': {'file': 'circuit.stim', 'sha256': csha, 'measurements': 4,\n                    'detectors': 2, 'observables': 1, 'sweep_bits': 0},\n        'shots_file': {'file': 'shots.b8', 'sha256': ssha, 'bits': bits, 'bytes_per_shot': 1}})\n    return dataset\n\n\ndef failure_cases(binary, work):\n    \"\"\"Real-CLI failure-semantics controls shared by both profiles.\"\"\"\n    records = []\n\n    def run_failure(case_id, decoder, dataset, expected, extra=(), pre_existing=False):\n        out = work/(case_id + '.b8')\n        stats_out = work/(case_id + '.json')\n        stale = b'\\x00' * 7\n        if pre_existing:\n            out.write_bytes(stale)\n            stats_out.write_text('{}\\n')\n        before = out.read_bytes() if pre_existing else None\n        argv = [binary, 'decode', '--decoder', decoder, '--dataset', dataset,\n                '--out', out, '--stats-out', stats_out, *extra]\n        result, wall, peak = run_cli(argv, work)\n        error = {}\n        if result.stderr.strip():\n            try:\n                error = json.loads(result.stderr).get('error', {})\n            except json.JSONDecodeError:\n                error = {}\n        stats = json.loads(stats_out.read_text()) if stats_out.is_file() and not pre_existing else None\n        if stats_out.is_file() and pre_existing and result.returncode == 0:\n            stats = json.loads(stats_out.read_text())\n        record = {\n            'id': case_id, 'decoder': decoder, 'kind': 'failure-semantics',\n            'expected': expected, 'shots': expected.get('declared_shots', 0),\n            'exit_code': result.returncode, 'error_code': error.get('code'),\n            'error_message': error.get('message', ''), 'wall_seconds': wall,\n            'peak_rss_watermark_bytes': peak,\n            'completed_shots': 0 if result.returncode else (stats or {}).get('shot_count', 0),\n            'attempted_shots': (stats or {}).get('attempted_shot_count', 0),\n            'compile_seconds': (stats or {}).get('compile_seconds'),\n            'predictions': {\n                'installed': out.is_file(),\n                'pre_existing': pre_existing,\n                'unchanged': pre_existing and out.is_file() and out.read_bytes() == before,\n            },\n            'stats_written': stats is not None,\n            'stats': stats,\n        }\n        record['output_rule_problems'] = evaluate_run(record)\n        records.append(record)\n        return record\n\n    run_failure('fail-mle-candidate-limit', 'envelope-mle', CONVENTIONAL,\n                {'outcome': 'rejection', 'exit_code': 2, 'error_code': 'unsupported_circuit',\n                 'stats_written': False},\n                extra=['--shot-timeout-ms', '2000'])\n    timeout_record = run_failure(\n        'fail-mle-solve-timeout', 'envelope-mle', mini_dataset(work, MINI_CIRCUIT, '02010100'),\n        {'outcome': 'rejection', 'exit_code': 3, 'error_code': 'decode_timeout',\n         'stats_written': True, 'declared_shots': 4},\n        extra=['--shot-timeout-ms', '0'])\n    # Compilation is outside the per-shot timeout: the diagnostic stats carry a\n    # completed compile phase and exactly one attempted shot.\n    stats = timeout_record['stats'] or {}\n    timeout_record['compilation_outside_timeout'] = bool(\n        stats.get('compile_seconds') is not None and stats.get('attempted_shot_count') == 1\n        and stats.get('timeout_count') == 1)\n    run_failure('fail-mle-infeasible', 'envelope-mle', mini_dataset(work, INFEASIBLE_CIRCUIT, '08'),\n                {'outcome': 'rejection', 'exit_code': 3, 'error_code': 'decode_infeasible',\n                 'stats_written': True, 'declared_shots': 1})\n    run_failure('fail-stale-output-overwrite', 'envelope-matching',\n                mini_dataset(work, MINI_CIRCUIT, '02010100'),\n                {'outcome': 'rejection', 'exit_code': 2, 'error_code': 'output_error',\n                 'stats_written': False},\n                pre_existing=True)\n    return records\n\n\ndef case_matrix(binary, work, profile):\n    \"\"\"Declared finite measurement matrix; nothing is measured outside it.\"\"\"\n    cases = []\n    if profile == 'smoke':\n        plan = [\n            ('matching-eviction-wires24', 'envelope-matching', 'cache-eviction', None, None, None, None, None),\n            ('matching-d3r2-p002-b1024', 'envelope-matching', 'repeated-patterns', 3, 2, 0.002, 1024, 715_102),\n            ('matching-d3r2-p100-b4096', 'envelope-matching', 'batch-scale', 3, 2, 0.1, 4096, 715_101),\n            ('mle-eviction-wires24', 'envelope-mle', 'cache-eviction', None, None, None, None, None),\n            ('mle-d3r2-p002-b1024', 'envelope-mle', 'repeated-patterns', 3, 2, 0.002, 1024, 715_104),\n        ]\n    else:\n        plan = []\n        for loss in LOSS_RATES_FULL:\n            for batch in BATCH_SIZES_FULL:\n                plan.append((f'matching-d3r2-p{int(loss*1000):03d}-b{batch}', 'envelope-matching',\n                             'batch-scale',\n                             3, 2, loss, batch, 715_200 + int(loss*1000)*10 + batch % 997))\n        plan.append(('matching-d3r3-p020-b16384', 'envelope-matching', 'circuit-scale',\n                     3, 3, 0.02, 16384, 715_301))\n        plan.append(('matching-d5r3-p020-b16384', 'envelope-matching', 'circuit-scale',\n                     5, 3, 0.02, 16384, 715_302))\n        plan.append(('matching-eviction-wires24', 'envelope-matching', 'cache-eviction',\n                     None, None, None, None, None))\n        plan.append(('mle-d3r2-p002-b1024', 'envelope-mle', 'repeated-patterns',\n                     3, 2, 0.002, 1024, 715_401))\n        plan.append(('mle-d3r2-p002-b16384', 'envelope-mle', 'repeated-patterns',\n                     3, 2, 0.002, 16384, 715_402))\n        plan.append(('mle-eviction-wires24', 'envelope-mle', 'cache-eviction',\n                     None, None, None, None, None))\n    for case_id, decoder, kind, distance, rounds, loss, shots, seed in plan:\n        if distance is None:\n            text = decoder_reference.circuit_for(24)\n            source = 'benchmarks.atom_loss.decoder_reference.circuit_for(24)'\n            cases.append({'id': case_id, 'decoder': decoder, 'kind': kind,\n                          'circuit_text': text, 'source': source, 'loss_rate': None,\n                          'corpus': 'synthetic-eviction'})\n            continue\n        text, source = generated_circuit(binary, work, distance, rounds, loss)\n        cases.append({'id': case_id, 'decoder': decoder, 'kind': kind,\n                      'circuit_text': text, 'source': source, 'loss_rate': loss,\n                      'shots': shots, 'seed': seed})\n    return cases\n\n\ndef recommended_ranges(records):\n    \"\"\"Derived strictly from successful measurements; verify recomputes these.\"\"\"\n    def successful(decoder):\n        return [r for r in records if r['decoder'] == decoder and r['kind'] != 'failure-semantics'\n                and r['exit_code'] == 0 and not r['output_rule_problems']]\n    matching, mle = successful('envelope-matching'), successful('envelope-mle')\n    return {\n        'basis': 'workload- and machine-specific measurements in this manifest; not universal '\n                 'latency guarantees; hard code limits are listed separately',\n        'envelope-matching': {\n            'max_shots_per_batch': max(r['shots'] for r in matching),\n            'max_loss_rate_measured': max(r['loss_rate'] for r in matching\n                                          if r['loss_rate'] is not None),\n            'circuits_measured': sorted({r['circuit']['source'] for r in matching}),\n            'scale_note': 'decode stays near-linear in shots at fixed pattern count; cache '\n                          'eviction rebuilds were measured and remained within budget'},\n        'envelope-mle': {\n            'max_shots_per_batch': max(r['shots'] for r in mle),\n            'max_loss_rate_measured': max(r['loss_rate'] for r in mle\n                                          if r['loss_rate'] is not None),\n            'circuits_measured': sorted({r['circuit']['source'] for r in mle}),\n            'scale_note': 'cost is dominated by ILP build+solve per distinct loss pattern; use '\n                          '--shot-timeout-ms so a slow pattern stops the batch with decode_timeout '\n                          'instead of running unbounded'},\n        'hard_code_limits': {\n            'max_envelope_candidates': 100_000, 'max_primitive_probes': 100_000,\n            'max_primitive_symptom_terms': 10_000_000,\n            'max_conditioned_decoder_artifacts': 1024,\n            'observables': '1..=64', 'sweep_bits': 0,\n        },\n    }\n\n\ndef run_campaign(binary, matrix_path, profile, out_path):\n    matrix = json.loads(Path(matrix_path).read_text())\n    require(matrix.get('schema_version') == 'rustqec.envelope-support.v1',\n            'resources campaign requires the envelope support matrix schema')\n    budget = dict(BUDGETS[profile])\n    started = time.perf_counter()\n    budget_note = {'declared_before_run': True, 'values': budget}\n    records = []\n    with tempfile.TemporaryDirectory(prefix=f'envelope-resources-{profile}-') as tmp:\n        work = Path(tmp)\n        cases = case_matrix(binary, work, profile)\n        for case in cases:\n            records.append(measure_case(binary, work, case))\n        records += failure_cases(binary, work)\n    total_wall = time.perf_counter() - started\n    problems = []\n    for record in records:\n        problems += [f\"{record['id']}: {p}\" for p in record['output_rule_problems']]\n        if record['wall_seconds'] > budget['per_case_wall_seconds']:\n            problems.append(f\"{record['id']}: wall {record['wall_seconds']:.1f}s exceeds budget\")\n        if record['peak_rss_watermark_bytes'] > budget['peak_rss_bytes']:\n            problems.append(f\"{record['id']}: peak RSS exceeds budget\")\n    if total_wall > budget['total_wall_seconds']:\n        problems.append(f'total wall {total_wall:.1f}s exceeds budget')\n    eviction = [r for r in records if r['kind'] == 'cache-eviction']\n    if not eviction or any(r['cache']['eviction_rebuilds_observed'] <= 0 for r in eviction):\n        problems.append('cache-eviction case(s) recorded no eviction; coverage validation failed')\n    repeated = [r for r in records if r['kind'] == 'repeated-patterns']\n    if not repeated or any(r['cache']['hits'] <= 0 for r in repeated):\n        problems.append('repeated-pattern case(s) recorded no cache hits')\n    result = {\n        'schema_version': SCHEMA,\n        'profile': profile,\n        'checkout_revision': checkout_revision(),\n        'generated_at': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),\n        'machine': machine_identity(),\n        'build': build_identity(binary),\n        'matrix': {'path': str(matrix_path), 'sha256': digest(Path(matrix_path)),\n                   'source_revision': matrix.get('applies_to', {}).get('source_revision')},\n        'stress_budget': budget_note,\n        'total_wall_seconds': total_wall,\n        'cases': records,\n        'exclusions': EXCLUSIONS_FULL if profile == 'full' else [],\n        'recommended': recommended_ranges(records),\n        'problems': problems,\n        'status': 'pass' if not problems else 'fail',\n    }\n    if profile == 'full':\n        write_retained_report(result, out_path)\n    else:\n        save(out_path, result)\n    return result\n\n\ndef write_retained_report(result, out_dir):\n    \"\"\"Versioned raw observations + concise report + manifest.\"\"\"\n    out_dir = Path(out_dir)\n    raw_dir = out_dir/'raw'\n    raw_dir.mkdir(parents=True, exist_ok=True)\n    manifest_cases = []\n    for record in result['cases']:\n        raw_name = record['id'] + '.json'\n        save(raw_dir/raw_name, record)\n        manifest_cases.append({\n            'id': record['id'], 'decoder': record['decoder'], 'kind': record['kind'],\n            'loss_rate': record.get('loss_rate'), 'shots': record['shots'],\n            'seed': record.get('seed'), 'exit_code': record['exit_code'],\n            'error_code': record.get('error_code'),\n            'wall_seconds': record['wall_seconds'],\n            'compile_seconds': record.get('compile_seconds'),\n            'decode_seconds': record.get('decode_seconds'),\n            'stats_written': record['stats_written'],\n            'peak_rss_watermark_bytes': record['peak_rss_watermark_bytes'],\n            'observed_pattern_count': record.get('observed_pattern_count'),\n            'cache': record.get('cache'),\n            'completed_shots': record['completed_shots'],\n            'raw': f'raw/{raw_name}', 'raw_sha256': digest(raw_dir/raw_name),\n            'output_rule_problems': record['output_rule_problems'],\n        })\n    manifest = {\n        'schema_version': MANIFEST_SCHEMA,\n        'generated_by': 'python3 -m benchmarks.atom_loss.readiness_resources --profile full',\n        'generated_at': result['generated_at'],\n        'checkout_revision': result.get('checkout_revision'),\n        'machine': result['machine'], 'build': result['build'], 'matrix': result['matrix'],\n        'stress_budget': result['stress_budget'],\n        'total_wall_seconds': result['total_wall_seconds'],\n        'cases': manifest_cases,\n        'exclusions': result['exclusions'],\n        'recommended': result['recommended'],\n        'status': result['status'],\n        'problems': result['problems'],\n    }\n    save(out_dir/'manifest.json', manifest)\n    (out_dir/'report.md').write_text(render_report(manifest), encoding='utf-8')\n    save(out_dir/'report.json', {'sha256': digest(out_dir/'report.md')})\n\n\ndef fmt_bytes(value):\n    return f'{value / 1024**3:.2f} GiB' if value and value >= 1024**3 else f'{value / 1024**2:.1f} MiB'\n\n\ndef render_report(manifest):\n    lines = [\n        '# Envelope decoder operating envelope', '',\n        f\"Measured {manifest['generated_at']} on `{manifest['machine']['platform']}` \"\n        f\"({manifest['machine']['machine']}, {manifest['machine']['cpu_count']} CPUs, \"\n        f\"{fmt_bytes(manifest['machine']['memory_bytes'])}).\",\n        f\"Binary `{manifest['build']['version']}` sha256 `{manifest['build']['sha256'][:16]}\u2026`.\",\n        '',\n        'These are workload- and machine-specific measurements, not universal latency '\n        'guarantees. The stress budget was declared before the run: '\n        f\"per-case wall \u2264 {manifest['stress_budget']['values']['per_case_wall_seconds']} s, \"\n        f\"total \u2264 {manifest['stress_budget']['values']['total_wall_seconds']} s, \"\n        f\"peak RSS \u2264 {fmt_bytes(manifest['stress_budget']['values']['peak_rss_bytes'])}.\", '',\n        '| Case | Decoder | Kind | Loss | Shots | Wall (s) | Compile (s) | Decode (s) | Patterns | Cache builds | Cache hits | Eviction rebuilds | Peak RSS watermark |',\n        '| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |']\n    for case in manifest['cases']:\n        if case['kind'] == 'failure-semantics':\n            continue\n        cache = case['cache'] or {}\n        loss = case['loss_rate'] if case['loss_rate'] is not None else 'synthetic'\n        compile_s = case.get('compile_seconds')\n        decode_s = case.get('decode_seconds')\n        lines.append(\n            f\"| {case['id']} | {case['decoder']} | {case['kind']} | {loss} | {case['shots']} \"\n            f\"| {case['wall_seconds']:.2f} | {compile_s:.3f} | {decode_s:.2f} | {case['observed_pattern_count']} \"\n            f\"| {cache.get('builds')} | {cache.get('hits')} | {cache.get('eviction_rebuilds_observed')} \"\n            f\"| {fmt_bytes(case['peak_rss_watermark_bytes'])} |\")\n    lines += ['', '## Failure semantics (tested against the real CLI)', '',\n              '| Case | Decoder | Exit | Error code | Stats written | Predictions |',\n              '| --- | --- | --- | --- | --- | --- |']\n    for case in manifest['cases']:\n        if case['kind'] != 'failure-semantics':\n            continue\n        lines.append(f\"| {case['id']} | {case['decoder']} | {case['exit_code']} \"\n                     f\"| {case['error_code']} | {'yes' if case['stats_written'] else 'no'} \"\n                     f\"| none installed |\")\n    rec = manifest['recommended']\n    lines += ['', '## Recommended operating ranges (this machine, this workload)', '',\n              '### envelope-matching',\n              f\"- Shots per batch: \u2264 {rec['envelope-matching']['max_shots_per_batch']} measured.\",\n              f\"- Loss rate: \u2264 {rec['envelope-matching']['max_loss_rate_measured']} measured.\",\n              f\"- {rec['envelope-matching']['scale_note']}.\",\n              '', '### envelope-mle',\n              f\"- Shots per batch: \u2264 {rec['envelope-mle']['max_shots_per_batch']} measured.\",\n              f\"- Loss rate: \u2264 {rec['envelope-mle']['max_loss_rate_measured']} measured.\",\n              f\"- {rec['envelope-mle']['scale_note']}.\",\n              '', '### Exact failure semantics',\n              '- Compilation rejection (`unsupported_circuit`, exit 2): neither predictions nor '\n              'statistics are published; compilation is outside `--shot-timeout-ms`.',\n              '- MLE solve timeout (`decode_timeout`, exit 3): diagnostic statistics are written '\n              '(including `compile_seconds`, `attempted_shot_count`, `timeout_count=1`) and no '\n              'prediction file is published; completed shots count as zero.',\n              '- MLE infeasible shot (`decode_infeasible`, exit 3): same output rule as timeout, '\n              'with `infeasible_shot_count=1`.',\n              '- Pre-existing outputs: the CLI refuses to overwrite (`output_error`, exit 2) and '\n              'leaves stale files byte-identical; never read a stale prediction as this run\u2019s '\n              'success. Counts after timeout/infeasible are attempts, never completed shots.',\n              '', '## Exclusions', '']\n    lines += [f\"- {item['case']}: {item['reason']}\" for item in manifest['exclusions']]\n    lines += ['', '## Hard code limits (separate from measurements)', '']\n    for key, value in rec['hard_code_limits'].items():\n        lines.append(f'- `{key}` = {value}')\n    lines.append('')\n    return '\\n'.join(lines)\n\n\ndef verify_manifest(manifest_path):\n    \"\"\"Fast structural + hash + coverage + budget verification of the retained report.\"\"\"\n    manifest_path = Path(manifest_path)\n    manifest = json.loads(manifest_path.read_text())\n    problems = []\n    require(manifest.get('schema_version') == MANIFEST_SCHEMA,\n            f\"unsupported manifest schema: {manifest.get('schema_version')!r}\")\n    root = manifest_path.parent\n    for field in ('machine', 'build', 'stress_budget', 'recommended', 'cases'):\n        if field not in manifest:\n            problems.append(f'manifest missing {field}')\n    if problems:\n        return problems\n    if not manifest['stress_budget'].get('declared_before_run'):\n        problems.append('stress budget was not declared before the run')\n    if not manifest['build'].get('sha256') or not manifest['machine'].get('platform'):\n        problems.append('machine/build identity incomplete')\n    raws = {}\n    for case in manifest['cases']:\n        raw_path = root/case['raw']\n        if not raw_path.is_file():\n            problems.append(f\"{case['id']}: missing raw file {case['raw']}\")\n            continue\n        if digest(raw_path) != case['raw_sha256']:\n            problems.append(f\"{case['id']}: raw file hash mismatch\")\n            continue\n        raws[case['id']] = json.loads(raw_path.read_text())\n    workloads = [c for c in manifest['cases'] if c['kind'] != 'failure-semantics']\n    matching = [c for c in workloads if c['decoder'] == 'envelope-matching']\n    batches = {c['shots'] for c in matching}\n    for required_shots in BATCH_SIZES_FULL:\n        if required_shots not in batches:\n            problems.append(f'missing required shot-count scale point: {required_shots}')\n    rates = {c['loss_rate'] for c in workloads if c['loss_rate'] is not None}\n    if len(rates) < 3:\n        problems.append('fewer than three declared loss rates measured')\n    eviction = [c for c in workloads if c['kind'] == 'cache-eviction']\n    if not eviction:\n        problems.append('no cache-eviction case declared')\n    for case in eviction:\n        raw = raws.get(case['id'], {})\n        if raw.get('cache', {}).get('eviction_rebuilds_observed', 0) <= 0:\n            problems.append(f\"{case['id']}: cache-eviction case recorded no eviction\")\n    repeated = [c for c in workloads if c['kind'] == 'repeated-patterns']\n    for case in repeated:\n        raw = raws.get(case['id'], {})\n        if raw.get('cache', {}).get('hits', 0) <= 0:\n            problems.append(f\"{case['id']}: repeated-pattern case recorded no cache hits\")\n    budget = manifest['stress_budget']['values']\n    # Manifest summary fields that must be identical to the raw record; a\n    # passing summary must never launder an out-of-budget or tampered raw.\n    # Absent fields normalize to None on both sides (the manifest writer uses\n    # record.get), so only genuinely divergent values mismatch.\n    summary_fields = ('decoder', 'kind', 'loss_rate', 'shots', 'seed', 'exit_code',\n                      'error_code', 'compile_seconds', 'decode_seconds', 'stats_written',\n                      'peak_rss_watermark_bytes', 'observed_pattern_count', 'cache',\n                      'completed_shots', 'output_rule_problems')\n    for case in manifest['cases']:\n        if case['wall_seconds'] > budget['per_case_wall_seconds']:\n            problems.append(f\"{case['id']}: measured wall exceeds declared budget\")\n        if case['peak_rss_watermark_bytes'] > budget['peak_rss_bytes']:\n            problems.append(f\"{case['id']}: measured peak RSS exceeds declared budget\")\n        raw = raws.get(case['id'])\n        if raw is not None:\n            problems += [f\"{case['id']}: {p}\" for p in evaluate_run(raw)]\n            if raw['wall_seconds'] != case['wall_seconds']:\n                problems.append(f\"{case['id']}: manifest/raw wall mismatch\")\n            if raw.get('peak_rss_watermark_bytes', 0) > budget['peak_rss_bytes']:\n                problems.append(f\"{case['id']}: raw peak RSS exceeds declared budget\")\n            for field in summary_fields:\n                if raw.get(field) != case.get(field):\n                    problems.append(f\"{case['id']}: manifest/raw {field} mismatch\")\n    if manifest['total_wall_seconds'] > budget['total_wall_seconds']:\n        problems.append('measured total wall exceeds declared budget')\n    # Resource claims must agree with raw measurements.\n    rec = manifest['recommended']\n    for decoder, key in (('envelope-matching', 'envelope-matching'), ('envelope-mle', 'envelope-mle')):\n        successful = [c for c in workloads if c['decoder'] == decoder and c['exit_code'] == 0\n                      and not c['output_rule_problems']]\n        if not successful:\n            problems.append(f'{decoder}: no successful workload cases')\n            continue\n        claim = rec[key]\n        if claim['max_shots_per_batch'] != max(c['shots'] for c in successful):\n            problems.append(f'{decoder}: recommended batch does not match raw measurements')\n        if claim['max_loss_rate_measured'] != max(\n                c['loss_rate'] for c in successful if c['loss_rate'] is not None):\n            problems.append(f'{decoder}: recommended loss rate does not match raw measurements')\n        measured_sources = {raws[c['id']]['circuit']['source'] for c in successful if c['id'] in raws}\n        if set(claim['circuits_measured']) != measured_sources:\n            problems.append(f'{decoder}: recommended circuit list disagrees with raw measurements')\n    failure = {c['id']: c for c in manifest['cases'] if c['kind'] == 'failure-semantics'}\n    for required_case, code in (('fail-mle-candidate-limit', 'unsupported_circuit'),\n                                ('fail-mle-solve-timeout', 'decode_timeout'),\n                                ('fail-mle-infeasible', 'decode_infeasible'),\n                                ('fail-stale-output-overwrite', 'output_error')):\n        case = failure.get(required_case)\n        if case is None:\n            problems.append(f'missing failure-semantics case {required_case}')\n        elif case['error_code'] != code or case['completed_shots'] != 0:\n            problems.append(f'{required_case}: expected {code} with zero completed shots')\n    if manifest.get('status') != 'pass' or manifest.get('problems'):\n        problems.append('manifest does not record a passing campaign')\n    return problems\n\n\ndef self_test(binary):\n    \"\"\"Negative controls: the runner must reject incomplete/tampered/defective reports.\"\"\"\n    require(RESOURCES_DIR.joinpath('manifest.json').is_file(),\n            'self-test requires the retained full report; run --profile full first')\n    observations = []\n    with tempfile.TemporaryDirectory(prefix='envelope-resources-selftest-') as tmp:\n        work = Path(tmp)\n        # Tamper A: drop the largest required shot count.\n        shutil.copytree(RESOURCES_DIR, work/'resources-a')\n        manifest_a = json.loads((work/'resources-a/manifest.json').read_text())\n        removed = [c for c in manifest_a['cases'] if c['shots'] == 65536]\n        manifest_a['cases'] = [c for c in manifest_a['cases'] if c['shots'] != 65536]\n        for case in removed:\n            target = work/'resources-a'/case['raw']\n            if target.is_file():\n                target.unlink()\n        save(work/'resources-a/manifest.json', manifest_a)\n        problems_a = verify_manifest(work/'resources-a/manifest.json')\n        first = any('65536' in p for p in problems_a)\n        observations.append({'mutation': 'largest-shot-count-missing', 'rejected': first,\n                             'detail': problems_a[:2]})\n\n        # Tamper B: inflate a peak-memory result and re-seal the hash.\n        shutil.copytree(RESOURCES_DIR, work/'resources-b')\n        manifest_b = json.loads((work/'resources-b/manifest.json').read_text())\n        target = next(c for c in manifest_b['cases'] if c['kind'] != 'failure-semantics')\n        raw_path = work/'resources-b'/target['raw']\n        raw = json.loads(raw_path.read_text())\n        raw['peak_rss_watermark_bytes'] = BUDGETS['full']['peak_rss_bytes'] * 2\n        save(raw_path, raw)\n        target['peak_rss_watermark_bytes'] = raw['peak_rss_watermark_bytes']\n        target['raw_sha256'] = digest(raw_path)\n        save(work/'resources-b/manifest.json', manifest_b)\n        problems_b = verify_manifest(work/'resources-b/manifest.json')\n        second = any('peak RSS' in p for p in problems_b)\n        observations.append({'mutation': 'tampered-peak-memory', 'rejected': second,\n                             'detail': problems_b[:2]})\n\n        # Tamper C: simulated timeout that installs a truncated prediction file,\n        # wrapped around a real CLI timeout control.\n        timeout_work = work/'timeout'\n        timeout_work.mkdir()\n        dataset = mini_dataset(timeout_work, MINI_CIRCUIT, '02010100')\n        out = timeout_work/'predictions.b8'\n        stats_out = timeout_work/'stats.json'\n        result = subprocess.run([str(binary), 'decode', '--decoder', 'envelope-mle', '--dataset',\n                                 str(dataset), '--out', str(out), '--stats-out', str(stats_out),\n                                 '--shot-timeout-ms', '0'],\n                                capture_output=True, text=True, check=False)\n        real_clean = result.returncode == 3 and not out.exists()\n        stats = json.loads(stats_out.read_text())\n        defective = {\n            'id': 'simulated-timeout-truncated', 'decoder': 'envelope-mle',\n            'kind': 'failure-semantics', 'shots': 4,\n            'expected': {'outcome': 'rejection', 'exit_code': 3, 'error_code': 'decode_timeout',\n                         'stats_written': True},\n            'exit_code': result.returncode, 'error_code': 'decode_timeout',\n            'completed_shots': 0, 'attempted_shots': stats['attempted_shot_count'],\n            'predictions': {'installed': True, 'pre_existing': False,\n                            'sha256': 'truncated', 'bytes': 2},\n            'stats_written': True,\n        }\n        problems_c = evaluate_run(defective)\n        third = real_clean and any('truncated or partial predictions' in p for p in problems_c)\n        observations.append({'mutation': 'timeout-installs-truncated-predictions',\n                             'rejected': third, 'real_cli_clean': real_clean,\n                             'detail': problems_c})\n\n        # Tamper D: cache-eviction case with no eviction recorded.\n        shutil.copytree(RESOURCES_DIR, work/'resources-d')\n        manifest_d = json.loads((work/'resources-d/manifest.json').read_text())\n        target = next(c for c in manifest_d['cases'] if c['kind'] == 'cache-eviction')\n        raw_path = work/'resources-d'/target['raw']\n        raw = json.loads(raw_path.read_text())\n        raw['cache']['eviction_rebuilds_observed'] = 0\n        save(raw_path, raw)\n        target['cache']['eviction_rebuilds_observed'] = 0\n        target['raw_sha256'] = digest(raw_path)\n        save(work/'resources-d/manifest.json', manifest_d)\n        problems_d = verify_manifest(work/'resources-d/manifest.json')\n        fourth = any('no eviction' in p for p in problems_d)\n        observations.append({'mutation': 'cache-eviction-without-eviction', 'rejected': fourth,\n                             'detail': problems_d[:2]})\n\n        # Tamper E: inflate only the raw record's peak memory, reseal its hash,\n        # and leave the manifest summary unchanged (review repro: 100 GiB raw RSS).\n        shutil.copytree(RESOURCES_DIR, work/'resources-e')\n        manifest_e = json.loads((work/'resources-e/manifest.json').read_text())\n        target = next(c for c in manifest_e['cases'] if c['kind'] != 'failure-semantics')\n        raw_path = work/'resources-e'/target['raw']\n        raw = json.loads(raw_path.read_text())\n        raw['peak_rss_watermark_bytes'] = 100 * 1024**3\n        save(raw_path, raw)\n        target['raw_sha256'] = digest(raw_path)\n        save(work/'resources-e/manifest.json', manifest_e)\n        problems_e = verify_manifest(work/'resources-e/manifest.json')\n        fifth = any('raw peak RSS' in p for p in problems_e)\n        observations.append({'mutation': 'raw-only-peak-memory-inflated', 'rejected': fifth,\n                             'detail': problems_e[:2]})\n\n    passed = all(o['rejected'] for o in observations)\n    print(json.dumps({'self_test_mutations': observations}, indent=2))\n    if passed:\n        print('PASS envelope operating envelope self-test')\n        return 0\n    print('FAIL envelope operating envelope self-test: a mutation was not rejected', file=sys.stderr)\n    return 1\n\n\ndef main():\n    parser = argparse.ArgumentParser(description=__doc__)\n    parser.add_argument('--binary', type=Path, default=ROOT/'target/release/rustqec')\n    parser.add_argument('--matrix', type=Path, default=MATRIX_PATH)\n    parser.add_argument('--profile', default='smoke', choices=('smoke', 'full'))\n    parser.add_argument('--out', type=Path)\n    parser.add_argument('--verify', type=Path)\n    parser.add_argument('--self-test', action='store_true')\n    args = parser.parse_args()\n    if args.verify is not None:\n        problems = verify_manifest(args.verify)\n        if not problems:\n            print(f'{PASS_LINE} verify')\n            raise SystemExit(0)\n        print('FAIL envelope operating envelope verify', file=sys.stderr)\n        for problem in problems:\n            print('  - ' + problem, file=sys.stderr)\n        raise SystemExit(1)\n    binary = args.binary.resolve()\n    require(binary.is_file(), f'missing binary: {binary}')\n    if args.self_test:\n        raise SystemExit(self_test(binary))\n    require(args.out is not None, '--out is required for a campaign run')\n    result = run_campaign(binary, args.matrix, args.profile, args.out)\n    if result['status'] == 'pass':\n        print(f\"{PASS_LINE} profile={args.profile} cases={len(result['cases'])} \"\n              f\"wall={result['total_wall_seconds']:.1f}s\")\n        raise SystemExit(0)\n    print('FAIL envelope operating envelope', file=sys.stderr)\n    for problem in result['problems']:\n        print('  - ' + problem, file=sys.stderr)\n    raise SystemExit(1)\n\n\nif __name__ == '__main__':\n    main()\n",
    "benchmarks/atom_loss/reference.py": "\"\"\"Independent persistent-loss lowering to Stim, with no RustQEC imports.\n\nLost wires retain their unobserved quantum state; gates touching them are\nomitted until reset. This is equivalent to tracing out those wires for all\nsurviving-wire observables. LOSS histories remain private to this sampler.\n\"\"\"\nfrom collections import defaultdict\nfrom dataclasses import dataclass\nimport re\nimport numpy as np\nimport stim\n\n\n@dataclass(frozen=True)\nclass Op:\n    name: str\n    args: tuple\n    targets: tuple\n\n\ndef parse(text):\n    lines = iter(text.splitlines())\n    def block(nested=False):\n        result = []\n        for raw in lines:\n            line = raw.split('#', 1)[0].strip()\n            if not line:\n                continue\n            if line == '}':\n                if not nested:\n                    raise ValueError('Unexpected closing brace')\n                return result\n            if line.startswith('REPEAT '):\n                match = re.fullmatch(r'REPEAT (\\d+)\\s*\\{', line)\n                if not match:\n                    raise ValueError(line)\n                body = block(True)\n                result.extend(body * int(match[1]))\n                continue\n            match = re.fullmatch(r'([A-Z_0-9]+)(?:\\[[^\\]]*\\])?(?:\\(([^)]*)\\))?(?:\\s+(.*))?', line)\n            if not match:\n                raise ValueError(line)\n            name, args, targets = match.groups()\n            result.append(Op(name, tuple(float(x) for x in args.split(',')) if args else (), tuple((targets or '').split())))\n        if nested:\n            raise ValueError('Unclosed repeat')\n        return result\n    return block()\n\n\ndef lower(ops, events, *, skip_lost_gates=True):\n    \"\"\"One fixed onset history -> an ordinary Stim circuit, preserving row order.\"\"\"\n    # Assemble text before crossing the Python/C++ boundary. Appending each\n    # instruction through Stim separately dominates this reference's runtime.\n    instructions = []\n    def emit(name, targets, args=()):\n        parameters = '(' + ','.join(map(str, args)) + ')' if args else ''\n        instructions.append(name + parameters + ' ' + ' '.join(map(str, targets)))\n    lost = set()\n    loss_index = 0\n    for op in ops:\n        name, args, targets = op.name, op.args, op.targets\n        if name in {'DETECTOR', 'OBSERVABLE_INCLUDE', 'QUBIT_COORDS', 'SHIFT_COORDS', 'TICK'}:\n            # Sampling measurement rows does not require detector annotations.\n            continue\n        if name == 'LOSS':\n            for target in targets:\n                if events[loss_index]:\n                    lost.add(int(target))\n                loss_index += 1\n            continue\n        if name in {'R', 'RZ'}:\n            for target in targets:\n                q = int(target)\n                emit('R', [q])\n                lost.discard(q)\n            continue\n        if name in {'M', 'MZ', 'MR', 'MRZ', 'ML', 'MZL', 'MRL', 'MRZL'}:\n            if args:\n                raise ValueError('Inline measurement noise is outside the reference subset')\n            for target in targets:\n                inverted = target.startswith('!')\n                q = int(target.lstrip('!'))\n                absent = q in lost\n                if name.endswith('L'):\n                    emit('MPAD', [int(absent)])\n                if absent:\n                    emit('MPAD', [int(not inverted)])\n                    if name.startswith('MR'):\n                        emit('R', [q])\n                else:\n                    emit('MR' if name.startswith('MR') else 'M', ['!' + str(q) if inverted else q])\n                if name.startswith('MR'):\n                    lost.discard(q)\n            continue\n        if name in {'CX', 'CNOT', 'ZCX', 'CZ', 'DEPOLARIZE2'}:\n            if len(targets) % 2:\n                raise ValueError('Unpaired gate')\n            for a, b in zip(targets[::2], targets[1::2]):\n                pair = [int(a), int(b)]\n                if not skip_lost_gates or not lost.intersection(pair):\n                    emit('CX' if name in {'CNOT', 'ZCX'} else name, pair, args)\n            continue\n        if name in {'H', 'S', 'S_DAG', 'X', 'Y', 'Z', 'X_ERROR', 'Y_ERROR', 'Z_ERROR', 'DEPOLARIZE1'}:\n            for target in targets:\n                q = int(target)\n                if q not in lost:\n                    emit(name, [q], args)\n            continue\n        raise ValueError(f'Unsupported reference operation: {name}')\n    if loss_index != len(events):\n        raise ValueError('Loss history width mismatch')\n    return stim.Circuit('\\n'.join(instructions))\n\n\ndef sample(text, shots, seed=7, *, skip_lost_gates=True):\n    ops = parse(text)\n    probabilities = [op.args[0] for op in ops if op.name == 'LOSS' for _ in op.targets]\n    rng = np.random.default_rng(seed)\n    histories = rng.random((shots, len(probabilities))) < probabilities\n    # Grouping only reuses identical physical histories; it never conditions\n    # a decoder on their private onset times.\n    groups = defaultdict(list)\n    for row, history in enumerate(histories):\n        groups[np.packbits(history, bitorder='little').tobytes()].append(row)\n    output = None\n    for packed, indices in groups.items():\n        history = np.unpackbits(np.frombuffer(packed, dtype=np.uint8), bitorder='little')[:len(probabilities)]\n        circuit = lower(ops, history, skip_lost_gates=skip_lost_gates)\n        batch = circuit.compile_sampler(seed=int(rng.integers(0, 2**63))).sample(len(indices))\n        if output is None:\n            output = np.empty((shots, circuit.num_measurements), dtype=np.bool_)\n        output[indices] = batch\n    if output is None:\n        raise ValueError('Positive shots required')\n    return output\n\n\ndef signatures(text, rows):\n    \"\"\"Shared externally observable marginals and small joint observables.\"\"\"\n    ops = parse(text)\n    cursor = 0\n    flags, detectors, observables = [], [], []\n    for op in ops:\n        if op.name in {'M', 'MZ', 'MR', 'MRZ'}:\n            cursor += len(op.targets)\n        elif op.name in {'ML', 'MZL', 'MRL', 'MRZL'}:\n            for _ in op.targets:\n                flags.append(cursor)\n                cursor += 2\n        elif op.name in {'DETECTOR', 'OBSERVABLE_INCLUDE'}:\n            indices = [cursor + int(re.fullmatch(r'rec\\[(-\\d+)\\]', t)[1]) for t in op.targets]\n            parity = np.logical_xor.reduce(rows[:, indices], axis=1)\n            (detectors if op.name == 'DETECTOR' else observables).append(parity)\n    columns = [rows[:, i] for i in flags] + detectors + observables\n    columns += [np.logical_and(a, b) for a, b in zip(columns, columns[1:])]\n    if not columns:\n        columns = list(rows.T)\n    return np.stack(columns, axis=1).mean(axis=0)\n",
    "benchmarks/atom_loss/remeasure.py": "\"\"\"Remeasure decoding on retained, hash-checked corpora without changing samples.\"\"\"\nfrom .shot_data import require\nimport argparse\nfrom datetime import datetime, timezone\nimport importlib.metadata\nimport json\nimport os\nfrom pathlib import Path\nimport platform\nimport shutil\nimport subprocess\nimport sys\nfrom .run import ROOT, cpu_model, decoder_case, digest, save\nfrom .decoder_reference import run as check_decoder\n\n\ndef main():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--corpora', type=Path, required=True)\n    parser.add_argument('--baseline', type=Path, required=True)\n    parser.add_argument('--work', type=Path, required=True)\n    parser.add_argument('--out', type=Path, required=True)\n    args = parser.parse_args()\n    args.work.mkdir(parents=True, exist_ok=False)\n    args.out.mkdir(parents=True, exist_ok=True)\n    binary = ROOT/'target/release/rustqec'\n    exporter = ROOT/'target/release/examples/export_matching_benchmark'\n    from .source_contract import capture\n    capture(args.out, 'timing', {'baseline_sha256': {name: digest(args.baseline/name)\n            for name in ['decoding.json', 'tradeoff.json']},\n            'timing': 'Serial three-repetition decoding remeasurement on retained corpora. Same boundaries as run.py.'})\n    result = check_decoder(binary, exporter)\n    require((result['status']=='PASS'), \"remeasure: result['status']=='PASS'\")\n    save(args.out/'decoder-correctness.json', result)\n    from . import correctness, chain_reference\n    for name,check in [('correctness',lambda:correctness.run(binary)),('chain-correctness',lambda:chain_reference.run(binary,exporter))]:\n        report=check();save(args.out/(name+'.json'),report);require((report['status']=='PASS'), \"remeasure: report['status']=='PASS'\")\n    for filename in ['decoding.json','tradeoff.json']:\n        old = json.loads((args.baseline/filename).read_text())\n        cases = old if isinstance(old,list) else [old]\n        results = []\n        for case in cases:\n            label = f\"d{case['distance']}-p{case['loss_probability']}\" if filename=='decoding.json' else 'tradeoff'\n            source = args.corpora/label\n            for path,key in [('circuit.stim','circuit_sha256'),('public/shots.b8','public_rows_sha256'),('private/answers.b8','answers_sha256')]:\n                require((digest(source/path)==case[key]), f'Corpus mismatch: {label}/{path}')\n            work = args.work/label\n            work.mkdir()\n            shutil.copyfile(source/'circuit.stim',work/'circuit.stim')\n            for kind in ['public','private']:\n                shutil.copytree(source/kind,work/kind)\n            fresh = decoder_case(binary,exporter,work,case['distance'],case['rounds'],case['loss_probability'],\n                                 case['shots'],case['seed'],3,include_mle=filename=='tradeoff.json',reuse=True)\n            for key in ['dataset_id','circuit_sha256','public_rows_sha256','answers_sha256']:\n                require((fresh[key]==case[key]), 'remeasure: fresh[key]==case[key]')\n            for name, previous in case['decoders'].items():\n                current = fresh['decoders'][name]\n                require((current['status']=='ok'), current)\n                require((current['prediction_sha256']==previous['prediction_sha256']), f'Prediction changed: {label}/{name}')\n            fresh['baseline_predictions_unchanged']=True\n            results.append(fresh)\n            save(args.out/filename, results if isinstance(old,list) else fresh)\n            print(f'{label}: all corpus and prediction hashes unchanged; fresh timings complete',flush=True)\n\n\nif __name__=='__main__':\n    main()\n",
    "benchmarks/atom_loss/replay.py": "\"\"\"Re-export each archived corpus with the specified generator, without decoding.\"\"\"\nimport argparse\nimport hashlib\nimport json\nfrom pathlib import Path\nimport tempfile\nimport zipfile\nfrom .run import ROOT, checked, generate, logical_x\nfrom .shot_data import cases_from, validate_dataset\n\n\ndef replay(archive, binary):\n    checked_cases=[]\n    with zipfile.ZipFile(archive) as z, tempfile.TemporaryDirectory() as tmp:\n        cases=([(f\"{c['setting']}-s{c['seed']}\",c) for c in json.loads(z.read('accuracy-seeds.json'))['cases']]\n               if 'accuracy-seeds.json' in z.namelist() else cases_from(z.read))\n        for label,case in cases:\n            read=lambda n:z.read(f'{label}/{n}')\n            validate_dataset(read,case)\n            work=Path(tmp)/label;work.mkdir();circuit=work/'circuit.stim'\n            generate(binary,circuit,case['distance'],case['rounds'],case['loss_probability'],case['pauli_probability'])\n            if circuit.read_bytes()!=read('public/circuit.stim'): raise ValueError('Regenerated circuit mismatch: '+label)\n            generation=json.loads(read('private/manifest.json'))['generation']\n            if generation['batch_shots']!=10000: raise ValueError('Unsupported CLI batch size')\n            checked([binary,'dataset','export','--circuit',circuit,'--shots',case['shots'],\n                     '--seed',case['seed'],\n                     '--mode','measurements_blinded','--logical-x-qubits',logical_x(circuit.read_text(),case['distance']),\n                     '--public-out',work/'public','--private-out',work/'private'])\n            for member in ['public/shots.b8','private/masks.b8','private/answers.b8']:\n                if (work/member).read_bytes()!=read(member): raise ValueError('Regenerated bytes mismatch: '+label+'/'+member)\n            checked_cases.append(label)\n            print(label+': deterministic circuit, public rows, masks and answers match',flush=True)\n    return checked_cases\n\n\nif __name__=='__main__':\n    p=argparse.ArgumentParser();p.add_argument('--archive',type=Path,default=ROOT/'site/static/data/atom-loss/shot-data-v1.zip')\n    p.add_argument('--binary',type=Path,default=ROOT/'target/release/rustqec');args=p.parse_args()\n    print('PASS:',len(replay(args.archive,args.binary)),'corpora')\n",
    "benchmarks/atom_loss/report_contract.py": "\"\"\"Recompute sampling report decisions from complete observations (stdlib only).\n\nKnown probe definitions are the contract; verdicts, thresholds and summaries are\nnot authorities. SciPy produces low-rate intervals/Fisher p-values; this module\nindependently recomputes them for verification without that runtime dependency.\n\"\"\"\nimport math\nfrom functools import lru_cache\nfrom .probe_specs import CASES, KNOWN, noise_specs, distribution_specs, low_specs\nfrom .shot_data import circuit_layout\n\n\ndef require(condition, message):\n    if not condition:\n        raise ValueError('Sampling report contract: '+message)\n\n\ndef integer(value, minimum=0):\n    require(type(value) is int and value>=minimum,'invalid integer observation')\n    return value\n\n\ndef close(value, expected, *, tolerance=1e-12):\n    require(type(value) in [int,float] and math.isfinite(value) and\n            math.isclose(value,expected,rel_tol=tolerance,abs_tol=tolerance),'inconsistent derived number')\n\n\ndef named(records, names):\n    require(isinstance(records,list) and len(records)==len(names),'incomplete case list')\n    require({r['case'] for r in records}==set(names),'duplicate or unknown case')\n    return {r['case']:r for r in records}\n\n\ndef counts(values, size, shots):\n    require(isinstance(values,list) and len(values)==size,'incomplete counts')\n    require(all(type(k) is int and 0<=k<=shots for k in values),'invalid counts')\n    return values\n\n\ndef probabilities(values, size, shots):\n    require(isinstance(values,list) and len(values)==size,'incomplete probabilities')\n    for value in values:\n        require(type(value) in [int,float] and math.isfinite(value) and 0<=value<=1,'invalid probability')\n        close(value*shots,round(value*shots),tolerance=1e-10)\n    close(sum(values),1.)\n    return values\n\n\ndef marginal(joint, bits):\n    return [sum(p for i,p in enumerate(joint) if i&(1<<b)) for b in range(bits)]\n\n\ndef checked_rates(actual, expected, tolerance):\n    return all(abs(a-p)<=tolerance and (p not in [0,1] or a==p) for a,p in zip(actual,expected))\n\n\ndef verdict(record, passed, *, allow_failure=False):\n    require(record['status']==('PASS' if passed else 'FAIL'),'verdict contradicts observations')\n    require(passed or allow_failure,'failed sampling observation')\n\n\n@lru_cache(maxsize=128)\ndef binomial_interval(n,p,tail):\n    \"\"\"Quantiles via normalized PMF recurrence around the mode, avoiding CDF cancellation.\"\"\"\n    if p==0: return [0,0]\n    if p==1: return [n,n]\n    if p>.5:\n        lo,hi=binomial_interval(n,1-p,tail)\n        return [n-hi,n-lo]\n    mode=int((n+1)*p);lower=[];weight=1.;k=mode\n    while k>0 and weight>1e-300:\n        weight*=k/(n-k+1)*(1-p)/p;k-=1;lower.append(weight)\n    weights=list(reversed(lower))+[1.];first=k;weight=1.;k=mode\n    while k<n and weight>1e-300:\n        weight*=(n-k)/(k+1)*p/(1-p);k+=1;weights.append(weight)\n    total=math.fsum(weights)\n    cumulative=0.;lo=None;hi=None\n    for offset,weight in enumerate(weights):\n        cumulative+=weight\n        if lo is None and cumulative>=tail*total: lo=first+offset\n        if cumulative>=(1-tail)*total:\n            hi=first+offset;break\n    require(lo is not None and hi is not None,'binomial quantile did not converge')\n    return [lo,hi]\n\n\ndef fisher_pvalue(a,n,b,m):\n    \"\"\"Two-sided conditional hypergeometric test, summed in log space.\"\"\"\n    successes=a+b;total=n+m\n    low=max(0,successes-m);high=min(n,successes)\n    if low==high:return 1.\n    def choose(top,k):\n        return math.lgamma(top+1)-math.lgamma(k+1)-math.lgamma(top-k+1)\n    denominator=choose(total,successes)\n    def logp(k):return choose(n,k)+choose(m,successes-k)-denominator\n    observed=logp(a)\n    # lgamma subtraction at ~65k introduces ~1e-10 error for equal-probability tails.\n    return min(1.,math.fsum(math.exp(value) for k in range(low,high+1)\n                           if (value:=logp(k))<=observed+1e-8))\n\n\n\ndef verify_noise_cases(records):\n    specs=list(noise_specs());noise=named(records,[s[0] for s in specs])\n    for name,text,columns,expected,channel in specs:\n        case=noise[name];n=integer(case['shots_per_sampler'],32768)\n        require(case['channel']==channel,'wrong channel')\n        tolerance=math.sqrt(math.log(4*len(specs)/4e-7)/(2*n))\n        close(case['expected_probability'],expected);close(case['tolerance'],tolerance)\n        rates=[case[k] for k in ['rust_probability','reference_probability']]\n        for p in rates:probabilities([p,1-p],2,n)\n        verdict(case,checked_rates(rates,[expected]*2,tolerance),allow_failure=True)\n    return [name for name,case in noise.items() if case['status']=='FAIL']\n\ndef verify_distribution_cases(records):\n    specs=distribution_specs();records=named(records,[s['name'] for s in specs])\n    events=sum(len(s['expected'])+len(s['columns']) for s in specs)\n    for spec in specs:\n        case=records[spec['name']];n=integer(case['shots_per_sampler'],32768)\n        expected=spec['expected'];bits=len(spec['columns']);marg=marginal(expected,bits)\n        require(case['channel']==spec['channel'] and case['expected_joint']==expected and case['expected_marginals']==marg,'wrong distribution specification')\n        tolerance=math.sqrt(math.log(4*events/1e-7)/(2*n));close(case['tolerance'],tolerance)\n        passed=True\n        for backend in ['rust','reference']:\n            obs=case[backend];joint=probabilities(obs['joint'],len(expected),n)\n            require(len(obs['marginals'])==bits,'missing marginal')\n            for a,b in zip(obs['marginals'],marginal(joint,bits)):close(a,b)\n            passed &= checked_rates(joint,expected,tolerance) and checked_rates(obs['marginals'],marg,tolerance)\n        verdict(case,passed,allow_failure=True)\n    return [name for name,case in records.items() if case['status']=='FAIL']\n\ndef verify_low_cases(records):\n    specs=low_specs();records=named(records,[s[0] for s in specs]);events=sum(len(p)+len(cols)+1 for _,_,cols,p in specs)\n    for name,text,columns,expected in specs:\n        case=records[name];primitive=.001 if not name.startswith('LOSS') else float(name[5:])\n        n=integer(case['shots_per_sampler'],max(262144,math.ceil(26/primitive)) if name.startswith('LOSS') else 262144)\n        close(case['primitive_probability'],primitive)\n        ps=expected+marginal(expected,len(columns))+[1-expected[0]]\n        require(case['expected_probabilities']==ps,'wrong low-rate probabilities')\n        intervals=[binomial_interval(n,p,1e-7/(4*events)) for p in ps]\n        require(case['accepted_counts']==intervals,'wrong low-rate acceptance interval')\n        require(set(case['counts'])=={'rust','reference'},'missing low-rate backend')\n        passed=True\n        for values in case['counts'].values():\n            values=counts(values,len(ps),n);joint=values[:len(expected)]\n            require(sum(joint)==n,'low-rate histogram incomplete')\n            require(values[len(expected):-1]==marginal(joint,len(columns)) and values[-1]==n-joint[0],'low-rate derived counts inconsistent')\n            passed &= all(lo<=k<=hi for k,(lo,hi) in zip(values,intervals))\n        verdict(case,passed)\n\n\ndef verify_real_comparison(comparison,n):\n    all_names=[f'measurement_{i}' for i in range(50)]+[f'detector_{i}' for i in range(16)]+['observable']+[f'adjacent_detector_joint_{i}' for i in range(15)]\n    expected_names={f'input_{mask}/{group}/{event}' for mask in [0,1] for group,names in [('all',all_names),('no_visible_loss',[f'detector_{i}' for i in range(16)])] for event in names}\n    rows=comparison['events'];require(len(rows)==len(expected_names) and {e['event'] for e in rows}==expected_names,'incomplete real-circuit events')\n    threshold=1e-7/len(rows);close(comparison['threshold'],threshold,tolerance=1e-16)\n    totals={};failed=[]\n    for e in rows:\n        a,native,b,ref=[integer(e[k]) for k in ['rust_events','rust_shots','reference_events','reference_shots']]\n        require(native>0 and ref>0 and a<=native and b<=ref,'invalid Fisher counts')\n        mask,group,_=e['event'].split('/');key=(mask,group)\n        require(totals.setdefault(key,(native,ref))==(native,ref),'inconsistent stratum denominators')\n        p=fisher_pvalue(a,native,b,ref)\n        close(e['pvalue'],p,tolerance=2e-8)\n        if p<threshold:failed.append(e['event'])\n    for backend in [0,1]:\n        require(sum(totals[(f'input_{m}','all')][backend] for m in [0,1])==n,'missing logical-input shots')\n        require(all(totals[(f'input_{m}','no_visible_loss')][backend]<=totals[(f'input_{m}','all')][backend] for m in [0,1]),'invalid conditioned denominator')\n    require(comparison['failed_events']==failed,'stale Fisher verdict')\n    verdict(comparison,not failed,allow_failure=True)\n    return failed\n\ndef verify_sampler(report):\n    close(report['familywise_alpha_bound'],1.2e-6)\n    require(report['negative_skipped_gate_mutation_rejected'] is True and\n            report['unsupported_reference_operation_rejected'] is True,'missing semantic controls')\n    small=named(report['cases'],CASES)\n    for name,text in CASES.items():\n        case=small[name];n=integer(case['shots_per_sampler'],32768)\n        bits=circuit_layout(text)[0];size=1<<bits\n        require(set(case['histogram_counts'])=={'rust','reference'},'missing histogram backend')\n        hist=[counts(case['histogram_counts'][key],size,n) for key in ['rust','reference']]\n        require(all(sum(h)==n for h in hist),'histogram does not cover all shots')\n        tolerance=2*math.sqrt(math.log(4*64*len(CASES)/5e-7)/(2*n))\n        delta=max(abs(a-b)/n for a,b in zip(*hist))\n        known=True\n        if name in KNOWN:\n            target=sum(bit<<i for i,bit in enumerate(KNOWN[name]))\n            known=all(h[target]==n for h in hist)\n        close(case['max_bin_difference'],delta);close(case['tolerance'],tolerance)\n        require(case['known_answer_pass'] is known,'known answer verdict mismatch')\n        verdict(case,delta<=tolerance and known)\n    analytic=report['analytic_noise_controls'];distribution=analytic['distribution_probes']\n    low=report['low_probability_controls'];unit=low['analytic']\n    close(analytic['familywise_alpha_bound'],5e-7);close(distribution['familywise_alpha_bound'],1e-7)\n    close(low['familywise_alpha_bound'],2e-7);close(unit['familywise_alpha_bound'],1e-7)\n    require(not verify_noise_cases(analytic['cases']),'failed analytic noise observation')\n    require(not verify_distribution_cases(distribution['cases']),'failed channel distribution observation')\n    verify_low_cases(unit['cases'])\n    actual=low['real_circuit'];n=integer(actual['shots_per_sampler'],65536)\n    require(actual['mode']=='measurements_blinded' and actual['pauli_probability']==.001 and actual['loss_probability']==.003,'wrong real-circuit configuration')\n    require(actual['scoring_key_check']=={'status':'PASS','checked_shots':n},'missing scoring key check')\n    close(actual['familywise_alpha_bound'],1e-7)\n    require(not verify_real_comparison(actual['comparison'],n),'failed real-circuit sampling observation')\n    # Top-level PASS cannot override any rejected/missing constituent observation.\n    for r in [actual,unit,low,distribution,analytic,report]:verdict(r,True)\n\n    verify_mutations(analytic,distribution,unit,actual)\n\n\ndef mutation_family(records, names):\n    require(type(records) is dict and set(records)==set(names),'missing mutation family')\n    return records\n\n\ndef mutation_summary(record, failures, field='failed_cases'):\n    require(record.get('rejected') is True and bool(failures),'mutation was not rejected')\n    require(record.get(field)==failures,'mutation summary contradicts observations')\n\n\ndef low_mutation_count(text,kind):\n    # Read the fixed probe/fixture definition independently of the input mutator.\n    import re\n    count=0\n    for line in text.splitlines():\n        match=re.match(r'^\\s*(X_ERROR|Y_ERROR|Z_ERROR|DEPOLARIZE1|DEPOLARIZE2|LOSS)\\(([^)]+)\\)',line)\n        if match and 0<float(match[2])<.01 and (kind=='both' or (match[1]=='LOSS')==(kind=='loss')):\n            count+=1\n    return count\n\n\ndef low_counts_pass(values,case,columns,expected):\n    n=case['shots_per_sampler'];values=counts(values,len(case['expected_probabilities']),n)\n    joint=values[:len(expected)]\n    require(sum(joint)==n,'mutation histogram incomplete')\n    require(values[len(expected):-1]==marginal(joint,len(columns)) and values[-1]==n-joint[0],\n            'mutation derived counts inconsistent')\n    return all(lo<=k<=hi for k,(lo,hi) in zip(values,case['accepted_counts']))\n\n\ndef verify_mutations(analytic,distribution,unit,actual):\n    channels=['X_ERROR','Y_ERROR','Z_ERROR','DEPOLARIZE1','DEPOLARIZE2']\n    noise=mutation_family(analytic['channel_deletion_mutations'],channels)\n    healthy={r['case']:r for r in analytic['cases']}\n    for channel,record in noise.items():\n        observations=record.get('observations')\n        failures=verify_noise_cases(observations)\n        for observed in observations:\n            base=healthy[observed['case']]\n            require(observed['shots_per_sampler']==base['shots_per_sampler'] and\n                    observed['reference_probability']==base['reference_probability'],\n                    'mutation changed independent noise reference')\n            if observed['channel']!=channel:\n                require(observed==base,'noise deletion changed an unrelated probe')\n        mutation_summary(record,failures)\n\n    replacements=['DEPOLARIZE2_ix_only','DEPOLARIZE2_xi_only','DEPOLARIZE2_independent_x',\n                  'DEPOLARIZE1_x_only','DEPOLARIZE1_z_only']\n    records=mutation_family(distribution['channel_replacement_mutations'],replacements)\n    healthy={r['case']:r for r in distribution['cases']}\n    for name,record in records.items():\n        observations=record.get('observations')\n        failures=verify_distribution_cases(observations)\n        for observed in observations:\n            base=healthy[observed['case']]\n            require(observed['shots_per_sampler']==base['shots_per_sampler'] and observed['reference']==base['reference'],\n                    'mutation changed independent distribution reference')\n            if observed['channel']!=name.split('_',1)[0]:\n                require(observed==base,'channel replacement changed an unrelated probe')\n        mutation_summary(record,failures)\n\n    low=mutation_family(unit['low_probability_deletion_mutations'],['pauli','loss','both'])\n    healthy={r['case']:r for r in unit['cases']}\n    for kind,record in low.items():\n        affected={name:(columns,expected,removed) for name,text,columns,expected in low_specs()\n                  if (removed:=low_mutation_count(text,kind))}\n        observations=named(record.get('observations'),affected)\n        failures=[]\n        for name,(columns,expected,removed) in affected.items():\n            observed=observations[name]\n            require(integer(observed['removed_instructions'],1)==removed,'wrong probe mutation instruction count')\n            if not low_counts_pass(observed['counts'],healthy[name],columns,expected):failures.append(name)\n        # These powered probes require every affected case to detect deletion.\n        require(set(failures)==set(affected),'low-rate mutation escaped an affected probe')\n        mutation_summary(record,failures)\n\n    from pathlib import Path\n    text=(Path(__file__).parent/'fixtures/midswap_d3_r2.stim').read_text()\n    records=mutation_family(actual['low_probability_deletion_mutations'],['pauli','loss','both'])\n    reference={e['event']:(e['reference_events'],e['reference_shots']) for e in actual['comparison']['events']}\n    for kind,record in records.items():\n        require(integer(record['removed_instructions'],1)==low_mutation_count(text,kind),\n                'wrong real-circuit mutation instruction count')\n        comparison=record.get('comparison')\n        require(type(comparison) is dict,'missing real-circuit mutation observations')\n        failures=verify_real_comparison(comparison,actual['shots_per_sampler'])\n        require(all((e['reference_events'],e['reference_shots'])==reference[e['event']] for e in comparison['events']),\n                'mutation changed independent real-circuit reference')\n        mutation_summary(record,failures,'failed_events')\n",
    "benchmarks/atom_loss/requirements.txt": "stim==1.16.0\nnumpy==2.4.6\npymatching==2.4.0\nmatplotlib==3.10.9\nscipy==1.18.1\npillow==12.3.0\ncontourpy==1.3.3\ncycler==0.12.1\nfonttools==4.65.0\nkiwisolver==1.5.1\npackaging==26.3\npyparsing==3.3.2\npython-dateutil==2.9.0.post0\nsix==1.17.0\n",
    "benchmarks/atom_loss/run.py": "\"\"\"Reproducible, bounded Mid-SWAP sampling and public-input decoder experiments.\"\"\"\nfrom .shot_data import require\nimport argparse\nfrom collections import OrderedDict\nfrom datetime import datetime, timezone\nimport hashlib\nimport importlib.metadata\nimport json\nimport os\nfrom pathlib import Path\nimport platform\nimport subprocess\nimport sys\nimport time\nimport numpy as np\nimport pymatching\nfrom scipy.sparse import csc_matrix\nfrom .artifacts import native_total, wilson\nfrom . import correctness, reference\nfrom .shot_data import validate_dataset\n\nROOT = Path(__file__).resolve().parents[2]\n\n\ndef save(path, value):\n    path.parent.mkdir(parents=True, exist_ok=True)\n    path.write_text(json.dumps(value, indent=2) + '\\n')\n\n\ndef digest(path):\n    return hashlib.sha256(path.read_bytes()).hexdigest()\n\n\ndef command(args, timeout=300):\n    start = time.perf_counter()\n    try:\n        result = subprocess.run(list(map(str, args)), capture_output=True, text=True, timeout=timeout)\n    except subprocess.TimeoutExpired:\n        result = subprocess.CompletedProcess(args, 124, '', f'Process exceeded {timeout} second limit; no complete accuracy result')\n    return result, time.perf_counter() - start\n\n\ndef checked(args):\n    result, seconds = command(args)\n    if result.returncode:\n        raise RuntimeError(result.stderr + result.stdout)\n    return seconds\n\n\ndef generate(binary, path, distance, rounds, loss, pauli=.001):\n    checked([binary, 'circuit', 'gen', '--code', 'surface_code', '--task', 'rotated_memory_z_midswap',\n             '--distance', distance, '--rounds', rounds, '--noise', pauli,\n             '--operation-loss-probability', loss, '--measurement-loss-probability', loss, '--out', path])\n\n\ndef logical_x(text, distance):\n    # Mid-SWAP initial-layout X string is the left column of data coordinates.\n    coords = [op for op in reference.parse(text) if op.name == 'QUBIT_COORDS']\n    support = [int(op.targets[0]) for op in coords if op.args[0] == 1 and int(op.args[1]) % 2 == 1]\n    if len(support) != distance:\n        raise ValueError('Unexpected initial data layout')\n    return ','.join(map(str, support))\n\n\ndef score(predictions, answers):\n    if predictions.shape != answers.shape or np.any(predictions > 1) or np.any(answers > 1):\n        raise ValueError('Incomplete or invalid prediction rows')\n    errors = int(np.count_nonzero(predictions != answers))\n    return {'errors': errors, 'shots': len(answers), 'logical_error_rate': errors/len(answers),\n            'wilson_95': wilson(errors, len(answers)),\n            'prediction_sha256': hashlib.sha256(predictions.tobytes()).hexdigest()}\n\n\ndef prepare_matching(graph):\n    \"\"\"Build the invariant sparse topology once per measured adapter invocation.\"\"\"\n    edges = graph['edges']\n    detectors, columns, observables, fault_columns = [], [], [], []\n    for column, edge in enumerate(edges):\n        for detector in (edge['u'], edge['v']):\n            if detector is not None:\n                detectors.append(detector)\n                columns.append(column)\n        for observable in edge['observables']:\n            observables.append(observable)\n            fault_columns.append(column)\n    # Match the edge API's detector extent, so out-of-graph fired bits still fail.\n    count = max(detectors, default=-1) + 1\n    fault_count = graph.get('num_observables', max(observables, default=-1) + 1)\n    checks = csc_matrix((np.ones(len(detectors), dtype=np.uint8), (detectors, columns)),\n                        shape=(count, len(edges)))\n    faults = csc_matrix((np.ones(len(observables), dtype=np.uint8), (observables, fault_columns)),\n                        shape=(fault_count, len(edges)))\n    scale = max(1., max((edge['weight'] for edge in edges), default=0.))\n    base = np.array([edge['weight']/scale for edge in edges])\n    conditioned = np.array([edge['loss_factor']*graph['mean_weight']/scale for edge in edges])\n    return checks, faults, base, conditioned\n\n\ndef build_matching(graph, losses, prepared=None):\n    checks, faults, base, conditioned = prepare_matching(graph) if prepared is None else prepared\n    active = list({i for loss in losses for i in graph['loss_edges'][loss]})\n    weights = base.copy()\n    weights[active] = conditioned[active]\n    return pymatching.Matching.from_check_matrix(\n        checks, weights=weights, faults_matrix=faults,\n        merge_strategy='smallest-weight', use_virtual_boundary_node=True)\n\n\ndef python_decode_loop(graph, conditioned):\n    # Identical shot order and at most 1024 FIFO cached patterns. RustQEC also\n    # enforces a work budget; its actual builds/hits are retained for comparison.\n    started = time.perf_counter()\n    prepared = prepare_matching(graph)\n    syndromes = np.asarray(graph['syndromes'], dtype=np.uint8)\n    predictions = np.zeros(len(syndromes), dtype=np.uint8)\n    cache, builds, hits = OrderedDict(), 0, 0\n    for row, (syndrome, loss) in enumerate(zip(syndromes, graph['losses'], strict=True)):\n        key = tuple(loss) if conditioned else ()\n        if key not in cache:\n            if len(cache) == 1024:\n                cache.popitem(last=False)\n            cache[key] = build_matching(graph, key, prepared)\n            builds += 1\n        else:\n            hits += 1\n        matching = cache[key]\n        if np.any(syndrome[matching.num_detectors:]):\n            raise ValueError('Unreachable fired detector')\n        value = matching.decode(syndrome[:matching.num_detectors])\n        predictions[row] = value[0] if len(value) else 0\n    return predictions, {'decode_seconds': time.perf_counter()-started, 'graph_builds': builds, 'cache_hits': hits}\n\n\ndef python_decode(graph, conditioned, batch=True):\n    if not batch:\n        return python_decode_loop(graph, conditioned)\n    started = time.perf_counter()\n    prepared = prepare_matching(graph)\n    topology_seconds = time.perf_counter()-started\n    syndromes = np.asarray(graph['syndromes'], dtype=np.uint8)\n    if len(syndromes) != len(graph['losses']):\n        raise ValueError('Incomplete loss rows')\n    predictions = np.zeros(len(syndromes), dtype=np.uint8)\n    groups = {}\n    for row, losses in enumerate(graph['losses']):\n        groups.setdefault(tuple(losses) if conditioned else (), []).append(row)\n    preprocessing = time.perf_counter()-started-topology_seconds\n    graph_seconds = matching_seconds = output_seconds = 0.\n    for losses, indices in groups.items():\n        stage = time.perf_counter()\n        matching = build_matching(graph, losses, prepared)\n        graph_seconds += time.perf_counter()-stage\n        stage = time.perf_counter()\n        rows = syndromes[indices]\n        if np.any(rows[:, matching.num_detectors:]):\n            raise ValueError('Unreachable fired detector')\n        preprocessing += time.perf_counter()-stage\n        stage = time.perf_counter()\n        values = matching.decode_batch(rows[:, :matching.num_detectors])\n        matching_seconds += time.perf_counter()-stage\n        stage = time.perf_counter()\n        if values.shape[1]:\n            predictions[indices] = values[:, 0]\n        output_seconds += time.perf_counter()-stage\n    elapsed = time.perf_counter()-started\n    return predictions, {'decode_seconds': elapsed,\n                         'topology_seconds': topology_seconds, 'preprocess_seconds': preprocessing, 'graph_build_seconds': graph_seconds,\n                         'matching_seconds': matching_seconds, 'output_seconds': output_seconds,\n                         'adapter_overhead_seconds': elapsed-topology_seconds-preprocessing-graph_seconds-matching_seconds-output_seconds,\n                         'graph_builds': len(groups), 'batch_calls': len(groups),\n                         'graph_api': 'from_check_matrix',\n                         'execution': 'batch grouped by loss pattern' if conditioned else 'batch fixed graph'}\n\n\ndef export_graph(exporter, work, repetition):\n    path = work/f'graph-{repetition}.json'\n    checked([exporter, work/'public', path])\n    return json.loads(path.read_text())\n\n\ndef native_decode(binary, work, decoder, repetition):\n    predictions = work / f'{decoder}-{repetition}.b8'\n    stats = work / f'{decoder}-{repetition}.json'\n    args = [binary, 'decode', '--decoder', decoder, '--dataset', work/'public',\n            '--out', predictions, '--stats-out', stats]\n    if decoder == 'envelope-mle':\n        args += ['--shot-timeout-ms', 500]\n    result, wall = command(args, timeout=300)\n    record = {'status': 'ok' if result.returncode == 0 else 'failed', 'process_wall_seconds': wall,\n              'exit_code': result.returncode}\n    if stats.exists():\n        record['stats'] = json.loads(stats.read_text())\n    if result.returncode:\n        record['error'] = (result.stderr + result.stdout)[-4000:]\n        return None, record\n    return np.frombuffer(predictions.read_bytes(), dtype=np.uint8), record\n\n\ndef measure_offline(exporter, work, rep, answers):\n    name='envelope-matching-offline'\n    graph=export_graph(exporter,work,f'{name}-{rep}')\n    predictions=work/f'{name}-{rep}.b8';stats=work/f'{name}-{rep}.json'\n    result,wall=command([exporter.parent/'offline_matching_benchmark',\n                        work/f'graph-{name}-{rep}.json',predictions,stats])\n    if result.returncode:\n        return {'status':'failed','runs':[{'exit_code':result.returncode,'error':result.stderr}]}\n    batch=json.loads(stats.read_text())\n    record={'status':'ok','exit_code':0,'process_wall_seconds':wall,'batch':batch,\n        'transform_seconds':graph['transform_seconds'],\n        'stats':{'compile_seconds':graph['compile_seconds'],\n                 'decode_seconds':graph['transform_seconds']+batch['decode_seconds'],\n                 'attempted_shot_count':batch['shots'],'timeout_count':0,'infeasible_shot_count':0,\n                 'matching_graph_builds':batch['graph_builds'],'cache_hits':0}}\n    predicted=np.frombuffer(predictions.read_bytes(),dtype=np.uint8)\n    return {'status':'ok','runs':[record],'total_seconds':[native_total(record)],**score(predicted,answers)}\n\n\ndef decoder_case(binary, exporter, work, distance, rounds, loss, shots, seed, repeats, include_mle=False, reuse=False):\n    work.mkdir(parents=True, exist_ok=True)\n    circuit = work/'circuit.stim'\n    if not reuse:\n        generate(binary, circuit, distance, rounds, loss)\n        support = logical_x(circuit.read_text(), distance)\n        checked([binary, 'dataset', 'export', '--circuit', circuit, '--shots', shots, '--seed', seed,\n                 '--mode', 'measurements_blinded', '--logical-x-qubits', support,\n                 '--public-out', work/'public', '--private-out', work/'private'])\n    support = logical_x(circuit.read_text(), distance)\n    public = json.loads((work/'public/manifest.json').read_text())\n    private = json.loads((work/'private/manifest.json').read_text())\n    require((public['dataset_id'] == private['dataset_id'] and public['circuit']['observables'] == 1), \"run: public['dataset_id'] == private['dataset_id'] and public['circuit']['observables'] == 1\")\n    answers = np.frombuffer(validate_dataset(lambda name:(work/name).read_bytes()), dtype=np.uint8)\n    require((len(answers) == shots), 'run: len(answers) == shots')\n    case = {'distance': distance, 'rounds': rounds, 'loss_probability': loss, 'pauli_probability': .001,\n            'shots': shots, 'seed': seed, 'logical_x_support': support, 'dataset_id': public['dataset_id'],\n            'circuit_sha256': digest(circuit), 'public_rows_sha256': digest(work/'public/shots.b8'),\n            'answers_sha256': digest(work/'private/answers.b8'), 'decoders': {}}\n    result, wall = command([exporter, work/'public', work/'graph.json'])\n    if result.returncode:\n        case['export_failure'] = result.stderr[-4000:]\n        return case\n    graph = json.loads((work/'graph.json').read_text())\n    case['graph'] = {k: graph[k] for k in ['source','compile_seconds','transform_seconds','num_observables']}\n    case['graph'].update(edges=len(graph['edges']), detectors=public['circuit']['detectors'],\n                         loss_patterns=len(set(map(tuple, graph['losses']))))\n    names = ['envelope-matching', 'pymatching-fixed', 'pymatching-envelope', 'envelope-matching-offline']\n    if include_mle:\n        names += ['envelope-mle', 'pymatching-fixed-loop']\n    entries = {name: [] for name in names}\n    case['timing_order'] = []\n    for rep in range(repeats):\n        order = names[rep % len(names):] + names[:rep % len(names)]\n        case['timing_order'].append(order)\n        for name in order:\n            if name == 'envelope-matching-offline':\n                entry = measure_offline(exporter, work, rep, answers)\n            elif name.startswith('pymatching'):\n                entry = measure_python(\n                    lambda _: export_graph(exporter, work, f'{name}-{rep}'),\n                    name == 'pymatching-envelope', answers, 1,\n                    batch=not name.endswith('-loop'), repetition_offset=rep,\n                    prediction_path=work/f'{name}-{rep}.b8')\n            else:\n                predicted, record = native_decode(binary, work, name, rep)\n                entry = {'status': record['status'], 'runs': [record]}\n                if predicted is not None:\n                    entry.update(score(predicted, answers))\n                    entry['total_seconds'] = [native_total(record)]\n            entries[name].append(entry)\n    for name, repetitions in entries.items():\n        runs = [run for entry in repetitions for run in entry['runs']]\n        if any(entry['status'] != 'ok' for entry in repetitions):\n            case['decoders'][name] = {'status': 'failed', 'runs': runs,\n                                     'error': 'Incomplete repetition; no prefix accuracy'}\n            continue\n        if len({entry['prediction_sha256'] for entry in repetitions}) != 1:\n            raise ValueError(f'{name} predictions changed between timing repetitions')\n        case['decoders'][name] = {**repetitions[0], 'runs': runs,\n            'total_seconds': [entry['total_seconds'][0] for entry in repetitions]}\n    native = case['decoders']['envelope-matching']\n    offline = case['decoders']['envelope-matching-offline']\n    require(offline['status']=='ok' and native['status']=='ok' and offline['prediction_sha256']==native['prediction_sha256'], 'Offline/streaming predictions differ')\n    if native['status'] == 'ok':\n        native_predictions = np.frombuffer((work/'envelope-matching-0.b8').read_bytes(), dtype=np.uint8)\n        for name, entry in case['decoders'].items():\n            if not name.startswith('pymatching') or entry['status'] != 'ok':\n                continue\n            predicted = np.frombuffer((work/f'{name}-0.b8').read_bytes(), dtype=np.uint8)\n            native_wrong, py_wrong = native_predictions != answers, predicted != answers\n            entry.update(disagreements_with_native=int(np.count_nonzero(predicted != native_predictions)),\n                         paired_native_only_wrong=int(np.count_nonzero(native_wrong & ~py_wrong)),\n                         paired_python_only_wrong=int(np.count_nonzero(~native_wrong & py_wrong)))\n    if include_mle:\n        batch_result, loop_result = [case['decoders'][key] for key in ['pymatching-fixed','pymatching-fixed-loop']]\n        if batch_result['status'] == loop_result['status'] == 'ok':\n            require((batch_result['prediction_sha256'] == loop_result['prediction_sha256']), \"run: batch_result['prediction_sha256'] == loop_result['prediction_sha256']\")\n    return case\n\n\ndef measure_python(graph_factory, conditioned, answers, repeats, native_predictions=None, batch=True, repetition_offset=0, prediction_path=None):\n    timings, final = [], None\n    try:\n        for rep in range(repeats):\n            graph = graph_factory(rep)\n            predicted, timing = python_decode(graph, conditioned, batch=batch)\n            timing.update(compile_seconds=graph['compile_seconds'], transform_seconds=graph['transform_seconds'],\n                          export_repetition=rep+repetition_offset)\n            if final is not None and not np.array_equal(predicted, final):\n                raise ValueError('PyMatching predictions changed between repetitions')\n            final = predicted\n            if prediction_path is not None:\n                write_started = time.perf_counter()\n                with prediction_path.open('wb') as stream:\n                    stream.write(predicted.tobytes())\n                    stream.flush()\n                timing['write_seconds'] = time.perf_counter()-write_started\n                timing['decode_seconds'] += timing['write_seconds']\n                if 'output_seconds' in timing:\n                    timing['output_seconds'] += timing['write_seconds']\n            timings.append(timing)\n        entry = {'status':'ok', 'runs':timings, **score(final, answers)}\n        entry['total_seconds'] = [r['compile_seconds']+r['transform_seconds']+r['decode_seconds'] for r in timings]\n        if native_predictions is not None:\n            entry['disagreements_with_native'] = int(np.count_nonzero(final != native_predictions))\n            native_wrong, py_wrong = native_predictions != answers, final != answers\n            entry['paired_native_only_wrong'] = int(np.count_nonzero(native_wrong & ~py_wrong))\n            entry['paired_python_only_wrong'] = int(np.count_nonzero(~native_wrong & py_wrong))\n        return entry\n    except Exception as error:\n        # Preserve completed timing runs but never score their successful prefix.\n        return {'status':'failed', 'runs':timings, 'error':f'{type(error).__name__}: {error}'}\n\n\ndef sampling_case(binary, sampler, work, distance, shots, repeats):\n    work.mkdir(parents=True, exist_ok=True)\n    circuit = work/'circuit.stim'\n    generate(binary, circuit, distance, distance, .003)\n    checked([sampler, circuit, shots, repeats, work/'rust.json'])\n    rust = json.loads((work/'rust.json').read_text())\n    text = circuit.read_text()\n    timings = []\n    for rep in range(repeats + 1):\n        start = time.perf_counter()\n        rows = reference.sample(text, shots, 1700+rep)\n        sample_seconds = time.perf_counter()-start\n        start = time.perf_counter()\n        payload = np.packbits(rows, axis=1, bitorder='little')\n        packing_seconds = time.perf_counter()-start\n        if rep:\n            timings.append({'sample_seconds':sample_seconds, 'packing_seconds':packing_seconds,'bytes':payload.nbytes})\n    return {'distance':distance, 'rounds':distance, 'shots':shots, 'pauli_probability':.001, 'loss_probability':.003,\n            'circuit_sha256':digest(circuit), 'rust':rust,\n            'reference':{'backend':'Python per-history lowering + Stim (correctness reference)', 'warmups':1,'records':timings}}\n\n\ndef cpu_model():\n    if sys.platform == 'darwin':\n        return subprocess.check_output(['sysctl','-n','machdep.cpu.brand_string'],text=True).strip()\n    if Path('/proc/cpuinfo').exists():\n        for line in Path('/proc/cpuinfo').read_text().splitlines():\n            if line.startswith('model name'):\n                return line.split(':',1)[1].strip()\n    return platform.processor() or 'unavailable'\n\n\ndef main():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--work', type=Path, default=Path('drafts/atom-loss-benchmark'))\n    parser.add_argument('--out', type=Path, default=Path('site/static/data/atom-loss'))\n    parser.add_argument('--shots', type=int, default=5000)\n    parser.add_argument('--sampling-shots', type=int, default=256)\n    parser.add_argument('--repeats', type=int, default=3)\n    parser.add_argument('--stage', choices=['correctness','sampling','decoding','tradeoff','all'], default='all')\n    args = parser.parse_args()\n    if min(args.shots, args.sampling_shots, args.repeats) < 1:\n        parser.error('shots, sampling-shots and repeats must be positive')\n    binary, exporter, sampler = [ROOT/'target/release'/p for p in ['rustqec','examples/export_matching_benchmark','examples/atom_loss_sampling_benchmark']]\n    out, work = args.out.resolve(), args.work.resolve()\n    out.mkdir(parents=True, exist_ok=True)\n    from .source_contract import capture\n    capture(out, args.stage, {'timing': 'Serial cold workflow measurements with rotated backend order. Includes compilation, transformation, graph construction, decoding and prediction write/flush. Excludes process startup, JSON transport/loading and scoring. Streaming and offline policies are distinct; no kernel ranking. Sampling records absolute Rust throughput and unoptimized reference cost with different parse/warmup boundaries.'})\n    if args.stage in ['all','correctness']:\n        result = correctness.run(binary)\n        save(out/'correctness.json', result)\n        require((result['status'] == 'PASS'), \"run: result['status'] == 'PASS'\")\n        from .decoder_reference import run as decoder_reference_run\n        decoder_result = decoder_reference_run(binary, exporter)\n        save(out/'decoder-correctness.json', decoder_result)\n        require((decoder_result['status'] == 'PASS'), \"run: decoder_result['status'] == 'PASS'\")\n        from .chain_reference import run as chain_reference_run\n        chain_result = chain_reference_run(binary, exporter)\n        save(out/'chain-correctness.json', chain_result)\n        require((chain_result['status'] == 'PASS'), \"run: chain_result['status'] == 'PASS'\")\n        print('sampling, matching and real-circuit chain correctness PASS', flush=True)\n    if args.stage in ['all','sampling']:\n        results = []\n        for distance in [3,5,7]:\n            results.append(sampling_case(binary,sampler,work/f'sampling-d{distance}',distance,args.sampling_shots,args.repeats))\n            save(out/'sampling.json', results)\n            print(f'sampling d={distance} complete',flush=True)\n    if args.stage in ['all','decoding']:\n        results = []\n        for distance in [3,5,7]:\n            for loss in [.0001,.0003,.001,.003,.01]:\n                case = decoder_case(binary,exporter,work/f'd{distance}-p{loss}',distance,distance,loss,args.shots,20260911,args.repeats)\n                results.append(case)\n                save(out/'decoding.json',results)\n                print(f'decoding d={distance} p={loss}: '+', '.join(f'{k} {v.get(\"errors\",v[\"status\"])}' for k,v in case['decoders'].items()),flush=True)\n    if args.stage in ['all','tradeoff']:\n        result = decoder_case(binary,exporter,work/'tradeoff',3,2,.003,args.shots,20260912,args.repeats,include_mle=True)\n        save(out/'tradeoff.json',result)\n        print('tradeoff complete',flush=True)\n\n\nif __name__ == '__main__':\n    main()\n",
    "benchmarks/atom_loss/shot_data.py": "\"\"\"Package and independently rescore the synthetic, blinded benchmark corpus.\n\nThe rescore subcommand needs only the Python standard library and reads ZIP\nmembers directly; it never extracts paths or invokes a decoder.\n\"\"\"\nimport argparse\nimport hashlib\nimport json\nfrom pathlib import Path\nimport zipfile\n\nARCHIVE = 'shot-data-v1.zip'\n\n\ndef require(condition, message):\n    if not condition:\n        raise ValueError('Dataset contract: ' + message)\n\n\ndef mask_stream(seed, domain):\n    \"\"\"Independent ChaCha12 word stream: rand 0.8 / rand_chacha 0.3, 64-bit host.\n\n    This reproduces the pinned exporter RNG, not a portable promise about StdRng\n    in future rand releases. Counter and stream start at zero; words are LE.\n    \"\"\"\n    import struct\n    key=hashlib.sha256(b'rstim-decoder-dataset-v1\\n'+domain+b'\\n'+seed.to_bytes(8,'little')).digest()\n    initial=list(struct.unpack('<4I',b'expand 32-byte k'))+list(struct.unpack('<8I',key))\n    counter=0; mask=2**32-1\n    def rotate(v,n): return ((v<<n)|(v>>(32-n)))&mask\n    while True:\n        state=initial+[counter&mask,counter>>32,0,0];x=state.copy()\n        def quarter(a,b,c,d):\n            x[a]=(x[a]+x[b])&mask;x[d]=rotate(x[d]^x[a],16)\n            x[c]=(x[c]+x[d])&mask;x[b]=rotate(x[b]^x[c],12)\n            x[a]=(x[a]+x[b])&mask;x[d]=rotate(x[d]^x[a],8)\n            x[c]=(x[c]+x[d])&mask;x[b]=rotate(x[b]^x[c],7)\n        for _ in range(6):\n            for q in [(0,4,8,12),(1,5,9,13),(2,6,10,14),(3,7,11,15),\n                      (0,5,10,15),(1,6,11,12),(2,7,8,13),(3,4,9,14)]: quarter(*q)\n        yield from ((a+b)&mask for a,b in zip(x,state))\n        counter+=1\n\n\ndef generated_masks(seed, shots, batch_shots):\n    \"\"\"Reconstruct private labels including per-batch unbiased row shuffling.\"\"\"\n    labels=mask_stream(seed,b'logical-mask');permutation=mask_stream(seed,b'row-permutation')\n    result=bytearray();maximum=2**64-1\n    for offset in range(0,shots,batch_shots):\n        batch=[next(labels)>>31 for _ in range(min(batch_shots,shots-offset))]\n        for index in range(len(batch)-1,0,-1):\n            width=index+1;zone=(width<<(64-width.bit_length()))-1\n            while True:\n                value=next(permutation)|(next(permutation)<<32)\n                product=value*width\n                if (product&maximum)<=zone: break\n            replacement=product>>64\n            batch[index],batch[replacement]=batch[replacement],batch[index]\n        result.extend(batch)\n    return bytes(result)\n\n\ndef circuit_layout(text):\n    \"\"\"Independent record indexing for the benchmark's documented circuit subset.\n\n    No Rust m2d/compiler or private answers participate in this calculation.\n    Unknown operations fail closed; REPEAT is expanded, annotations are counted.\n    \"\"\"\n    import re\n    def parse(lines, nested=False):\n        operations=[]\n        for raw in lines:\n            line=raw.split('#',1)[0].strip()\n            if not line: continue\n            if line=='}':\n                require(nested,'unexpected closing brace')\n                return operations\n            if line.startswith('REPEAT '):\n                match=re.fullmatch(r'REPEAT (\\d+)\\s*\\{',line)\n                require(match is not None,'invalid REPEAT')\n                operations.extend(parse(lines,True)*int(match[1]));continue\n            match=re.fullmatch(r'([A-Z_0-9]+)(?:\\[[^\\]]*\\])?(?:\\(([^)]*)\\))?(?:\\s+(.*))?',line)\n            require(match is not None,'invalid instruction')\n            operations.append((match[1],match[2],(match[3] or '').split()))\n        require(not nested,'unclosed REPEAT')\n        return operations\n    measurements=detectors=0;observables={}\n    inert={'R','RZ','H','S','S_DAG','X','Y','Z','CX','CNOT','ZCX','CZ','X_ERROR','Y_ERROR',\n           'Z_ERROR','DEPOLARIZE1','DEPOLARIZE2','LOSS','TICK','QUBIT_COORDS','SHIFT_COORDS'}\n    for name,args,targets in parse(iter(text.splitlines())):\n        if name in {'M','MR','MZ','MRZ','ML','MRL','MZL','MRZL'}:\n            require(args is None,'inline measurement noise outside subset')\n            measurements+=len(targets)*(2 if name.endswith('L') else 1)\n        elif name in {'DETECTOR','OBSERVABLE_INCLUDE'}:\n            indices=[]\n            for target in targets:\n                match=re.fullmatch(r'rec\\[(-\\d+)\\]',target)\n                require(match is not None,'invalid record target')\n                index=measurements+int(match[1]);require(0<=index<measurements,'record outside prefix')\n                indices.append(index)\n            if name=='DETECTOR': detectors+=1\n            else:\n                require(args is not None and args.isdigit(),'invalid observable index')\n                observables.setdefault(int(args),[]).extend(indices)\n        else:\n            require(name in inert,'unsupported instruction '+name)\n    return measurements,detectors,observables\n\n\ndef validate_dataset(read, expected=None):\n    \"\"\"Validate public/private formats and derive every scoring bit independently.\n\n    `read` resolves paths relative to one corpus. Returns validated scoring keys.\n    This function stays inside rescore.py so the download has no dependencies.\n    \"\"\"\n    sha=lambda data:hashlib.sha256(data).hexdigest()\n    public=json.loads(read('public/manifest.json'));private=json.loads(read('private/manifest.json'))\n    text=read('public/circuit.stim')\n    bits,detectors,observables=circuit_layout(text.decode())\n    require(set(observables)=={0},'exactly one observable required')\n    shots=public['shots'];require(type(shots) is int and shots>0,'invalid shot count')\n    stride=(bits+7)//8;require(bits>0,'empty measurements')\n    rows=read('public/shots.b8');answers=read('private/answers.b8');masks=read('private/masks.b8')\n    require(len(rows)==shots*stride,'public row length')\n    require(len(answers)==len(masks)==shots,'private row length')\n    require(set(answers)<={0,1} and set(masks)<={0,1},'private bits outside 0/1')\n    if bits%8:\n        require(all(rows[i]>>(bits%8)==0 for i in range(stride-1,len(rows),stride)),'nonzero padding')\n    identity=(f'format=rstim_decoder_dataset\\nschema_version=1\\nmode=measurements_blinded\\n'\n              f'circuit_sha256={sha(text)}\\nshots={shots}\\nrow_bits={bits}\\nshots_b8_sha256={sha(rows)}\\n')\n    for manifest in [public,private]:\n        require(manifest['format']=='rstim_decoder_dataset' and type(manifest['schema_version']) is int\n                and manifest['schema_version']==1 and manifest['mode']=='measurements_blinded','schema/mode')\n        require(type(manifest['shots']) is int and manifest['shots']==shots,'manifest shots')\n        require(manifest['dataset_id']==sha(identity.encode()),'dataset identity')\n    require(public['row']==dict(kind='measurements',bits=bits,encoding='b8',bit_order='lsb_first',bytes_per_shot=stride),'row format')\n    require(public['circuit']==dict(file='circuit.stim',sha256=sha(text),measurements=bits,detectors=detectors,\n                                   observables=1,sweep_bits=0),'circuit metadata')\n    for manifest,key,file,data,width,size in [(public,'shots_file','shots.b8',rows,bits,stride),\n            (private,'answers_file','answers.b8',answers,1,1),(private,'masks_file','masks.b8',masks,1,1)]:\n        require(manifest[key]==dict(file=file,sha256=sha(data),bits=width,bytes_per_shot=size),'file metadata '+key)\n    for record,keys in [(public['row'],['bits','bytes_per_shot']),\n            (public['circuit'],['measurements','detectors','observables','sweep_bits']),\n            (public['shots_file'],['bits','bytes_per_shot']),\n            (private['answers_file'],['bits','bytes_per_shot']),(private['masks_file'],['bits','bytes_per_shot'])]:\n        require(all(type(record[k]) is int for k in keys),'non-integer row metadata')\n    generation=private['generation']\n    require(isinstance(generation['rstim_version'],str) and bool(generation['rstim_version']),'generation version')\n    require(type(generation['batch_shots']) is int and generation['batch_shots']>0,'generation batch size')\n    require(type(generation['seed']) is int and 0<=generation['seed']<2**64,'generation seed')\n    require(masks==generated_masks(generation['seed'],shots,generation['batch_shots']),\n            'mask differs from seeded exporter generation')\n    record_bits=observables[0]\n    derived=bytes((sum((rows[row*stride+bit//8]>>(bit%8))&1 for bit in record_bits)%2)^masks[row]\n                  for row in range(shots))\n    require(answers==derived,'scoring answer differs from observable XOR mask')\n    if expected is not None:\n        require(expected['shots']==shots and expected['dataset_id']==public['dataset_id'],'case identity/shots')\n        require(expected['seed']==generation['seed'],'case seed')\n        for key,data in [('circuit_sha256',text),('public_rows_sha256',rows),('answers_sha256',answers)]:\n            require(expected[key]==sha(data),'case digest '+key)\n    return derived\n\n\ndef case_label(case, tradeoff=False):\n    return 'tradeoff' if tradeoff else f\"d{case['distance']}-p{case['loss_probability']}\"\n\n\ndef cases_from(read):\n    return [(case_label(c), c) for c in json.loads(read('decoding.json'))] + [\n        ('tradeoff', json.loads(read('tradeoff.json')))]\n\n\ndef original_plan(cases):\n    \"\"\"The download has a fixed experiment inventory, independent of its index.\"\"\"\n    settings = {f'd{d}-p{p}': (d, d, p, 20260911)\n                for d in (3, 5, 7) for p in (.0001, .0003, .001, .003, .01)}\n    settings['tradeoff'] = (3, 2, .003, 20260912)\n    require(len(cases) == 16 and {label for label, _ in cases} == set(settings),\n            'original experiment requires all 16 fixed settings exactly once')\n    for label, case in cases:\n        d, rounds, loss, seed = settings[label]\n        for key, expected in [('distance', d), ('rounds', rounds), ('seed', seed), ('shots', 5000)]:\n            require(type(case.get(key)) is int and case[key] == expected,\n                    'original fixed workload '+key)\n        for key, expected in [('loss_probability', loss), ('pauli_probability', .001)]:\n            require(type(case.get(key)) in (int, float) and case[key] == expected,\n                    'Declared Pauli probability differs from fixed workload' if key == 'pauli_probability'\n                    else 'original fixed workload '+key)\n        backends = {'envelope-matching', 'envelope-matching-offline',\n                    'pymatching-fixed', 'pymatching-envelope'}\n        if label == 'tradeoff':\n            backends |= {'envelope-mle', 'pymatching-fixed-loop'}\n        require(type(case.get('decoders')) is dict and set(case['decoders']) == backends,\n                'original comparator inventory')\n        for name, result in case['decoders'].items():\n            require(type(result) is dict and result.get('status') == 'ok',\n                    'original comparator did not complete')\n            runs = result.get('runs')\n            require(type(runs) is list and len(runs) == 3\n                    and all(type(run) is dict and bool(run) for run in runs),\n                    'original comparator requires three complete run records')\n            if name.startswith('pymatching'):\n                require(all(type(run.get('export_repetition')) is int and run['export_repetition'] == rep\n                            for rep, run in enumerate(runs)), 'original Python repetition identity')\n            else:\n                require(all(run.get('status') == 'ok' and type(run.get('exit_code')) is int\n                            and run['exit_code'] == 0 for run in runs),\n                        'original native repetition did not complete')\n                for run in runs:\n                    stats = run.get('stats')\n                    require(type(stats) is dict and all(type(stats.get(key)) is int and stats[key] == value\n                            for key, value in [('attempted_shot_count', 5000), ('timeout_count', 0),\n                                               ('infeasible_shot_count', 0)]),\n                            'original native repetition has incomplete shot outcomes')\n\n\ndef check_score(result, predicted, answers):\n    \"\"\"Recompute every portable accuracy field; timing is outside this check.\"\"\"\n    import math\n    require(len(predicted) == len(answers) and set(predicted) <= {0, 1}, 'Prediction rescore mismatch: invalid rows')\n    errors = sum(p != a for p, a in zip(predicted, answers))\n    shots = len(answers)\n    require(type(result.get('errors')) is int and result['errors'] == errors\n            and type(result.get('shots')) is int and result['shots'] == shots,\n            'Prediction rescore mismatch: integer counts')\n    require(result.get('prediction_sha256') == hashlib.sha256(predicted).hexdigest(),\n            'Prediction rescore mismatch: hash')\n    rate = errors/shots\n    require(type(result.get('logical_error_rate')) in (int, float)\n            and result['logical_error_rate'] == rate, 'Prediction rescore mismatch: failure rate')\n    z = 1.959963984540054\n    center = (rate+z*z/(2*shots))/(1+z*z/shots)\n    half = z*math.sqrt(rate*(1-rate)/shots+z*z/(4*shots*shots))/(1+z*z/shots)\n    interval = result.get('wilson_95')\n    require(type(interval) is list and len(interval) == 2\n            and all(type(v) in (int, float) and math.isfinite(v) for v in interval)\n            and interval == [max(0., center-half), min(1., center+half)],\n            'Prediction rescore mismatch: Wilson interval')\n\n\ndef check_pairs(result, native, predicted, answers):\n    actual = [sum(n != p for n, p in zip(native, predicted)),\n              sum(n != a and p == a for n, p, a in zip(native, predicted, answers)),\n              sum(n == a and p != a for n, p, a in zip(native, predicted, answers))]\n    keys = ('disagreements_with_native', 'paired_native_only_wrong', 'paired_python_only_wrong')\n    require(all(type(result.get(key)) is int for key in keys)\n            and [result[key] for key in keys] == actual, 'paired errors differ from published results')\n\n\ndef required_members(cases):\n    original_plan(cases)\n    names = {'decoding.json', 'tradeoff.json', 'rescore.py'}\n    for label, case in cases:\n        names.update(f'{label}/{name}' for name in [\n            'circuit.stim', 'public/circuit.stim', 'public/manifest.json',\n            'public/shots.b8', 'private/manifest.json', 'private/answers.b8', 'private/masks.b8'])\n        for decoder in case['decoders']:\n            names.update(f'{label}/{decoder}-{rep}.b8' for rep in range(3))\n    return names\n\n\ndef pack(work, out):\n    results = {name: (out/name).read_bytes() for name in ['decoding.json', 'tradeoff.json']}\n    cases = cases_from(results.__getitem__)\n    payload = {**results, 'rescore.py': Path(__file__).read_bytes()}\n    for name in required_members(cases) - payload.keys():\n        payload[name] = (work/name).read_bytes()\n    index = {'schema': 1, 'description': 'Synthetic benchmark inputs, scoring keys and all timing-repetition predictions. Decoders receive public/ only.',\n             'sha256': {name: hashlib.sha256(data).hexdigest() for name, data in sorted(payload.items())}}\n    payload['index.json'] = (json.dumps(index, indent=2) + '\\n').encode()\n    with zipfile.ZipFile(out/ARCHIVE, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:\n        for name, data in sorted(payload.items()):\n            info = zipfile.ZipInfo(name, date_time=(2026, 1, 1, 0, 0, 0))\n            info.compress_type = zipfile.ZIP_DEFLATED\n            archive.writestr(info, data)\n    return rescore(out/ARCHIVE, out)\n\n\ndef rescore(path, results_root=None):\n    count = 0\n    with zipfile.ZipFile(path) as archive:\n        read = archive.read\n        index = json.loads(read('index.json'))\n        if type(index['schema']) is not int or index['schema'] != 1:\n            raise ValueError('Unknown shot archive schema')\n        cases = cases_from(read)\n        expected = required_members(cases)\n        if set(index['sha256']) != expected or sorted(archive.namelist()) != sorted(expected | {'index.json'}):\n            raise ValueError('Incomplete or duplicate shot archive members/checksums')\n        for name, checksum in index['sha256'].items():\n            if hashlib.sha256(read(name)).hexdigest() != checksum:\n                raise ValueError(f'Shot archive checksum mismatch: {name}')\n        if results_root is not None:\n            if read('rescore.py') != Path(__file__).read_bytes():\n                raise ValueError('Archived rescorer differs from the checked implementation')\n            for name in ['decoding.json', 'tradeoff.json']:\n                if read(name) != (results_root/name).read_bytes():\n                    raise ValueError('Archive results differ from published results')\n        if len(cases) != 16 or len({label for label, _ in cases}) != 16:\n            raise ValueError('Expected all 16 benchmark corpora')\n        for label, case in cases:\n            require(case.get('pauli_probability') == .001, 'Declared Pauli probability differs from fixed workload')\n            for name, key in [('circuit.stim', 'circuit_sha256'), ('public/shots.b8', 'public_rows_sha256'),\n                              ('private/answers.b8', 'answers_sha256')]:\n                if hashlib.sha256(read(f'{label}/{name}')).hexdigest() != case[key]:\n                    raise ValueError(f'Corpus differs from published hash: {label}/{name}')\n            if read(f'{label}/circuit.stim') != read(f'{label}/public/circuit.stim'):\n                raise ValueError('Public circuit differs from benchmark circuit')\n            for kind in ['public', 'private']:\n                manifest = json.loads(read(f'{label}/{kind}/manifest.json'))\n                if manifest['dataset_id'] != case['dataset_id']:\n                    raise ValueError('Mismatched dataset identity')\n            answers = validate_dataset(lambda name:read(f'{label}/{name}'), case)\n            if len(answers) != case['shots'] or not set(answers) <= {0, 1}:\n                raise ValueError('Invalid scoring key')\n            native = read(f'{label}/envelope-matching-0.b8')\n            for decoder, result in case['decoders'].items():\n                for rep in range(3):\n                    predicted = read(f'{label}/{decoder}-{rep}.b8')\n                    check_score(result, predicted, answers)\n                    if decoder.startswith('pymatching'):\n                        check_pairs(result, native, predicted, answers)\n                    count += 1\n    require(count == 198, 'original experiment requires all 198 prediction files')\n    return f'PASS: {len(cases)} corpora; {count} prediction files rescored'\n\n\nSEEDS = [2026091401,2026091402,2026091403]\n\n\ndef paired_interval(a,b,n):\n    \"\"\"Conservative pointwise 95% CI for P(native-only wrong)-P(other-only wrong).\n\n    Each discordant count has a binomial marginal. Bound both at 97.5% using\n    Clopper-Pearson and subtract opposite ends; union bound gives >=95% joint\n    coverage without treating the two decoder outcomes as independent.\n    \"\"\"\n    import math\n    def cdf(k,p):\n        if p==0:return 1.\n        if p==1:return float(k==n)\n        logs=[n*math.log1p(-p)]\n        for j in range(k):logs.append(logs[-1]+math.log(n-j)-math.log(j+1)+math.log(p)-math.log1p(-p))\n        top=max(logs)\n        return min(1.,math.exp(top)*math.fsum(math.exp(v-top) for v in logs))\n    def bound(k,target):\n        lo,hi=0.,1.\n        for _ in range(55):\n            mid=(lo+hi)/2\n            if cdf(k,mid)>target:lo=mid\n            else:hi=mid\n        return (lo+hi)/2\n    def cp(k):\n        if k>n//2:\n            lo,hi=cp(n-k);return 1-hi,1-lo\n        return (0. if k==0 else bound(k-1,.9875),1. if k==n else bound(k,.0125))\n    al,ah=cp(a);bl,bh=cp(b)\n    return [al-bh,ah-bl]\n\n\ndef seed_summaries(cases):\n    grouped={}\n    for case in cases:grouped.setdefault(case['setting'],[]).append(case)\n    summaries=[]\n    for label,group in sorted(grouped.items()):\n        for backend in sorted(group[0]['paired']):\n            n=sum(c['shots'] for c in group)\n            a=sum(c['paired'][backend]['native_only_wrong'] for c in group)\n            b=sum(c['paired'][backend]['other_only_wrong'] for c in group)\n            summaries.append({'setting':label,'comparator':backend,'shots':n,\n                'native_only_wrong':a,'other_only_wrong':b,'difference':(a-b)/n,\n                'paired_95':paired_interval(a,b,n)})\n    return summaries\n\n\ndef rescore_seeds(path, results_root=None):\n    with zipfile.ZipFile(path) as z:\n        index=json.loads(z.read('index.json'));report=json.loads(z.read('accuracy-seeds.json'))\n        if results_root is not None:\n            require(z.read('accuracy-seeds.json')==(results_root/'accuracy-seeds.json').read_bytes(),'seed report mismatch')\n            require(z.read('rescore.py')==Path(__file__).read_bytes(),'seed rescorer mismatch')\n        cases=report['cases'];settings={f'd{d}-p{p}' for d in [3,5,7] for p in [.0001,.0003,.001,.003,.01]}|{'tradeoff'}\n        require(len(cases)==48 and {(c['setting'],c['seed']) for c in cases}=={(label,seed) for label in settings for seed in SEEDS},'seed experiment completeness')\n        require(type(report['seeds']) is list and all(type(seed) is int for seed in report['seeds'])\n                and report['seeds']==SEEDS and type(report['shots_per_seed']) is int\n                and report['shots_per_seed']==5000,'seed plan')\n        members={'accuracy-seeds.json','rescore.py'}\n        for c in cases:\n            require(c.get('pauli_probability') == .001, 'Declared Pauli probability differs from fixed workload')\n            label=c['setting'];prefix=f\"{label}-s{c['seed']}\"\n            read=lambda name:z.read(f'{prefix}/{name}')\n            d,p=(3,.003) if label=='tradeoff' else (int(label[1]),float(label.split('-p')[1]))\n            require(all(type(c.get(key)) is int for key in ('distance','rounds','shots','seed'))\n                    and c['distance']==d and c['rounds']==(2 if label=='tradeoff' else d)\n                    and type(c['loss_probability']) in (int,float) and c['loss_probability']==p\n                    and c['shots']==5000,'seed workload')\n            answers=validate_dataset(read,c)\n            names={'envelope-matching','pymatching-envelope','pymatching-fixed'}|({'envelope-mle'} if label=='tradeoff' else set())\n            require(set(c['decoders'])==names and set(c['paired'])==names-{'envelope-matching'},'seed comparators')\n            for name in ['public/circuit.stim','public/manifest.json','public/shots.b8','private/manifest.json','private/answers.b8','private/masks.b8']:\n                members.add(prefix+'/'+name)\n            native=read('envelope-matching.b8')\n            for name,r in c['decoders'].items():\n                members.add(prefix+'/'+name+'.b8');pred=read(name+'.b8')\n                check_score(r,pred,answers)\n                if name!='envelope-matching':\n                    a=sum(n!=k and q==k for n,q,k in zip(native,pred,answers))\n                    b=sum(n==k and q!=k for n,q,k in zip(native,pred,answers))\n                    pair=c['paired'][name]\n                    require(type(pair) is dict and all(type(v) is int for v in pair.values())\n                            and pair=={'native_only_wrong':a,'other_only_wrong':b},'seed paired scores')\n        require(set(index['sha256'])==members and sorted(z.namelist())==sorted(members|{'index.json'}),'seed archive completeness')\n        for name,digest in index['sha256'].items():require(hashlib.sha256(z.read(name)).hexdigest()==digest,'seed archive checksum')\n        expected=seed_summaries(cases)\n        import math\n        require(len(report['pooled'])==len(expected),'seed pooled completeness')\n        for actual,want in zip(report['pooled'],expected):\n            require(all(type(actual.get(key)) is int for key in\n                        ('shots','native_only_wrong','other_only_wrong'))\n                    and type(actual.get('difference')) in (int,float), 'seed pooled score types')\n            interval=actual['paired_95']\n            require(isinstance(interval,list) and len(interval)==2 and all(type(v) in [float,int] and math.isfinite(v) for v in interval),'seed paired interval format')\n            require(all(math.isclose(a,b,rel_tol=1e-10,abs_tol=1e-12) for a,b in zip(interval,want['paired_95'])),'seed pooled paired intervals')\n            require({**actual,'paired_95':want['paired_95']}==want,'seed pooled counts/difference')\n    return 'PASS: 48 independent-seed corpora and 147 predictions rescored'\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(description=__doc__)\n    subs = parser.add_subparsers(dest='command', required=True)\n    seeds = subs.add_parser('rescore-seeds')\n    seeds.add_argument('archive', type=Path)\n    packing = subs.add_parser('pack')\n    packing.add_argument('--work', type=Path, required=True)\n    packing.add_argument('--out', type=Path, required=True)\n    scoring = subs.add_parser('rescore')\n    scoring.add_argument('archive', type=Path)\n    args = parser.parse_args()\n    print(pack(args.work, args.out) if args.command == 'pack' else\n          rescore_seeds(args.archive) if args.command == 'rescore-seeds' else rescore(args.archive))\n",
    "benchmarks/atom_loss/source_contract.py": "\"\"\"Bind evidence to a clean source commit, allowing a later artifact-only commit.\n\nThe inventory is derived from Git and Cargo workspace membership, never from a\nbundle's own list. Historical timing is not revalidated by prediction replay.\n\"\"\"\nimport hashlib\nimport json\nimport os\nfrom pathlib import Path\nimport subprocess\nimport tomllib\n\nROOT = Path(__file__).resolve().parents[2]\nBUILD_COMMANDS = [\n    ['cargo', 'build', '--release', '--locked', '-p', 'rustqec-cli', '--features',\n     'benchmark-tools,ilp', '--bin', 'rustqec', '--example', 'export_matching_benchmark',\n     '--example', 'export_decoder_oracle', '--example', 'offline_matching_benchmark'],\n    ['cargo', 'build', '--release', '--locked', '-p', 'rstim', '--example', 'atom_loss_sampling_benchmark'],\n]\nBINARIES = ['target/release/rustqec'] + ['target/release/examples/'+name for name in\n    ['export_matching_benchmark', 'export_decoder_oracle', 'offline_matching_benchmark', 'atom_loss_sampling_benchmark']]\n\n\nBUILD_POLICY = 'isolated-cargo-home; allowlisted-environment; no-external-ancestor-config-v1'\nBUILD_ENV_KEYS = ('PATH', 'HOME', 'TMPDIR', 'TMP', 'TEMP', 'RUSTUP_HOME',\n                  'SystemRoot', 'WINDIR', 'COMSPEC', 'PATHEXT')\nNETWORK_ENV_KEYS = ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'NO_PROXY',\n                    'http_proxy', 'https_proxy', 'all_proxy', 'no_proxy',\n                    'SSL_CERT_FILE', 'SSL_CERT_DIR')\nCAPTURE_DEPENDENCIES = ('stim', 'numpy', 'pymatching', 'scipy', 'matplotlib')\nTHREAD_ENVIRONMENT = {'OMP_NUM_THREADS': '1', 'OPENBLAS_NUM_THREADS': '1', 'RAYON_NUM_THREADS': '1'}\n\n\ndef verify_local_cargo_config(repo):\n    # git status omits ignored files, but Cargo still consumes these two names.\n    for name in ('.cargo/config', '.cargo/config.toml'):\n        path = repo/name\n        if path.exists() or path.is_symlink():\n            tracked = git(repo, 'ls-tree', '--name-only', 'HEAD', '--', name).decode().strip()\n            if tracked != name or not path.is_file() or path.is_symlink():\n                raise ValueError('Cargo configuration must be tracked in the source commit: '+name)\n\n\ndef build_environment(repo, cargo_home):\n    \"\"\"No inherited Cargo/profile/compiler flags or ambient Cargo configuration.\n\n    Fresh CARGO_HOME isolates user registry/config state. Cargo also searches\n    ancestor directories independently of CARGO_HOME, so reject those configs.\n    The checkout's own .cargo files remain part of the source inventory.\n    \"\"\"\n    for parent in repo.resolve().parents:\n        for name in ('config', 'config.toml'):\n            path = parent/'.cargo'/name\n            if path.exists():\n                raise ValueError('External ancestor Cargo configuration: '+str(path))\n    verify_local_cargo_config(repo)\n    if cargo_home.exists():\n        raise ValueError('Use a fresh isolated Cargo home')\n    env = {key: os.environ[key] for key in BUILD_ENV_KEYS + NETWORK_ENV_KEYS if key in os.environ}\n    env.update(CARGO_HOME=str(cargo_home.resolve()), LANG='C', LC_ALL='C', **THREAD_ENVIRONMENT)\n    return env\n\n\ndef git(repo, *args):\n    return subprocess.check_output(['git', '-C', str(repo), *args])\n\n\ndef inventory(repo, revision):\n    cargo = tomllib.loads(git(repo, 'show', revision+':Cargo.toml').decode())\n    members = cargo['workspace']['members']\n    if any('*' in member or '..' in Path(member).parts for member in members):\n        raise ValueError('Source contract requires explicit workspace member paths')\n    prefixes = tuple(member+'/' for member in members) + ('benchmarks/atom_loss/', '.cargo/')\n    entries = {}\n    for entry in git(repo, 'ls-tree', '-rz', '--full-tree', revision).split(b'\\0'):\n        if not entry:\n            continue\n        header, name = entry.split(b'\\t', 1)\n        mode, kind, oid = header.decode().split()\n        name = name.decode()\n        # All files in every workspace member include build.rs, include_bytes!\n        # assets and local dependency configuration, not just decoder .rs files.\n        if name.startswith(prefixes) or name in {\n            'Cargo.toml', 'Cargo.lock', 'rust-toolchain', 'rust-toolchain.toml',\n            'build.rs', '.github/workflows/atom-loss-reference.yml'}:\n            if kind != 'blob' or mode not in {'100644', '100755'}:\n                raise ValueError('Unsupported source entry: '+name)\n            entries[name] = {'mode': mode, 'git_blob': oid}\n    return entries\n\n\ndef input_digest(entries):\n    return hashlib.sha256(json.dumps(entries, sort_keys=True, separators=(',', ':')).encode()).hexdigest()\n\n\ndef check_worktree(repo, entries):\n    for name, entry in entries.items():\n        path = repo/name\n        if path.is_symlink() or not path.is_file():\n            raise ValueError('Missing or redirected source input: '+name)\n        data = path.read_bytes()\n        blob = hashlib.sha1(b'blob '+str(len(data)).encode()+b'\\0'+data).hexdigest()\n        executable = bool(path.stat().st_mode & 0o111)\n        if blob != entry['git_blob'] or executable != (entry['mode'] == '100755'):\n            raise ValueError('Dirty source input: '+name)\n\n\ndef clean_source(repo=ROOT):\n    verify_local_cargo_config(repo)\n    if git(repo, 'status', '--porcelain', '--untracked-files=all').strip():\n        raise ValueError('Evidence generation requires a clean checkout; use a detached worktree and external output directories')\n    commit = git(repo, 'rev-parse', 'HEAD').decode().strip()\n    entries = inventory(repo, commit)\n    check_worktree(repo, entries)\n    return {'schema': 1, 'source_commit': commit, 'working_tree_dirty': False,\n            'inputs': entries, 'input_digest': input_digest(entries), 'build_commands': BUILD_COMMANDS, 'build_policy': BUILD_POLICY}\n\n\ndef verify_source(record, repo=ROOT):\n    commit = record['source_commit']\n    if record.get('schema') != 1 or record.get('working_tree_dirty') is not False:\n        raise ValueError('Missing clean source provenance')\n    if len(commit) != 40 or any(c not in '0123456789abcdef' for c in commit):\n        raise ValueError('Invalid source commit')\n    subprocess.run(['git', '-C', str(repo), 'merge-base', '--is-ancestor', commit, 'HEAD'], check=True)\n    expected = inventory(repo, commit)\n    if record['inputs'] != expected or record['input_digest'] != input_digest(expected):\n        raise ValueError('Incomplete or altered source inventory')\n    if record.get('build_policy') != BUILD_POLICY:\n        raise ValueError('Unexpected clean-build environment policy')\n    if record['build_commands'] != BUILD_COMMANDS:\n        raise ValueError('Unexpected evidence build commands')\n    if inventory(repo, 'HEAD') != expected:\n        raise ValueError('Current source/build inputs differ from measured source commit; regenerate evidence')\n    # Catch newly staged/untracked build inputs before a local verification too.\n    members = tomllib.loads(git(repo, 'show', 'HEAD:Cargo.toml').decode())['workspace']['members']\n    prefixes = tuple(member+'/' for member in members) + ('benchmarks/atom_loss/', '.cargo/')\n    added = git(repo, 'diff', 'HEAD', '--name-only', '--diff-filter=A', '-z') + git(repo, 'ls-files', '--others', '--exclude-standard', '-z')\n    for name in added.decode().split('\\0'):\n        if name and (name.startswith(prefixes) or name in {'rust-toolchain', 'rust-toolchain.toml', 'build.rs'}):\n            raise ValueError('Uncommitted source input: '+name)\n    verify_local_cargo_config(repo)\n    check_worktree(repo, expected)\n    return commit\n\n\ndef capture(out, stage, extra=None):\n    \"\"\"Record only sources and binaries produced by the clean-build entry point.\"\"\"\n    import importlib.metadata\n    import platform\n    import sys\n    from datetime import datetime, timezone\n    from .run import cpu_model, save, digest\n    binding = json.loads((out/'source-manifest.json').read_text())\n    commit = verify_source(binding)\n    if clean_source()['source_commit'] != commit:\n        raise ValueError('Measurements must execute at the source commit itself')\n    binaries = {name: digest(ROOT/name) for name in BINARIES}\n    if binaries != binding['binaries']:\n        raise ValueError('Measured binaries differ from clean build')\n    sources = {name: (ROOT/name).read_text() for name in binding['inputs']\n               if name.startswith('benchmarks/atom_loss/') and (ROOT/name).suffix in {'.py', '.stim', '.txt', '.md'}}\n    suffix = '' if stage == 'all' else '-'+stage\n    save(out/('source-snapshot'+suffix+'.json'), {'base_commit': commit, 'files': sources})\n    record = {'source_commit': commit, 'working_tree_dirty': False,\n              'input_digest': binding['input_digest'], 'started_utc': datetime.now(timezone.utc).isoformat(),\n              'command': sys.argv, 'os': platform.platform(), 'cpu': cpu_model(), 'python': sys.version,\n              'rustc': binding['rustc'], 'binaries': binaries,\n              'dependencies': {p: importlib.metadata.version(p) for p in CAPTURE_DEPENDENCIES},\n              'environment': {k: os.environ.get(k) for k in THREAD_ENVIRONMENT},\n              'sources': {name: hashlib.sha256(data.encode()).hexdigest() for name, data in sources.items()}}\n    record.update(extra or {})\n    save(out/('provenance-'+stage+'.json'), record)\n\n\ndef verify_bundle_source(out, repo=ROOT):\n    binding = json.loads((out/'source-manifest.json').read_text())\n    commit = verify_source(binding, repo)\n    env = binding.get('build_environment', {})\n    fixed = {'LANG': 'C', 'LC_ALL': 'C', **THREAD_ENVIRONMENT}\n    if (not {'PATH', 'HOME', 'CARGO_HOME'}.issubset(env)\n            or set(env) - (set(BUILD_ENV_KEYS) | set(fixed) | {'CARGO_HOME'})\n            or any(not isinstance(value, str) or not value for value in env.values())\n            or any(env.get(key) != value for key, value in fixed.items())):\n        raise ValueError('Invalid effective build environment')\n    if set(binding['binaries']) != set(BINARIES) or any(len(h) != 64 for h in binding['binaries'].values()):\n        raise ValueError('Incomplete clean-build binary manifest')\n    if not isinstance(binding.get('rustc'), str) or not binding['rustc'].strip():\n        raise ValueError('Missing recorded build compiler')\n    dependencies = {}\n    for line in (repo/'benchmarks/atom_loss/requirements.txt').read_text().splitlines():\n        package, separator, version = line.strip().partition('==')\n        if package in CAPTURE_DEPENDENCIES:\n            if not separator or not version.strip() or package in dependencies:\n                raise ValueError('Invalid pinned provenance dependency: '+package)\n            dependencies[package] = version\n    if set(dependencies) != set(CAPTURE_DEPENDENCIES):\n        raise ValueError('Missing pinned provenance dependency')\n    runtime = None\n    for path in sorted(out.glob('provenance-*.json')):\n        record = json.loads(path.read_text())\n        if (record['source_commit'] != commit or record.get('working_tree_dirty') is not False\n                or record.get('input_digest') != binding['input_digest'] or record['binaries'] != binding['binaries']):\n            raise ValueError('Stage provenance differs from clean build: '+path.name)\n        if record.get('dependencies') != dependencies:\n            raise ValueError('Stage dependencies differ from pinned requirements: '+path.name)\n        if record.get('rustc') != binding['rustc']:\n            raise ValueError('Stage compiler differs from clean build: '+path.name)\n        if record.get('environment') != THREAD_ENVIRONMENT:\n            raise ValueError('Stage threading environment differs from fixed run contract: '+path.name)\n        host = {key: record.get(key) for key in ['cpu', 'os', 'python']}\n        if any(not isinstance(value, str) or not value.strip() for value in host.values()):\n            raise ValueError('Missing recorded stage runtime: '+path.name)\n        # Compare the stages of this historical run, never the verifier's host.\n        if runtime is not None and host != runtime:\n            raise ValueError('Stage runtime differs within the recorded run: '+path.name)\n        runtime = host\n        suffix = '' if path.stem == 'provenance-all' else path.stem.removeprefix('provenance')\n        snapshot = json.loads((out/('source-snapshot'+suffix+'.json')).read_text())\n        expected = {name: (repo/name).read_text() for name in binding['inputs']\n                    if name.startswith('benchmarks/atom_loss/') and (repo/name).suffix in {'.py', '.stim', '.txt', '.md'}}\n        if record['sources'] != {name: hashlib.sha256(text.encode()).hexdigest() for name, text in expected.items()}:\n            raise ValueError('Stage source inventory differs from current source: '+path.name)\n        if snapshot != {'base_commit': commit, 'files': expected}:\n            raise ValueError('Snapshot differs from measured/current source: '+path.name)\n    return commit\n",
    "benchmarks/atom_loss/test_chain_reference.py": "\"\"\"Actual graph-adapter controls and retained chain-report corruption tests.\"\"\"\nimport copy\nimport hashlib\nimport json\nfrom pathlib import Path\nimport subprocess\nimport sys\nimport tempfile\nimport unittest\nfrom unittest.mock import patch\n\nimport numpy as np\n\nfrom . import chain_reference, run\nfrom .chain_contract import ROWS, compare_reports, verify_chain\n\n\nclass ChainContractTests(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        cls.report = chain_reference.run(run.ROOT/'target/release/rustqec',\n                                        run.ROOT/'target/release/examples/export_matching_benchmark')\n\n    def reject(self, change):\n        report = copy.deepcopy(self.report)\n        change(report)\n        with self.assertRaises(ValueError):\n            verify_chain(report)\n\n    def test_actual_healthy_graph_adapters_and_three_mutants(self):\n        verify_chain(self.report)\n        self.assertEqual(self.report['witness_generation'], 'stim-reference-sample')\n        self.assertEqual(self.report['measurement_sha256'],\n                         'f179f618bd3a18bcab28565103c4717c0111d3ae3a534d326200698e8d118cea')\n        for backend in chain_reference.GRAPH_BACKENDS:\n            self.assertEqual(self.report['backends'][backend]['rejected_rows'], [])\n            for mutation in chain_reference.GRAPH_MUTATIONS:\n                record = self.report['graph_adapter_controls'][mutation][backend]\n                if mutation == 'empty_edges' and record['outcome'] == 'decoder_error':\n                    continue\n                self.assertEqual(record['outcome'], 'oracle_rejected')\n                self.assertGreater(len(record['rejected_rows']), 0)\n\n    def test_complete_backend_objective_and_mutation_inventory_required(self):\n        for section in ('backends', 'allowed_answers', 'graph_adapter_controls',\n                        'compiler_output_mutations_rejected'):\n            for name in self.report[section]:\n                with self.subTest(section=section, missing=name):\n                    self.reject(lambda r, s=section, n=name: r[s].pop(n))\n            self.reject(lambda r, s=section: r[s].update(unexpected={}))\n        for mutation in chain_reference.GRAPH_MUTATIONS:\n            for backend in chain_reference.GRAPH_BACKENDS:\n                self.reject(lambda r, m=mutation, b=backend: r['graph_adapter_controls'][m].pop(b))\n\n    def test_raw_rows_cannot_be_truncated_or_replaced_with_nonbinary_values(self):\n        for name in self.report['backends']:\n            self.reject(lambda r, n=name: r['backends'][n]['predictions'].pop())\n            for value in (2, -1, True, 0.0, None):\n                self.reject(lambda r, n=name, v=value: r['backends'][n]['predictions'].__setitem__(0, v))\n        for name in self.report['allowed_answers']:\n            self.reject(lambda r, n=name: r['allowed_answers'][n].pop())\n            for value in ([], [0, 0], [1, 0], [True], [0.0], [2], None):\n                self.reject(lambda r, n=name, v=value: r['allowed_answers'][n].__setitem__(0, v))\n        self.reject(lambda r: r.update(rows=ROWS-1))\n        self.reject(lambda r: r.update(rows=float(ROWS)))\n        for field in ('measurement_sha256', 'witness_generation'):\n            self.reject(lambda r, f=field: r.pop(f))\n        for value in ('invalid-hash', 'g'*64, None, 0):\n            self.reject(lambda r, v=value: r.update(measurement_sha256=v))\n        self.reject(lambda r: r.update(witness_generation='seeded-iid-sample'))\n\n    def test_all_stored_summaries_and_hashes_are_recomputed(self):\n        for name, original in self.report['backends'].items():\n            for field, value in original.items():\n                if field == 'predictions':\n                    continue\n                changed = not value if type(value) is bool else value+1 if type(value) is int else [0] if type(value) is list else '0'*64\n                with self.subTest(backend=name, field=field):\n                    self.reject(lambda r, n=name, f=field, v=changed: r['backends'][n].__setitem__(f, v))\n        self.reject(lambda r: r['backends']['envelope-matching'].__setitem__('placeholder_invariance', 1))\n        self.reject(lambda r: r['compiler_output_mutations_rejected'].__setitem__('pauli_weight', 1))\n\n    def test_corrupted_predictions_fail_even_after_hash_is_resealed(self):\n        for name in self.report['backends']:\n            def change(report):\n                record = report['backends'][name]\n                record['predictions'][0] ^= 1\n                record['prediction_sha256'] = hashlib.sha256(bytes(record['predictions'])).hexdigest()\n            self.reject(change)\n        self.reject(lambda r: r['allowed_answers'].__setitem__('envelope-matching', [[0, 1]]*ROWS))\n\n    def test_mutant_outcomes_need_actual_complete_wrong_predictions(self):\n        for mutation in chain_reference.GRAPH_MUTATIONS:\n            for backend in chain_reference.GRAPH_BACKENDS:\n                def control(report):\n                    return report['graph_adapter_controls'][mutation][backend]\n                self.reject(lambda r: control(r).__setitem__('outcome', 'accepted'))\n                self.reject(lambda r: control(r).__setitem__('rejected_rows', [ROWS]))\n                if mutation != 'empty_edges':\n                    self.reject(lambda r: control(r).update(outcome='decoder_error', predictions=None, rejected_rows=[]))\n                if control(self.report)['outcome'] == 'oracle_rejected':\n                    self.reject(lambda r: control(r)['predictions'].pop())\n                    self.reject(lambda r: control(r).update(predictions=r['backends']['envelope-matching']['predictions'], rejected_rows=[]))\n                else:\n                    self.reject(lambda r: control(r).__setitem__('predictions', []))\n\n    def test_actual_constant_zero_python_adapter_fails_the_positive_oracle(self):\n        def wrong(graph, conditioned):\n            return np.zeros(len(graph['syndromes']), dtype=np.uint8), {}\n        with patch.object(run, 'python_decode', wrong):\n            report = chain_reference.run(run.ROOT/'target/release/rustqec',\n                                         run.ROOT/'target/release/examples/export_matching_benchmark')\n        self.assertEqual(report['status'], 'FAIL')\n        self.assertGreater(len(report['backends']['pymatching-envelope']['rejected_rows']), 0)\n        self.assertEqual(report['backends']['pymatching-envelope']['predicted_ones'], 0)\n        with self.assertRaises(ValueError):\n            verify_chain(report)\n\n    def test_contract_works_without_site_packages_and_with_python_optimization(self):\n        with tempfile.TemporaryDirectory() as temp:\n            path = Path(temp)/'report.json'\n            program = ('import json,sys; from benchmarks.atom_loss.chain_contract import verify_chain; '\n                       'verify_chain(json.load(open(sys.argv[1])))')\n            path.write_text(json.dumps(self.report))\n            healthy = subprocess.run([sys.executable, '-S', '-O', '-c', program, str(path)],\n                                     cwd=run.ROOT, capture_output=True, text=True)\n            self.assertEqual(healthy.returncode, 0, healthy.stderr)\n            report = copy.deepcopy(self.report)\n            report['backends']['pymatching-envelope']['predicted_ones'] += 1\n            path.write_text(json.dumps(report))\n            rejected = subprocess.run([sys.executable, '-S', '-O', '-c', program, str(path)],\n                                      cwd=run.ROOT, capture_output=True, text=True)\n            self.assertNotEqual(rejected.returncode, 0)\n            self.assertIn('Chain report contract', rejected.stderr)\n\n    def test_cli_compare_rejects_a_different_published_report(self):\n        with tempfile.TemporaryDirectory() as temp:\n            temp = Path(temp)\n            different = copy.deepcopy(self.report)\n            different['method'] += ' An altered experiment definition.'\n            published = temp/'published.json'; published.write_text(json.dumps(different))\n            result = subprocess.run([sys.executable, '-m', 'benchmarks.atom_loss.chain_reference',\n                                     '--out', str(temp/'out.json'), '--compare', str(published)],\n                                    cwd=run.ROOT, capture_output=True, text=True, timeout=120)\n            self.assertNotEqual(result.returncode, 0)\n            self.assertIn('Fresh chain oracle definitions differ from published evidence', result.stderr)\n\n    def test_fresh_comparison_accepts_different_legal_tied_optima(self):\n        alternate = copy.deepcopy(self.report)\n        choices = alternate['allowed_answers']['envelope-mle']\n        row = next(i for i, values in enumerate(choices[:ROWS//2]) if len(values) == 2)\n        record = alternate['backends']['envelope-mle']\n        for i in (row, row+ROWS//2):\n            record['predictions'][i] ^= 1\n        record['predicted_ones'] = sum(record['predictions'])\n        record['prediction_sha256'] = hashlib.sha256(bytes(record['predictions'])).hexdigest()\n        self.assertNotEqual(record['prediction_sha256'], self.report['backends']['envelope-mle']['prediction_sha256'])\n        verify_chain(alternate)\n        compare_reports(alternate, self.report)\n\n    def test_fresh_comparison_rejects_changed_allowed_sets_and_metadata(self):\n        changed = copy.deepcopy(self.report)\n        changed['method'] += ' Different definition.'\n        verify_chain(changed)\n        with self.assertRaisesRegex(ValueError, 'oracle definitions differ.*method'):\n            compare_reports(changed, self.report)\n        changed = copy.deepcopy(self.report)\n        changed['measurement_sha256'] = '0'*64\n        verify_chain(changed)\n        with self.assertRaisesRegex(ValueError, 'oracle definitions differ.*measurement_sha256'):\n            compare_reports(changed, self.report)\n        changed = copy.deepcopy(self.report)\n        # Remove only the unchosen answer from a tied row and its placeholder\n        # counterpart, keeping this report internally consistent and valid.\n        choices = changed['allowed_answers']['envelope-mle']\n        row = next(i for i, values in enumerate(choices[:ROWS//2]) if len(values) == 2)\n        record = changed['backends']['envelope-mle']\n        for i in (row, row+ROWS//2):\n            choices[i] = [record['predictions'][i]]\n        record['unique_optimum_rows'] += 2\n        verify_chain(changed)\n        with self.assertRaisesRegex(ValueError, 'oracle definitions differ.*allowed_answers'):\n            compare_reports(changed, self.report)\n\n\nif __name__ == '__main__':\n    unittest.main()\n",
    "benchmarks/atom_loss/test_decoder_contract.py": "\"\"\"Actual small-oracle observations and adversarial publication-contract checks.\"\"\"\nimport copy\nimport json\nfrom pathlib import Path\nimport subprocess\nimport sys\nimport tempfile\nimport unittest\n\nfrom . import decoder_reference\nfrom .decoder_contract import compare_reports, verify_decoder\n\nROOT = Path(__file__).resolve().parents[2]\n\n\nclass DecoderContractTests(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        cls.report = decoder_reference.run(ROOT/'target/release/rustqec',\n                                          ROOT/'target/release/examples/export_matching_benchmark')\n\n    def reject(self, change):\n        report = copy.deepcopy(self.report)\n        change(report)\n        with self.assertRaises(ValueError):\n            verify_decoder(report)\n\n    def test_actual_decoder_observations_pass_independent_contract(self):\n        verify_decoder(self.report)\n        self.assertEqual([case['rows_checked'] for case in self.report['cases']], [64, 1024])\n        witness = self.report['cases'][1]['strict_witness']\n        self.assertEqual(witness['logical_order'], [0, 1])\n        self.assertEqual(witness['fixed_costs'], [2, 3])\n        self.assertEqual(witness['conditioned_costs'], [2, 1.5])\n\n    def test_original_explicit_failure_missing_backend_and_wrong_witness_attacks(self):\n        for field in ('hand_derived_graph_pass', 'loss_mapping_pass', 'placeholder_invariance_pass'):\n            self.reject(lambda r, f=field: r['cases'][0].__setitem__(f, False))\n        self.reject(lambda r: r['cases'][1].update(status='FAIL'))\n        self.reject(lambda r: r['cases'][1].update(rejected_rows={}))\n        for name in ('native_prediction', 'pymatching_prediction'):\n            self.reject(lambda r, n=name: r['cases'][1]['strict_witness'].__setitem__(n, 0))\n\n    def test_exact_report_case_graph_and_backend_inventory(self):\n        self.reject(lambda r: r['cases'].pop())\n        self.reject(lambda r: r['cases'].reverse())\n        for key in self.report:\n            self.reject(lambda r, k=key: r.pop(k))\n        for key in self.report['cases'][0]:\n            self.reject(lambda r, k=key: r['cases'][0].pop(k))\n        for section in ('graph', 'raw_predictions', 'rejected_rows'):\n            for key in self.report['cases'][0][section]:\n                self.reject(lambda r, s=section, k=key: r['cases'][0][s].pop(k))\n            self.reject(lambda r, s=section: r['cases'][0][s].update(unexpected=[]))\n        self.reject(lambda r: r['cases'][1].update(rows_checked=1024.0))\n        self.reject(lambda r: r['cases'][0].update(wires=True))\n\n    def test_all_raw_predictions_require_complete_integer_bits(self):\n        for backend in self.report['cases'][0]['raw_predictions']:\n            self.reject(lambda r, n=backend: r['cases'][0]['raw_predictions'][n].pop())\n            for value in (True, 0.0, 2, -1, None):\n                self.reject(lambda r, n=backend, v=value: r['cases'][0]['raw_predictions'][n].__setitem__(0, v))\n        for backend in ('native', 'pymatching'):\n            self.reject(lambda r, n=backend: r['cases'][0]['raw_predictions'][n].__setitem__(0, 1))\n\n    def test_graph_structure_weights_mapping_and_all_transform_rows(self):\n        self.reject(lambda r: r['cases'][0]['graph']['edges'].pop())\n        self.reject(lambda r: r['cases'][0]['graph']['edges'][0].update(weight=0.))\n        self.reject(lambda r: r['cases'][0]['graph']['edges'][0].update(weight=float('nan')))\n        self.reject(lambda r: r['cases'][0]['graph']['edges'][0].update(loss_factor=.25))\n        self.reject(lambda r: r['cases'][0]['graph']['edges'][0].update(u=True))\n        self.reject(lambda r: r['cases'][0]['graph']['edges'][0].update(observables=[True]))\n        self.reject(lambda r: r['cases'][0]['graph'].update(mean_weight=0.))\n        self.reject(lambda r: r['cases'][0]['graph']['loss_edges'].__setitem__(0, []))\n        self.reject(lambda r: r['cases'][0]['graph']['loss_edges'].__setitem__(0, [True]))\n        self.reject(lambda r: r['cases'][0]['graph']['loss_edges'].reverse())\n        for section in ('syndromes', 'losses'):\n            self.reject(lambda r, s=section: r['cases'][0]['graph'][s].pop())\n            self.reject(lambda r, s=section: r['cases'][0]['graph'][s].__setitem__(1, []))\n            self.reject(lambda r, s=section: r['cases'][0]['graph'][s].__setitem__(0, [True]))\n\n    def test_mutant_predictions_and_rejection_summaries_are_recomputed(self):\n        self.reject(lambda r: r['cases'][0]['rejected_rows'].update(native=[0]))\n        self.reject(lambda r: r['cases'][0].update(flipped_prediction_rejected_rows=[]))\n        self.reject(lambda r: r['cases'][0].update(flipped_prediction_rejected_rows=[False]))\n        self.reject(lambda r: r['cases'][1].update(ignored_conditioning_rejected_rows=[21]))\n        self.reject(lambda r: r['cases'][1]['raw_predictions']['ignored_conditioning'].__setitem__(0, 1))\n        self.reject(lambda r: r['cases'][0]['raw_predictions'].update(\n            flipped_native=r['cases'][0]['raw_predictions']['native'].copy()))\n        self.reject(lambda r: r['cases'][0].update(placeholder_invariance_pass=1))\n\n    def test_every_witness_field_has_an_independent_or_raw_source(self):\n        original = self.report['cases'][1]['strict_witness']\n        for key in original:\n            self.reject(lambda r, k=key: r['cases'][1]['strict_witness'].pop(k))\n        for key, value in {\n            'packed_row': True, 'logical_order': [1, 0], 'fixed_optimum': [1],\n            'conditioned_optimum': [0], 'fixed_decoder_prediction': 1,\n            'native_prediction': True, 'pymatching_prediction': 0,\n            'fixed_costs': [3, 2], 'conditioned_costs': [1.5, 2],\n        }.items():\n            self.reject(lambda r, k=key, v=value: r['cases'][1]['strict_witness'].__setitem__(k, v))\n        self.reject(lambda r: r['cases'][0].update(strict_witness=original))\n\n    def test_fresh_comparison_allows_legal_ties_and_equivalent_graph_order(self):\n        alternate = copy.deepcopy(self.report)\n        case = alternate['cases'][0]\n        row = next(raw for raw in range(64) if len(decoder_reference.oracle(raw, wires=3)[0]) == 2)\n        canonical = lambda raw: raw | sum(1 << (2*q+1) for q in range(3) if raw >> (2*q) & 1)\n        for raw in range(64):\n            if canonical(raw) == canonical(row):\n                case['raw_predictions']['pymatching'][raw] ^= 1\n        self.assertNotEqual(case['raw_predictions']['pymatching'], self.report['cases'][0]['raw_predictions']['pymatching'])\n        graph = case['graph'];count = len(graph['edges'])\n        graph['edges'].reverse()\n        graph['loss_edges'] = [[count-1-i for i in indices] for indices in graph['loss_edges']]\n        for edge in graph['edges']:\n            if edge['v'] is not None:\n                edge['u'], edge['v'] = edge['v'], edge['u']\n            edge['weight'] += 2e-13\n        graph['mean_weight'] += 2e-13\n        compare_reports(alternate, self.report)\n        alternate['method'] += ' Changed experiment definition.'\n        with self.assertRaisesRegex(ValueError, 'Fresh decoder oracle definitions differ'):\n            compare_reports(alternate, self.report)\n\n    def test_tied_optimum_still_requires_placeholder_invariance(self):\n        case = self.report['cases'][0]\n        row = next(raw for raw in range(64) if len(decoder_reference.oracle(raw, wires=3)[0]) == 2\n                   and any(raw >> (2*q) & 1 and not raw >> (2*q+1) & 1 for q in range(3)))\n        self.reject(lambda r: r['cases'][0]['raw_predictions']['pymatching'].__setitem__(\n            row, case['raw_predictions']['pymatching'][row] ^ 1))\n\n    def test_contract_works_without_site_packages_and_under_optimization(self):\n        program = ('import json,sys; from benchmarks.atom_loss.decoder_contract import verify_decoder; '\n                   'verify_decoder(json.load(open(sys.argv[1])))')\n        with tempfile.TemporaryDirectory() as tmp:\n            path = Path(tmp)/'report.json'\n            for flags in (['-S'], ['-S', '-O']):\n                path.write_text(json.dumps(self.report))\n                good = subprocess.run([sys.executable, *flags, '-c', program, str(path)], cwd=ROOT,\n                                      capture_output=True, text=True)\n                self.assertEqual(good.returncode, 0, good.stderr)\n                for kind in ('wrong_witness', 'failed_graph', 'missing_backend'):\n                    report = copy.deepcopy(self.report)\n                    if kind == 'wrong_witness':\n                        report['cases'][1]['strict_witness']['native_prediction'] = 0\n                    elif kind == 'failed_graph':\n                        report['cases'][0]['hand_derived_graph_pass'] = False\n                    else:\n                        report['cases'][0]['rejected_rows'] = {}\n                    path.write_text(json.dumps(report))\n                    bad = subprocess.run([sys.executable, *flags, '-c', program, str(path)], cwd=ROOT,\n                                         capture_output=True, text=True)\n                    self.assertNotEqual(bad.returncode, 0, kind)\n                    self.assertIn('Decoder report contract', bad.stderr)\n\n\nif __name__ == '__main__':\n    unittest.main()\n",
    "benchmarks/atom_loss/test_figure_contract.py": "\"\"\"Regressions for resealed presentation corruption, including optimized Python.\"\"\"\nimport hashlib\nimport json\nfrom pathlib import Path\nimport shutil\nimport subprocess\nimport struct\nimport sys\nimport tempfile\nimport unittest\nimport zlib\n\nfrom PIL import Image\nfrom PIL.PngImagePlugin import PngInfo\nimport matplotlib.pyplot as plt\n\nfrom .artifacts import FIGURE_INPUTS, FIGURE_NAMES\nfrom .figure_contract import compare_figures, same_svg, verify_presentation\nfrom .plot import render\nfrom .source_contract import ROOT\n\n\nclass FigureTests(unittest.TestCase):\n    def test_svg_roundoff_is_absolute_and_limited_to_path_coordinates(self):\n        expected = (b'<svg viewBox=\"0 0 100 100\"><text>1.0</text><path '\n                    b'd=\"M 1 2 L 1000000000 4\" style=\"fill: red\" transform=\"scale(1)\"/></svg>')\n        self.assertTrue(same_svg(expected.replace(b'M 1 ', b'M 1.000001 '), expected))\n        self.assertTrue(same_svg(expected.replace(b'M 1 ', b'M 0.999999 '), expected))\n        for old, new in [(b'M 1 ', b'M 1.000002 '),\n                         (b'1000000000 4', b'1000000000.000002 4'),\n                         (b'M 1 2 L', b'M 1 2 3 L'), (b' L ', b' M '),\n                         (b'100 100', b'100 100.000001'), (b'>1.0<', b'>1.000001<'),\n                         (b'scale(1)', b'scale(1.000001)'), (b'red', b'blue'),\n                         (b'<path d=', b'<path id=\"other\" d=')]:\n            with self.subTest(change=new):\n                self.assertFalse(same_svg(expected.replace(old, new), expected))\n        glyph = expected.replace(b'<path d=', b'<path id=\"glyph\" d=')\n        self.assertFalse(same_svg(glyph.replace(b'M 1 ', b'M 1.000001 '), glyph))\n        relative = expected.replace(b'M 1 ', b'm 1 ')\n        self.assertFalse(same_svg(relative.replace(b'm 1 ', b'm 1.000001 '), relative))\n        arc = b'<svg><path d=\"M 0 0 A 1 1 0 0 1 2 2\"/></svg>'\n        self.assertFalse(same_svg(arc.replace(b'0 0 1 2', b'0 0 1.000001 2'), arc))\n\n    @classmethod\n    def setUpClass(cls):\n        cls.temp = tempfile.TemporaryDirectory()\n        cls.addClassCleanup(cls.temp.cleanup)\n        cls.redrawn = Path(cls.temp.name)/'redrawn'\n        cls.redrawn.mkdir()\n        for name in FIGURE_INPUTS:\n            shutil.copyfile(ROOT/'site/static/data/atom-loss'/name, cls.redrawn/name)\n        shutil.copyfile(ROOT/'benchmarks/atom_loss/README.md', cls.redrawn/'methodology.md')\n        render(cls.redrawn)\n\n    def test_deterministic_redraw_ignores_ambient_style(self):\n        with plt.rc_context({'font.size': 30, 'axes.facecolor': 'magenta',\n                             'svg.hashsalt': 'ambient-random-id'}):\n            verify_presentation(self.redrawn)\n\n    def test_every_svg_and_png_is_checked(self):\n        with tempfile.TemporaryDirectory() as temp:\n            root = Path(temp)/'bundle'\n            shutil.copytree(self.redrawn, root)\n            for name in FIGURE_NAMES:\n                for ext in ['svg', 'png']:\n                    filename = name+'.'+ext\n                    original = (root/filename).read_bytes()\n                    # A different valid figure models an accidentally copied old chart.\n                    other = next(n for n in FIGURE_NAMES if n != name)+'.'+ext\n                    shutil.copyfile(root/other, root/filename)\n                    with self.subTest(file=filename), self.assertRaisesRegex(ValueError, filename):\n                        compare_figures(root, self.redrawn)\n                    (root/filename).write_bytes(original)\n\n    def test_modified_input_requires_different_figures(self):\n        with tempfile.TemporaryDirectory() as temp:\n            root = Path(temp)/'bundle'\n            shutil.copytree(self.redrawn, root)\n            path = root/'sampling.json'\n            data = json.loads(path.read_text())\n            for record in data[0]['rust']['records']:\n                record['sample_seconds'] *= 1000\n            path.write_text(json.dumps(data))\n            with self.assertRaisesRegex(ValueError, 'sampling-throughput.svg'):\n                verify_presentation(root)\n\n    def test_trailing_png_metadata_is_checked_after_loading(self):\n        with tempfile.TemporaryDirectory() as temp:\n            root = Path(temp)/'bundle'\n            shutil.copytree(self.redrawn, root)\n            path = root/'accuracy-time.png'\n            original = path.read_bytes()\n            exif = Image.Exif()\n            exif[274] = 3  # A viewer honoring this tag rotates the chart 180 degrees.\n            for tag, data in [(b'eXIf', exif.tobytes()[6:]),\n                              (b'tEXt', b'Description\\x00A false claim about the chart')]:\n                chunk = (struct.pack('>I', len(data))+tag+data\n                         + struct.pack('>I', zlib.crc32(tag+data) & 0xffffffff))\n                path.write_bytes(original[:-12]+chunk+original[-12:])\n                with self.subTest(tag=tag), self.assertRaisesRegex(ValueError, 'accuracy-time.png'):\n                    compare_figures(root, self.redrawn)\n\n    def test_png_with_corrupted_chunk_crc_is_rejected(self):\n        with tempfile.TemporaryDirectory() as temp:\n            root = Path(temp)/'bundle'\n            shutil.copytree(self.redrawn, root)\n            path = root/'accuracy-time.png'\n            content = bytearray(path.read_bytes())\n            offset = 8\n            while content[offset+4:offset+8] != b'IDAT':\n                offset += 12+struct.unpack('>I', content[offset:offset+4])[0]\n            crc = offset+8+struct.unpack('>I', content[offset:offset+4])[0]\n            content[crc] ^= 1\n            path.write_bytes(content)\n            with self.assertRaisesRegex(ValueError, 'Invalid published PNG: accuracy-time.png'):\n                compare_figures(root, self.redrawn)\n\n    def test_resealed_corruption_rejected_by_full_verifier_in_both_modes(self):\n        with tempfile.TemporaryDirectory() as temp:\n            root = Path(temp)/'bundle'\n            source = ROOT/'site/static/data/atom-loss'\n            shutil.copytree(source, root)\n            for defect in ['fabricated-svg', 'changed-pixel', 'swapped-png', 'methodology']:\n                name = {'fabricated-svg': 'accuracy-time.svg', 'changed-pixel': 'accuracy-time.png',\n                        'swapped-png': 'sampling-throughput.png', 'methodology': 'methodology.md'}[defect]\n                if defect == 'fabricated-svg':\n                    (root/name).write_text('<svg xmlns=\"http://www.w3.org/2000/svg\">'\n                                          '<text>RustQEC is 1000x faster</text></svg>')\n                elif defect == 'changed-pixel':\n                    with Image.open(root/name) as image:\n                        image.load()\n                        changed = image.copy()\n                        metadata = PngInfo()\n                        metadata.add_text('Software', image.info['Software'])\n                        dpi = image.info['dpi']\n                    pixel = changed.getpixel((0, 0))\n                    changed.putpixel((0, 0), (pixel[0] ^ 255, *pixel[1:]))\n                    changed.save(root/name, pnginfo=metadata, dpi=dpi)\n                elif defect == 'swapped-png':\n                    shutil.copyfile(root/'logical-error-rate.png', root/name)\n                else:\n                    (root/name).write_text('An unreviewed claim of universal speedup.')\n                manifest = json.loads((source/'bundle.json').read_text())\n                manifest['sha256'][name] = hashlib.sha256((root/name).read_bytes()).hexdigest()\n                (root/'bundle.json').write_text(json.dumps(manifest))\n                for flags in [[], ['-O']]:\n                    with self.subTest(defect=defect, flags=flags):\n                        result = subprocess.run([sys.executable, *flags, '-m',\n                                                 'benchmarks.atom_loss.verify', str(root)],\n                                                cwd=ROOT, capture_output=True, text=True)\n                        self.assertNotEqual(result.returncode, 0)\n                        self.assertIn('ValueError', result.stderr)\n                        self.assertIn('methodology' if defect == 'methodology' else name, result.stderr)\n                shutil.copyfile(source/name, root/name)\n",
    "benchmarks/atom_loss/test_reference.py": "\"\"\"Semantic controls for the benchmark/reference harness, without timing assertions.\"\"\"\nimport unittest\nimport hashlib\nimport csv\nimport io\nimport json\nfrom pathlib import Path\nimport shutil\nimport tempfile\nimport zipfile\nimport pymatching\nfrom unittest.mock import patch\nimport numpy as np\nfrom . import reference\nfrom .verify import require_complete_sweep, verify\nfrom .run import ROOT, build_matching, logical_x, score, wilson, measure_python, python_decode\nfrom . import decoder_reference, chain_reference, correctness, noise_controls, channel_probes, low_probability\nimport itertools\n\n\nclass ReferenceTests(unittest.TestCase):\n    def test_seeded_mask_rejects_coherently_forced_perfect_decoder(self):\n        from .shot_data import validate_dataset, generated_masks\n        with zipfile.ZipFile(ROOT/'site/static/data/atom-loss/shot-data-v1.zip') as z:\n            payload={n.removeprefix('tradeoff/'):z.read(n) for n in z.namelist() if n.startswith('tradeoff/')}\n        old=payload['private/answers.b8'];target=payload['envelope-matching-0.b8']\n        masks=payload['private/masks.b8']\n        payload['private/masks.b8']=bytes(m^a^p for m,a,p in zip(masks,old,target))\n        payload['private/answers.b8']=target\n        manifest=json.loads(payload['private/manifest.json'])\n        for key,name in [('masks_file','masks.b8'),('answers_file','answers.b8')]:\n            manifest[key]['sha256']=hashlib.sha256(payload['private/'+name]).hexdigest()\n        payload['private/manifest.json']=json.dumps(manifest).encode()\n        with self.assertRaisesRegex(ValueError,'seeded exporter'):\n            validate_dataset(payload.__getitem__)\n        # Exercise an actual export spanning more than one 10,000-shot batch.\n        with tempfile.TemporaryDirectory() as tmp:\n            work=Path(tmp)\n            text=(ROOT/'benchmarks/atom_loss/fixtures/midswap_d3_r2.stim').read_text()\n            low_probability.export_rows(ROOT/'target/release/rustqec',text,10017,119,work)\n            manifest=json.loads((work/'private/manifest.json').read_text())\n            self.assertEqual((work/'private/masks.b8').read_bytes(),generated_masks(119,10017,manifest['generation']['batch_shots']))\n\n    def test_optimized_verifier_rejects_same_resealed_corruption(self):\n        import subprocess,sys\n        source=ROOT/'site/static/data/atom-loss'\n        with tempfile.TemporaryDirectory() as tmp:\n            root=Path(tmp)/'bundle';shutil.copytree(source,root)\n            chain=json.loads((root/'chain-correctness.json').read_text());chain['distance']=999\n            (root/'chain-correctness.json').write_text(json.dumps(chain))\n            manifest=json.loads((root/'bundle.json').read_text())\n            manifest['sha256']['chain-correctness.json']=hashlib.sha256((root/'chain-correctness.json').read_bytes()).hexdigest()\n            (root/'bundle.json').write_text(json.dumps(manifest))\n            for flags in [[],['-O']]:\n                result=subprocess.run([sys.executable,*flags,'-m','benchmarks.atom_loss.verify',str(root)],capture_output=True,text=True)\n                self.assertNotEqual(result.returncode,0)\n                self.assertIn('chain',result.stderr)\n                self.assertIn('ValueError',result.stderr)\n        import ast\n        for path in (ROOT/'benchmarks/atom_loss').glob('*.py'):\n            if not path.name.startswith('test_'):\n                self.assertFalse(any(isinstance(n,ast.Assert) for n in ast.walk(ast.parse(path.read_text()))),str(path))\n\n    def test_paired_interval_matches_exact_binomial_marginals(self):\n        from scipy.stats import beta\n        from .shot_data import paired_interval\n        def cp(k,n):\n            return (0 if k==0 else beta.ppf(.0125,k,n-k+1),\n                    1 if k==n else beta.ppf(.9875,k+1,n-k))\n        for a,b,n in [(0,0,15000),(0,13,5000),(10,3,15000),(50,40,100),(100,0,100)]:\n            al,ah=cp(a,n);bl,bh=cp(b,n)\n            np.testing.assert_allclose(paired_interval(a,b,n),[al-bh,ah-bl],atol=1e-10)\n\n    def test_prediction_write_is_within_python_timing(self):\n        import time\n        graph={'edges':[{'u':0,'v':None,'observables':[0],'weight':1.,'loss_factor':.5}],\n               'loss_edges':[],'mean_weight':1.,'syndromes':[[0],[1]],'losses':[[],[]],\n               'compile_seconds':0.,'transform_seconds':0.}\n        with tempfile.TemporaryDirectory() as tmp:\n            path=Path(tmp)/'predictions.b8';original=Path.open\n            def slow_open(p,*args,**kwargs):\n                if p==path:time.sleep(.02)\n                return original(p,*args,**kwargs)\n            with patch.object(Path,'open',slow_open):\n                result=measure_python(lambda _:graph,False,np.array([0,1]),1,prediction_path=path)\n            run=result['runs'][0]\n            self.assertGreaterEqual(run['write_seconds'],.02)\n            self.assertGreaterEqual(run['decode_seconds'],run['write_seconds'])\n            self.assertEqual(path.read_bytes(),bytes([0,1]))\n            self.assertAlmostEqual(sum(run[k] for k in ['topology_seconds','preprocess_seconds','graph_build_seconds','matching_seconds','output_seconds','adapter_overhead_seconds']),run['decode_seconds'])\n\n    def test_multiseed_archive_rejects_missing_seed_and_resealed_summary(self):\n        from .shot_data import rescore_seeds\n        with zipfile.ZipFile(ROOT/'site/static/data/atom-loss/accuracy-seeds.zip') as z:\n            original={n:z.read(n) for n in z.namelist()}\n        with tempfile.TemporaryDirectory() as tmp:\n            for defect in ['missing_seed','paired_summary','missing_prediction']:\n                payload=original.copy();report=json.loads(payload['accuracy-seeds.json'])\n                if defect=='missing_seed':report['cases'].pop()\n                elif defect=='paired_summary':report['pooled'][0]['paired_95']=[-1.,1.]\n                else:del payload[next(n for n in payload if n.endswith('/envelope-matching.b8'))]\n                payload['accuracy-seeds.json']=json.dumps(report).encode()\n                payload['index.json']=json.dumps({'sha256':{n:hashlib.sha256(v).hexdigest() for n,v in payload.items() if n!='index.json'}}).encode()\n                path=Path(tmp)/'mutated.zip'\n                with zipfile.ZipFile(path,'w',compression=zipfile.ZIP_DEFLATED) as z:\n                    for n,v in payload.items():z.writestr(n,v)\n                with self.subTest(defect=defect),self.assertRaises((ValueError,KeyError)):\n                    rescore_seeds(path)\n\n    def test_loss_is_persistent_and_reset_restores(self):\n        rows=reference.sample('R 0 1\\nX 0\\nLOSS(1) 0\\nCX 0 1\\nML 0 1\\nR 0\\nX 0\\nML 0',128)\n        np.testing.assert_array_equal(rows,np.tile([1,1,0,0,0,1],(128,1)))\n\n    def test_lost_entangled_partner_does_not_collapse_survivor_to_zero(self):\n        rows=reference.sample('R 0 1\\nH 0\\nCX 0 1\\nLOSS(1) 0\\nML 0 1',8192)\n        self.assertTrue(np.all(rows[:,:3]==[1,1,0]))\n        self.assertLess(abs(rows[:,3].mean()-.5),.04)\n\n    def test_lost_two_qubit_noise_is_skipped(self):\n        rows=reference.sample('R 0 1\\nLOSS(1) 0\\nDEPOLARIZE2(1) 0 1\\nML 0 1',128)\n        np.testing.assert_array_equal(rows,np.tile([1,1,0,0],(128,1)))\n\n    def test_repeat_and_inverted_measurement(self):\n        rows=reference.sample('R 0\\nREPEAT 2 {\\nX 0\\n}\\nLOSS(1) 0\\nML !0\\nMRL 0\\nML 0',16)\n        np.testing.assert_array_equal(rows,np.tile([1,0,1,1,0,0],(16,1)))\n\n    def test_unsupported_operations_and_noise_fail(self):\n        for circuit in ['R 0\\nT 0\\nM 0','R 0\\nML(0.1) 0','REPEAT 2 {\\nR 0']:\n            with self.assertRaises(ValueError): reference.sample(circuit,4)\n\n    def test_incomplete_scoring_cannot_report_success(self):\n        with self.assertRaises(ValueError): score(np.array([0]),np.array([0,0]))\n        with self.assertRaises(ValueError): score(np.array([2]),np.array([0]))\n        self.assertGreater(wilson(0,5000)[1],0)\n\n    def test_backend_failure_preserves_timings_without_partial_accuracy(self):\n        successful = (np.array([0,1], dtype=np.uint8), {'decode_seconds':.1})\n        with patch('benchmarks.atom_loss.run.python_decode', side_effect=[successful, ValueError('unreachable syndrome')]):\n            result = measure_python(lambda rep: {'compile_seconds':.01,'transform_seconds':.01}, True, np.array([0,1]), 3)\n        self.assertEqual(result['status'], 'failed')\n        self.assertEqual(len(result['runs']), 1)\n        self.assertIn('unreachable syndrome', result['error'])\n        self.assertNotIn('logical_error_rate', result)\n        self.assertNotIn('errors', result)\n        self.assertNotIn('total_seconds', result)\n\n    def test_each_repetition_remeasures_common_stages(self):\n        calls=[]\n        def export(rep):\n            calls.append(rep)\n            return {'compile_seconds':rep+1.,'transform_seconds':rep+.5}\n        successful=(np.array([0,1],dtype=np.uint8),{'decode_seconds':.1})\n        with patch('benchmarks.atom_loss.run.python_decode', side_effect=lambda *a, **kw: (successful[0],successful[1].copy())):\n            result=measure_python(export,False,np.array([0,1]),3)\n        self.assertEqual(calls,[0,1,2])\n        np.testing.assert_allclose(result['total_seconds'],[1.6,3.6,5.6])\n\n    def test_actual_ignore_conditioning_mutation_fails_oracle(self):\n        with patch('benchmarks.atom_loss.decoder_reference.build_matching', side_effect=lambda graph, losses: build_matching(graph,[])):\n            result=decoder_reference.run(ROOT/'target/release/rustqec',ROOT/'target/release/examples/export_matching_benchmark')\n        self.assertEqual(result['status'],'FAIL')\n        five=result['cases'][1]\n        self.assertEqual(five['rejected_rows']['native'],[])\n        self.assertIn(21,five['rejected_rows']['pymatching'])\n        self.assertEqual(decoder_reference.oracle(21,False,5)[0],{0})\n        self.assertEqual(decoder_reference.oracle(21,True,5)[0],{1})\n\n    def test_batch_matches_loop_and_preserves_interleaved_shot_order(self):\n        graph={'edges':[{'u':0,'v':None,'observables':[0],'weight':1.,'loss_factor':.5},\n                        {'u':0,'v':1,'observables':[],'weight':1.,'loss_factor':.5},\n                        {'u':1,'v':None,'observables':[],'weight':1.,'loss_factor':.5}],\n               'loss_edges':[[0],[1],[2]],'mean_weight':1.,'syndromes':[],'losses':[]}\n        for raw in range(64):\n            _,syndrome,flags=decoder_reference.oracle(raw)\n            graph['syndromes'].append(syndrome)\n            graph['losses'].append([i for i,f in enumerate(flags) if f])\n        for conditioned in [False,True]:\n            batch,timing=python_decode(graph,conditioned)\n            phases=[timing[k] for k in ['topology_seconds','preprocess_seconds','graph_build_seconds','matching_seconds','output_seconds','adapter_overhead_seconds']]\n            self.assertGreaterEqual(min(phases),0)\n            self.assertAlmostEqual(sum(phases),timing['decode_seconds'])\n            loop,_=python_decode(graph,conditioned,batch=False)\n            np.testing.assert_array_equal(batch,loop)\n        graph['syndromes'][0].append(1)\n        for row in graph['syndromes'][1:]: row.append(0)\n        with self.assertRaisesRegex(ValueError,'Unreachable'):\n            python_decode(graph,False)\n\n    def test_bulk_graph_preserves_parallel_boundary_weights_and_predictions(self):\n        # Parallel edges have identical logical labels, as required by the compiler.\n        # Conditioning changes which parallel edge survives smallest-weight merge.\n        graph = {'edges': [\n            {'u':0,'v':None,'observables':[0],'weight':4.,'loss_factor':.25},\n            {'u':0,'v':None,'observables':[0],'weight':2.,'loss_factor':.5},\n            {'u':0,'v':1,'observables':[],'weight':3.,'loss_factor':.25},\n            {'u':0,'v':1,'observables':[],'weight':1.,'loss_factor':.5},\n            {'u':1,'v':None,'observables':[],'weight':2.,'loss_factor':.5}],\n            'mean_weight':2.4, 'num_observables':1,\n            'loss_edges': [[0,2], [1,3], [4]], 'syndromes':[[0,0]], 'losses':[[]]}\n        for mask in range(8):\n            losses = [i for i in range(3) if mask & (1 << i)]\n            active = {i for loss in losses for i in graph['loss_edges'][loss]}\n            legacy = pymatching.Matching()\n            for i, edge in enumerate(graph['edges']):\n                weight = (edge['loss_factor']*graph['mean_weight'] if i in active else edge['weight'])/4.\n                kwargs = dict(weight=weight, fault_ids=set(edge['observables']), merge_strategy='smallest-weight')\n                if edge['v'] is None: legacy.add_boundary_edge(edge['u'], **kwargs)\n                else: legacy.add_edge(edge['u'], edge['v'], **kwargs)\n            bulk = build_matching(graph, losses)\n            self.assertEqual(bulk.edges(), legacy.edges())\n            rows = np.array(list(itertools.product([0,1], repeat=2)), dtype=np.uint8)\n            np.testing.assert_array_equal(bulk.decode_batch(rows), legacy.decode_batch(rows))\n\n    def test_bundle_rejects_resealed_native_time_and_missing_checksums(self):\n        source = ROOT/'site/static/data/atom-loss'\n        self.assertEqual(verify(source), 'PASS')\n        with tempfile.TemporaryDirectory() as tmp:\n            root = Path(tmp)/'bundle'\n            def reset():\n                shutil.copytree(source, root, dirs_exist_ok=True)\n            def reseal(name):\n                manifest = json.loads((root/'bundle.json').read_text())\n                manifest['sha256'][name] = hashlib.sha256((root/name).read_bytes()).hexdigest()\n                (root/'bundle.json').write_text(json.dumps(manifest))\n            for defect in ['total', 'missing_stats', 'negative', 'nan', 'failed']:\n                reset()\n                data = json.loads((root/'tradeoff.json').read_text())\n                native = data['decoders']['envelope-matching']\n                if defect == 'total': native['total_seconds'] = [v/100 for v in native['total_seconds']]\n                elif defect == 'missing_stats': del native['runs'][0]['stats']\n                elif defect in ['negative','nan']: native['runs'][0]['stats']['compile_seconds'] = -1. if defect == 'negative' else float('nan')\n                else: native['runs'][0]['exit_code'] = 1\n                (root/'tradeoff.json').write_text(json.dumps(data))\n                reseal('tradeoff.json')\n                with self.subTest(defect=defect), self.assertRaisesRegex(ValueError, 'native|Native'):\n                    verify(root)\n            for name in ['accuracy-time.svg', 'source-snapshot-timing.json', 'shot-data-v1.zip', 'timing-sweep.svg', 'sampling-reference-cost.svg', 'provenance-correctness.json']:\n                reset()\n                manifest = json.loads((root/'bundle.json').read_text())\n                del manifest['sha256'][name]\n                (root/name).write_text('replaced but unlisted')\n                (root/'bundle.json').write_text(json.dumps(manifest))\n                with self.subTest(name=name), self.assertRaisesRegex(ValueError, 'Missing required'):\n                    verify(root)\n            reset()\n            manifest = json.loads((root/'bundle.json').read_text())\n            for name in ['provenance-timing.json', 'source-snapshot-timing.json']:\n                del manifest['sha256'][name]\n                (root/name).unlink()\n            (root/'bundle.json').write_text(json.dumps(manifest))\n            with self.assertRaisesRegex(ValueError, 'Missing required'):\n                verify(root)\n            reset()\n            snapshot = json.loads((root/'source-snapshot-timing.json').read_text())\n            snapshot['files'][next(iter(snapshot['files']))] += '# changed'\n            (root/'source-snapshot-timing.json').write_text(json.dumps(snapshot))\n            reseal('source-snapshot-timing.json')\n            with self.assertRaisesRegex(ValueError, 'Source snapshot mismatch'):\n                verify(root)\n\n    def test_timing_table_corruption_is_rejected_after_resealing(self):\n        with tempfile.TemporaryDirectory() as tmp:\n            root = Path(tmp)/'bundle'\n            shutil.copytree(ROOT/'site/static/data/atom-loss',root)\n            path = root/'timing-sweep.csv'\n            lines = path.read_text().splitlines()\n            cells = lines[1].split(',')\n            cells[5] = str(float(cells[5])/100)\n            lines[1] = ','.join(cells)\n            path.write_text('\\n'.join(lines)+'\\n')\n            manifest = json.loads((root/'bundle.json').read_text())\n            manifest['sha256'][path.name] = hashlib.sha256(path.read_bytes()).hexdigest()\n            (root/'bundle.json').write_text(json.dumps(manifest))\n            with self.assertRaisesRegex(ValueError, 'Timing sweep CSV'):\n                verify(root)\n\n    def test_summary_fields_and_completeness_reject_resealed_corruption(self):\n        source = ROOT/'site/static/data/atom-loss'\n        with (source/'summary.csv').open() as stream:\n            reader = csv.DictReader(stream)\n            fields, original = reader.fieldnames, list(reader)\n        with tempfile.TemporaryDirectory() as tmp:\n            root = Path(tmp)/'bundle'\n            shutil.copytree(source,root)\n            for defect in fields + ['missing','duplicate','extra','header']:\n                rows = [row.copy() for row in original]\n                header = fields[:]\n                if defect == 'missing': rows.pop()\n                elif defect == 'duplicate': rows[1] = rows[0].copy()\n                elif defect == 'extra': rows.append(rows[0].copy())\n                elif defect == 'header': header[0] = 'wrong_experiment'\n                elif defect == 'errors': rows[0][defect] = '4999'\n                elif defect == 'median_microseconds_per_shot': rows[0][defect] = '0.000001'\n                else: rows[0][defect] = 'wrong'\n                stream = io.StringIO()\n                writer = csv.DictWriter(stream,fieldnames=header,extrasaction='ignore')\n                writer.writeheader(); writer.writerows(rows)\n                path = root/'summary.csv'\n                path.write_text(stream.getvalue())\n                manifest = json.loads((root/'bundle.json').read_text())\n                manifest['sha256']['summary.csv'] = hashlib.sha256(path.read_bytes()).hexdigest()\n                (root/'bundle.json').write_text(json.dumps(manifest))\n                with self.subTest(defect=defect), self.assertRaisesRegex(ValueError,'Summary CSV'):\n                    verify(root)\n\n    def test_low_probability_cutoff_fails_overall_sampling_report(self):\n        original = correctness.rust_rows\n        affected = []\n        def defective(binary,text,shots,seed,work):\n            changed,count = low_probability.remove_low_noise(text,'both')\n            affected.append(count)\n            return original(binary,changed,shots,seed,work)\n        with patch('benchmarks.atom_loss.correctness.rust_rows',side_effect=defective):\n            report = correctness.run(ROOT/'target/release/rustqec')\n        self.assertGreater(sum(affected),0)\n        self.assertEqual(report['status'],'FAIL')\n        self.assertEqual(report['low_probability_controls']['analytic']['status'],'FAIL')\n        rejected = {r['case'] for r in report['low_probability_controls']['analytic']['cases'] if r['status']=='FAIL'}\n        self.assertEqual(rejected,{'X_ERROR','Y_ERROR','Z_ERROR','DEPOLARIZE1','DEPOLARIZE2',\n                                  *[f'LOSS_{p}' for p in low_probability.LOSS_RATES if p < .01]})\n\n    def test_export_only_low_pauli_cutoff_is_detected_independently(self):\n        # Ordinary circuit sample can be correct while the benchmark export path\n        # drops noise. Ensure the real-circuit reference catches that alone.\n        def defective(binary,text,shots,seed,work):\n            changed,_ = low_probability.remove_low_noise(text,'pauli')\n            return low_probability.export_rows(binary,changed,shots,seed,work)\n        report = low_probability.real_circuit(ROOT/'target/release/rustqec',65536,exporter=defective)\n        self.assertEqual(report['status'],'FAIL')\n        self.assertTrue(any('/no_visible_loss/' in e for e in report['comparison']['failed_events']))\n\n    def test_dataset_contract_checks_shape_identity_and_scoring_relation(self):\n        from .shot_data import validate_dataset\n        with zipfile.ZipFile(ROOT/'site/static/data/atom-loss/shot-data-v1.zip') as archive:\n            original={name.removeprefix('tradeoff/'):archive.read(name) for name in archive.namelist() if name.startswith('tradeoff/')}\n        self.assertEqual(validate_dataset(original.__getitem__),original['private/answers.b8'])\n        # One matrix covers missing fields, inconsistent metadata, invalid packed\n        # data and coherent-checksum corruption of the actual scoring relation.\n        metadata=[('public/manifest.json',path,value) for path,value in [\n            (['schema_version'],2),(['mode'],'detectors'),(['shots'],4999),(['dataset_id'],'0'*64),\n            (['row','bits'],1),(['row','bytes_per_shot'],1),(['row','bit_order'],'msb_first'),\n            (['circuit','detectors'],1),(['circuit','observables'],2),(['circuit','sha256'],'0'*64),\n            (['shots_file','file'],'other.b8'),(['shots_file','sha256'],'0'*64)]]\n        metadata += [('private/manifest.json',path,value) for path,value in [\n            (['masks_file','bits'],True),(['masks_file','bytes_per_shot'],2),(['shots'],4999),\n            (['generation','seed'],-1),(['generation','batch_shots'],0)]]\n        for member,path,value in metadata:\n            for delete in [False,True]:\n                payload=original.copy();manifest=json.loads(payload[member]);target=manifest\n                for key in path[:-1]:target=target[key]\n                if delete:del target[path[-1]]\n                else:target[path[-1]]=value\n                payload[member]=json.dumps(manifest).encode()\n                with self.subTest(path=path,delete=delete),self.assertRaises((KeyError,ValueError)):\n                    validate_dataset(payload.__getitem__)\n        for defect in ['answer_one','answer_all','wrong_observable','mask','empty_mask','invalid_mask','truncated_rows','padding']:\n            payload=original.copy();member='private/answers.b8'\n            if defect=='answer_one':payload[member]=bytes([payload[member][0]^1])+payload[member][1:]\n            elif defect=='answer_all':payload[member]=bytes(v^1 for v in payload[member])\n            elif defect=='wrong_observable':payload[member]=payload['private/masks.b8']\n            elif defect in ['mask','empty_mask','invalid_mask']:\n                member='private/masks.b8'\n                payload[member]=b'' if defect=='empty_mask' else bytes([2 if defect=='invalid_mask' else payload[member][0]^1])+payload[member][1:]\n            else:\n                member='public/shots.b8'\n                if defect=='truncated_rows':payload[member]=payload[member][:-1]\n                else:\n                    rows=bytearray(payload[member]);rows[6]|=128;payload[member]=bytes(rows)\n            # Reseal the private checksum so rejection exercises semantics too.\n            if member.startswith('private/'):\n                manifest=json.loads(payload['private/manifest.json'])\n                manifest['answers_file' if 'answers' in member else 'masks_file']['sha256']=hashlib.sha256(payload[member]).hexdigest()\n                payload['private/manifest.json']=json.dumps(manifest).encode()\n            with self.subTest(defect=defect),self.assertRaises(ValueError):\n                validate_dataset(payload.__getitem__)\n\n    def test_actual_export_with_flipped_answers_fails_independent_check(self):\n        def broken(binary,text,shots,seed,work):\n            rows,masks=low_probability.export_rows(binary,text,shots,seed,work)\n            path=work/'private/answers.b8';path.write_bytes(bytes(v^1 for v in path.read_bytes()))\n            meta=work/'private/manifest.json';manifest=json.loads(meta.read_text())\n            manifest['answers_file']['sha256']=hashlib.sha256(path.read_bytes()).hexdigest();meta.write_text(json.dumps(manifest))\n            return rows,masks\n        with self.assertRaisesRegex(ValueError,'scoring answer'):\n            low_probability.real_circuit(ROOT/'target/release/rustqec',65536,exporter=broken)\n\n    def test_resealed_incomplete_or_contradictory_reports_are_rejected(self):\n        source=ROOT/'site/static/data/atom-loss'\n        original=json.loads((source/'correctness.json').read_text())\n        mutations=[\n            (['cases',0,'max_bin_difference'],1.),\n            (['cases',0,'tolerance'],1.),\n            (['cases',0,'known_answer_pass'],False),\n            (['cases',0,'histogram_counts'],{}),\n            (['cases'],original['cases'][:-1]),\n            (['analytic_noise_controls','cases',0,'rust_probability'],1.),\n            (['analytic_noise_controls','distribution_probes','cases',0,'rust','marginals'],[]),\n            (['low_probability_controls','analytic','cases',0,'counts'],{}),\n            (['low_probability_controls','analytic','cases',0,'accepted_counts'],[[0,262144]]*7),\n            (['low_probability_controls','analytic','cases',0,'expected_probabilities'],[1.]),\n            (['low_probability_controls','real_circuit','comparison','events',0,'rust_events'],999999),\n            (['low_probability_controls','real_circuit','comparison','events',0,'rust_events'],original['low_probability_controls']['real_circuit']['comparison']['events'][0]['rust_shots']),\n            (['low_probability_controls','real_circuit','comparison','events',0,'pvalue'],.123456),\n            (['low_probability_controls','real_circuit','comparison','events',0,'pvalue'],-1.),\n            (['low_probability_controls','real_circuit','comparison','threshold'],1.),\n            (['low_probability_controls','real_circuit','scoring_key_check','checked_shots'],1),\n        ]\n        with tempfile.TemporaryDirectory() as tmp:\n            root=Path(tmp)/'bundle';shutil.copytree(source,root)\n            for path,value in mutations:\n                report=json.loads(json.dumps(original));target=report\n                for key in path[:-1]:target=target[key]\n                target[path[-1]]=value\n                (root/'correctness.json').write_text(json.dumps(report))\n                manifest=json.loads((root/'bundle.json').read_text())\n                manifest['sha256']['correctness.json']=hashlib.sha256((root/'correctness.json').read_bytes()).hexdigest()\n                (root/'bundle.json').write_text(json.dumps(manifest))\n                with self.subTest(path=path),self.assertRaises((KeyError,ValueError)):\n                    verify(root)\n\n    def test_sampling_count_cannot_change_throughput_after_resealing(self):\n        source=ROOT/'site/static/data/atom-loss'\n        with tempfile.TemporaryDirectory() as tmp:\n            root=Path(tmp)/'bundle';shutil.copytree(source,root)\n            data=json.loads((root/'sampling.json').read_text());data[0]['shots']*=100\n            (root/'sampling.json').write_text(json.dumps(data))\n            manifest=json.loads((root/'bundle.json').read_text())\n            manifest['sha256']['sampling.json']=hashlib.sha256((root/'sampling.json').read_bytes()).hexdigest()\n            (root/'bundle.json').write_text(json.dumps(manifest))\n            with self.assertRaisesRegex(ValueError,'Sampling workload'):verify(root)\n\n    def test_stdlib_statistics_match_independent_reference(self):\n        from scipy.stats import binom, fisher_exact\n        from .report_contract import binomial_interval,fisher_pvalue\n        for n,p in [(262144,.001/15),(520000,.00005),(262144,.01),(262144,.999),(128,0.),(128,1.)]:\n            tail=1e-10\n            self.assertEqual(binomial_interval(n,p,tail),[int(binom.ppf(tail,n,p)),int(binom.ppf(1-tail,n,p))])\n        for a,n,b,m in [(0,100,0,100),(0,100,100,100),(13,5000,0,5000),(500,1000,493,1001),(19,32000,310,33536)]:\n            expected=fisher_exact([[a,n-a],[b,m-b]]).pvalue\n            self.assertAlmostEqual(fisher_pvalue(a,n,b,m),expected,delta=2e-8)\n\n    def test_archive_rejects_resealed_wrong_predictions_and_missing_rows(self):\n        from .shot_data import rescore, ARCHIVE\n        source = ROOT/'site/static/data/atom-loss'/ARCHIVE\n        with zipfile.ZipFile(source) as archive:\n            original = {name:archive.read(name) for name in archive.namelist()}\n        member = 'tradeoff/envelope-matching-0.b8'\n        with tempfile.TemporaryDirectory() as tmp:\n            target = Path(tmp)/ARCHIVE\n            for defect in ['prediction', 'missing']:\n                payload = original.copy()\n                index = json.loads(payload['index.json'])\n                if defect == 'prediction':\n                    rows = bytearray(payload[member]); rows[0] ^= 1\n                    payload[member] = bytes(rows)\n                    index['sha256'][member] = hashlib.sha256(rows).hexdigest()\n                else:\n                    del payload[member]; del index['sha256'][member]\n                payload['index.json'] = json.dumps(index).encode()\n                with zipfile.ZipFile(target, 'w') as archive:\n                    for name, data in payload.items(): archive.writestr(name, data)\n                with self.subTest(defect=defect), self.assertRaisesRegex(ValueError, 'rescore mismatch|Incomplete'):\n                    rescore(target)\n\n    def test_bell_readout_resolves_every_two_qubit_pauli(self):\n        # Hand-derived Bell syndromes, phase bit then bit-flip bit, per wire.\n        syndromes = {'I':[0,0], 'X':[0,1], 'Y':[1,1], 'Z':[1,0]}\n        with tempfile.TemporaryDirectory() as tmp:\n            for first, second in itertools.product('IXYZ', repeat=2):\n                text = channel_probes.bell_text(f'{first} 0\\n{second} 1'.replace('I 0\\n','').replace('I 1',''), 2)\n                expected = np.tile(syndromes[first]+syndromes[second], (16,1))\n                with self.subTest(pauli=first+second):\n                    np.testing.assert_array_equal(reference.sample(text,16), expected)\n                    np.testing.assert_array_equal(correctness.rust_rows(ROOT/'target/release/rustqec', text,16,7,Path(tmp)), expected)\n\n    def test_ix_only_channel_fails_overall_sampling_report(self):\n        original = correctness.rust_rows\n        def defective(binary,text,shots,seed,work):\n            return original(binary, channel_probes.replace_channel(text,'DEPOLARIZE2_ix_only'), shots,seed,work)\n        with patch('benchmarks.atom_loss.correctness.rust_rows', side_effect=defective):\n            report = correctness.run(ROOT/'target/release/rustqec')\n        self.assertEqual(report['status'], 'FAIL')\n        probes = report['analytic_noise_controls']['distribution_probes']\n        self.assertEqual(probes['status'], 'FAIL')\n        product = next(c for c in probes['cases'] if c['case']=='DEPOLARIZE2_product_ZZ')\n        self.assertEqual(product['status'], 'FAIL')\n        self.assertEqual(product['rust']['marginals'][0], 0.)\n        self.assertAlmostEqual(product['expected_marginals'][0],8*.17/15)\n        # The old single parity signature agreed; the first marginal exposes it.\n        bell = next(c for c in probes['cases'] if c['case']=='DEPOLARIZE2_bell_p0.6')\n        self.assertEqual(bell['status'], 'FAIL')\n        self.assertEqual(len(bell['expected_joint']),16)\n\n    def test_deleted_two_qubit_channel_fails_same_acceptance(self):\n        original=correctness.rust_rows\n        def defective(binary,text,shots,seed,work):\n            text='\\n'.join(line for line in text.splitlines() if not line.startswith('DEPOLARIZE2('))\n            return original(binary,text,shots,seed,work)\n        with patch('benchmarks.atom_loss.correctness.rust_rows',side_effect=defective):\n            report=correctness.run(ROOT/'target/release/rustqec')\n        self.assertEqual(report['status'],'FAIL')\n        analytic=report['analytic_noise_controls']\n        case=next(r for r in analytic['cases'] if r['case']=='DEPOLARIZE2_alive')\n        self.assertEqual(case['status'],'FAIL')\n        self.assertEqual(case['rust_probability'],0.)\n        self.assertAlmostEqual(case['expected_probability'],8*.17/15)\n\n    def test_exact_parity_costs_match_exhaustive_fault_choices(self):\n        terms=[(1,1.1),(2,.3),(3,.4),(5,.7),(1,.2)]\n        expected=np.full(8,np.inf)\n        for choices in itertools.product([0,1],repeat=len(terms)):\n            mask=0; cost=0.\n            for choose,(effect,weight) in zip(choices,terms):\n                if choose: mask^=effect; cost+=weight\n            expected[mask]=min(expected[mask],cost)\n        np.testing.assert_allclose(chain_reference.costs(terms,3),expected)\n        self.assertEqual(chain_reference.allowed(np.array([0.,1.,0.,1.]),1,1),{0,1})\n        with self.assertRaises(ValueError): chain_reference.allowed(np.array([np.inf,np.inf]),0,0)\n\n    def test_incomplete_comparison_cannot_be_published_as_a_curve(self):\n        cases=[{'distance':d,'loss_probability':p,'decoders':{name:{'status':'ok'} for name in\n                ['envelope-matching','pymatching-fixed','pymatching-envelope','envelope-matching-offline']}}\n               for d in [3,5,7] for p in [.0001,.0003,.001,.003,.01]]\n        require_complete_sweep(cases)\n        with self.assertRaises(ValueError): require_complete_sweep(cases[:-1])\n        cases[0]['decoders']['pymatching-fixed']['status']='failed'\n        with self.assertRaises(ValueError): require_complete_sweep(cases)\n        del cases[0]['decoders']['pymatching-fixed']\n        with self.assertRaises(ValueError): require_complete_sweep(cases)\n\n    def test_logical_support_is_derived_from_coordinates(self):\n        text='QUBIT_COORDS(1,5) 15\\nQUBIT_COORDS(2,2) 9\\nQUBIT_COORDS(1,1) 1\\nQUBIT_COORDS(1,3) 8'\n        self.assertEqual(logical_x(text,3),'15,1,8')\n        with self.assertRaises(ValueError): logical_x(text,5)\n\n\nif __name__=='__main__': unittest.main()\n",
    "benchmarks/atom_loss/test_sampler_mutations.py": "\"\"\"Retained negative controls must support their rejection claims from observations.\"\"\"\nimport copy\nimport json\nfrom pathlib import Path\nimport subprocess\nimport sys\nimport tempfile\nimport unittest\n\nfrom . import correctness, low_probability\nfrom .report_contract import verify_sampler\n\nROOT = Path(__file__).resolve().parents[2]\n\n\nclass SamplerMutationEvidenceTests(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        # One executed experiment supplies every test; individual report mutations\n        # never rerun sampling or substitute fabricated positive observations.\n        cls.report = correctness.run(ROOT/'target/release/rustqec')\n        if cls.report['status'] != 'PASS':\n            raise ValueError('Fresh sampling experiment failed')\n\n    def test_producer_retains_complete_negative_observations(self):\n        report = self.report\n        analytic = report['analytic_noise_controls']\n        for family in [analytic['channel_deletion_mutations'],\n                       analytic['distribution_probes']['channel_replacement_mutations']]:\n            for control in family.values():\n                self.assertEqual(control['failed_cases'],\n                                 [r['case'] for r in control['observations'] if r['status']=='FAIL'])\n                self.assertTrue(control['rejected'])\n        unit = report['low_probability_controls']['analytic']\n        intervals = {r['case']:r['accepted_counts'] for r in unit['cases']}\n        for kind,control in unit['low_probability_deletion_mutations'].items():\n            expected = {name:removed for name,text,_,_ in low_probability.specifications()\n                        if (removed:=low_probability.remove_low_noise(text,kind)[1])}\n            self.assertEqual({r['case']:r['removed_instructions'] for r in control['observations']}, expected)\n            self.assertEqual(set(control['failed_cases']),set(expected))\n            for observation in control['observations']:\n                self.assertTrue(any(k<lo or k>hi for k,(lo,hi) in\n                                    zip(observation['counts'],intervals[observation['case']],strict=True)))\n        for control in report['low_probability_controls']['real_circuit']['low_probability_deletion_mutations'].values():\n            self.assertEqual(control['failed_events'],control['comparison']['failed_events'])\n            self.assertEqual(len(control['comparison']['events']),196)\n        verify_sampler(report)\n\n    def corrupted_reports(self):\n        cases = []\n        def mutate(label, action):\n            report = copy.deepcopy(self.report)\n            action(report)\n            cases.append((label, report))\n        def low(report):\n            return report['low_probability_controls']['analytic']['low_probability_deletion_mutations']['pauli']\n        def noise(report):\n            return report['analytic_noise_controls']['channel_deletion_mutations']['X_ERROR']\n        def distribution(report):\n            return report['analytic_noise_controls']['distribution_probes']['channel_replacement_mutations']['DEPOLARIZE2_ix_only']\n        def real(report):\n            return report['low_probability_controls']['real_circuit']['low_probability_deletion_mutations']['pauli']\n\n        mutate('original truncated failure list',lambda r:low(r).update(failed_cases=low(r)['failed_cases'][:1]))\n        mutate('unaffected LOSS_0.01 witness',lambda r:low(r).update(failed_cases=['LOSS_0.01']))\n        mutate('missing negative observations',lambda r:low(r).pop('observations'))\n        mutate('missing affected probe',lambda r:low(r)['observations'].pop())\n        mutate('duplicate affected probe',lambda r:low(r)['observations'].append(copy.deepcopy(low(r)['observations'][0])))\n        mutate('unaffected probe raw record',lambda r:low(r)['observations'][0].update(case='LOSS_0.01'))\n        mutate('false mutation verdict',lambda r:low(r).update(rejected=False))\n        mutate('altered deleted instruction count',lambda r:low(r)['observations'][0].update(removed_instructions=2))\n        mutate('incomplete raw counts',lambda r:low(r)['observations'][0].update(counts=[]))\n        def healthy_low(report):\n            healthy = {r['case']:r['counts']['rust'] for r in report['low_probability_controls']['analytic']['cases']}\n            for observation in low(report)['observations']:\n                observation['counts'] = healthy[observation['case']]\n        mutate('healthy observations cannot claim channel deletion rejected',healthy_low)\n        mutate('analytic healthy observations cannot claim rejection',\n               lambda r:noise(r).update(observations=copy.deepcopy(r['analytic_noise_controls']['cases'])))\n        mutate('analytic unrelated witness',lambda r:noise(r).update(failed_cases=['Z_ERROR_alive']))\n        mutate('distribution missing observations',lambda r:distribution(r).update(observations=[]))\n        mutate('distribution altered raw marginal',\n               lambda r:distribution(r)['observations'][0]['rust'].update(marginals=[]))\n        mutate('distribution healthy observations cannot claim rejection',lambda r:distribution(r).update(\n            observations=copy.deepcopy(r['analytic_noise_controls']['distribution_probes']['cases'])))\n        mutate('real circuit missing raw events',lambda r:real(r)['comparison'].update(events=[]))\n        mutate('real circuit false event count',lambda r:real(r)['comparison']['events'][0].update(rust_events=999999))\n        mutate('real circuit stale pvalue',lambda r:real(r)['comparison']['events'][0].update(pvalue=-1.))\n        mutate('real circuit false rejection list',lambda r:real(r).update(failed_events=[]))\n        mutate('real circuit wrong removed instructions',lambda r:real(r).update(removed_instructions=1))\n        return cases\n\n    def test_negative_claims_are_recomputed_from_raw_observations(self):\n        for label,report in self.corrupted_reports():\n            with self.subTest(mutation=label), self.assertRaises((ValueError,KeyError)):\n                verify_sampler(report)\n\n    def test_optimized_python_rejects_the_same_negative_claims(self):\n        script = '''import json,sys\nfrom benchmarks.atom_loss.report_contract import verify_sampler\nhealthy,cases=json.load(open(sys.argv[1]))\nverify_sampler(healthy)\nfor label,report in cases:\n    try:\n        verify_sampler(report)\n    except (ValueError,KeyError):\n        continue\n    raise RuntimeError('Accepted corrupted negative evidence: '+label)\nprint('PASS: optimized negative-observation checks')\n'''\n        with tempfile.TemporaryDirectory(prefix='sampler-mutations-') as tmp:\n            path = Path(tmp)/'reports.json'\n            path.write_text(json.dumps([self.report,self.corrupted_reports()]))\n            result = subprocess.run([sys.executable,'-O','-c',script,str(path)],cwd=ROOT,\n                                    capture_output=True,text=True,timeout=120)\n        self.assertEqual(result.returncode,0,result.stdout+result.stderr)\n\n\nif __name__ == '__main__':\n    unittest.main()\n",
    "benchmarks/atom_loss/test_source_contract.py": "\"\"\"Adversarial source-binding and actual decoder replay regression tests.\"\"\"\nimport copy\nimport hashlib\nimport json\nfrom pathlib import Path\nimport subprocess\nimport sys\nimport tempfile\nimport unittest\nimport zipfile\nfrom .source_contract import clean_source, verify_source, ROOT\n\n\nclass SourceContractTests(unittest.TestCase):\n    def setUp(self):\n        self.temp = tempfile.TemporaryDirectory()\n        self.addCleanup(self.temp.cleanup)\n        self.repo = Path(self.temp.name)\n        self.git('init', '-q')\n        self.git('config', 'user.email', 'test@example.invalid')\n        self.git('config', 'user.name', 'Source test')\n        self.write('Cargo.toml', '[workspace]\\nmembers = [\"decoder\"]\\n')\n        self.write('decoder/src/lib.rs', '// measured decoder\\n')\n        self.write('decoder/build.rs', '// measured build\\n')\n        self.write('benchmarks/atom_loss/run.py', '# measured harness\\n')\n        self.write('benchmarks/atom_loss/requirements.txt',\n                   (ROOT/'benchmarks/atom_loss/requirements.txt').read_text())\n        self.commit()\n        self.record = clean_source(self.repo)\n\n    def git(self, *args):\n        return subprocess.check_output(['git', '-C', str(self.repo), *args], stderr=subprocess.STDOUT)\n\n    def write(self, name, text):\n        path = self.repo/name; path.parent.mkdir(parents=True, exist_ok=True); path.write_text(text)\n\n    def commit(self):\n        self.git('add', '.'); self.git('commit', '-qm', 'test source')\n\n    def test_later_artifact_commit_valid_but_changed_decoder_fails(self):\n        self.write('site/static/data/result.json', '{}'); self.commit()\n        self.assertEqual(verify_source(self.record, self.repo), self.record['source_commit'])\n        self.write('decoder/src/lib.rs', '// different decoder\\n'); self.commit()\n        with self.assertRaisesRegex(ValueError, 'Current source/build inputs differ'):\n            verify_source(self.record, self.repo)\n\n    def test_missing_inventory_and_new_build_input_rejected(self):\n        record = copy.deepcopy(self.record); del record['inputs']['decoder/build.rs']\n        with self.assertRaisesRegex(ValueError, 'source inventory'):\n            verify_source(record, self.repo)\n        self.write('.cargo/config.toml', '[build]\\nrustflags = [\"-C\", \"opt-level=0\"]\\n'); self.commit()\n        with self.assertRaisesRegex(ValueError, 'Current source/build inputs differ'):\n            verify_source(self.record, self.repo)\n\n    def test_dirty_generation_and_dirty_verification_rejected(self):\n        self.write('benchmarks/atom_loss/run.py', '# changed harness\\n')\n        with self.assertRaisesRegex(ValueError, 'clean checkout'):\n            clean_source(self.repo)\n        with self.assertRaisesRegex(ValueError, 'Dirty source input'):\n            verify_source(self.record, self.repo)\n\n    def test_new_untracked_build_input_is_rejected(self):\n        self.write('.cargo/config.toml', '[build]\\nrustflags = []\\n')\n        with self.assertRaisesRegex(ValueError, 'Uncommitted source input'):\n            verify_source(self.record, self.repo)\n\n    def test_ignored_local_cargo_config_is_rejected(self):\n        from .source_contract import build_environment\n        self.write('.git/info/exclude', '.cargo/\\n')\n        self.write('.cargo/config.toml', '[profile.release]\\nopt-level=0\\n')\n        for check in [lambda:clean_source(self.repo), lambda:verify_source(self.record,self.repo),\n                      lambda:build_environment(self.repo,self.repo.parent/'unused-cargo-home')]:\n            with self.assertRaisesRegex(ValueError, 'Cargo configuration must be tracked'):\n                check()\n\n    def test_optimized_python_rejects_old_results_after_source_change(self):\n        record_path = self.repo/'record.json'; record_path.write_text(json.dumps(self.record))\n        self.write('decoder/src/lib.rs', '// changed\\n'); self.commit()\n        program = ('from pathlib import Path; import json; '\n                   'from benchmarks.atom_loss.source_contract import verify_source; '\n                   'verify_source(json.loads(Path(__import__(\"sys\").argv[1]).read_text()), Path(__import__(\"sys\").argv[2]))')\n        for flags in [[], ['-O']]:\n            result = subprocess.run([sys.executable, *flags, '-c', program, str(record_path), str(self.repo)], capture_output=True, text=True, cwd=ROOT)\n            self.assertNotEqual(result.returncode, 0)\n            self.assertIn('Current source/build inputs differ', result.stderr)\n\n    def runtime_bundle(self):\n        \"\"\"A committed source fixture with internally consistent historical metadata.\"\"\"\n        from .source_contract import BINARIES, CAPTURE_DEPENDENCIES, THREAD_ENVIRONMENT\n        out = self.repo/'evidence'; out.mkdir()\n        binding = copy.deepcopy(self.record)\n        binding.update(binaries={name:'a'*64 for name in BINARIES},\n                       rustc='recorded historical rustc, not the verifier compiler',\n                       build_environment={'PATH':'/recorded/bin', 'HOME':'/recorded/home',\n                           'CARGO_HOME':'/recorded/cargo', 'LANG':'C', 'LC_ALL':'C', **THREAD_ENVIRONMENT})\n        requirements = dict(line.split('==') for line in\n                            (self.repo/'benchmarks/atom_loss/requirements.txt').read_text().splitlines()\n                            if line and not line.startswith('#'))\n        sources = {name:(self.repo/name).read_text() for name in binding['inputs']\n                   if name.startswith('benchmarks/atom_loss/')}\n        stage = {'source_commit':binding['source_commit'], 'working_tree_dirty':False,\n                 'input_digest':binding['input_digest'], 'binaries':binding['binaries'],\n                 'rustc':binding['rustc'], 'dependencies':{p:requirements[p] for p in CAPTURE_DEPENDENCIES},\n                 'environment':dict(THREAD_ENVIRONMENT), 'cpu':'Recorded historical CPU',\n                 'os':'Recorded historical OS', 'python':'Recorded historical Python',\n                 'sources':{name:hashlib.sha256(text.encode()).hexdigest() for name,text in sources.items()}}\n        (out/'source-manifest.json').write_text(json.dumps(binding))\n        for suffix in ['all','seeds']:\n            (out/f'provenance-{suffix}.json').write_text(json.dumps(stage))\n            snapshot = 'source-snapshot.json' if suffix=='all' else 'source-snapshot-seeds.json'\n            (out/snapshot).write_text(json.dumps({'base_commit':binding['source_commit'], 'files':sources}))\n        return out, binding, stage\n\n    def test_runtime_provenance_contract_in_normal_and_optimized_python(self):\n        out, binding, stage = self.runtime_bundle()\n        program = ('from pathlib import Path; import sys; '\n                   'from benchmarks.atom_loss.source_contract import verify_bundle_source; '\n                   'print(verify_bundle_source(Path(sys.argv[1]), Path(sys.argv[2])))')\n        def verify(flags):\n            return subprocess.run([sys.executable,*flags,'-c',program,str(out),str(self.repo)],\n                                  capture_output=True,text=True,cwd=ROOT)\n        defects = {\n            'dependency_version': (lambda r:r['dependencies'].update(pymatching='999.0.0'), 'dependencies'),\n            'missing_dependency': (lambda r:r['dependencies'].pop('stim'), 'dependencies'),\n            'extra_dependency': (lambda r:r['dependencies'].update(unrecorded='1.0'), 'dependencies'),\n            'compiler': (lambda r:r.update(rustc='contradicts manifest'), 'compiler'),\n            'missing_compiler': (lambda r:r.pop('rustc'), 'compiler'),\n            'cpu': (lambda r:r.update(cpu='different CPU'), 'runtime'),\n            'os': (lambda r:r.update(os='different OS'), 'runtime'),\n            'python': (lambda r:r.update(python='different Python'), 'runtime'),\n            'missing_cpu': (lambda r:r.pop('cpu'), 'runtime'),\n            'non_string_os': (lambda r:r.update(os=123), 'runtime'),\n            'empty_python': (lambda r:r.update(python='  '), 'runtime'),\n            'thread_count': (lambda r:r['environment'].update(OMP_NUM_THREADS='999'), 'threading'),\n            'numeric_thread_count': (lambda r:r['environment'].update(OPENBLAS_NUM_THREADS=1), 'threading'),\n            'missing_thread_count': (lambda r:r['environment'].pop('RAYON_NUM_THREADS'), 'threading'),\n            'extra_thread_setting': (lambda r:r['environment'].update(UNKNOWN_THREADS='1'), 'threading'),\n        }\n        for flags in [[],['-O']]:\n            # A different but internally consistent historical host is accepted.\n            result = verify(flags)\n            self.assertEqual(result.returncode,0,result.stderr)\n            self.assertEqual(result.stdout.strip(),binding['source_commit'])\n            for name,(mutate,error) in defects.items():\n                with self.subTest(flags=flags,defect=name):\n                    changed=copy.deepcopy(stage);mutate(changed)\n                    (out/'provenance-seeds.json').write_text(json.dumps(changed))\n                    result=verify(flags)\n                    self.assertNotEqual(result.returncode,0)\n                    self.assertIn('ValueError',result.stderr)\n                    self.assertIn(error,result.stderr)\n            (out/'provenance-seeds.json').write_text(json.dumps(stage))\n            # Agreement between stages cannot override requirements/build/thread pins.\n            for name in ['dependency_version','compiler','thread_count']:\n                with self.subTest(flags=flags,all_stages=name):\n                    changed=copy.deepcopy(stage);mutate,error=defects[name];mutate(changed)\n                    for suffix in ['all','seeds']:\n                        (out/f'provenance-{suffix}.json').write_text(json.dumps(changed))\n                    result=verify(flags)\n                    self.assertNotEqual(result.returncode,0)\n                    self.assertIn(error,result.stderr)\n            for suffix in ['all','seeds']:\n                (out/f'provenance-{suffix}.json').write_text(json.dumps(stage))\n\n    def test_runtime_provenance_requires_a_recorded_build_compiler(self):\n        from .source_contract import verify_bundle_source\n        out, binding, _ = self.runtime_bundle()\n        for value in [None, '', '  ', 123]:\n            with self.subTest(value=value):\n                binding['rustc']=value\n                (out/'source-manifest.json').write_text(json.dumps(binding))\n                with self.assertRaisesRegex(ValueError,'recorded build compiler'):\n                    verify_bundle_source(out,self.repo)\n\n\nclass DecoderReplayTests(unittest.TestCase):\n    def test_actual_wrong_decoder_with_unchanged_archive_is_rejected(self):\n        from .decoder_replay import replay_case\n        from .shot_data import cases_from\n        binary = ROOT/'target/release/rustqec'\n        exporter = ROOT/'target/release/examples/export_matching_benchmark'\n        with tempfile.TemporaryDirectory() as tmp, zipfile.ZipFile(ROOT/'site/static/data/atom-loss/shot-data-v1.zip') as z:\n            path = Path(tmp); label, case = cases_from(z.read)[0]\n            # Positive control exercises real current compiler + all four backends.\n            self.assertEqual(replay_case(z, label, case, path/'good', binary, exporter, False), 4)\n            wrapper = path/'wrong-decoder'\n            wrapper.write_text('#!'+sys.executable+'\\nimport pathlib, subprocess, sys\\n'\n                +'subprocess.run(['+repr(str(binary))+', *sys.argv[1:]], check=True)\\n'\n                +'p=pathlib.Path(sys.argv[sys.argv.index(\"--out\")+1])\\n'\n                +'b=bytearray(p.read_bytes()); b[0]^=1; p.write_bytes(b)\\n')\n            wrapper.chmod(0o755)\n            with self.assertRaisesRegex(ValueError, 'Current decoder differs from archive'):\n                replay_case(z, label, case, path/'bad', wrapper, exporter, False)\n\n    def test_current_workload_counters_are_replayed_without_historical_durations(self):\n        from .decoder_replay import decode_current, verify_work_observations, replay_case\n        from .shot_data import cases_from\n        binary=ROOT/'target/release/rustqec';exporter=ROOT/'target/release/examples/export_matching_benchmark'\n        with tempfile.TemporaryDirectory() as tmp, zipfile.ZipFile(ROOT/'site/static/data/atom-loss/shot-data-v1.zip') as z:\n            path=Path(tmp);label,case=cases_from(z.read)[0]\n            public=path/'probe/public';public.mkdir(parents=True)\n            for name in ['manifest.json','circuit.stim','shots.b8']:\n                (public/name).write_bytes(z.read(f'{label}/public/{name}'))\n            _,observations,graph=decode_current(path/'probe',binary,exporter,case['decoders'])\n            verify_work_observations(case,observations,graph,label)\n            changed=copy.deepcopy(case)\n            changed['graph']['compile_seconds']=999.\n            for entry in changed['decoders'].values():\n                for run in entry['runs']:\n                    run['compile_seconds']=999.\n            verify_work_observations(changed,observations,graph,label)\n            for backend,section,field in [('envelope-matching','stats','primitive_probe_count'),\n                    ('envelope-matching','stats','cache_hits'),\n                    ('envelope-matching-offline','batch','graph_builds'),\n                    ('pymatching-envelope',None,'batch_calls'),('pymatching-fixed',None,'graph_api')]:\n                changed=copy.deepcopy(case)\n                record=changed['decoders'][backend]['runs'][0]\n                record=record[section] if section else record\n                record[field]='wrong' if field=='graph_api' else record[field]+1\n                with self.subTest(backend=backend,field=field),self.assertRaisesRegex(ValueError,'Current workload metadata'):\n                    verify_work_observations(changed,observations,graph,label)\n            changed=copy.deepcopy(case);changed['graph']['edges']+=1\n            with self.assertRaisesRegex(ValueError,'Current workload metadata'):\n                verify_work_observations(changed,observations,graph,label)\n            # Execute a real decoder whose predictions are unchanged but its\n            # output stats are defective. The integrated replay must reject it.\n            wrapper=path/'wrong-stats'\n            wrapper.write_text('#!'+sys.executable+'\\nimport json,pathlib,subprocess,sys\\n'\n                +'subprocess.run(['+repr(str(binary))+', *sys.argv[1:]],check=True)\\n'\n                +'p=pathlib.Path(sys.argv[sys.argv.index(\"--stats-out\")+1])\\n'\n                +'s=json.loads(p.read_text());s[\"primitive_probe_count\"]+=1;p.write_text(json.dumps(s))\\n')\n            wrapper.chmod(0o755)\n            with self.assertRaisesRegex(ValueError,'Current workload metadata'):\n                replay_case(z,label,case,path/'bad-stats',wrapper,exporter,False)\n            # Run the same actual wrapper through optimized Python, rather than\n            # checking only a hand-built comparison dictionary.\n            program=('import pathlib,zipfile,sys; from benchmarks.atom_loss.decoder_replay import replay_case; '\n                'from benchmarks.atom_loss.shot_data import cases_from; '\n                'z=zipfile.ZipFile(sys.argv[1]); label,case=cases_from(z.read)[0]; '\n                'replay_case(z,label,case,pathlib.Path(sys.argv[2]),pathlib.Path(sys.argv[3]),pathlib.Path(sys.argv[4]),False)')\n            result=subprocess.run([sys.executable,'-O','-c',program,str(ROOT/'site/static/data/atom-loss/shot-data-v1.zip'),\n                str(path/'bad-optimized'),str(wrapper),str(exporter)],cwd=ROOT,capture_output=True,text=True)\n            self.assertNotEqual(result.returncode,0)\n            self.assertIn('Current workload metadata',result.stderr)\n\n\n\nclass BuildEnvironmentTests(unittest.TestCase):\n    def test_real_entrypoint_ignores_inherited_profile_override(self):\n        \"\"\"A real release build must stay optimized despite ambient profile flags.\"\"\"\n        import os\n        from unittest.mock import patch\n        from . import evidence_run, source_contract\n        real_run = subprocess.run\n        class BuildComplete(Exception):\n            pass\n        with tempfile.TemporaryDirectory() as tmp:\n            base = Path(tmp); repo = base/'repo'; repo.mkdir()\n            files = {\n                'Cargo.toml': '[workspace]\\nmembers=[\"rustqec-cli\"]\\nresolver=\"2\"\\n',\n                'rustqec-cli/Cargo.toml': '[package]\\nname=\"rustqec-cli\"\\nversion=\"0.1.0\"\\nedition=\"2021\"\\n[features]\\nbenchmark-tools=[]\\nilp=[]\\n[[bin]]\\nname=\"rustqec\"\\npath=\"src/main.rs\"\\n',\n                'rustqec-cli/src/main.rs': 'fn main(){println!(\"debug_assertions={}\",cfg!(debug_assertions));}\\n',\n                'benchmarks/atom_loss/requirements.txt': '',\n            }\n            for name in ['export_matching_benchmark','export_decoder_oracle','offline_matching_benchmark']:\n                files[f'rustqec-cli/examples/{name}.rs'] = 'fn main(){}\\n'\n            for name, data in files.items():\n                path = repo/name; path.parent.mkdir(parents=True, exist_ok=True); path.write_text(data)\n            real_run(['cargo','generate-lockfile'], cwd=repo, check=True, capture_output=True)\n            for args in [['init','-q'],['config','user.email','test@example.invalid'],['config','user.name','Test'],['add','.'],['commit','-qm','fixture']]:\n                real_run(['git',*args], cwd=repo, check=True, capture_output=True)\n            (repo/'.git/info/exclude').write_text('target/\\n')\n            def build_then_stop(args, **kwargs):\n                if list(args) == source_contract.BUILD_COMMANDS[0]:\n                    result = real_run(args, **kwargs, capture_output=True, text=True)\n                    self.assertIn('[optimized]', result.stderr)\n                    self.assertEqual(subprocess.check_output([repo/'target/release/rustqec'], text=True).strip(), 'debug_assertions=false')\n                    self.assertNotIn('CARGO_PROFILE_RELEASE_OPT_LEVEL', kwargs['env'])\n                    self.assertNotIn('CARGO_PROFILE_RELEASE_DEBUG_ASSERTIONS', kwargs['env'])\n                    raise BuildComplete\n                return real_run(args, **kwargs)\n            overrides = {'CARGO_PROFILE_RELEASE_OPT_LEVEL':'0', 'CARGO_PROFILE_RELEASE_DEBUG_ASSERTIONS':'true'}\n            with patch.object(evidence_run,'ROOT',repo), patch.object(evidence_run,'clean_source',lambda:source_contract.clean_source(repo)), patch.object(sys,'argv',['evidence_run','--out',str(base/'out'),'--work',str(base/'work')]), patch.dict(os.environ,overrides), patch.object(subprocess,'run',build_then_stop):\n                with self.assertRaises(BuildComplete):\n                    evidence_run.main()\n\n    def test_external_ancestor_config_is_rejected_before_build(self):\n        from .source_contract import build_environment\n        with tempfile.TemporaryDirectory() as tmp:\n            base = Path(tmp); repo = base/'repo'; repo.mkdir()\n            (base/'.cargo').mkdir()\n            (base/'.cargo/config.toml').write_text('[profile.release]\\nopt-level=0\\n')\n            with self.assertRaisesRegex(ValueError, 'External ancestor Cargo configuration'):\n                build_environment(repo, base/'fresh-cargo-home')\n\n\nclass WorkloadMetadataTests(unittest.TestCase):\n    def test_resealed_false_pauli_metadata_rejected_in_every_report(self):\n        import hashlib\n        import shutil\n        from .verify import verify\n        from .shot_data import rescore, rescore_seeds\n        for report_name, archive_name in [('decoding.json','shot-data-v1.zip'), ('tradeoff.json','shot-data-v1.zip'), ('accuracy-seeds.json','accuracy-seeds.zip')]:\n            with self.subTest(report=report_name), tempfile.TemporaryDirectory() as tmp:\n                root = Path(tmp)/'bundle'; shutil.copytree(ROOT/'site/static/data/atom-loss',root)\n                report = json.loads((root/report_name).read_text())\n                cases = report if isinstance(report,list) else report['cases'] if report_name=='accuracy-seeds.json' else [report]\n                cases[0]['pauli_probability'] = .5\n                (root/report_name).write_text(json.dumps(report))\n                with zipfile.ZipFile(root/archive_name) as z:\n                    payload = {name:z.read(name) for name in z.namelist()}\n                payload[report_name] = (root/report_name).read_bytes()\n                index = json.loads(payload['index.json'])\n                index['sha256'][report_name] = hashlib.sha256(payload[report_name]).hexdigest()\n                payload['index.json'] = json.dumps(index).encode()\n                with zipfile.ZipFile(root/archive_name,'w',compression=zipfile.ZIP_DEFLATED) as z:\n                    for name,data in payload.items(): z.writestr(name,data)\n                bundle = json.loads((root/'bundle.json').read_text())\n                for name in [report_name,archive_name]:\n                    bundle['sha256'][name] = hashlib.sha256((root/name).read_bytes()).hexdigest()\n                (root/'bundle.json').write_text(json.dumps(bundle))\n                with self.assertRaisesRegex(ValueError,'Declared Pauli probability'):\n                    verify(root)\n                with self.assertRaisesRegex(ValueError,'Declared Pauli probability'):\n                    (rescore_seeds if archive_name=='accuracy-seeds.zip' else rescore)(root/archive_name)\n\n    def test_generator_uses_declared_pauli_probability(self):\n        from .run import generate\n        with tempfile.TemporaryDirectory() as tmp:\n            low, high = Path(tmp)/'low.stim', Path(tmp)/'high.stim'\n            generate(ROOT/'target/release/rustqec',low,3,2,.003,.001)\n            generate(ROOT/'target/release/rustqec',high,3,2,.003,.5)\n            self.assertNotEqual(low.read_bytes(),high.read_bytes())\n            self.assertIn('DEPOLARIZE2(0.5)', high.read_text())\n\n\nif __name__ == '__main__':\n    unittest.main()\n",
    "benchmarks/atom_loss/test_standalone_contract.py": "\"\"\"Exercise the downloadable stdlib-only checker against coherently resealed ZIPs.\"\"\"\nimport hashlib\nimport json\nfrom pathlib import Path\nimport subprocess\nimport sys\nimport tempfile\nimport unittest\nimport zipfile\n\nfrom .shot_data import original_plan\n\nROOT = Path(__file__).resolve().parents[2]\nSOURCE = ROOT/'site/static/data/atom-loss'\nSCRIPT = Path(__file__).with_name('shot_data.py')\nPAIR_KEYS = ('disagreements_with_native', 'paired_native_only_wrong', 'paired_python_only_wrong')\n\n\ndef resealed(payload, path):\n    index = json.loads(payload['index.json'])\n    index['sha256'] = {name: hashlib.sha256(data).hexdigest()\n                       for name, data in payload.items() if name != 'index.json'}\n    payload = {**payload, 'index.json': json.dumps(index).encode()}\n    with zipfile.ZipFile(path, 'w', compression=zipfile.ZIP_DEFLATED) as archive:\n        for name, data in payload.items():\n            archive.writestr(name, data)\n\n\nclass StandaloneTests(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        with zipfile.ZipFile(SOURCE/'shot-data-v1.zip') as archive:\n            cls.original = {name: archive.read(name) for name in archive.namelist()}\n        with zipfile.ZipFile(SOURCE/'accuracy-seeds.zip') as archive:\n            cls.seeded = {name: archive.read(name) for name in archive.namelist()}\n\n    def check_cli(self, archive, command, *, accepted):\n        for optimize in ([], ['-O']):\n            with self.subTest(optimize=optimize):\n                # Copy the single file to a directory without the repository or dependencies.\n                script = archive.parent/'rescore.py'\n                script.write_bytes(SCRIPT.read_bytes())\n                result = subprocess.run([sys.executable, '-I', '-S', *optimize, str(script), command, str(archive)],\n                                        cwd=archive.parent, text=True, capture_output=True)\n                if accepted:\n                    self.assertEqual(result.returncode, 0, result.stderr)\n                    self.assertIn('198 prediction files' if command == 'rescore' else '147 predictions', result.stdout)\n                else:\n                    self.assertNotEqual(result.returncode, 0, result.stdout)\n                    self.assertIn('Dataset contract:', result.stderr)\n                    self.assertNotIn('ModuleNotFoundError', result.stderr)\n\n    def test_complete_archives_pass_without_repository_or_site_packages(self):\n        with tempfile.TemporaryDirectory() as temp:\n            for name, payload, command in [('original.zip', self.original, 'rescore'),\n                                           ('seeds.zip', self.seeded, 'rescore-seeds')]:\n                path = Path(temp)/name\n                resealed(payload, path)\n                self.check_cli(path, command, accepted=True)\n\n    def test_removed_comparator_and_prediction_members_cannot_redefine_completeness(self):\n        payload = self.original.copy()\n        for filename in ('decoding.json', 'tradeoff.json'):\n            data = json.loads(payload[filename])\n            for case in data if isinstance(data, list) else [data]:\n                case['decoders'].pop('pymatching-envelope')\n            payload[filename] = json.dumps(data).encode()\n        for name in list(payload):\n            if '/pymatching-envelope-' in name:\n                del payload[name]\n        with tempfile.TemporaryDirectory() as temp:\n            path = Path(temp)/'missing-comparator.zip'\n            resealed(payload, path)\n            self.check_cli(path, 'rescore', accepted=False)\n\n    def test_fixed_plan_rejects_unknown_missing_duplicate_or_relabelled_settings(self):\n        sweep = json.loads(self.original['decoding.json'])\n        tradeoff = json.loads(self.original['tradeoff.json'])\n        cases = [(f\"d{c['distance']}-p{c['loss_probability']}\", c) for c in sweep]+[('tradeoff', tradeoff)]\n        for changed in [cases[:-1], cases[:-1]+[cases[0]], [('d9-p0.01', cases[0][1])]+cases[1:]]:\n            with self.subTest(labels=[label for label, _ in changed]), self.assertRaises(ValueError):\n                original_plan(changed)\n        # A wrong distance must fail even when its archive label is left intact.\n        altered = json.loads(json.dumps(cases))\n        altered[0][1]['distance'] = 9\n        with self.assertRaises(ValueError):\n            original_plan(altered)\n\n    def test_resealed_original_score_plan_and_pair_attacks_fail_in_both_modes(self):\n        def set_score(key, value):\n            return lambda c: c['decoders']['envelope-mle'].__setitem__(key, value)\n        def set_pair(key, value):\n            return lambda c: c['decoders']['pymatching-envelope'].__setitem__(key, value)\n        mutations = {\n            'wilson-zero': set_score('wilson_95', [0, 0]),\n            'wilson-missing': lambda c: c['decoders']['envelope-mle'].pop('wilson_95'),\n            'wilson-nan': set_score('wilson_95', [0, float('nan')]),\n            'missing-paired': lambda c: [c['decoders']['pymatching-envelope'].pop(k) for k in PAIR_KEYS],\n            'missing-one-pair': lambda c: c['decoders']['pymatching-envelope'].pop(PAIR_KEYS[1]),\n            'bool-pair': set_pair('paired_native_only_wrong', False),\n            'float-pair': set_pair('paired_native_only_wrong', 0.0),\n            'wrong-rounds': lambda c: c.__setitem__('rounds', 999),\n            'wrong-seed': lambda c: c.__setitem__('seed', 20260911),\n            'wrong-shots': lambda c: c.__setitem__('shots', 5000.0),\n            'wrong-loss': lambda c: c.__setitem__('loss_probability', .001),\n            'wrong-pauli': lambda c: c.__setitem__('pauli_probability', .002),\n            'bool-errors': set_score('errors', True),\n            'float-errors': set_score('errors', 1.0),\n            'float-score-shots': set_score('shots', 5000.0),\n            'bool-rate': set_score('logical_error_rate', False),\n            'string-runs': set_score('runs', 'abc'),\n            'missing-repetition': lambda c: c['decoders']['envelope-mle']['runs'].pop(),\n            'empty-repetition': lambda c: c['decoders']['envelope-mle']['runs'].__setitem__(0, {}),\n            'failed-repetition': lambda c: c['decoders']['envelope-mle']['runs'][0].__setitem__('status', 'failed'),\n            'incomplete-shot-outcomes': lambda c: c['decoders']['envelope-mle']['runs'][0]['stats'].__setitem__('attempted_shot_count', 4999),\n            'python-repetition-identity': lambda c: c['decoders']['pymatching-envelope']['runs'][0].__setitem__('export_repetition', 1),\n            'arbitrary-python-record': lambda c: c['decoders']['pymatching-envelope']['runs'].__setitem__(0, {'invented': 1}),\n        }\n        with tempfile.TemporaryDirectory() as temp:\n            for label, mutate in mutations.items():\n                with self.subTest(attack=label):\n                    payload = self.original.copy()\n                    case = json.loads(payload['tradeoff.json'])\n                    mutate(case)\n                    payload['tradeoff.json'] = json.dumps(case).encode()\n                    path = Path(temp)/(label+'.zip')\n                    resealed(payload, path)\n                    self.check_cli(path, 'rescore', accepted=False)\n\n    def test_resealed_seed_score_types_and_mandatory_pairs_fail_in_both_modes(self):\n        mutations = {\n            'bool-rate': lambda r: r['cases'][0]['decoders']['envelope-matching'].__setitem__('logical_error_rate', False),\n            'float-shots': lambda r: r['cases'][0].__setitem__('shots', 5000.0),\n            'float-seed-plan': lambda r: r.__setitem__('shots_per_seed', 5000.0),\n            'missing-pairs': lambda r: r['cases'][0]['paired'].pop('pymatching-envelope'),\n            'bool-pair': lambda r: r['cases'][0]['paired']['pymatching-envelope'].__setitem__('native_only_wrong', False),\n            'float-pooled-shots': lambda r: r['pooled'][0].__setitem__('shots', 15000.0),\n        }\n        with tempfile.TemporaryDirectory() as temp:\n            for label, mutate in mutations.items():\n                with self.subTest(attack=label):\n                    payload = self.seeded.copy()\n                    report = json.loads(payload['accuracy-seeds.json'])\n                    mutate(report)\n                    payload['accuracy-seeds.json'] = json.dumps(report).encode()\n                    path = Path(temp)/(label+'.zip')\n                    resealed(payload, path)\n                    self.check_cli(path, 'rescore-seeds', accepted=False)\n\n\nif __name__ == '__main__':\n    unittest.main()\n",
    "benchmarks/atom_loss/test_workload_contract.py": "\"\"\"Raw-public-row workload checks and fully resealed publication attacks.\"\"\"\nimport copy\nimport hashlib\nimport json\nfrom pathlib import Path\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nimport unittest\nimport zipfile\n\nfrom .plot import render\nfrom .source_contract import ROOT\nfrom .workload_contract import measurement_flags, public_workload, verify_case, verify_workloads\n\n\nSOURCE = ROOT/'site/static/data/atom-loss'\n\n\ndef defects():\n    def counts(case):\n        case['graph']['loss_patterns'] = 1\n        for run in case['decoders']['pymatching-envelope']['runs']:\n            run['graph_builds'] = run['batch_calls'] = 1\n        for run in case['decoders']['envelope-matching-offline']['runs']:\n            run['batch']['graph_builds'] = run['stats']['matching_graph_builds'] = 1\n    def set_run(backend, field, value, nested=None):\n        def mutate(case):\n            run = case['decoders'][backend]['runs'][0]\n            (run if nested is None else run[nested])[field] = value\n        return mutate\n    return {\n        'coherent-pattern-count': counts,\n        'conditioned-calls': set_run('pymatching-envelope', 'batch_calls', 1),\n        'fixed-graph-count': set_run('pymatching-fixed', 'graph_builds', 193),\n        'fixed-loop-cache': set_run('pymatching-fixed-loop', 'cache_hits', 5000),\n        'python-api': set_run('pymatching-envelope', 'graph_api', 'per-edge loop'),\n        'python-policy': set_run('pymatching-envelope', 'execution', 'unrecorded cache'),\n        'offline-stats-mirror': set_run('envelope-matching-offline', 'matching_graph_builds', 1, 'stats'),\n        'offline-policy': set_run('envelope-matching-offline', 'policy', 'FIFO', 'batch'),\n        'offline-boundary': set_run('envelope-matching-offline', 'boundary', 'output excluded', 'batch'),\n        'offline-shots': set_run('envelope-matching-offline', 'shots', 4999, 'batch'),\n        'native-decoder': set_run('envelope-matching', 'decoder', 'envelope-mle', 'stats'),\n        'native-schema': set_run('envelope-matching', 'schema_version', 'unknown', 'stats'),\n        'native-circuit': set_run('envelope-matching', 'circuit_sha256', '0'*64, 'stats'),\n        'native-shot-count': set_run('envelope-matching', 'shot_count', 4999, 'stats'),\n        'native-exact-pattern-count': set_run('envelope-matching', 'distinct_loss_patterns', 1, 'stats'),\n        'native-cache-accounting': set_run('envelope-matching', 'cache_hits', 0, 'stats'),\n        'native-bool-counter': set_run('envelope-matching', 'primitive_probe_count', True, 'stats'),\n        'native-failed-run': set_run('envelope-matching', 'status', 'failed'),\n        'native-exit-code': set_run('envelope-matching', 'exit_code', 1),\n        'native-unknown-counter': set_run('envelope-matching', 'unvalidated_counter', 1, 'stats'),\n        'native-mle-counter': set_run('envelope-matching', 'mle_model_builds', 1, 'stats'),\n        'timing-order': lambda c: c['timing_order'][0].reverse(),\n        'graph-detectors': lambda c: c['graph'].__setitem__('detectors', 999),\n        'graph-observables': lambda c: c['graph'].__setitem__('num_observables', 2),\n        'graph-source': lambda c: c['graph'].__setitem__('source', 'private answers'),\n        'logical-x-support': lambda c: c.__setitem__('logical_x_support', '1'),\n        'workload-rounds': lambda c: c.__setitem__('rounds', 3),\n        'missing-run-field': lambda c: c['decoders']['pymatching-envelope']['runs'][0].pop('batch_calls'),\n    }\n\n\ndef reseal(root, case, *, redraw=False):\n    \"\"\"Update all copies/hashes so failure cannot be ordinary integrity mismatch.\"\"\"\n    data = (json.dumps(case, indent=2)+'\\n').encode()\n    (root/'tradeoff.json').write_bytes(data)\n    archive = root/'shot-data-v1.zip'\n    with zipfile.ZipFile(archive) as z:\n        payload = {name: z.read(name) for name in z.namelist()}\n    payload['tradeoff.json'] = data\n    index = json.loads(payload['index.json'])\n    index['sha256']['tradeoff.json'] = hashlib.sha256(data).hexdigest()\n    payload['index.json'] = (json.dumps(index, indent=2)+'\\n').encode()\n    with zipfile.ZipFile(archive, 'w', compression=zipfile.ZIP_DEFLATED) as z:\n        for name, value in payload.items():\n            z.writestr(name, value)\n    if redraw:\n        render(root)\n    manifest = json.loads((root/'bundle.json').read_text())\n    manifest['sha256'] = {name: hashlib.sha256((root/name).read_bytes()).hexdigest()\n                          for name in manifest['sha256']}\n    (root/'bundle.json').write_text(json.dumps(manifest))\n\n\nclass WorkloadTests(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        cls.case = json.loads((SOURCE/'tradeoff.json').read_text())\n        with zipfile.ZipFile(SOURCE/'shot-data-v1.zip') as z:\n            cls.workload = public_workload(lambda name: z.read('tradeoff/'+name))\n\n    def test_actual_complete_bundle_agrees_with_public_rows_and_fixed_policy(self):\n        verify_workloads(SOURCE)\n        self.assertEqual(self.workload['loss_patterns'], 193)\n\n    def test_flag_positions_expand_nested_repeats_and_skip_plain_measurements(self):\n        text = 'R 0 1\\nM 0\\nREPEAT 2 {\\nML 1\\nREPEAT 2 {\\nMRL 0\\n}\\nM 1\\n}\\n'\n        bits, detectors, observables, flags = measurement_flags(text)\n        self.assertEqual((bits, detectors, observables, flags),\n                         (15, 0, {}, [1, 3, 5, 8, 10, 12]))\n\n    def test_all_fixed_metadata_mutations_fail(self):\n        for label, mutate in defects().items():\n            with self.subTest(defect=label):\n                case = copy.deepcopy(self.case)\n                mutate(case)\n                # The public evidence remains the independent authority.\n                with self.assertRaises((ValueError, KeyError)):\n                    verify_case(case, self.workload, tradeoff=True)\n\n    def test_fully_resealed_attacks_fail_full_verifier_in_both_python_modes(self):\n        selected = ['coherent-pattern-count', 'fixed-loop-cache', 'offline-stats-mirror',\n                    'native-circuit', 'native-bool-counter', 'timing-order', 'python-policy']\n        with tempfile.TemporaryDirectory() as temp:\n            for label in selected:\n                root = Path(temp)/label\n                shutil.copytree(SOURCE, root)\n                case = copy.deepcopy(self.case)\n                defects()[label](case)\n                # Reproduce the originally successful complete, chart-changing attack.\n                reseal(root, case, redraw=label == 'coherent-pattern-count')\n                for flags in [[], ['-O']]:\n                    with self.subTest(defect=label, flags=flags):\n                        result = subprocess.run([sys.executable, *flags, '-m',\n                                                 'benchmarks.atom_loss.verify', str(root)],\n                                                cwd=ROOT, text=True, capture_output=True)\n                        self.assertNotEqual(result.returncode, 0)\n                        # Dirty source/provenance or another unrelated check is not success.\n                        self.assertIn('ValueError: Workload report contract:', result.stderr)\n\n\nif __name__ == '__main__':\n    unittest.main()\n",
    "benchmarks/atom_loss/verify.py": "\"\"\"Check the published evidence bundle; incomplete runs cannot become accuracy points.\"\"\"\nfrom .shot_data import require\nimport argparse\nimport csv\nimport hashlib\nimport json\nimport math\nfrom pathlib import Path\nfrom .artifacts import require_complete_sweep, required_files, TIMING_FILES, CORRECTNESS_FILES, native_total, timing_rows, summary_rows, SUMMARY_FIELDS, wilson\n\n\ndef verify(root):\n    manifest=json.loads((root/'bundle.json').read_text())\n    listed = set(manifest['sha256'])\n    required = required_files(root)\n    if listed & TIMING_FILES:\n        required = required | TIMING_FILES\n    if listed & CORRECTNESS_FILES:\n        required = required | CORRECTNESS_FILES\n    missing = required - listed\n    if missing:\n        raise ValueError(f'Missing required artifact checksums: {sorted(missing)}')\n    for name,expected in manifest['sha256'].items():\n        path=root/name\n        if path.parent != root or hashlib.sha256(path.read_bytes()).hexdigest()!=expected:\n            raise ValueError(f'Artifact integrity mismatch: {name}')\n    for provenance, snapshot in [('provenance-all.json', 'source-snapshot.json'),('provenance-seeds.json','source-snapshot-seeds.json')] + (\n            [('provenance-timing.json', 'source-snapshot-timing.json')] if listed & TIMING_FILES else []) + (\n            [('provenance-correctness.json', 'source-snapshot-correctness.json')] if listed & CORRECTNESS_FILES else []):\n        record = json.loads((root/provenance).read_text())\n        source = json.loads((root/snapshot).read_text())\n        if source['base_commit'] != record['source_commit']:\n            raise ValueError('Source snapshot base differs from provenance')\n        for name, expected in record['sources'].items():\n            if name not in source['files'] or hashlib.sha256(source['files'][name].encode()).hexdigest() != expected:\n                raise ValueError(f'Source snapshot mismatch: {name}')\n    for name in ['correctness.json','decoder-correctness.json','chain-correctness.json']:\n        data=json.loads((root/name).read_text())\n        if data['status']!='PASS': raise ValueError(f'Correctness failed: {name}')\n    sampler=json.loads((root/'correctness.json').read_text())\n    from .report_contract import verify_sampler\n    verify_sampler(sampler)\n    if sampler['low_probability_controls']['real_circuit']['fixture_sha256']!=hashlib.sha256((root/'midswap_d3_r2.stim').read_bytes()).hexdigest():\n        raise ValueError('Real-circuit sampling fixture mismatch')\n    chain=json.loads((root/'chain-correctness.json').read_text())\n    from .chain_contract import verify_chain\n    verify_chain(chain)\n    require((hashlib.sha256((root/'midswap_d3_r2.stim').read_bytes()).hexdigest()==chain['fixture_sha256']), \"verify: hashlib.sha256((root/'midswap_d3_r2.stim').read_bytes()).hexdigest()==chain['fixture_sha256']\")\n    oracle=json.loads((root/'decoder-correctness.json').read_text())\n    from .decoder_contract import verify_decoder\n    verify_decoder(oracle)\n    def duration(value, *, positive=False):\n        if type(value) not in [int,float] or not math.isfinite(value) or (value<=0 if positive else value<0):\n            raise ValueError('Invalid finite phase duration')\n    sampling=json.loads((root/'sampling.json').read_text())\n    require(([c['distance'] for c in sampling]==[3,5,7]), \"verify: [c['distance'] for c in sampling]==[3,5,7]\")\n    for c in sampling:\n        if (c['shots']!=256 or c['rounds']!=c['distance'] or c['pauli_probability']!=.001 or c['loss_probability']!=.003\n                or c['rust']['shots']!=c['shots'] or c['rust']['warmups']!=2 or c['reference']['warmups']!=1):\n            raise ValueError('Sampling workload metadata mismatch')\n        duration(c['rust']['parse_seconds'])\n        for backend in ['rust','reference']:\n            require((len(c[backend]['records'])==3), \"verify: len(c[backend]['records'])==3\")\n            for r in c[backend]['records']:\n                duration(r['sample_seconds'],positive=True);duration(r['packing_seconds'])\n                require((type(r['bytes']) is int and r['bytes']>0), \"verify: type(r['bytes']) is int and r['bytes']>0\")\n        require((c['rust']['records'][0]['bytes']==c['reference']['records'][0]['bytes']), \"verify: c['rust']['records'][0]['bytes']==c['reference']['records'][0]['bytes']\")\n    decoding=json.loads((root/'decoding.json').read_text())\n    require_complete_sweep(decoding)\n    import zipfile\n    from .shot_data import circuit_layout, ARCHIVE\n    with zipfile.ZipFile(root/ARCHIVE) as archive:\n        for case in sampling:\n            d=case['distance'];circuit=archive.read(f'd{d}-p0.003/public/circuit.stim')\n            if hashlib.sha256(circuit).hexdigest()!=case['circuit_sha256']:\n                raise ValueError('Sampling circuit differs from corresponding archived sweep circuit')\n            expected_bytes=((circuit_layout(circuit.decode())[0]+7)//8)*case['shots']\n            if any(r['bytes']!=expected_bytes for backend in ['rust','reference'] for r in case[backend]['records']):\n                raise ValueError('Sampling byte count differs from circuit layout and shots')\n    tradeoff=json.loads((root/'tradeoff.json').read_text())\n    require((set(tradeoff['decoders'])=={'envelope-matching','envelope-mle','pymatching-fixed','pymatching-envelope','pymatching-fixed-loop','envelope-matching-offline'}), \"verify: set(tradeoff['decoders'])=={'envelope-matching','envelope-mle','pymatching-fixed','pymatching-envelope','pymatching-fixed-loop','envelope-matching-offline'}\")\n    require((tradeoff['decoders']['pymatching-fixed']['prediction_sha256']==tradeoff['decoders']['pymatching-fixed-loop']['prediction_sha256']), \"verify: tradeoff['decoders']['pymatching-fixed']['prediction_sha256']==tradeoff['decoders']['pymatching-fixed-loop']['prediction_sha256']\")\n    for c in decoding+[tradeoff]:\n        require(c.get('pauli_probability') == .001, 'Declared Pauli probability differs from fixed workload')\n        require((c['shots']==5000 and c['decoders'] and 'export_failure' not in c), \"verify: c['shots']==5000 and c['decoders'] and 'export_failure' not in c\")\n        require(c['seed']==(20260912 if c is tradeoff else 20260911), 'Predeclared original seed')\n        native=c['decoders']['envelope-matching']\n        require(c['decoders']['envelope-matching-offline']['prediction_sha256']==native['prediction_sha256'],'Offline predictions')\n        for name,r in c['decoders'].items():\n            if r['status']=='ok':\n                require((type(r['shots']) is int and type(r['errors']) is int and r['shots']==c['shots'] and 0<=r['errors']<=r['shots']), \"verify: type(r['shots']) is int and type(r['errors']) is int and r['shots']==c['shots'] and 0<=r['errors']<=r['shots']\")\n                require((r['logical_error_rate']==r['errors']/r['shots']), \"verify: r['logical_error_rate']==r['errors']/r['shots']\")\n                require((r['wilson_95']==wilson(r['errors'],r['shots'])), \"verify: r['wilson_95']==wilson(r['errors'],r['shots'])\")\n                require((r['wilson_95'][1]>0 and len(r['runs'])==len(r['total_seconds'])==3), \"verify: r['wilson_95'][1]>0 and len(r['runs'])==len(r['total_seconds'])==3\")\n                for value in r['total_seconds']:duration(value,positive=True)\n                for rep,(run,total) in enumerate(zip(r['runs'],r['total_seconds'])):\n                    if name.startswith('pymatching'):\n                        for key in ['compile_seconds','transform_seconds','decode_seconds']:duration(run[key])\n                        duration(run['write_seconds'])\n                        require((run['export_repetition']==rep), \"verify: run['export_repetition']==rep\")\n                        require((total==run['compile_seconds']+run['transform_seconds']+run['decode_seconds']), \"verify: total==run['compile_seconds']+run['transform_seconds']+run['decode_seconds']\")\n                        if not name.endswith('-loop'):\n                            require((run['batch_calls']>0), \"verify: run['batch_calls']>0\")\n                            phases=[run[k] for k in ['topology_seconds','preprocess_seconds','graph_build_seconds','matching_seconds','output_seconds','adapter_overhead_seconds']]\n                            require((min(phases)>=0 and math.isclose(sum(phases),run['decode_seconds'],rel_tol=1e-9)), \"verify: min(phases)>=0 and math.isclose(sum(phases),run['decode_seconds'],rel_tol=1e-9)\")\n                    else:\n                        if name == 'envelope-matching-offline':\n                            batch=run['batch']\n                            for key in ['graph_build_seconds','matching_seconds','write_seconds','batch_overhead_seconds']:\n                                duration(batch[key])\n                            require(math.isclose(sum(batch[k] for k in ['graph_build_seconds','matching_seconds','write_seconds','batch_overhead_seconds']),batch['decode_seconds'],rel_tol=1e-9),'Offline phases')\n                            require(run['stats']['decode_seconds']==run['transform_seconds']+batch['decode_seconds'],'Offline total')\n                            require(batch['graph_builds']==c['graph']['loss_patterns'],'Offline graph count')\n                        expected = native_total(run)\n                        if not math.isfinite(total) or not math.isclose(total, expected, rel_tol=1e-12, abs_tol=0.):\n                            raise ValueError(f'Native total differs from compile + decode: {name}')\n                        require((run['stats']['attempted_shot_count']==r['shots']), \"verify: run['stats']['attempted_shot_count']==r['shots']\")\n                        require((run['stats']['timeout_count']==run['stats']['infeasible_shot_count']==0), \"verify: run['stats']['timeout_count']==run['stats']['infeasible_shot_count']==0\")\n                if 'paired_native_only_wrong' in r:\n                    a,b=r['paired_native_only_wrong'],r['paired_python_only_wrong']\n                    require((r['errors']-native['errors']==b-a), \"verify: r['errors']-native['errors']==b-a\")\n                    require((a+b==r['disagreements_with_native']), \"verify: a+b==r['disagreements_with_native']\")\n            else:\n                require(('logical_error_rate' not in r and 'errors' not in r and 'total_seconds' not in r), \"verify: 'logical_error_rate' not in r and 'errors' not in r and 'total_seconds' not in r\")\n    from .workload_contract import verify_workloads\n    verify_workloads(root)\n    with (root/'timing-sweep.csv').open() as stream:\n        rows = list(csv.DictReader(stream))\n    expected = [{key:str(value) for key,value in row.items()} for row in timing_rows(decoding)]\n    if rows != expected or len(rows) != 180:\n        raise ValueError('Timing sweep CSV differs from complete raw repetitions')\n    with (root/'summary.csv').open() as stream:\n        reader = csv.DictReader(stream)\n        rows = list(reader)\n        fields = reader.fieldnames\n    expected = [{key:str(value) for key,value in row.items()} for row in summary_rows(decoding,tradeoff)]\n    if fields != SUMMARY_FIELDS or rows != expected or len(rows) != 66:\n        raise ValueError('Summary CSV differs from complete raw counts and phase timings')\n    from .shot_data import rescore, ARCHIVE\n    rescore(root/ARCHIVE, root)\n    from .shot_data import rescore_seeds\n    rescore_seeds(root/'accuracy-seeds.zip',root)\n    from .source_contract import verify_bundle_source\n    verify_bundle_source(root)\n    from .figure_contract import verify_presentation\n    verify_presentation(root)\n    return 'PASS'\n\n\nif __name__=='__main__':\n    p=argparse.ArgumentParser();p.add_argument('root',type=Path,nargs='?',default=Path('site/static/data/atom-loss'))\n    print(verify(p.parse_args().root))\n",
    "benchmarks/atom_loss/workload_contract.py": "\"\"\"Bind deterministic execution metadata to public rows and the fixed run policy.\n\nElapsed times are checked for finite ranges and additive identities elsewhere;\nneither these checks nor fresh decoder replay authenticate historical timings.\nNative compiler/cache internals are range checked here and compared with current\nexecutables by decoder_replay. Visible-pattern counts need no decoder at all.\n\"\"\"\nimport hashlib\nimport json\nimport math\nimport re\nimport zipfile\n\nfrom .shot_data import ARCHIVE, circuit_layout\n\nSWEEP_BACKENDS = ('envelope-matching', 'pymatching-fixed', 'pymatching-envelope',\n                  'envelope-matching-offline')\nTRADEOFF_BACKENDS = SWEEP_BACKENDS + ('envelope-mle', 'pymatching-fixed-loop')\nGRAPH_SOURCE = 'public dataset only; graph/compiler shared with RustQEC'\nOFFLINE_POLICY = 'offline groups; one graph per pattern'\nOFFLINE_BOUNDARY = ('JSON transport excluded; grouping, graph build, batch decode, '\n                    'reorder, b8 write and flush included; no fsync')\nNATIVE_COUNTERS = ('shot_count', 'attempted_shot_count', 'distinct_loss_patterns',\n                   'cache_hits', 'timeout_count', 'infeasible_shot_count',\n                   'circuit_compilations', 'primitive_probe_count',\n                   'primitive_symptom_terms', 'loss_envelope_candidate_count',\n                   'matching_graph_builds', 'mle_model_builds', 'mle_detector_rows')\nNATIVE_FIELDS = set(NATIVE_COUNTERS) | {'schema_version', 'decoder', 'circuit_sha256',\n                                      'compile_seconds', 'decode_seconds',\n                                      'distinct_loss_patterns_exact'}\n\n\ndef require(condition, message):\n    if not condition:\n        raise ValueError('Workload report contract: '+message)\n\n\ndef integer(value, label, minimum=0, maximum=None):\n    require(type(value) is int and value >= minimum\n            and (maximum is None or value <= maximum), 'invalid '+label)\n    return value\n\n\ndef mapping(record, fields, label):\n    require(type(record) is dict and set(record) == set(fields), label+' fields')\n\n\ndef seconds(record):\n    for name, value in record.items():\n        if name.endswith('_seconds'):\n            require(type(value) in (int, float) and math.isfinite(value) and value >= 0,\n                    'invalid '+name)\n\n\ndef measurement_flags(text):\n    \"\"\"Index visible flags from the documented measurement/REPEAT syntax.\"\"\"\n    bits, detectors, observables = circuit_layout(text)  # Reject unknown syntax.\n    lines = iter(text.splitlines())\n    def block(nested=False):\n        widths = []\n        for raw in lines:\n            line = raw.split('#', 1)[0].strip()\n            if not line:\n                continue\n            if line == '}':\n                require(nested, 'unexpected closing REPEAT')\n                return widths\n            repeat = re.fullmatch(r'REPEAT (\\d+)\\s*\\{', line)\n            if repeat:\n                widths.extend(block(True)*int(repeat[1]))\n                continue\n            measurement = re.fullmatch(r'(M|MZ|MR|MRZ|ML|MZL|MRL|MRZL)(?:\\[[^\\]]*\\])?\\s+(.+)', line)\n            if measurement:\n                widths.extend([2 if measurement[1].endswith('L') else 1]\n                              *len(measurement[2].split()))\n        require(not nested, 'unclosed REPEAT')\n        return widths\n    flags, cursor = [], 0\n    for width in block():\n        if width == 2:\n            flags.append(cursor)\n        cursor += width\n    require(cursor == bits, 'measurement indexing mismatch')\n    return bits, detectors, observables, flags\n\n\ndef public_workload(read):\n    text = read('public/circuit.stim')\n    bits, detectors, observables, flags = measurement_flags(text.decode())\n    support = []\n    for line in text.decode().splitlines():\n        coordinate = re.fullmatch(r'\\s*QUBIT_COORDS\\(([^)]+)\\)\\s+(\\d+)\\s*', line)\n        if coordinate:\n            xy = [float(value) for value in coordinate[1].split(',')]\n            if len(xy) >= 2 and xy[0] == 1 and xy[1] % 2 == 1:\n                support.append(coordinate[2])\n    manifest = json.loads(read('public/manifest.json'))\n    shots = integer(manifest['shots'], 'public shots', 1)\n    stride = (bits+7)//8\n    rows = read('public/shots.b8')\n    require(bits > 0 and len(rows) == stride*shots, 'public row dimensions')\n    require(set(observables) == {0}, 'one observable required')\n    patterns = {tuple((rows[row*stride+bit//8] >> (bit%8)) & 1 for bit in flags)\n                for row in range(shots)}\n    return {'shots': shots, 'detectors': detectors, 'num_observables': 1,\n            'loss_patterns': len(patterns), 'circuit_sha256': hashlib.sha256(text).hexdigest(),\n            'logical_x_support': ','.join(support)}\n\n\ndef native_stats(stats, name, workload):\n    mapping(stats, NATIVE_FIELDS, name+' native stats')\n    seconds(stats)\n    n, patterns = workload['shots'], workload['loss_patterns']\n    for key in NATIVE_COUNTERS:\n        integer(stats[key], name+'/'+key)\n    require(stats['schema_version'] == 'rustqec.decode-stats.v1' and stats['decoder'] == name,\n            'native decoder/schema')\n    require(stats['circuit_sha256'] == workload['circuit_sha256'], 'native circuit identity')\n    require(stats['shot_count'] == stats['attempted_shot_count'] == n, 'native shot count')\n    require(stats['timeout_count'] == stats['infeasible_shot_count'] == 0, 'incomplete native run')\n    require(stats['circuit_compilations'] == 1, 'native circuit compilations')\n    require(stats['primitive_probe_count'] > 0 and stats['primitive_symptom_terms'] > 0,\n            'missing compiler probes')\n    integer(stats['distinct_loss_patterns'], 'native distinct patterns', 1, n)\n    require(type(stats['distinct_loss_patterns_exact']) is bool, 'native exact-count flag')\n    # Approximate counters can lie on either side of the exact cardinality.\n    if stats['distinct_loss_patterns_exact']:\n        require(stats['distinct_loss_patterns'] == patterns, 'native exact pattern count')\n    builds = stats['matching_graph_builds'] if name == 'envelope-matching' else stats['mle_model_builds']\n    integer(builds, 'native builds', patterns, n)\n    integer(stats['cache_hits'], 'native cache hits', 0, n)\n    require(builds + stats['cache_hits'] == n, 'native build/cache accounting')\n    if name == 'envelope-matching':\n        require(stats['mle_model_builds'] == stats['mle_detector_rows'] == stats['loss_envelope_candidate_count'] == 0,\n                'matching run contains MLE counters')\n    else:\n        require(stats['matching_graph_builds'] == 0\n                and stats['mle_detector_rows'] == workload['detectors']\n                and stats['loss_envelope_candidate_count'] > 0, 'MLE model counters')\n\n\ndef verify_case(case, workload, *, tradeoff=False):\n    names = TRADEOFF_BACKENDS if tradeoff else SWEEP_BACKENDS\n    require(type(case['decoders']) is dict and set(case['decoders']) == set(names), 'backend inventory')\n    require(case['timing_order'] == [list(names[rep:]+names[:rep]) for rep in range(3)],\n            'fixed serial timing order')\n    n, patterns = workload['shots'], workload['loss_patterns']\n    require(type(case['shots']) is int and case['shots'] == n == 5000, 'case shots')\n    integer(case['distance'], 'case distance', 3, 7)\n    integer(case['rounds'], 'case rounds', 1)\n    require(case['distance'] in (3, 5, 7), 'fixed workload distance')\n    require((case['distance'], case['rounds'], case['loss_probability']) == (3, 2, .003)\n            if tradeoff else case['rounds'] == case['distance'], 'fixed workload dimensions')\n    require(case['circuit_sha256'] == workload['circuit_sha256'], 'case circuit identity')\n    require(case['logical_x_support'] == workload['logical_x_support']\n            and len(workload['logical_x_support'].split(',')) == case['distance'], 'logical-X support')\n    graph = case['graph']\n    mapping(graph, ('source', 'compile_seconds', 'transform_seconds', 'num_observables',\n                    'edges', 'detectors', 'loss_patterns'), 'graph metadata')\n    seconds(graph)\n    require(graph['source'] == GRAPH_SOURCE, 'graph source')\n    integer(graph['edges'], 'graph edges', 1)\n    for key in ('num_observables', 'detectors', 'loss_patterns'):\n        integer(graph[key], 'graph '+key, 1)\n        require(graph[key] == workload[key], 'graph '+key+' differs from public rows')\n    for name, result in case['decoders'].items():\n        require(result['status'] == 'ok' and type(result['shots']) is int and result['shots'] == n,\n                name+' incomplete result')\n        require(type(result['runs']) is list and len(result['runs']) == 3, name+' repetitions')\n        for rep, run in enumerate(result['runs']):\n            seconds(run)\n            if name.startswith('pymatching'):\n                common = {'compile_seconds', 'transform_seconds', 'decode_seconds', 'write_seconds',\n                          'export_repetition', 'graph_builds'}\n                if name.endswith('-loop'):\n                    mapping(run, common | {'cache_hits'}, name+' run')\n                    integer(run['cache_hits'], name+' cache hits')\n                    require(run['cache_hits'] == n-1, 'fixed loop cache accounting')\n                    expected = 1\n                else:\n                    mapping(run, common | {'topology_seconds', 'preprocess_seconds', 'graph_build_seconds',\n                            'matching_seconds', 'output_seconds', 'adapter_overhead_seconds', 'batch_calls',\n                            'graph_api', 'execution'}, name+' run')\n                    expected = patterns if name == 'pymatching-envelope' else 1\n                    integer(run['batch_calls'], name+' batch calls', 1)\n                    require(run['batch_calls'] == expected, name+' batch calls differ from public rows/policy')\n                    require(run['graph_api'] == 'from_check_matrix', 'Python graph API')\n                    require(run['execution'] == ('batch grouped by loss pattern' if name == 'pymatching-envelope'\n                                                 else 'batch fixed graph'), 'Python execution policy')\n                    require(run['output_seconds'] >= run['write_seconds'], 'Python output/write accounting')\n                integer(run['graph_builds'], name+' graph builds', 1)\n                require(run['graph_builds'] == expected, name+' graph builds differ from public rows/policy')\n                integer(run['export_repetition'], name+' export repetition')\n                require(run['export_repetition'] == rep, 'Python export repetition')\n                require(run['decode_seconds'] >= run['write_seconds'], 'Python decode/write accounting')\n            else:\n                fields = {'status', 'exit_code', 'process_wall_seconds', 'stats'}\n                if name == 'envelope-matching-offline':\n                    fields |= {'batch', 'transform_seconds'}\n                mapping(run, fields, name+' run')\n                require(run['status'] == 'ok' and type(run['exit_code']) is int and run['exit_code'] == 0,\n                        'native run status/exit code')\n                if name != 'envelope-matching-offline':\n                    native_stats(run['stats'], name, workload)\n                    continue\n                batch, stats = run['batch'], run['stats']\n                mapping(batch, ('decode_seconds', 'graph_build_seconds', 'matching_seconds', 'write_seconds',\n                                'batch_overhead_seconds', 'graph_builds', 'shots', 'policy', 'boundary'), 'offline batch')\n                mapping(stats, ('compile_seconds', 'decode_seconds', 'attempted_shot_count', 'timeout_count',\n                                'infeasible_shot_count', 'matching_graph_builds', 'cache_hits'), 'offline stats')\n                seconds(batch); seconds(stats)\n                for record, key in [(batch, 'shots'), (batch, 'graph_builds'),\n                                    (stats, 'attempted_shot_count'), (stats, 'matching_graph_builds'),\n                                    (stats, 'cache_hits'), (stats, 'timeout_count'), (stats, 'infeasible_shot_count')]:\n                    integer(record[key], 'offline '+key)\n                require(batch['shots'] == stats['attempted_shot_count'] == n, 'offline shots')\n                require(batch['graph_builds'] == stats['matching_graph_builds'] == patterns, 'offline graph count')\n                require(stats['cache_hits'] == stats['timeout_count'] == stats['infeasible_shot_count'] == 0,\n                        'offline cache/failures')\n                require(batch['policy'] == OFFLINE_POLICY and batch['boundary'] == OFFLINE_BOUNDARY,\n                        'offline policy/boundary')\n\n\ndef verify_workloads(root):\n    \"\"\"Validate all original measured workflows before trusting derived tables.\"\"\"\n    try:\n        cases = json.loads((root/'decoding.json').read_text())\n        tradeoff = json.loads((root/'tradeoff.json').read_text())\n        with zipfile.ZipFile(root/ARCHIVE) as archive:\n            for case in cases+[tradeoff]:\n                label = 'tradeoff' if case is tradeoff else f\"d{case['distance']}-p{case['loss_probability']}\"\n                workload = public_workload(lambda name: archive.read(label+'/'+name))\n                verify_case(case, workload, tradeoff=case is tradeoff)\n    except (KeyError, TypeError, AttributeError) as error:\n        raise ValueError('Workload report contract: missing or malformed observation') from error\n"
  }
}
