From 88087169637713e458e819840d1e50bc9ba22bbf Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Sat, 17 Oct 2026 15:53:33 +0800 Subject: [PATCH 1/4] Prepare the authorized topic-based repository refurnishing --- .github/refurnish.py | 149 +++++++++++++++++++ .github/workflows/refurnish-once.yml | 33 +++++ AGENTS.md | 46 +++--- README.md | 85 +++++------ check_repository.py | 83 ++++++----- learning/README.md | 20 +++ llms.txt | 45 +++--- science/README.md | 38 +++++ science/interpretation.md | 57 ++++++++ verification/tools/check_learning.py | 49 +++++++ verification/tools/check_release.py | 73 ++++++++++ verification/tools/inspect_hosted_render.py | 154 ++++++++++++++++++++ verification/tools/test_structure.py | 130 +++++++++++++++++ 13 files changed, 834 insertions(+), 128 deletions(-) create mode 100644 .github/refurnish.py create mode 100644 .github/workflows/refurnish-once.yml create mode 100644 learning/README.md create mode 100644 science/README.md create mode 100644 science/interpretation.md create mode 100644 verification/tools/check_learning.py create mode 100644 verification/tools/check_release.py create mode 100644 verification/tools/inspect_hosted_render.py create mode 100644 verification/tools/test_structure.py diff --git a/.github/refurnish.py b/.github/refurnish.py new file mode 100644 index 0000000..0a3e4ef --- /dev/null +++ b/.github/refurnish.py @@ -0,0 +1,149 @@ +"""One-time, branch-confined migration; removed before the furnished revision is merged.""" +from pathlib import Path +import os +import posixpath +import re +import shutil +import subprocess + +ROOT = Path(__file__).resolve().parents[1] +assert os.environ.get('GITHUB_REPOSITORY') == 'GoGoKo699/Quantum-Routing-Bandwidth' +assert os.environ.get('GITHUB_REF') == 'refs/heads/refurnish/current-guidance-20261017' +assert subprocess.check_output(['git','rev-parse','HEAD^'],cwd=ROOT,text=True).strip() == '39ad350c7563f0908034eef21a0024bd6121df13' +subprocess.run(['git','diff','--exit-code','HEAD^','--','docs','checks','results','references.bib','requirements.txt','verify.py','LICENSE'],cwd=ROOT,check=True) + +mapping = { + 'docs/bandwidth.md':'science/bandwidth.md', + 'docs/mixed-helpers.md':'science/mixed-helpers.md', + 'docs/entropy-flow.md':'science/entropy-flow.md', + 'docs/control-models.md':'science/control-models.md', + 'docs/accuracy-and-resources.md':'science/accuracy-and-resources.md', + 'docs/theorem-map.md':'science/theorem-map.md', + 'docs/learning.md':'learning/WATROUS_BRIDGE.md', + 'docs/learning-bridges.md':'learning/WORKED_EXAMPLES.md', + 'docs/milestones.md':'learning/MILESTONES.md', + 'docs/related-work.md':'references/RELATED_WORK.md', + 'references.bib':'references/references.bib', + 'docs/verification.md':'verification/README.md', + 'verify.py':'verification/run_all.py', + 'requirements.txt':'verification/requirements.txt', + 'docs/coaching.md':None, +} +for folder in ('checks','results'): + for p in (ROOT/folder).iterdir(): + if p.is_file():mapping[str(p.relative_to(ROOT))]='verification/'+str(p.relative_to(ROOT)) +original={src:(ROOT/src).read_bytes() for src in mapping} + +def relink(text,old,new): + def link(m): + label,target=m[1],m[2] + if re.match(r'[a-zA-Z][\w+.-]*:',target) or target.startswith('//'):return m[0] + path,sep,frag=target.partition('#') + full=posixpath.normpath(posixpath.join(posixpath.dirname(old),path)) if path else old + dest=mapping.get(full,full) + if dest is None:return label + relative=posixpath.relpath(dest,posixpath.dirname(new) or '.') if dest!=new or path else '' + return f'[{label}]({relative}{sep}{frag})' + return re.sub(r'\[([^\]\n]+)\]\(([^\s)]+)\)',link,text) + +for src,dst in mapping.items(): + if dst is None:continue + raw=original[src] + if src.endswith('.md'):raw=relink(raw.decode(),src,dst).encode() + out=ROOT/dst;out.parent.mkdir(parents=True,exist_ok=True);out.write_bytes(raw) + +connections = [ + 'A routing operation must preserve relative phases as well as populations. This is why the same hardware is tested on unknown quantum data rather than a known classical label.', + 'The partial trace forgets correlations. The reference-assisted routing test later distinguishes outputs that have identical local density operators but carry different quantum information.', + 'Purification turns preservation of unknown information into preservation of entanglement. References supply a test of the operation without adding controllable qubits to the resource budget.', + 'A normalized Choi state describes one complete channel test; an inserted helper preparation instead fixes part of a larger isometry. Keeping these representations separate prevents the helper promise from becoming an arbitrary-input promise.', + 'Watrous uses root fidelity, whereas the verification programs report squared pure-target overlaps. The square and the trace-distance factor matter when transporting an accuracy bound into the converse.', + 'The diamond norm allows an inaccessible reference to accompany any payload input. The fixed helper purification makes joint restoration part of the output comparison without granting control of the preparation reference.', + 'Internal unitaries can concentrate polarization locally but cannot change the physical state\'s total entropy deficit. That conservation law remains available even when the control sequence is unrestricted.', + 'Relative entropy to a normalized exponential operator bounds a state-weighted second moment. This variational step connects preparation quality to usable interaction strength without requiring simultaneous diagonalization.', + 'An approximate swap must still establish mutual information between the payload/reference subsystems on opposite sides. Choosing those subsystems removes an unnecessary continuity penalty proportional to the helper count.', + 'Orthogonal Pauli coefficients add quadratically under normalized trace, while aligned extremal eigenvalues may add linearly. The proof needs the former together with the actual state\'s spectral weight, not an input-uniform replacement for operator norm.', + 'Treating module unitaries as instantaneous isolates the interface resource. Charging their duration changes the comparator, just as replacing individual contact bounds by an aggregate strength bound changes the theorem.', + 'A reversible basis permutation changes where a spectrum is supported, not its eigenvalues. A prescribed product of commuting conjugated evolutions then realizes a Hamiltonian average coherently, rather than randomizing the output channel.', + 'The probability of an entire zero-prefix subspace is the useful preparation promise. It controls a coherent operation on all payload inputs even though the compressed prefix bits need not be independently pure.', + 'The two helper tasks keep payload, contacts, allowed internal processing, and restoration obligations fixed. Identifying the one altered input promise is necessary before calling their times a resource separation.', + 'The bus dimension limits the conditional-log fluctuation factor even when the register includes large references. The remaining state-weighted interaction factor is where geometry and initialization enter.', + 'Cut-local terms cannot change the cut entropy. Removing them by an orthogonal coefficient projection is justified in normalized Frobenius norm, avoiding an unsupported operator-norm step.', + 'Gaussian-type spectral tails constrain the contact, while relative entropy constrains the evolving state. Their combination prevents unlimited internal processing from concentrating arbitrary weight in the strongest part of the spectrum.', + 'The payload marginals can remain maximally mixed throughout a perfect exchange. The reference cut reveals the required transfer through correlations and gives a payload-sized condition for approximate success.', + 'Integrating a state-dependent rate gives a lower bound on every permitted schedule, not merely on the constructed protocol. The ensemble version retains its common-input-control condition and permits specially prepared states outside that premise.', + 'The encoding separates the target\'s sign from the spectators\' magnitude. Because it is a bijection, the spectators\' unknown information is retained rather than erased to obtain the larger contact.', + 'Each block only needs a uniform marginal list because the contact is additive over blocks. Commutation then gives an exact finite-time operator identity, and reference preservation follows from identity on the spectator factors.', + 'Clean leaders can be reversibly correlated with the target so their block strengths add. The balanced partition relates this local mechanism to the total number of contacts and initialized helpers.', + 'A local gate identity becomes useful for routing only when the complete wire permutation, its phase, and the bus\'s original information are restored. The buffered sequence meets those requirements without a clean-bus assumption.', + 'An upper bound alone demonstrates feasibility; the entropy lower bound limits every admissible alternative. Their common exponent establishes optimal interaction-time scaling for each exact helper promise.', + 'Reversible concentration transfers entropy into qubits that the contact amplifier can use as occupied spectators. No pure qubits are created by a reset, and small bias is handled by the same bound or the no-concentration fallback.', + 'All gates are correct on the same invariant preparation sector with one common phase. This is why initial preparation error need not add gate by gate, whereas new control errors have a separate composition bound.', + 'The quantity one plus the total iid entropy deficit joins the unknown-helper and polarized-helper regimes. Uniformity in the bias is separate from uniformity as the allowed error tends to zero.', + 'Full rank forces every eigenstate component to implement the exact unitary when zero error is required. At nonzero error, spectral concentration permits discarding only a small weight in the error analysis; a broad maximally mixed component can prevent that concentration.', + 'A finite construction beats the full comparator class only when its upper bound lies below the class\'s lower bound. The resource analysis then determines whether that comparison concerns contact time, count, quadratic strength, or a fixed sum of strengths.', + 'The result joins a reference-assisted information requirement, a conserved preparation budget, and a coherent realization. Its significance is a matched interface-resource law with explicit initialization and accuracy assumptions, not an assertion of faster noisy hardware.' +] +p=ROOT/'learning/MILESTONES.md';text=p.read_text() +body=text[text.index('## Background and preliminaries'):text.index('## Completion')] +body=re.sub(r' \*\*Teaching intensity:\*\* [123]\.', '', body) +parts=list(re.finditer(r'^### (M\d{2})\.',body,re.M));out=[] +assert len(parts)==len(connections)==30 +for i,h in enumerate(parts): + end=parts[i+1].start() if i+1 set[str]: found = set() + occurrences = {} + in_fence = False for line in text.splitlines(): - if re.match(r'^#{1,6} ', line): + if line.startswith('```'): + in_fence = not in_fence + if not in_fence and re.match(r'^#{1,6} ', line): title = re.sub(r'^#{1,6} ', '', line).lower() - found.add(re.sub(r'[^\w\- ]', '', title).replace(' ', '-')) + slug = re.sub(r'[^\w\- ]', '', title).replace(' ', '-') + count = occurrences.get(slug, 0) + occurrences[slug] = count+1 + found.add(slug if count == 0 else f'{slug}-{count}') return found + def main() -> None: if not __debug__: - raise RuntimeError('Repository checks require Python assertions.') - markdown = [ROOT/'README.md', ROOT/'AGENTS.md', ROOT/'llms.txt', *sorted((ROOT/'docs').glob('*.md'))] - link_count = 0 - for path in markdown: + raise RuntimeError('Repository checks require assertions.') + pages = reading_pages(ROOT) + links = 0 + for path in pages: text = path.read_text() clean = re.sub(r'```.*?```', '', text, flags=re.S) - assert '\\[' not in clean and '\\]' not in clean, f'Use dollar math: {path}' - assert len(re.findall(r'^\$\$$', clean, flags=re.M)) % 2 == 0, f'Unclosed display math: {path}' + assert '/mnt/data/' not in text and 'sandbox:' not in text, f'Runtime path in {path}' + assert not re.search(r'GoGoKo699/Guinevere|preferences/TUTORIALS', text), f'Private dependency in {path}' inline = re.sub(r'\$\$.*?\$\$', '', clean, flags=re.S) assert len(re.findall(r'(? Reusable initialization and the optimal interaction-time bandwidth of a bounded qubit interface. One educational anchor, a common 30-milestone learning map, and canonical scientific proofs. +> Matched interaction-time laws for exchanging unknown registers through a bounded qubit bus, with reusable clean or independently mixed helpers. -## Learning +## Story and scientific results -- [Milestone map](docs/milestones.md): QRB-W18-30-v1; exactly M01–M30, with 14 background and 16 narrative targets. This is the shared project map, not a learner's progress record. -- [Watrous anchor](docs/learning.md): The Theory of Quantum Information (2018), selected sections, notation/normalization translations, author access and errata. The only educational anchor. -- [Worked bridges](docs/learning-bridges.md): Reference-assisted information flow, occupied-data amplification, and reversible mixed-helper preparation. -- [Coaching](docs/coaching.md): Revise → Learn → Test, challenge retries, immediate learning feedback, answer-selection interface, and completion rules. Do not start or score a lesson during repository maintenance. +- [Scientific account](science/README.md): Physical question, model, principal result, and connected reading route. +- [Theorem map](science/theorem-map.md): Exact quantifiers, proof dependencies, and canonical statement locations. +- [Information flow](science/entropy-flow.md): Conditional variance, singular-state support, and weighted-interface ensemble bounds. +- [Exact helper laws](science/bandwidth.md): Physical entropy budget and spectator-preserving coherent constructions. +- [Imperfect preparation](science/mixed-helpers.md): Fixed-error iid law, joint/reference restoration, full-rank zero-error boundary, and correlated-state counterexample. +- [Accuracy and resources](science/accuracy-and-resources.md): Finite certificates against the full comparator class, synchronized lists, fresh-payload reuse, and alternate contact budgets. +- [Finite control](science/control-models.md): An explicit bounded-strength compiler, separate from the free-internal-control theorem. +- [Physical interpretation](science/interpretation.md): How contact geometry, unknown data, and reusable preparation determine the operational comparison. -## Authoritative research +## Study -- [Theorem map](docs/theorem-map.md): Claims, assumptions, proof dependencies, and direct specialist route. -- [Mixed helpers](docs/mixed-helpers.md): Matched fixed-error law and exact/full-rank and correlated-state boundaries. -- [Bandwidth](docs/bandwidth.md): Exact clean/unknown endpoints, entropy-deficit converse, and coherent construction. -- [Entropy flow](docs/entropy-flow.md): Conditional variance, supports, weighted interfaces, and input-ensemble requirements. -- [Accuracy and resources](docs/accuracy-and-resources.md): Finite certificates, synchronized sequences, error composition, and changed strength budgets. -- [Control models](docs/control-models.md): Separate finite-strength compiler and contact-count results. -- [Related work](docs/related-work.md): Primary attribution; these papers are not additional prerequisite courses. -- [Bibliography](references.bib): Source metadata, including W18 for the anchor. +- [Learning route](learning/README.md): Common foundations-to-result route. +- [Watrous bridge](learning/WATROUS_BRIDGE.md): The sole educational anchor, relevant sections, errata, and normalization conventions. +- [Thirty milestones](learning/MILESTONES.md): Stable project-defined M01–M30, with 14 background and 16 narrative targets, dependencies, conceptual connections, and sources. +- [Worked examples](learning/WORKED_EXAMPLES.md): Reference-assisted swap, three-qubit coherent amplification, and preparation concentration. -## Verification and editing +## Sources and reproduction -- [Verification guide](docs/verification.md): Executed numerical checks, their scope, and reproduction. -- [Recorded results](results/verification.json): Scientific check-source provenance. Numerical checks are not external scientific review. -- [Agent guidance](AGENTS.md): Repository boundary, claim invariants, editing and teaching instructions. +- [Related work](references/RELATED_WORK.md): Established ingredients and model-level literature comparisons. +- [Bibliography](references/references.bib): Source metadata, including W18 for the anchor. +- [Verification](verification/README.md): Commands, suite coverage, expected outputs, and their evidence limits. +- [Executed summary](verification/results/verification.json): Scientific source and output hashes from an executed run. +- [Exact certificates](verification/results/scientific-closure.json): Finite quantitative and reuse checks. +- [Research guidance](AGENTS.md): Authorized scope, scientific invariants, presentation, and checks. -Preserve free internal-control interaction time versus total runtime, per-contact versus aggregate budgets, and exact helper marginal return versus approximate joint/reference restoration. The fixed inserted helper purification is not an arbitrary helper input. Do not infer progress from file access or from a request to continue. Do not redistribute the linked textbook or private records. This guide aids navigation; it does not guarantee indexing. +Essential distinctions: both interfaces are bounded; the main budget is per contact; internal unitaries are free only in the interaction-time theorem. Unknown helpers and fixed inserted helper purifications are different input promises. Exact helper marginal return is not exact joint/reference restoration in the mixed case. The entropy-budget converse does not establish arbitrary-state entropy-only saturation. The finite-strength compiler is not a universal no-go theorem. Proofs establish general claims; finite verification is not independent endorsement or hardware validation. + +This guide maps common scientific and study questions to public authoritative files. It contains no personal assessment contract or learner record and requires no private source for the shared learning route. It aids retrieval without guaranteeing indexing. diff --git a/science/README.md b/science/README.md new file mode 100644 index 0000000..25a643d --- /dev/null +++ b/science/README.md @@ -0,0 +1,38 @@ +# Quantum information through a bounded interface + +A small interface need not behave as a sequence of independent wires. Several bounded contacts can act simultaneously, and internal reversible processing can organize the information already stored in a module so that it assists communication. The question is how much **unknown quantum data** can be exchanged this way, and how the answer changes when some qubits have a known preparation. + +The model has three separately controlled regions: a left module, one bus qubit, and a right module. Neither interface is free. Each module contains the same number of payload and helper qubits in every comparison. The task includes arbitrary payload correlations with inaccessible references; the bus and helper resources must satisfy the specified return guarantee. The time charged is the duration of bounded pairwise contacts, with module-internal unitaries treated as instantaneous. + +## Connected reading route + +| Step | Scientific question | Account | +|---|---|---| +| 1 | What is transferred, what is held fixed, and what counts as accurate return? | [Exact task](bandwidth.md#1-result-model-and-comparison) and [fixed-preparation error](mixed-helpers.md#1-task-and-matching-law) | +| 2 | How can a small bus limit entropy flow even with strong internal controls? | [Conditional entropy rate, supports, and weighted interfaces](entropy-flow.md) | +| 3 | How does the preparation budget limit usable contact strength? | [Entropy-deficit moment bound](bandwidth.md#2-entropy-deficit-controls-contact-second-moments) | +| 4 | Can occupied data attain the permitted scaling without being discarded? | [Sign encoding, block averaging, and returned helpers](bandwidth.md#5-matching-exact-construction-with-returned-clean-helpers) | +| 5 | Does imperfect preparation retain the advantage at complete-operation accuracy? | [Reversible concentration, routing, and decompression](mixed-helpers.md) | +| 6 | Which comparisons remain valid at finite size and under other strength budgets? | [Finite certificates and accuracy](accuracy-and-resources.md); [finite-duration controls](control-models.md) | +| 7 | What do these results establish about the physical resource? | [Interpretation and boundaries](interpretation.md) | + +The [theorem map](theorem-map.md) gives a shorter dependency-based route. The [learning route](../learning/README.md) supplies foundations and complete small examples before these specialist arguments. + +## Main result and its endpoints + +Write $`N=n+s`$ for module size and $`d(p)=1-h_2(p)`$ for the entropy deficit of a known independently prepared helper. For fixed complete-operation error $`0\lt\epsilon\le0.1`$, + +```math +T_{\epsilon,p}(n,s) +=\Theta_\epsilon\!\left(\frac{n}{J\sqrt{N[1+sd(p)]}}\right). +``` + +The upper and lower constants are independent of $`n,s,p`$. The lower bound combines an extensive reference-assisted information requirement with a preparation-dependent rate. The upper bound reversibly concentrates the helpers and uses entropy-bearing qubits as occupied spectators. It is exact on one common high-probability sector; this controls the entire inserted-preparation channel rather than a sum of input-specific gate errors. + +Exactly clean helpers give time $`\Theta(n/[J\sqrt{N(s+1)}])`$. Arbitrary unknown helpers give $`\Theta(n/[J\sqrt N])`$. These [exact laws](bandwidth.md) are proved separately from the fixed-error result. Full rank prevents a growing initialization advantage in the zero-error task, while [correlated preparations](mixed-helpers.md#7-why-the-product-state-assumption-cannot-be-dropped) show that a scalar entropy deficit is not a sufficient achievability invariant for every helper spectrum. + +## Attribution and verification + +Conditional-variance estimates, reversible polarization concentration, Hamiltonian simulation by conjugation, and initialization-sensitive transfer all have established precedents. The [related-work account](../references/RELATED_WORK.md) identifies their roles and the exact comparison to the closest routing results. The contribution studied here is the matched extensive-throughput characterization in this model, not the invention of those tools. + +The [verification guide](../verification/README.md) connects each finite check to a proof or construction. Exact rational certificates establish finite comparisons using proved bounds; they are not simulations of the corresponding large register. Neither these tests nor the ideal interaction-time model establishes device performance or independent proof validation. diff --git a/science/interpretation.md b/science/interpretation.md new file mode 100644 index 0000000..6b2df95 --- /dev/null +++ b/science/interpretation.md @@ -0,0 +1,57 @@ +# Initialization, information flow, and usable bandwidth + +The results distinguish three resources that can otherwise be conflated: the number and strength of physical contacts, the quantum information already occupying the module, and the known part of its preparation. Their optimal-time comparison holds the contacts and payload fixed while changing the helper input promise. + +## Unknown information is not an idle obstacle + +An unknown spectator cannot simply be set to a favorable spin orientation: doing so would destroy its information or require an additional storage resource. The occupied-data construction instead encodes the sign of a collective contact into a selected target and then removes its dependence on spectator labels through a coherent sequence of commuting interactions. + +The completed operation acts as identity on every spectator subsystem, including correlations with references. For a block of $`b`$ occupied qubits, the effective contact gain is the average absolute magnetization $`\mu_b=\Theta(\sqrt b)`$. The spectators help without being measured or consumed. This is an operator identity, not a statement limited to single-excitation states or favorable computational-basis inputs. The [construction](bandwidth.md#51-an-occupied-data-block) supplies its explicit encoding and averaging sequence. + +This explains why no-helper register exchange can take $`\Theta(\sqrt n/J)`$ in the free-internal-control model, whereas a time-division bus with at most one active contact has a linear lower bound. Simultaneous contacts and internal processing are essential to that comparison; a bare star with no usable internal module operations is a different model. + +## A preparation promise changes usable collective strength + +The largest collective contact eigenvalue can scale linearly with the number of contacts. An accurate operation on an unknown register cannot assume that its physical state occupies only that extremal sector. The reference-assisted input test and the conserved physical entropy deficit constrain how much weight can reach the strongly interacting part of the spectrum. + +For independently prepared helpers, that deficit is + +```math +\mathcal I(\omega)=1+2s[1-h_2(p)] +``` + +on the pure-bus lower-bound test. The [conditional entropy rate](entropy-flow.md) and [contact moment estimate](bandwidth.md#2-entropy-deficit-controls-contact-second-moments) turn it into an information-flow limit. This limits arbitrary internal processing without imposing a minimum switching interval. + +The upper bound reaches the same scaling by concentrating preparation weight reversibly into useful leader bits. The remaining entropy stays in the device, in qubits that the occupied-data construction already knows how to preserve. Thus initialization is useful not because entropy is erased during routing, but because a known distribution permits coherent concentration into a large favorable subspace. + +At fixed hardware, define one-direction throughput as $`\mathcal B=n/T`$. The [matching law](mixed-helpers.md#1-task-and-matching-law) gives throughput of order $`J\sqrt{(n+s)[1+s(1-h_2(p))]}`$ at fixed nonzero error. Counting both directions multiplies throughput by two. No frequency bandwidth or unrestricted channel-capacity statement is intended. + +## Returned resources and reference correlations + +Returning a helper marginal is weaker than returning its complete quantum state together with its correlations. The [fixed-preparation maps](mixed-helpers.md#1-task-and-matching-law) include inaccessible helper purifications in the output comparison and allow arbitrary reference-entangled payload and bus inputs. + +For the specified diagonal mixed preparation, the construction returns the physical helper density matrix exactly. Joint correlations and bus inaccuracies are bounded by the complete-operation half diamond error. On one common favorable helper sector the full route agrees exactly with the ideal operation, including one common phase. That is the reason initial preparation error does not grow gate by gate in the ideal sequence. + +Coherent reuse on fresh payloads retains the same favorable sector. It therefore retains the same initial-sector error bound in the absence of new physical noise. This is not a collection of independent error-free calls: unfavorable-sector errors may be correlated across uses. Pulse errors, Hamiltonian perturbations, and list-approximation errors have their own [composition bound](accuracy-and-resources.md#5-error-composition-and-reuse). + +## Two limits on an entropy-only interpretation + +**Zero error tests the full support.** A full-rank helper preparation gives nonzero weight to every helper eigenstate. An exactly unitary output channel has a pure Choi state, so every such component must implement the same operation; exact preparation-reference return then forces the unknown-helper operation on the full space. A nonzero bias can improve fixed-error scaling without improving the zero-error law. The constants of the fixed-error result need not remain bounded as the error goes to zero. + +**Equal entropy does not imply equal concentration.** A state with a small pure spike and a substantial maximally mixed component can have extensive entropy deficit but still require the unknown-helper time scale at small fixed error. The [correlated-helper example](mixed-helpers.md#7-why-the-product-state-assumption-cannot-be-dropped) makes this distinction explicit. Entropy deficit gives a general converse; independent preparation supplies the spectral concentration used to attain it. Neither statement warrants a universal entropy-only law for arbitrary mixed helpers. + +## The contact budget determines the operational comparison + +Under a per-contact bound, adding module qubits increases the quadratic contact strength. The clean and unknown comparisons nevertheless use identical wiring and the same strengths, so their relative initialization enhancement is not an extra-wire advantage. + +The [alternative-budget analysis](accuracy-and-resources.md#6-what-changes-under-a-different-interaction-budget) isolates this issue. With a fixed quadratic edge budget $`\Lambda_2`$, the matched time is $`\Theta_\epsilon(n/[\Lambda_2\sqrt{1+sd(p)}])`$, and the preparation enhancement survives. With a fixed sum of edge strengths $`\Lambda_1`$, the optimum is $`\Theta_\epsilon(n/\Lambda_1)`$, regardless of the helper initialization class. In that normalization there is no parametrically growing enhancement. + +The [finite certificates](accuracy-and-resources.md#2-finite-size-advantage-against-every-unknown-helper-protocol) compare a constructed upper bound with a lower bound for every allowed unknown-helper protocol, not just with one convenient implementation. Their input promises differ exactly as stated in the resource comparison. + +## Interaction time is not an apparatus runtime + +Synchronized block translations remove an unnecessary product of control-list lengths. With fixed nonzero polarization, fixed accuracy, and an extensive helper pool, the route has a linear number of exact contact intervals. This does not assign zero physical cost to concentration, global encoding, or pulses. + +The [displayed finite-strength compiler](control-models.md#24-finite-control-consequence) has linear total duration at a fixed internal/contact strength ratio. Its constants can improve in suitable regimes, but it does not establish a sublinear fixed-hardware runtime. Conversely, its limitation is not a theorem excluding every better finite-speed implementation. + +The scientific conclusion is a matched characterization of a bounded quantum interface under explicit preparation, control, and accuracy assumptions. The information-flow converse, coherent realization, exact endpoints, and counterexamples jointly identify which resource is quantified and which changes of task alter the answer. diff --git a/verification/tools/check_learning.py b/verification/tools/check_learning.py new file mode 100644 index 0000000..ee75407 --- /dev/null +++ b/verification/tools/check_learning.py @@ -0,0 +1,49 @@ +"""Validate the reader-independent 30-milestone map and public learning boundary.""" +from __future__ import annotations +from pathlib import Path +import re + +MAP_ID = 'QRB-W18-30-v1' +PERSONAL = re.compile(r'Revise\s*(?:→|->|–|-)\s*Learn|teaching intensity|learning rounds|challenge questions|failed challenges|retry rules|question count|passing requirement', re.I) + +def validate_map(text: str) -> dict[str, int]: + headers = list(re.finditer(r'^### (M\d{2})\. (.+)$', text, re.M)) + expected = [f'M{i:02d}' for i in range(1, 31)] + assert [h[1] for h in headers] == expected, 'Expected exactly M01-M30 in order' + assert MAP_ID in text, 'Missing stable map identifier' + split = text.index('## Narrative and innovation') + assert sum(h.start() < split for h in headers) == 14, 'Background allocation changed' + assert sum(h.start() > split for h in headers) == 16, 'Narrative allocation changed' + assert not PERSONAL.search(text), 'Personal assessment procedure in the common map' + edges = 0 + for i, h in enumerate(headers): + end = headers[i+1].start() if i+1 < len(headers) else len(text) + section = text[h.end():end] + for field in ('Central question', 'Understanding target', 'Dependencies', 'Conceptual connection', 'Sources', 'Story role'): + assert f'**{field}:**' in section, f'{h[1]} lacks {field}' + dep = re.search(r'\*\*Dependencies:\*\* ([^\n]+)', section) + assert dep, f'{h[1]} lacks dependencies' + ids = re.findall(r'M\d{2}', dep[1]) + assert len(ids) == len(set(ids)) and all(d in expected[:i] for d in ids), 'Forward/cyclic dependency' + assert ids or (i == 0 and dep[1].strip() == 'None.'), 'Missing prerequisite' + sources = section.split('**Sources:**', 1)[1].split('\n', 1)[0] + assert re.search(r'\[[^\]]+\]\([^\s)]+\)', sources), 'Missing scientific source pointer' + connection = section.split('**Conceptual connection:**', 1)[1].split('\n', 1)[0] + assert len(connection.split()) >= 12, 'Conceptual connection is not explanatory' + edges += len(ids) + return {'milestones': 30, 'background': 14, 'narrative': 16, 'dependency_edges': edges} + +def check_learning(root: Path) -> dict[str, int]: + report = validate_map((root/'learning/MILESTONES.md').read_text()) + for p in (root/'learning').glob('*.md'): + assert not PERSONAL.search(p.read_text()), f'Personal assessment procedure in {p.name}' + for name in ('README.md', 'llms.txt'): + text = (root/name).read_text() + for target in ('learning/MILESTONES.md', 'learning/WATROUS_BRIDGE.md', 'science/README.md', 'verification/README.md'): + assert target in text, f'{name} omits {target}' + anchor = (root/'learning/WATROUS_BRIDGE.md').read_text() + assert 'John Watrous' in anchor and '2018' in anchor + assert 'https://jhwatrous.github.io/TQI.errata.pdf' in anchor + assert not (root/'docs').exists(), 'Obsolete documentation tree retained' + assert not any('coach' in p.name.lower() for p in root.rglob('*.md') if 'build' not in p.parts), 'Public personal guide retained' + return report diff --git a/verification/tools/check_release.py b/verification/tools/check_release.py new file mode 100644 index 0000000..43107fd --- /dev/null +++ b/verification/tools/check_release.py @@ -0,0 +1,73 @@ +"""Dependency-free reading syntax and executed-certificate integrity checks.""" +from __future__ import annotations +import hashlib +import json +from pathlib import Path +import re + + +def reading_pages(root: Path) -> list[Path]: + return [root/'README.md', root/'AGENTS.md', root/'llms.txt', + *sorted((root/'science').glob('*.md')), *sorted((root/'learning').glob('*.md')), + *sorted((root/'references').glob('*.md')), root/'verification/README.md'] + + +def check_reading_text(text: str, label: str) -> int: + fence = None + math_fence = False + display = False + table_width = None + tables = 0 + labels = [] + for index, line in enumerate(text.splitlines(), 1): + stripped = line.strip() + match = re.fullmatch(r'([`~]{3,})(.*)', stripped) + if match: + marks, info = match.groups() + if fence is None: + fence = marks + math_fence = info.strip() == 'math' + elif marks[0] == fence[0] and len(marks) >= len(fence) and not info.strip(): + fence = None + math_fence = False + table_width = None + continue + if stripped == '$$' and fence is None: + display = not display + table_width = None + continue + if math_fence or display: + assert not re.search(r'\\tag\*?\{', line), f'{label}:{index}: unsafe native equation numbering' + labels += re.findall(r'\\text\{\((\d+)\)\}', line) + if fence or display: + continue + if stripped.startswith('|'): + width = len(re.findall(r'(? dict[str, int]: + tables = 0 + pages = reading_pages(root) + for page in pages: + assert not page.is_symlink(), f'Reading file is a symbolic link: {page}' + tables += check_reading_text(page.read_text(), str(page.relative_to(root))) + report = json.loads((root/'verification/results/verification.json').read_text()) + assert report.get('all_passed') is True, 'No explicit overall success' + for suite in report['suites']: + summary = suite['summary'] + flags = (summary.get('all_passed'), summary.get('all_assertions_passed'), summary.get('summary', {}).get('all_passed')) + assert any(f is True for f in flags), 'No explicit suite success flag' + closure = next(x for x in report['suites'] if x['script'] == 'verify_scientific_closure.py') + raw = (root/'verification/results/scientific-closure.json').read_bytes() + assert hashlib.sha256(raw).hexdigest() == closure['output_sha256'], 'Tracked certificates differ from executed output' + return {'reading_files': len(pages), 'tables': tables, 'tracked_certificate_files': 1} diff --git a/verification/tools/inspect_hosted_render.py b/verification/tools/inspect_hosted_render.py new file mode 100644 index 0000000..71fe49d --- /dev/null +++ b/verification/tools/inspect_hosted_render.py @@ -0,0 +1,154 @@ +"""Inspect public GitHub Markdown at an immutable ref; retain source and screenshots. + +This network-only check is separate from scientific verification. A blocked or +unrendered page fails; local preview output is never substituted for GitHub. +""" +from __future__ import annotations +import argparse +import hashlib +import json +from pathlib import Path +import re +import sys +from urllib.parse import quote + +REPOSITORY = 'GoGoKo699/Quantum-Routing-Bandwidth' +ROOT = Path(__file__).resolve().parents[2] + + +def page_names(root: Path) -> tuple[str, ...]: + files = [root/'README.md', *sorted((root/'science').glob('*.md')), + *sorted((root/'learning').glob('*.md')), *sorted((root/'references').glob('*.md')), + root/'verification/README.md'] + return tuple(str(p.relative_to(root)) for p in files) + + +SNAPSHOT = r'''() => { + const article = document.querySelector('article.markdown-body') || document.querySelector('.markdown-body'); + if (!article) return {article: false}; + function elements(root) { + const out = [...root.querySelectorAll('*')]; + for (const item of [...out]) if (item.shadowRoot) out.push(...elements(item.shadowRoot)); + return out; + } + const all = elements(article); + const markers = all.filter(x => x.localName === 'math-renderer'); + const errors = all.filter(x => x.matches('mjx-merror,merror,.MathJax_Error,.flash-error,[data-mjx-error],[data-mml-node="merror"]')); + const nativeErrors = all.filter(x => x.namespaceURI === 'http://www.w3.org/1998/Math/MathML' && + (x.localName === 'mlabeledtr' || (x.localName === 'mtd' && x.parentElement?.localName !== 'mtr')) + ).map(x => ({element:x.localName,parent:x.parentElement?.localName,text:(x.textContent || '').trim().slice(0,180)})); + const nodes = markers.map(x => { + const inside = elements(x.shadowRoot || x); + const box = x.getBoundingClientRect(); + return {ready:inside.some(y => y.matches('mjx-container,svg,math,img')),width:box.width,height:box.height, + error:/Math rendering failed|Undefined control sequence|ParseError|Unable to render expression|macros are not allowed|Missing (open|close) brace/i.test(x.textContent || '')}; + }); + const copy = article.cloneNode(true); + copy.querySelectorAll('math-renderer,pre,code').forEach(x => x.remove()); + return {article:true, heading:article.querySelector('h1')?.textContent?.trim(),markers:markers.length, + ready:nodes.filter(x => x.ready).length, + errors:errors.map(x => (x.getAttribute('data-mjx-error') || x.textContent || '').slice(0,180)), + marker_errors:nodes.filter(x => x.error).length,native_layout_errors:nativeErrors, + literal_math_lines:(copy.textContent || '').split('\n').filter(x => x.includes('$')), + equation_geometry:nodes.map(x => ({width:x.width,height:x.height})), + page_width:document.documentElement.scrollWidth,viewport:window.innerWidth, + table_columns:[...article.querySelectorAll('table')].map(t => [...t.rows].map(row => row.cells.length))}; +}''' + + +def source_math_count(text: str) -> int: + count = len(re.findall(r'^```math\s*\n.*?^```\s*$', text, re.S|re.M)) + text = re.sub(r'```.*?```', '', text, flags=re.S) + count += len(re.findall(r'\$\$.*?\$\$', text, re.S)) + text = re.sub(r'\$\$.*?\$\$', '', text, flags=re.S) + return count+len(re.findall(r'(? list[str]: + problems = [] + if not state.get('article') or state.get('heading') != title: + problems.append('missing expected document title') + if state.get('markers') != expected or state.get('ready', 0) < expected: + problems.append('missing or unfinished mathematics') + if state.get('literal_math_lines'): + problems.append('unprocessed math delimiters') + if state.get('errors') or state.get('marker_errors'): + problems.append('mathematical rendering error') + if state.get('native_layout_errors'): + problems.append('unsupported native MathML equation layout') + if state.get('page_width', 0) > width+3: + problems.append('page-level horizontal overflow') + if any(len(set(cols)) > 1 for cols in state.get('table_columns', [])): + problems.append('inconsistent rendered table cells') + return [f'{width}px: {p}' for p in problems] + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--ref', required=True) + parser.add_argument('--output', type=Path, default=ROOT/'build/hosted-render') + args = parser.parse_args() + if not re.fullmatch(r'[0-9a-f]{40}', args.ref): + parser.error('--ref must be a full immutable commit SHA') + from playwright.sync_api import sync_playwright + names = page_names(ROOT) + args.output.mkdir(parents=True, exist_ok=True) + report = {'repository':REPOSITORY,'ref':args.ref,'source_sha256':{},'pages':[], + 'scope':'Actual public GitHub DOM/layout and screenshots, not scientific review.'} + for name in names: + raw = (ROOT/name).read_bytes() + dest = args.output/'sources'/name + dest.parent.mkdir(parents=True,exist_ok=True) + dest.write_bytes(raw) + report['source_sha256'][name] = hashlib.sha256(raw).hexdigest() + with sync_playwright() as p: + browser = p.chromium.launch() + context = browser.new_context(viewport={'width':1180,'height':900},color_scheme='light') + page = context.new_page() + for name in names: + text = (ROOT/name).read_text() + expected = source_math_count(text) + title = text.splitlines()[0].removeprefix('# ') + url = f'https://github.com/{REPOSITORY}/blob/{args.ref}/{quote(name)}' + row = {'file':name,'url':url,'expected_math':expected,'checks':[],'problems':[]} + try: + response = page.goto(url,wait_until='domcontentloaded',timeout=45000) + row['http_status'] = response.status if response else None + if not response or response.status != 200: + raise RuntimeError(f'GitHub returned {row["http_status"]}') + page.locator('article.markdown-body, .markdown-body').first.wait_for(timeout=30000) + for width in (1180,390): + page.set_viewport_size({'width':width,'height':900}) + markers = page.locator('math-renderer') + for i in range(markers.count()): + markers.nth(i).scroll_into_view_if_needed(timeout=5000) + page.wait_for_timeout(50) + for _ in range(20): + state = page.evaluate(SNAPSHOT) + if state.get('ready',0) >= expected: + break + page.wait_for_timeout(250) + state = page.evaluate(SNAPSHOT) + row['problems'] += snapshot_problems(state,expected,title,width) + row['checks'].append(state) + page.evaluate('window.scrollTo(0,0)') + page.screenshot(path=str(args.output/f'{name.replace("/","_")}-{width}.png'),full_page=True) + except Exception as exc: + row['problems'].append(str(exc)[:1000]) + row['passed'] = not row['problems'] + report['pages'].append(row) + print(json.dumps({'file':name,'expected_math':expected,'passed':row['passed'],'problems':row['problems']}),flush=True) + if row.get('http_status') in (403,429) or any('ERR_' in s for s in row['problems']): + break + context.close() + browser.close() + report['all_passed'] = len(report['pages']) == len(names) and all(x['passed'] for x in report['pages']) + (args.output/'report.json').write_text(json.dumps(report,indent=2)+'\n') + print('HOSTED_RENDER_RESULT='+json.dumps({'ref':args.ref,'pages':len(report['pages']), + 'all_passed':report['all_passed']}),flush=True) + if not report['all_passed']: + sys.exit(1) + + +if __name__ == '__main__': + main() diff --git a/verification/tools/test_structure.py b/verification/tools/test_structure.py new file mode 100644 index 0000000..4790632 --- /dev/null +++ b/verification/tools/test_structure.py @@ -0,0 +1,130 @@ +"""Structural regressions; not additional scientific verification suites.""" +from __future__ import annotations +import hashlib +import json +from pathlib import Path +import tempfile +import unittest +from check_release import check_reading_text, check_release +from check_learning import validate_map, check_learning +from inspect_hosted_render import snapshot_problems, source_math_count, page_names + +ROOT = Path(__file__).resolve().parents[2] + + +class ReadingChecks(unittest.TestCase): + def test_valid_table_and_math(self): + text = '| A | B |\n|---|---|\n| $`\\lvert x\\rangle`$ | y |\n\n```math\nx\\qquad\\text{(1)}\n```\n' + self.assertEqual(check_reading_text(text,'fixture'),1) + + def test_unescaped_pipe(self): + with self.assertRaisesRegex(AssertionError,'table cells'): + check_reading_text('| A | B |\n|---|---|\n| $|x\\rangle$ | y |\n','fixture') + + def test_unsafe_numbering(self): + with self.assertRaisesRegex(AssertionError,'unsafe native'): + check_reading_text('```math\nx\\tag{1}\n```','fixture') + + def test_duplicate_label(self): + with self.assertRaisesRegex(AssertionError,'repeated equation'): + check_reading_text('$$\nx\\text{(1)}\n$$\n\n```math\ny\\text{(1)}\n```','fixture') + + def test_nonmath_fence(self): + self.assertEqual(check_reading_text('```text\n| a |\n| a | b |\n$$\n```','fixture'),0) + + def test_unclosed_fence(self): + with self.assertRaisesRegex(AssertionError,'code fence'): + check_reading_text('```python\nx=1','fixture') + + def test_short_closing_fence(self): + with self.assertRaisesRegex(AssertionError,'code fence'): + check_reading_text('````text\nx\n```','fixture') + + def test_unclosed_display(self): + with self.assertRaisesRegex(AssertionError,'display mathematics'): + check_reading_text('$$\nx','fixture') + + def test_result_integrity(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + for folder in ('science','learning','references','verification/results'): + (root/folder).mkdir(parents=True) + for name in ('README.md','AGENTS.md','llms.txt','verification/README.md'): + (root/name).write_text('# Fixture\n') + raw = b'{"all_passed":true}\n' + path = root/'verification/results/scientific-closure.json' + path.write_bytes(raw) + result = {'all_passed':True,'suites':[{'script':'verify_scientific_closure.py','output_sha256':hashlib.sha256(raw).hexdigest(),'summary':{'all_passed':True}}]} + record = root/'verification/results/verification.json' + record.write_text(json.dumps(result)) + self.assertEqual(check_release(root)['tracked_certificate_files'],1) + path.write_bytes(raw+b' ') + with self.assertRaisesRegex(AssertionError,'certificates differ'): + check_release(root) + path.write_bytes(raw) + result['suites'][0]['summary']['all_passed']='true' + record.write_text(json.dumps(result)) + with self.assertRaisesRegex(AssertionError,'explicit suite success'): + check_release(root) + + +class HostedChecks(unittest.TestCase): + def state(self): + return {'article':True,'heading':'Title','markers':1,'ready':1,'errors':[], + 'marker_errors':0,'native_layout_errors':[],'literal_math_lines':[], + 'page_width':390,'table_columns':[[2,2]]} + + def test_ready_valid(self): + self.assertEqual(snapshot_problems(self.state(),1,'Title',390),[]) + + def test_ready_invalid_native(self): + state = self.state();state['native_layout_errors']=[{'element':'mlabeledtr'}] + self.assertTrue(any('native MathML' in p for p in snapshot_problems(state,1,'Title',390))) + + def test_unfinished(self): + state=self.state();state['ready']=0 + self.assertTrue(snapshot_problems(state,1,'Title',390)) + + def test_overflow_and_table(self): + state=self.state();state['page_width']=500;state['table_columns']=[[2,3]] + self.assertEqual(len(snapshot_problems(state,1,'Title',390)),2) + + def test_math_count(self): + self.assertEqual(source_math_count('$`x_1`$\n\n```math\ny\n```\n\n$$z$$'),3) + + def test_new_pages(self): + names=page_names(ROOT) + self.assertIn('science/interpretation.md',names) + self.assertIn('learning/MILESTONES.md',names) + self.assertFalse(any('docs/' in name or 'coaching' in name for name in names)) + + +class LearningChecks(unittest.TestCase): + def text(self): + return (ROOT/'learning/MILESTONES.md').read_text() + + def test_current_map(self): + result=check_learning(ROOT) + self.assertEqual((result['milestones'],result['background'],result['narrative']),(30,14,16)) + + def test_missing_connection(self): + with self.assertRaisesRegex(AssertionError,'Conceptual connection'): + validate_map(self.text().replace('**Conceptual connection:**','**Other:**',1)) + + def test_forward_dependency(self): + with self.assertRaisesRegex(AssertionError,'Forward/cyclic'): + validate_map(self.text().replace('**Dependencies:** M01.','**Dependencies:** M30.',1)) + + def test_personal_procedure(self): + with self.assertRaisesRegex(AssertionError,'Personal assessment'): + validate_map(self.text()+'\nTeaching intensity: 3 learning rounds.\n') + + def test_missing_milestone(self): + with self.assertRaisesRegex(AssertionError,'exactly M01'): + validate_map(self.text().replace('### M30.','### M31.')) + + +if __name__ == '__main__': + if not __debug__: + raise RuntimeError('Structural tests require assertions.') + unittest.main() From 32b7045969c57b5d4013c01dc08db88a5946c352 Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Sat, 17 Oct 2026 15:55:28 +0800 Subject: [PATCH 2/4] Keep executed verification records paired during the layout migration --- .github/workflows/refurnish-once.yml | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/.github/workflows/refurnish-once.yml b/.github/workflows/refurnish-once.yml index c68c360..813f08b 100644 --- a/.github/workflows/refurnish-once.yml +++ b/.github/workflows/refurnish-once.yml @@ -2,7 +2,7 @@ name: Apply authorized repository layout on: push: branches: ['refurnish/current-guidance-20261017'] - paths: ['.github/refurnish.py'] + paths: ['.github/refurnish.py', '.github/workflows/refurnish-once.yml'] permissions: contents: write jobs: @@ -13,16 +13,34 @@ jobs: steps: - uses: actions/checkout@v4 with: - fetch-depth: 2 + fetch-depth: 0 - uses: actions/setup-python@v5 with: python-version: '3.13' - - run: python .github/refurnish.py + - name: Verify the unchanged baseline and apply the migration + run: | + git merge-base --is-ancestor 39ad350c7563f0908034eef21a0024bd6121df13 HEAD + python - <<'PY' + from pathlib import Path + p = Path('.github/refurnish.py') + p.write_text(p.read_text().replace("'HEAD^'", "'39ad350c7563f0908034eef21a0024bd6121df13'")) + PY + python .github/refurnish.py - run: python -m pip install -r verification/requirements.txt - run: python verification/run_all.py - - name: Record the executed sources and check the complete tree + - name: Record matching executed outputs and verify exact certificates run: | - cp build/verification/summary.json verification/results/verification.json + python - <<'PY' + from pathlib import Path + import json, shutil + old = json.loads(Path('verification/results/scientific-closure.json').read_text()) + fresh = json.loads(Path('build/verification/verify_scientific_closure.json').read_text()) + def exact(rows): + return [{k:v for k,v in row.items() if isinstance(v,(int,str,bool))} for row in rows] + assert exact(old['finite_certificates']) == exact(fresh['finite_certificates']) + shutil.copy2('build/verification/verify_scientific_closure.json','verification/results/scientific-closure.json') + shutil.copy2('build/verification/summary.json','verification/results/verification.json') + PY python check_repository.py python verification/tools/test_structure.py - name: Commit only to the authorized working branch From 9a5d050e965e6546c5043929b929e7b82ba85c25 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 17 Oct 2026 07:55:57 +0000 Subject: [PATCH 3/4] Organize science, shared learning, references, and verification --- .github/refurnish.py | 149 ------ .gitignore | 2 +- README.md | 2 +- docs/coaching.md | 41 -- docs/milestones.md | 377 --------------- learning/MILESTONES.md | 446 ++++++++++++++++++ .../learning.md => learning/WATROUS_BRIDGE.md | 15 +- .../WORKED_EXAMPLES.md | 14 +- .../RELATED_WORK.md | 12 +- references.bib => references/references.bib | 0 {docs => science}/accuracy-and-resources.md | 14 +- {docs => science}/bandwidth.md | 4 +- {docs => science}/control-models.md | 2 +- {docs => science}/entropy-flow.md | 4 +- {docs => science}/mixed-helpers.md | 8 +- {docs => science}/theorem-map.md | 14 +- tools/check_learning.py | 65 --- tools/check_release.py | 91 ---- tools/inspect_hosted_render.py | 161 ------- tools/test_release_checks.py | 84 ---- .../verification.md => verification/README.md | 18 +- .../checks}/audit_conditional_rate.py | 0 .../checks}/audit_ensemble_cut.py | 0 .../audit_translation_approximation.py | 0 .../checks}/finite_control.py | 0 .../checks}/recursive_three.py | 0 .../checks}/verify_entropy_budget.py | 2 +- .../checks}/verify_finite_control.py | 0 .../checks}/verify_full_nine.py | 0 .../checks}/verify_mixed_helpers.py | 0 .../checks}/verify_scientific_closure.py | 0 .../checks}/verify_workspace_construction.py | 0 .../requirements.txt | 0 .../results}/scientific-closure.json | 32 +- .../results}/verification.json | 90 ++-- verify.py => verification/run_all.py | 9 +- 36 files changed, 567 insertions(+), 1089 deletions(-) delete mode 100644 .github/refurnish.py delete mode 100644 docs/coaching.md delete mode 100644 docs/milestones.md create mode 100644 learning/MILESTONES.md rename docs/learning.md => learning/WATROUS_BRIDGE.md (80%) rename docs/learning-bridges.md => learning/WORKED_EXAMPLES.md (71%) rename docs/related-work.md => references/RELATED_WORK.md (86%) rename references.bib => references/references.bib (100%) rename {docs => science}/accuracy-and-resources.md (92%) rename {docs => science}/bandwidth.md (98%) rename {docs => science}/control-models.md (99%) rename {docs => science}/entropy-flow.md (98%) rename {docs => science}/mixed-helpers.md (92%) rename {docs => science}/theorem-map.md (84%) delete mode 100644 tools/check_learning.py delete mode 100644 tools/check_release.py delete mode 100644 tools/inspect_hosted_render.py delete mode 100644 tools/test_release_checks.py rename docs/verification.md => verification/README.md (64%) rename {checks => verification/checks}/audit_conditional_rate.py (100%) rename {checks => verification/checks}/audit_ensemble_cut.py (100%) rename {checks => verification/checks}/audit_translation_approximation.py (100%) rename {checks => verification/checks}/finite_control.py (100%) rename {checks => verification/checks}/recursive_three.py (100%) rename {checks => verification/checks}/verify_entropy_budget.py (98%) rename {checks => verification/checks}/verify_finite_control.py (100%) rename {checks => verification/checks}/verify_full_nine.py (100%) rename {checks => verification/checks}/verify_mixed_helpers.py (100%) rename {checks => verification/checks}/verify_scientific_closure.py (100%) rename {checks => verification/checks}/verify_workspace_construction.py (100%) rename requirements.txt => verification/requirements.txt (100%) rename {results => verification/results}/scientific-closure.json (94%) rename {results => verification/results}/verification.json (64%) rename verify.py => verification/run_all.py (94%) diff --git a/.github/refurnish.py b/.github/refurnish.py deleted file mode 100644 index 0a3e4ef..0000000 --- a/.github/refurnish.py +++ /dev/null @@ -1,149 +0,0 @@ -"""One-time, branch-confined migration; removed before the furnished revision is merged.""" -from pathlib import Path -import os -import posixpath -import re -import shutil -import subprocess - -ROOT = Path(__file__).resolve().parents[1] -assert os.environ.get('GITHUB_REPOSITORY') == 'GoGoKo699/Quantum-Routing-Bandwidth' -assert os.environ.get('GITHUB_REF') == 'refs/heads/refurnish/current-guidance-20261017' -assert subprocess.check_output(['git','rev-parse','HEAD^'],cwd=ROOT,text=True).strip() == '39ad350c7563f0908034eef21a0024bd6121df13' -subprocess.run(['git','diff','--exit-code','HEAD^','--','docs','checks','results','references.bib','requirements.txt','verify.py','LICENSE'],cwd=ROOT,check=True) - -mapping = { - 'docs/bandwidth.md':'science/bandwidth.md', - 'docs/mixed-helpers.md':'science/mixed-helpers.md', - 'docs/entropy-flow.md':'science/entropy-flow.md', - 'docs/control-models.md':'science/control-models.md', - 'docs/accuracy-and-resources.md':'science/accuracy-and-resources.md', - 'docs/theorem-map.md':'science/theorem-map.md', - 'docs/learning.md':'learning/WATROUS_BRIDGE.md', - 'docs/learning-bridges.md':'learning/WORKED_EXAMPLES.md', - 'docs/milestones.md':'learning/MILESTONES.md', - 'docs/related-work.md':'references/RELATED_WORK.md', - 'references.bib':'references/references.bib', - 'docs/verification.md':'verification/README.md', - 'verify.py':'verification/run_all.py', - 'requirements.txt':'verification/requirements.txt', - 'docs/coaching.md':None, -} -for folder in ('checks','results'): - for p in (ROOT/folder).iterdir(): - if p.is_file():mapping[str(p.relative_to(ROOT))]='verification/'+str(p.relative_to(ROOT)) -original={src:(ROOT/src).read_bytes() for src in mapping} - -def relink(text,old,new): - def link(m): - label,target=m[1],m[2] - if re.match(r'[a-zA-Z][\w+.-]*:',target) or target.startswith('//'):return m[0] - path,sep,frag=target.partition('#') - full=posixpath.normpath(posixpath.join(posixpath.dirname(old),path)) if path else old - dest=mapping.get(full,full) - if dest is None:return label - relative=posixpath.relpath(dest,posixpath.dirname(new) or '.') if dest!=new or path else '' - return f'[{label}]({relative}{sep}{frag})' - return re.sub(r'\[([^\]\n]+)\]\(([^\s)]+)\)',link,text) - -for src,dst in mapping.items(): - if dst is None:continue - raw=original[src] - if src.endswith('.md'):raw=relink(raw.decode(),src,dst).encode() - out=ROOT/dst;out.parent.mkdir(parents=True,exist_ok=True);out.write_bytes(raw) - -connections = [ - 'A routing operation must preserve relative phases as well as populations. This is why the same hardware is tested on unknown quantum data rather than a known classical label.', - 'The partial trace forgets correlations. The reference-assisted routing test later distinguishes outputs that have identical local density operators but carry different quantum information.', - 'Purification turns preservation of unknown information into preservation of entanglement. References supply a test of the operation without adding controllable qubits to the resource budget.', - 'A normalized Choi state describes one complete channel test; an inserted helper preparation instead fixes part of a larger isometry. Keeping these representations separate prevents the helper promise from becoming an arbitrary-input promise.', - 'Watrous uses root fidelity, whereas the verification programs report squared pure-target overlaps. The square and the trace-distance factor matter when transporting an accuracy bound into the converse.', - 'The diamond norm allows an inaccessible reference to accompany any payload input. The fixed helper purification makes joint restoration part of the output comparison without granting control of the preparation reference.', - 'Internal unitaries can concentrate polarization locally but cannot change the physical state\'s total entropy deficit. That conservation law remains available even when the control sequence is unrestricted.', - 'Relative entropy to a normalized exponential operator bounds a state-weighted second moment. This variational step connects preparation quality to usable interaction strength without requiring simultaneous diagonalization.', - 'An approximate swap must still establish mutual information between the payload/reference subsystems on opposite sides. Choosing those subsystems removes an unnecessary continuity penalty proportional to the helper count.', - 'Orthogonal Pauli coefficients add quadratically under normalized trace, while aligned extremal eigenvalues may add linearly. The proof needs the former together with the actual state\'s spectral weight, not an input-uniform replacement for operator norm.', - 'Treating module unitaries as instantaneous isolates the interface resource. Charging their duration changes the comparator, just as replacing individual contact bounds by an aggregate strength bound changes the theorem.', - 'A reversible basis permutation changes where a spectrum is supported, not its eigenvalues. A prescribed product of commuting conjugated evolutions then realizes a Hamiltonian average coherently, rather than randomizing the output channel.', - 'The probability of an entire zero-prefix subspace is the useful preparation promise. It controls a coherent operation on all payload inputs even though the compressed prefix bits need not be independently pure.', - 'The two helper tasks keep payload, contacts, allowed internal processing, and restoration obligations fixed. Identifying the one altered input promise is necessary before calling their times a resource separation.', - 'The bus dimension limits the conditional-log fluctuation factor even when the register includes large references. The remaining state-weighted interaction factor is where geometry and initialization enter.', - 'Cut-local terms cannot change the cut entropy. Removing them by an orthogonal coefficient projection is justified in normalized Frobenius norm, avoiding an unsupported operator-norm step.', - 'Gaussian-type spectral tails constrain the contact, while relative entropy constrains the evolving state. Their combination prevents unlimited internal processing from concentrating arbitrary weight in the strongest part of the spectrum.', - 'The payload marginals can remain maximally mixed throughout a perfect exchange. The reference cut reveals the required transfer through correlations and gives a payload-sized condition for approximate success.', - 'Integrating a state-dependent rate gives a lower bound on every permitted schedule, not merely on the constructed protocol. The ensemble version retains its common-input-control condition and permits specially prepared states outside that premise.', - 'The encoding separates the target\'s sign from the spectators\' magnitude. Because it is a bijection, the spectators\' unknown information is retained rather than erased to obtain the larger contact.', - 'Each block only needs a uniform marginal list because the contact is additive over blocks. Commutation then gives an exact finite-time operator identity, and reference preservation follows from identity on the spectator factors.', - 'Clean leaders can be reversibly correlated with the target so their block strengths add. The balanced partition relates this local mechanism to the total number of contacts and initialized helpers.', - 'A local gate identity becomes useful for routing only when the complete wire permutation, its phase, and the bus\'s original information are restored. The buffered sequence meets those requirements without a clean-bus assumption.', - 'An upper bound alone demonstrates feasibility; the entropy lower bound limits every admissible alternative. Their common exponent establishes optimal interaction-time scaling for each exact helper promise.', - 'Reversible concentration transfers entropy into qubits that the contact amplifier can use as occupied spectators. No pure qubits are created by a reset, and small bias is handled by the same bound or the no-concentration fallback.', - 'All gates are correct on the same invariant preparation sector with one common phase. This is why initial preparation error need not add gate by gate, whereas new control errors have a separate composition bound.', - 'The quantity one plus the total iid entropy deficit joins the unknown-helper and polarized-helper regimes. Uniformity in the bias is separate from uniformity as the allowed error tends to zero.', - 'Full rank forces every eigenstate component to implement the exact unitary when zero error is required. At nonzero error, spectral concentration permits discarding only a small weight in the error analysis; a broad maximally mixed component can prevent that concentration.', - 'A finite construction beats the full comparator class only when its upper bound lies below the class\'s lower bound. The resource analysis then determines whether that comparison concerns contact time, count, quadratic strength, or a fixed sum of strengths.', - 'The result joins a reference-assisted information requirement, a conserved preparation budget, and a coherent realization. Its significance is a matched interface-resource law with explicit initialization and accuracy assumptions, not an assertion of faster noisy hardware.' -] -p=ROOT/'learning/MILESTONES.md';text=p.read_text() -body=text[text.index('## Background and preliminaries'):text.index('## Completion')] -body=re.sub(r' \*\*Teaching intensity:\*\* [123]\.', '', body) -parts=list(re.finditer(r'^### (M\d{2})\.',body,re.M));out=[] -assert len(parts)==len(connections)==30 -for i,h in enumerate(parts): - end=parts[i+1].start() if i+1 dict[str, int]: - text = (root/'docs/milestones.md').read_text() - headers = list(re.finditer(r'^### (M\d{2})\. (.+)$', text, re.M)) - expected = [f'M{i:02d}' for i in range(1, 31)] - assert [h[1] for h in headers] == expected, 'Expected exactly M01-M30 in order' - split = text.index('## Narrative and innovation') - assert sum(h.start() < split for h in headers) == 14, 'Background allocation changed' - assert sum(h.start() > split for h in headers) == 16, 'Narrative allocation changed' - assert 'QRB-W18-30-v1' in text - edges = 0 - for i, header in enumerate(headers): - end = headers[i+1].start() if i+1 < len(headers) else len(text) - section = text[header.end():end] - for field in ('Central question', 'Understanding target', 'Dependencies', 'Sources', 'Story role'): - assert f'**{field}:**' in section, f'{header[1]} lacks {field}' - match = re.search(r'\*\*Dependencies:\*\* (.*?)\. \*\*Teaching intensity:\*\* ([123])\.', section) - assert match, f'{header[1]} lacks valid dependencies/intensity' - deps = re.findall(r'M\d{2}', match[1]) - assert len(deps) == len(set(deps)) - assert all(d in expected[:i] for d in deps), f'{header[1]} has forward/cyclic dependency' - assert deps or (i == 0 and match[1] == 'None') - sources = section.split('**Sources:**', 1)[1].split('\n', 1)[0] - assert re.search(r'\[[^\]]+\]\([^\s)]+\)', sources), f'{header[1]} needs a source pointer' - edges += len(deps) - learning = (root/'docs/learning.md').read_text() - coaching = (root/'docs/coaching.md').read_text() - agents = (root/'AGENTS.md').read_text() - for name in ('README.md', 'llms.txt'): - entry = (root/name).read_text() - for target in ('docs/milestones.md', 'docs/learning.md', 'docs/coaching.md'): - assert target in entry, f'{name} omits {target}' - assert 'John Watrous' in learning and '2018' in learning - assert 'https://jhwatrous.github.io/TQI.errata.pdf' in learning - assert 'docs/coaching.md' in agents and 'docs/milestones.md' in agents - assert 'q=\\min(2+f,6)' in coaching - assert '1–3 targeted learning rounds' in coaching - assert '60 challenge questions' in coaching - assert 'M01–M30' in coaching - assert '
' not in learning, 'Do not reintroduce a competing expandable-answer course' - # Raw pipes inside a math cell can split a GitHub Markdown table before - # MathJax sees it. Keep cell delimiters unambiguous in the new reading pages. - for name in ('README.md', 'docs/learning.md', 'docs/learning-bridges.md'): - columns = None - for line in (root/name).read_text().splitlines(): - if line.startswith('|'): - count = len(re.findall(r'(? list[str]: - """Use inline number text, not legacy MathML table rows, for equation labels.""" - if re.search(r'\\tag\*?\s*\{', line): - raise AssertionError(f'{label}:{index}: legacy equation tag is unsafe in native MathML') - return re.findall(r'\\qquad\s*\\text\{\(([^(){}]+)\)\}', line) - - -def check_reading_text(text: str, label: str) -> int: - """Check Markdown structures that can silently change mathematical meaning.""" - fenced = re.compile(r'^([`~]{3,}).*$') - in_fence = None - math_fence = False - display = False - table_width = None - tables = 0 - tags = [] - for index, line in enumerate(text.splitlines(), 1): - stripped = line.strip() - match = fenced.fullmatch(stripped) - if match: - mark = match[1] - if in_fence is None: - in_fence = mark[0] - math_fence = stripped[len(mark):].strip() == 'math' - elif mark[0] == in_fence: - in_fence = None - math_fence = False - table_width = None - continue - if in_fence: - if math_fence: - tags.extend(equation_labels(line, label, index)) - continue - if stripped == '$$': - display = not display - table_width = None - continue - if display: - tags.extend(equation_labels(line, label, index)) - continue - if stripped.startswith('|'): - width = len(re.findall(r'(? dict[str, int]: - pages = [root/'README.md', root/'AGENTS.md', root/'llms.txt', *sorted((root/'docs').glob('*.md'))] - tables = 0 - for page in pages: - if page.is_symlink(): - raise AssertionError(f'Reading file is a symbolic link: {page}') - tables += check_reading_text(page.read_text(), str(page.relative_to(root))) - report = json.loads((root/'results/verification.json').read_text()) - if report.get('all_passed') is not True: - raise AssertionError('Recorded verification does not explicitly report success') - for suite in report['suites']: - summary = suite['summary'] - flags = (summary.get('all_passed'), summary.get('all_assertions_passed'), - summary.get('summary', {}).get('all_passed')) - if not any(flag is True for flag in flags): - raise AssertionError(f"No explicit success flag: {suite['script']}") - closure = next(x for x in report['suites'] if x['script'] == 'verify_scientific_closure.py') - certificate = root/'results/scientific-closure.json' - if hashlib.sha256(certificate.read_bytes()).hexdigest() != closure['output_sha256']: - raise AssertionError('Tracked scientific certificates differ from the recorded executed output') - return {'reading_files': len(pages), 'tables': tables, 'tracked_certificate_files': 1} - - -if __name__ == '__main__': - print('PASS:', check_release(Path(__file__).resolve().parents[1])) diff --git a/tools/inspect_hosted_render.py b/tools/inspect_hosted_render.py deleted file mode 100644 index 8da7dfb..0000000 --- a/tools/inspect_hosted_render.py +++ /dev/null @@ -1,161 +0,0 @@ -"""Inspect actual GitHub Markdown in Chromium; save screenshots and DOM diagnostics. - -Run separately from the offline scientific checks. It uses no credentials and -only reads public pages of this repository at a supplied immutable commit. -A blocked or unrendered page is a failure, never a successful visual check. -""" -from __future__ import annotations -import argparse -import hashlib -import json -from pathlib import Path -import re -import sys -from urllib.parse import quote - -REPOSITORY = 'GoGoKo699/Quantum-Routing-Bandwidth' -PAGES = ('README.md', 'docs/learning.md', 'docs/learning-bridges.md', - 'docs/milestones.md', 'docs/bandwidth.md', 'docs/mixed-helpers.md', - 'docs/accuracy-and-resources.md', 'docs/theorem-map.md', - 'docs/entropy-flow.md', 'docs/control-models.md', 'docs/coaching.md', - 'docs/related-work.md', 'docs/verification.md') - -SNAPSHOT = r'''() => { - const article = document.querySelector('article.markdown-body') || document.querySelector('.markdown-body'); - if (!article) return {article: false}; - function elements(root) { - let out = [...root.querySelectorAll('*')]; - for (const item of [...out]) if (item.shadowRoot) out.push(...elements(item.shadowRoot)); - return out; - } - const all = elements(article); - const markers = all.filter(x => x.localName === 'math-renderer'); - const errors = all.filter(x => x.matches('mjx-merror,merror,.MathJax_Error,.flash-error,[data-mjx-error],[data-mml-node="merror"]')); - // MathML Core does not support the legacy mlabeledtr numbering element. - // Its presence can stack every token vertically without a parse error. - const nativeLayoutErrors = all.filter(x => - x.namespaceURI === 'http://www.w3.org/1998/Math/MathML' && - (x.localName === 'mlabeledtr' || - (x.localName === 'mtd' && x.parentElement?.localName !== 'mtr')) - ).map(x => ({element:x.localName, parent:x.parentElement?.localName, - text:(x.textContent || '').trim().slice(0,180)})); - const nodes = markers.map(x => { - const inner = elements(x.shadowRoot || x); - const rectangle = x.getBoundingClientRect(); - return {markup: x.outerHTML.slice(0,1800), shadow: x.shadowRoot?.innerHTML.slice(0,1800), ready: inner.some(y => y.matches('mjx-container,svg,math,img')), - width:rectangle.width, height:rectangle.height, - error: /Math rendering failed|Undefined control sequence|ParseError|Unable to render expression|macros are not allowed|Missing (open|close) brace/i.test(x.textContent || '')}; - }); - const copy = article.cloneNode(true); - copy.querySelectorAll('math-renderer,pre,code').forEach(x => x.remove()); - const literal = (copy.textContent || '').split('\n').filter(x => x.includes('$')); - return {unready_details: nodes.filter(x => !x.ready), sample_ready: nodes.find(x => x.ready), - literal_math_lines: literal, article: true, heading: article.querySelector('h1')?.textContent?.trim(), - markers: markers.length, ready: nodes.filter(x => x.ready).length, - errors: errors.map(x => (x.getAttribute('data-mjx-error') || x.textContent || '').slice(0,180)), - marker_errors: nodes.filter(x => x.error).length, native_layout_errors:nativeLayoutErrors, - equation_geometry:nodes.map(x => ({width:x.width,height:x.height})), - rendered_containers: all.filter(x => x.localName === 'mjx-container').length, - page_width: document.documentElement.scrollWidth, viewport: window.innerWidth, - table_columns: [...article.querySelectorAll('table')].map(t => [...t.rows].map(row => row.cells.length))}; -}''' - - -def source_math_count(text: str) -> int: - math_fences = len(re.findall(r'^```math\s*\n.*?^```\s*$', text, flags=re.S|re.M)) - text = re.sub(r'```.*?```', '', text, flags=re.S) - displays = re.findall(r'\$\$.*?\$\$', text, re.S) - text = re.sub(r'\$\$.*?\$\$', '', text, flags=re.S) - return math_fences + len(displays) + len(re.findall(r'(? list[str]: - problems = [] - if state.get('heading') != title: - problems.append('missing expected document title') - if state.get('markers') != expected or state.get('ready', 0) < expected: - problems.append('missing or unfinished mathematics') - if state.get('literal_math_lines'): - problems.append('unprocessed math delimiters') - if state.get('errors') or state.get('marker_errors'): - problems.append('mathematical rendering error') - if state.get('native_layout_errors'): - problems.append('unsupported native MathML equation layout') - if state.get('page_width', 0) > width+3: - problems.append('page-level horizontal overflow') - if any(len(set(cols)) > 1 for cols in state.get('table_columns', [])): - problems.append('inconsistent rendered table cells') - return [f'{width}px: {x}' for x in problems] - - -def main() -> None: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--ref', required=True) - parser.add_argument('--output', type=Path, default=Path('build/hosted-render')) - args = parser.parse_args() - if not re.fullmatch(r'[0-9a-f]{40}', args.ref): - parser.error('--ref must be a full immutable Git commit SHA') - from playwright.sync_api import sync_playwright - root = Path(__file__).resolve().parents[1] - args.output.mkdir(parents=True, exist_ok=True) - report = {'repository': REPOSITORY, 'ref': args.ref, - 'scope': 'Actual public GitHub rendering; automated DOM/layout checks and screenshot evidence, not scientific review.', - 'source_sha256': {}, 'pages': []} - # Keep the exact public source associated with each inspected page alongside - # the screenshots. No authentication data or private repository is included. - for name in PAGES: - raw = (root/name).read_bytes() - destination = args.output/'sources'/name - destination.parent.mkdir(parents=True, exist_ok=True) - destination.write_bytes(raw) - report['source_sha256'][name] = hashlib.sha256(raw).hexdigest() - with sync_playwright() as p: - browser = p.chromium.launch() - context = browser.new_context(viewport={'width': 1180, 'height': 900}, color_scheme='light') - page = context.new_page() - for name in PAGES: - row = {'file': name, 'checks': [], 'problems': []} - expected = source_math_count((root/name).read_text()) - row['expected_math'] = expected - url = f'https://github.com/{REPOSITORY}/blob/{args.ref}/{quote(name)}' - row['url'] = url - try: - response = page.goto(url, wait_until='domcontentloaded', timeout=45000) - row['http_status'] = response.status if response else None - if not response or response.status != 200: - raise RuntimeError(f'GitHub returned {row["http_status"]}') - page.locator('article.markdown-body, .markdown-body').first.wait_for(timeout=30000) - for width in (1180, 390): - page.set_viewport_size({'width': width, 'height': 900}) - markers = page.locator('math-renderer') - for i in range(markers.count()): - markers.nth(i).scroll_into_view_if_needed(timeout=5000) - page.wait_for_timeout(50) - for _ in range(20): - state = page.evaluate(SNAPSHOT) - if state.get('ready', 0) >= expected: - break - page.wait_for_timeout(250) - state = page.evaluate(SNAPSHOT) - title = (root/name).read_text().splitlines()[0].removeprefix('# ') - row['problems'].extend(snapshot_problems(state, expected, title, width)) - row['checks'].append(state) - page.evaluate('window.scrollTo(0,0)') - page.screenshot(path=str(args.output/f'{name.replace("/", "_")}-{width}.png'), full_page=True) - except Exception as exc: - row['problems'].append(str(exc)[:1000]) - row['passed'] = not row['problems'] - report['pages'].append(row) - print(json.dumps(row), flush=True) - if row.get('http_status') in (403, 429) or any('ERR_' in x for x in row['problems']): - break - context.close(); browser.close() - report['all_passed'] = len(report['pages']) == len(PAGES) and all(x['passed'] for x in report['pages']) - (args.output/'report.json').write_text(json.dumps(report, indent=2)+'\n') - print('HOSTED_RENDER_RESULT='+json.dumps(report), flush=True) - if not report['all_passed']: - sys.exit(1) - - -if __name__ == '__main__': - main() diff --git a/tools/test_release_checks.py b/tools/test_release_checks.py deleted file mode 100644 index 159bcf0..0000000 --- a/tools/test_release_checks.py +++ /dev/null @@ -1,84 +0,0 @@ -"""Regression tests for release validation, distinct from scientific suites.""" -from __future__ import annotations -import hashlib -import json -from pathlib import Path -import tempfile -import unittest -from check_release import check_reading_text, check_release -from inspect_hosted_render import snapshot_problems - - -class ReadingChecks(unittest.TestCase): - def test_valid_math_and_table(self): - text = '| A | B |\n|---|---|\n| $\\lvert x\\rangle$ | $\\lVert X\\rVert$ |\n\n$$\n|x|\\qquad\\text{(1)}\n$$\n' - self.assertEqual(check_reading_text(text, 'fixture'), 1) - - def test_unescaped_ket_in_table(self): - with self.assertRaisesRegex(AssertionError, 'table cells'): - check_reading_text('| A | B |\n|---|---|\n| $|x\\rangle$ | yes |\n', 'fixture') - - def test_duplicate_label(self): - with self.assertRaisesRegex(AssertionError, 'repeated equation'): - check_reading_text('$$\nx\\qquad\\text{(1)}\n$$\n\n$$\ny\\qquad\\text{(1)}\n$$\n', 'fixture') - - def test_labels_in_math_fences(self): - with self.assertRaisesRegex(AssertionError, 'repeated equation'): - check_reading_text('```math\nx\\qquad\\text{(1)}\n```\n\n```math\ny\\qquad\\text{(1)}\n```\n', 'fixture') - - def test_fenced_examples_are_not_tables(self): - self.assertEqual(check_reading_text('```text\n| a |\n| a | b |\n$$\n```\n', 'fixture'), 0) - - def test_unclosed_fence(self): - with self.assertRaisesRegex(AssertionError, 'code fence'): - check_reading_text('```python\nx=1\n', 'fixture') - - def test_unclosed_math(self): - with self.assertRaisesRegex(AssertionError, 'display mathematics'): - check_reading_text('$$\nx\n', 'fixture') - - def test_result_integrity_and_explicit_success(self): - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - (root/'docs').mkdir(); (root/'results').mkdir() - for name in ('README.md', 'AGENTS.md', 'llms.txt'): - (root/name).write_text('# Fixture\n') - content = b'{"all_passed": true}\n' - path = root/'results/scientific-closure.json'; path.write_bytes(content) - result = {'all_passed': True, 'suites': [{'script': 'verify_scientific_closure.py', - 'output_sha256': hashlib.sha256(content).hexdigest(), 'summary': {'all_passed': True}}]} - summary = root/'results/verification.json'; summary.write_text(json.dumps(result)) - self.assertEqual(check_release(root)['tracked_certificate_files'], 1) - path.write_bytes(content+b' ') - with self.assertRaisesRegex(AssertionError, 'certificates differ'): - check_release(root) - path.write_bytes(content) - result['suites'][0]['summary']['all_passed'] = 'true' - summary.write_text(json.dumps(result)) - with self.assertRaisesRegex(AssertionError, 'explicit success flag'): - check_release(root) - - def test_legacy_tag_in_math_fence(self): - with self.assertRaisesRegex(AssertionError, 'legacy equation tag'): - check_reading_text('```math\nx=y\\tag{1}\n```\n', 'fixture') - - def test_legacy_tag_in_dollar_display(self): - with self.assertRaisesRegex(AssertionError, 'legacy equation tag'): - check_reading_text('$$\nx=y\\tag{1}\n$$\n', 'fixture') - - def test_ready_math_with_unsupported_layout_is_not_a_pass(self): - state = {'heading': 'Fixture', 'markers': 1, 'ready': 1, - 'page_width': 1180, 'errors': [], 'marker_errors': 0, - 'native_layout_errors': [{'element': 'mlabeledtr'}]} - self.assertEqual(snapshot_problems(state, 1, 'Fixture', 1180), - ['1180px: unsupported native MathML equation layout']) - - def test_valid_hosted_snapshot(self): - state = {'heading': 'Fixture', 'markers': 1, 'ready': 1, - 'page_width': 390, 'errors': [], 'marker_errors': 0, - 'native_layout_errors': [], 'table_columns': [[2, 2]]} - self.assertEqual(snapshot_problems(state, 1, 'Fixture', 390), []) - - -if __name__ == '__main__': - unittest.main() diff --git a/docs/verification.md b/verification/README.md similarity index 64% rename from docs/verification.md rename to verification/README.md index 1291e6d..e221e71 100644 --- a/docs/verification.md +++ b/verification/README.md @@ -1,21 +1,21 @@ # Verification and reproduction -Proofs are in [Bandwidth](bandwidth.md), [Mixed helpers](mixed-helpers.md), [Entropy flow](entropy-flow.md), [Accuracy and resources](accuracy-and-resources.md), and [Control models](control-models.md). Programs check finite identities and stated numerical inequalities. They are not experiments, independent review, or numerical proofs of asymptotic theorems. +Proofs are in [Bandwidth](../science/bandwidth.md), [Mixed helpers](../science/mixed-helpers.md), [Entropy flow](../science/entropy-flow.md), [Accuracy and resources](../science/accuracy-and-resources.md), and [Control models](../science/control-models.md). Programs check finite identities and stated numerical inequalities. They are not experiments, independent review, or numerical proofs of asymptotic theorems. ## Run Use Python 3.13 with the pinned NumPy 2.3.5 and SciPy 1.17.0 dependencies: ```bash -python -m pip install -r requirements.txt +python -m pip install -r verification/requirements.txt python check_repository.py -python tools/test_release_checks.py -python verify.py +python verification/tools/test_structure.py +python verification/run_all.py ``` -The verifier copies check sources into a temporary directory, runs each with one BLAS thread and assertions enabled, and writes complete JSON outputs, logs, and a summary under `build/verification/`. Use `--output PATH` for another directory. A failed assertion, nonzero exit, missing success flag, or timeout fails the run. Optimization mode is rejected. +Run the commands from the repository root. The scientific programs are in `verification/checks/`; the runner copies check sources into a temporary directory, runs each with one BLAS thread and assertions enabled, and writes complete JSON outputs, logs, and a summary under `build/verification/`. Use `--output PATH` for another directory. A failed assertion, nonzero exit, missing success flag, or timeout fails the run. Optimization mode is rejected. -The [finite certificates and full closure checks](../results/scientific-closure.json) retain the quantitative examples. The [tracked summary](../results/verification.json) records source hashes, output hashes, environment, counts, and diagnostic residuals from an executed run. Timing and raw-output hashes can differ between runs; they are provenance, not portable numerical targets. Normal verification never replaces this tracked record. +The [finite certificates and full closure checks](results/scientific-closure.json) retain the quantitative examples. The [tracked summary](results/verification.json) records source hashes, output hashes, environment, counts, and diagnostic residuals from an executed run. Timing and raw-output hashes can differ between runs; they are provenance, not portable numerical targets. Normal verification never replaces this tracked record. ## Coverage @@ -42,20 +42,20 @@ The ensemble suite includes a selected collective state that violates an incorre ## Maintenance -`check_repository.py` checks syntax, local links and citation anchors, math delimiters, bibliography keys, the contact paragraph, the original license, the 30-milestone map, exact suite coverage, and all check-source hashes. The release checker additionally checks table-cell consistency across every reading page, duplicate equation labels in dollar displays and math fences, unsafe legacy numbering syntax, explicit success flags, and the digest of the tracked finite-size certificate file against its executed-output record. Twelve regression tests exercise valid input and deliberately malformed material, including a ready-but-invalid native MathML layout; these are structural tests, not extra scientific suites. CI runs these checks and the ten numerical suites. Update tracked scientific results only from a successful associated run after changing scientific check sources. Keep generated cases in the ignored build directory or export them as a verification bundle. +`check_repository.py` checks syntax, local links and citation anchors, math delimiters, bibliography keys, the contact paragraph, the original license, the 30-milestone map, exact suite coverage, and all check-source hashes. The release checker additionally checks table-cell consistency across every reading page, duplicate equation labels in dollar displays and math fences, unsafe legacy numbering syntax, explicit success flags, and the digest of the tracked finite-size certificate file against its executed-output record. Structural regression tests exercise valid input and deliberately malformed material, including a ready-but-invalid native MathML layout and a shared learning map contaminated by personal assessment rules; these are structural tests, not extra scientific suites. CI runs these checks and the ten numerical suites. Update tracked scientific provenance only from a successful associated run when paths or source programs change. Preserve numerical certificate bytes when their calculation is unchanged. Keep generated cases in the ignored build directory or export them as a verification bundle. Use protected GitHub mathematical syntax for formulas that contain Markdown-sensitive characters. Fenced math blocks preserve backslashes in norm and spacing commands; backtick-protected inline math preserves starred subscripts and punctuation boundaries. Prefer supported upright commands and explicitly braced starred indices. Preserve equation numbers with ordinary `\qquad\text{(n)}` content rather than `\tag{n}`. The latter can emit legacy `mlabeledtr` rows that stack tokens in native browser MathML even when parsing succeeds; the source checker rejects that numbering syntax in mathematical blocks. The [official syntax reference](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/writing-mathematical-expressions) and the hosted check are complementary to local source validation. ## Hosted rendering -The separate `Inspect hosted mathematics` workflow opens thirteen actual public GitHub pages at an immutable commit in Chromium. It checks entrypoint, learning, and scientific pages at desktop and mobile widths, verifies the expected mathematics has rendered, detects GitHub and MathJax error messages and unprocessed delimiters, checks table structure, rejects unsupported native MathML table rows, and records equation geometry and page-level overflow. Screenshots, the exact inspected public sources with SHA-256 hashes, and a JSON report are retained as workflow artifacts for 14 days. It needs network access and a separate Playwright installation; it is not a dependency of the offline scientific verifier. +The separate `Inspect hosted mathematics` workflow opens the root README and every science, learning, reference, and verification Markdown page at an immutable commit in Chromium. It checks entrypoint, learning, and scientific pages at desktop and mobile widths, verifies the expected mathematics has rendered, detects GitHub and MathJax error messages and unprocessed delimiters, checks table structure, rejects unsupported native MathML table rows, and records equation geometry and page-level overflow. Screenshots, the exact inspected public sources with SHA-256 hashes, and a JSON report are retained as workflow artifacts for 14 days. It needs network access and a separate Playwright installation; it is not a dependency of the offline scientific verifier. To invoke the same check in a network-enabled environment: ```bash python -m pip install playwright==1.55.0 python -m playwright install chromium -python tools/inspect_hosted_render.py --ref COMMIT_SHA +python verification/tools/inspect_hosted_render.py --ref COMMIT_SHA ``` Replace `COMMIT_SHA` with a full 40-character commit hash in this repository. The script uses no authentication and only reads this repository's public pages. A blocked host or unfinished render fails the check; it is not silently replaced by a local preview. A hosted-browser diagnostic and a screenshot review are different evidence from mathematical verification. Neither establishes independent scientific review or validates a different hosting renderer. diff --git a/checks/audit_conditional_rate.py b/verification/checks/audit_conditional_rate.py similarity index 100% rename from checks/audit_conditional_rate.py rename to verification/checks/audit_conditional_rate.py diff --git a/checks/audit_ensemble_cut.py b/verification/checks/audit_ensemble_cut.py similarity index 100% rename from checks/audit_ensemble_cut.py rename to verification/checks/audit_ensemble_cut.py diff --git a/checks/audit_translation_approximation.py b/verification/checks/audit_translation_approximation.py similarity index 100% rename from checks/audit_translation_approximation.py rename to verification/checks/audit_translation_approximation.py diff --git a/checks/finite_control.py b/verification/checks/finite_control.py similarity index 100% rename from checks/finite_control.py rename to verification/checks/finite_control.py diff --git a/checks/recursive_three.py b/verification/checks/recursive_three.py similarity index 100% rename from checks/recursive_three.py rename to verification/checks/recursive_three.py diff --git a/checks/verify_entropy_budget.py b/verification/checks/verify_entropy_budget.py similarity index 98% rename from checks/verify_entropy_budget.py rename to verification/checks/verify_entropy_budget.py index 4eb80a0..24ece0a 100644 --- a/checks/verify_entropy_budget.py +++ b/verification/checks/verify_entropy_budget.py @@ -1,6 +1,6 @@ """Adversarial finite-dimensional checks of the entropy-deficit moment bound. -The universal claims rest on the analytical proof in docs/bandwidth.md. +The universal claims rest on the analytical proof in science/bandwidth.md. Tests include exact maximization over fixed-spectrum unitary orbits, Gibbs states of H^2 (entropy-constrained moment maximizers), and noncommuting states. """ diff --git a/checks/verify_finite_control.py b/verification/checks/verify_finite_control.py similarity index 100% rename from checks/verify_finite_control.py rename to verification/checks/verify_finite_control.py diff --git a/checks/verify_full_nine.py b/verification/checks/verify_full_nine.py similarity index 100% rename from checks/verify_full_nine.py rename to verification/checks/verify_full_nine.py diff --git a/checks/verify_mixed_helpers.py b/verification/checks/verify_mixed_helpers.py similarity index 100% rename from checks/verify_mixed_helpers.py rename to verification/checks/verify_mixed_helpers.py diff --git a/checks/verify_scientific_closure.py b/verification/checks/verify_scientific_closure.py similarity index 100% rename from checks/verify_scientific_closure.py rename to verification/checks/verify_scientific_closure.py diff --git a/checks/verify_workspace_construction.py b/verification/checks/verify_workspace_construction.py similarity index 100% rename from checks/verify_workspace_construction.py rename to verification/checks/verify_workspace_construction.py diff --git a/requirements.txt b/verification/requirements.txt similarity index 100% rename from requirements.txt rename to verification/requirements.txt diff --git a/results/scientific-closure.json b/verification/results/scientific-closure.json similarity index 94% rename from results/scientific-closure.json rename to verification/results/scientific-closure.json index 7386b05..f36169f 100644 --- a/results/scientific-closure.json +++ b/verification/results/scientific-closure.json @@ -289,7 +289,7 @@ "p": 0.01, "payload_bus_input_columns": 32, "helper_sectors": 64, - "purified_isometry_operator_error": 0.04228054853002728, + "purified_isometry_operator_error": 0.042280548530027266, "same_preparation_bound": 0.04882258477385236 }, { @@ -309,69 +309,69 @@ "p": 0.4, "payload_bus_input_columns": 32, "helper_sectors": 64, - "purified_isometry_operator_error": 1.2713709136204083, + "purified_isometry_operator_error": 1.2713709136204088, "same_preparation_bound": 1.523280670132724 } ], "perturbation_checks": [ { "time": 0.6413895334877393, - "operator_error": 0.017068530294159712, + "operator_error": 0.017068530294159705, "Duhamel_upper": 0.02112885840578925 }, { "time": 0.07384639959688252, - "operator_error": 0.002085233770911831, + "operator_error": 0.0020852337709118315, "Duhamel_upper": 0.002088518438619112 }, { "time": 1.7129631722724368, - "operator_error": 0.02938512320997811, + "operator_error": 0.029385123209977822, "Duhamel_upper": 0.05033711297919295 }, { "time": 1.5264082231101628, - "operator_error": 0.036816320350972216, + "operator_error": 0.036816320350972195, "Duhamel_upper": 0.042710437623595596 }, { "time": 1.6182812521287437, - "operator_error": 0.02917270209243977, + "operator_error": 0.029172702092439995, "Duhamel_upper": 0.04645824983778291 }, { "time": 1.4308817167826757, - "operator_error": 0.02997651091563912, + "operator_error": 0.02997651091563916, "Duhamel_upper": 0.04652593781143633 }, { "time": 1.540247490272937, - "operator_error": 0.03446275926605976, - "Duhamel_upper": 0.04462872453184362 + "operator_error": 0.034462759266059816, + "Duhamel_upper": 0.044628724531843626 }, { "time": 0.8742319016315779, - "operator_error": 0.018621709484664777, + "operator_error": 0.01862170948466487, "Duhamel_upper": 0.021696219045081004 }, { "time": 1.5731952035922157, - "operator_error": 0.024368602975132006, + "operator_error": 0.024368602975131957, "Duhamel_upper": 0.040608811947598515 }, { "time": 0.2032475488523221, - "operator_error": 0.009520774279861224, - "Duhamel_upper": 0.009539615448033403 + "operator_error": 0.009520774279861244, + "Duhamel_upper": 0.009539615448033402 }, { "time": 1.8671045194284732, - "operator_error": 0.0352720059424501, + "operator_error": 0.035272005942450384, "Duhamel_upper": 0.06537201088549645 }, { "time": 0.7856828169294799, - "operator_error": 0.028901618543840157, + "operator_error": 0.028901618543840293, "Duhamel_upper": 0.03632336699100447 } ], diff --git a/results/verification.json b/verification/results/verification.json similarity index 64% rename from results/verification.json rename to verification/results/verification.json index 6db4412..fb77d77 100644 --- a/results/verification.json +++ b/verification/results/verification.json @@ -1,12 +1,12 @@ { "scope": "Deterministic numerical consistency checks; not independent proof review or hardware data.", - "python": "3.13.5", - "platform": "Linux-6.18.44-x86_64-with-glibc2.41", + "python": "3.13.16", + "platform": "Linux-6.17.0-1022-azure-x86_64-with-glibc2.39", "suites": [ { "script": "verify_workspace_construction.py", - "elapsed_seconds": 1.23, - "output_sha256": "1732f227f519b6f47eccfee696b9a8ffbc8c59e589acd9af8d97c72a620706f1", + "elapsed_seconds": 0.963, + "output_sha256": "bcf2d5dea4711dd1d3da5c41b91fee2ae77fb0cf4a9056cacf3fbdc059e83b41", "summary": { "model": "Free internal controls, J=1 per contact, s initialized helpers per module, arbitrary bus", "all_passed": true, @@ -14,8 +14,8 @@ "gate_count": 12, "route_count": 8, "scaling_count": 16, - "max_swap_isometry_error": 1.3071221847431714e-15, - "max_route_isometry_error": 8.99933488754697e-15, + "max_swap_isometry_error": 1.3063632377895411e-15, + "max_route_isometry_error": 8.858715569395616e-15, "largest_route": { "n": 3, "s": 2, @@ -23,7 +23,7 @@ "input_columns": 128, "bus_swaps": 7, "time": 5.497787143782138, - "isometry_operator_error": 5.5857234926833385e-15, + "isometry_operator_error": 5.59366902760566e-15, "full_data_and_bus_process_fidelity": 0.9999999999999905, "helpers_returned": true } @@ -31,8 +31,8 @@ }, { "script": "verify_entropy_budget.py", - "elapsed_seconds": 1.359, - "output_sha256": "c3353e0598cce58e22ad2a65423ebece6bb07073b5ca18794fb8b505f8002098", + "elapsed_seconds": 1.689, + "output_sha256": "73d6a7a7b571d704f2c7c91c7279c3db8ea65365ef1d54a6421d4eaab3936477", "summary": { "seed": 2026101607, "group_scaling_tests": 16512, @@ -43,7 +43,7 @@ "scalar_mgfs": 54, "balanced_partitions": 16512, "min_operator_square_difference_eigenvalue": 0.0, - "max_conditional_rate_ratio": 0.20993163216153346, + "max_conditional_rate_ratio": 0.2099316321615335, "all_passed": true }, "gibbs_tests_count": 120, @@ -54,16 +54,16 @@ }, { "script": "audit_conditional_rate.py", - "elapsed_seconds": 0.945, - "output_sha256": "5aa826199704fad562539b276d5a9526c9249a8fed329738e84fff8c11687c5a", + "elapsed_seconds": 0.422, + "output_sha256": "fd209cd43acf84c7fb8af2a5afc0c0ca905a355124c4e8c8f0a517a0e9597fe8", "summary": { "all_assertions_passed": true, "states_tested": 204, "qubit_bus_states_tested": 114, - "max_qubit_bus_optimized_rate_nats": 1.6151941802831211, - "max_ratio_to_elementary_bound": 0.5710573789056209, - "max_spectral_formula_residual": 3.419486915845482e-14, - "max_dual_optimum_residual": 1.887379141862766e-15, + "max_qubit_bus_optimized_rate_nats": 1.6151941802831218, + "max_ratio_to_elementary_bound": 0.5710573789056211, + "max_spectral_formula_residual": 7.238654120556021e-14, + "max_dual_optimum_residual": 1.9984014443252818e-15, "scope": "For every sampled state, optimize over all Hermitian h with Tr(rho h^2)=1. Not a global state optimization.", "seed": 2026101601, "cases_count": 204 @@ -71,15 +71,15 @@ }, { "script": "audit_ensemble_cut.py", - "elapsed_seconds": 1.225, - "output_sha256": "f964a263505649b72ef5ea5ba827de56cef7e8a49f09dd0111f0969a705f651d", + "elapsed_seconds": 0.922, + "output_sha256": "ff82a5c9d1a0593ab6cf6492796f52ad7cef06df3d1aa449ebb4ff0db100e218", "summary": { "all_assertions_passed": true, "segments": 18, "pure_states_checked": 1152, - "maximum_finite_difference_residual": 1.554406963227839e-06, - "maximum_flat_moment_residual": 6.661338147750939e-16, - "maximum_observed_bound_ratio": 0.08755567546472029, + "maximum_finite_difference_residual": 1.7497813687532282e-06, + "maximum_flat_moment_residual": 7.771561172376096e-16, + "maximum_observed_bound_ratio": 0.08755567546472015, "selected_GHZ_state": { "n": 64, "p": 0.1, @@ -94,7 +94,7 @@ }, { "script": "audit_translation_approximation.py", - "elapsed_seconds": 0.694, + "elapsed_seconds": 0.132, "output_sha256": "9de84e02911247a9ab54a736d0a98c5562396ac8e839ed823703262af94b26c5", "summary": { "all_assertions_passed": true, @@ -110,7 +110,7 @@ }, { "script": "recursive_three.py", - "elapsed_seconds": 0.682, + "elapsed_seconds": 0.099, "output_sha256": "4000ad570b792060da3a22050aef5cfd4e524ad056237aefb60268ce688629de", "summary": { "all_passed": true, @@ -121,7 +121,7 @@ }, { "script": "verify_finite_control.py", - "elapsed_seconds": 0.793, + "elapsed_seconds": 0.28, "output_sha256": "f664a6fea3ef22ff7b2f415474330578f97a4fd3593820d1fef5618c5ee1ded2", "summary": { "all_passed": true, @@ -140,23 +140,23 @@ }, { "script": "verify_full_nine.py", - "elapsed_seconds": 2.956, - "output_sha256": "479dffb9c24d659344c2b34c36b9afa35a594a73b8d452ae62f6b3af4c06a01e", + "elapsed_seconds": 3.579, + "output_sha256": "c0e58ab769999a61849d242bc163452dcd5637e1d395490c6320930b375e3d36", "summary": { "data_qubits": 9, "bus_qubits": 1, "full_input_columns": 1024, "explicit_two_qubit_control_gates": 390, - "operator_error_upper_bound_by_unnormalized_Frobenius": 6.639096555949766e-15, - "maximum_entry_error": 3.510833468576701e-16, - "runtime_seconds": 2.3003544910000073, + "operator_error_upper_bound_by_unnormalized_Frobenius": 8.273281641021161e-15, + "maximum_entry_error": 8.326672684688674e-16, + "runtime_seconds": 3.474018029, "all_passed": true } }, { "script": "verify_mixed_helpers.py", - "elapsed_seconds": 2.118, - "output_sha256": "b9043d5748f4b025c0cb5d127543e599891b2b5184cbe5af576091fcfffcf1d5", + "elapsed_seconds": 2.202, + "output_sha256": "264dfc2e5e5e1770950242c2629f2d6c72be8e666598383ea45f963c4f2a439a", "summary": { "all_passed": true, "scope": "Analytical spectral sums and full helper-block operator checks; not physical noise simulation or independent proof review.", @@ -166,14 +166,14 @@ "complete_routes_count": 6, "finite_examples_count": 9, "same_entropy_counterexamples_count": 3, - "max_good_subspace_error": 9.154722157333965e-15, + "max_good_subspace_error": 9.119947107586788e-15, "max_helper_block_leakage": 0.0 } }, { "script": "verify_scientific_closure.py", - "elapsed_seconds": 1.57, - "output_sha256": "1069745656f8c44f6d30b12457df83babd566e9d7fcdc73124939af12e136d3e", + "elapsed_seconds": 1.141, + "output_sha256": "ce3cecc0796037897ae0855c0fb11362e50df58aab7d45c1f22f9f1aa4e51f1c", "summary": { "all_passed": true, "scope": "Exact rational spectral certification, finite operator checks and analytical timing bounds; no external review or hardware performance claim.", @@ -187,17 +187,17 @@ } ], "source_sha256": { - "checks/audit_conditional_rate.py": "e855c858fd9074c0565d3b51e6a8fc1177e31b2ee737e5fd3e3619c155c953e7", - "checks/audit_ensemble_cut.py": "cc562292fb567f23285e622d930b5a382996a6128e9bf6f612d14b7c568cadd5", - "checks/audit_translation_approximation.py": "9eecaf60ef95dd145020bb4bf7b6256d1b85748ddd98f0c5c5b4951cedf828aa", - "checks/finite_control.py": "d2dd789a8172b3fbd1b1fb7641e0fcdd5a87fe5b182992a3a984a5e16a550226", - "checks/recursive_three.py": "f4577aca7fad831b5e3628c662a13d0c75caec6759a10effec4f68143e180149", - "checks/verify_entropy_budget.py": "6e6d514c73822f88f8c34f1ffa7d797d616b6706ac353492a625fbd8b80db7a5", - "checks/verify_finite_control.py": "a51ecda7a4433bab18931ece1932e7fa6274c49bc4b6c02e1e4b6a9bf2806642", - "checks/verify_full_nine.py": "5921e758407b8ca5e10329b9b5136853aa4f4b7a354f660a800cb0cde341c362", - "checks/verify_mixed_helpers.py": "106277889eeacc211804b4a233e32d35aa7a9aa768d9adc480ed2f892a5e31a1", - "checks/verify_scientific_closure.py": "7836c6a751d9a07eb9462ce9d5eea12a979f47b60b7035fca7923de8923bc4d9", - "checks/verify_workspace_construction.py": "7553585f54782505ec513df840c1ed6d8b3a1c359dc6b8bfa239ce6b120c3698" + "verification/checks/audit_conditional_rate.py": "e855c858fd9074c0565d3b51e6a8fc1177e31b2ee737e5fd3e3619c155c953e7", + "verification/checks/audit_ensemble_cut.py": "cc562292fb567f23285e622d930b5a382996a6128e9bf6f612d14b7c568cadd5", + "verification/checks/audit_translation_approximation.py": "9eecaf60ef95dd145020bb4bf7b6256d1b85748ddd98f0c5c5b4951cedf828aa", + "verification/checks/finite_control.py": "d2dd789a8172b3fbd1b1fb7641e0fcdd5a87fe5b182992a3a984a5e16a550226", + "verification/checks/recursive_three.py": "f4577aca7fad831b5e3628c662a13d0c75caec6759a10effec4f68143e180149", + "verification/checks/verify_entropy_budget.py": "ea88ff42d5afe902432befb66a79fd0c1cd921ccee6b8b00cc9a80ef8d5110ea", + "verification/checks/verify_finite_control.py": "a51ecda7a4433bab18931ece1932e7fa6274c49bc4b6c02e1e4b6a9bf2806642", + "verification/checks/verify_full_nine.py": "5921e758407b8ca5e10329b9b5136853aa4f4b7a354f660a800cb0cde341c362", + "verification/checks/verify_mixed_helpers.py": "106277889eeacc211804b4a233e32d35aa7a9aa768d9adc480ed2f892a5e31a1", + "verification/checks/verify_scientific_closure.py": "7836c6a751d9a07eb9462ce9d5eea12a979f47b60b7035fca7923de8923bc4d9", + "verification/checks/verify_workspace_construction.py": "7553585f54782505ec513df840c1ed6d8b3a1c359dc6b8bfa239ce6b120c3698" }, "numpy": "2.3.5", "scipy": "1.17.0", diff --git a/verify.py b/verification/run_all.py similarity index 94% rename from verify.py rename to verification/run_all.py index cb74214..28c74c7 100644 --- a/verify.py +++ b/verification/run_all.py @@ -12,7 +12,8 @@ import tempfile import time -ROOT = Path(__file__).resolve().parent +ROOT = Path(__file__).resolve().parent.parent +CHECKS = ROOT/'verification'/'checks' SUITES = ( ('verify_workspace_construction.py', 'verify_workspace_construction.json'), ('verify_entropy_budget.py', 'verify_entropy_budget.json'), @@ -33,19 +34,19 @@ def main() -> None: if not __debug__ or os.environ.get('PYTHONOPTIMIZE'): parser.error('Assertions are part of verification; do not enable Python optimization.') output = args.output.resolve() - if output == ROOT or output == ROOT/'checks': + if output == ROOT or output == CHECKS: parser.error('Use a dedicated output directory.') output.mkdir(parents=True, exist_ok=True) env = dict(os.environ, OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1', MKL_NUM_THREADS='1') report = {'scope': 'Deterministic numerical consistency checks; not independent proof review or hardware data.', 'python': platform.python_version(), 'platform': platform.platform(), 'suites': [], 'source_sha256': {str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest() - for p in sorted((ROOT/'checks').glob('*.py'))}} + for p in sorted((CHECKS).glob('*.py'))}} for package in ('numpy', 'scipy'): report[package] = __import__(package).__version__ with tempfile.TemporaryDirectory(prefix='qrb-checks-') as temporary: work = Path(temporary) - for p in (ROOT/'checks').glob('*.py'): + for p in (CHECKS).glob('*.py'): shutil.copy2(p, work/p.name) for script, filename in SUITES: print(f'Running {script}', flush=True) From 7d435f5e7370aadf250fbe8d0c3b54cdf4e0c67c Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Sat, 17 Oct 2026 15:59:37 +0800 Subject: [PATCH 4/4] Complete topic-based refurnishing and restore read-only verification workflows --- .github/workflows/hosted-render.yml | 4 +-- .github/workflows/refurnish-once.yml | 51 ---------------------------- .github/workflows/verify.yml | 7 ++-- 3 files changed, 6 insertions(+), 56 deletions(-) delete mode 100644 .github/workflows/refurnish-once.yml diff --git a/.github/workflows/hosted-render.yml b/.github/workflows/hosted-render.yml index f066f96..ac8fc98 100644 --- a/.github/workflows/hosted-render.yml +++ b/.github/workflows/hosted-render.yml @@ -3,7 +3,7 @@ on: pull_request: paths: - '**.md' - - 'tools/inspect_hosted_render.py' + - 'verification/tools/inspect_hosted_render.py' - '.github/workflows/hosted-render.yml' workflow_dispatch: permissions: @@ -23,7 +23,7 @@ jobs: python-version: '3.13' - run: python -m pip install playwright==1.55.0 - run: python -m playwright install --with-deps chromium - - run: python tools/inspect_hosted_render.py --ref "$RENDER_REF" + - run: python verification/tools/inspect_hosted_render.py --ref "$RENDER_REF" - uses: actions/upload-artifact@v4 if: always() with: diff --git a/.github/workflows/refurnish-once.yml b/.github/workflows/refurnish-once.yml deleted file mode 100644 index 813f08b..0000000 --- a/.github/workflows/refurnish-once.yml +++ /dev/null @@ -1,51 +0,0 @@ -name: Apply authorized repository layout -on: - push: - branches: ['refurnish/current-guidance-20261017'] - paths: ['.github/refurnish.py', '.github/workflows/refurnish-once.yml'] -permissions: - contents: write -jobs: - migrate: - if: github.repository == 'GoGoKo699/Quantum-Routing-Bandwidth' && github.ref == 'refs/heads/refurnish/current-guidance-20261017' - runs-on: ubuntu-latest - timeout-minutes: 10 - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - uses: actions/setup-python@v5 - with: - python-version: '3.13' - - name: Verify the unchanged baseline and apply the migration - run: | - git merge-base --is-ancestor 39ad350c7563f0908034eef21a0024bd6121df13 HEAD - python - <<'PY' - from pathlib import Path - p = Path('.github/refurnish.py') - p.write_text(p.read_text().replace("'HEAD^'", "'39ad350c7563f0908034eef21a0024bd6121df13'")) - PY - python .github/refurnish.py - - run: python -m pip install -r verification/requirements.txt - - run: python verification/run_all.py - - name: Record matching executed outputs and verify exact certificates - run: | - python - <<'PY' - from pathlib import Path - import json, shutil - old = json.loads(Path('verification/results/scientific-closure.json').read_text()) - fresh = json.loads(Path('build/verification/verify_scientific_closure.json').read_text()) - def exact(rows): - return [{k:v for k,v in row.items() if isinstance(v,(int,str,bool))} for row in rows] - assert exact(old['finite_certificates']) == exact(fresh['finite_certificates']) - shutil.copy2('build/verification/verify_scientific_closure.json','verification/results/scientific-closure.json') - shutil.copy2('build/verification/summary.json','verification/results/verification.json') - PY - python check_repository.py - python verification/tools/test_structure.py - - name: Commit only to the authorized working branch - run: | - rm .github/refurnish.py - git add -A - git -c user.name='github-actions[bot]' -c user.email='41898282+github-actions[bot]@users.noreply.github.com' commit -m 'Organize science, shared learning, references, and verification' - git push origin HEAD:refs/heads/refurnish/current-guidance-20261017 diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index a424fca..1bb740f 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -18,7 +18,8 @@ jobs: with: python-version: '3.13' cache: pip - - run: python -m pip install -r requirements.txt + cache-dependency-path: verification/requirements.txt + - run: python -m pip install -r verification/requirements.txt - run: python check_repository.py - - run: python tools/test_release_checks.py - - run: python verify.py + - run: python verification/tools/test_structure.py + - run: python verification/run_all.py