From e10b69cbf7249ce945f5ea24e32aefc2d11b6805 Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Sun, 15 Nov 2026 22:54:51 +0800 Subject: [PATCH 1/5] Add Watrous learning route and read-only hosted mathematics checks --- .github/workflows/hosted-math.yml | 52 ++ README.md | 4 + learning/MILESTONES.md | 286 +++++++++ learning/README.md | 54 ++ learning/WATROUS_BRIDGE.md | 136 +++++ llms.txt | 1 + references/references.bib | 8 + verification/README.md | 12 + verification/hosted-contract.json | 35 ++ .../hosted-tools/capture_hosted_math.cjs | 549 ++++++++++++++++++ .../hosted-tools/check_rendered_math.py | 370 ++++++++++++ 11 files changed, 1507 insertions(+) create mode 100644 .github/workflows/hosted-math.yml create mode 100644 learning/MILESTONES.md create mode 100644 learning/README.md create mode 100644 learning/WATROUS_BRIDGE.md create mode 100644 verification/hosted-contract.json create mode 100644 verification/hosted-tools/capture_hosted_math.cjs create mode 100644 verification/hosted-tools/check_rendered_math.py diff --git a/.github/workflows/hosted-math.yml b/.github/workflows/hosted-math.yml new file mode 100644 index 0000000..8168c43 --- /dev/null +++ b/.github/workflows/hosted-math.yml @@ -0,0 +1,52 @@ +name: Hosted mathematics + +on: + pull_request: + types: [opened, synchronize, reopened] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: hosted-math-${{ github.ref }} + cancel-in-progress: true + +jobs: + capture: + runs-on: ubuntu-24.04 + timeout-minutes: 30 + env: + SOURCE_REVISION: ${{ github.event.pull_request.head.sha || github.sha }} + steps: + - name: Check out the exact source + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + ref: ${{ env.SOURCE_REVISION }} + persist-credentials: false + - name: Prepare Node + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 + with: + node-version: '20' + - name: Install isolated capture dependencies + run: | + npm install --prefix "$RUNNER_TEMP/hosted-dependencies" playwright@1.56.1 mathjax-full@3.2.1 + "$RUNNER_TEMP/hosted-dependencies/node_modules/.bin/playwright" install --with-deps chromium + - name: Capture actual pinned GitHub pages + env: + NODE_PATH: ${{ runner.temp }}/hosted-dependencies/node_modules + run: | + node verification/hosted-tools/capture_hosted_math.cjs \ + --root "$GITHUB_WORKSPACE" \ + --repository "$GITHUB_REPOSITORY" \ + --revision "$SOURCE_REVISION" \ + --contract verification/hosted-contract.json \ + --output "$RUNNER_TEMP/hosted-evidence" + - name: Retain reports and screenshots + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: hosted-math-${{ env.SOURCE_REVISION }} + path: ${{ runner.temp }}/hosted-evidence + if-no-files-found: warn + retention-days: 7 diff --git a/README.md b/README.md index c4d54e6..dc4fb0e 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,10 @@ With the additional promise of a known depolarizing probability below one, the s The [science guide](science/README.md) connects the proof dependencies, and [llms.txt](llms.txt) maps reader intentions to the same authoritative files. +## Learn the project + +The [learning guide](learning/README.md) starts from a physical channel and follows the mechanism to the dimension frontier. Its single educational anchor is John Watrous, *The Theory of Quantum Information* (2018). The [source bridge](learning/WATROUS_BRIDGE.md) translates the book’s conventions and identifies the research ingredients supplied here. The [30-milestone map](learning/MILESTONES.md) connects background objects to the complete contribution; it is a common understanding map rather than a record of a reader’s progress. + ## Reproduce the finite checks ```bash diff --git a/learning/MILESTONES.md b/learning/MILESTONES.md new file mode 100644 index 0000000..b5daaf7 --- /dev/null +++ b/learning/MILESTONES.md @@ -0,0 +1,286 @@ +# Thirty milestones for Quantum Channel Coherentization + +This is a common understanding map for the scientific contribution. It has exactly 30 milestones: **12 background/preliminary milestones** and **18 narrative/innovation milestones**. The background joins channel theory, matrix representations, coherent operations and error measures into one input-output problem. The narrative builds the compiler, derives its cost, reconstructs the inversion obstruction, and then integrates the scope and significance of the result. Each phase moves from local objects to a global account. + +The sole educational anchor is John Watrous, *The Theory of Quantum Information* (2018), abbreviated **[W]**. The [Watrous bridge](WATROUS_BRIDGE.md) explains the relevant sections, notation translations and locally supplied steps. Sections cited below refer to that edition; they are entry points, not a requirement to read whole chapters. Niwa et al. (**[N]**), Gilyén et al. (**[G]**) and Chen–Yu–Zhang (**[C]**) are primary research dependencies, not additional educational anchors. The local proofs remain the authoritative statements of this project's assumptions and claims. + +The map records understanding targets and dependencies. It contains no learner assessments or personal coaching procedure, and does not claim to cover every technical lemma or neighboring problem. + +## Background and preliminaries — M01–M12 + +### M01 — States, vectors and linear operators + +- **ID and phase:** M01; background/preliminaries. +- **Central question:** What mathematical objects describe a quantum input and an operation acting on it? +- **Understanding target:** Distinguish a state vector, a density operator and a linear map on operators; explain why a coherent matrix algorithm acts on vectors even when its matrix originated from a channel. +- **Dependencies and story role:** No earlier milestone; establishes the objects that the rest of the map connects. +- **Conceptual connection:** Separating these object types prevents confusing a physical channel output with a vectorized operator. +- **Source pointers:** [W] §§1.1, 2.1; [model: fixed basis and vectorization](../science/model.md#fixed-basis-and-vectorization). + +### M02 — An ordinary call to an unknown channel + +- **ID and phase:** M02; background/preliminaries. +- **Central question:** What does black-box access to a physical channel actually supply? +- **Understanding target:** Explain complete positivity, trace preservation and a memoryless ordinary invocation; distinguish that invocation from supplied Kraus operators, a reversible dilation, a controlled channel or environmental access. +- **Dependencies and story role:** M01; turns the mathematical map into the concrete resource available to the compiler. +- **Conceptual connection:** A representation can describe a channel without being an accessible quantum oracle for that representation. +- **Source pointers:** [W] §2.2; [model: access and charged resources](../science/model.md#access-and-charged-resources). + +### M03 — Composite data and untouched references + +- **ID and phase:** M03; background/preliminaries. +- **Central question:** Why must the compiled operation work when its input is entangled with another register? +- **Understanding target:** Explain tensor-product registers, reduced states and discarding; identify which register carries the requested output and which registers may be consumed or ignored. +- **Dependencies and story role:** M01–M02; expands a single input-output operation into the setting needed for a composable guarantee. +- **Conceptual connection:** Partial trace is a permitted physical operation, while a guarantee for one input does not imply a guarantee on reference-entangled data. +- **Source pointers:** [W] §§2.1, 2.1.3, 2.2; [model: target evolution](../science/model.md#target-evolution-and-normalization), [error convention](../science/model.md#error-convention). + +### M04 — The Liouville matrix and its basis convention + +- **ID and phase:** M04; background/preliminaries. +- **Central question:** How does a map on operators become a matrix acting on vectors? +- **Understanding target:** Use the stated vectorization convention to explain the Liouville matrix and derive the unitary-channel form $`U\otimes\overline U`$; distinguish adjoint, transpose and complex conjugation. +- **Dependencies and story role:** M01–M03; supplies the particular matrix whose coherent use is the research target. +- **Conceptual connection:** Fixing the basis and index order determines which factor later contains the actual unknown inverse. +- **Source pointers:** [W] §§1.1.2, 2.2.2; [model: fixed basis and vectorization](../science/model.md#fixed-basis-and-vectorization). + +### M05 — A normalized Choi state from one query + +- **ID and phase:** M05; background/preliminaries. +- **Central question:** What program specimen can one ordinary channel call prepare? +- **Understanding target:** Explain preparation of $`J_{\mathcal E}`$ from a normalized maximally entangled input, its normalization, and the marginal fixed by trace preservation; distinguish this mixed specimen from an accessible purification. +- **Dependencies and story role:** M02–M04; connects the physical oracle to the disposable program used in the construction. +- **Conceptual connection:** Channel-state correspondence provides a one-query resource without supplying a reversible preparation oracle. +- **Source pointers:** [W] §§2.1.3, 2.2.2; [model: normalized Choi state](../science/model.md#fixed-basis-and-vectorization). + +### M06 — What unitality changes + +- **ID and phase:** M06; background/preliminaries. +- **Central question:** Why is preservation of the identity a consequential promise here? +- **Understanding target:** Explain the second flat Choi marginal and Hilbert–Schmidt contraction; connect these to a dimension-independent norm for the Liouville matrix without assuming every unital channel is a mixture of unitaries. +- **Dependencies and story role:** M02, M04–M05; identifies the promise that will support both constant normalization and the improved collision bound. +- **Conceptual connection:** A channel property has one consequence for its matrix norm and another for the state used to program the matrix. +- **Source pointers:** [W] §§4.1.1, 4.2.2; [model: target normalization](../science/model.md#target-evolution-and-normalization). + +### M07 — Swaps and entangled contractions + +- **ID and phase:** M07; background/preliminaries. +- **Central question:** How can known interactions turn a program state's entries into a data Hamiltonian? +- **Understanding target:** Explain the swap operator and maximally entangled projector, and follow the partial-trace identities that produce an ordinary or partially transposed program moment. +- **Dependencies and story role:** M03–M05; introduces the two concrete contractions needed for the collision interaction. +- **Conceptual connection:** Transposition can appear in a derived Hamiltonian coefficient without being performed as a standalone physical transposition map. +- **Source pointers:** [W] §§1.1.2, 2.1, 2.2.2; [compiler: programs and first moments](../science/collision-compiler.md#programs-and-their-first-moments). + +### M08 — Hermitian lifts and coherent evolution + +- **ID and phase:** M08; background/preliminaries. +- **Central question:** How can a generally non-Hermitian channel matrix define a unitary target? +- **Understanding target:** Explain the flag-qubit Hermitian lift, its two off-diagonal blocks and the evolution it generates; distinguish this enlarged-space unitary from applying the original channel to a density operator. +- **Dependencies and story role:** M04, M06–M07; completes the target object independently of the later implementation. +- **Conceptual connection:** The adjoint block makes the lift Hermitian and later enables the inversion reduction. +- **Source pointers:** [W] §1.1; [model: target evolution and normalization](../science/model.md#target-evolution-and-normalization), [interpretation](../science/interpretation.md). + +### M09 — Error for a complete quantum operation + +- **ID and phase:** M09; background/preliminaries. +- **Central question:** What does it mean to approximate the requested output uniformly? +- **Understanding target:** Explain the unhalved diamond norm, reference systems and contractivity under initialization, discarding and composition; distinguish an operator-norm bound, a normalized Choi diagnostic and a full-channel guarantee. +- **Dependencies and story role:** M03, M08; supplies the error language used by both construction and converse. +- **Conceptual connection:** The same composable error measure permits local collision errors to be summed and an inverse to be extracted safely. +- **Source pointers:** [W] §§3.2, 3.3.2–3.3.3; [model: error convention](../science/model.md#error-convention), [verification limits](../verification/README.md#limits-of-this-report). + +### M10 — Known control and relative phase + +- **ID and phase:** M10; background/preliminaries. +- **Central question:** When can a coherent control be implemented without controlling the unknown channel? +- **Understanding target:** Explain the Hamiltonian $`|1\rangle\langle1|\otimes H`$, the significance of relative phase between active and inactive branches, and why controlling known post-preparation interactions is an operationally different task from a controlled unknown-channel call. +- **Dependencies and story role:** M02, M05, M08–M09; resolves the control distinction before it is used in block encoding. +- **Conceptual connection:** A mixed program can be prepared unconditionally while the subsequent known interaction carries the data control coherently. +- **Source pointers:** [W] §§1.1, 2.2; [compiler: coherent control and negative time](../science/collision-compiler.md#coherent-control-and-negative-time), [resources: finite synthesis](../science/resources.md#finite-gate-synthesis). + +### M11 — Designated blocks and polynomial transformations + +- **ID and phase:** M11; background/preliminaries. +- **Central question:** What coherent interface does a matrix-based quantum algorithm need? +- **Understanding target:** Explain a designated ancilla block, its normalization and its complementary unitary blocks; distinguish an accurate block from approximation to a complete unitary, and understand what a polynomial functional calculus requests. +- **Dependencies and story role:** M01, M08–M10; introduces the output interface whose resource cost the project will characterize. +- **Conceptual connection:** The locally supplied block-encoding explanation joins Watrous's operator theory to the research-level QSVT dependency. +- **Source pointers:** [W] §1.1; [block compiler: output guarantee](../science/block-encoding.md#output-and-error-guarantee); [G], Corollary 18, as a research dependency. + +### M12 — The whole ordinary-access conversion problem + +- **ID and phase:** M12; background/preliminaries. +- **Central question:** What precisely must be converted, produced and paid for? +- **Understanding target:** Give one consistent account of ordinary memoryless unital-channel access, one-query Choi programs, the Liouville-lift target, complete-channel error, controls, normalization and charged resources; identify stronger supplied interfaces as different problems. +- **Dependencies and story role:** M01–M11; synthesizes the background into the scientific question rather than adding another isolated prerequisite. +- **Conceptual connection:** This input-output contract explains why a matrix representation is not already a free coherent oracle. +- **Source pointers:** [W] §§2.2, 3.3, 4.2.2; [model](../science/model.md), [resource account](../science/resources.md). + +## Narrative and innovation — M13–M30 + +### M13 — Two mixed controlled-SWAP programs + +- **ID and phase:** M13; narrative/innovation. +- **Central question:** Which physical states expose the desired off-diagonal channel matrix? +- **Understanding target:** Explain the roles of $`J_{\mathcal E}`$, the known controlled swap and the two program flag signs; account for one ordinary query per disposable program. +- **Dependencies and story role:** M05, M07, M12; begins the construction with its actual physical ingredients. +- **Conceptual connection:** Opposite flag coherences allow common diagonal blocks to cancel in a difference of first moments. +- **Source pointers:** [W] §§2.1–2.2; [compiler: programs and first moments](../science/collision-compiler.md#programs-and-their-first-moments); [N], Eqs. (9)–(14). + +### M14 — The first moment, the twist and the time scale + +- **ID and phase:** M14; narrative/innovation. +- **Central question:** Why does the program difference encode the intended Liouville lift rather than a transposed or misnormalized matrix? +- **Understanding target:** Follow the partial-transpose identities, the known controlled-SWAP twist and its removal; explain why collision time must total $`dt`$ to obtain target time $`t`$. +- **Dependencies and story role:** M04, M07–M08, M13; identifies the exact generator before estimating implementation error. +- **Conceptual connection:** Index conventions, the normalized Choi factor and the final conjugation jointly determine the operational target. +- **Source pointers:** [W] §§1.1.2, 2.2.2; [compiler: first moments](../science/collision-compiler.md#programs-and-their-first-moments). + +### M15 — The inherited variance bound + +- **ID and phase:** M15; narrative/innovation. +- **Central question:** Which property of a program controls its reduced collision error? +- **Understanding target:** Explain the first moment $`K`$, second moment $`M`$, and variance $`M-K^2`$; reconstruct how compression and leakage yield an all-time diamond bound, while recognizing that the proof's purification is not supplied access. +- **Dependencies and story role:** M03, M07, M09, M14; isolates the inherited error mechanism that the project specializes. +- **Conceptual connection:** An evaluated program moment can be much smaller than a bound using only the joint interaction norm. +- **Source pointers:** [W] §§2.1.3, 3.3; [compiler: program-variance bound](../science/collision-compiler.md#the-inherited-program-variance-bound), [related work: moment-sensitive exponentiation](../references/RELATED_WORK.md#moment-sensitive-exponentiation-and-the-inherited-variance-estimate). + +### M16 — The flat marginal removes a dimension factor + +- **ID and phase:** M16; narrative/innovation. +- **Central question:** Where does the improved dimension dependence actually enter? +- **Understanding target:** Derive the relevant marginal of each mixed program and its exact collision second moment $`M=I`$; explain why unitality retains useful information that a worst-case interaction-norm estimate discards. +- **Dependencies and story role:** M06, M13–M15; supplies the construction's decisive unital-case specialization. +- **Conceptual connection:** The same flat-marginal promise that supported normalization now bounds the physical collision variance independently of dimension. +- **Source pointers:** [W] §4.2.2; [compiler: exact second moment](../science/collision-compiler.md#flat-marginal-and-exact-second-moment), [related work](../references/RELATED_WORK.md#moment-sensitive-exponentiation-and-the-inherited-variance-estimate). + +### M17 — From one pair to a finite global compiler + +- **ID and phase:** M17; narrative/innovation. +- **Central question:** How do the two local collisions produce the complete finite-budget theorem? +- **Understanding target:** Explain the opposite collision signs, chronological product, partial-transpose norm bound, commutator error and telescoping; recover the (2m)-query guarantee and its integer ceiling without hiding a small-step remainder. +- **Dependencies and story role:** M09, M14–M16; assembles the first full constructive result. +- **Conceptual connection:** The first-moment time scale and second-moment error must be combined before reading off the dimension cost. +- **Source pointers:** [W] §§1.1, 3.3; [compiler: pairing and total error](../science/collision-compiler.md#pairing-product-formula-and-total-error), [finite-budget theorem](../science/collision-compiler.md#finite-budget-theorem). + +### M18 — Controls and inverses as generated outputs + +- **ID and phase:** M18; narrative/innovation. +- **Central question:** How are coherent control and negative-time evolution obtained from forward channel calls? +- **Understanding target:** Track the controlled interaction's moments and the reversal of known collision angles; explain why fresh ordinary program preparations suffice and why an arbitrary noisy output channel is not being inverted after the fact. +- **Dependencies and story role:** M10, M15–M17; upgrades the evolution result to the interface required by the next construction. +- **Conceptual connection:** Controlling the physical synthesis preserves the chosen target phase, which ordinary channel-distance information alone would not provide. +- **Source pointers:** [W] §§2.2, 3.3; [compiler: control and negative time](../science/collision-compiler.md#coherent-control-and-negative-time), [resources: controlled collision](../science/resources.md#a-collision-has-a-small-known-circuit). + +### M19 — Turning a short evolution into its generator + +- **ID and phase:** M19; narrative/innovation. +- **Central question:** How can controlled evolution supply a matrix block proportional to the generator? +- **Understanding target:** Derive the sine block with its correct sign and explain why a bounded odd inverse-sine polynomial recovers the generator on the promised spectral interval. +- **Dependencies and story role:** M08, M11, M18; begins the inherited evolution-to-block route with explicit normalization. +- **Conceptual connection:** A small generator norm keeps the inverse-sine approximation away from its difficult endpoints. +- **Source pointers:** [W] §1.1; [block compiler: sine block](../science/block-encoding.md#an-exact-sine-block), [inverse-sine polynomial](../science/block-encoding.md#a-bounded-odd-inverse-sine-polynomial); [G], Lemma 70. + +### M20 — The exact polynomial block + +- **ID and phase:** M20; narrative/innovation. +- **Central question:** Which block does real-polynomial QSVT produce, including its normalization? +- **Understanding target:** Explain why odd singular-value transformation agrees with Hermitian polynomial calculus here, why the designated block has no additional factor one-half, and how its approximation to the Hermitian lift divided by pi is bounded. +- **Dependencies and story role:** M11, M19; fixes the exact ideal polynomial circuit before physical approximation is introduced. +- **Conceptual connection:** Matching parity and the strict contraction interval are material hypotheses, not interchangeable versions of a generic QSVT statement. +- **Source pointers:** [W] §1.1; [block compiler: inverse-sine polynomial](../science/block-encoding.md#a-bounded-odd-inverse-sine-polynomial); [G], Corollary 18. + +### M21 — Completing one common comparison unitary + +- **ID and phase:** M21; narrative/innovation. +- **Central question:** Why does an accurate polynomial block imply proximity to a complete unitary with the exact target block? +- **Understanding target:** Explain the active unitary completion, its strict-contraction stability bound and the role of commuting Hermitian blocks; show why forward, inverse and controlled implementations refer to the same exact comparison unitary. +- **Dependencies and story role:** M09–M11, M18–M20; closes the complete-operation gap that a block-only statement would leave. +- **Conceptual connection:** Existence of complementary blocks is sufficient for the comparison guarantee; their classical reconstruction is not an input resource. +- **Source pointers:** [W] §1.1; [block compiler: stable completion](../science/block-encoding.md#stable-completion-of-the-whole-unitary), [inverse and controlled versions](../science/block-encoding.md#inverse-and-controlled-versions). + +### M22 — The block compiler's ordinary-query budget + +- **ID and phase:** M22; narrative/innovation. +- **Central question:** How does the complete block construction translate into a channel-query count? +- **Understanding target:** Combine logarithmic polynomial degree, fixed-time evolution cost and per-primitive error allocation to obtain $`O(d^2\delta^{-1}[1+\log(1/\delta)]^2)`$; distinguish this sufficient precision dependence from the later dimension converse. +- **Dependencies and story role:** M09, M17–M21; integrates the constructive query frontier. +- **Conceptual connection:** Fresh program specimens and diamond-norm telescoping make the compositional error budget operational. +- **Source pointers:** [W] §3.3; [block compiler: ordinary-channel query count](../science/block-encoding.md#ordinary-channel-query-count), [resources: ordinary access](../science/resources.md#ordinary-channel-access-is-the-input). + +### M23 — Gates, synthesis, memory and work return + +- **ID and phase:** M23; narrative/innovation. +- **Central question:** Which costs remain after counting channel queries? +- **Understanding target:** Explain the Bell-projector test, swap-sign extraction, controlled rotation and uncomputation; distinguish constant block flags from logarithmic program/workspace, and account for known-gate precision, disposable programs and returned clean work. +- **Dependencies and story role:** M07, M10, M17–M22; completes the constructive resource account beyond the oracle count. +- **Conceptual connection:** A dimension-optimal query conversion need not be cheap in input qubit count or furnish an application-level advantage. +- **Source pointers:** [W] §§1.1, 2.2; [resources: collision circuit](../science/resources.md#a-collision-has-a-small-known-circuit), [finite synthesis](../science/resources.md#finite-gate-synthesis), [memory and work return](../science/resources.md#memory-and-work-return). + +### M24 — Extracting the actual unknown inverse + +- **ID and phase:** M24; narrative/innovation. +- **Central question:** What extra capability does coherent Liouville access expose even for a noiseless channel? +- **Understanding target:** Use the unitary subclass and time $`\pi/2`$ to select $`U^\dagger\otimes U^{\mathsf T}`$; explain why preparing and discarding a dummy factor yields the inverse on arbitrary reference-entangled data, rather than a transpose or complex conjugate. +- **Dependencies and story role:** M03–M04, M08, M17; starts the converse from a concrete operational reduction. +- **Conceptual connection:** The enlarged coherent output is harder than one ordinary forward invocation because it can act on an arbitrary live input with the inverse. +- **Source pointers:** [W] §§1.1.2, 2.2.2; [lower bound: direct coherent evolution](../science/dimension-lower-bound.md#direct-coherent-evolution), [unitary example](../science/examples.md#an-unknown-unitary). + +### M25 — The robust inversion obstruction + +- **ID and phase:** M25; narrative/innovation. +- **Central question:** Why does the dimension obstruction survive a fixed nonzero implementation error? +- **Understanding target:** Explain normalized Choi fidelity, its projector test, the unhalved-diamond factor and the Haar-averaged inversion bound; derive the direct-evolution lower bound under a hard query cap and recognize the imported theorem's scope. +- **Dependencies and story role:** M09, M24; converts the extraction into a robust dimension converse. +- **Conceptual connection:** An exact-only inversion theorem would not justify the approximate compiler lower bound. +- **Source pointers:** [W] §§3.2, 3.3; [lower bound: inversion theorem](../science/dimension-lower-bound.md#the-inversion-theorem-used), [direct evolution](../science/dimension-lower-bound.md#direct-coherent-evolution); [C], Theorem 3.7. + +### M26 — A forward block is already enough + +- **ID and phase:** M26; narrative/innovation. +- **Central question:** Does the block compiler need an accessible inverse before the lower bound applies? +- **Understanding target:** Explain constant-probability inverse extraction from one forward designated block, complete failure to a deterministic channel, and derive the fidelity lower bound $`c^2-\delta/2`$ and its useful error regime. +- **Dependencies and story role:** M11, M21–M22, M24–M25; aligns the converse with the exact interface constructed above. +- **Conceptual connection:** A successful branch contributes positive inverse fidelity even when the failure output is unrelated to the inverse. +- **Source pointers:** [W] §§2.3, 3.2–3.3; [lower bound: constant-normalization block](../science/dimension-lower-bound.md#a-constant-normalization-block-is-already-sufficient); [C], Theorem 3.7. + +### M27 — Recovery with a known depolarizing component + +- **ID and phase:** M27; narrative/innovation. +- **Central question:** What concrete finite-noise capability follows from the same compiler? +- **Understanding target:** Decompose the noisy-unitary Liouville matrix, explain the known commuting correction and time rescaling, and recover the clean unitary or inverse; identify known (p<1) as a supplied calibration promise and the bound as sufficient rather than optimal. +- **Dependencies and story role:** M04, M08, M17–M18, M24; demonstrates the operational meaning beyond the noiseless hard family. +- **Conceptual connection:** The maximally entangled identity direction makes the depolarizing correction independent of the unknown unitary. +- **Source pointers:** [W] §§2.2, 4.1–4.2; [examples: known depolarizing noise](../science/examples.md#depolarizing-noise-around-an-unknown-unitary), [related work: noisy-unitary purification](../references/RELATED_WORK.md#noisy-unitary-purification-and-the-open-precision-dependence). + +### M28 — What the finite checks establish + +- **ID and phase:** M28; narrative/innovation. +- **Central question:** Which consequential mistakes can the numerical diagnostics detect, and which claims still require proof? +- **Understanding target:** Explain the roles of complex nonsymmetric fixtures, nonunital boundaries, control checks, collision reconstruction and inverse negative controls; distinguish a normalized Choi-distance diagnostic from a diamond-norm upper certificate or general proof. +- **Dependencies and story role:** M09, M14–M18, M24, M27; connects the analytical claims to reproducible evidence without upgrading finite tests into universal guarantees. +- **Conceptual connection:** Verification is selected around orientation, normalization and operational failure modes, rather than treated as a test-count argument for correctness. +- **Source pointers:** [W] §§2.2.2, 3.3; [verification account](../verification/README.md), [verification report](../verification/report.json). + +### M29 — Attribution, closest work and scope boundaries + +- **ID and phase:** M29; narrative/innovation. +- **Central question:** What remains after the inherited constructions and material restrictions are stated? +- **Understanding target:** Separate the inherited Liouville programs, marginal-sensitive variance, QSVT and inversion theorem from the supported unital-case compiler and operational dimension frontier; explain the superseded preprint exponent, nonunital earlier hard family, and why virtual adjoints and ordered low-noise results are different claims. +- **Dependencies and story role:** M12–M28; evaluates the assembled contribution against its actual antecedents and neighboring tasks. +- **Conceptual connection:** Correct attribution and matched operational models determine the surviving scientific consequence. +- **Source pointers:** [W] §§2.2, 3.3, 4.2.2; [related work](../references/RELATED_WORK.md), [interpretation](../science/interpretation.md). + +### M30 — The complete fixed-accuracy frontier + +- **ID and phase:** M30; narrative/innovation. +- **Central question:** What can now be concluded about converting physical channel access into coherent matrix access? +- **Understanding target:** Connect the flat-marginal construction, complete block guarantee, robust inverse extraction and charged resources into the fixed-accuracy quadratic dimension law; preserve the suitable-time qualification, exponential qubit dependence, and open joint precision/time frontier while explaining the result's operational significance. +- **Dependencies and story role:** M12–M29; synthesizes the whole contribution and its limits without introducing a separate final curriculum. +- **Conceptual connection:** The constructive and converse mechanisms meet on one interface: ordinary unital-channel calls must pay for the coherent capability they generate. +- **Source pointers:** [W] §§2.2, 3.3, 4.2.2; [principal result](../README.md#principal-result), [resource frontier](../science/resources.md#what-the-resource-frontier-means), [matching regime and open questions](../science/dimension-lower-bound.md#what-is-matched-and-what-remains-open). + +[W]: https://cs.uwaterloo.ca/~watrous/TQI/ +[N]: https://arxiv.org/html/2506.24112v3 +[G]: https://arxiv.org/abs/1806.01838 +[C]: https://arxiv.org/abs/2507.05736v4 diff --git a/learning/README.md b/learning/README.md new file mode 100644 index 0000000..58e0362 --- /dev/null +++ b/learning/README.md @@ -0,0 +1,54 @@ +# Learn the channel-coherentization result + +Imagine being given a device that applies an unknown quantum process. You can send a register through it and retain the visible output. The device may lose information into an environment that you cannot inspect. A spectral quantum algorithm can require a different interface: a unitary operation on a larger register whose designated matrix block contains the process's Liouville matrix. + +The scientific question is how many ordinary device uses are needed to build that interface. For every unknown unital channel, the compiler has quadratic dimension cost at fixed accuracy. A matching worst-case obstruction already comes from noiseless unknown unitary channels. Error is measured on the whole output operation, including data entangled with an untouched reference; an accurate value of one observable would be a weaker task. + +| Object | What it supplies | +| --- | --- | +| Ordinary channel call | One physical input-output use of the unknown process | +| Liouville matrix | A coefficient representation of the same linear map on operators | +| Coherent target | A compiled unitary operation acting on arbitrary vectors of an enlarged data space | + +Writing down a matrix representation does not supply the corresponding quantum gate. In particular, the two vectorization registers are actual computational data registers in the compiled target; their input need not be the coefficients of a physical density matrix. + +## Start with one source and the project map + +The educational anchor is **John Watrous, *The Theory of Quantum Information* (2018)**. The [Watrous bridge](WATROUS_BRIDGE.md) identifies the relevant sections, translates notation, and supplies the steps from textbook channel theory to this problem. It is a route into the science, rather than an instruction to read the whole book first. + +The [30-milestone map](MILESTONES.md) is the common understanding route. Its 12 background milestones assemble individual objects into the complete input-output task. Its 18 narrative milestones assemble the compiler, the converse and their meaning. This allocation follows the project: understanding the representation is the starting point, while the main work is connecting the construction's resource accounting to an unrestricted dimension obstruction. + +| Part of the route | Main question | Connected reading | +| --- | --- | --- | +| M01–M12: background | What is given, what is requested, and how is error measured? | [Watrous bridge](WATROUS_BRIDGE.md) and [model](../science/model.md) | +| M13–M23: construction | How do ordinary calls become a complete coherent operation? | [Collision compiler](../science/collision-compiler.md), [block encoding](../science/block-encoding.md) and [resources](../science/resources.md) | +| M24–M26: converse | Why must even the best universal compiler pay quadratically in dimension? | [Inverse extraction and lower bound](../science/dimension-lower-bound.md) | +| M27–M30: synthesis | What can the interface do, what was checked, and what is actually matched? | [Examples](../science/examples.md), [verification](../verification/README.md), [related work](../references/RELATED_WORK.md) and [interpretation](../science/interpretation.md) | + +The map records each milestone's understanding target, dependencies and exact source pointers. The [scientific reading route](../science/README.md) provides a direct path through the proofs. + +## Follow the causal chain + +**Unitality enters twice.** A unital channel preserves the maximally mixed state. First, this makes its Liouville matrix a contraction, so a constant block normalization is possible. Second, it makes the relevant program marginal maximally mixed. These are different uses of the same promise; the second is what improves the collision cost. + +**One ordinary call supplies one consumable program.** Prepare a known maximally entangled state, apply the unknown channel to one half, and use a known controlled swap. The resulting mixed program is not a purification or a reversible description of the channel. Its first collision moment is the average Hamiltonian seen by the data and contains the desired Liouville matrix. Its second moment controls fluctuations about that average; it is exactly the identity in the unital case. The inherited program-variance estimate turns these evaluated moments into a complete-channel error bound. + +**Many small collisions build the target.** The two programs are paired with opposite known collision signs. Fresh programs let the errors be composed and every channel call counted. Changing the signs or controlling the known interactions generates inverse or controlled target evolutions; it does not require an inverse or controlled invocation of the unknown device. + +**The block guarantee concerns the whole operation.** A sine block and a bounded inverse-sine polynomial produce an accurate designated block. Stable unitary completion then shows that the entire implemented channel is close to one exact block unitary with block $`\mathsf H(L_{\mathcal E})/\pi`$. This is stronger than checking that one submatrix is accurate on its own. + +**The converse exposes an inverse capability.** For an unknown unitary channel, the doubled Liouville lift contains a sector acting as the inverse unitary on one data factor. A universal coherent compiler would therefore implement an unknown inverse. The established inversion fidelity bound supplies the quadratic dimension obstruction. This argument tests the capability of the output interface, rather than the variance analysis of the proposed construction. + +## Read the conclusion with its conditions + +The matched law holds when accuracy is fixed at a sufficiently small constant and the evolution time is fixed appropriately: + +```math +Q(d)=\Theta(d^2). +``` + +Here $`d`$ is the unknown channel's input dimension. For $`n`$ input qubits, $`d=2^n`$, so the worst-case conversion costs $`\Theta(4^n)`$ ordinary calls. This is a statement about building a coherent interface, not an application-level quantum–classical speedup. + +The construction's dependence on precision and time is an upper bound; the dimension converse does not make those dependences optimal. The supplied channel is unital and memoryless, and known gates, finite synthesis, disposable programs and workspace remain charged separately. The [known-noise example](../science/examples.md) is an achievable recovery construction with a calibrated noise parameter, not an optimal purification law. + +The learning route uses the same definitions and scope as the proofs. Finite diagnostics help check conventions and examples; they do not replace the analytical all-channel guarantee. diff --git a/learning/WATROUS_BRIDGE.md b/learning/WATROUS_BRIDGE.md new file mode 100644 index 0000000..b8868d5 --- /dev/null +++ b/learning/WATROUS_BRIDGE.md @@ -0,0 +1,136 @@ +# From Watrous to the coherent channel interface + +The single background anchor is John Watrous, *The Theory of Quantum Information* (Cambridge University Press, 2018), available through [the author's book page](https://cs.uwaterloo.ca/~watrous/TQI/). The locators below refer to the author's standard-layout manuscript, whose section and equation numbers were checked against the author-hosted chapters. The book is linked, not redistributed. + +The book supplies the language for channels, their matrix representations, and error on entangled inputs. This project asks an additional algorithmic question: how many ordinary uses of an unknown channel are needed to implement a coherent evolution containing its matrix? A representation theorem identifies the desired matrix; an access model determines what it costs to use that matrix in a circuit. + +## The relevant parts of the book + +| Book locator | Role in this project | Project destination | +| --- | --- | --- | +| §1.1.2, “The operator-vector correspondence,” Eqs. (1.127)–(1.134) | Fix tensor order, conjugation, and the operator-to-vector isometry. | [Model and conventions](../science/model.md) | +| §2.2.1 and §2.2.2, “Representations and characterizations of channels,” especially Eqs. (2.60)–(2.66) | Distinguish the physical channel, its natural representation, and its Choi representation. | [Model](../science/model.md), then [collision compiler](../science/collision-compiler.md) | +| §2.2.3, “Examples of channels and other mappings,” Eqs. (2.154)–(2.155) | Check the depolarizing channel in both representations. | The worked example below and [scientific examples](../science/examples.md) | +| §3.1.1 and §3.2, Definition 3.11 | Relate observable probabilities, trace distance, and the book's fidelity convention. | [Dimension lower bound](../science/dimension-lower-bound.md) | +| §3.3.2, Definition 3.43, and §3.3.3, “Distances between channels” | Understand the reference system and the completely bounded trace norm. | [Full channel error](../science/model.md#error-convention) | +| §4.2.2, “Fixed-points, spectra, and norms of unital channels,” Theorem 4.27 | Obtain the Hilbert–Schmidt contraction of a unital channel. | [Target normalization](../science/model.md#target-evolution-and-normalization) | + +These are targeted entry points. Later sections on capacities, entropy, and entanglement theory are not prerequisites for this project's main proof. The [milestone map](MILESTONES.md) organizes the background and research argument separately. + +## Translate the conventions before using the formulas + +### Vectorization and the two representations + +Watrous uses $`\operatorname{vec}(E_{ij})=|i\rangle\otimes|j\rangle`$. This project uses exactly that tensor convention: + +```math +|X\rangle\!\rangle +=\operatorname{vec}(X) +=\sum_{i,j}X_{ij}|i\rangle|j\rangle, +\qquad +|AXB^\dagger\rangle\!\rangle +=(A\otimes\overline B)|X\rangle\!\rangle. +``` + +The explicit formula is the convention: software that flattens a matrix into a column can order its entries differently. In particular, the unitary channel $`X\mapsto UXU^\dagger`$ has matrix $`U\otimes\overline U`$ here. Watrous writes $`A^*`$ for the adjoint; this project writes $`A^\dagger`$. + +| Object | Watrous | This project | +| --- | --- | --- | +| Natural/Liouville representation | $`K(\mathcal E)\operatorname{vec}(X)=\operatorname{vec}(\mathcal E(X))`$ | $`L_{\mathcal E}=K(\mathcal E)`$ | +| Entangled vector | $`\operatorname{vec}(I)`$, of squared norm $`d`$ | $`|\Phi_d\rangle=\operatorname{vec}(I)/\sqrt d`$ | +| Choi operator/state | $`J(\mathcal E)=(\mathcal E\otimes\mathrm{id})(\operatorname{vec}(I)\operatorname{vec}(I)^\dagger)`$ | $`J_{\mathcal E}=J(\mathcal E)/d`$ | +| Tensor legs of the Choi object | Output first, input second | The same | + +For a trace-preserving map, the book's Choi operator has trace $`d`$; the project's Choi state has trace one. Thus a physical call on one half of $`|\Phi_d\rangle`$ prepares $`J_{\mathcal E}`$, with no extra factor of $`d`$. The normalized reconstruction formula is + +```math +\mathcal E(X) +=d\,\mathrm{Tr}_{\mathrm{input}} +\!\left[J_{\mathcal E}(I_{\mathrm{output}}\otimes X^{\mathsf T})\right]. +``` + +Trace preservation gives $`\mathrm{Tr}_{\mathrm{output}}J_{\mathcal E}=I/d`$. Unitality gives the other marginal, $`\mathrm{Tr}_{\mathrm{input}}J_{\mathcal E}=I/d`$. Both identities enter the compiler's second-moment calculation. Theorem 4.27 gives $`\|L_{\mathcal E}\|_\infty=1`$ for a unital channel; this is the spectral norm of its matrix, corresponding to the induced Hilbert–Schmidt norm on operators, rather than the trace norm of its Choi state. + +### Distance and fidelity + +The project's $`\|\cdot\|_\diamond`$ is Watrous's completely bounded trace norm, without a factor of one half. For states, write $`D(\rho,\sigma)=\tfrac12\|\rho-\sigma\|_1`$. Consequently a compiler guarantee of unhalved diamond error $`\delta`$ implies output trace distance at most $`\delta/2`$, even with an untouched reference. Any specified measurement probability changes by at most $`\delta/2`$. + +Watrous's Definition 3.11 uses the **unsquared** fidelity + +```math +F_{\mathrm W}(\rho,\sigma)=\|\sqrt\rho\sqrt\sigma\|_1. +``` + +The lower bound instead uses overlap with the pure normalized Choi state of the ideal unitary: + +```math +F_{\mathrm{ch}}(\mathcal R,\mathrm{Ad}_V) +=\langle\Phi_V|J_{\mathcal R}|\Phi_V\rangle +=F_{\mathrm W}\!\left(J_{\mathcal R},|\Phi_V\rangle\langle\Phi_V|\right)^2, +\qquad |\Phi_V\rangle=(V\otimes I)|\Phi_d\rangle. +``` + +Here $`F_{\mathrm{ch}}`$ is a squared fidelity, not the book's $`F_{\mathrm W}`$. Measuring the projector $`|\Phi_V\rangle\langle\Phi_V|`$ directly gives $`F_{\mathrm{ch}}\ge1-\delta/2`$ from diamond error $`\delta`$. This fixes the factor used in the lower-bound reduction. + +## Where the book stops and the research task starts + +The natural and Choi representations describe the same linear map, but the physical operations they make available differ. An ordinary channel call produces a state from an input state. It does not supply matrix entries, a controlled channel, an adjoint, or a reversible environment interface. The existence of a Stinespring representation in §2.2.2 does not make its dilation an accessible oracle. Likewise, an algebraic reshuffling or partial transpose of a Choi matrix is not automatically a physical operation on an unknown specimen. + +The research target is a new unitary on a flag qubit and two data registers: + +```math +U_{\mathcal E}(t)=e^{-it\mathsf H(L_{\mathcal E})}, +\qquad +\mathsf H(A)=\begin{pmatrix}0&A\\A^\dagger&0\end{pmatrix}. +``` + +Its input is an arbitrary vector in the enlarged space, and its guarantee is a channel guarantee on arbitrary reference-entangled inputs. Repeated physical channel calls prepare fresh normalized Choi specimens; known interactions consume those specimens to approximate the target. Their preparation, collision error, circuit synthesis, and workspace need an explicit resource account. This conversion is the gap between knowing what $`L_{\mathcal E}`$ means and having a gate that coherently uses it. + +Watrous supports the background statements above. The compiler itself depends on the later Liouville-program construction of Niwa and collaborators, marginal-sensitive Hamiltonian-mapping analysis, and a cited collision-variance lemma. The dimension lower bound depends on the later universal-unitary-inversion theorem of Chen, Yu, and Zhang. These are research dependencies, documented with their precise roles in [related work](../references/RELATED_WORK.md); they are not additional background anchors or results supplied by the book. For the direct evolution, the matching dimension bounds use the fixed time $`t=\pi/2`$ and fixed admissible accuracy. The block-encoding comparison fixes a constant normalization. Neither establishes a matching joint lower bound in dimension and inverse error. + +## A complete qubit calculation + +Take the known qubit channel + +```math +\mathcal E(X)=\tfrac12X+\tfrac12\mathrm{Tr}(X)I/2. +``` + +This is the $`U=I,p=1/2`$ instance of [the depolarizing example](../science/examples.md#a-simple-qubit-noise-channel). Define two normalized operator vectors + +```math +|e_0\rangle=|I\rangle\!\rangle/\sqrt2 +=\frac{|00\rangle+|11\rangle}{\sqrt2}, +\qquad +|e_z\rangle=|Z\rangle\!\rangle/\sqrt2 +=\frac{|00\rangle-|11\rangle}{\sqrt2}. +``` + +The ordinary channel fixes the identity and halves every traceless operator. On a physical input qubit, + +```math +|0\rangle\langle0|=\frac{I+Z}{2} +\quad\longmapsto\quad +\frac{I+Z/2}{2} +=\begin{pmatrix}3/4&0\\0&1/4\end{pmatrix}. +``` + +The corresponding Choi state and Liouville matrix are different objects: + +```math +J_{\mathcal E}=\tfrac12|e_0\rangle\langle e_0|+\tfrac18 I_4, +\qquad +L_{\mathcal E}=\tfrac12 I_4+\tfrac12|e_0\rangle\langle e_0|. +``` + +The first has trace one and both marginals $`I_2/2`$. The second has eigenvalue one on $`e_0`$ and eigenvalue $`1/2`$ on $`e_z`$. Since $`L_{\mathcal E}`$ is Hermitian, its lift is $`X_C\otimes L_{\mathcal E}`$, giving + +```math +U_{\mathcal E}(t)|0\rangle_C|e_z\rangle +=\left(\cos(t/2)|0\rangle_C-i\sin(t/2)|1\rangle_C\right)|e_z\rangle. +``` + +At $`t=\pi/2`$, the output is $`(|0\rangle-i|1\rangle)_C|e_z\rangle/\sqrt2`$. At the same time, $`|0\rangle_C|e_0\rangle`$ becomes $`-i|1\rangle_C|e_0\rangle`$. The channel's contraction coefficients have become coherent flag-rotation frequencies. No trace or norm is lost by this enlarged unitary. + +Although $`Z/\sqrt2`$ is not a density operator, its vectorization $`|e_z\rangle`$ is a valid normalized two-qubit state. This is why the enlarged interface can act on data that are not physical channel inputs under the operator interpretation. The example has known parameters and a known small circuit; it illustrates the interface and is not the universal hard family or a claim of optimal noise purification. + diff --git a/llms.txt b/llms.txt index 14c106f..12f4f10 100644 --- a/llms.txt +++ b/llms.txt @@ -8,6 +8,7 @@ Upper proof: science/collision-compiler.md; complete-unitary block output: scien Lower proof: science/dimension-lower-bound.md. Its robust inversion reduction uses one forward compiled block and no compiler inverse. Implementation: science/resources.md. Count channel calls, known gates, phase synthesis, disposable program and work qubits separately. Prior work: references/RELATED_WORK.md and references/references.bib. +Learning: learning/README.md; fixed project map: learning/MILESTONES.md; selected source and convention translation: learning/WATROUS_BRIDGE.md (John Watrous, The Theory of Quantum Information, 2018). Reproduction: verification/README.md, verification/verify.py, verification/report.json. Essential distinctions: ordinary channel is the input; dilation/inverse/control are not supplied. All diamond norms are unhalved. The output target has no hidden dimension normalization; its exact designated block is Herm(L)/pi. Quadratic dimension order is matched at fixed precision, not a joint d-squared-over-error lower law. The ideal block ancilla count is constant; physical workspace is logarithmic in dimension. No application-level speedup is claimed. diff --git a/references/references.bib b/references/references.bib index 328e59a..c94d343 100644 --- a/references/references.bib +++ b/references/references.bib @@ -1,3 +1,11 @@ +@book{Watrous2018TQI, + author = {Watrous, John}, + title = {The Theory of Quantum Information}, + publisher = {Cambridge University Press}, year = {2018}, + doi = {10.1017/9781316848142}, + url = {https://cs.uwaterloo.ca/~watrous/TQI/}, + note = {The single educational anchor; author-hosted chapter locators are mapped in learning/WATROUS_BRIDGE.md} +} @article{Niwa2026Liouville, author = {Niwa, Ryotaro and Rossi, Zane Marius and Taranto, Philip and Murao, Mio}, title = {Singular value transformation for unknown quantum channels}, diff --git a/verification/README.md b/verification/README.md index e9fa57b..84799ba 100644 --- a/verification/README.md +++ b/verification/README.md @@ -1,5 +1,17 @@ # Finite verification +The numerical checks below concern finite algebraic consistency. The separate +[hosted mathematics workflow](../.github/workflows/hosted-math.yml) visits every +tracked Markdown page at its exact pull-request head revision, using a fresh +anonymous Chromium context at widths 1440 and 760. Its +[collector](hosted-tools/capture_hosted_math.cjs) and +[text checker](hosted-tools/check_rendered_math.py) compare complete source and +hosted MathML, counts, relations and bounded display geometry. Reports, HTML and +screenshots are retained as temporary workflow artifacts. A structural pass +still requires visual inspection and does not certify the scientific proofs. +The job has only `contents: read`, persists no checkout credentials, and uses +neither repository secrets nor account or certificate-setting changes. + Run from the repository root: ```bash diff --git a/verification/hosted-contract.json b/verification/hosted-contract.json new file mode 100644 index 0000000..4eb549f --- /dev/null +++ b/verification/hosted-contract.json @@ -0,0 +1,35 @@ +{ + "schema_version": 1, + "expressions": [ + { + "path": "README.md", + "index": 4, + "source_sha256": "620e6e6abc5a2495c094cea8de314f92122d330c6a5d78ec2e106b8817078ec3", + "expected_text": "H(LE)=(0LELE†0)." + }, + { + "path": "README.md", + "index": 7, + "source_sha256": "b49c3252359df71c646b31678d7ca643d8fdd3667a0b19803a1bd41ec723a1d6", + "expected_text": "(4d2+2)t2/m" + }, + { + "path": "README.md", + "index": 10, + "source_sha256": "f6b8515784519076db68c4419758da9ca6a5b3994307d012f163ba9d19419b6c", + "expected_text": "q≥d2(1−ϵ/2)−1" + }, + { + "path": "README.md", + "index": 14, + "source_sha256": "e53237bd3a64ff95b5064d11e285c26a03cd1a24450719213271c164938a5c1d", + "expected_text": "q≥d2(π−2−δ/2)−1" + }, + { + "path": "README.md", + "index": 15, + "source_sha256": "7fc1a2d1f4e9616998ee9741a3ad3c4cace752aa449e0613c875f0b8d4b1fc90", + "expected_text": "Q(d)=Θ(d2)." + } + ] +} diff --git a/verification/hosted-tools/capture_hosted_math.cjs b/verification/hosted-tools/capture_hosted_math.cjs new file mode 100644 index 0000000..6f36ee0 --- /dev/null +++ b/verification/hosted-tools/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-tools/check_rendered_math.py b/verification/hosted-tools/check_rendered_math.py new file mode 100644 index 0000000..1d3bf98 --- /dev/null +++ b/verification/hosted-tools/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 c87efd9db5dd452c8169266e571e0a5d91c05c97 Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Sun, 15 Nov 2026 22:58:25 +0800 Subject: [PATCH 2/5] Use GitHub-supported operators and explicit norm delimiters --- learning/WATROUS_BRIDGE.md | 16 +++++----- references/RELATED_WORK.md | 8 ++--- science/block-encoding.md | 46 ++++++++++++++-------------- science/collision-compiler.md | 52 ++++++++++++++++---------------- science/dimension-lower-bound.md | 24 +++++++-------- science/model.md | 10 +++--- 6 files changed, 78 insertions(+), 78 deletions(-) diff --git a/learning/WATROUS_BRIDGE.md b/learning/WATROUS_BRIDGE.md index b8868d5..cef0e0c 100644 --- a/learning/WATROUS_BRIDGE.md +++ b/learning/WATROUS_BRIDGE.md @@ -21,11 +21,11 @@ These are targeted entry points. Later sections on capacities, entropy, and enta ### Vectorization and the two representations -Watrous uses $`\operatorname{vec}(E_{ij})=|i\rangle\otimes|j\rangle`$. This project uses exactly that tensor convention: +Watrous uses $`\mathrm{vec}(E_{ij})=|i\rangle\otimes|j\rangle`$. This project uses exactly that tensor convention: ```math |X\rangle\!\rangle -=\operatorname{vec}(X) +=\mathrm{vec}(X) =\sum_{i,j}X_{ij}|i\rangle|j\rangle, \qquad |AXB^\dagger\rangle\!\rangle @@ -36,9 +36,9 @@ The explicit formula is the convention: software that flattens a matrix into a c | Object | Watrous | This project | | --- | --- | --- | -| Natural/Liouville representation | $`K(\mathcal E)\operatorname{vec}(X)=\operatorname{vec}(\mathcal E(X))`$ | $`L_{\mathcal E}=K(\mathcal E)`$ | -| Entangled vector | $`\operatorname{vec}(I)`$, of squared norm $`d`$ | $`|\Phi_d\rangle=\operatorname{vec}(I)/\sqrt d`$ | -| Choi operator/state | $`J(\mathcal E)=(\mathcal E\otimes\mathrm{id})(\operatorname{vec}(I)\operatorname{vec}(I)^\dagger)`$ | $`J_{\mathcal E}=J(\mathcal E)/d`$ | +| Natural/Liouville representation | $`K(\mathcal E)\mathrm{vec}(X)=\mathrm{vec}(\mathcal E(X))`$ | $`L_{\mathcal E}=K(\mathcal E)`$ | +| Entangled vector | $`\mathrm{vec}(I)`$, of squared norm $`d`$ | $`|\Phi_d\rangle=\mathrm{vec}(I)/\sqrt d`$ | +| Choi operator/state | $`J(\mathcal E)=(\mathcal E\otimes\mathrm{id})(\mathrm{vec}(I)\mathrm{vec}(I)^\dagger)`$ | $`J_{\mathcal E}=J(\mathcal E)/d`$ | | Tensor legs of the Choi object | Output first, input second | The same | For a trace-preserving map, the book's Choi operator has trace $`d`$; the project's Choi state has trace one. Thus a physical call on one half of $`|\Phi_d\rangle`$ prepares $`J_{\mathcal E}`$, with no extra factor of $`d`$. The normalized reconstruction formula is @@ -49,16 +49,16 @@ For a trace-preserving map, the book's Choi operator has trace $`d`$; the projec \!\left[J_{\mathcal E}(I_{\mathrm{output}}\otimes X^{\mathsf T})\right]. ``` -Trace preservation gives $`\mathrm{Tr}_{\mathrm{output}}J_{\mathcal E}=I/d`$. Unitality gives the other marginal, $`\mathrm{Tr}_{\mathrm{input}}J_{\mathcal E}=I/d`$. Both identities enter the compiler's second-moment calculation. Theorem 4.27 gives $`\|L_{\mathcal E}\|_\infty=1`$ for a unital channel; this is the spectral norm of its matrix, corresponding to the induced Hilbert–Schmidt norm on operators, rather than the trace norm of its Choi state. +Trace preservation gives $`\mathrm{Tr}_{\mathrm{output}}J_{\mathcal E}=I/d`$. Unitality gives the other marginal, $`\mathrm{Tr}_{\mathrm{input}}J_{\mathcal E}=I/d`$. Both identities enter the compiler's second-moment calculation. Theorem 4.27 gives $`\VertL_{\mathcal E}\Vert_\infty=1`$ for a unital channel; this is the spectral norm of its matrix, corresponding to the induced Hilbert–Schmidt norm on operators, rather than the trace norm of its Choi state. ### Distance and fidelity -The project's $`\|\cdot\|_\diamond`$ is Watrous's completely bounded trace norm, without a factor of one half. For states, write $`D(\rho,\sigma)=\tfrac12\|\rho-\sigma\|_1`$. Consequently a compiler guarantee of unhalved diamond error $`\delta`$ implies output trace distance at most $`\delta/2`$, even with an untouched reference. Any specified measurement probability changes by at most $`\delta/2`$. +The project's $`\Vert\cdot\Vert_\diamond`$ is Watrous's completely bounded trace norm, without a factor of one half. For states, write $`D(\rho,\sigma)=\tfrac12\Vert\rho-\sigma\Vert_1`$. Consequently a compiler guarantee of unhalved diamond error $`\delta`$ implies output trace distance at most $`\delta/2`$, even with an untouched reference. Any specified measurement probability changes by at most $`\delta/2`$. Watrous's Definition 3.11 uses the **unsquared** fidelity ```math -F_{\mathrm W}(\rho,\sigma)=\|\sqrt\rho\sqrt\sigma\|_1. +F_{\mathrm W}(\rho,\sigma)=\Vert\sqrt\rho\sqrt\sigma\Vert_1. ``` The lower bound instead uses overlap with the pure normalized Choi state of the ideal unitary: diff --git a/references/RELATED_WORK.md b/references/RELATED_WORK.md index 24feb00..e39a5dc 100644 --- a/references/RELATED_WORK.md +++ b/references/RELATED_WORK.md @@ -28,7 +28,7 @@ Wei, Liu, Liu, Han, Deng and Liu, *Simulating non-completely positive actions vi Their general sample bound uses the norm of the joint interaction. Appendix C2 goes further for partial transposition: Proposition 3 improves the bound to $`O(d_A t^2/\epsilon)`$, and Eq. (C17) explicitly retains ```math -d_A\|\operatorname{Tr}_B\rho\|_\infty +d_A\Vert\mathrm{Tr}_B\rho\Vert_\infty ``` before bounding it by $`d_A`$. Their convolution inequality and parity analysis already exhibit the relevance of reduced program states. The present account therefore credits marginal-sensitive exponentiation to this prior work; it does not introduce that observation as a new principle. @@ -36,10 +36,10 @@ before bounding it by $`d_A`$. Their convolution inequality and parity analysis The all-time collision estimate used here is also inherited. The public proof in [*Collective Quantum Programming*, `science/collision_bound.md`, revision `0fefb607599f9c864918ed1ab58a778fe5b50cf1`](https://github.com/GoGoKo699/Collective-Quantum-Programming/blob/0fefb607599f9c864918ed1ab58a778fe5b50cf1/science/collision_bound.md) establishes ```math -\|\Phi_\tau-\operatorname{Ad}_{e^{-i\tau h}}\|_\diamond +\Vert\Phi_\tau-\mathrm{Ad}_{e^{-i\tau h}}\Vert_\diamond \le2\tau^2 -\left\|\mathcal E_\sigma(V^2) --\mathcal E_\sigma(V)^2\right\|_\infty, +\left\Vert\mathcal E_\sigma(V^2) +-\mathcal E_\sigma(V)^2\right\Vert_\infty, \qquad h=\mathcal E_\sigma(V), ``` diff --git a/science/block-encoding.md b/science/block-encoding.md index 422b034..eccb1e1 100644 --- a/science/block-encoding.md +++ b/science/block-encoding.md @@ -21,8 +21,8 @@ For every unital channel $`\mathcal E`$ on $`\mathbb C^d`$ and every $`0<\delta\ (\langle0^a|\otimes I)V_{\mathcal E} (|0^a\rangle\otimes I)=A, \qquad -\left\|\widetilde{\mathcal V}_{\mathcal E} --\operatorname{Ad}_{V_{\mathcal E}}\right\|_\diamond +\left\Vert\widetilde{\mathcal V}_{\mathcal E} +-\mathrm{Ad}_{V_{\mathcal E}}\right\Vert_\diamond \le\delta. ``` @@ -39,7 +39,7 @@ The physical implementation additionally uses one disposable Choi-based program ## An exact sine block -Unitality gives $`\|H_0\|_\infty\le1/2`$. Define +Unitality gives $`\VertH_0\Vert_\infty\le1/2`$. Define ```math U=e^{-iH_0}, @@ -106,10 +106,10 @@ Real-polynomial singular value transformation, Corollary 18 of that work, applie B=P_m(\sin H_0). ``` -For a Hermitian input and an odd polynomial, singular value transformation agrees with the Hermitian polynomial functional calculus. Thus $`B`$ is Hermitian and commutes with $`H_0`$ and $`A`$. Since $`\|\sin H_0\|\le\sin(1/2)<1/2`$ and $`\arcsin(\sin H_0)=H_0`$, +For a Hermitian input and an odd polynomial, singular value transformation agrees with the Hermitian polynomial functional calculus. Thus $`B`$ is Hermitian and commutes with $`H_0`$ and $`A`$. Since $`\Vert\sin H_0\Vert\le\sin(1/2)<1/2`$ and $`\arcsin(\sin H_0)=H_0`$, ```math -\|B-A\|_\infty\le\zeta. +\VertB-A\Vert_\infty\le\zeta. ``` There is also a useful strict contraction bound. For $`0\le h\le1/2`$, positivity of the Taylor coefficients gives @@ -120,7 +120,7 @@ There is also a useful strict contraction bound. For $`0\le h\le1/2`$, positivit =\frac2\pi h. ``` -Oddness handles negative $`h`$. Consequently $`\|A\|_\infty,\|B\|_\infty\le1/\pi<1/2`$. The ideal QSVT circuit uses $`O(q)`$ occurrences of controlled $`U`$ and its inverse, together with known operations. +Oddness handles negative $`h`$. Consequently $`\VertA\Vert_\infty,\VertB\Vert_\infty\le1/\pi<1/2`$. The ideal QSVT circuit uses $`O(q)`$ occurrences of controlled $`U`$ and its inverse, together with known operations. ## Stable completion of the whole unitary @@ -133,7 +133,7 @@ V=\begin{pmatrix}B&C\\D&E\end{pmatrix} \quad\text{on }\mathcal D\oplus\mathcal K. ``` -Put $`S_B=\sqrt{I-B^2}`$. It is invertible because $`\|B\|<1`$. The unitary relations imply +Put $`S_B=\sqrt{I-B^2}`$. It is invertible because $`\VertB\Vert<1`$. The unitary relations imply ```math CC^\dagger=S_B^2, @@ -170,12 +170,12 @@ The operator $`V_A`$ is unitary and its designated block is exactly $`A`$. Since ```math \begin{aligned} -\|V_A-V\|_\infty -&=\|J_A-J_B\|_\infty\\ -&\le\max_{(a,b)\in\operatorname{joint\,spec}(A,B)} +\VertV_A-V\Vert_\infty +&=\VertJ_A-J_B\Vert_\infty\\ +&\le\max_{(a,b)\in\mathrm{joint\,spec}(A,B)} \sqrt{(a-b)^2+ \left(\sqrt{1-a^2}-\sqrt{1-b^2}\right)^2}\\ -&\le\frac2{\sqrt3}\|A-B\|_\infty +&\le\frac2{\sqrt3}\VertA-B\Vert_\infty <2\zeta. \end{aligned} ``` @@ -183,15 +183,15 @@ The operator $`V_A`$ is unitary and its designated block is exactly $`A`$. Since For any two unitaries $`W_1,W_2`$, adjoining an arbitrary reference and expanding the two conjugations gives ```math -\|\operatorname{Ad}_{W_1}-\operatorname{Ad}_{W_2}\|_\diamond -\le2\|W_1-W_2\|_\infty. +\Vert\mathrm{Ad}_{W_1}-\mathrm{Ad}_{W_2}\Vert_\diamond +\le2\VertW_1-W_2\Vert_\infty. ``` Apply this completion to $`V=V_P`$ and denote the resulting $`V_A`$ by $`V_{\mathcal E}`$. It follows that ```math -\|\operatorname{Ad}_{V_P} --\operatorname{Ad}_{V_{\mathcal E}}\|_\diamond +\Vert\mathrm{Ad}_{V_P} +-\mathrm{Ad}_{V_{\mathcal E}}\Vert_\diamond \le4\zeta=\delta/2. ``` @@ -208,8 +208,8 @@ Let $`r\le c_0q`$ be the number of controlled-evolution primitives in a fixed QS The collision compiler at time $`1/2`$, with any needed extra controls, uses $`O(d^2/\eta)`$ ordinary calls per primitive. Contractivity and telescoping over the $`r`$ occurrences give ```math -\|\widetilde{\mathcal V}_{\mathcal E} --\operatorname{Ad}_{V_P}\|_\diamond +\Vert\widetilde{\mathcal V}_{\mathcal E} +-\mathrm{Ad}_{V_P}\Vert_\diamond \le r\eta\le\delta/2. ``` @@ -226,20 +226,20 @@ The programs are prepared using unconditional calls to $`\mathcal E`$. Coherent ## Inverse and controlled versions -Reverse the ideal QSVT circuit and replace every ideal controlled evolution by the inverse-time collision construction. This produces a physical channel close to $`\operatorname{Ad}_{V_P^\dagger}`$ with the same error and query bounds. The same stable completion already fixed $`V_{\mathcal E}`$, and +Reverse the ideal QSVT circuit and replace every ideal controlled evolution by the inverse-time collision construction. This produces a physical channel close to $`\mathrm{Ad}_{V_P^\dagger}`$ with the same error and query bounds. The same stable completion already fixed $`V_{\mathcal E}`$, and ```math -\|V_P^\dagger-V_{\mathcal E}^\dagger\|_\infty -=\|V_P-V_{\mathcal E}\|_\infty. +\VertV_P^\dagger-V_{\mathcal E}^\dagger\Vert_\infty +=\VertV_P-V_{\mathcal E}\Vert_\infty. ``` -Therefore the inverse implementation is $`\delta`$-close to $`\operatorname{Ad}_{V_{\mathcal E}^\dagger}`$ for that same exact comparison unitary. +Therefore the inverse implementation is $`\delta`$-close to $`\mathrm{Ad}_{V_{\mathcal E}^\dagger}`$ for that same exact comparison unitary. Likewise, coherently control the known ideal QSVT sequence and its constituent compiled evolutions. Since ```math -\|C_{V_P}-C_{V_{\mathcal E}}\|_\infty -=\|V_P-V_{\mathcal E}\|_\infty, +\VertC_{V_P}-C_{V_{\mathcal E}}\Vert_\infty +=\VertV_P-V_{\mathcal E}\Vert_\infty, ``` the resulting channel is $`\delta`$-close to the controlled version of the same $`V_{\mathcal E}`$. These controls and inverses are output capabilities of the compiler. They do not assert that an arbitrary approximate physical channel can be inverted or controlled after the fact. diff --git a/science/collision-compiler.md b/science/collision-compiler.md index 07dc0c1..8fbc3df 100644 --- a/science/collision-compiler.md +++ b/science/collision-compiler.md @@ -9,15 +9,15 @@ The construction below implements the full target from [the model](model.md), wi Let $`\mathcal E`$ be any unital channel on a $`d`$-dimensional system, and let $`m\ge1`$ be an integer. For every real $`t`$, there is a circuit using exactly $`2m`$ ordinary calls to $`\mathcal E`$ whose output channel $`\widetilde{\mathcal U}_{\mathcal E,t}^{(m)}`$ satisfies ```math -\left\| +\left\Vert \widetilde{\mathcal U}_{\mathcal E,t}^{(m)} --\operatorname{Ad}_{e^{-it\mathsf H(L_{\mathcal E})}} -\right\|_\diamond +-\mathrm{Ad}_{e^{-it\mathsf H(L_{\mathcal E})}} +\right\Vert_\diamond \le \min\!\left\{2,\frac{(4d^2+2)t^2}{m}\right\}. ``` -Here $`\operatorname{Ad}_W(X)=WXW^\dagger`$. The known gates in this theorem are exact. For $`t\ne0`$ and $`0<\epsilon<2`$, the choice +Here $`\mathrm{Ad}_W(X)=WXW^\dagger`$. The known gates in this theorem are exact. For $`t\ne0`$ and $`0<\epsilon<2`$, the choice ```math m=\left\lceil\frac{(4d^2+2)t^2}{\epsilon}\right\rceil @@ -46,13 +46,13 @@ The partial-trace expressions agree with sandwiching $`V`$ or $`V^2`$ by $`\rho^ =\mathrm{Tr}_{\mathrm{prog}} \left[e^{-ihV}(\rho\otimes X)e^{ihV}\right], \qquad -v=\|M-K^2\|_\infty. +v=\VertM-K^2\Vert_\infty. ``` For every real $`h`$, ```math -\|\mathcal C_{\rho,h}-\operatorname{Ad}_{e^{-ihK}}\|_\diamond +\Vert\mathcal C_{\rho,h}-\mathrm{Ad}_{e^{-ihK}}\Vert_\diamond \le2h^2v. ``` @@ -63,7 +63,7 @@ W^\dagger VW=K, \qquad W^\dagger V^2W=M, \qquad -\|QVW\|_\infty^2=v. +\VertQVW\Vert_\infty^2=v. ``` It is enough to take $`h\ge0`$; changing $`V`$ to $`-V`$ handles negative time. Put @@ -79,7 +79,7 @@ The projected Schrödinger equations and variation of constants give ```math B_s=-i\int_0^s e^{-i(s-r)QVQ}QVWA_r\,dr, \qquad -\|B_s\|_\infty\le s\sqrt v, +\VertB_s\Vert_\infty\le s\sqrt v, ``` because $`A_r`$ is a compression of a unitary and is a contraction. The equation for $`A_s`$ then gives @@ -88,7 +88,7 @@ because $`A_r`$ is a compression of a unitary and is a contraction. The equation A_h-e^{-ihK} =-i\int_0^h e^{-i(h-r)K}W^\dagger VQB_r\,dr, \qquad -\|A_h-e^{-ihK}\|_\infty\le\frac{h^2v}{2}. +\VertA_h-e^{-ihK}\Vert_\infty\le\frac{h^2v}{2}. ``` In a basis of the enlarged environment beginning with $`|s\rangle`$, tracing out that environment removes the cross terms between $`P`$ and $`Q`$. Thus @@ -99,7 +99,7 @@ In a basis of the enlarged environment beginning with $`|s\rangle`$, tracing out \mathcal B_h(X)=\mathrm{Tr}_{\mathrm{env}}[B_hXB_h^\dagger]. ``` -The leakage map $`\mathcal B_h`$ is completely positive, so $`\|\mathcal B_h\|_\diamond=\|B_h^\dagger B_h\|_\infty\le h^2v`$. The compressed term differs from $`\operatorname{Ad}_{e^{-ihK}}`$ by at most $`(\|A_h\|_\infty+1)\|A_h-e^{-ihK}\|_\infty\le h^2v`$ in diamond norm. These product bounds remain valid after adjoining an arbitrary reference. Adding the two contributions proves the lemma for all real $`h`$. +The leakage map $`\mathcal B_h`$ is completely positive, so $`\Vert\mathcal B_h\Vert_\diamond=\VertB_h^\dagger B_h\Vert_\infty\le h^2v`$. The compressed term differs from $`\mathrm{Ad}_{e^{-ihK}}`$ by at most $`(\VertA_h\Vert_\infty+1)\VertA_h-e^{-ihK}\Vert_\infty\le h^2v`$ in diamond norm. These product bounds remain valid after adjoining an arbitrary reference. Adding the two contributions proves the lemma for all real $`h`$. ## Programs and their first moments @@ -184,17 +184,17 @@ M_\pm =I_{A'B'}. ``` -It follows that $`v_\pm=\|I-K_\pm^2\|_\infty\le1`$. The inherited variance lemma now gives the uniform local guarantee +It follows that $`v_\pm=\VertI-K_\pm^2\Vert_\infty\le1`$. The inherited variance lemma now gives the uniform local guarantee ```math -\|\mathcal C_{\rho_\pm,h} --\operatorname{Ad}_{e^{-ihK_\pm}}\|_\diamond +\Vert\mathcal C_{\rho_\pm,h} +-\mathrm{Ad}_{e^{-ihK_\pm}}\Vert_\diamond \le2h^2 ``` for every real step $`h`$. Replacing this evaluated moment by a worst-case interaction bound would discard the flat-marginal information. -For the product-formula constant, we also use $`\|K_\pm\|_\infty\le1/d`$. Here is a direct reason. For any bipartite state $`\rho_{AB}`$, the maps $`X\mapsto\mathrm{Tr}(X)I\pm X^T`$ are completely positive because their Choi matrices are $`I\pm F`$. Applying either map on $`A`$ to the positive matrix $`\rho^{T_{AB}}`$ proves +For the product-formula constant, we also use $`\VertK_\pm\Vert_\infty\le1/d`$. Here is a direct reason. For any bipartite state $`\rho_{AB}`$, the maps $`X\mapsto\mathrm{Tr}(X)I\pm X^T`$ are completely positive because their Choi matrices are $`I\pm F`$. Applying either map on $`A`$ to the positive matrix $`\rho^{T_{AB}}`$ proves ```math -I_A\otimes\rho_B^T @@ -202,7 +202,7 @@ For the product-formula constant, we also use $`\|K_\pm\|_\infty\le1/d`$. Here i \preceq I_A\otimes\rho_B^T. ``` -Thus $`\|\rho^{T_B}\|_\infty\le\|\rho_B\|_\infty`$. Substituting $`\rho_B=I/d`$ gives the required bound for both programs. +Thus $`\Vert\rho^{T_B}\Vert_\infty\le\Vert\rho_B\Vert_\infty`$. Substituting $`\rho_B=I/d`$ gives the required bound for both programs. ## Pairing, product formula, and total error @@ -218,23 +218,23 @@ Its ideal product is the unitary channel of $`e^{ihK_-}e^{-ihK_+}`$. Channel com For Hermitian $`A,B`$, the first-order unitary product formula obeys ```math -\|e^{-ihA}e^{-ihB}-e^{-ih(A+B)}\|_\infty -\le\frac{h^2}{2}\|[A,B]\|_\infty. +\Verte^{-ihA}e^{-ihB}-e^{-ih(A+B)}\Vert_\infty +\le\frac{h^2}{2}\Vert[A,B]\Vert_\infty. ``` This follows by differentiating an interpolating product and integrating the commutator once more; the surrounding factors are unitary, so the estimate holds for all real $`h`$. Passing to channels multiplies this operator bound by at most $`2`$. With $`A=-K_-`$ and $`B=K_+`$, ```math -\|[K_+,K_-]\|_\infty -\le2\|K_+\|_\infty\|K_-\|_\infty +\Vert[K_+,K_-]\Vert_\infty +\le2\VertK_+\Vert_\infty\VertK_-\Vert_\infty \le2/d^2. ``` Combining collision and product-formula errors gives ```math -\left\|\mathcal P_h --\operatorname{Ad}_{e^{-ih(K_+-K_-)}}\right\|_\diamond +\left\Vert\mathcal P_h +-\mathrm{Ad}_{e^{-ih(K_+-K_-)}}\right\Vert_\diamond \le(4+2/d^2)h^2. ``` @@ -242,20 +242,20 @@ Take $`h=dt/m`$, prepare fresh programs for every collision, and set ```math \widetilde{\mathcal U}_{\mathcal E,t}^{(m)} -=\operatorname{Ad}_S\circ\mathcal P_{dt/m}^{\,m} -\circ\operatorname{Ad}_S. +=\mathrm{Ad}_S\circ\mathcal P_{dt/m}^{\,m} +\circ\mathrm{Ad}_S. ``` Telescoping the $`m`$ channel differences gives ```math -\left\|\mathcal P_{dt/m}^{\,m} --\operatorname{Ad}_{e^{-idt(K_+-K_-)}}\right\|_\diamond +\left\Vert\mathcal P_{dt/m}^{\,m} +-\mathrm{Ad}_{e^{-idt(K_+-K_-)}}\right\Vert_\diamond \le m(4+2/d^2)\frac{d^2t^2}{m^2} =\frac{(4d^2+2)t^2}{m}. ``` -The first-moment identity and $`S^2=I`$ turn the ideal channel after the two outer conjugations into $`\operatorname{Ad}_{e^{-it\mathsf H(L_{\mathcal E})}}`$. There are two fresh one-query programs per pair, proving the stated $`2m`$-query theorem. +The first-moment identity and $`S^2=I`$ turn the ideal channel after the two outer conjugations into $`\mathrm{Ad}_{e^{-it\mathsf H(L_{\mathcal E})}}`$. There are two fresh one-query programs per pair, proving the stated $`2m`$-query theorem. ## Coherent control and negative time diff --git a/science/dimension-lower-bound.md b/science/dimension-lower-bound.md index 6763503..6e13cd0 100644 --- a/science/dimension-lower-bound.md +++ b/science/dimension-lower-bound.md @@ -36,7 +36,7 @@ For a deterministic ordinary-query algorithm $`\mathcal R`$ that makes at most $ ```math \mathbb E_{U\sim\mathrm{Haar}} -F_{\mathrm{ch}}(\mathcal R_U,\operatorname{Ad}_{U^{\dagger}}) +F_{\mathrm{ch}}(\mathcal R_U,\mathrm{Ad}_{U^{\dagger}}) \le\frac{q+1}{d^2}. ``` @@ -49,10 +49,10 @@ We use this fidelity bound directly. This matters when extracting an inverse fro Suppose a $`q`$-query compiler produces $`\widetilde{\mathcal V}_{\mathcal E}`$ satisfying ```math -\left\| +\left\Vert \widetilde{\mathcal V}_{\mathcal E} --\operatorname{Ad}_{e^{-i(\pi/2)\mathsf H_{\mathcal E}}} -\right\|_{\diamond}\le\delta +-\mathrm{Ad}_{e^{-i(\pi/2)\mathsf H_{\mathcal E}}} +\right\Vert_{\diamond}\le\delta ``` for every unital $`\mathcal E`$. On the unitary family, @@ -70,14 +70,14 @@ Prepare the dilation flag in $`|0\rangle`$, place an arbitrary target state in t \otimes U^{\mathsf T}|0\rangle. ``` -Discarding the flag and the second register therefore implements $`\operatorname{Ad}_{U^{\dagger}}`$. The same statement holds with a target reference system: the discarded output is independent of the target and its reference. Diamond distance is contractive under this initialization and discarding, so the actual inverse channel has error at most $`\delta`$. +Discarding the flag and the second register therefore implements $`\mathrm{Ad}_{U^{\dagger}}`$. The same statement holds with a target reference system: the discarded output is independent of the target and its reference. Diamond distance is contractive under this initialization and discarding, so the actual inverse channel has error at most $`\delta`$. If a channel $`\mathcal R_U`$ has diamond distance at most $`\delta`$ from the desired unitary, its normalized Choi state $`\rho_U`$ satisfies ```math -1-F_{\mathrm{ch}}(\mathcal R_U,\operatorname{Ad}_{U^{\dagger}}) -\le\frac12\left\|\rho_U- -|u^{-1}\rangle\langle u^{-1}|\right\|_1 +1-F_{\mathrm{ch}}(\mathcal R_U,\mathrm{Ad}_{U^{\dagger}}) +\le\frac12\left\Vert\rho_U- +|u^{-1}\rangle\langle u^{-1}|\right\Vert_1 \le\frac\delta2. ``` @@ -101,8 +101,8 @@ The same conclusion holds for the block-encoding output used by spectral algorit The unspecified blocks of $`W_{\mathcal E}`$ may depend on the channel. Suppose an ordinary-query compiler produces $`\widetilde{\mathcal W}_{\mathcal E}`$ such that ```math -\left\|\widetilde{\mathcal W}_{\mathcal E} --\operatorname{Ad}_{W_{\mathcal E}}\right\|_{\diamond}\le\delta. +\left\Vert\widetilde{\mathcal W}_{\mathcal E} +-\mathrm{Ad}_{W_{\mathcal E}}\right\Vert_{\diamond}\le\delta. ``` Apply this output channel once, initializing its block ancilla in $`|0^a\rangle`$ and the remaining registers as in the previous construction. Measure whether the block ancilla returns to $`0^a`$. In the ideal channel this outcome has probability exactly $`c^2`$, independent of the target, because $`\mathsf H_U`$ is unitary. On this outcome the first data register is the desired $`U^{\dagger}`$ output. On failure discard the data and prepare an arbitrary fixed state. This completes the protocol to a deterministic channel without any further oracle call. @@ -111,14 +111,14 @@ For the ideal block unitary, the completed inverse channel has the form ```math \mathcal R_U^{\mathrm{ideal}} -=c^2\operatorname{Ad}_{U^{\dagger}} +=c^2\mathrm{Ad}_{U^{\dagger}} +(1-c^2)\mathcal F_U ``` for some channel $`\mathcal F_U`$. Its channel fidelity with the desired inverse is at least $`c^2`$, since the contribution of the failure channel is nonnegative. The identical completion applied to the actual output channel stays within $`\delta`$ of this ideal completion. Testing the ideal inverse Choi projector therefore gives ```math -F_{\mathrm{ch}}(\mathcal R_U,\operatorname{Ad}_{U^{\dagger}}) +F_{\mathrm{ch}}(\mathcal R_U,\mathrm{Ad}_{U^{\dagger}}) \ge c^2-\frac\delta2. ``` diff --git a/science/model.md b/science/model.md index 87a4649..ca622ad 100644 --- a/science/model.md +++ b/science/model.md @@ -63,14 +63,14 @@ U_{\mathcal E}(t)=e^{-it\mathsf H(L_{\mathcal E})}, There is no factor $`1/2`$, $`1/d`$, or hidden block normalization in this definition. The flag and the two vectorization registers have total dimension $`2d^2`$. The output must work on arbitrary data inputs, including inputs entangled with an untouched reference system. -For a unital channel, $`\|L_{\mathcal E}\|_\infty=1`$. Indeed, the Schwarz inequality for unital completely positive maps gives +For a unital channel, $`\VertL_{\mathcal E}\Vert_\infty=1`$. Indeed, the Schwarz inequality for unital completely positive maps gives ```math \mathcal E(X)^\dagger\mathcal E(X) \preceq\mathcal E(X^\dagger X). ``` -Taking the trace and using trace preservation proves Hilbert-Schmidt contraction, so $`\|L_{\mathcal E}\|_\infty\le1`$. The fixed vector $`|I\rangle\!\rangle`$ gives equality. Consequently $`\|\mathsf H(L_{\mathcal E})\|_\infty=1`$. This explains why the unnormalized target already has a dimension-independent Hamiltonian norm in the present class. +Taking the trace and using trace preservation proves Hilbert-Schmidt contraction, so $`\VertL_{\mathcal E}\Vert_\infty\le1`$. The fixed vector $`|I\rangle\!\rangle`$ gives equality. Consequently $`\Vert\mathsf H(L_{\mathcal E})\Vert_\infty=1`$. This explains why the unnormalized target already has a dimension-independent Hamiltonian norm in the present class. ## Access and charged resources @@ -85,12 +85,12 @@ The primary resource bound counts ordinary channel calls. Preparing the known en All diamond distances are **unhalved**. For a linear map $`\Lambda`$, ```math -\|\Lambda\|_\diamond +\Vert\Lambda\Vert_\diamond =\sup_{r\ge1}\sup_{X\ne0} -\frac{\|(\Lambda\otimes\mathrm{id}_r)(X)\|_1}{\|X\|_1}. +\frac{\Vert(\Lambda\otimes\mathrm{id}_r)(X)\Vert_1}{\VertX\Vert_1}. ``` -In particular, the diamond distance between two channels is at most $`2`$. The compiler's guarantee is $`\|\widetilde{\mathcal U}_{\mathcal E,t}-\mathcal U_{\mathcal E,t}\|_\diamond\le\epsilon`$, with this convention. It is a uniform channel guarantee, rather than a bound for one chosen input or one observable. +In particular, the diamond distance between two channels is at most $`2`$. The compiler's guarantee is $`\Vert\widetilde{\mathcal U}_{\mathcal E,t}-\mathcal U_{\mathcal E,t}\Vert_\diamond\le\epsilon`$, with this convention. It is a uniform channel guarantee, rather than a bound for one chosen input or one observable. ## Relation to the existing construction From 49035bae3f66515f5d7430701a820bf2321217da Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Sun, 15 Nov 2026 23:00:30 +0800 Subject: [PATCH 3/5] Separate explicit norm control words from adjacent operands --- learning/WATROUS_BRIDGE.md | 2 +- science/block-encoding.md | 24 ++++++++++++------------ science/collision-compiler.md | 18 +++++++++--------- science/model.md | 6 +++--- 4 files changed, 25 insertions(+), 25 deletions(-) diff --git a/learning/WATROUS_BRIDGE.md b/learning/WATROUS_BRIDGE.md index cef0e0c..817ef92 100644 --- a/learning/WATROUS_BRIDGE.md +++ b/learning/WATROUS_BRIDGE.md @@ -49,7 +49,7 @@ For a trace-preserving map, the book's Choi operator has trace $`d`$; the projec \!\left[J_{\mathcal E}(I_{\mathrm{output}}\otimes X^{\mathsf T})\right]. ``` -Trace preservation gives $`\mathrm{Tr}_{\mathrm{output}}J_{\mathcal E}=I/d`$. Unitality gives the other marginal, $`\mathrm{Tr}_{\mathrm{input}}J_{\mathcal E}=I/d`$. Both identities enter the compiler's second-moment calculation. Theorem 4.27 gives $`\VertL_{\mathcal E}\Vert_\infty=1`$ for a unital channel; this is the spectral norm of its matrix, corresponding to the induced Hilbert–Schmidt norm on operators, rather than the trace norm of its Choi state. +Trace preservation gives $`\mathrm{Tr}_{\mathrm{output}}J_{\mathcal E}=I/d`$. Unitality gives the other marginal, $`\mathrm{Tr}_{\mathrm{input}}J_{\mathcal E}=I/d`$. Both identities enter the compiler's second-moment calculation. Theorem 4.27 gives $`\Vert L_{\mathcal E}\Vert_\infty=1`$ for a unital channel; this is the spectral norm of its matrix, corresponding to the induced Hilbert–Schmidt norm on operators, rather than the trace norm of its Choi state. ### Distance and fidelity diff --git a/science/block-encoding.md b/science/block-encoding.md index eccb1e1..071ec3f 100644 --- a/science/block-encoding.md +++ b/science/block-encoding.md @@ -39,7 +39,7 @@ The physical implementation additionally uses one disposable Choi-based program ## An exact sine block -Unitality gives $`\VertH_0\Vert_\infty\le1/2`$. Define +Unitality gives $`\Vert H_0\Vert_\infty\le1/2`$. Define ```math U=e^{-iH_0}, @@ -109,7 +109,7 @@ B=P_m(\sin H_0). For a Hermitian input and an odd polynomial, singular value transformation agrees with the Hermitian polynomial functional calculus. Thus $`B`$ is Hermitian and commutes with $`H_0`$ and $`A`$. Since $`\Vert\sin H_0\Vert\le\sin(1/2)<1/2`$ and $`\arcsin(\sin H_0)=H_0`$, ```math -\VertB-A\Vert_\infty\le\zeta. +\Vert B-A\Vert_\infty\le\zeta. ``` There is also a useful strict contraction bound. For $`0\le h\le1/2`$, positivity of the Taylor coefficients gives @@ -120,7 +120,7 @@ There is also a useful strict contraction bound. For $`0\le h\le1/2`$, positivit =\frac2\pi h. ``` -Oddness handles negative $`h`$. Consequently $`\VertA\Vert_\infty,\VertB\Vert_\infty\le1/\pi<1/2`$. The ideal QSVT circuit uses $`O(q)`$ occurrences of controlled $`U`$ and its inverse, together with known operations. +Oddness handles negative $`h`$. Consequently $`\Vert A\Vert_\infty,\Vert B\Vert_\infty\le1/\pi<1/2`$. The ideal QSVT circuit uses $`O(q)`$ occurrences of controlled $`U`$ and its inverse, together with known operations. ## Stable completion of the whole unitary @@ -133,7 +133,7 @@ V=\begin{pmatrix}B&C\\D&E\end{pmatrix} \quad\text{on }\mathcal D\oplus\mathcal K. ``` -Put $`S_B=\sqrt{I-B^2}`$. It is invertible because $`\VertB\Vert<1`$. The unitary relations imply +Put $`S_B=\sqrt{I-B^2}`$. It is invertible because $`\Vert B\Vert<1`$. The unitary relations imply ```math CC^\dagger=S_B^2, @@ -170,12 +170,12 @@ The operator $`V_A`$ is unitary and its designated block is exactly $`A`$. Since ```math \begin{aligned} -\VertV_A-V\Vert_\infty -&=\VertJ_A-J_B\Vert_\infty\\ +\Vert V_A-V\Vert_\infty +&=\Vert J_A-J_B\Vert_\infty\\ &\le\max_{(a,b)\in\mathrm{joint\,spec}(A,B)} \sqrt{(a-b)^2+ \left(\sqrt{1-a^2}-\sqrt{1-b^2}\right)^2}\\ -&\le\frac2{\sqrt3}\VertA-B\Vert_\infty +&\le\frac2{\sqrt3}\Vert A-B\Vert_\infty <2\zeta. \end{aligned} ``` @@ -184,7 +184,7 @@ For any two unitaries $`W_1,W_2`$, adjoining an arbitrary reference and expandin ```math \Vert\mathrm{Ad}_{W_1}-\mathrm{Ad}_{W_2}\Vert_\diamond -\le2\VertW_1-W_2\Vert_\infty. +\le2\Vert W_1-W_2\Vert_\infty. ``` Apply this completion to $`V=V_P`$ and denote the resulting $`V_A`$ by $`V_{\mathcal E}`$. It follows that @@ -229,8 +229,8 @@ The programs are prepared using unconditional calls to $`\mathcal E`$. Coherent Reverse the ideal QSVT circuit and replace every ideal controlled evolution by the inverse-time collision construction. This produces a physical channel close to $`\mathrm{Ad}_{V_P^\dagger}`$ with the same error and query bounds. The same stable completion already fixed $`V_{\mathcal E}`$, and ```math -\VertV_P^\dagger-V_{\mathcal E}^\dagger\Vert_\infty -=\VertV_P-V_{\mathcal E}\Vert_\infty. +\Vert V_P^\dagger-V_{\mathcal E}^\dagger\Vert_\infty +=\Vert V_P-V_{\mathcal E}\Vert_\infty. ``` Therefore the inverse implementation is $`\delta`$-close to $`\mathrm{Ad}_{V_{\mathcal E}^\dagger}`$ for that same exact comparison unitary. @@ -238,8 +238,8 @@ Therefore the inverse implementation is $`\delta`$-close to $`\mathrm{Ad}_{V_{\m Likewise, coherently control the known ideal QSVT sequence and its constituent compiled evolutions. Since ```math -\VertC_{V_P}-C_{V_{\mathcal E}}\Vert_\infty -=\VertV_P-V_{\mathcal E}\Vert_\infty, +\Vert C_{V_P}-C_{V_{\mathcal E}}\Vert_\infty +=\Vert V_P-V_{\mathcal E}\Vert_\infty, ``` the resulting channel is $`\delta`$-close to the controlled version of the same $`V_{\mathcal E}`$. These controls and inverses are output capabilities of the compiler. They do not assert that an arbitrary approximate physical channel can be inverted or controlled after the fact. diff --git a/science/collision-compiler.md b/science/collision-compiler.md index 8fbc3df..9451ac3 100644 --- a/science/collision-compiler.md +++ b/science/collision-compiler.md @@ -46,7 +46,7 @@ The partial-trace expressions agree with sandwiching $`V`$ or $`V^2`$ by $`\rho^ =\mathrm{Tr}_{\mathrm{prog}} \left[e^{-ihV}(\rho\otimes X)e^{ihV}\right], \qquad -v=\VertM-K^2\Vert_\infty. +v=\Vert M-K^2\Vert_\infty. ``` For every real $`h`$, @@ -63,7 +63,7 @@ W^\dagger VW=K, \qquad W^\dagger V^2W=M, \qquad -\VertQVW\Vert_\infty^2=v. +\Vert QVW\Vert_\infty^2=v. ``` It is enough to take $`h\ge0`$; changing $`V`$ to $`-V`$ handles negative time. Put @@ -79,7 +79,7 @@ The projected Schrödinger equations and variation of constants give ```math B_s=-i\int_0^s e^{-i(s-r)QVQ}QVWA_r\,dr, \qquad -\VertB_s\Vert_\infty\le s\sqrt v, +\Vert B_s\Vert_\infty\le s\sqrt v, ``` because $`A_r`$ is a compression of a unitary and is a contraction. The equation for $`A_s`$ then gives @@ -88,7 +88,7 @@ because $`A_r`$ is a compression of a unitary and is a contraction. The equation A_h-e^{-ihK} =-i\int_0^h e^{-i(h-r)K}W^\dagger VQB_r\,dr, \qquad -\VertA_h-e^{-ihK}\Vert_\infty\le\frac{h^2v}{2}. +\Vert A_h-e^{-ihK}\Vert_\infty\le\frac{h^2v}{2}. ``` In a basis of the enlarged environment beginning with $`|s\rangle`$, tracing out that environment removes the cross terms between $`P`$ and $`Q`$. Thus @@ -99,7 +99,7 @@ In a basis of the enlarged environment beginning with $`|s\rangle`$, tracing out \mathcal B_h(X)=\mathrm{Tr}_{\mathrm{env}}[B_hXB_h^\dagger]. ``` -The leakage map $`\mathcal B_h`$ is completely positive, so $`\Vert\mathcal B_h\Vert_\diamond=\VertB_h^\dagger B_h\Vert_\infty\le h^2v`$. The compressed term differs from $`\mathrm{Ad}_{e^{-ihK}}`$ by at most $`(\VertA_h\Vert_\infty+1)\VertA_h-e^{-ihK}\Vert_\infty\le h^2v`$ in diamond norm. These product bounds remain valid after adjoining an arbitrary reference. Adding the two contributions proves the lemma for all real $`h`$. +The leakage map $`\mathcal B_h`$ is completely positive, so $`\Vert\mathcal B_h\Vert_\diamond=\Vert B_h^\dagger B_h\Vert_\infty\le h^2v`$. The compressed term differs from $`\mathrm{Ad}_{e^{-ihK}}`$ by at most $`(\Vert A_h\Vert_\infty+1)\Vert A_h-e^{-ihK}\Vert_\infty\le h^2v`$ in diamond norm. These product bounds remain valid after adjoining an arbitrary reference. Adding the two contributions proves the lemma for all real $`h`$. ## Programs and their first moments @@ -184,7 +184,7 @@ M_\pm =I_{A'B'}. ``` -It follows that $`v_\pm=\VertI-K_\pm^2\Vert_\infty\le1`$. The inherited variance lemma now gives the uniform local guarantee +It follows that $`v_\pm=\Vert I-K_\pm^2\Vert_\infty\le1`$. The inherited variance lemma now gives the uniform local guarantee ```math \Vert\mathcal C_{\rho_\pm,h} @@ -194,7 +194,7 @@ It follows that $`v_\pm=\VertI-K_\pm^2\Vert_\infty\le1`$. The inherited variance for every real step $`h`$. Replacing this evaluated moment by a worst-case interaction bound would discard the flat-marginal information. -For the product-formula constant, we also use $`\VertK_\pm\Vert_\infty\le1/d`$. Here is a direct reason. For any bipartite state $`\rho_{AB}`$, the maps $`X\mapsto\mathrm{Tr}(X)I\pm X^T`$ are completely positive because their Choi matrices are $`I\pm F`$. Applying either map on $`A`$ to the positive matrix $`\rho^{T_{AB}}`$ proves +For the product-formula constant, we also use $`\Vert K_\pm\Vert_\infty\le1/d`$. Here is a direct reason. For any bipartite state $`\rho_{AB}`$, the maps $`X\mapsto\mathrm{Tr}(X)I\pm X^T`$ are completely positive because their Choi matrices are $`I\pm F`$. Applying either map on $`A`$ to the positive matrix $`\rho^{T_{AB}}`$ proves ```math -I_A\otimes\rho_B^T @@ -218,7 +218,7 @@ Its ideal product is the unitary channel of $`e^{ihK_-}e^{-ihK_+}`$. Channel com For Hermitian $`A,B`$, the first-order unitary product formula obeys ```math -\Verte^{-ihA}e^{-ihB}-e^{-ih(A+B)}\Vert_\infty +\Vert e^{-ihA}e^{-ihB}-e^{-ih(A+B)}\Vert_\infty \le\frac{h^2}{2}\Vert[A,B]\Vert_\infty. ``` @@ -226,7 +226,7 @@ This follows by differentiating an interpolating product and integrating the com ```math \Vert[K_+,K_-]\Vert_\infty -\le2\VertK_+\Vert_\infty\VertK_-\Vert_\infty +\le2\Vert K_+\Vert_\infty\Vert K_-\Vert_\infty \le2/d^2. ``` diff --git a/science/model.md b/science/model.md index ca622ad..c873999 100644 --- a/science/model.md +++ b/science/model.md @@ -63,14 +63,14 @@ U_{\mathcal E}(t)=e^{-it\mathsf H(L_{\mathcal E})}, There is no factor $`1/2`$, $`1/d`$, or hidden block normalization in this definition. The flag and the two vectorization registers have total dimension $`2d^2`$. The output must work on arbitrary data inputs, including inputs entangled with an untouched reference system. -For a unital channel, $`\VertL_{\mathcal E}\Vert_\infty=1`$. Indeed, the Schwarz inequality for unital completely positive maps gives +For a unital channel, $`\Vert L_{\mathcal E}\Vert_\infty=1`$. Indeed, the Schwarz inequality for unital completely positive maps gives ```math \mathcal E(X)^\dagger\mathcal E(X) \preceq\mathcal E(X^\dagger X). ``` -Taking the trace and using trace preservation proves Hilbert-Schmidt contraction, so $`\VertL_{\mathcal E}\Vert_\infty\le1`$. The fixed vector $`|I\rangle\!\rangle`$ gives equality. Consequently $`\Vert\mathsf H(L_{\mathcal E})\Vert_\infty=1`$. This explains why the unnormalized target already has a dimension-independent Hamiltonian norm in the present class. +Taking the trace and using trace preservation proves Hilbert-Schmidt contraction, so $`\Vert L_{\mathcal E}\Vert_\infty\le1`$. The fixed vector $`|I\rangle\!\rangle`$ gives equality. Consequently $`\Vert\mathsf H(L_{\mathcal E})\Vert_\infty=1`$. This explains why the unnormalized target already has a dimension-independent Hamiltonian norm in the present class. ## Access and charged resources @@ -87,7 +87,7 @@ All diamond distances are **unhalved**. For a linear map $`\Lambda`$, ```math \Vert\Lambda\Vert_\diamond =\sup_{r\ge1}\sup_{X\ne0} -\frac{\Vert(\Lambda\otimes\mathrm{id}_r)(X)\Vert_1}{\VertX\Vert_1}. +\frac{\Vert(\Lambda\otimes\mathrm{id}_r)(X)\Vert_1}{\Vert X\Vert_1}. ``` In particular, the diamond distance between two channels is at most $`2`$. The compiler's guarantee is $`\Vert\widetilde{\mathcal U}_{\mathcal E,t}-\mathcal U_{\mathcal E,t}\Vert_\diamond\le\epsilon`$, with this convention. It is a uniform channel guarantee, rather than a bound for one chosen input or one observable. From efe8f96fd2d96a5a660d4ce9cbc1ce8117c8d69d Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Sun, 15 Nov 2026 23:05:29 +0800 Subject: [PATCH 4/5] Preserve the table ket and strict inequality in hosted mathematics --- learning/WATROUS_BRIDGE.md | 2 +- science/dimension-lower-bound.md | 2 +- verification/hosted-contract.json | 12 ++++++++++++ 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/learning/WATROUS_BRIDGE.md b/learning/WATROUS_BRIDGE.md index 817ef92..9fb0e61 100644 --- a/learning/WATROUS_BRIDGE.md +++ b/learning/WATROUS_BRIDGE.md @@ -37,7 +37,7 @@ The explicit formula is the convention: software that flattens a matrix into a c | Object | Watrous | This project | | --- | --- | --- | | Natural/Liouville representation | $`K(\mathcal E)\mathrm{vec}(X)=\mathrm{vec}(\mathcal E(X))`$ | $`L_{\mathcal E}=K(\mathcal E)`$ | -| Entangled vector | $`\mathrm{vec}(I)`$, of squared norm $`d`$ | $`|\Phi_d\rangle=\mathrm{vec}(I)/\sqrt d`$ | +| Entangled vector | $`\mathrm{vec}(I)`$, of squared norm $`d`$ | $`\lvert\Phi_d\rangle=\mathrm{vec}(I)/\sqrt d`$ | | Choi operator/state | $`J(\mathcal E)=(\mathcal E\otimes\mathrm{id})(\mathrm{vec}(I)\mathrm{vec}(I)^\dagger)`$ | $`J_{\mathcal E}=J(\mathcal E)/d`$ | | Tensor legs of the Choi object | Output first, input second | The same | diff --git a/science/dimension-lower-bound.md b/science/dimension-lower-bound.md index 6e13cd0..e28044d 100644 --- a/science/dimension-lower-bound.md +++ b/science/dimension-lower-bound.md @@ -91,7 +91,7 @@ Thus constant-time, constant-error coherent evolution of the unnormalized Hermit ## A constant-normalization block is already sufficient -The same conclusion holds for the block-encoding output used by spectral algorithms. Fix a known constant $`0 Date: Sun, 15 Nov 2026 23:06:04 +0800 Subject: [PATCH 5/5] Bind repaired equation text to the serialized mathematical reference --- verification/hosted-contract.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/verification/hosted-contract.json b/verification/hosted-contract.json index 3a8da2a..8582962 100644 --- a/verification/hosted-contract.json +++ b/verification/hosted-contract.json @@ -35,7 +35,7 @@ "path": "learning/WATROUS_BRIDGE.md", "index": 11, "source_sha256": "ad478d64f78d2d7c25a9ae14dbb047bf85bbfb132119703336cc4fb4f9fd4ee5", - "expected_text": "|Φd⟩=vec(I)/√d" + "expected_text": "|Φd⟩=vec(I)/d" }, { "path": "science/dimension-lower-bound.md",