From 337360a11aafbb8286b0d9f7cffa664b917e4fe9 Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Mon, 30 Nov 2026 16:49:22 +0800 Subject: [PATCH 1/8] Prove two-fault gate bounds on a calibratable surface-code patch --- README.md | 9 +- learning/MILESTONES.md | 2 + learning/PRESKILL_BRIDGE.md | 6 +- learning/README.md | 4 +- llms.txt | 2 + science/README.md | 4 + science/rotated_surface_patch.md | 178 ++ verification/README.md | 4 +- verification/certified_5_11.json | 2395 +++++++++++++++ verification/certified_7_13.json | 2697 +++++++++++++++++ verification/results/verify_surface_gate.json | 12 + .../results/verify_surface_gate_d5.json | 8 + verification/run_all.py | 2 + verification/verify_surface_gate.py | 205 ++ verification/verify_surface_gate_d5.py | 87 + 15 files changed, 5608 insertions(+), 7 deletions(-) create mode 100644 science/rotated_surface_patch.md create mode 100644 verification/certified_5_11.json create mode 100644 verification/certified_7_13.json create mode 100644 verification/results/verify_surface_gate.json create mode 100644 verification/results/verify_surface_gate_d5.json create mode 100644 verification/verify_surface_gate.py create mode 100644 verification/verify_surface_gate_d5.py diff --git a/README.md b/README.md index ac9a2f8..9e1f5b4 100644 --- a/README.md +++ b/README.md @@ -4,15 +4,18 @@ A correctable fault during a gate can change the logical evolution rate until recovery. Exact error transparency removes this timing dependence: the physical Hamiltonian implements the same logical generator in the code and every protected error image. This repository proves general interaction-order and native coupling bounds, gives a sharp four-body witness, and constructs resource-optimal protected controls and entanglers on fixed concatenated five-qubit codes. -## Sister projects: Protected Gates and Syndrome Readout +## Sister projects: Protected Gates, Syndrome Readout, and Calibration | Sister repository | Central question | |---|---| | **[Error-Transparent Locality](https://github.com/GoGoKo699/Error-Transparent-Locality) (this repository)** | Which native interaction order and coupling budget let a logical gate tolerate faults at unknown times? | | **[Syndrome Reversibility Distance](https://github.com/GoGoKo699/Syndrome-Reversibility-Distance)** | When does the original syndrome measurement preserve logical information after a known product unitary? | +| **[Coherent Syndrome Calibration](https://github.com/GoGoKo699/Coherent-Syndrome-Calibration)** | Which sites need trusted signed pulses to learn coherent rotation signs from the original syndrome? | The [shared gate/readout theorem](science/gate_readout_tradeoff.md) connects the two requirements on a fixed code. The gate and readout models retain separate assumptions. +On the [same calibratable rotated surface-code patch](science/rotated_surface_patch.md), two-fault-transparent logical $Z$ requires native order at least $d+6$ for every odd $d\geq5$. The order is sharp at $d=5,7$. At distance seven the optimal normalized coupling is $J/\omega=25$. The patch also admits exact known-product-unitary recovery and calibration with $d$ trusted signed phase addresses. + ## General resource bounds Let a fixed code have detection distance $d$ and encoding $V$. A Hermitian, code-preserving Hamiltonian is transparent through Pauli-error weight $t$ when @@ -78,7 +81,7 @@ The first entangler's compact dense specification contains **41,032,000,000 nati | Study from the shared educational anchor | [Learning guide](learning/README.md), [Preskill bridge](learning/PRESKILL_BRIDGE.md), and [30 milestones](learning/MILESTONES.md) | | Check attribution and nearest precedents | [Related work](references/RELATED_WORK.md) and [bibliography](references/references.bib) | -The shared educational anchor is **John Preskill, _Quantum Information_, Chapter 7, “Quantum Error Correction”**, in the author-hosted draft updated March 2026. This project's bridge selects relevant sections and translates notation and Pauli phases; its twelve background and eighteen narrative milestones lead through protected entanglers and universal encoded control. The [sister project's Preskill bridge](https://github.com/GoGoKo699/Syndrome-Reversibility-Distance/blob/main/learning/PRESKILL_BRIDGE.md) follows the readout argument with its own 30-milestone map. +The shared educational anchor is **John Preskill, _Quantum Information_, Chapter 7, “Quantum Error Correction”**, in the author-hosted draft updated March 2026. This project's bridge selects relevant sections and translates notation and Pauli phases; its twelve background and eighteen narrative milestones lead through protected entanglers and universal encoded control. The [calibration project's Preskill bridge](https://github.com/GoGoKo699/Coherent-Syndrome-Calibration/blob/main/learning/PRESKILL_BRIDGE.md) follows syndrome identifiability. The [readout project's Preskill bridge](https://github.com/GoGoKo699/Syndrome-Reversibility-Distance/blob/main/learning/PRESKILL_BRIDGE.md) follows the readout argument with its own 30-milestone map. ## Reproduce the certificates @@ -88,7 +91,7 @@ Only Python 3.10 or later and its standard library are required: python verification/run_all.py ``` -The [verification guide](verification/README.md) describes fourteen exact checks and their committed JSON records. They cover full error-image identities, code and stabilizer properties, coefficient normalization, moment primal/dual certificates, sparse constructions, recursive response coverage, entanglers, and control phases. No floating-point tolerance is used. Finite certificates support the stated instances; the general and arbitrary-depth conclusions use the analytical proofs. +The [verification guide](verification/README.md) describes sixteen exact checks and their committed JSON records. They cover full error-image identities, code and stabilizer properties, coefficient normalization, moment primal/dual certificates, sparse constructions, recursive response coverage, entanglers, and control phases. No floating-point tolerance is used. Finite certificates support the stated instances; the general and arbitrary-depth conclusions use the analytical proofs. ## Physical scope diff --git a/learning/MILESTONES.md b/learning/MILESTONES.md index e261dd9..c3d112a 100644 --- a/learning/MILESTONES.md +++ b/learning/MILESTONES.md @@ -245,6 +245,8 @@ Dependencies point only to earlier milestones. The map connects the load-bearing **Source pointers.** Anchor foundation: [Preskill §§7.4 and 7.10][p74]. Local bridge: [§9](PRESKILL_BRIDGE.md#9-the-same-code-in-a-syndrome-readout-experiment); [joint proof and witness](../science/gate_readout_tradeoff.md#2-joint-theorem). +**Companion example.** Apply the same logic to the [rotated patch](../science/rotated_surface_patch.md): explain why odd intersections with a logical $X$ cut, together with the two-site moment constraints, raise the two-fault interaction order to at least $d+6$. Use [Preskill §§7.18.2–7.18.4](https://www.preskill.caltech.edu/ph219/chap7_26_6A.pdf) to connect the cut to the logical operator. + ### M19: Concatenation preserves a parity obstruction to readout loss **Central question.** Which code family avoids every equal-support stabilizer/logical collision? diff --git a/learning/PRESKILL_BRIDGE.md b/learning/PRESKILL_BRIDGE.md index 6348e0c..aeb63ac 100644 --- a/learning/PRESKILL_BRIDGE.md +++ b/learning/PRESKILL_BRIDGE.md @@ -1,6 +1,6 @@ # From Preskill's QEC foundations to error-transparent locality -Error-Transparent Locality and Syndrome Reversibility Distance share one educational anchor: John Preskill, *Quantum Information*, Chapter 7, updated March 2026. The [author's course index](https://preskill.caltech.edu/ph229/index.html) links the [complete chapter](https://www.preskill.caltech.edu/ph219/chap7_26_6A.pdf). Page numbers below are the chapter's printed numbers; PDF viewer numbers are six larger. +Error-Transparent Locality, Syndrome Reversibility Distance, and Coherent Syndrome Calibration share one educational anchor: John Preskill, *Quantum Information*, Chapter 7, updated March 2026. The [author's course index](https://preskill.caltech.edu/ph229/index.html) links the [complete chapter](https://www.preskill.caltech.edu/ph219/chap7_26_6A.pdf). Page numbers below are the chapter's printed numbers; PDF viewer numbers are six larger. Preskill supplies the foundations of correctability, distance, CSS codes, stabilizers, and concatenation. The Hamiltonian, twirl, moment, coupling, and control arguments below are supplied locally. Sections 9–14 connect them to the separate syndrome-readout experiment, optimal concatenated families through three physical errors, sparse synthesis, and protected logical strings. Their complete statements and proofs are in the [scientific account](../science/README.md). The [milestone map](MILESTONES.md) organizes a progression through those dependencies. @@ -469,6 +469,10 @@ e_{\rm opt}=\varepsilon_{\rm opt} Here $e_{\rm opt}$ is optimal entanglement infidelity and $\varepsilon_{\rm opt}$ is optimal half-diamond error in that readout experiment. The known rotation can still cause information loss because the measurement is prescribed. This formula does not describe an unknown-time gate fault, and the two models do not automatically compose. +### The same rotated patch in all three experiments + +After §§7.7 and 7.10.4, read §§7.18.2–7.18.4 for chains and loops on surface codes. In the [rotated patch proof](../science/rotated_surface_patch.md), a logical $X$ cut has odd intersection with every logical $Z$ support. A quadratic in the cut incidence gives a sharper two-fault order obstruction than total weight alone. Separate parity of stabilizers and logical operators explains reversible readout. Trusted signed biases on one logical $Z$ row then provide the sign class needed for informed recovery of a calibrated coherent drift. + ## 10. Concatenation, parity, and one-error gates Preskill §7.17 defines concatenation by replacing each qubit of an outer encoding with an inner encoded qubit. Applying that construction repeatedly to the five-qubit code gives diff --git a/learning/README.md b/learning/README.md index f7d5442..3be2ad5 100644 --- a/learning/README.md +++ b/learning/README.md @@ -4,9 +4,9 @@ The central question is how demanding the same logical evolution before and afte ## One shared educational anchor -Error-Transparent Locality and Syndrome Reversibility Distance use one common educational anchor: **John Preskill, _Quantum Information_, Chapter 7, “Quantum Error Correction”**, in the author-hosted prepublication draft updated March 2026. The [official course index](https://preskill.caltech.edu/ph229/index.html) links the [complete chapter](https://www.preskill.caltech.edu/ph219/chap7_26_6A.pdf). The repositories link to that draft; they do not redistribute it. +Error-Transparent Locality, [Syndrome Reversibility Distance](https://github.com/GoGoKo699/Syndrome-Reversibility-Distance), and [Coherent Syndrome Calibration](https://github.com/GoGoKo699/Coherent-Syndrome-Calibration) use one common educational anchor: **John Preskill, _Quantum Information_, Chapter 7, “Quantum Error Correction”**, in the author-hosted prepublication draft updated March 2026. The [official course index](https://preskill.caltech.edu/ph229/index.html) links the [complete chapter](https://www.preskill.caltech.edu/ph219/chap7_26_6A.pdf). The repositories link to that draft; they do not redistribute it. -The common foundation is §§7.2–7.4 for exact correction, logical information leakage, reference decoupling, and distance; §§7.6–7.8 for classical linear codes and CSS codes; §§7.10–7.11 for stabilizers, encoded Pauli operators, and the five-qubit code; and §7.17 for concatenation. Section 7.9 supplies additional code-parameter context for the gate comparisons. This is a targeted route through one source. The research references remain attribution and comparison sources, rather than additional educational anchors. +The common foundation is §§7.2–7.4 for exact correction, logical information leakage, reference decoupling, and distance; §§7.6–7.8 for classical linear codes and CSS codes; §§7.10–7.11 for stabilizers, encoded Pauli operators, and the five-qubit code; and §7.17 for concatenation. Sections 7.18.2–7.18.4 introduce the homological surface-code setting for the [shared rotated-patch result](../science/rotated_surface_patch.md). Section 7.9 supplies additional code-parameter context for the gate comparisons. This is a targeted route through one source. The research references remain attribution and comparison sources, rather than additional educational anchors. Begin with the [Preskill-to-project bridge](PRESKILL_BRIDGE.md). It translates the source's notation and assumptions, including its stabilizer convention for $Y$, into the repository's Hermitian Pauli basis. Its worked example explains why correcting a fault need not correct the angle accumulated during a gate. The later sections supply the additional moment, readout, sparse-synthesis, and tensor-lifting steps needed for the final results. The [bibliography](../references/references.bib) records the source version under `Preskill2026QEC`. diff --git a/llms.txt b/llms.txt index c38e185..6c1e8ec 100644 --- a/llms.txt +++ b/llms.txt @@ -6,6 +6,8 @@ Start with [README](README.md) for the principal results and [scientific overview](science/README.md) for the complete theorem, construction, and proof map. Error correction repairs a recoverable error; exact error transparency additionally preserves the logical evolution despite its unknown arrival time. The project separates general all-code obstructions from attained, sharper optima on specified codes. +The [rotated surface-code patch](science/rotated_surface_patch.md) adds a geometric two-fault order lower bound and sharp distance-seven certificate. The two sister repositories treat known-product recovery and coherent sign calibration using the same original checks. + ## General theorem route: which assumptions support the bounds? - [Model](science/model.md): fixed encoding, detection distance d, full physical-space error-image identities, consistent scalar sector shifts, unknown fault time, and ideal final recovery. diff --git a/science/README.md b/science/README.md index fad62d6..9bf0ee8 100644 --- a/science/README.md +++ b/science/README.md @@ -68,6 +68,10 @@ The earlier two-error construction uses uniform active promotions and correlated | [Twenty-five-qubit three-error gate](three_error_gates.md) | Seven-class seed, forced outer logical branch, full three-error responses, and all-direction optimum | | [Growing three-error optima](growing_three_error_gates.md) | Strict increment lifting, sign preservation, arbitrary-Hamiltonian block-moment dual, and all-depth exact costs | +## A calibratable surface-code patch + +On an odd rotated planar patch, a [quadratic logical-cut certificate](rotated_surface_patch.md) forces native order at least $d+6$ for logical $Z$ through two faults. Exact rational certificates attain this bound at $d=5,7$. At distance seven, the optimal native coupling budget at order 13 is $25\omega$. The same original checks support known-product-unitary recovery and signed calibration of static coherent $Z$ drift. + ## Protected entanglers and universal encoded control Keep $M$ product blocks of $Q_m$ fixed, with $m\ge2$. For a prescribed nonidentity logical Pauli string $P$ of logical weight $p$, its target coset has minimum physical weight $D=pd$. The ordinary distance of the full product code is still $d$. The [pure-string theorem](protected_entangling_gates.md) gives diff --git a/science/rotated_surface_patch.md b/science/rotated_surface_patch.md new file mode 100644 index 0000000..cbdefc2 --- /dev/null +++ b/science/rotated_surface_patch.md @@ -0,0 +1,178 @@ +# Fault-transparent logical Z on a calibratable rotated surface-code patch + +Fix the odd-distance rotated planar CSS code with one encoded qubit and data sites +$(x,y)$, $0\leq x,y0$ for a +logical target $\Omega Z_L+cI$. The same code and original syndrome projectors +are used in the three experiments. + +## Reduction to site and pair moments + +A native transparent Hamiltonian satisfies the logical target after conjugation +by every physical Pauli $E$ of weight at most two and restriction to the +code. Consider just the coefficient of $Z_L$ and probes $E=X(e)$, +$|e|\leq 2$. Detectable Paulis restrict to zero. Of the other Paulis only +the physical $Z_L$ coset can contribute to this logical coefficient. A +representative has binary $X$ part in $C_X$, and $Z$ part +$z\in \ell_Z+C_Z$. Absorb its real restriction sign into its coefficient, +then add the normalized coefficients for each fixed $z$. Conjugation by +$X(e)$ has sign $(-1)^{e\cdot z}$, independent of the $X$ part. + +The resulting pure $Z$ Hamiltonian has at most the original order and +coupling budget. It preserves every syndrome sector. On every correctable +error image the $X$ and $Y$ components of faults give the same sign rule, +and the $Z$ components commute. The reduced constraints therefore suffice +for exact transparency, including a code state entangled with a reference. +Adding a global scalar to the lifted construction can realize the target +scalar $c$ without changing either resource. Conversely, any allowed +sector-dependent scalar shifts of the original Hamiltonian disappear under +logical Pauli projection. + +With $z_i$ the incidence bit at site $i$, these constraints on the signed +normalized coefficients $c_z$ are +```math + \sum_z c_z=1,\qquad + \sum_z c_z z_i=0,\qquad + \sum_z c_z z_i z_j=0 \quad(i 1] + assert all(len(pair) == 2 for pair in self.pairs) + assert all(a % distance == b % distance for a, b in self.pairs) + check_supports = {frozenset(check) for check in x_checks(distance)} + assert all( + frozenset(self.size - 1 - site for site in check) in check_supports + for check in check_supports + ) + + def rotate(self, word): + return int(f"{word:0{self.size}b}"[::-1], 2) + + def swap_normal_form(self, word): + for low, high in self.pairs: + if (word >> high) & 1 and not (word >> low) & 1: + word ^= (1 << low) | (1 << high) + return word + + def canonical(self, word): + return min(self.swap_normal_form(word), self.swap_normal_form(self.rotate(word))) + + def orbit(self, word): + orbit = {word} + for low, high in self.pairs: + mask = (1 << low) | (1 << high) + if ((word >> low) ^ (word >> high)) & 1: + orbit |= {current ^ mask for current in orbit} + return orbit | {self.rotate(current) for current in orbit} + + +def verify(certificate): + distance = certificate["d"] + cap = certificate["interaction_order"] + size = distance * distance + assert distance == 7 and cap == 13 + syndrome = site_syndromes(distance) + group = Symmetry(distance, syndrome) + assert certificate["symmetry_pairs"] == group.pairs + + words = set(supports(distance, cap, syndrome)) + counts = Counter(word.bit_count() for word in words) + assert sum(counts.values()) == certificate["words_at_cap"] + assert counts == {7: 296, 9: 2201, 11: 12624, 13: 53139} + + # An odd-overlap logical-X cut omits all five-hit supports at cap 11. + # The corresponding vanishing quadratic certifies infeasibility. + logical_x = sum( + 1 << ((2 if y % 4 in (1, 2) else 1) + distance * y) + for y in range(distance) + ) + for word in words: + overlap = (logical_x & word).bit_count() + assert overlap % 2 == 1 + if word.bit_count() <= cap - 2: + assert overlap in (1, 3) + + coefficients = {} + for word, value in certificate["primal_orbits"]: + assert word == group.canonical(word) + orbit = group.orbit(word) + assert orbit <= words and not orbit & coefficients.keys() + coefficient = Fraction(value) / len(orbit) + assert coefficient != 0 + coefficients.update(dict.fromkeys(orbit, coefficient)) + assert len(coefficients) == certificate["physical_term_count"] + assert max(word.bit_count() for word in coefficients) == cap + denominator = lcm(*(value.denominator for value in coefficients.values())) + zero_moment = 0 + one_moments = [0] * size + two_moments = defaultdict(int) + for word, coefficient in coefficients.items(): + weight = int(coefficient * denominator) + selected = list(sites(word)) + zero_moment += weight + for site in selected: + one_moments[site] += weight + for pair in combinations(selected, 2): + two_moments[pair] += weight + assert zero_moment == denominator + assert not any(one_moments) and not any(two_moments.values()) + assert sum(map(abs, coefficients.values())) == Fraction(certificate["coupling"]) + + dual = {mask: Fraction(value) for mask, value in certificate["dual_orbit_coefficients"]} + assert len(dual) == len(certificate["dual_orbit_coefficients"]) + assert all(mask.bit_count() <= 2 and mask == group.canonical(mask) for mask in dual) + assert dual[0] == Fraction(certificate["coupling"]) + denominator = lcm(*(value.denominator for value in dual.values())) + monomials = { + mask: int(dual.get(group.canonical(mask), 0) * denominator) + for degree in (0, 1, 2) + for indices in combinations(range(size), degree) + for mask in [sum(1 << site for site in indices)] + } + for word in words: + selected = [1 << site for site in sites(word)] + value = monomials[0] + value += sum(monomials[bit] for bit in selected) + value += sum(monomials[a | b] for a, b in combinations(selected, 2)) + assert abs(value) <= denominator + return { + "distance": distance, + "minimum_interaction_order": cap, + "optimal_normalized_coupling": str(dual[0]), + "verified_native_terms": len(coefficients), + "verified_logical_Z_supports": dict(sorted(counts.items())), + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "certificate", type=Path, nargs="?", + default=Path(__file__).with_name("certified_7_13.json"), + ) + args = parser.parse_args() + print(json.dumps(verify(json.loads(args.certificate.read_text())), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/verification/verify_surface_gate_d5.py b/verification/verify_surface_gate_d5.py new file mode 100644 index 0000000..7853a54 --- /dev/null +++ b/verification/verify_surface_gate_d5.py @@ -0,0 +1,87 @@ +"""Verify the inherited exact distance-five rotated-patch gate certificate.""" + +import argparse +from collections import defaultdict +from fractions import Fraction +from itertools import combinations +import json +from math import lcm +from pathlib import Path + +from verify_surface_gate import site_syndromes, sites, supports + + +def exact_polynomial_bound(words, entries, expected_constant, bound): + coefficients = {tuple(indices): Fraction(value) for indices, value in entries} + assert len(coefficients) == len(entries) + assert all(len(indices) <= 2 for indices in coefficients) + assert coefficients[()] == expected_constant + denominator = lcm(*(value.denominator for value in coefficients.values())) + numerators = { + indices: int(value * denominator) for indices, value in coefficients.items() + } + for word in words: + selected = list(sites(word)) + value = numerators[()] + value += sum(numerators.get((site,), 0) for site in selected) + value += sum(numerators.get(pair, 0) for pair in combinations(selected, 2)) + assert abs(value) <= bound * denominator + + +def verify(certificate): + distance = certificate["d"] + assert distance == 5 + exclusion, optimum = certificate["exact_certificates"] + assert exclusion["ell"] == 9 and optimum["ell"] == 11 + syndrome = site_syndromes(distance) + low_words = set(supports(distance, 9, syndrome)) + high_words = set(supports(distance, 11, syndrome)) + assert len(low_words) == exclusion["words"] == 768 + assert len(high_words) == optimum["words"] == 1705 + exact_polynomial_bound(low_words, exclusion["exact_exclusion_dual"], 1, 0) + + coefficients = {word: Fraction(value) for word, value in optimum["primal_witness"]} + assert len(coefficients) == len(optimum["primal_witness"]) + assert set(coefficients) <= high_words + assert max(word.bit_count() for word in coefficients) == 11 + assert all(coefficients.values()) + denominator = lcm(*(value.denominator for value in coefficients.values())) + zero_moment = 0 + one_moments = [0] * (distance * distance) + two_moments = defaultdict(int) + for word, coefficient in coefficients.items(): + weight = int(coefficient * denominator) + selected = list(sites(word)) + zero_moment += weight + for site in selected: + one_moments[site] += weight + for pair in combinations(selected, 2): + two_moments[pair] += weight + assert zero_moment == denominator + assert not any(one_moments) and not any(two_moments.values()) + coupling = Fraction(optimum["exact_J"]) + assert sum(map(abs, coefficients.values())) == coupling + exact_polynomial_bound(high_words, optimum["dual_certificate"], coupling, 1) + + return { + "distance": distance, + "minimum_interaction_order": optimum["ell"], + "optimal_normalized_coupling": str(coupling), + "verified_native_terms": len(coefficients), + "low_cap_logical_Z_supports": len(low_words), + "optimal_cap_logical_Z_supports": len(high_words), + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "certificate", type=Path, nargs="?", + default=Path(__file__).with_name("certified_5_11.json"), + ) + args = parser.parse_args() + print(json.dumps(verify(json.loads(args.certificate.read_text())), indent=2)) + + +if __name__ == "__main__": + main() From 2754ec291dd7751aa1ec7839b9d5fe9477176c55 Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Mon, 30 Nov 2026 16:50:10 +0800 Subject: [PATCH 2/8] Capture hosted mathematics for the pinned sister integration --- .github/workflows/hosted-math.yml | 85 +++ .../hosted_math/capture_hosted_math.cjs | 612 ++++++++++++++++++ .../hosted_math/check_rendered_math.py | 370 +++++++++++ .../hosted_math/probe_hosted_math.cjs | 146 +++++ 4 files changed, 1213 insertions(+) create mode 100644 .github/workflows/hosted-math.yml create mode 100644 verification/hosted_math/capture_hosted_math.cjs create mode 100644 verification/hosted_math/check_rendered_math.py create mode 100644 verification/hosted_math/probe_hosted_math.cjs diff --git a/.github/workflows/hosted-math.yml b/.github/workflows/hosted-math.yml new file mode 100644 index 0000000..fe11935 --- /dev/null +++ b/.github/workflows/hosted-math.yml @@ -0,0 +1,85 @@ +name: Hosted mathematics + +on: + pull_request: + paths: + - '.github/workflows/hosted-math.yml' + - 'verification/hosted_math/**' + +permissions: + contents: read + +concurrency: + group: hosted-math-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + capture: + if: github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-24.04 + timeout-minutes: 30 + env: + CAPTURE_REVISION: 337360a11aafbb8286b0d9f7cffa664b917e4fe9 + REPRESENTATIVE_PAGE: science/rotated_patch.md + steps: + - name: Check out the validation helpers + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false + - name: Check out the exact scientific source + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + ref: ${{ env.CAPTURE_REVISION }} + path: checked-source + persist-credentials: false + - name: Set up Node + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 + with: + node-version: '22' + - name: Set up the capture runtime + run: | + npm install --prefix "$RUNNER_TEMP/math-runtime" playwright@1.56.1 mathjax-full@3.2.1 + node "$RUNNER_TEMP/math-runtime/node_modules/playwright/cli.js" install chromium + - name: Probe representative mathematics at both widths + run: | + export NODE_PATH="$RUNNER_TEMP/math-runtime/node_modules" + node verification/hosted_math/probe_hosted_math.cjs \ + --root "$GITHUB_WORKSPACE/checked-source" \ + --repository "$GITHUB_REPOSITORY" \ + --revision "$CAPTURE_REVISION" \ + --page "$REPRESENTATIVE_PAGE" \ + --output "$RUNNER_TEMP/hosted-probe" + - name: Compare all hosted pages at both widths + if: ${{ !cancelled() }} + run: | + export NODE_PATH="$RUNNER_TEMP/math-runtime/node_modules" + node verification/hosted_math/capture_hosted_math.cjs \ + --root "$GITHUB_WORKSPACE/checked-source" \ + --repository "$GITHUB_REPOSITORY" \ + --revision "$CAPTURE_REVISION" \ + --output "$RUNNER_TEMP/hosted-first" || { + result=$? + if test -f "$RUNNER_TEMP/hosted-first/hosted-report.json" && + grep -Eq 'HTTP (502|503|504)' "$RUNNER_TEMP/hosted-first/hosted-report.json"; then + node verification/hosted_math/capture_hosted_math.cjs \ + --root "$GITHUB_WORKSPACE/checked-source" \ + --repository "$GITHUB_REPOSITORY" \ + --revision "$CAPTURE_REVISION" \ + --output "$RUNNER_TEMP/hosted-resume" \ + --resume-from "$RUNNER_TEMP/hosted-first" + else + exit "$result" + fi + } + - name: Retain the captures and comparison reports + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: hosted-math-${{ env.CAPTURE_REVISION }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/hosted-first + ${{ runner.temp }}/hosted-resume + ${{ runner.temp }}/hosted-probe + if-no-files-found: error + retention-days: 14 diff --git a/verification/hosted_math/capture_hosted_math.cjs b/verification/hosted_math/capture_hosted_math.cjs new file mode 100644 index 0000000..e8d2c87 --- /dev/null +++ b/verification/hosted_math/capture_hosted_math.cjs @@ -0,0 +1,612 @@ +#!/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'); + const {CharacterMap}=require('mathjax-full/js/input/tex/SymbolMap.js'); + const {Configuration}=require('mathjax-full/js/input/tex/Configuration.js'); + const {default:ParseMethods}=require('mathjax-full/js/input/tex/ParseMethods.js'); + RegisterHTMLHandler(liteAdaptor()); + // Mark the original MathJax operator without changing its grouping or + // inherited style. A literal ⊥ still uses the unmarked base parser. + const provenance='merlin-operator-provenance'; + new CharacterMap(provenance,ParseMethods.mathchar0mo,{perp:['⊥',{'data-merlin-command':'perp'}]}); + Configuration.create(provenance,{handler:{macro:[provenance]},priority:0}); + const doc=mathjax.document('',{InputJax:new TeX({packages:[...AllPackages,provenance],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, operators, 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(); + if(!text) return []; + const token=[tag,text,variant]; + if(tag==='mo') operators.push({token,element:e}); + return [token]; + } + // 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,operators,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 reconcileOperators(expected, actual, tex) { + if(expected.length!==actual.length) return []; + const aliases=[]; + for(let i=0;ie.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,operatorAliases=[]; + const actualOperators=[]; + const actualTree=actual?canonical(actual,actualOperators):null; + 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 { + const expectedOperators=[]; + const expectedTree=canonical(parsed.documentElement,expectedOperators); + expectedSignature=JSON.stringify(expectedTree); + operatorAliases=reconcileOperators(expectedOperators,actualOperators,want.tex); + } + } + const actualSignature=actualTree===null?null:JSON.stringify(actualTree); + 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, + operator_aliases:operatorAliases,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:[],navigation_retries:[]}; +} +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, + navigation_retries:session.navigation_retries ?? []}}; +} +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, options={}) { + 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 navigate=async()=>{ + const response=await page.goto(source.url,{waitUntil:'domcontentloaded',timeout:60000}); + if(page.url()!==source.url) throw new Error('Browser redirected away from exact pinned source URL'); + return response; + }; + let response=await navigate(); + const status=response?.status(); + // Retry only a response from the exact pinned navigation, with no redirect. + if([502,503,504].includes(status)) { + if(response.url()!==source.url || response.request().redirectedFrom()!==null) + throw new Error('Browser redirected away from exact pinned source URL'); + options.onNavigationRetry?.({http_status:status,observed_at:new Date().toISOString()}); + await page.waitForTimeout(1000); + response=await navigate(); + } + if(response?.status()!==200) throw new Error('HTTP '+response?.status()); + 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,options); + 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;index{ + session.navigation_retries.push({path:source.path,url:source.url,viewport,...retry}); + session.updated_at=retry.observed_at; + saveSession(output,session); + } + }); + const receipt=savePageReceipt(args,helper,output,session,inventory,source,viewport,item,prefix,contract); + artifacts.push(...receipt.artifacts); + pageProvenance.push({path:source.path,viewport,observed_at:item.observed_at,reused:false}); + if(!receipt.passed) { + const reason='Captured page failed structural or text comparison'; + session.failures.push({category:'verification_failure',path:source.path,viewport,observed_at:item.observed_at,reason}); + failures.push(source.path+' at '+viewport.width+': verification_failure: '+reason); + session.updated_at=new Date().toISOString();saveSession(output,session); + } + } catch(error) { + const category=classifyFailure(error),observed_at=new Date().toISOString(); + item={path:source.path,url:source.url,revision:args.revision,source_sha256:source.source_sha256, + errors:[String(error)],math:[],observed_at}; + session.failures.push({category,path:source.path,viewport,observed_at,reason:String(error)}); + session.updated_at=observed_at;saveSession(output,session); + failures.push(source.path+' at '+viewport.width+': '+category+': '+String(error)); + fatal=['policy_denied','access_required','transport_failure'].includes(category); + } + } + capture.pages.push(item); + if(fatal) break; + } + } finally {await context.close();} + const observed=capture.pages.map(p=>p.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, + navigation_retries:session?.navigation_retries ?? [],diagnostic_only:args.diagnosticOnly===true}; + if(session?.previous_attempt) report.previous_attempt=session.previous_attempt; + writeJSON(path.join(output,'hosted-report.json'),report); + console.log(JSON.stringify({status:report.status,report:path.join(output,'hosted-report.json'),sha256:sha256(fs.readFileSync(path.join(output,'hosted-report.json'))),pages:report.required_pages.length,failures:report.failures.length,reused_pages:pageProvenance.filter(p=>p.reused).length})); + return report.status==='pass'?0:1; +} +module.exports={argumentsFor,safePath,pinnedPages,mathCompiler,inspectArticle,hostedMathReadiness,waitForHostedMath,classifyFailure,artifact,boundReport,VIEWPORTS,run, + safeEvidenceFile,readBoundArtifact,observationTime,pageKey,capturePassed,sessionBinding,newSession,saveSession,loadResume, + runTextCheck,savePageReceipt,captureHostedPage,RESUME_MAX_AGE_MS,RENDER_TIMEOUT_MS}; +if(require.main===module) { + (async()=>{ + const args=argumentsFor(process.argv.slice(2)); + if(args.help) {console.log('capture_hosted_math.cjs --root REPO --repository owner/name --revision FULLSHA --output EMPTY_DIR [--page PATH ...] [--contract JSON] [--python python3] [--resume-from PRIOR_EVIDENCE_DIR]');return;} + process.exitCode=await run(args); + })().catch(error=>{console.error(String(error));process.exitCode=2;}); +} diff --git a/verification/hosted_math/check_rendered_math.py b/verification/hosted_math/check_rendered_math.py new file mode 100644 index 0000000..1d3bf98 --- /dev/null +++ b/verification/hosted_math/check_rendered_math.py @@ -0,0 +1,370 @@ +#!/usr/bin/env python3 +r"""Check captured mathematical text against pinned GitHub Markdown source. + +Usage (Python 3.10+, standard library only): + check_rendered_math.py inventory --root REPO --repository owner/name \ + --revision FULL_COMMIT --page README.md --page science/results.md \ + --output math-source.json + check_rendered_math.py check --inventory math-source.json \ + --capture math-capture.json [--contract math-contract.json] [--output result.json] + +Inventory reads Git objects at the requested commit, not the working tree. +It recognizes math fences, $`...`$, $$...$$ and single-dollar inline math, +excluding ordinary code fences/spans. This is a bounded Markdown scanner, +not the hosting renderer's parser. Inspect its inventory before capture. + +Capture schema (collect actual full accessible math text in document order): + {"schema_version": 1, "repository": "owner/name", "revision": "40 hex", + "renderer_profile": "github", "captured_at": "ISO-8601 with timezone", + "capture_method": "how the actual hosted DOM was inspected", + "pages": [{"path": "README.md", "url": "exact pinned inventory URL", + "revision": "40 hex", "source_sha256": "inventory source hash", + "errors": [], "math": [{"rendered": true, "errors": [], + "text_source": "mathml", "text": "full text, not a sample"}]}]} +Allowed text_source values: mathml, mathjax-assistive, katex-accessibility, +renderer-accessibility. Extract one accessible representation per host; +exclude TeX annotation nodes and duplicate visual/accessibility copies. +Native MathML is valid. Empty math lists are valid for math-free pages. + +Optional contract strengthens content checks without pretending to translate +arbitrary TeX. Each entry selects a path/index (1-based) and source_sha256 +(the expression hash in inventory), with expected_text and/or required_text: + {"schema_version": 1, "expressions": [{"path": "README.md", "index": 1, + "source_sha256": "expression hash", "required_text": ["d", "(C1)"], + "expected_text": "|A|", "le": "≤", "leq": "≤", "ge": "≥", "geq": "≥", + "ne": "≠", "neq": "≠", "in": "∈", "notin": "∉", "subset": "⊂", + "subseteq": "⊆", "supset": "⊃", "supseteq": "⊇", "approx": "≈", + "simeq": "≃", "equiv": "≡", "propto": "∝", "cong": "≅", "sim": "∼", + "to": "→", "rightarrow": "→", "Rightarrow": "⇒", "implies": "⇒", + "mapsto": "↦", "leftrightarrow": "↔", "Leftrightarrow": "⇔", "iff": "⇔", +} +RELATION_SYMBOLS = set("<>=") | set(RELATIONS.values()) +COMMAND = re.compile(r"\\([A-Za-z]+)") +LABEL = re.compile(r"\\tag(\*)?\{([^{}]+)\}|\\text\{\s*\(([^{}()]+)\)\s*\}") +FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})([^\n]*)\n?$") +SHA = re.compile(r"[0-9a-f]{40}") +TEXT_SOURCES = {"mathml", "mathjax-assistive", "katex-accessibility", "renderer-accessibility"} + + +def digest(text: str) -> str: + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +def compact(text: str) -> str: + return "".join(c for c in unicodedata.normalize("NFKC", text) + if not c.isspace() and unicodedata.category(c) != "Cf") + + +def escaped(text: str, index: int) -> bool: + backslashes = 0 + while index > 0 and text[index - 1] == "\\": + backslashes += 1 + index -= 1 + return bool(backslashes % 2) + + +def tex_body(text: str) -> str: + """Drop unescaped TeX comments; do not expand user macros.""" + return "\n".join(line[:next((i for i, c in enumerate(line) + if c == "%" and not escaped(line, i)), len(line))] + for line in text.splitlines()) + + +def relations(tex: str) -> dict[str, int]: + expanded = COMMAND.sub(lambda m: RELATIONS.get(m.group(1), m.group(0)), tex_body(tex)) + return dict(sorted(Counter(c for c in expanded if c in RELATION_SYMBOLS).items())) + + +def labels(tex: str) -> list[str]: + return [compact(tag if star else f"({tag or text})") + for star, tag, text in LABEL.findall(tex_body(tex))] + + +def expressions(source: str) -> list[dict]: + """Return ordered source spans; reject unterminated recognized delimiters.""" + found: list[dict] = [] + + def add(tex: str, offset: int, end: int, kind: str) -> None: + found.append({"line_start": source.count("\n", 0, offset) + 1, + "line_end": source.count("\n", 0, end) + 1, + "kind": kind, "tex": tex, "source_sha256": digest(tex), + "relations": relations(tex), "labels": labels(tex)}) + + def prose(start: int, end: int) -> None: + i = start + while i < end: + if source[i] == "$" and not escaped(source, i): + opener, closer, kind = ("$`", "`$", "github-inline") if source.startswith("$`", i) else ( + ("$$", "$$", "dollar-display") if source.startswith("$$", i) + else ("$", "$", "dollar-inline")) + j = source.find(closer, i + len(opener), end) + while j >= 0 and escaped(source, j): + j = source.find(closer, j + len(closer), end) + if j < 0 or (kind == "dollar-inline" and "\n" in source[i:j]): + raise ValueError(f"unclosed {kind} at line {source.count(chr(10), 0, i) + 1}") + add(source[i + len(opener):j], i, j + len(closer) - 1, kind) + i = j + len(closer) + elif source[i] == "`" and not escaped(source, i): + n = 1 + while i + n < end and source[i + n] == "`": + n += 1 + j = source.find("`" * n, i + n, end) + i = j + n if j >= 0 else i + n + else: + i += 1 + + lines = source.splitlines(keepends=True) + offset = start = i = 0 + while i < len(lines): + match = FENCE.match(lines[i]) + if not match: + offset += len(lines[i]) + i += 1 + continue + prose(start, offset) + marker, info = match.groups() + begin = offset + offset += len(lines[i]) + body_start = offset + i += 1 + while i < len(lines): + closing = FENCE.match(lines[i]) + if closing and closing[1][0] == marker[0] and len(closing[1]) >= len(marker) and not closing[2].strip(): + break + offset += len(lines[i]) + i += 1 + if i == len(lines): + raise ValueError(f"unclosed code fence at line {source.count(chr(10), 0, begin) + 1}") + if info.strip() == "math": + add(source[body_start:offset], begin, offset, "math-fence") + offset += len(lines[i]) + i += 1 + start = offset + prose(start, len(source)) + for index, item in enumerate(found, 1): + item["index"] = index + return found + + +def safe_path(path: str) -> bool: + return isinstance(path, str) and bool(path) and "\\" not in path and not PurePosixPath(path).is_absolute() and all( + part not in {"", ".", ".."} for part in path.split("/")) + + +def make_inventory(repository: str, revision: str, sources: dict[str, str]) -> dict: + if not isinstance(repository, str) or not isinstance(revision, str) or not re.fullmatch( + r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository) or not SHA.fullmatch(revision): + raise ValueError("use owner/name and an exact lowercase 40-character commit SHA") + if not isinstance(sources, dict) or not sources or not all( + safe_path(p) and isinstance(s, str) for p, s in sources.items()): + raise ValueError("supply at least one safe repository-relative page path") + return {"schema_version": 1, "repository": repository, "revision": revision, + "renderer_profile": "github", "pages": [ + {"path": path, "url": f"https://github.com/{repository}/blob/{revision}/{quote(path, safe='/')}", + "source_sha256": digest(source), "source_text": source, "expressions": expressions(source)} + for path, source in sources.items()]} + + +def validate(inventory: dict, capture: dict, contract: dict | None = None) -> dict: + """Return failures rather than equating a passing text check with readiness.""" + failures: list[str] = [] + boundaries: list[dict] = [] + exceptions: list[dict] = [] + if not isinstance(inventory, dict) or not isinstance(capture, dict): + raise ValueError("inventory and capture must be JSON objects") + if type(inventory.get("schema_version")) is not int or type(capture.get("schema_version")) is not int or inventory["schema_version"] != 1 or capture["schema_version"] != 1: + raise ValueError("unsupported inventory or capture schema_version") + pages = inventory.get("pages") + if not isinstance(pages, list) or not pages or any(not isinstance(p, dict) for p in pages): + raise ValueError("inventory needs a nonempty pages array") + paths = [p.get("path") for p in pages] + if any(not isinstance(p, str) for p in paths) or len(set(paths)) != len(paths): + raise ValueError("inventory page paths must be unique strings") + rebuilt = make_inventory(inventory.get("repository", ""), inventory.get("revision", ""), + {p["path"]: p["source_text"] for p in pages}) + if inventory != rebuilt: + raise ValueError("inventory does not match its embedded source bytes/expression inventory") + for field in ("repository", "revision", "renderer_profile"): + if capture.get(field) != inventory[field]: + failures.append(f"capture {field} mismatch") + try: + timestamp = datetime.fromisoformat(capture.get("captured_at", "").replace("Z", "+00:00")) + if timestamp.tzinfo is None: + raise ValueError() + except (ValueError, AttributeError, TypeError): + failures.append("capture needs captured_at with a timezone") + if not isinstance(capture.get("capture_method"), str) or not capture["capture_method"].strip(): + failures.append("capture needs a nonempty capture_method") + captured_pages = capture.get("pages") + if not isinstance(captured_pages, list) or any(not isinstance(p, dict) for p in captured_pages): + raise ValueError("capture pages must be an array of objects") + captured_paths = [p.get("path") for p in captured_pages] + if captured_paths != paths: + failures.append("capture page paths/order differ from inventory (missing, extra or duplicate page)") + + contract = {"schema_version": 1, "expressions": []} if contract is None else contract + if not isinstance(contract, dict) or type(contract.get("schema_version")) is not int or contract["schema_version"] != 1 or not isinstance(contract.get("expressions"), list): + raise ValueError("invalid text contract schema") + rules: dict[tuple, dict] = {} + known = {(p["path"], e["index"]): e for p in pages for e in p["expressions"]} + for rule in contract["expressions"]: + if not isinstance(rule, dict): + raise ValueError("contract expressions must be objects") + key = (rule.get("path"), rule.get("index")) + if not isinstance(key[0], str) or type(key[1]) is not int or key not in known or key in rules or rule.get("source_sha256") != known[key]["source_sha256"]: + raise ValueError("unknown, duplicate or stale expression contract") + allowed = {"path", "index", "source_sha256", "required_text", "expected_text", "relation_override", + "allow_html_like_inequality", "reason", "evidence"} + if set(rule) - allowed: + raise ValueError("unknown contract field (contracts cannot skip checks)") + if "expected_text" in rule and (not isinstance(rule["expected_text"], str) or not compact(rule["expected_text"])): + raise ValueError("expected_text must be nonempty text") + if not isinstance(rule.get("required_text", []), list) or any( + not isinstance(v, str) or not compact(v) for v in rule.get("required_text", [])): + raise ValueError("required_text must be an array of nonempty text") + if "expected_text" not in rule and not rule.get("required_text"): + raise ValueError("each expression contract needs expected_text or required_text") + if "allow_html_like_inequality" in rule and not isinstance(rule["allow_html_like_inequality"], bool): + raise ValueError("allow_html_like_inequality must be boolean") + if "relation_override" in rule: + override = rule["relation_override"] + if not isinstance(override, dict) or any(k not in RELATION_SYMBOLS or type(v) is not int or v < 0 + for k, v in override.items()): + raise ValueError("relation_override must map known symbols to nonnegative integer counts") + if "relation_override" in rule or rule.get("allow_html_like_inequality"): + if not all(isinstance(rule.get(k), str) and rule[k].strip() for k in ("expected_text", "reason", "evidence")): + raise ValueError("renderer exception requires expected_text, reason and evidence") + exceptions.append(rule) + rules[key] = rule + + by_path = {p.get("path"): p for p in captured_pages if isinstance(p.get("path"), str)} + checked = 0 + for page in pages: + path = page["path"] + current = by_path.get(path) + if current is None: + continue + boundaries.append({"path": path, "source_sha256": page["source_sha256"], "url": current.get("url"), + "revision": current.get("revision"), "source_expressions": len(page["expressions"]), + "source_spans": [{k: e[k] for k in ("index", "line_start", "line_end", "source_sha256")} + for e in page["expressions"]]}) + for field, expected in (("url", page["url"]), ("revision", inventory["revision"]), ("source_sha256", page["source_sha256"])): + if current.get(field) != expected: + failures.append(f"{path}: captured {field} mismatch") + if current.get("errors") != []: + failures.append(f"{path}: renderer errors present or error evidence missing") + hosts = current.get("math") + if not isinstance(hosts, list): + failures.append(f"{path}: missing math-host array") + continue + boundaries[-1]["captured_hosts"] = len(hosts) + if len(hosts) != len(page["expressions"]): + failures.append(f"{path}: {len(page['expressions'])} source expressions, {len(hosts)} captured hosts") + for expr, host in zip(page["expressions"], hosts): + label = f"{path}:{expr['line_start']} expression {expr['index']}" + rule = rules.get((path, expr["index"]), {}) + if not isinstance(host, dict) or host.get("rendered") is not True or host.get("errors") != []: + failures.append(f"{label}: missing/unrendered host or renderer-error evidence") + continue + if host.get("text_source") not in TEXT_SOURCES or not isinstance(host.get("text"), str) or not compact(host["text"]): + failures.append(f"{label}: missing full accessible mathematical text/source") + continue + checked += 1 + text = compact(host["text"]) + expected = {k: v for k, v in rule.get("relation_override", expr["relations"]).items() if v} + actual = dict(sorted(Counter(c for c in text if c in RELATION_SYMBOLS).items())) + if expected != actual: + failures.append(f"{label}: relation mismatch; expected {expected}, captured {actual}") + for equation_label in expr["labels"]: + if equation_label not in text: + failures.append(f"{label}: missing equation label {equation_label}") + if re.search(r"<\s*[A-Za-z]", tex_body(expr["tex"])) and not rule.get("allow_html_like_inequality"): + failures.append(f"{label}: GitHub HTML-like inequality hazard; use supported syntax or a traced exact-text exception") + if "expected_text" in rule and compact(rule["expected_text"]) != text: + failures.append(f"{label}: full expected_text mismatch") + for required in rule.get("required_text", []): + if compact(required) not in text: + failures.append(f"{label}: missing required_text {required!r}") + return {"schema_version": 1, "status": "fail" if failures else "pass", + "repository": inventory["repository"], "revision": inventory["revision"], + "renderer_profile": inventory["renderer_profile"], "captured_at": capture.get("captured_at"), + "capture_method": capture.get("capture_method"), "boundaries": boundaries, + "expressions_checked": checked, "text_contracts": len(rules), "renderer_exceptions": exceptions, + "failures": failures, "visual_review_required": True, + "limits": "Counts, supported relations/visible labels and explicit text contracts only. No arbitrary TeX equivalence, scientific correctness, capture authentication or visual-layout certification."} + + +def read_json(path: Path) -> dict: + return json.loads(path.read_text(encoding="utf-8")) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + commands = parser.add_subparsers(dest="command", required=True) + inv = commands.add_parser("inventory", help="read math source from an exact local Git commit") + inv.add_argument("--root", type=Path, required=True) + inv.add_argument("--repository", required=True) + inv.add_argument("--revision", required=True) + inv.add_argument("--page", action="append", required=True) + inv.add_argument("--output", type=Path, required=True) + check = commands.add_parser("check", help="check pinned extracted capture; does not fetch or render") + check.add_argument("--inventory", type=Path, required=True) + check.add_argument("--capture", type=Path, required=True) + check.add_argument("--contract", type=Path) + check.add_argument("--output", type=Path) + args = parser.parse_args(argv) + try: + if args.command == "inventory": + if not SHA.fullmatch(args.revision) or len(set(args.page)) != len(args.page) or not all(safe_path(p) for p in args.page): + raise ValueError("use an exact commit SHA and unique safe page paths") + commit = subprocess.check_output(["git", "--no-replace-objects", "rev-parse", f"{args.revision}^{{commit}}"], cwd=args.root, text=True).strip() + if commit != args.revision: + raise ValueError("revision does not identify the supplied commit") + sources = {p: subprocess.check_output(["git", "--no-replace-objects", "show", f"{commit}:{p}"], cwd=args.root).decode("utf-8") for p in args.page} + result = make_inventory(args.repository, commit, sources) + else: + result = validate(read_json(args.inventory), read_json(args.capture), read_json(args.contract) if args.contract else None) + output = json.dumps(result, indent=2, ensure_ascii=False) + "\n" + if args.output: + args.output.write_text(output, encoding="utf-8") + else: + print(output, end="") + return 1 if result.get("status") == "fail" else 0 + except (OSError, UnicodeError, ValueError, KeyError, TypeError, subprocess.CalledProcessError) as error: + print(f"ERROR: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/verification/hosted_math/probe_hosted_math.cjs b/verification/hosted_math/probe_hosted_math.cjs new file mode 100644 index 0000000..f83ea9d --- /dev/null +++ b/verification/hosted_math/probe_hosted_math.cjs @@ -0,0 +1,146 @@ +#!/usr/bin/env node +'use strict'; +// Representative read-only diagnostic, not release-readiness evidence. +// Importing this module neither starts a browser nor visits a site. +const fs = require('node:fs'); +const path = require('node:path'); +const cp = require('node:child_process'); +const crypto = require('node:crypto'); +const collector = require('./capture_hosted_math.cjs'); +const sha256 = bytes => crypto.createHash('sha256').update(bytes).digest('hex'); + +function argumentsFor(argv) { + if (argv.includes('--resume-from')) throw new Error('A diagnostic does not resume captures; use the full collector for that operation'); + const args = collector.argumentsFor(argv); + if (args.help) return args; + if (args.pages.length !== 1) throw new Error('Choose exactly one representative --page for the early diagnostic'); + return args; +} + +function sourceAdvisories(source, page) { + const warnings = []; + let fence = null; + for (const [index, line] of source.split(/\r?\n/).entries()) { + const mark = line.match(/^\s{0,3}(`{3,}|~{3,})/); + if (mark) { + if (!fence) fence = mark[1]; + else if (mark[1][0] === fence[0] && mark[1].length >= fence.length) fence = null; + continue; + } + if (fence) continue; + const inline = [...line.matchAll(/(? warnings.push({code, path:page, line:index+1, message}); + if (tex.includes('<')) add('raw_inline_less_than', 'Inspect raw < in inline mathematics on GitHub; use an appropriate TeX relation if the host truncates it.'); + if (/_[A-Za-z0-9]+_/.test(tex)) add('repeated_unbraced_subscript', 'Inspect a possible repeated unbraced subscript; braces may be needed to express the intended indices.'); + if (/^\s*\|/.test(line) && /(? message.includes(category) || collector.classifyFailure(message) === category)) return category; + } + return messages.length ? 'verification_failure' : null; +} + +function dependencies(args, services = {}) { + const execute = services.execFileSync || cp.execFileSync; + const resolve = services.resolve || require.resolve; + const result = {node:process.version}; + if (Number(process.versions.node.split('.')[0]) < 18) throw new Error('capability_unavailable: Node.js 18 or later is required'); + for (const [key, command, flags] of [['git','git',['--version']], ['python',args.python,['--version']]]) { + try { + result[key] = String(execute(command, flags, {encoding:'utf8',stdio:'pipe'})).trim(); + } catch (error) { + throw new Error('capability_unavailable: Cannot execute '+key+': '+String(error)); + } + } + const pythonVersion = result.python.match(/Python\s+(\d+)\.(\d+)/); + if (!pythonVersion || Number(pythonVersion[1]) < 3 || (Number(pythonVersion[1]) === 3 && Number(pythonVersion[2]) < 10)) + throw new Error('capability_unavailable: Python 3.10 or later is required; observed '+result.python); + for (const name of ['playwright','mathjax-full']) { + try { result[name] = resolve(name+'/package.json'); } + catch (error) { throw new Error('capability_unavailable: Cannot find module '+name+': '+String(error)); } + } + return result; +} + +function emptyOutput(directory) { + const resolved = path.resolve(directory); + if (fs.existsSync(resolved)) { + if (fs.lstatSync(resolved).isSymbolicLink() || !fs.statSync(resolved).isDirectory()) throw new Error('Output must be a regular directory'); + if (fs.readdirSync(resolved).length) throw new Error('Use an empty output directory; preserve earlier diagnostic evidence'); + } + return resolved; +} + +async function run(args, services = {}) { + if (args.pages?.length !== 1 || args['resume-from'] || args.resumeFrom) throw new Error('Diagnostic requires exactly one page and no resumed evidence'); + const output = emptyOutput(args.output); + const at = (services.now || (() => new Date().toISOString()))(); + const execute = services.execFileSync || cp.execFileSync; + const inspectPinned = services.pinnedPages || collector.pinnedPages; + const capture = services.capture || collector.run; + const failures = []; + let pinned, runtime = {}, sourceHash = null, advisories = [], captureReport = null, captureExit = null; + try { + runtime = dependencies(args, services); + pinned = inspectPinned(args); + if (pinned.pages.length !== 1 || pinned.pages[0] !== args.pages[0]) throw new Error('Pinned diagnostic scope differs from the requested page'); + const source = execute('git', ['--no-replace-objects','show',args.revision+':'+args.pages[0]], {cwd:args.root,encoding:'utf8',maxBuffer:32*1024*1024}); + sourceHash = sha256(source); + advisories = sourceAdvisories(String(source), args.pages[0]); + const log = console.log; + // The diagnostic emits one summary of its own; raw collector records remain on disk. + try { console.log = () => {}; captureExit = await capture({...args,output,diagnosticOnly:true}); } + finally { console.log = log; } + const filename = path.join(output,'hosted-report.json'); + if (!fs.existsSync(filename)) throw new Error('Collector did not produce its report'); + const bytes = fs.readFileSync(filename); + captureReport = JSON.parse(bytes); + if (captureReport.repository !== args.repository || captureReport.revision !== args.revision || + captureReport.tree !== pinned.tree || JSON.stringify(captureReport.required_pages) !== JSON.stringify(args.pages)) + throw new Error('Collector diagnostic report identity/scope mismatch'); + if (captureReport.diagnostic_only !== true) throw new Error('Collector did not mark its representative capture as diagnostic-only; use the matching current helper bundle'); + failures.push(...(captureReport.failures || [])); + if (captureExit !== 0 || captureReport.status !== 'pass') { + if (!failures.length) failures.push('Representative hosted comparison did not pass'); + } + } catch (error) { failures.push(String(error)); } + fs.mkdirSync(output,{recursive:true}); + const category = categoryFor(failures); + const filename = path.join(output,'hosted-report.json'); + const report = { + schema_version:1,kind:'hosted_probe',repository:args.repository,revision:args.revision, + tree:pinned?.tree || null,page:args.pages[0],source_sha256:sourceHash, + observed_at:at,status:failures.length?'fail':'pass',failure_category:category,failures, + runtime,advisories,diagnostic_only:true,release_ready:false,release_evidence:false, + capture_report:fs.existsSync(filename)?{path:'hosted-report.json',sha256:sha256(fs.readFileSync(filename))}:null, + limits:'One representative page at the collector\'s two viewports only. This early diagnostic is not full repository review, visual approval, scientific validation, or release-readiness evidence. Source advisories are heuristic and do not prove a rendering defect.', + next_action:!failures.length ? 'Continue furnishing; perform the complete final source-bound hosted and visual review later.' : + category === 'policy_denied' ? 'Record the denial and continue unaffected work; retry only after applicable access evidence changes, without routing around the denial.' : + category === 'access_required' ? 'Identify the actual missing access requirement and resolve it through an authorized flow; preserve the named grant and continue unaffected work.' : + category === 'capability_unavailable' ? 'Use or provision a permitted compatible runtime within the actual grant, then repeat the diagnostic; no access-setting change is implied.' : + category === 'transport_failure' ? 'Preserve this failed attempt and retry the same authorized operation after the transient transport condition changes.' : + 'Inspect the pinned source and captured representative page, repair demonstrated defects within scope, and repeat the diagnostic.' + }; + fs.writeFileSync(path.join(output,'probe-report.json'),JSON.stringify(report,null,2)+'\n'); + return {code:report.status==='pass'?0:1,report}; +} + +module.exports = {argumentsFor,sourceAdvisories,categoryFor,dependencies,emptyOutput,run}; +if (require.main === module) { + (async () => { + const args = argumentsFor(process.argv.slice(2)); + if (args.help) { console.log('probe_hosted_math.cjs --root REPO --repository owner/name --revision FULLSHA --page REPRESENTATIVE.md --output EMPTY_DIR [--contract JSON] [--python python3]'); return; } + const result = await run(args); + console.log(JSON.stringify({status:result.report.status,category:result.report.failure_category,report:path.join(path.resolve(args.output),'probe-report.json'),release_ready:false})); + process.exitCode = result.code; + })().catch(error => {console.error(String(error));process.exitCode=2;}); +} From a7c0429910b779567ff941c0750805003990bef0 Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Mon, 30 Nov 2026 16:50:58 +0800 Subject: [PATCH 3/8] Probe the exact rotated surface patch proof page --- .github/workflows/hosted-math.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/hosted-math.yml b/.github/workflows/hosted-math.yml index fe11935..48516e5 100644 --- a/.github/workflows/hosted-math.yml +++ b/.github/workflows/hosted-math.yml @@ -20,7 +20,7 @@ jobs: timeout-minutes: 30 env: CAPTURE_REVISION: 337360a11aafbb8286b0d9f7cffa664b917e4fe9 - REPRESENTATIVE_PAGE: science/rotated_patch.md + REPRESENTATIVE_PAGE: science/rotated_surface_patch.md steps: - name: Check out the validation helpers uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 From 7c59b860785ef02046c9e3dbf999ce04fdec582d Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Mon, 30 Nov 2026 16:53:46 +0800 Subject: [PATCH 4/8] Recheck the pinned scientific source after hosted formatting repairs --- .github/workflows/hosted-math.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/hosted-math.yml b/.github/workflows/hosted-math.yml index 48516e5..8e27613 100644 --- a/.github/workflows/hosted-math.yml +++ b/.github/workflows/hosted-math.yml @@ -19,7 +19,7 @@ jobs: runs-on: ubuntu-24.04 timeout-minutes: 30 env: - CAPTURE_REVISION: 337360a11aafbb8286b0d9f7cffa664b917e4fe9 + CAPTURE_REVISION: 47724c016826b9c49a1e37b65c802e429860a69a REPRESENTATIVE_PAGE: science/rotated_surface_patch.md steps: - name: Check out the validation helpers From 649bb0a7feffb1f02ee341529dfcf1535b985ef2 Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Mon, 30 Nov 2026 16:56:55 +0800 Subject: [PATCH 5/8] Diagnose missing hosts on the exact proof revision --- .github/workflows/hosted-math.yml | 88 +++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) diff --git a/.github/workflows/hosted-math.yml b/.github/workflows/hosted-math.yml index 8e27613..8d3e19a 100644 --- a/.github/workflows/hosted-math.yml +++ b/.github/workflows/hosted-math.yml @@ -50,6 +50,94 @@ jobs: --revision "$CAPTURE_REVISION" \ --page "$REPRESENTATIVE_PAGE" \ --output "$RUNNER_TEMP/hosted-probe" + - name: Record observed math hosts for the representative page + if: ${{ !cancelled() }} + run: | + export NODE_PATH="$RUNNER_TEMP/math-runtime/node_modules" + node - "$RUNNER_TEMP/hosted-probe/math-source.json" "$RUNNER_TEMP/hosted-diagnostic" <<'HOSTED_DIAGNOSTIC' + 'use strict'; + const {chromium}=require('playwright'); + const {writeFile,readFile,mkdir}=require('node:fs/promises'); + const {join}=require('node:path'); + const {setTimeout:wait}=require('node:timers/promises'); + const [inventoryFile,output]=process.argv.slice(2); + (async () => { + const source=JSON.parse(await readFile(inventoryFile,'utf8')).pages[0]; + await mkdir(output,{recursive:true}); + const browser=await chromium.launch({headless:true}); + try { + for (const width of [1440,760]) { + const context=await browser.newContext({viewport:{width,height:960}}); + try { + const page=await context.newPage(); + const response=await page.goto(source.url,{waitUntil:'domcontentloaded',timeout:60000}); + const htmlPath=join(output,`diagnostic-${width}.html`); + if(response?.status()!==200 || page.url()!==source.url){ + await writeFile(htmlPath,await page.content()); + await writeFile(join(output,`diagnostic-${width}.json`),JSON.stringify({width,expected:source.url,url:page.url(),status:response?.status()},null,2)); + continue; + } + const article=page.locator('article.markdown-body').first(); + await article.waitFor({state:'visible',timeout:30000}); + for(let y=0;y document.body.scrollHeight);y+=800){ + await page.evaluate(top => window.scrollTo(0,top),y); await wait(75); + } + await page.evaluate(() => window.scrollTo(0,0)); + await wait(5000); + const observation=await article.evaluate(root=>{ + const hosts=[...root.querySelectorAll('math-renderer')]; + const usable=hosts.filter(h=>!!h.querySelector('math')); + return {hosts:hosts.length,math:usable.length,unparsed:root.innerText.split('\n').filter(x=>x.includes(' + if: ${{ !cancelled() }} + run: | + export NODE_PATH="$RUNNER_TEMP/math-runtime/node_modules" + node verification/hosted_math/capture_hosted_math.cjs \ + --root "$GITHUB_WORKSPACE/checked-source" \ + --repository "$GITHUB_REPOSITORY" \ + --revision "$CAPTURE_REVISION" \ + --output "$RUNNER_TEMP/hosted-first" || { + result=$? + if test -f "$RUNNER_TEMP/hosted-first/hosted-report.json" && + grep -Eq 'HTTP (502|503|504)' "$RUNNER_TEMP/hosted-first/hosted-report.json"; then + node verification/hosted_math/capture_hosted_math.cjs \ + --root "$GITHUB_WORKSPACE/checked-source" \ + --repository "$GITHUB_REPOSITORY" \ + --revision "$CAPTURE_REVISION" \ + --output "$RUNNER_TEMP/hosted-resume" \ + --resume-from "$RUNNER_TEMP/hosted-first" + else + exit "$result" + fi + } + - name: Retain the captures and comparison reports + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: hosted-math-${{ env.CAPTURE_REVISION }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/hosted-first + ${{ runner.temp }}/hosted-resume + ${{ runner.temp }}/hosted-probe + ${{ runner.temp }}/hosted-diagnostic + if-no-files-found: error + retention-days: 14 +)), + formulas:hosts.map(h=>[h.querySelector('math')?.getAttribute('data-latex')||h.textContent.trim(),h.className]), + errors:[...root.querySelectorAll('merror,[data-mjx-error],.katex-error,math-renderer .flash-error')].map(e=>e.textContent.trim())}; + }); + await writeFile(htmlPath,await page.content()); + await page.screenshot({path:join(output,`diagnostic-${width}.png`),fullPage:true}); + await writeFile(join(output,`diagnostic-${width}.json`),JSON.stringify({width,url:source.url,status:response.status(),expected:source.expressions.map(x=>x.tex),...observation},null,2)); + console.log(JSON.stringify({width,status:response.status(),expected:source.expressions.length,hosts:observation.hosts,math:observation.math,unparsed:observation.unparsed,errors:observation.errors})); + } finally { + await context.close(); + } + } + } finally { + await browser.close(); + } + })().catch(error=>{console.error(error);process.exitCode=1;}); + HOSTED_DIAGNOSTIC - name: Compare all hosted pages at both widths if: ${{ !cancelled() }} run: | From b10d2a1a8b1f835271ddcd1f8df14de16fd58733 Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Mon, 30 Nov 2026 16:59:33 +0800 Subject: [PATCH 6/8] Run full validation and retain diagnostic browser observations --- .github/workflows/hosted-math.yml | 46 ++++++------------------------- 1 file changed, 9 insertions(+), 37 deletions(-) diff --git a/.github/workflows/hosted-math.yml b/.github/workflows/hosted-math.yml index 8d3e19a..05cd621 100644 --- a/.github/workflows/hosted-math.yml +++ b/.github/workflows/hosted-math.yml @@ -50,11 +50,15 @@ jobs: --revision "$CAPTURE_REVISION" \ --page "$REPRESENTATIVE_PAGE" \ --output "$RUNNER_TEMP/hosted-probe" - - name: Record observed math hosts for the representative page + - name: Record observed math host counts on the affected pages if: ${{ !cancelled() }} run: | export NODE_PATH="$RUNNER_TEMP/math-runtime/node_modules" - node - "$RUNNER_TEMP/hosted-probe/math-source.json" "$RUNNER_TEMP/hosted-diagnostic" <<'HOSTED_DIAGNOSTIC' + for page in science/rotated_surface_patch.md; do + diagnostic="$RUNNER_TEMP/hosted-diagnostic/${page##*/}" + mkdir -p "$diagnostic" + python3 verification/hosted_math/check_rendered_math.py inventory --root "$GITHUB_WORKSPACE/checked-source" --repository "$GITHUB_REPOSITORY" --revision "$CAPTURE_REVISION" --page "$page" --output "$diagnostic/inventory.json" + node - "$diagnostic/inventory.json" "$diagnostic" <<'HOSTED_DIAGNOSTIC' 'use strict'; const {chromium}=require('playwright'); const {writeFile,readFile,mkdir}=require('node:fs/promises'); @@ -87,41 +91,7 @@ jobs: const observation=await article.evaluate(root=>{ const hosts=[...root.querySelectorAll('math-renderer')]; const usable=hosts.filter(h=>!!h.querySelector('math')); - return {hosts:hosts.length,math:usable.length,unparsed:root.innerText.split('\n').filter(x=>x.includes(' - if: ${{ !cancelled() }} - run: | - export NODE_PATH="$RUNNER_TEMP/math-runtime/node_modules" - node verification/hosted_math/capture_hosted_math.cjs \ - --root "$GITHUB_WORKSPACE/checked-source" \ - --repository "$GITHUB_REPOSITORY" \ - --revision "$CAPTURE_REVISION" \ - --output "$RUNNER_TEMP/hosted-first" || { - result=$? - if test -f "$RUNNER_TEMP/hosted-first/hosted-report.json" && - grep -Eq 'HTTP (502|503|504)' "$RUNNER_TEMP/hosted-first/hosted-report.json"; then - node verification/hosted_math/capture_hosted_math.cjs \ - --root "$GITHUB_WORKSPACE/checked-source" \ - --repository "$GITHUB_REPOSITORY" \ - --revision "$CAPTURE_REVISION" \ - --output "$RUNNER_TEMP/hosted-resume" \ - --resume-from "$RUNNER_TEMP/hosted-first" - else - exit "$result" - fi - } - - name: Retain the captures and comparison reports - if: always() - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 - with: - name: hosted-math-${{ env.CAPTURE_REVISION }}-${{ github.run_attempt }} - path: | - ${{ runner.temp }}/hosted-first - ${{ runner.temp }}/hosted-resume - ${{ runner.temp }}/hosted-probe - ${{ runner.temp }}/hosted-diagnostic - if-no-files-found: error - retention-days: 14 -)), + return {hosts:hosts.length,math:usable.length,unparsed:root.innerText.split('\n').filter(x=>x.includes('$')), formulas:hosts.map(h=>[h.querySelector('math')?.getAttribute('data-latex')||h.textContent.trim(),h.className]), errors:[...root.querySelectorAll('merror,[data-mjx-error],.katex-error,math-renderer .flash-error')].map(e=>e.textContent.trim())}; }); @@ -138,6 +108,7 @@ jobs: } })().catch(error=>{console.error(error);process.exitCode=1;}); HOSTED_DIAGNOSTIC + done - name: Compare all hosted pages at both widths if: ${{ !cancelled() }} run: | @@ -169,5 +140,6 @@ jobs: ${{ runner.temp }}/hosted-first ${{ runner.temp }}/hosted-resume ${{ runner.temp }}/hosted-probe + ${{ runner.temp }}/hosted-diagnostic if-no-files-found: error retention-days: 14 From 310641403da68b79231b1ce56dfb4b91f752c704 Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Mon, 30 Nov 2026 17:02:31 +0800 Subject: [PATCH 7/8] Validate the exact final science with paced hosted navigation --- .github/workflows/hosted-math.yml | 154 ++++++++++++++---------------- 1 file changed, 72 insertions(+), 82 deletions(-) diff --git a/.github/workflows/hosted-math.yml b/.github/workflows/hosted-math.yml index 05cd621..88792dd 100644 --- a/.github/workflows/hosted-math.yml +++ b/.github/workflows/hosted-math.yml @@ -19,7 +19,7 @@ jobs: runs-on: ubuntu-24.04 timeout-minutes: 30 env: - CAPTURE_REVISION: 47724c016826b9c49a1e37b65c802e429860a69a + CAPTURE_REVISION: 48e6ff477a6b8abe76860c95e653f2715301a85a REPRESENTATIVE_PAGE: science/rotated_surface_patch.md steps: - name: Check out the validation helpers @@ -41,105 +41,95 @@ jobs: run: | npm install --prefix "$RUNNER_TEMP/math-runtime" playwright@1.56.1 mathjax-full@3.2.1 node "$RUNNER_TEMP/math-runtime/node_modules/playwright/cli.js" install chromium + - name: Pace GitHub navigation + run: | + cat > "$RUNNER_TEMP/hosted-navigation-pacing.cjs" <<'PACING_SCRIPT' + 'use strict'; + + const {setTimeout: delay} = require('node:timers/promises'); + const {chromium} = require('playwright'); + const launch = chromium.launch.bind(chromium); + const intervalMs = 3000; + let previousStart = 0; + + chromium.launch = async (...args) => { + const browser = await launch(...args); + const originalNewContext = browser.newContext.bind(browser); + browser.newContext = async (...contextArgs) => { + const context = await originalNewContext(...contextArgs); + const originalNewPage = context.newPage.bind(context); + context.newPage = async (...pageArgs) => { + const page = await originalNewPage(...pageArgs); + const originalGoto = page.goto.bind(page); + page.goto = async (url, options) => { + if (new URL(url).hostname === 'github.com') { + await delay(Math.max(0, previousStart + intervalMs - Date.now())); + previousStart = Date.now(); + } + return originalGoto(url, options); + }; + return page; + }; + return context; + }; + return browser; + }; + PACING_SCRIPT - name: Probe representative mathematics at both widths + continue-on-error: true run: | export NODE_PATH="$RUNNER_TEMP/math-runtime/node_modules" - node verification/hosted_math/probe_hosted_math.cjs \ + node --require "$RUNNER_TEMP/hosted-navigation-pacing.cjs" verification/hosted_math/probe_hosted_math.cjs \ --root "$GITHUB_WORKSPACE/checked-source" \ --repository "$GITHUB_REPOSITORY" \ --revision "$CAPTURE_REVISION" \ --page "$REPRESENTATIVE_PAGE" \ --output "$RUNNER_TEMP/hosted-probe" - - name: Record observed math host counts on the affected pages - if: ${{ !cancelled() }} - run: | - export NODE_PATH="$RUNNER_TEMP/math-runtime/node_modules" - for page in science/rotated_surface_patch.md; do - diagnostic="$RUNNER_TEMP/hosted-diagnostic/${page##*/}" - mkdir -p "$diagnostic" - python3 verification/hosted_math/check_rendered_math.py inventory --root "$GITHUB_WORKSPACE/checked-source" --repository "$GITHUB_REPOSITORY" --revision "$CAPTURE_REVISION" --page "$page" --output "$diagnostic/inventory.json" - node - "$diagnostic/inventory.json" "$diagnostic" <<'HOSTED_DIAGNOSTIC' - 'use strict'; - const {chromium}=require('playwright'); - const {writeFile,readFile,mkdir}=require('node:fs/promises'); - const {join}=require('node:path'); - const {setTimeout:wait}=require('node:timers/promises'); - const [inventoryFile,output]=process.argv.slice(2); - (async () => { - const source=JSON.parse(await readFile(inventoryFile,'utf8')).pages[0]; - await mkdir(output,{recursive:true}); - const browser=await chromium.launch({headless:true}); - try { - for (const width of [1440,760]) { - const context=await browser.newContext({viewport:{width,height:960}}); - try { - const page=await context.newPage(); - const response=await page.goto(source.url,{waitUntil:'domcontentloaded',timeout:60000}); - const htmlPath=join(output,`diagnostic-${width}.html`); - if(response?.status()!==200 || page.url()!==source.url){ - await writeFile(htmlPath,await page.content()); - await writeFile(join(output,`diagnostic-${width}.json`),JSON.stringify({width,expected:source.url,url:page.url(),status:response?.status()},null,2)); - continue; - } - const article=page.locator('article.markdown-body').first(); - await article.waitFor({state:'visible',timeout:30000}); - for(let y=0;y document.body.scrollHeight);y+=800){ - await page.evaluate(top => window.scrollTo(0,top),y); await wait(75); - } - await page.evaluate(() => window.scrollTo(0,0)); - await wait(5000); - const observation=await article.evaluate(root=>{ - const hosts=[...root.querySelectorAll('math-renderer')]; - const usable=hosts.filter(h=>!!h.querySelector('math')); - return {hosts:hosts.length,math:usable.length,unparsed:root.innerText.split('\n').filter(x=>x.includes('$')), - formulas:hosts.map(h=>[h.querySelector('math')?.getAttribute('data-latex')||h.textContent.trim(),h.className]), - errors:[...root.querySelectorAll('merror,[data-mjx-error],.katex-error,math-renderer .flash-error')].map(e=>e.textContent.trim())}; - }); - await writeFile(htmlPath,await page.content()); - await page.screenshot({path:join(output,`diagnostic-${width}.png`),fullPage:true}); - await writeFile(join(output,`diagnostic-${width}.json`),JSON.stringify({width,url:source.url,status:response.status(),expected:source.expressions.map(x=>x.tex),...observation},null,2)); - console.log(JSON.stringify({width,status:response.status(),expected:source.expressions.length,hosts:observation.hosts,math:observation.math,unparsed:observation.unparsed,errors:observation.errors})); - } finally { - await context.close(); - } - } - } finally { - await browser.close(); - } - })().catch(error=>{console.error(error);process.exitCode=1;}); - HOSTED_DIAGNOSTIC - done - name: Compare all hosted pages at both widths if: ${{ !cancelled() }} run: | export NODE_PATH="$RUNNER_TEMP/math-runtime/node_modules" - node verification/hosted_math/capture_hosted_math.cjs \ - --root "$GITHUB_WORKSPACE/checked-source" \ - --repository "$GITHUB_REPOSITORY" \ - --revision "$CAPTURE_REVISION" \ - --output "$RUNNER_TEMP/hosted-first" || { - result=$? - if test -f "$RUNNER_TEMP/hosted-first/hosted-report.json" && - grep -Eq 'HTTP (502|503|504)' "$RUNNER_TEMP/hosted-first/hosted-report.json"; then - node verification/hosted_math/capture_hosted_math.cjs \ - --root "$GITHUB_WORKSPACE/checked-source" \ - --repository "$GITHUB_REPOSITORY" \ - --revision "$CAPTURE_REVISION" \ - --output "$RUNNER_TEMP/hosted-resume" \ - --resume-from "$RUNNER_TEMP/hosted-first" - else - exit "$result" - fi - } + previous= + for attempt in 1 2 3; do + output="$RUNNER_TEMP/hosted-attempt-$attempt" + options=() + if [ -n "$previous" ]; then + options=(--resume-from "$previous") + fi + if node --require "$RUNNER_TEMP/hosted-navigation-pacing.cjs" verification/hosted_math/capture_hosted_math.cjs \ + --root "$GITHUB_WORKSPACE/checked-source" \ + --repository "$GITHUB_REPOSITORY" \ + --revision "$CAPTURE_REVISION" \ + --output "$output" "${options[@]}"; then + exit 0 + fi + python3 - "$output/capture-state.json" <<'RETRY_POLICY' + import json + from pathlib import Path + import re + import sys + path = Path(sys.argv[1]) + if not path.is_file(): + sys.exit(1) + failures = json.loads(path.read_bytes())["failures"] + eligible = bool(failures) and all( + item["category"] == "transport_failure" and + re.search(r"HTTP (502|503|504)|ERR_EMPTY_RESPONSE", json.dumps(item)) + for item in failures + ) + sys.exit(0 if eligible else 1) + RETRY_POLICY + previous="$output" + sleep 25 + done + exit 1 - name: Retain the captures and comparison reports if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with: name: hosted-math-${{ env.CAPTURE_REVISION }}-${{ github.run_attempt }} path: | - ${{ runner.temp }}/hosted-first - ${{ runner.temp }}/hosted-resume + ${{ runner.temp }}/hosted-attempt-* ${{ runner.temp }}/hosted-probe - ${{ runner.temp }}/hosted-diagnostic if-no-files-found: error retention-days: 14 From b67928fbc2c6c1ef0431de59da317c0ca2aeaa93 Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Mon, 30 Nov 2026 17:08:29 +0800 Subject: [PATCH 8/8] Validate all changed Markdown at both widths --- .github/workflows/hosted-math.yml | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/.github/workflows/hosted-math.yml b/.github/workflows/hosted-math.yml index 88792dd..600aa32 100644 --- a/.github/workflows/hosted-math.yml +++ b/.github/workflows/hosted-math.yml @@ -19,8 +19,16 @@ jobs: runs-on: ubuntu-24.04 timeout-minutes: 30 env: - CAPTURE_REVISION: 48e6ff477a6b8abe76860c95e653f2715301a85a + CAPTURE_REVISION: e80c50c43b991cddd33020a1390cf63cb03bf6f7 REPRESENTATIVE_PAGE: science/rotated_surface_patch.md + CAPTURE_PAGES: | + README.md + learning/MILESTONES.md + learning/PRESKILL_BRIDGE.md + learning/README.md + science/README.md + science/rotated_surface_patch.md + verification/README.md steps: - name: Check out the validation helpers uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 @@ -85,10 +93,16 @@ jobs: --revision "$CAPTURE_REVISION" \ --page "$REPRESENTATIVE_PAGE" \ --output "$RUNNER_TEMP/hosted-probe" - - name: Compare all hosted pages at both widths + - name: Compare every changed Markdown page at both widths if: ${{ !cancelled() }} run: | export NODE_PATH="$RUNNER_TEMP/math-runtime/node_modules" + page_arguments=() + while IFS= read -r page; do + if [ -n "$page" ]; then page_arguments+=(--page "$page"); fi + done <<< "$CAPTURE_PAGES" + test "${#page_arguments[@]}" -gt 0 + printf '%s' "$CAPTURE_PAGES" > "$RUNNER_TEMP/hosted-scope.txt" previous= for attempt in 1 2 3; do output="$RUNNER_TEMP/hosted-attempt-$attempt" @@ -100,7 +114,7 @@ jobs: --root "$GITHUB_WORKSPACE/checked-source" \ --repository "$GITHUB_REPOSITORY" \ --revision "$CAPTURE_REVISION" \ - --output "$output" "${options[@]}"; then + --output "$output" "${page_arguments[@]}" "${options[@]}"; then exit 0 fi python3 - "$output/capture-state.json" <<'RETRY_POLICY' @@ -131,5 +145,6 @@ jobs: path: | ${{ runner.temp }}/hosted-attempt-* ${{ runner.temp }}/hosted-probe + ${{ runner.temp }}/hosted-scope.txt if-no-files-found: error retention-days: 14