From f465b0f84059f636b461026a4ea982ffda935db4 Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Fri, 13 Nov 2026 19:38:08 +0800 Subject: [PATCH 1/4] Add the Watrous bridge, complete storage example and thirty milestones --- README.md | 6 + learning/MILESTONES.md | 288 +++++++++++++++++++++++++++++++++++++ learning/README.md | 29 ++++ learning/WATROUS_BRIDGE.md | 93 ++++++++++++ learning/WORKED_EXAMPLE.md | 135 +++++++++++++++++ llms.txt | 6 + science/README.md | 1 + science/examples.md | 2 +- science/interpretation.md | 2 +- verification/README.md | 2 +- 10 files changed, 561 insertions(+), 3 deletions(-) create mode 100644 learning/MILESTONES.md create mode 100644 learning/README.md create mode 100644 learning/WATROUS_BRIDGE.md create mode 100644 learning/WORKED_EXAMPLE.md diff --git a/README.md b/README.md index b29f2ef..5d92ea0 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,12 @@ python3 verification/check_science.py --output verification/results.json The [verification guide](verification/README.md) states the actual matrix calculations and their limits. The all-size theorem rests on the analytical proof and its imported control theorem, rather than finite tests. +## Learn the mechanism + +The single educational anchor is **John Watrous, *The Theory of Quantum Information* (2018)**, using the January 2018 standard-layout author manuscript. The [Watrous bridge](learning/WATROUS_BRIDGE.md) connects its channel, distance and entanglement foundations to the control theorem and repeated-memory argument, with conventions translated explicitly. + +The [worked storage experiment](learning/WORKED_EXAMPLE.md) follows a Bell pair through an exact SWAP, full port reset, retrieval and measurement, then adds repetition and a rare quantum sector. The [30-milestone map](learning/MILESTONES.md) develops twelve background and eighteen narrative understanding targets in one connected route. Start with the [learning guide](learning/README.md), or use the specialist science route above. + ## Scope The theorem permits ideal local operations, exact resets, unrestricted finite laboratory ancillas and arbitrarily accurate control synthesis. A qubit port may be stabilized by one controllable laboratory qubit; that helper is erased at the memory cuts and is never an extra emulator port. All hidden persistent quantum systems count jointly toward the hard cap. No preshared entanglement or uncounted quantum side channel is supplied to an emulator. diff --git a/learning/MILESTONES.md b/learning/MILESTONES.md new file mode 100644 index 0000000..9143389 --- /dev/null +++ b/learning/MILESTONES.md @@ -0,0 +1,288 @@ +# Thirty milestones for Hamiltonian quantum memory + +[Learning route](README.md) · [Watrous bridge](WATROUS_BRIDGE.md) · [Worked example](WORKED_EXAMPLE.md) · [Scientific account](../science/README.md) + +This common map follows one question: which coherent part of a known, finite, static bath must a physical quantum-port emulator retain under arbitrary interventions? It contains exactly thirty project-defined understanding targets. It is independent of any reader's assessment history and does not prescribe a personal teaching or testing procedure. + +The single educational anchor is John Watrous, *The Theory of Quantum Information* (2018). Section numbers below refer to the verified standard-layout January 2018 author manuscript identified in the [bridge](WATROUS_BRIDGE.md). Primary research citations supply the control and multitime-process ingredients that the textbook does not cover. + +| Phase | Milestones | Why this allocation fits the story | +| --- | --- | --- | +| Background/preliminaries | M01–M12 | Assemble states, references, instruments, memory cuts, operational error and the imported control structure into the actual simulation problem. | +| Narrative/innovation | M13–M30 | Build the indirect storage witness locally, then combine its repeated-use converse with the sector simulator to obtain the tail law, classical boundary and physical limitations. | + +Throughout, $`Q_j`$ denotes a controllable bath factor of dimension $`r_j`$, $`p_j`$ its initial sector probability, and $`D`$ the hard maximum persistent quantum dimension of an emulator. Its classical memory is unrestricted. The headline error is uniform over arbitrarily long **finite** experiments; it is not a finite-time efficiency or classical numerical-prediction claim. + +## Background/preliminaries — M01–M12 + +### M01 — A physical port with an unknown input + +**Central question:** What must an emulator reproduce when an actual quantum input arrives? + +- **Understanding target:** Distinguish quantum-port emulation, including unknown input correlations, from computing probabilities for a fully described experiment. +- **Dependencies and story role:** Entry point; identifies the physical task before introducing a memory resource. +- **Conceptual connection:** Registers and channels become an input/output contract with a user. +- **Source pointers:** Watrous §§2.1–2.2 through the [bridge](WATROUS_BRIDGE.md); [model opening and physical process](../science/model.md#physical-process); [interpretation](../science/interpretation.md). + +### M02 — What remains after a subsystem is ignored + +**Central question:** When can an unobserved bath component be traced out? + +- **Understanding target:** Explain reduced states and why tracing a subsystem preserves all observations on the remaining registers; distinguish this operation from assuming a product state. +- **Dependencies and story role:** Builds on M01; supplies the first local simplification used by the exact simulator. +- **Conceptual connection:** Partial trace permits ignoring an invisible multiplicity even when it is initially correlated with the useful factor. +- **Source pointers:** Watrous §2.1.3; [drift reduction](../science/control_structure.md#consequence-for-the-physical-drift). + +### M03 — A reference that records quantum correlations + +**Central question:** Why is returning the right reduced payload state an insufficient memory test? + +- **Understanding target:** Explain how a sealed reference distinguishes genuine transmission of an unknown quantum state from measurement and repreparation. +- **Dependencies and story role:** Uses M01–M02; makes the later Bell test physically meaningful. +- **Conceptual connection:** Purification turns a statement about all unknown inputs into a reference-correlation requirement. +- **Source pointers:** Watrous §2.1.3; [reference convention](../science/model.md#physical-process); [worked example](WORKED_EXAMPLE.md). + +### M04 — Channels must act consistently on larger systems + +**Central question:** What changes when a channel's input is entangled with an untouched register? + +- **Understanding target:** Explain complete positivity and why the same port operation must remain valid with arbitrary finite references. +- **Dependencies and story role:** Builds on M03; prevents a reduced-state-only interpretation of emulation. +- **Conceptual connection:** The channel framework supplies the reference-complete setting for both simulation and control-approximation errors. +- **Source pointers:** Watrous §§2.2–2.2.2; [distance and quantifiers](../science/model.md#distance-and-order-of-quantifiers). + +### M05 — Classical branches and quantum carriers + +**Central question:** What may a simulator retain after an instrument produces an outcome? + +- **Understanding target:** Separate a measured classical record from a coherent register; recognize that conditioning later channels on a record is allowed. +- **Dependencies and story role:** Uses M04; introduces the strongest classical competitor rather than only a fixed random-field model. +- **Conceptual connection:** Measurements and channels compose into invasive classical feedforward, while classical labels remain diagonal. +- **Source pointers:** Watrous §§2.2 and 2.3; [permitted simulators](../science/model.md#permitted-simulators); [classical-memory distinction](../science/classical_boundary.md#classical-common-cause-versus-general-classical-memory). + +### M06 — A reset that closes the accessible path + +**Central question:** Which registers must be erased to test whether information survived in the bath? + +- **Understanding target:** Identify the port and every accessible working carrier in a trace-and-replace operation, while keeping the reference sealed until readout. +- **Dependencies and story role:** Combines M03–M05; defines the physical cut used in the converse. +- **Conceptual connection:** A reset is a prescribed channel on real wires; hidden surviving quantum carriers belong to the emulator's counted memory. +- **Source pointers:** Watrous §2.2; [simulator contract](../science/model.md#permitted-simulators); [finite repeated tester](../science/memory_law.md#the-finite-repeated-tester); [worked example](WORKED_EXAMPLE.md). + +### M07 — Quantum dimension and Bell overlap + +**Central question:** How can one Bell measurement reveal that a quantum carrier is too small? + +- **Understanding target:** Interpret pure-state Schmidt rank and the mixed-state Schmidt-number extension used locally; explain why a $`D`$-dimensional carrier bounds the Bell overlap by $`D/r`$. +- **Dependencies and story role:** Uses M03–M06; supplies the local dimension obstruction without confusing dimension with entropy. +- **Conceptual connection:** Textbook entanglement foundations support a project-supplied finite-dimensional overlap lemma; the mixed-state extension is a research ingredient. +- **Source pointers:** Watrous §§6.1 and 6.2.1 via the [bridge](WATROUS_BRIDGE.md); [one-round lemma](../science/memory_law.md#a-one-round-dimension-lemma). + +### M08 — A hard memory budget on every branch + +**Central question:** What resource does $`D`$ constrain when the simulator adapts? + +- **Understanding target:** Distinguish a maximum coherent dimension at each intervention boundary from average entropy, expected memory or the bath's initial rank. +- **Dependencies and story role:** Integrates M05–M07; fixes the resource before optimizing an error. +- **Conceptual connection:** Classical alternatives may select different states in one common bounded quantum register, but cannot hide coherence in an uncharged label. +- **Source pointers:** [permitted simulators](../science/model.md#permitted-simulators); [resource contract](../science/interpretation.md#resource-contract); Bisio's research framework in [related work](../references/related_work.md). + +### M09 — Operational error as a distinguishable event + +**Central question:** How does one event supply a lower bound on whole-process error? + +- **Understanding target:** Read total variation and half trace distance in the $`[0,1]`$ convention, and connect them to optimized discrimination. +- **Dependencies and story role:** Uses M04 and M08; introduces the error that the memory theorem actually optimizes. +- **Conceptual connection:** A final measurement converts a quantum-output discrepancy into a probability difference; an unhalved norm would change constants. +- **Source pointers:** Watrous §§3.1 and 3.3.2; [distance definition](../science/model.md#distance-and-order-of-quantifiers). + +### M10 — One compatible causal process + +**Central question:** Why does matching a collection of terminal channels fail to specify an emulator? + +- **Understanding target:** Explain the order of inputs, intervals, interventions and outputs, including adaptive choices and an inaccessible reference. +- **Dependencies and story role:** Combines M01–M09 into the reusable-process viewpoint. +- **Conceptual connection:** Channel composition extends to a physical strategy that must answer future interventions without receiving their private descriptions in advance. +- **Source pointers:** Watrous §§2.2 and 3.3 as foundations; [model](../science/model.md); Bisio/Goswami process dependencies in [related work](../references/related_work.md). + +### M11 — Local control can reach a hidden factor + +**Central question:** How can an inaccessible bath subsystem become indirectly writable through the port? + +- **Understanding target:** Explain the role of the connected control algebra, ancillary stabilization to accessible dimension at least three, and reachable-unitary closure. +- **Dependencies and story role:** Uses M04 and M10; imports the specific research structure that makes the storage witness possible. +- **Conceptual connection:** Complete local control plus a fixed drift produces effective joint operations; associative bath algebra alone does not prove controllability. +- **Source pointers:** [imported Kato statement](../science/control_structure.md#exact-imported-statement); [finite control closure](../science/control_structure.md#reachable-operations-closure-is-sufficient); Kato primary source in [related work](../references/related_work.md). This control classification is outside Watrous. + +### M12 — The complete background model + +**Central question:** How do the bath structure, laboratory and emulator fit into one experiment? + +- **Understanding target:** Identify conserved $`j`$, invisible $`B_j`$, controllable $`Q_j`$, original port $`S`$, reset working ancillas and sealed reference; state the initial-state and all-time promises together. +- **Dependencies and story role:** Integrates M01–M11; completes the background phase as one operational model. +- **Conceptual connection:** The inherited decomposition supplies opportunities for writing information, while quantum channels and the hard resource cap determine what an emulator must preserve. +- **Source pointers:** [model](../science/model.md); [control structure](../science/control_structure.md); [resource table](../science/interpretation.md#resource-contract); [Watrous bridge](WATROUS_BRIDGE.md). + +## Narrative/innovation — M13–M30 + +### M13 — Indirectly reading the conserved label + +**Central question:** How can the laboratory learn which bath factor is present without a supplied bath measurement? + +- **Understanding target:** Explain a sector-controlled flag operation, its classical outcome probability $`p_j`$, and why sector phases do not affect reduced statistics. +- **Dependencies and story role:** Starts locally from M11–M12; selects the branch on which the new witness will operate. +- **Conceptual connection:** Independent connected control in the actual decomposition makes the sector readable; arbitrary blocks chosen from a matrix representation would not suffice. +- **Source pointers:** [sector readout](../science/control_structure.md#reading-the-conserved-sector); [Kato transfer](../science/control_structure.md#exact-imported-statement). + +### M14 — Writing past the bath's initial rank + +**Central question:** Why can a pure initial bath factor still carry an arbitrary unknown payload later? + +- **Understanding target:** Follow encoding by SWAP, erasure of the old bath state now in the laboratory, and retrieval after a complete working reset. +- **Dependencies and story role:** Uses M06, M12 and M13; constructs the physical storage mechanism before bounding a simulator. +- **Conceptual connection:** The resource is what controls can write into a factor, not how much entropy the factor initially contains. +- **Source pointers:** [payload write and retrieval](../science/control_structure.md#writing-and-retrieving-an-unknown-payload); [worked example](WORKED_EXAMPLE.md). + +### M15 — One storage round defeats a smaller carrier + +**Central question:** What can a dimension-limited emulator retain across the prescribed reset? + +- **Understanding target:** Apply the $`D/r_j`$ Bell bound after every accessible carrier is erased and only counted private memory can carry input correlations forward. +- **Dependencies and story role:** Combines M07–M08 with M14; turns physical storage into a quantitative witness. +- **Conceptual connection:** Reference-complete channel emulation becomes a Schmidt-number obstruction at a single causal cut. +- **Source pointers:** [one-round dimension lemma](../science/memory_law.md#a-one-round-dimension-lemma); [worked example](WORKED_EXAMPLE.md); Watrous entanglement foundations through the [bridge](WATROUS_BRIDGE.md). + +### M16 — Fresh references under adaptive history + +**Central question:** Why does an earlier successful test not remove the next dimension obstruction? + +- **Understanding target:** Explain conditioning on arbitrary previous classical history, allowing an arbitrary residual simulator state, and then preparing a fresh independent Bell pair. +- **Dependencies and story role:** Builds on M05, M10 and M15; closes the adaptive-memory loophole in repetition. +- **Conceptual connection:** Conditional probability can be iterated without assuming independent simulator memories; old quantum outputs and references are disposed of. +- **Source pointers:** [finite repeated tester](../science/memory_law.md#the-finite-repeated-tester); [worked example](WORKED_EXAMPLE.md). + +### M17 — One event for many storage rounds + +**Central question:** How does repetition turn partial Bell overlap into an asymptotically decisive test? + +- **Understanding target:** Derive the all-pass probability bound $`(D/r_j)^n`$ and its uniform high-sector bound $`[D/(D+1)]^n`$. +- **Dependencies and story role:** Uses M09 and M16; assembles the local round into the converse's observable event. +- **Conceptual connection:** The test remains valid if an emulator changes its reported sector distribution; every high label still demands transmission through an oversized carrier. +- **Source pointers:** [repeated event and relabelling bound](../science/memory_law.md#the-finite-repeated-tester); [worked example](WORKED_EXAMPLE.md). + +### M18 — Finite compilation is enough + +**Central question:** Does the argument require an exactly reachable SWAP or an infinite physical experiment? + +- **Understanding target:** Explain finite compiled controls with aggregate error $`\eta`$, and why the emulator's dimension bound holds for the actual compiled operations without assuming they act as its internal SWAP. +- **Dependencies and story role:** Combines M11 and M17; converts the ideal mechanism into permitted finite witnesses. +- **Conceptual connection:** Reference-complete control approximation affects the target probability, while the reset-based dimension lemma applies to every emulator encoding and decoding. +- **Source pointers:** [control closure](../science/control_structure.md#reachable-operations-closure-is-sufficient); [finite lower bound](../science/memory_law.md#finite-control-approximation-and-lower-bound); Watrous §3.3.2 foundations. + +### M19 — An exact emulator for each fitting sector + +**Central question:** Which bath information must a constructive emulator actually retain? + +- **Understanding target:** Keep $`j`$ classically and the reduced $`Q_j`$ state coherently; trace $`B_j`$ and retain no intersector coherence. +- **Dependencies and story role:** Returns to a local construction using M02, M08 and M12; begins the upper-bound half of the contribution. +- **Conceptual connection:** The Hamiltonian reduction works for arbitrary initial correlations inside $`B_jQ_j`$ and leaves all user ancillas outside the simulator's original port. +- **Source pointers:** [exact drift reduction](../science/control_structure.md#consequence-for-the-physical-drift); [memory upper bound](../science/memory_law.md#upper-bound-keep-small-factors-and-a-classical-sector). + +### M20 — Combining sector errors + +**Central question:** Why does omitting oversized sectors cost only their total probability? + +- **Understanding target:** Use an exact model on $`r_j\le D`$ and arbitrary causal stand-ins otherwise to obtain the uniform bound $`q_D=\sum_{r_j>D}p_j`$. +- **Dependencies and story role:** Builds on M09, M13 and M19; turns sector-level construction into a global emulator. +- **Conceptual connection:** Convex mixing charges the weight of replaced branches, while free classical labels avoid summing their coherent dimensions. +- **Source pointers:** [upper-bound proof](../science/memory_law.md#upper-bound-keep-small-factors-and-a-classical-sector); [weighted staircase](../science/examples.md#a-weighted-memory-staircase). + +### M21 — Matching the tail from below + +**Central question:** Why can no better adaptive emulator beat the same omitted weight? + +- **Understanding target:** Combine the high-label all-pass event with finite compilation to read $`q_D-[D/(D+1)]^n-\eta`$, then take the supremum over finite testers before the simulator infimum. +- **Dependencies and story role:** Integrates M17–M20; establishes the central equality $`\epsilon_D^\infty=q_D`$. +- **Conceptual connection:** One chosen finite tester works uniformly against every permitted emulator, so no interchange with an infinite experiment is needed. +- **Source pointers:** [main theorem and converse](../science/memory_law.md); [model quantifiers](../science/model.md#distance-and-order-of-quantifiers). + +### M22 — Reading the memory staircase + +**Central question:** What coherent register is necessary at a chosen uniform error tolerance? + +- **Understanding target:** Read exact dimension $`\max_{p_j>0}r_j`$ and the smallest $`D`$ satisfying $`q_D\le\epsilon`$; translate a hard $`k`$-qubit register to $`D=2^k`$. +- **Dependencies and story role:** Uses M08 and M21; turns the theorem into an operational resource frontier. +- **Conceptual connection:** The frontier is a quantile of active factor dimensions, with plateaus when no new factor fits; it is not a bath-eigenvalue or average-entropy code. +- **Source pointers:** [theorem](../science/memory_law.md#the-theorem); [weighted example](../science/examples.md#a-weighted-memory-staircase); [resource interpretation](../science/interpretation.md). + +### M23 — The large-horizon limit + +**Central question:** What remains true if a different compatible emulator is designed for each finite horizon? + +- **Understanding target:** Explain why each finite witness supplies a lower bound once its compilation time fits, giving $`\lim_{T\to\infty}\epsilon_D(T)=q_D`$ without a convergence rate. +- **Dependencies and story role:** Uses M18 and M21; states the limiting order needed to interpret the global result. +- **Conceptual connection:** Uniform finite witnesses prevent a horizon-specific redesign from evading the asymptotic obstruction, while leaving shortest-time synthesis unresolved. +- **Source pointers:** [horizon-specific simulators](../science/memory_law.md#horizon-specific-simulators); [distance convention](../science/model.md#distance-and-order-of-quantifiers). + +### M24 — Excluding invasive classical memory + +**Central question:** What does the theorem say when no private coherent register survives? + +- **Understanding target:** Set $`D=1`$ and explain why every occupied $`r_j>1`$ obstructs exact emulation even with unlimited classical measurement, updating and feedforward. +- **Dependencies and story role:** Builds on M05, M08 and M21; extracts the genuinely quantum-memory consequence. +- **Conceptual connection:** Failure of a fixed noninvasive noise label is weaker than exclusion of all classical causal emulators; the Bell argument establishes the latter in this model. +- **Source pointers:** [classical boundary](../science/classical_boundary.md#exact-boundary-for-a-fixed-initial-bath); [classical-noise interpretation](../science/interpretation.md#consequence-for-classical-noise-models). + +### M25 — A common-cause realization when factors are scalar + +**Central question:** Why does a fixed bath basis suffice whenever exact classical emulation is possible here? + +- **Understanding target:** Explain the controlled-Hamiltonian form on active sectors and the resulting mixture of unitary process families; distinguish common cause from one memoryless process. +- **Dependencies and story role:** Uses M12 and M24; completes both directions of the static classical boundary. +- **Conceptual connection:** The collapse of general classical feedforward to common cause is specific to this complete static-bath family, not all multitime processes or observation grids. +- **Source pointers:** [fixed-state equivalence](../science/classical_boundary.md#exact-boundary-for-a-fixed-initial-bath); [classical classes](../science/classical_boundary.md#classical-common-cause-versus-general-classical-memory); [correlated classical bath example](../science/examples.md#a-classical-bath-need-not-be-memoryless). + +### M26 — Active support and faithful-state qualifiers + +**Central question:** Which parts of the full Hamiltonian can a supplied initial bath state make relevant? + +- **Understanding target:** Separate inactive sectors from rank-deficient states inside active quantum factors; state when the full-Hamiltonian controlled-basis conclusion follows. +- **Dependencies and story role:** Combines M14, M22 and M25; removes an initial-state loophole from the global interpretation. +- **Conceptual connection:** A faithful state occupies every sector, while a pure state in an occupied controllable factor can still be overwritten with an arbitrary payload. +- **Source pointers:** [faithful and inactive sectors](../science/classical_boundary.md#faithful-states-and-inactive-sectors); [model weights](../science/model.md#stabilized-control-decomposition); [weighted example](../science/examples.md#a-weighted-memory-staircase). + +### M27 — A concrete Hamiltonian crosses the boundary + +**Central question:** How can a single bath rotation turn a classical factor structure into a quantum one? + +- **Understanding target:** Follow the qutrit–qubit family $`H_g=C\otimes Z+gI\otimes X`$: conserved bath labels at $`g=0`$ and a full connected $`\mathfrak{su}(6)`$ algebra at every nonzero $`g`$. +- **Dependencies and story role:** Uses M11 and M24–M26; tests the abstract boundary on one explicit static model. +- **Conceptual connection:** The analytical generator-spanning argument establishes the factor change; finite numerical Lie-rank checks support the example without replacing its proof. +- **Source pointers:** [weak transverse-term example](../science/examples.md#an-arbitrarily-weak-bath-term-changes-the-all-time-answer); [verification scope](../verification/README.md). + +### M28 — Weak coupling during a fixed experiment + +**Central question:** Why can maximal all-time classical-emulation error coexist with a good short-time classical model? + +- **Understanding target:** Apply the perturbation bound $`d_T(P_{H_g},P_{H_0})\le\min\{1,|g|T\}`$ and explain the noncommuting weak-coupling and long-time limits. +- **Dependencies and story role:** Combines M23 and M27; prevents a structural theorem from being promoted into an efficient diagnostic. +- **Conceptual connection:** Unitary-channel continuity controls a fixed elapsed-time budget, while the repeated witness permits a time budget that depends on coupling and desired separation. +- **Source pointers:** Watrous §3.3.2 foundations; [finite-time proof](../science/examples.md#finite-time-proximity-survives); [finite-time caution](../science/classical_boundary.md#finite-time-caution). + +### M29 — What is inherited and what is added + +**Central question:** What consequential statement remains after the closest ingredients are credited? + +- **Understanding target:** Attribute Kato's control classification, Koashi–Imoto's information decomposition, Bisio's memory framework and the Bell-overlap bound; identify the sharp weighted all-time error law and repeated operational converse as the addition. +- **Dependencies and story role:** Integrates M11–M28; locates the contribution in its actual literature and model. +- **Conceptual connection:** A new use of established structure can answer a different operational question, but does not create a new decomposition or settle passive-snapshot memory detection. +- **Source pointers:** [primary comparisons](../references/related_work.md); [proof attribution](../science/memory_law.md#attribution-and-scope); [Hamiltonian-conjecture relation](../science/classical_boundary.md#relation-to-the-hamiltonian-conjecture); [anchor bridge](WATROUS_BRIDGE.md). + +### M30 — The whole physical account + +**Central question:** Which coherent part of a static bath must survive in any universal physical emulator, and within what limits? + +- **Understanding target:** Connect the factor decomposition, original quantum port, sealed-reference reset test, adaptive repetition, exact tail frontier, classical boundary, active-state qualification and finite-time warning in one explanation. +- **Dependencies and story role:** Integrates M13–M29 and the background model; closes the narrative phase with the supported contribution and its scope. +- **Conceptual connection:** The result prices a hidden coherent carrier under ideal complete control and unrestricted finite duration; it supplies neither classical computational hardness nor an efficient control, communication, thermodynamic or hardware advantage. +- **Source pointers:** [scientific overview](../science/README.md); [memory theorem](../science/memory_law.md); [interpretation and resources](../science/interpretation.md); [worked example](WORKED_EXAMPLE.md). diff --git a/learning/README.md b/learning/README.md new file mode 100644 index 0000000..1fe5606 --- /dev/null +++ b/learning/README.md @@ -0,0 +1,29 @@ +# Learning route + +Imagine using a device to hold an unknown qubit while every working register in the laboratory is erased. If the device later returns the qubit with its original quantum correlations intact, something quantum must have survived inside it. This project turns that observation into an exact memory requirement for a controlled finite environment. + +The selected educational anchor is **John Watrous, *The Theory of Quantum Information* (2018)**, using the author's standard-layout manuscript whose preface is dated January 2018. The [author's source page](https://cs.uwaterloo.ca/~watrous/TQI/) provides the manuscript and individual chapters. The [bridge](WATROUS_BRIDGE.md) specifies the relevant sections, notation and additional research ingredients. Reading the entire book is unnecessary for this route. + +## Start with a complete experiment + +The [worked example](WORKED_EXAMPLE.md) follows a Bell pair through storage, a full laboratory reset and retrieval. It gives every input, output and measured event. A hidden qubit passes its Bell test with probability one; any emulator retaining only classical information passes with probability at most one half. Repetition exposes the memory difference without assuming independent emulator behavior. + +## From the example to the result + +The [30-milestone map](MILESTONES.md) develops two connected phases. The first twelve milestones assemble states, channels, references, memory cuts and the supplied control structure. The remaining eighteen connect the storage test to repeated tests, conserved sectors, the exact error tail and its physical limits. Within both phases, individual objects lead to the full operational picture. + +| Reading goal | Route | +| --- | --- | +| See how quantum memory is tested | [Worked example](WORKED_EXAMPLE.md) | +| Translate the textbook into this project | [Watrous bridge](WATROUS_BRIDGE.md) | +| Follow the project's complete conceptual story | [Milestone map](MILESTONES.md) | +| Inspect the exact assumptions and simulator class | [Scientific model](../science/model.md) | +| Separate inherited control theory from the new memory argument | [Control structure](../science/control_structure.md) and [memory-law proof](../science/memory_law.md) | +| Understand what classical memory can reproduce | [Classical boundary](../science/classical_boundary.md) | +| Check time limits and physical interpretation | [Examples](../science/examples.md) and [resource account](../science/interpretation.md) | + +The textbook supplies quantum-information foundations. The control decomposition is an explicitly attributed research theorem, and the repeated-use memory law is proved in this repository. The learning material preserves that division. Its conceptual map does not claim to cover every specialist proof detail. + +The main result concerns ideal controls and arbitrarily long finite experiments. It determines a hard coherent-memory dimension, not the shortest experiment, a thermodynamic cost or the runtime of a classical numerical calculation. + +[Repository overview](../README.md) · [Scientific overview](../science/README.md) · [Attribution](../references/related_work.md) diff --git a/learning/WATROUS_BRIDGE.md b/learning/WATROUS_BRIDGE.md new file mode 100644 index 0000000..8e0f9b6 --- /dev/null +++ b/learning/WATROUS_BRIDGE.md @@ -0,0 +1,93 @@ +# From Watrous to Hamiltonian quantum memory + +[Learning route](README.md) · [Worked example](WORKED_EXAMPLE.md) · [Milestone map](MILESTONES.md) + +The one educational anchor is John Watrous, *The Theory of Quantum Information* (2018). Section references below identify the **January 2018 author manuscript, standard layout** available from the [author's source page](https://cs.uwaterloo.ca/~watrous/TQI/). The [front matter](https://cs.uwaterloo.ca/~watrous/TQI/TQI.frontmatter.pdf) verifies its section names and preface date. The project supplies the steps needed beyond those foundations. + +## Relevant textbook sections + +| Section in the selected manuscript | Foundation | Its use here | +| --- | --- | --- | +| [2.1 Registers and states](https://cs.uwaterloo.ca/~watrous/TQI/TQI.2.pdf), especially 2.1.3, Reductions and purifications of quantum states | Joint states and partial traces | A returned payload must preserve its correlations with a reference. | +| [2.2 Quantum channels](https://cs.uwaterloo.ca/~watrous/TQI/TQI.2.pdf), especially 2.2.1–2.2.2 | Completely positive, trace-preserving transformations and their representations | Preparations, idle evolutions and resets are actual physical maps. | +| [2.3 Measurements](https://cs.uwaterloo.ca/~watrous/TQI/TQI.2.pdf) | Outcomes obtained from positive measurement operators | A Bell test produces a pass or failure; both outcomes count. | +| [3.1 Quantum state discrimination](https://cs.uwaterloo.ca/~watrous/TQI/TQI.3.pdf) and 3.3, Channel distances and discrimination, especially 3.3.2 | Distinguishability and reference-assisted channel norms | The emulator must match operational observations, including correlated inputs. | +| [6.1 Separability](https://cs.uwaterloo.ca/~watrous/TQI/TQI.6.pdf), especially 6.1.2, and 6.2.1, Entanglement transformation | Quantum correlations and restrictions on local processing | Classical records cannot carry an arbitrary entangled payload across an erased laboratory. | + +These are entry points rather than a claim that the book proves the project's control or process-memory theorems. In particular, Section 2.3 concerns measurements; purification belongs to Section 2.1.3. + +## The physical roles behind the notation + +| Project symbol | Physical role | +| --- | --- | +| $`S`$ | The visible quantum port through which the laboratory interacts. | +| $`E`$ | The inaccessible finite bath, initially independent of laboratory inputs. | +| $`A`$ | Finite laboratory work systems; they are erased at storage cuts. | +| $`R`$ | The sealed test reference, retained only to check the retrieved payload. | +| $`Q_j`$ | The bath factor that can store arbitrary quantum information in sector $`j`$. | +| $`B_j`$ | An invisible bath multiplicity factor whose state need not be retained. | +| $`D`$ | The hard maximum dimension of all persistent private emulator quantum systems together. | +| $`p_j`$ | The probability that the supplied initial bath occupies sector $`j`$. | + +The book's registers and channels can represent every item in one finite experiment. Here the letters emphasize their distinct physical permissions. A reference is not an extra emulator input. A classical record must remain classical; its many possible labels do not supply a coherent quantum carrier. + +## Three translations that matter + +### A reset erases correlations as well as a local state + +For a working register $`W`$, a reset to a fixed state $`\omega_W`$ is + +```math +\mathcal R_W(X)=\operatorname{Tr}(X)\,\omega_W. +``` + +When applied to part of a joint state, it discards that register and prepares a replacement independent of the rest. Keeping a purification in another accessible work register would defeat this reset. The distinguishing experiment therefore erases **all** accessible quantum work systems, not just the port. The sealed reference survives, but cannot interact with any controller across the cut. + +### A probability is the directly measured quantity + +For a two-qubit Bell state $`|\Phi_2\rangle=(|00\rangle+|11\rangle)/\sqrt2`$, the pass probability on output state $`\rho_{RS}`$ is + +```math +P_{\mathrm{pass}} +=\langle\Phi_2|\rho_{RS}|\Phi_2\rangle. +``` + +Watrous uses the unsquared, or root, fidelity convention. For this pure target the displayed probability equals the **square** of that fidelity. The proof uses the probability itself. A favorable conditional outcome is not free success: all failed outcomes remain in the distribution. + +### The distance includes a factor of one half + +The project's state-distance convention is $`\tfrac12\|\rho-\sigma\|_1`$. Its one-channel analogue is half the completely bounded trace norm from Section 3.3.2, commonly called the diamond norm. A process has several intervention slots, so [the model](../science/model.md#distance-and-order-of-quantifiers) optimizes distinguishability over finite causal experiments rather than replacing the whole process by one passive channel snapshot. + +The normalized Bell projector used in a test has trace one. Under the usual unnormalized Choi convention, the Choi operator of a qubit identity channel is twice that projector. This normalization changes neither the physical channel nor the test, but it matters when reading formulas. + +## What must be added to the textbook foundations + +**A causal memory model.** The emulator receives actual quantum inputs as they arrive. It cannot receive the unknown state of the reference or future private choices. It may adapt using an unlimited classical history. Its coherent storage is bounded at every intervention boundary. This is stronger than asking for a numerical prediction of a fully described experiment. The definitions and quantifiers are in [the model](../science/model.md). + +**An inherited control theorem.** The Kato–Owari–Maruyama theorem supplies the stabilized bath decomposition + +```math +\mathcal H_E=\bigoplus_j\mathcal H_{B_j}\otimes\mathcal H_{Q_j}. +``` + +Its independent connected control allows a sector to be recorded classically and an unknown payload to be written into and retrieved from $`Q_j`$. A qubit port is first enlarged by a controllable laboratory qubit; that helper is also erased at the memory cuts. [Control structure](../science/control_structure.md) states the imported theorem, the required closure argument and the resulting operations. These are research-level dependencies, not topics attributed to Watrous. + +**A repeated operational argument.** A memory of dimension $`D`$ can preserve Bell overlap at most $`D/r`$ across a complete working-laboratory reset for an $`r`$-dimensional payload. The mixed-state Schmidt-number bound is an inherited ingredient, with attribution and proof in [the memory argument](../science/memory_law.md#a-one-round-dimension-lemma). Fresh references let that bound be applied after every prior classical history. This does not require independent emulator errors. + +For $`n`$ repeated tests and total control-approximation error $`\eta`$, one finite tester has separation at least + +```math +q_D-\left(\frac{D}{D+1}\right)^n-\eta, +\qquad +q_D=\sum_{j:r_j>D}p_j. +``` + +An emulator can also reproduce every sector with $`r_j\leq D`$ exactly and replace the others at total error at most $`q_D`$. These two directions give the [sharp law](../science/memory_law.md) + +```math +\epsilon_D^\infty(H,\tau)=q_D. +``` + +Each chosen tester is finite, but approaching the tail can require longer experiments and more accurate control. The theorem does not supply a universal witness time. The [worked example](WORKED_EXAMPLE.md) makes the storage cut explicit; [the scientific examples](../science/examples.md) show why a weak bath term can be negligible at fixed time and decisive over unrestricted time. + +[Learning route](README.md) · [Milestone map](MILESTONES.md) · [Sources and attribution](../references/related_work.md) diff --git a/learning/WORKED_EXAMPLE.md b/learning/WORKED_EXAMPLE.md new file mode 100644 index 0000000..01445f0 --- /dev/null +++ b/learning/WORKED_EXAMPLE.md @@ -0,0 +1,135 @@ +# Store a qubit, erase the laboratory, retrieve it + +[Learning route](README.md) · [Textbook bridge](WATROUS_BRIDGE.md) · [Memory-law proof](../science/memory_law.md) + +A device is useful as quantum memory if it can return an unknown state together with its correlations. We test this using one half of a Bell pair. The other half stays sealed, so it cannot secretly carry the payload back to the device. + +## The device and its input + +Let the visible port $`S`$ and hidden bath $`E`$ each be one qubit. Their known static Hamiltonian is + +```math +H=J W_{ES},\qquad J>0, +``` + +where the SWAP operator $`W_{ES}`$ exchanges their states and satisfies $`W_{ES}^2=I`$. Consequently + +```math +e^{-itH}=\cos(Jt)I-i\sin(Jt)W_{ES}. +``` + +At $`t_*=\pi/(2J)`$, this is a SWAP up to a physically irrelevant global phase. The bath starts in any fixed supplied density operator $`\tau_E`$, independent of the laboratory. + +Prepare the port and a reference qubit $`R`$ in + +```math +|\Phi_2\rangle_{RS} +=\frac{|00\rangle+|11\rangle}{\sqrt2}. +``` + +The reference is now sealed. It has no interaction with the port, the bath or a controller until the final measurement. The port alone has the known mixed state $`I/2`$, but returning that local state is insufficient: its correlations with $`R`$ must survive. The emulator receives the actual port, and has no access to $`R`$ or an alternative input path. + +## Follow one complete round + +Write $`\Phi_{RS}=|\Phi_2\rangle\langle\Phi_2|_{RS}`$. The three relevant stages are + +```math +\Phi_{RS}\otimes\tau_E +\ \xrightarrow{\text{write SWAP}}\ +\Phi_{RE}\otimes\tau_S +\ \xrightarrow{\text{reset }S}\ +\Phi_{RE}\otimes|0\rangle\langle0|_S +\ \xrightarrow{\text{read SWAP}}\ +\Phi_{RS}\otimes|0\rangle\langle0|_E. +``` + +Each SWAP takes idle duration $`t_*`$. The middle intervention discards the port and prepares it in $`|0\rangle`$. Any additional accessible working or controller qubits would be discarded too. In this simple device none are needed. The reference is the only surviving laboratory quantum system, and its seal prevents a bypass. + +After retrieval, measure the pair $`RS`$ using two outcomes: + +```math +P_{\mathrm{pass}}=\Phi_{RS},\qquad +P_{\mathrm{fail}}=I_{RS}-\Phi_{RS}. +``` + +The physical device passes with probability one. The bath ends in $`|0\rangle`$, so another round can start with a fresh Bell pair without refreshing the bath. This explicit Hamiltonian supplies exact SWAPs; the general theorem instead obtains its storage operations through the inherited control result. + +## What a purely classical emulator can do + +A classical-memory emulator may measure, retain arbitrarily many classical outcomes and adapt its later behavior. It may use temporary quantum systems during each interval. At the cut, however, the port is erased and no hidden quantum system may survive: this is hard coherent dimension $`D=1`$. + +After the cut, the sealed reference and any later returned output must have a separable state, of the form + +```math +\rho_{RS}=\sum_x a_x\,\sigma_R^{(x)}\otimes\omega_S^{(x)}, +\qquad a_x\ge0,\quad\sum_xa_x=1. +``` + +For a normalized product vector $`|u\rangle_R|v\rangle_S`$, Cauchy–Schwarz gives + +```math +|\langle\Phi_2|u\otimes v\rangle|^2 +=\frac{|u_0v_0+u_1v_1|^2}{2} +\le\frac12. +``` + +Decomposing mixed product states into pure ones and taking convex combinations preserves the bound. Therefore every such emulator has Bell acceptance at most one half. Measuring the input in the computational basis, retaining the outcome and returning the corresponding basis state attains one half, illustrating the difference between preserving a classical bit and preserving the full qubit. + +The test counts both outcomes. Discarding failed rounds would change the task. + +## Repeat against an adaptive emulator + +Use a fresh independent Bell pair in every round. After measuring one round, discard its reference and payload and reset the laboratory before starting the next. The emulator may retain all classical history and change its strategy. + +Conditional on any history in which earlier tests passed, the next fresh pair still faces the same erased-laboratory cut. The next conditional passing probability is at most one half. Thus + +```math +\Pr_{\mathrm{physical}}(\text{all }n\text{ pass})=1, +\qquad +\Pr_{\mathrm{classical}}(\text{all }n\text{ pass})\le2^{-n}. +``` + +This multiplication uses conditional probabilities, not an assumption of independent emulator errors. The event difference lower-bounds total variation, giving separation at least $`1-2^{-n}`$. + +| Rounds | Physical all-pass probability | Classical all-pass ceiling | Guaranteed separation | +| --- | --- | --- | --- | +| 1 | 1 | 1/2 | 1/2 | +| 3 | 1 | 1/8 | 7/8 | +| 6 | 1 | 1/64 | 63/64 | + +Each experiment is finite. The separation approaches one as the number of rounds grows; the table does not claim perfect discrimination in one fixed finite experiment. + +## Add a rare quantum sector + +Now consider a device with the supplied controllability structure $`r_0=1`$, $`r_1=2`$, and initial sector weights $`1-p`$ and $`p`$. Assume the independent sector control required in [the scientific model](../science/model.md), including its indirectly compiled sector readout. The scalar sector needs only classical hidden storage. The two-dimensional sector supports the storage experiment above. + +Read the sector into a flag, measure the flag and discard its quantum register. Keep only its classical value. Define event $`A_n`$ as: the flag reports the two-dimensional sector and every one of $`n`$ subsequent Bell tests passes. For the ideal effective operations, + +```math +\Pr_{\mathrm{physical}}(A_n)=p, +\qquad +\Pr_{D=1}(A_n)\le2^{-n}. +``` + +The second bound lets the emulator choose any flag distribution. Requiring it to reproduce the target flag distribution would be an extra restriction and is unnecessary. The ideal event gives separation at least $`p-2^{-n}`$. For a general Hamiltonian realizing these sectors, finite control compilation gives, for any chosen total operational error $`\eta>0`$, a finite experiment with separation at least $`p-2^{-n}-\eta`$. This is one error budget for the whole compiled experiment. + +Conversely, a classical emulator can simulate the scalar sector exactly and replace the quantum sector, giving uniform error at most $`p`$. Repetition approaches this same number from below. The exact all-time optimum is therefore $`\epsilon_1^\infty=p`$, while dimension $`D=2`$ represents both sectors exactly. + +For example, if $`p=1/4`$, the ideal six-round lower bound is $`15/64`$ and the matching uniform upper bound is $`1/4`$. Finite compilation gives the former bound minus $`\eta`$. Rare sectors reduce the unavoidable operational discrepancy, even though their occupied quantum factor still requires a qubit for exact universal emulation. + +## Resource account and scope + +| Item | Treatment in the simple SWAP experiment | +| --- | --- | +| Hidden persistent quantum state | One bath qubit; every emulator hidden carrier is included in its hard cap. | +| Visible quantum systems | One port and one fresh sealed reference per round, used sequentially. | +| Input and output | A reference-correlated qubit enters; a qubit returns for a Bell measurement. | +| Preparations and measurements | One fresh Bell pair and one two-outcome Bell measurement per round. | +| Erasure | The port and all accessible work registers are erased at the storage cut; old test registers are discarded between rounds. | +| Bath reuse | The same bath persists; the read SWAP leaves it in a fixed state for the next round. | +| Idle duration | Two intervals per round, total $`2nt_*`$ for $`n`$ rounds. | +| Classical records | All labels, pass/failure outcomes and adaptation are allowed. | + +These are ideal preparations, resets and controls. The general weighted-sector example may require long control compilation and is not assigned the explicit SWAP duration. The main theorem proves a structural memory cost over arbitrary finite experiments, with no universal shortest witness time or noisy-control guarantee. + +[Next: the complete milestone map](MILESTONES.md) · [Exact proof and quantifiers](../science/memory_law.md) · [Physical limitations](../science/interpretation.md) diff --git a/llms.txt b/llms.txt index 39bc70a..4f66f6d 100644 --- a/llms.txt +++ b/llms.txt @@ -14,6 +14,12 @@ This repository gives an exact hard quantum-memory versus uniform process-error - science/examples.md: weighted staircase; exact qutrit–qubit Lie spanning; finite-time Duhamel bound and order of weak-coupling/long-time limits. - science/interpretation.md: what counts as persistent quantum memory, what is free, and which physical consequences do not follow. +## Learning +- learning/README.md: selected Watrous2018 route, exact source identity and story. +- learning/WATROUS_BRIDGE.md: verified textbook sections, norm/fidelity/Choi conventions and explicitly supplied research dependencies. +- learning/WORKED_EXAMPLE.md: complete SWAP–reset–retrieve experiment, sealed reference, classical ceiling, adaptive repetition, rare-sector and finite compilation-error qualification. +- learning/MILESTONES.md: exactly M01–M30, twelve background and eighteen narrative project-intrinsic understanding targets, each progressing from local ingredients to synthesis. + ## Attribution and reproduction - references/related_work.md: inherited control/compression/comb/Schmidt-number ingredients and specific operational addition. - references/references.bib: primary bibliographic identities and exact versions. diff --git a/science/README.md b/science/README.md index 0a4a349..721300c 100644 --- a/science/README.md +++ b/science/README.md @@ -17,6 +17,7 @@ The [examples](examples.md) give a weighted memory staircase and a fully control | Follow the mechanism | Model → control structure → memory law → classical boundary → examples → interpretation | | Check the theorem | Model’s quantifiers, control theorem transfer, one-round Schmidt-number lemma, repeated finite tester, approximation and horizon limit | | Inspect attribution | [Primary comparisons](../references/related_work.md) and [bibliography](../references/references.bib) | +| Learn from the selected textbook | [Watrous route and worked example](../learning/README.md) | | Reproduce finite examples | [Verification](../verification/README.md) | The sharp tail law is the project’s operational addition. The algebraic classification, classical/quantum/irrelevant distinction, classical-assisted memory convention and Bell-overlap inequality are credited to their prior sources. diff --git a/science/examples.md b/science/examples.md index 0e8a192..b92cc8f 100644 --- a/science/examples.md +++ b/science/examples.md @@ -39,7 +39,7 @@ where the first tensor factor is the port. Every port Hamiltonian is controllabl At zero transverse term the two eigenspaces of bath Z are invariant. Conditional on its eigenvalue, the port evolves under C or minus C. Thus one classical bit is an exact hidden memory for every controlled experiment. -The connected Lie algebra has dimension 16 and is the direct sum of two copies of su(3). To see this, port controls supply su(3) tensored with the bath identity; the nonzero traceless C and the simplicity of su(3) give su(3) tensored with Z. Their commutators close within these two spaces. Both active factors have dimension one. +The connected Lie algebra has dimension 16 and is the direct sum of two copies of su(3). To see this, port controls supply su(3) tensored with the bath identity; the nonzero traceless C and the simplicity of su(3) give su(3) tensored with Z. Their commutators close within these two spaces. Both controllable-factor spaces have dimension one; only sectors of nonzero initial weight are occupied. ### Any nonzero transverse term diff --git a/science/interpretation.md b/science/interpretation.md index 14e0cd0..f535027 100644 --- a/science/interpretation.md +++ b/science/interpretation.md @@ -7,7 +7,7 @@ The [main theorem](memory_law.md) determines the smallest hidden quantum carrier | Part | Operational role | Required simulator storage | | --- | --- | --- | | Sector label j | A conserved label selecting conditional dynamics | Classical storage | -| Active factor R_j | Can receive and later return arbitrary quantum information through port controls | Coherent storage of dimension r_j | +| Active factor Q_j | Can receive and later return arbitrary quantum information through port controls | Coherent storage of dimension r_j | | Invisible multiplicity B_j | Its evolution cannot influence future port experiments | Can be traced out | This decomposition and its controllability properties come from earlier quantum-control theory. General quantum/classical/irrelevant decompositions and quantum-memory cost with free classical records also have established antecedents. The contribution here is the sharp weighted uniform process-error law and its repeated operational witness. See [related work](../references/related_work.md). diff --git a/verification/README.md b/verification/README.md index da4b3ab..2bdbaa3 100644 --- a/verification/README.md +++ b/verification/README.md @@ -18,7 +18,7 @@ The program raises an exception on a failed check, prints one `PASS` line for ea | Finite dimension obstruction | For every $`2\le r\le6`$ and $`1\le D\le r`$, decode an actual mixed state on $`R\otimes M_D`$ by a local isometry and evaluate its Bell overlap. Also construct saturating Schmidt-rank-$`D`$ states. | The finite Bell bound $`D/r`$ concerns coherent dimension and survives mixing and local decoding. The general statement follows from the written Schmidt-number proof. | | Physical compression with a classical branch | Encode a Bell half into at most $`D`$ levels using a CPTP block-selection instrument, retain the block label classically, and decode each branch. Check completeness, trace preservation and the unchanged sealed-reference marginal. | The bound is attainable by this channel when $`D`$ divides $`r`$. For a smaller final block the program reports the actual lower overlap; it does not claim universal channel saturation in every dimension. | | Qutrit-port Lie algebra | Starting only with the eight local qutrit generators and $`H_g=C\otimes Z+gI\otimes X`$, form commutators and perform exact rational real-coordinate elimination until closure or the full traceless dimension is reached. | The dimensions are exactly 16 at $`g=0`$ and 35 at the tested nonzero values $`g=1,1/3`$. No floating rank threshold is used. The statement for **every** nonzero $`g`$ comes from the analytical spanning argument. | -| Finite-time perturbation | Evolve the qutrit–qubit Hamiltonians by matrix exponentials, apply a two-outcome port instrument, choose a later control and idle duration from its outcome, and retain both classical output flags and a reference. | At 18 tested combinations of initial bath rank, coupling and hard horizon, the actual flagged half trace distance obeys $`d_T\le\min\{1,|g|T\}`$. The example is not a search over testers or a formula for the optimal finite-horizon memory. | +| Finite-time perturbation | Evolve the qutrit–qubit Hamiltonians by matrix exponentials, apply a two-outcome port instrument, choose a later control and idle duration from its outcome, and retain both classical output flags and a reference. | At 18 tested combinations of initial bath rank, coupling and hard horizon, the actual flagged half trace distance obeys $`d_T\le\min\{1,\lvert g\rvert T\}`$. The example is not a search over testers or a formula for the optimal finite-horizon memory. | | Weighted sectors | Construct one bath state with actual inter-sector coherences, prescribed controllable dimensions $`(1,2,4)`$ and invisible dimensions $`(2,1,2)`$. Compare two controlled full-bath intervals with a reduced classical-sector realization after tracing invisible factors. | The projector probabilities recover $`(0.6,0.3,0.1)`$; the tested reference-complete output reduction agrees numerically. The corresponding memory staircase is $`(0.4,0.1,0.1,0)`$. A physical two-round dimension-2 compressor on the four-level sector has weighted Bell-event probability $`0.025`$, versus $`0.1`$ for ideal storage. | The weighted-sector check starts from a **supplied** block structure. It does not infer that structure from an unknown Hamiltonian. The random block unitaries verify the reduced-model mechanism; they are not claimed to be pulses compiled from the qutrit example. From 03f3dba3223c6f9880b59d0f6dde0d57d731f15c Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Fri, 13 Nov 2026 19:44:49 +0800 Subject: [PATCH 2/4] Verify commit-pinned hosted mathematics with a read-only capture job --- .github/workflows/hosted-math.yml | 53 ++ verification/hosted_math/README.md | 22 + .../hosted_math/capture_hosted_math.cjs | 549 ++++++++++++++++++ .../hosted_math/check_rendered_math.py | 370 ++++++++++++ 4 files changed, 994 insertions(+) create mode 100644 .github/workflows/hosted-math.yml create mode 100644 verification/hosted_math/README.md create mode 100644 verification/hosted_math/capture_hosted_math.cjs create mode 100644 verification/hosted_math/check_rendered_math.py diff --git a/.github/workflows/hosted-math.yml b/.github/workflows/hosted-math.yml new file mode 100644 index 0000000..072afb1 --- /dev/null +++ b/.github/workflows/hosted-math.yml @@ -0,0 +1,53 @@ +name: Hosted mathematics + +on: + pull_request: + paths: + - '**.md' + - 'verification/hosted_math/**' + - '.github/workflows/hosted-math.yml' + +permissions: + contents: read + +concurrency: + group: hosted-math-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + capture: + if: github.repository == 'GoGoKo699/Hamiltonian-Quantum-Memory' && github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-24.04 + timeout-minutes: 20 + env: + CAPTURE_REVISION: ${{ github.event.pull_request.head.sha }} + steps: + - name: Check out the exact proposed source + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + ref: ${{ env.CAPTURE_REVISION }} + persist-credentials: false + - name: Set up Node + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: '22' + - name: Install the capture runtime + run: | + npm install --ignore-scripts --no-audit --no-fund --prefix "$RUNNER_TEMP/math-runtime" playwright@1.56.1 mathjax-full@3.2.1 + node "$RUNNER_TEMP/math-runtime/node_modules/playwright/cli.js" install --with-deps chromium + - name: Compare every hosted mathematical expression + run: | + export NODE_PATH="$RUNNER_TEMP/math-runtime/node_modules" + node verification/hosted_math/capture_hosted_math.cjs \ + --root "$GITHUB_WORKSPACE" \ + --repository "$GITHUB_REPOSITORY" \ + --revision "$CAPTURE_REVISION" \ + --output "$RUNNER_TEMP/hosted-math" + - name: Retain the actual captures and comparison report + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: hosted-math-${{ env.CAPTURE_REVISION }} + path: ${{ runner.temp }}/hosted-math + if-no-files-found: error + retention-days: 14 diff --git a/verification/hosted_math/README.md b/verification/hosted_math/README.md new file mode 100644 index 0000000..207a992 --- /dev/null +++ b/verification/hosted_math/README.md @@ -0,0 +1,22 @@ +# Actual hosted mathematics + +The [read-only capture workflow](../../.github/workflows/hosted-math.yml) checks the mathematical expressions rendered by GitHub at the exact source commit proposed by a pull request from this repository. It visits every tracked Markdown page at widths 1440 and 760 pixels, compares the accessible MathML with the pinned source, checks expression counts and supported relations, and retains full-page screenshots and HTML alongside the report. + +The workflow uploads an artifact named `hosted-math-` for 14 days. Its `hosted-report.json`, per-page receipts and screenshots are observations of that source revision. A successful scientific reproduction run, local Markdown inventory or an earlier screenshot is not a substitute for this hosted report. Screenshots still need visual review: the automated comparison does not certify complete layout quality or scientific correctness. + +The collector and text checker use the pinned implementations identified by these SHA-256 values: + +| File | SHA-256 | +| --- | --- | +| `capture_hosted_math.cjs` | `c96f5c769ef62711137fc4d75e110cfb40c0db149c87590cdfb463b69a648b54` | +| `check_rendered_math.py` | `edbc2d72af94e96b78166d74b66fcea150134f2f3ebaaea121e9057768e1dbfe` | + +The workflow structure was adapted from the inspected `hosted-math.yml` at Quantum-Memory-Calibration commit `213dcbf5013bf7ea63f796e6288ef24963281b23`. The helper implementations are unchanged. This repository-specific adaptation restricts the job to same-repository pull requests and disables npm lifecycle scripts during package installation. + +## Permissions and limits + +The job grants only `contents: read`. It checks out the exact pull-request head with credential persistence disabled. It does not request secrets, store authentication state, use signed-in browser sessions, publish pages, edit repository contents or change repository settings. All actions are pinned by their inspected full commit identifiers; Playwright and MathJax use explicit package versions. Installation downloads the browser and runtime on the disposable runner; it does not assert a frozen transitive npm dependency graph. + +The browser is anonymous and read-only. It rejects redirects away from the exact pinned GitHub URL and reports access failures, transport failures, rendering failures and policy denials distinctly. Capture artifacts can contain only the public pages actually visited in that anonymous session. No private-account screenshots are requested by this workflow. + +The workflow is a capture route, not a record that captures already passed. Inspect its actual run and source-bound artifact before claiming hosted verification. Failed reports and partial captures remain failed evidence. A changed mathematical source requires another capture at the corresponding revision. diff --git a/verification/hosted_math/capture_hosted_math.cjs b/verification/hosted_math/capture_hosted_math.cjs new file mode 100644 index 0000000..6f36ee0 --- /dev/null +++ b/verification/hosted_math/capture_hosted_math.cjs @@ -0,0 +1,549 @@ +#!/usr/bin/env node +'use strict'; +// Read-only collector for the real GitHub host. See ../references/hosted-rendering.md. +// Importing this module has no network effects; dependencies load only in run(). +const fs = require('node:fs'); +const path = require('node:path'); +const cp = require('node:child_process'); +const crypto = require('node:crypto'); +const VIEWPORTS = [{width:1440,height:1000}, {width:760,height:1000}]; +const RENDER_TIMEOUT_MS = 30000; +const sha256 = bytes => crypto.createHash('sha256').update(bytes).digest('hex'); + +function argumentsFor(argv) { + const args = {pages:[], python:'python3'}; + for (let i=0; i['.','..'].includes(p))) throw new Error('Use exact owner/name'); + if (!/^[a-f0-9]{40}$/.test(args.revision)) throw new Error('Use a full lowercase commit SHA'); + if (new Set(args.pages).size!==args.pages.length || args.pages.some(p=>!safePath(p))) throw new Error('Use unique safe page paths'); + return args; +} +function safePath(p) { + return typeof p==='string' && p.length>0 && !p.includes('\\') && !p.includes('\0') && + !p.startsWith('/') && p.split('/').every(x=>x && x!=='.' && x!=='..'); +} +function git(root, argv) { + return cp.execFileSync('git',['--no-replace-objects',...argv],{cwd:root,encoding:'utf8',maxBuffer:32*1024*1024}); +} +function pinnedPages(args) { + const commit=git(args.root,['rev-parse',args.revision+'^{commit}']).trim(); + if (commit!==args.revision) throw new Error('Revision does not identify the supplied commit'); + const files=git(args.root,['ls-tree','-r','--name-only','-z',commit]).split('\0').filter(Boolean); + const pages=args.pages.length?args.pages:files.filter(p=>/\.(md|markdown|mdown|mkdn|mkd)$/i.test(p)); + if (!pages.length || pages.some(p=>!safePath(p) || !files.includes(p))) throw new Error('No pages or a page is absent from the pinned tree'); + // Git symlinks are not rendered Markdown source and must not be followed. + for (const p of pages) { + const item=git(args.root,['ls-tree',commit,'--',p]); + if (!/^100644 blob |^100755 blob /.test(item)) throw new Error('Page must be a regular tracked file: '+p); + } + return {pages,tree:git(args.root,['rev-parse',commit+'^{tree}']).trim()}; +} +function mathCompiler() { + const {mathjax}=require('mathjax-full/js/mathjax.js'); + const {TeX}=require('mathjax-full/js/input/tex.js'); + const {SVG}=require('mathjax-full/js/output/svg.js'); + const {liteAdaptor}=require('mathjax-full/js/adaptors/liteAdaptor.js'); + const {RegisterHTMLHandler}=require('mathjax-full/js/handlers/html.js'); + const {AllPackages}=require('mathjax-full/js/input/tex/AllPackages.js'); + const {SerializedMmlVisitor}=require('mathjax-full/js/core/MmlTree/SerializedMmlVisitor.js'); + const {STATE}=require('mathjax-full/js/core/MathItem.js'); + RegisterHTMLHandler(liteAdaptor()); + const doc=mathjax.document('',{InputJax:new TeX({packages:AllPackages,tags:'none'}),OutputJax:new SVG({fontCache:'none'})}); + const visitor=new SerializedMmlVisitor(); + return (tex,display)=>visitor.visitTree(doc.convert(tex,{display,end:STATE.CONVERT})); +} + +// Self-contained function executed inside the hosted page, also exercised by the +// local-browser regression fixture. It never injects styling or renders TeX there. +function inspectArticle(root, expected) { + function canonical(e, inherited='') { + const tag=e.localName; + if (['annotation','annotation-xml','mspace'].includes(tag)) return []; + const variant=e.getAttribute('mathvariant') || inherited; + if (['mi','mo','mn','mtext','ms'].includes(tag)) { + const text=e.textContent.trim(); + return text?[[tag,text,variant]]:[]; + } + // Preserve each structural child slot: flattening numerator and denominator + // together would confuse (a+b)/c with a/(b+c), and similarly for scripts. + const children=[...e.children].filter(c=>!['annotation','annotation-xml','mspace'].includes(c.localName)) + .map(c=>canonical(c,variant)); + if (['math','mrow','mstyle','semantics'].includes(tag)) return children.flat(); + const semantic={}; + for (const name of ['notation','accent','accentunder','linethickness','bevelled','open','close','separators']) if(e.hasAttribute(name)) semantic[name]=e.getAttribute(name); + // A table cell is an inferred row (a sequence), not a fixed-arity operator. + // GitHub inserts empty mrow alignment nodes; ignore those inside the cell + // while preserving the cell and row themselves, including empty cells. + return [[tag,semantic,tag==='mtd'?children.flat():children]]; + } + function plain(math) { + const copy=math.cloneNode(true); + for (const e of copy.querySelectorAll('annotation,annotation-xml')) e.remove(); + return copy.textContent; + } + function geometry(math, host) { + const boxes=[...math.querySelectorAll('mi,mo,mn,mtext,ms')].map(e=>e.getBoundingClientRect()).filter(b=>b.width && b.height); + if (!boxes.length) return {measurable:false}; + const left=Math.min(...boxes.map(b=>b.left)),right=Math.max(...boxes.map(b=>b.right)); + const top=Math.min(...boxes.map(b=>b.top)),bottom=Math.max(...boxes.map(b=>b.bottom)); + const width=right-left,height=bottom-top; + return {measurable:true,width,height,available_width:root.clientWidth, + overflow:width>root.clientWidth+4,collapsed:height>Math.max(200,3*width),host_width:host.getBoundingClientRect().width}; + } + let hosts=[...root.querySelectorAll('math-renderer')]; + // Some host versions expose native MathML without a custom-element wrapper. + if (!hosts.length) hosts=[...root.querySelectorAll('math')].filter(e=>!e.parentElement?.closest('math,annotation,annotation-xml')); + const pageErrors=[...root.querySelectorAll('merror,[data-mjx-error],.katex-error,math-renderer .flash-error')] + .map(e=>e.textContent.trim() || 'empty renderer error'); + const math=hosts.map((host,i)=>{ + const nodes=host.localName==='math'?[host]:[...host.querySelectorAll('math')].filter(e=>!e.parentElement?.closest('math,annotation,annotation-xml')); + const errors=[]; + if(nodes.length!==1) errors.push('Expected one accessible MathML representation; found '+nodes.length); + const actual=nodes[0],want=expected[i]; + let expectedSignature=null,actualSignature=null; + if(actual) actualSignature=JSON.stringify(canonical(actual)); + if(want) { + const parsed=new DOMParser().parseFromString(want.mml,'application/xml'); + if(parsed.querySelector('parsererror,merror')) errors.push('Source compiler returned invalid/error MathML'); + else expectedSignature=JSON.stringify(canonical(parsed.documentElement)); + } + if(!want) errors.push('Unexpected extra hosted expression'); + const match=!!actual && !!expectedSignature && expectedSignature===actualSignature; + if(!match) errors.push('Source-to-host MathML structure mismatch'); + const measure=actual?geometry(actual,host):{measurable:false}; + if(want && ['math-fence','dollar-display'].includes(want.kind) && (!measure.measurable || measure.overflow || measure.collapsed)) + errors.push('Display geometry is unmeasurable, overflowing or collapsed'); + return {rendered:!!actual,errors,text_source:'mathml',text:actual?plain(actual):'', + source_sha256:want?.source_sha256,structural_match:match, + expected_signature:expectedSignature,actual_signature:actualSignature,geometry:measure}; + }); + return {errors:pageErrors,math}; +} + +// Self-contained, read-only page probe. Presence of a custom-element placeholder +// is not readiness; wait for the accessible representation used by inspection. +function hostedMathReadiness(root, expectedCount) { + const errors=[...root.querySelectorAll('merror,[data-mjx-error],.katex-error,math-renderer .flash-error')] + .map(e=>e.textContent.trim() || 'empty renderer error'); + let hosts=[...root.querySelectorAll('math-renderer')]; + if(!hosts.length) hosts=[...root.querySelectorAll('math')] + .filter(e=>!e.parentElement?.closest('math,annotation,annotation-xml')); + let usable=0; + for(const host of hosts) { + const nodes=host.localName==='math'?[host]:[...host.querySelectorAll('math')] + .filter(e=>!e.parentElement?.closest('math,annotation,annotation-xml')); + if(nodes.length!==1) continue; + const copy=nodes[0].cloneNode(true); + for(const annotation of copy.querySelectorAll('annotation,annotation-xml')) annotation.remove(); + if(copy.textContent.trim() && copy.querySelector('mi,mo,mn,mtext,ms')) usable++; + } + return {ready:errors.length===0 && hosts.length===expectedCount && usable===expectedCount, + errors,expected_hosts:expectedCount,observed_hosts:hosts.length,usable_hosts:usable}; +} + +async function waitForHostedMath(article, expectedCount, options={}) { + const timeoutMs=options.timeoutMs ?? RENDER_TIMEOUT_MS, intervalMs=options.intervalMs ?? 100; + if(!Number.isFinite(timeoutMs) || timeoutMs<=0 || timeoutMs>RENDER_TIMEOUT_MS || + !Number.isFinite(intervalMs) || intervalMs<=0 || intervalMs>timeoutMs || + !Number.isInteger(expectedCount) || expectedCount<0) + throw new Error('Invalid bounded hosted-math readiness wait'); + // Clock/delay injection is for deterministic offline adapters; production uses + // a monotonic clock and an explicitly bounded poll budget. + const now=options.now || (()=>performance.now()); + const delay=options.delay || (ms=>new Promise(resolve=>setTimeout(resolve,ms))); + const started=now(), maxPolls=Math.ceil(timeoutMs/intervalMs)+1; + let state; + for(let poll=0;poll{timer=setTimeout(()=>reject(new Error( + 'Hosted mathematics readiness evaluation exceeded its bounded budget')),evaluationBudget)}), + ]); + } finally {clearTimeout(timer);} + if(state.errors.length) throw new Error('Hosted mathematics renderer error: '+state.errors.join('; ')); + if(state.ready) return state; + const remaining=timeoutMs-(now()-started); + if(remaining<=0 || poll===maxPolls-1) break; + await delay(Math.min(intervalMs,remaining)); + } + // This is a verification failure, not evidence of a transport interruption + // eligible for blind capture resume. Missing/malformed hosts never pass. + throw new Error('Hosted mathematics readiness failed after '+timeoutMs+' ms: expected '+expectedCount+ + ' hosts; observed '+state?.observed_hosts+'; usable '+state?.usable_hosts); +} + +function classifyFailure(error) { + const message=String(error); + if (/ERR_BLOCKED_BY_ADMINISTRATOR|blocked by.*policy|URLBlocklist|policy denied/i.test(message)) return 'policy_denied'; + if (/HTTP (401|403)|redirected away|sign.in|authentication/i.test(message)) return 'access_required'; + if (/Cannot find module|Executable doesn't exist|browser executable/i.test(message)) return 'capability_unavailable'; + if (/HTTP (429|5[0-9]{2})|ERR_NAME_NOT_RESOLVED|ENOTFOUND|ERR_CONNECTION|ERR_EMPTY_RESPONSE|ERR_INTERNET_DISCONNECTED|ECONNRESET|Timeout|timed out/i.test(message)) return 'transport_failure'; + return 'verification_failure'; +} +function writeJSON(filename, value) {fs.writeFileSync(filename,JSON.stringify(value,null,2)+'\n');} +function artifact(directory, relative, kind) { + const bytes=fs.readFileSync(path.join(directory,relative)); + return {path:relative,sha256:sha256(bytes),size_bytes:bytes.length,kind}; +} +function boundReport(inventory, tree, viewports, artifacts, failures, at) { + const boundaries=inventory.pages.map(p=>{ + const counts=viewports.map(v=>v.boundaries?.find(b=>b.path===p.path)?.captured_hosts); + return {path:p.path,url:p.url,revision:inventory.revision,source_sha256:p.source_sha256, + source_expressions:p.expressions.length, + captured_hosts:counts.length===VIEWPORTS.length && counts.every(n=>Number.isInteger(n) && n===counts[0])?counts[0]:null}; + }); + const wanted=inventory.pages.reduce((n,p)=>n+p.expressions.length,0); + failures=[...failures]; + if(JSON.stringify(viewports.map(v=>({width:v.width,height:v.height})))!==JSON.stringify(VIEWPORTS)) + failures.push('Missing, duplicate or unexpected viewport coverage'); + for(const viewport of viewports) { + if(JSON.stringify((viewport.boundaries||[]).map(b=>b.path))!==JSON.stringify(inventory.pages.map(p=>p.path))) + failures.push(viewport.width+': page coverage differs from inventory'); + for(const source of inventory.pages) { + const boundary=viewport.boundaries?.find(b=>b.path===source.path); + if(!boundary || boundary.source_sha256!==source.source_sha256 || boundary.revision!==inventory.revision || + boundary.url!==source.url || boundary.source_expressions!==source.expressions.length || boundary.captured_hosts!==source.expressions.length) + failures.push(viewport.width+': incomplete source/host coverage for '+source.path); + } + } + const structural=viewports.length===VIEWPORTS.length && viewports.every(v=>v.structural_matches===wanted); + const pass=!failures.length && structural && viewports.length===VIEWPORTS.length && viewports.every(v=>v.status==='pass'); + return {schema_version:1,kind:'hosted_math',repository:inventory.repository,revision:inventory.revision,tree, + renderer_profile:'github',captured_at:at,capture_method:'playwright-github',status:pass?'pass':'fail', + required_pages:inventory.pages.map(p=>p.path),boundaries,viewports,artifacts,failures, + structural_comparison:{status:structural?'pass':'fail',expressions_checked:structural?wanted:0}, + visual_review_required:true, + limits:'Observed GitHub MathML structure, counts, labels, relations and bounded geometry only. No independent scientific proof, exhaustive pixel review, host authenticity certificate or cross-browser guarantee.'}; +} + +// Resume is an explicit new attempt against identical source and execution inputs. +// Receipts bind observations, not authenticity: the final visual review is separate. +const RESUME_MAX_AGE_MS = 24*60*60*1000; +const MAX_EVIDENCE_BYTES = 32*1024*1024; +function safeEvidenceFile(directory, relative) { + if(!safePath(relative)) throw new Error('Unsafe evidence path: '+relative); + const root=path.resolve(directory); + if(fs.lstatSync(root).isSymbolicLink() || !fs.statSync(root).isDirectory()) + throw new Error('Evidence root must be a regular directory'); + let current=root; + for(const component of relative.split('/')) { + current=path.join(current,component); + if(fs.lstatSync(current).isSymbolicLink()) throw new Error('Symlink evidence is not reusable: '+relative); + } + const stat=fs.statSync(current); + if(!stat.isFile() || stat.size>MAX_EVIDENCE_BYTES) throw new Error('Evidence must be a bounded regular file: '+relative); + return current; +} +function readBoundArtifact(directory, descriptor) { + if(!descriptor || typeof descriptor.path!=='string' || !/^[a-f0-9]{64}$/.test(descriptor.sha256) || + !Number.isInteger(descriptor.size_bytes) || descriptor.size_bytes<0) + throw new Error('Malformed evidence artifact descriptor'); + const bytes=fs.readFileSync(safeEvidenceFile(directory,descriptor.path)); + if(bytes.length!==descriptor.size_bytes || sha256(bytes)!==descriptor.sha256) + throw new Error('Evidence artifact hash/size mismatch: '+descriptor.path); + return bytes; +} +function observationTime(value, now=Date.now()) { + const parsed=typeof value==='string' && /(?:Z|[+-]\d{2}:\d{2})$/.test(value)?Date.parse(value):NaN; + if(!Number.isFinite(parsed) || parsed>now || now-parsed>RESUME_MAX_AGE_MS) + throw new Error('Capture observation is stale, future-dated or lacks a timezone'); + return parsed; +} +function pageKey(page, viewport) {return viewport.width+'x'+viewport.height+':'+page;} +function capturePassed(source, item) { + return item && item.path===source.path && item.url===source.url && + item.revision===source.revision && item.source_sha256===source.source_sha256 && + Array.isArray(item.errors) && item.errors.length===0 && Array.isArray(item.math) && + item.math.length===source.expressions.length && item.math.every((m,index)=> + m.rendered===true && Array.isArray(m.errors) && m.errors.length===0 && m.structural_match===true && + m.source_sha256===source.expressions[index].source_sha256 && + typeof m.expected_signature==='string' && m.expected_signature.length>0 && + m.expected_signature===m.actual_signature); +} +function sessionBinding(inventory, tree, expectedBytes, contractBytes, runtime, helper, diagnosticOnly=false, inventoryBytes=null) { + return {repository:inventory.repository,revision:inventory.revision,tree, + inventory_sha256:sha256(inventoryBytes || Buffer.from(JSON.stringify(inventory,null,2)+'\n')), + expected_sha256:sha256(expectedBytes),contract_sha256:sha256(contractBytes),has_contract:contractBytes.toString('utf8')!=='null', + collector_sha256:sha256(fs.readFileSync(__filename)),checker_sha256:sha256(fs.readFileSync(helper)), + runtime,viewports:VIEWPORTS,purpose:diagnosticOnly?'diagnostic':'release_verification'}; +} +function newSession(binding, at) { + return {schema_version:1,kind:'hosted_math_session',binding,started_at:at,updated_at:at, + completed:[],failures:[]}; +} +function saveSession(output, session) { + const temporary=path.join(output,'capture-state.json.tmp'); + writeJSON(temporary,session);fs.renameSync(temporary,path.join(output,'capture-state.json')); +} +function loadResume(directory, binding, inventory, now=Date.now()) { + const bytes=fs.readFileSync(safeEvidenceFile(directory,'capture-state.json')); + const session=JSON.parse(bytes.toString('utf8')); + if(session.schema_version!==1 || session.kind!=='hosted_math_session' || + JSON.stringify(session.binding)!==JSON.stringify(binding)) + throw new Error('Resume source, scope, contract, collector/checker or runtime binding differs'); + if(!Array.isArray(session.failures) || session.failures.some(f=>f.category!=='transport_failure')) + throw new Error('Resume refused after a nontransient, policy or access failure; preserve that attempt and resolve its actual cause'); + if(!Array.isArray(session.completed)) throw new Error('Malformed completed-capture receipts'); + const sourceByPath=new Map(inventory.pages.map(p=>[p.path,{...p,revision:inventory.revision}])); + const reusable=new Map(); + for(const descriptor of session.completed) { + const receiptBytes=readBoundArtifact(directory,descriptor.receipt); + const receipt=JSON.parse(receiptBytes.toString('utf8')); + const source=sourceByPath.get(receipt.path); + const viewport=VIEWPORTS.find(v=>v.width===receipt.viewport?.width && v.height===receipt.viewport?.height); + if(!source || !viewport || receipt.schema_version!==1 || receipt.kind!=='hosted_math_page' || receipt.status!=='pass' || + receipt.repository!==inventory.repository || receipt.revision!==inventory.revision || + receipt.tree!==binding.tree || receipt.source_sha256!==source.source_sha256 || + receipt.key!==pageKey(source.path,viewport) || !capturePassed(source,receipt.capture) || + receipt.capture.observed_at!==receipt.observed_at || !Array.isArray(receipt.artifacts)) + throw new Error('Invalid or mismatched passing page receipt'); + observationTime(receipt.observed_at,now); + if(descriptor.key!==receipt.key || reusable.has(receipt.key)) throw new Error('Duplicate or mismatched page receipt key'); + const prefix=String(inventory.pages.findIndex(p=>p.path===source.path)+1).padStart(4,'0')+'-'+viewport.width; + if(descriptor.receipt.path!==prefix+'-receipt.json') throw new Error('Unexpected page receipt artifact path'); + const expectedArtifacts=new Map([ + [prefix+'-source.json','page_source_inventory'],[prefix+'-capture.json','page_hosted_capture'], + [prefix+'-result.json','page_math_result'],[prefix+'.html','hosted_html'],[prefix+'.png','screenshot']]); + if(binding.has_contract) expectedArtifacts.set(prefix+'-contract.json','page_text_contract'); + const artifactPaths=new Set(); + const payloads=receipt.artifacts.map(a=>{ + if(artifactPaths.has(a.path) || expectedArtifacts.get(a.path)!==a.kind) throw new Error('Duplicate or unexpected receipt artifact path'); + artifactPaths.add(a.path);return {descriptor:a,bytes:readBoundArtifact(directory,a)}; + }); + if(artifactPaths.size!==expectedArtifacts.size) throw new Error('Incomplete page artifact set'); + const resultArtifact=payloads.find(a=>a.descriptor.kind==='page_math_result'); + const captureArtifact=payloads.find(a=>a.descriptor.kind==='page_hosted_capture'); + const sourceArtifact=payloads.find(a=>a.descriptor.kind==='page_source_inventory'); + const result=resultArtifact?JSON.parse(resultArtifact.bytes.toString('utf8')):null; + const capture=captureArtifact?JSON.parse(captureArtifact.bytes.toString('utf8')):null; + const sourceInventory=sourceArtifact?JSON.parse(sourceArtifact.bytes.toString('utf8')):null; + if(result?.status!=='pass' || !Array.isArray(result.failures) || result.failures.length || + result.repository!==inventory.repository || result.revision!==inventory.revision || + result.captured_at!==receipt.observed_at || result.boundaries?.length!==1 || + result.boundaries[0].path!==source.path || result.boundaries[0].url!==source.url || + result.boundaries[0].revision!==inventory.revision || result.boundaries[0].source_expressions!==source.expressions.length || + result.boundaries[0].source_sha256!==source.source_sha256 || + result.boundaries[0].captured_hosts!==source.expressions.length || + result.expressions_checked!==source.expressions.length || + capture?.pages?.length!==1 || JSON.stringify(capture.pages[0])!==JSON.stringify(receipt.capture) || + capture.schema_version!==1 || capture.capture_method!=='playwright-github' || capture.renderer_profile!=='github' || + capture.captured_at!==receipt.observed_at || capture.repository!==inventory.repository || + capture.revision!==inventory.revision || + JSON.stringify(sourceInventory)!==JSON.stringify({...inventory,pages:[inventory.pages.find(p=>p.path===source.path)]}) || + !payloads.some(a=>a.descriptor.path===receipt.capture.artifacts?.html && a.descriptor.kind==='hosted_html') || + !payloads.some(a=>a.descriptor.path===receipt.capture.artifacts?.screenshot && a.descriptor.kind==='screenshot')) + throw new Error('Missing or inconsistent passing page evidence'); + reusable.set(receipt.key,{receipt,descriptor,receiptBytes,payloads, + provenance:{source_directory:path.resolve(directory),session_sha256:sha256(bytes), + receipt_sha256:descriptor.receipt.sha256,observed_at:receipt.observed_at}}); + } + return {reusable,previous_attempt:{directory:path.resolve(directory),session_sha256:sha256(bytes), + started_at:session.started_at,updated_at:session.updated_at,failures:session.failures}}; +} +function runTextCheck(args, helper, output, inventoryFile, captureFile, resultFile, contractFile=null) { + const command=[helper,'check','--inventory',path.join(output,inventoryFile),'--capture',path.join(output,captureFile), + '--output',path.join(output,resultFile)]; + if(contractFile) command.push('--contract',path.join(output,contractFile)); + const check=cp.spawnSync(args.python,command,{encoding:'utf8'}); + if(check.error || !fs.existsSync(path.join(output,resultFile))) + throw new Error('Math checker did not produce a result: '+(check.error||check.stderr)); + return JSON.parse(fs.readFileSync(path.join(output,resultFile),'utf8')); +} +function savePageReceipt(args, helper, output, session, inventory, source, viewport, item, prefix, contract) { + const capture={schema_version:1,repository:args.repository,revision:args.revision,renderer_profile:'github', + captured_at:item.observed_at,capture_method:'playwright-github',pages:[item]}; + const invFile=prefix+'-source.json',captureFile=prefix+'-capture.json',resultFile=prefix+'-result.json'; + writeJSON(path.join(output,invFile),{...inventory,pages:[source]}); + writeJSON(path.join(output,captureFile),capture); + const pageContract=contract?{...contract,expressions:contract.expressions.filter(e=>e.path===source.path)}:null; + const contractFile=pageContract?prefix+'-contract.json':null; + if(pageContract) writeJSON(path.join(output,contractFile),pageContract); + const result=runTextCheck(args,helper,output,invFile,captureFile,resultFile,contractFile); + const files=[artifact(output,invFile,'page_source_inventory'),artifact(output,captureFile,'page_hosted_capture'), + artifact(output,resultFile,'page_math_result')]; + if(contractFile) files.push(artifact(output,contractFile,'page_text_contract')); + for(const [kind,name] of [['hosted_html',item.artifacts?.html],['screenshot',item.artifacts?.screenshot]]) + if(name) files.push(artifact(output,name,kind)); + if(result.status!=='pass' || !capturePassed({...source,revision:args.revision},item)) + return {passed:false,result,artifacts:files}; + const receipt={schema_version:1,kind:'hosted_math_page',status:'pass',repository:args.repository, + revision:args.revision,tree:session.binding.tree,path:source.path,source_sha256:source.source_sha256, + viewport,key:pageKey(source.path,viewport),observed_at:item.observed_at,capture:item,artifacts:files}; + const filename=prefix+'-receipt.json';writeJSON(path.join(output,filename),receipt); + const descriptor={key:receipt.key,receipt:artifact(output,filename,'page_receipt')}; + session.completed.push(descriptor);session.updated_at=new Date().toISOString();saveSession(output,session); + return {passed:true,result,artifacts:[...files,descriptor.receipt],receipt}; +} +async function captureHostedPage(context, source, expected, prefix, output, readinessOptions={}) { + const page=await context.newPage(); + const item={path:source.path,url:source.url,revision:source.revision,source_sha256:source.source_sha256,errors:[],math:[]}; + try { + const response=await page.goto(source.url,{waitUntil:'domcontentloaded',timeout:60000}); + if(response?.status()!==200) throw new Error('HTTP '+response?.status()); + if(page.url()!==source.url) throw new Error('Browser redirected away from exact pinned source URL'); + const article=page.locator('article.markdown-body').first(); + await article.waitFor({state:'visible',timeout:30000}); + await page.evaluate(async()=>{ + for(let y=0,steps=0;ysetTimeout(r,50)); + } + window.scrollTo(0,0); + }); + await waitForHostedMath(article,expected.length,readinessOptions); + Object.assign(item,await article.evaluate(inspectArticle,expected)); + const html=prefix+'.html',png=prefix+'.png'; + fs.writeFileSync(path.join(output,html),await page.content()); + await page.screenshot({path:path.join(output,png),fullPage:true,timeout:30000}); + item.artifacts={html,screenshot:png}; + item.observed_at=new Date().toISOString(); + return item; + } finally {await page.close();} +} +async function defaultRuntime() { + const {chromium}=require('playwright'); + const runtime={node:process.version,playwright:require('playwright/package.json').version, + mathjax:require('mathjax-full/package.json').version}; + const compile=mathCompiler(),browser=await chromium.launch({headless:true}); + runtime.browser=browser.version();return {browser,compile,runtime}; +} +async function run(args, adapters={}) { + const output=path.resolve(args.output); + if(fs.existsSync(output) && (fs.lstatSync(output).isSymbolicLink() || fs.readdirSync(output).length)) + throw new Error('Use an empty output directory; preserve earlier failed evidence'); + fs.mkdirSync(output,{recursive:true}); + const pinned=pinnedPages(args),helper=path.join(__dirname,'check_rendered_math.py'); + cp.execFileSync(args.python,[helper,'inventory','--root',args.root,'--repository',args.repository, + '--revision',args.revision,...pinned.pages.flatMap(p=>['--page',p]),'--output',path.join(output,'math-source.json')],{stdio:'pipe'}); + const inventory=JSON.parse(fs.readFileSync(path.join(output,'math-source.json'),'utf8')); + const at=new Date().toISOString(),failures=[],artifacts=[artifact(output,'math-source.json','source_inventory')],viewports=[]; + const contractBytes=args.contract?fs.readFileSync(path.resolve(args.contract)):Buffer.from('null'); + const contract=args.contract?JSON.parse(contractBytes.toString('utf8')):null; + if(args.contract && (!contract || !Array.isArray(contract.expressions) || contract.schema_version!==1)) throw new Error('Invalid text contract'); + if(args.contract) { + fs.writeFileSync(path.join(output,'math-contract.json'),contractBytes); + artifacts.push(artifact(output,'math-contract.json','text_contract')); + } + let browser,session,runtime={},resume={reusable:new Map()},fatal=false; + const pageProvenance=[]; + try { + // A policy/access failure is detected from the durable state before a new browser is started. + if(args.resumeFrom) { + const prior=JSON.parse(fs.readFileSync(safeEvidenceFile(args.resumeFrom,'capture-state.json'),'utf8')); + if(!Array.isArray(prior.failures) || prior.failures.some(f=>f.category!=='transport_failure')) + throw new Error('Resume refused after a nontransient, policy or access failure'); + } + const loaded=await (adapters.loadRuntime || defaultRuntime)(); + browser=loaded.browser; + runtime={...loaded.runtime,python:cp.execFileSync(args.python,['-c','import sys; print(sys.version)'],{encoding:'utf8'}).trim()}; + const expected=Object.fromEntries(inventory.pages.map(p=>[p.path,p.expressions.map(e=>({...e, + mml:loaded.compile(e.tex,['math-fence','dollar-display'].includes(e.kind))}))])); + writeJSON(path.join(output,'expected-mathml.json'),expected); + artifacts.push(artifact(output,'expected-mathml.json','expected_mathml')); + session=newSession(sessionBinding(inventory,pinned.tree,fs.readFileSync(path.join(output,'expected-mathml.json')), + contractBytes,runtime,helper,args.diagnosticOnly===true,fs.readFileSync(path.join(output,'math-source.json'))),at); + if(args.resumeFrom) { + resume=loadResume(args.resumeFrom,session.binding,inventory); + session.previous_attempt=resume.previous_attempt; + } + saveSession(output,session); + for(const viewport of VIEWPORTS) { + const context=await browser.newContext({viewport,deviceScaleFactor:1,colorScheme:'light'}); + const capture={schema_version:1,repository:args.repository,revision:args.revision,renderer_profile:'github', + captured_at:at,capture_method:'playwright-github',pages:[]}; + try { + for(let index=0;indexp.observed_at).filter(Boolean).sort((a,b)=>Date.parse(a)-Date.parse(b)); + capture.captured_at=observed[0] || at; + const captureFile='math-capture-'+viewport.width+'.json',resultFile='math-result-'+viewport.width+'.json'; + writeJSON(path.join(output,captureFile),capture);artifacts.push(artifact(output,captureFile,'hosted_capture')); + const result=runTextCheck(args,helper,output,'math-source.json',captureFile,resultFile,args.contract?'math-contract.json':null); + artifacts.push(artifact(output,resultFile,'math_result')); + failures.push(...result.failures.map(f=>viewport.width+': '+f)); + const matches=capture.pages.reduce((n,p)=>n+p.math.filter(m=>m.structural_match && !m.errors.length).length,0); + viewports.push({...viewport,status:result.status,structural_matches:matches,capture_path:captureFile,result_path:resultFile,boundaries:result.boundaries}); + if(fatal) break; + } + } catch(error) { + const category=classifyFailure(error);failures.push(category+': '+String(error)); + if(session) { + session.failures.push({category,reason:String(error),observed_at:new Date().toISOString()}); + session.updated_at=new Date().toISOString();saveSession(output,session); + } + } finally {if(browser) await browser.close();} + if(session) artifacts.push(artifact(output,'capture-state.json','capture_session')); + const observations=pageProvenance.map(p=>p.observed_at).sort((a,b)=>Date.parse(a)-Date.parse(b)); + const report={...boundReport(inventory,pinned.tree,viewports,artifacts,failures,observations[0] || at),runtime, + report_assembled_at:new Date().toISOString(),page_provenance:pageProvenance,diagnostic_only:args.diagnosticOnly===true}; + if(session?.previous_attempt) report.previous_attempt=session.previous_attempt; + writeJSON(path.join(output,'hosted-report.json'),report); + console.log(JSON.stringify({status:report.status,report:path.join(output,'hosted-report.json'),sha256:sha256(fs.readFileSync(path.join(output,'hosted-report.json'))),pages:report.required_pages.length,failures:report.failures.length,reused_pages:pageProvenance.filter(p=>p.reused).length})); + return report.status==='pass'?0:1; +} +module.exports={argumentsFor,safePath,pinnedPages,mathCompiler,inspectArticle,hostedMathReadiness,waitForHostedMath,classifyFailure,artifact,boundReport,VIEWPORTS,run, + safeEvidenceFile,readBoundArtifact,observationTime,pageKey,capturePassed,sessionBinding,newSession,saveSession,loadResume, + runTextCheck,savePageReceipt,captureHostedPage,RESUME_MAX_AGE_MS,RENDER_TIMEOUT_MS}; +if(require.main===module) { + (async()=>{ + const args=argumentsFor(process.argv.slice(2)); + if(args.help) {console.log('capture_hosted_math.cjs --root REPO --repository owner/name --revision FULLSHA --output EMPTY_DIR [--page PATH ...] [--contract JSON] [--python python3] [--resume-from PRIOR_EVIDENCE_DIR]');return;} + process.exitCode=await run(args); + })().catch(error=>{console.error(String(error));process.exitCode=2;}); +} diff --git a/verification/hosted_math/check_rendered_math.py b/verification/hosted_math/check_rendered_math.py new file mode 100644 index 0000000..1d3bf98 --- /dev/null +++ b/verification/hosted_math/check_rendered_math.py @@ -0,0 +1,370 @@ +#!/usr/bin/env python3 +r"""Check captured mathematical text against pinned GitHub Markdown source. + +Usage (Python 3.10+, standard library only): + check_rendered_math.py inventory --root REPO --repository owner/name \ + --revision FULL_COMMIT --page README.md --page science/results.md \ + --output math-source.json + check_rendered_math.py check --inventory math-source.json \ + --capture math-capture.json [--contract math-contract.json] [--output result.json] + +Inventory reads Git objects at the requested commit, not the working tree. +It recognizes math fences, $`...`$, $$...$$ and single-dollar inline math, +excluding ordinary code fences/spans. This is a bounded Markdown scanner, +not the hosting renderer's parser. Inspect its inventory before capture. + +Capture schema (collect actual full accessible math text in document order): + {"schema_version": 1, "repository": "owner/name", "revision": "40 hex", + "renderer_profile": "github", "captured_at": "ISO-8601 with timezone", + "capture_method": "how the actual hosted DOM was inspected", + "pages": [{"path": "README.md", "url": "exact pinned inventory URL", + "revision": "40 hex", "source_sha256": "inventory source hash", + "errors": [], "math": [{"rendered": true, "errors": [], + "text_source": "mathml", "text": "full text, not a sample"}]}]} +Allowed text_source values: mathml, mathjax-assistive, katex-accessibility, +renderer-accessibility. Extract one accessible representation per host; +exclude TeX annotation nodes and duplicate visual/accessibility copies. +Native MathML is valid. Empty math lists are valid for math-free pages. + +Optional contract strengthens content checks without pretending to translate +arbitrary TeX. Each entry selects a path/index (1-based) and source_sha256 +(the expression hash in inventory), with expected_text and/or required_text: + {"schema_version": 1, "expressions": [{"path": "README.md", "index": 1, + "source_sha256": "expression hash", "required_text": ["d", "(C1)"], + "expected_text": "|A|", "le": "≤", "leq": "≤", "ge": "≥", "geq": "≥", + "ne": "≠", "neq": "≠", "in": "∈", "notin": "∉", "subset": "⊂", + "subseteq": "⊆", "supset": "⊃", "supseteq": "⊇", "approx": "≈", + "simeq": "≃", "equiv": "≡", "propto": "∝", "cong": "≅", "sim": "∼", + "to": "→", "rightarrow": "→", "Rightarrow": "⇒", "implies": "⇒", + "mapsto": "↦", "leftrightarrow": "↔", "Leftrightarrow": "⇔", "iff": "⇔", +} +RELATION_SYMBOLS = set("<>=") | set(RELATIONS.values()) +COMMAND = re.compile(r"\\([A-Za-z]+)") +LABEL = re.compile(r"\\tag(\*)?\{([^{}]+)\}|\\text\{\s*\(([^{}()]+)\)\s*\}") +FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})([^\n]*)\n?$") +SHA = re.compile(r"[0-9a-f]{40}") +TEXT_SOURCES = {"mathml", "mathjax-assistive", "katex-accessibility", "renderer-accessibility"} + + +def digest(text: str) -> str: + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +def compact(text: str) -> str: + return "".join(c for c in unicodedata.normalize("NFKC", text) + if not c.isspace() and unicodedata.category(c) != "Cf") + + +def escaped(text: str, index: int) -> bool: + backslashes = 0 + while index > 0 and text[index - 1] == "\\": + backslashes += 1 + index -= 1 + return bool(backslashes % 2) + + +def tex_body(text: str) -> str: + """Drop unescaped TeX comments; do not expand user macros.""" + return "\n".join(line[:next((i for i, c in enumerate(line) + if c == "%" and not escaped(line, i)), len(line))] + for line in text.splitlines()) + + +def relations(tex: str) -> dict[str, int]: + expanded = COMMAND.sub(lambda m: RELATIONS.get(m.group(1), m.group(0)), tex_body(tex)) + return dict(sorted(Counter(c for c in expanded if c in RELATION_SYMBOLS).items())) + + +def labels(tex: str) -> list[str]: + return [compact(tag if star else f"({tag or text})") + for star, tag, text in LABEL.findall(tex_body(tex))] + + +def expressions(source: str) -> list[dict]: + """Return ordered source spans; reject unterminated recognized delimiters.""" + found: list[dict] = [] + + def add(tex: str, offset: int, end: int, kind: str) -> None: + found.append({"line_start": source.count("\n", 0, offset) + 1, + "line_end": source.count("\n", 0, end) + 1, + "kind": kind, "tex": tex, "source_sha256": digest(tex), + "relations": relations(tex), "labels": labels(tex)}) + + def prose(start: int, end: int) -> None: + i = start + while i < end: + if source[i] == "$" and not escaped(source, i): + opener, closer, kind = ("$`", "`$", "github-inline") if source.startswith("$`", i) else ( + ("$$", "$$", "dollar-display") if source.startswith("$$", i) + else ("$", "$", "dollar-inline")) + j = source.find(closer, i + len(opener), end) + while j >= 0 and escaped(source, j): + j = source.find(closer, j + len(closer), end) + if j < 0 or (kind == "dollar-inline" and "\n" in source[i:j]): + raise ValueError(f"unclosed {kind} at line {source.count(chr(10), 0, i) + 1}") + add(source[i + len(opener):j], i, j + len(closer) - 1, kind) + i = j + len(closer) + elif source[i] == "`" and not escaped(source, i): + n = 1 + while i + n < end and source[i + n] == "`": + n += 1 + j = source.find("`" * n, i + n, end) + i = j + n if j >= 0 else i + n + else: + i += 1 + + lines = source.splitlines(keepends=True) + offset = start = i = 0 + while i < len(lines): + match = FENCE.match(lines[i]) + if not match: + offset += len(lines[i]) + i += 1 + continue + prose(start, offset) + marker, info = match.groups() + begin = offset + offset += len(lines[i]) + body_start = offset + i += 1 + while i < len(lines): + closing = FENCE.match(lines[i]) + if closing and closing[1][0] == marker[0] and len(closing[1]) >= len(marker) and not closing[2].strip(): + break + offset += len(lines[i]) + i += 1 + if i == len(lines): + raise ValueError(f"unclosed code fence at line {source.count(chr(10), 0, begin) + 1}") + if info.strip() == "math": + add(source[body_start:offset], begin, offset, "math-fence") + offset += len(lines[i]) + i += 1 + start = offset + prose(start, len(source)) + for index, item in enumerate(found, 1): + item["index"] = index + return found + + +def safe_path(path: str) -> bool: + return isinstance(path, str) and bool(path) and "\\" not in path and not PurePosixPath(path).is_absolute() and all( + part not in {"", ".", ".."} for part in path.split("/")) + + +def make_inventory(repository: str, revision: str, sources: dict[str, str]) -> dict: + if not isinstance(repository, str) or not isinstance(revision, str) or not re.fullmatch( + r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository) or not SHA.fullmatch(revision): + raise ValueError("use owner/name and an exact lowercase 40-character commit SHA") + if not isinstance(sources, dict) or not sources or not all( + safe_path(p) and isinstance(s, str) for p, s in sources.items()): + raise ValueError("supply at least one safe repository-relative page path") + return {"schema_version": 1, "repository": repository, "revision": revision, + "renderer_profile": "github", "pages": [ + {"path": path, "url": f"https://github.com/{repository}/blob/{revision}/{quote(path, safe='/')}", + "source_sha256": digest(source), "source_text": source, "expressions": expressions(source)} + for path, source in sources.items()]} + + +def validate(inventory: dict, capture: dict, contract: dict | None = None) -> dict: + """Return failures rather than equating a passing text check with readiness.""" + failures: list[str] = [] + boundaries: list[dict] = [] + exceptions: list[dict] = [] + if not isinstance(inventory, dict) or not isinstance(capture, dict): + raise ValueError("inventory and capture must be JSON objects") + if type(inventory.get("schema_version")) is not int or type(capture.get("schema_version")) is not int or inventory["schema_version"] != 1 or capture["schema_version"] != 1: + raise ValueError("unsupported inventory or capture schema_version") + pages = inventory.get("pages") + if not isinstance(pages, list) or not pages or any(not isinstance(p, dict) for p in pages): + raise ValueError("inventory needs a nonempty pages array") + paths = [p.get("path") for p in pages] + if any(not isinstance(p, str) for p in paths) or len(set(paths)) != len(paths): + raise ValueError("inventory page paths must be unique strings") + rebuilt = make_inventory(inventory.get("repository", ""), inventory.get("revision", ""), + {p["path"]: p["source_text"] for p in pages}) + if inventory != rebuilt: + raise ValueError("inventory does not match its embedded source bytes/expression inventory") + for field in ("repository", "revision", "renderer_profile"): + if capture.get(field) != inventory[field]: + failures.append(f"capture {field} mismatch") + try: + timestamp = datetime.fromisoformat(capture.get("captured_at", "").replace("Z", "+00:00")) + if timestamp.tzinfo is None: + raise ValueError() + except (ValueError, AttributeError, TypeError): + failures.append("capture needs captured_at with a timezone") + if not isinstance(capture.get("capture_method"), str) or not capture["capture_method"].strip(): + failures.append("capture needs a nonempty capture_method") + captured_pages = capture.get("pages") + if not isinstance(captured_pages, list) or any(not isinstance(p, dict) for p in captured_pages): + raise ValueError("capture pages must be an array of objects") + captured_paths = [p.get("path") for p in captured_pages] + if captured_paths != paths: + failures.append("capture page paths/order differ from inventory (missing, extra or duplicate page)") + + contract = {"schema_version": 1, "expressions": []} if contract is None else contract + if not isinstance(contract, dict) or type(contract.get("schema_version")) is not int or contract["schema_version"] != 1 or not isinstance(contract.get("expressions"), list): + raise ValueError("invalid text contract schema") + rules: dict[tuple, dict] = {} + known = {(p["path"], e["index"]): e for p in pages for e in p["expressions"]} + for rule in contract["expressions"]: + if not isinstance(rule, dict): + raise ValueError("contract expressions must be objects") + key = (rule.get("path"), rule.get("index")) + if not isinstance(key[0], str) or type(key[1]) is not int or key not in known or key in rules or rule.get("source_sha256") != known[key]["source_sha256"]: + raise ValueError("unknown, duplicate or stale expression contract") + allowed = {"path", "index", "source_sha256", "required_text", "expected_text", "relation_override", + "allow_html_like_inequality", "reason", "evidence"} + if set(rule) - allowed: + raise ValueError("unknown contract field (contracts cannot skip checks)") + if "expected_text" in rule and (not isinstance(rule["expected_text"], str) or not compact(rule["expected_text"])): + raise ValueError("expected_text must be nonempty text") + if not isinstance(rule.get("required_text", []), list) or any( + not isinstance(v, str) or not compact(v) for v in rule.get("required_text", [])): + raise ValueError("required_text must be an array of nonempty text") + if "expected_text" not in rule and not rule.get("required_text"): + raise ValueError("each expression contract needs expected_text or required_text") + if "allow_html_like_inequality" in rule and not isinstance(rule["allow_html_like_inequality"], bool): + raise ValueError("allow_html_like_inequality must be boolean") + if "relation_override" in rule: + override = rule["relation_override"] + if not isinstance(override, dict) or any(k not in RELATION_SYMBOLS or type(v) is not int or v < 0 + for k, v in override.items()): + raise ValueError("relation_override must map known symbols to nonnegative integer counts") + if "relation_override" in rule or rule.get("allow_html_like_inequality"): + if not all(isinstance(rule.get(k), str) and rule[k].strip() for k in ("expected_text", "reason", "evidence")): + raise ValueError("renderer exception requires expected_text, reason and evidence") + exceptions.append(rule) + rules[key] = rule + + by_path = {p.get("path"): p for p in captured_pages if isinstance(p.get("path"), str)} + checked = 0 + for page in pages: + path = page["path"] + current = by_path.get(path) + if current is None: + continue + boundaries.append({"path": path, "source_sha256": page["source_sha256"], "url": current.get("url"), + "revision": current.get("revision"), "source_expressions": len(page["expressions"]), + "source_spans": [{k: e[k] for k in ("index", "line_start", "line_end", "source_sha256")} + for e in page["expressions"]]}) + for field, expected in (("url", page["url"]), ("revision", inventory["revision"]), ("source_sha256", page["source_sha256"])): + if current.get(field) != expected: + failures.append(f"{path}: captured {field} mismatch") + if current.get("errors") != []: + failures.append(f"{path}: renderer errors present or error evidence missing") + hosts = current.get("math") + if not isinstance(hosts, list): + failures.append(f"{path}: missing math-host array") + continue + boundaries[-1]["captured_hosts"] = len(hosts) + if len(hosts) != len(page["expressions"]): + failures.append(f"{path}: {len(page['expressions'])} source expressions, {len(hosts)} captured hosts") + for expr, host in zip(page["expressions"], hosts): + label = f"{path}:{expr['line_start']} expression {expr['index']}" + rule = rules.get((path, expr["index"]), {}) + if not isinstance(host, dict) or host.get("rendered") is not True or host.get("errors") != []: + failures.append(f"{label}: missing/unrendered host or renderer-error evidence") + continue + if host.get("text_source") not in TEXT_SOURCES or not isinstance(host.get("text"), str) or not compact(host["text"]): + failures.append(f"{label}: missing full accessible mathematical text/source") + continue + checked += 1 + text = compact(host["text"]) + expected = {k: v for k, v in rule.get("relation_override", expr["relations"]).items() if v} + actual = dict(sorted(Counter(c for c in text if c in RELATION_SYMBOLS).items())) + if expected != actual: + failures.append(f"{label}: relation mismatch; expected {expected}, captured {actual}") + for equation_label in expr["labels"]: + if equation_label not in text: + failures.append(f"{label}: missing equation label {equation_label}") + if re.search(r"<\s*[A-Za-z]", tex_body(expr["tex"])) and not rule.get("allow_html_like_inequality"): + failures.append(f"{label}: GitHub HTML-like inequality hazard; use supported syntax or a traced exact-text exception") + if "expected_text" in rule and compact(rule["expected_text"]) != text: + failures.append(f"{label}: full expected_text mismatch") + for required in rule.get("required_text", []): + if compact(required) not in text: + failures.append(f"{label}: missing required_text {required!r}") + return {"schema_version": 1, "status": "fail" if failures else "pass", + "repository": inventory["repository"], "revision": inventory["revision"], + "renderer_profile": inventory["renderer_profile"], "captured_at": capture.get("captured_at"), + "capture_method": capture.get("capture_method"), "boundaries": boundaries, + "expressions_checked": checked, "text_contracts": len(rules), "renderer_exceptions": exceptions, + "failures": failures, "visual_review_required": True, + "limits": "Counts, supported relations/visible labels and explicit text contracts only. No arbitrary TeX equivalence, scientific correctness, capture authentication or visual-layout certification."} + + +def read_json(path: Path) -> dict: + return json.loads(path.read_text(encoding="utf-8")) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + commands = parser.add_subparsers(dest="command", required=True) + inv = commands.add_parser("inventory", help="read math source from an exact local Git commit") + inv.add_argument("--root", type=Path, required=True) + inv.add_argument("--repository", required=True) + inv.add_argument("--revision", required=True) + inv.add_argument("--page", action="append", required=True) + inv.add_argument("--output", type=Path, required=True) + check = commands.add_parser("check", help="check pinned extracted capture; does not fetch or render") + check.add_argument("--inventory", type=Path, required=True) + check.add_argument("--capture", type=Path, required=True) + check.add_argument("--contract", type=Path) + check.add_argument("--output", type=Path) + args = parser.parse_args(argv) + try: + if args.command == "inventory": + if not SHA.fullmatch(args.revision) or len(set(args.page)) != len(args.page) or not all(safe_path(p) for p in args.page): + raise ValueError("use an exact commit SHA and unique safe page paths") + commit = subprocess.check_output(["git", "--no-replace-objects", "rev-parse", f"{args.revision}^{{commit}}"], cwd=args.root, text=True).strip() + if commit != args.revision: + raise ValueError("revision does not identify the supplied commit") + sources = {p: subprocess.check_output(["git", "--no-replace-objects", "show", f"{commit}:{p}"], cwd=args.root).decode("utf-8") for p in args.page} + result = make_inventory(args.repository, commit, sources) + else: + result = validate(read_json(args.inventory), read_json(args.capture), read_json(args.contract) if args.contract else None) + output = json.dumps(result, indent=2, ensure_ascii=False) + "\n" + if args.output: + args.output.write_text(output, encoding="utf-8") + else: + print(output, end="") + return 1 if result.get("status") == "fail" else 0 + except (OSError, UnicodeError, ValueError, KeyError, TypeError, subprocess.CalledProcessError) as error: + print(f"ERROR: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) From 02347f2ef57fa25e10bbb817910b7e93c7eb8e1d Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Fri, 13 Nov 2026 19:48:05 +0800 Subject: [PATCH 3/4] Repair demonstrated GitHub math macros, norm glyphs and storage diagram --- README.md | 2 +- learning/WATROUS_BRIDGE.md | 4 ++-- learning/WORKED_EXAMPLE.md | 16 +++++++++------- science/classical_boundary.md | 2 +- science/control_structure.md | 8 ++++---- science/examples.md | 2 +- science/memory_law.md | 6 +++--- science/model.md | 4 ++-- 8 files changed, 23 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 5d92ea0..595a829 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Use the established stabilized control decomposition ```math \mathcal H_E=\bigoplus_j\mathcal H_{B_j}\otimes\mathcal H_{Q_j}, -\qquad r_j=\dim Q_j,\qquad p_j=\operatorname{Tr}(\Pi_j\tau_E). +\qquad r_j=\dim Q_j,\qquad p_j=\mathrm{Tr}(\Pi_j\tau_E). ``` Here j is a conserved sector, its Q factor is controllable through the laboratory port, and its B factor is invisible to future port experiments. This structure is inherited from Kato–Owari–Maruyama; the quantum/classical decomposition and general memory-cost frameworks also have established antecedents. The [related-work account](references/related_work.md) identifies them. diff --git a/learning/WATROUS_BRIDGE.md b/learning/WATROUS_BRIDGE.md index 8e0f9b6..d9fffe0 100644 --- a/learning/WATROUS_BRIDGE.md +++ b/learning/WATROUS_BRIDGE.md @@ -38,7 +38,7 @@ The book's registers and channels can represent every item in one finite experim For a working register $`W`$, a reset to a fixed state $`\omega_W`$ is ```math -\mathcal R_W(X)=\operatorname{Tr}(X)\,\omega_W. +\mathcal R_W(X)=\mathrm{Tr}(X)\,\omega_W. ``` When applied to part of a joint state, it discards that register and prepares a replacement independent of the rest. Keeping a purification in another accessible work register would defeat this reset. The distinguishing experiment therefore erases **all** accessible quantum work systems, not just the port. The sealed reference survives, but cannot interact with any controller across the cut. @@ -56,7 +56,7 @@ Watrous uses the unsquared, or root, fidelity convention. For this pure target t ### The distance includes a factor of one half -The project's state-distance convention is $`\tfrac12\|\rho-\sigma\|_1`$. Its one-channel analogue is half the completely bounded trace norm from Section 3.3.2, commonly called the diamond norm. A process has several intervention slots, so [the model](../science/model.md#distance-and-order-of-quantifiers) optimizes distinguishability over finite causal experiments rather than replacing the whole process by one passive channel snapshot. +The project's state-distance convention is $`\tfrac12\lVert \rho-\sigma\rVert_1`$. Its one-channel analogue is half the completely bounded trace norm from Section 3.3.2, commonly called the diamond norm. A process has several intervention slots, so [the model](../science/model.md#distance-and-order-of-quantifiers) optimizes distinguishability over finite causal experiments rather than replacing the whole process by one passive channel snapshot. The normalized Bell projector used in a test has trace one. Under the usual unnormalized Choi convention, the Choi operator of a qubit identity channel is twice that projector. This normalization changes neither the physical channel nor the test, but it matters when reading formulas. diff --git a/learning/WORKED_EXAMPLE.md b/learning/WORKED_EXAMPLE.md index 01445f0..62509b5 100644 --- a/learning/WORKED_EXAMPLE.md +++ b/learning/WORKED_EXAMPLE.md @@ -34,13 +34,15 @@ The reference is now sealed. It has no interaction with the port, the bath or a Write $`\Phi_{RS}=|\Phi_2\rangle\langle\Phi_2|_{RS}`$. The three relevant stages are ```math -\Phi_{RS}\otimes\tau_E -\ \xrightarrow{\text{write SWAP}}\ -\Phi_{RE}\otimes\tau_S -\ \xrightarrow{\text{reset }S}\ -\Phi_{RE}\otimes|0\rangle\langle0|_S -\ \xrightarrow{\text{read SWAP}}\ -\Phi_{RS}\otimes|0\rangle\langle0|_E. +\begin{aligned} +&\Phi_{RS}\otimes\tau_E\\ +&\quad\overset{\text{write SWAP}}{\rightarrow} + \Phi_{RE}\otimes\tau_S\\ +&\quad\overset{\text{reset }S}{\rightarrow} + \Phi_{RE}\otimes|0\rangle\langle0|_S\\ +&\quad\overset{\text{read SWAP}}{\rightarrow} + \Phi_{RS}\otimes|0\rangle\langle0|_E. +\end{aligned} ``` Each SWAP takes idle duration $`t_*`$. The middle intervention discards the port and prepares it in $`|0\rangle`$. Any additional accessible working or controller qubits would be discarded too. In this simple device none are needed. The reference is the only surviving laboratory quantum system, and its seal prevents a bypass. diff --git a/science/classical_boundary.md b/science/classical_boundary.md index 048cda2..602d3fb 100644 --- a/science/classical_boundary.md +++ b/science/classical_boundary.md @@ -79,7 +79,7 @@ The proof is a connection to the inherited indirect-control decomposition. It do ## Finite-time caution -A positive value of $`\epsilon_1^\infty`$ says that an arbitrarily accurate classical explanation fails uniformly over unlimited finite experiments. It does not say that a short experiment can distinguish that explanation. If $`H_\lambda=H_0+\lambda V`$, then standard unitary telescoping bounds any tester of total idle duration $`T`$ by a discrepancy at most $`|\lambda|T\|V\|`$ when $`H_0`$ is used as a stand-in. This bound also covers adaptive interventions by contractivity and summing their branchwise elapsed durations under a hard horizon. +A positive value of $`\epsilon_1^\infty`$ says that an arbitrarily accurate classical explanation fails uniformly over unlimited finite experiments. It does not say that a short experiment can distinguish that explanation. If $`H_\lambda=H_0+\lambda V`$, then standard unitary telescoping bounds any tester of total idle duration $`T`$ by a discrepancy at most $`|\lambda|T\lVert V\rVert`$ when $`H_0`$ is used as a stand-in. This bound also covers adaptive interventions by contractivity and summing their branchwise elapsed durations under a hard horizon. Consequently the limits of weak coupling and long observation need not commute. The [memory law](memory_law.md) preserves that distinction: its horizon statement is a limit without a universal convergence rate. diff --git a/science/control_structure.md b/science/control_structure.md index ac7b3f6..67108a6 100644 --- a/science/control_structure.md +++ b/science/control_structure.md @@ -9,7 +9,7 @@ The bath decomposition in this project is inherited from Kato, Owari and Maruyam Order the physical Hilbert space as $`E\otimes\bar S`$, with $`d=\dim\bar S\ge3`$. Let ```math -\mathfrak L=\operatorname{Lie}_{\mathbb R} +\mathfrak L=\mathrm{Lie}_{\mathbb R} \left(iH_{E\bar S},\ I_E\otimes\mathfrak{su}(d)\right), ``` @@ -55,12 +55,12 @@ Scalar phases can be allocated between the terms without changing the process. T ```math \tau_{Q_j} -=p_j^{-1}\operatorname{Tr}_{B_j}(\Pi_j\tau_E\Pi_j) +=p_j^{-1}\mathrm{Tr}_{B_j}(\Pi_j\tau_E\Pi_j) ``` when $`p_j>0`$, and evolve $`Q_j\bar S`$ with $`K_j`$. Tracing out $`B_j`$ at the beginning is valid even if it is initially correlated with $`Q_j`$: its subsequent unitary acts on $`B_j`$ alone. Off-diagonal $`j`$ blocks never contribute after the final bath trace. This proves the exact simulator used in the upper bound. -The stabilization qubit remains an actual laboratory system, not an extra simulator port. To see this explicitly, when $`\bar S=S\otimes Z`$ the physical drift is $`H_{ES}\otimes I_Z`$. Set $`\widehat K_j=(\dim Z)^{-1}\operatorname{Tr}_ZK_j`$. Taking that normalized partial trace in the drift decomposition, tensoring back with $`I_Z`$, and subtracting the original equality gives +The stabilization qubit remains an actual laboratory system, not an extra simulator port. To see this explicitly, when $`\bar S=S\otimes Z`$ the physical drift is $`H_{ES}\otimes I_Z`$. Set $`\widehat K_j=(\dim Z)^{-1}\mathrm{Tr}_ZK_j`$. Taking that normalized partial trace in the drift decomposition, tensoring back with $`I_Z`$, and subtracting the original equality gives ```math K_j=\widehat K_j\otimes I_Z. @@ -94,7 +94,7 @@ No bath measurement is supplied for free. This is an indirect operation compiled On a known sector $`j`$, append an $`r_j`$-dimensional payload $`L`$. Independent full connected control on $`Q_j\bar SL`$ supplies ```math -W_j=\operatorname{SWAP}_{Q_j,L}\otimes I_{\bar S}, +W_j=\mathrm{SWAP}_{Q_j,L}\otimes I_{\bar S}, ``` again up to an irrelevant phase and arbitrarily small finite compilation error. Controls on other sectors may be chosen arbitrarily. If a common fixed laboratory dimension is desired, embed each payload in an $`r_j`$-dimensional subspace of a register of dimension $`\max_jr_j`$ and extend the indicated SWAP unitarily on its complement. diff --git a/science/examples.md b/science/examples.md index b92cc8f..f62a578 100644 --- a/science/examples.md +++ b/science/examples.md @@ -29,7 +29,7 @@ Even an initially pure state in the four-level factor still requires four levels Let the accessible port be a qutrit and the bath one qubit. In units with the longitudinal coupling equal to one, set ```math -C=\operatorname{diag}(-1,0,1),\qquad +C=\mathrm{diag}(-1,0,1),\qquad H_g=C\otimes Z+g I_3\otimes X, ``` diff --git a/science/memory_law.md b/science/memory_law.md index 718e700..48ca9a3 100644 --- a/science/memory_law.md +++ b/science/memory_law.md @@ -50,12 +50,12 @@ Prepare $`|\Phi_r\rangle_{RL}=r^{-1/2}\sum_{a=1}^r|a\rangle_R|a\rangle_L`$, with \Pr[\Phi_r\text{ on }RL']\le\min\{1,D/r\}. ``` -To prove this, condition on any classical branch at the cut. Every state on $`R\otimes M_D`$ has Schmidt number at most $`D`$. Local decoding and discarding systems cannot increase that Schmidt number. For a normalized pure output of Schmidt rank $`k\le D`$, write its coefficient matrix as $`Y`$, with $`\|Y\|_2=1`$. Then +To prove this, condition on any classical branch at the cut. Every state on $`R\otimes M_D`$ has Schmidt number at most $`D`$. Local decoding and discarding systems cannot increase that Schmidt number. For a normalized pure output of Schmidt rank $`k\le D`$, write its coefficient matrix as $`Y`$, with $`\lVert Y\rVert_2=1`$. Then ```math |\langle\Phi_r|\psi\rangle|^2 -=\frac{|\operatorname{Tr}Y|^2}{r} -\le\frac{\|Y\|_1^2}{r} +=\frac{|\mathrm{Tr}Y|^2}{r} +\le\frac{\lVert Y\rVert_1^2}{r} \le\frac{k}{r}\le\frac Dr. ``` diff --git a/science/model.md b/science/model.md index 5cca625..3352499 100644 --- a/science/model.md +++ b/science/model.md @@ -37,7 +37,7 @@ Here $`B_j`$ is an invisible multiplicity factor, $`Q_j`$ is an indirectly contr Let $`\Pi_j`$ project onto sector $`j`$, and define ```math -p_j=\operatorname{Tr}(\Pi_j\tau_E),\qquad +p_j=\mathrm{Tr}(\Pi_j\tau_E),\qquad q_D=\sum_{j:r_j>D}p_j,\qquad D\in\mathbb N,\ D\ge1. ``` @@ -60,7 +60,7 @@ A tester $`\mathsf T`$ specifies a finite causal laboratory experiment and a fin ```math d_\infty(P_{H,\tau},\mathsf M) =\sup_{\mathsf T\ \mathrm{finite}} - \operatorname{TV}\!\left( + \mathrm{TV}\!\left( p_{\mathsf T[P_{H,\tau}]},p_{\mathsf T[\mathsf M]}\right), ``` From 4f6121dd0fcda97a27554d684251816ad98c239d Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Fri, 13 Nov 2026 19:50:49 +0800 Subject: [PATCH 4/4] Clarify omitted-sector probability cost in the headline table --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 595a829..23f5722 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ The error uses half operational distance and is uniform over arbitrarily long ** | Consequence | Meaning | | --- | --- | -| Exact tail of sector probabilities | Small quantum sectors may be omitted at their total probability cost; a smaller coherent carrier cannot improve the unrestricted-time error. | +| Exact tail of sector probabilities | Omitted sectors cost their total probability; a smaller coherent carrier cannot improve the unrestricted-time error. | | Exact classical-memory boundary | Classical persistent memory suffices precisely when every occupied active factor is one-dimensional, even allowing invasive classical feedforward. | | Finite repeated witness | A sector flag followed by store–reset–retrieve Bell tests gives a lower bound approaching the tail, against every dimension-limited emulator. | | Finite-horizon limit | The optimal horizon-specific error tends to the same tail as duration grows; no universal convergence rate is claimed. |