diff --git a/research/row-reversal-rejection-cleanup/NOTICE.md b/research/row-reversal-rejection-cleanup/NOTICE.md new file mode 100644 index 0000000000..1e47bdc959 --- /dev/null +++ b/research/row-reversal-rejection-cleanup/NOTICE.md @@ -0,0 +1,11 @@ +# Source notices + +The new transformer, written proof and replay were produced by Nick Petalas, +under Apache-2.0. The visited-interval technique is classical. + +The exact `reverse.py`, `controller_reference.py` and `NOTICE.md` exports +under `inputs/reversal/` are Jerry Chen / CubeJerry's #7427 at +`7662d01d827c95d90032579c168cae78aa531f2f`. Their notices remain unchanged. +The preserved notice describes the original package and its predecessors; +its historical verification and review statements are not new claims of +this package. No other predecessor programs are imported here. diff --git a/research/row-reversal-rejection-cleanup/PROOF.md b/research/row-reversal-rejection-cleanup/PROOF.md new file mode 100644 index 0000000000..02c3be995d --- /dev/null +++ b/research/row-reversal-rejection-cleanup/PROOF.md @@ -0,0 +1,152 @@ +# Retirement after a finite rejection + +The transformer and this supplied-interface application were produced by Nick +Petalas. The visited-interval method is classical. The successful reversal, +its original implementation, and its original successful-run accounting are +Jerry Chen / CubeJerry's #7427, not results claimed here. + +## Statement and premises + +Fix a program on n tapes with the local instructions `read`, `write`, unit +`move`, `goto` and `halt`. A missing read branch is rejection. The program +and its finite alphabet are fixed before execution. Some tapes are public; +the rest are private. Each private cell the source execution will visit is +initially blank. Public cells may contain arbitrary alphabet symbols. + +Add n distinct monitor tapes. Each starts at its own origin. Its window +corresponding to the source run's visited interval, with one additional cell +on each side, is blank on entry. These whole-window blankness premises must +be supplied by the caller. Opaque exterior contents are permitted. This is +not a method for discovering whether a borrowed dirty interval is blank. + +Suppose the source halts or rejects after T instructions, counting its +terminal halt or rejecting read. Let I_i be its visited interval on tape i, +let l_i = |I_i|, and let L = sum_i l_i. The transformer emits a fixed program +on 2n tapes that has the following behavior. + +1. It simulates every source instruction up to that terminal event. +2. It preserves the source's public contents at that event, erases every + visited private cell, and returns every original and monitor head to its + entry position. It erases all monitor marks. +3. It terminates at distinct accepting and rejecting locations, matching the + source's terminal event. +4. Its time is at most `5T + 16L + 6n <= 21T + 22n` local instructions. +5. Each original head visits at most one extra cell at each end of I_i. + Each monitor visits the corresponding interval with those two cells. + +This is a scoped simulation and cleanup theorem. It asserts no cleanup on a +nonterminating execution, on a host interruption, on an absent blank window, +or on a machine fault outside the declared alphabet and instruction model. +Public writes already performed by a source are not rolled back. + +The implementation supports 1 <= n <= 32, source tables of 1 to 10,000 +locations, and alphabets of at most 16 symbols. These are compiler input +bounds, not bounds on T or the runtime descriptor values. The theorem holds +for each supported fixed table and every finite run meeting the premises. + +## Simulation invariant + +For tape i, the monitor head has the same displacement from its origin as +the original head has from its origin. The monitor stores `|` at its origin, +`1` at each other visited source position, and blank at unvisited positions. +Unit head motion makes the visited set an interval containing the origin. + +Initialization writes the n origin markers. A source read, write or jump +uses one instruction. Read branches are relocated to the corresponding +compiled locations; absent branches go to rejection cleanup. A halt goes +to acceptance cleanup. A move becomes these local instructions: + +1. Move the original head one cell. +2. Move its monitor head in the same direction. +3. Read the monitor. A prior mark branches directly to the next source + location. On blank, write `1` and jump there. + +Thus every source instruction costs at most five compiled instructions. +No source value, integer, coordinate, length or history counter enters the +runtime control. The simulated original contents agree instruction by +instruction with the source. Marks never change a public or private source +symbol during simulation. + +## Cleanup invariant + +Acceptance and rejection have separate copies of the same cleanup graph. +The terminal status therefore needs no runtime status register. + +For each tape and its monitor, the graph first moves both heads left until +the monitor is blank. This is exactly the cell immediately left of I_i. +It moves both heads right once and sweeps the l_i marked cells to the right. +On private tapes it writes blank at every such source cell; on public tapes +it makes no source write. It clears each `1` on the monitor, retaining `|`. +The first blank after the interval ends this sweep. No source cell outside +I_i is written. + +Both heads move left once, then continue left through the now blank monitor +until `|`. They are then at their original origins. Erasing `|` leaves the +monitor blank and makes the pair ready for another call. This loop stops +because the origin lies in I_i. Its stopping condition does not depend on +source symbols, which may include blanks and markers anywhere. + +Processing a pair never moves or writes another pair. Induction through +the fixed list of n pairs proves all head returns and erasures. Initial +private blankness makes erasure restore its entry contents; exterior cells +retain their contents even when an end cell is visited by cleanup. + +## Time and historical backing + +Write a for the number of marked cells traversed in the first left scan and +b for the distance from the rightmost source position to its origin. Then +`a <= l_i` and `b <= l_i - 1`. + +The first scan and its turn cost `4a + 3`. A right-sweep nonorigin cell +costs at most seven instructions, and the unique origin cell saves one. +The right turn costs three. The return costs `4b + 2`. Hence one pair costs +at most `15l_i + 3`, before the final cleanup halt. With n initialization +writes and that halt, the full run costs at most + +`5T + 15L + 4n + 1 <= 5T + 16L + 6n`. + +Each source move can enlarge the sum of visited lengths by at most one, so +`L <= T+n`. This gives the displayed bound `21T + 22n`. All loops have a +finite scan bound from l_i, a or b; no numerical length is supplied to the +runtime graph. + +Relative to the source execution's historical backing, cleanup adds at most +2n original cells. The monitor run visits at most `L+2n` cells. If its prior +historical backing is H0, the combined historical backing is at most + +`source historical backing + H0 + L + 4n`. + +Erasing cells does not reduce historical backing. On subsequent calls the +same monitor objects, origins and histories persist. An old long erased +tail is not scanned: the current run marks only its current interval, whose +adjacent unmarked cells stop the cleanup sweeps. + +## Whole-record reversal application + +The retained table is precisely #7427 at commit +`7662d01d827c95d90032579c168cae78aa531f2f`. Its three descriptor tapes and +DATA are public, and its nine other tapes are private. The two retained +source files are byte-bound in `program.py` and `SOURCES.json`. + +The predecessor stages the result and validates packet cardinality before +writing DATA. Its stated rejection contract preserves all public contents +but does not retire private state or heads. Taking that source property as +a premise, the new simulation preserves public contents on rejection and +adds the missing retirement. On acceptance it implements the same complete +record permutation. The new graph uses 26 tapes and the original four +symbols. It adds no trusted shape, address stream, runtime decoded integer +or payload callback. + +For a valid packet the predecessor's source bound is O(V+E), so the new +bound is O(V+E). For malformed packets the statement is O(T) in the actual +finite rejected source execution. A descriptor can request much more work +than the actual DATA length, so no O(actual payload) rejection bound is +claimed. Providing the additional monitor windows and their owned lifetime +is an explicit caller obligation. + +`verify.py` executes the emitted graph on valid and malformed packets and +on a rejected-then-valid reuse of the same 26 objects. Generic fixtures +also move left of the origin, retain public writes made before rejection, +and erase private intervals. These finite checks corroborate the invariant +proof; they do not enumerate all descriptors or prove a multiplication +theorem. Independent human and formal proof-kernel review are unclaimed. diff --git a/research/row-reversal-rejection-cleanup/README.md b/research/row-reversal-rejection-cleanup/README.md new file mode 100644 index 0000000000..c0f6cc630c --- /dev/null +++ b/research/row-reversal-rejection-cleanup/README.md @@ -0,0 +1,106 @@ +# Reuse reversal banks after a finite rejection + +This scoped constructive proof and executable graph add rejection retirement +to Jerry Chen / CubeJerry's [#7427](https://github.com/CrocSwap/integer-mult-bounds/pull/7427). +The contribution was produced by Nick Petalas. No new kappa is claimed. + +The new fixed graph uses **26 tapes, 2,145 locations and four symbols**. +After a finite malformed-input rejection it preserves all public contents, +erases private work and returns every head. The same private banks can then +serve a valid reversal. The predecessor's successful reversal and its public +preservation on rejection are cited premises. Their verification is not the +deliverable. + +For a source run of T instructions on n tapes with total visited length L, +the new graph costs at most `5T+16L+6n <= 21T+22n`. Here n=13, giving +`21T+286`. The graph records visits on synchronized monitor tapes, clears +each marked private interval and returns to its retained origin marker. +The visited-interval method is classical; the explicit transformer and this +rejection/reuse application are the new contribution. [PROOF.md](PROOF.md) +gives the quantified premises, loop bounds and historical-backing bill. + +The source is frozen at `7662d01d827c95d90032579c168cae78aa531f2f`. +Only its two executable files and original notice are retained locally. +[SOURCES.json](SOURCES.json) records their original paths, byte lengths, +Git blob IDs and SHA256 hashes. The verifier authenticates these local +exports before importing them. No pending Git object or network is needed. + +## Evidence and reproduction + +From the repository root with CPython 3.12: + +```sh +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -I -B -W error research/row-reversal-rejection-cleanup/verify.py +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -I -O -B -W error research/row-reversal-rejection-cleanup/verify.py +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -B scripts/research_package.py --package research/row-reversal-rejection-cleanup +/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12 -B scripts/check_research_commit.py --package research/row-reversal-rejection-cleanup --check-source-history +``` + +A reviewer elsewhere may substitute their CPython 3.12 path. Expected markers +are `PASS_ROW_REVERSAL_REJECTION_CLEANUP`, `PASS_REGISTERED_RESEARCH_PACKAGE` +and `PASS_RESEARCH_COMMIT_BYTES`. + +The complete replay executes 518 valid packets, 25 malformed packets, a +rejected-then-valid reuse chain and 16 generic left/right fixtures. It checks +public contents, opaque exteriors, original owner identity, all head returns, +private erasure, preserved historical backing and the instruction bound. +Eight controls reject omitted erasure, an unretired monitor origin and six +invalid compiler inputs. The valid-packet oracle reverses complete records +directly. The generic fixtures include public writes before rejection and +prove that cleanup preserves that terminal public state rather than rolling +it back. All counts enumerate the stated finite fixture sets. + +`RESULT.json` is generated by `verify.py --record`, with hashes binding the +proof, program, verifier and source manifest. Default replay only reads the +receipt. Runtime transition counts are local-instruction counts; they are +not wall-clock speed claims or a proof-assistant certificate. + +The compiler and checker use managed Python containers. The finite fixture +dimensions and two-million-instruction per-run cap bound replay resources. +The mathematical runtime is the emitted local graph; its scan loops have +the visited-interval bounds proved in PROOF.md. + +## Limits and scope + +The source program must halt or reject, and its private visited cells and +the additional monitor windows must be blank on entry. The caller must own +and provide those windows. Erasure preserves historical allocation. No +cleanup after interruption or nontermination is promised. This gives time +linear in the finite rejected execution, which can be much larger than the +actual DATA length for excessive descriptors. + +Card `formal-interface-lemma`, priority revision 8, changes scope to #7427's +Open next question 4. Base `e54523517d0f03e58352e647c403a5af3e525a57`. +The source-binding orientation command passes at selected #7000; the older +#5599 values in the priorities prose are historical. This package changes no +selected record. It implements no complete native MOVE, physical caller, +common-grid conversion or multiplier. Those integrations, the selected cold +replay, independent human review and formal proof-kernel acceptance are unrun +or unclaimed. + +## Open next questions + +Can fewer monitor tapes preserve this contract over the original alphabet? +Start with one pair of source heads and prove their displacement relation +on every malformed path before sharing a monitor. Can a concrete caller +reject excessive descriptors before doing work exponential in their bit +length? First give its encoded resource cap and pre-write contract. +[TASK.json](TASK.json) records why these questions matter and their blockers. + +## Credit and related open work + +Jerry Chen / CubeJerry #7427 supplies the reversal, finite machine reference, +source contract and failure-retirement question. The canonical stream +two-stack algorithm and visited-interval cleanup are prior techniques. +The original notice is preserved in [inputs/reversal/NOTICE.md](inputs/reversal/NOTICE.md). + +- #7427 implements the supplied-descriptor reversal with a success-only + retirement contract; this package adds rejection retirement. +- #7428 produces descriptors and applies that reversal to a selected + translation. Its descriptor producer and complete caller are outside this + package; its use of the original reversal does not include this wrapper. +- #7425 and #7426 implement related literal phase tables with success-only + private retirement. They are not transformed or priced here. + +New material is Apache-2.0. Independent human and formal proof-kernel review +are unclaimed. diff --git a/research/row-reversal-rejection-cleanup/RESULT.json b/research/row-reversal-rejection-cleanup/RESULT.json new file mode 100644 index 0000000000..1462610179 --- /dev/null +++ b/research/row-reversal-rejection-cleanup/RESULT.json @@ -0,0 +1,57 @@ +{ + "bindings": { + "PROOF.md": "9a34020b394d15aa26f40efe06bb9446206769a13bdb6f98577f6f89d422f04e", + "SOURCES.json": "b43a18d5fe88f4244466f079d2e56447baeec68773d0181ea8072484f018ce23", + "program.py": "905712189a9785244cb3058c8c552dae438a31eca565e72f7b8e1455202e326f", + "verify.py": "a36baae51054f0e30e475e139ab7b6b9f79c453aed7ff799770105150981ffe5" + }, + "controls": [ + "private_erasure", + "origin_retirement", + "bad_jump", + "long_move", + "unknown_write", + "fallthrough", + "missing_operand", + "nonlocal_opcode" + ], + "generic": { + "calls": 16, + "evidence_sha256": "4567b13409914b2e4346154de783281833381f294b02ead341c13b8eceaeecf6" + }, + "locations": 2145, + "pins": { + "inputs/reversal/NOTICE.md": "940493cde2626cb55438be8abda72b9ad971bf059f7c9046591665163e266904", + "inputs/reversal/inputs/controller_reference.py": "e664a748e6b6797d4b60f60a7a7dd68b59a5608acf56b9c5d8b466f363755f73", + "inputs/reversal/reverse.py": "4b516d85baf3303db809bc1174394009b1fc71a8f7d17fb6c729ec8bb6aba245" + }, + "rejection": { + "calls": 25, + "evidence_sha256": "d82f14a4a3087fb9250ad50c6962a1a2862c0e010783a6317aeb40d51ba3832a", + "transitions": 25832 + }, + "reuse": { + "final_history": 178, + "first": { + "source_span": 57, + "source_steps": 499, + "status": "reject", + "steps": 1768 + }, + "prior_history": 166, + "second": { + "source_span": 54, + "source_steps": 587, + "status": "accept", + "steps": 1851 + } + }, + "source_locations": 524, + "status": "PASS_ROW_REVERSAL_REJECTION_CLEANUP", + "success": { + "calls": 518, + "evidence_sha256": "218e3351d3fbbebea3e17c3eac18d24e29f3c470a773c3d7c7b293a0f1e9e9a5", + "transitions": 1121672 + }, + "tapes": 26 +} diff --git a/research/row-reversal-rejection-cleanup/SOURCES.json b/research/row-reversal-rejection-cleanup/SOURCES.json new file mode 100644 index 0000000000..2f4736bcbb --- /dev/null +++ b/research/row-reversal-rejection-cleanup/SOURCES.json @@ -0,0 +1,50 @@ +{ + "schema_version": 1, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "files": [ + { + "path": "certificates/selected-result.json", + "usage": "provenance", + "git_blob": "75d77b328ea02ded535e7f23aee5b1e55d0bb1a8", + "sha256": "154c3d30455d778fd3343b6b4851f0fa4665f0f7625b0adb3675e2bafbbf6bf1" + }, + { + "path": "docs/research/agent-task-catalog.json", + "usage": "provenance", + "git_blob": "3404fbdd5e7529a0674eef26114b5071e4586cec", + "sha256": "ead6cdc9d0af6d58e8a49744d8ec8c7c15e13d2ba93c276c434bcf9b51b93a81" + } + ], + "retained_exports": [ + { + "local_path": "inputs/reversal/reverse.py", + "origin_repository": "CrocSwap/integer-mult-bounds", + "origin_commit": "7662d01d827c95d90032579c168cae78aa531f2f", + "origin_path": "research/literal-row-reversal/reverse.py", + "origin_url": "https://github.com/CrocSwap/integer-mult-bounds/blob/7662d01d827c95d90032579c168cae78aa531f2f/research/literal-row-reversal/reverse.py", + "sha256": "4b516d85baf3303db809bc1174394009b1fc71a8f7d17fb6c729ec8bb6aba245", + "git_blob": "60fce51dd8c3336e2bcf2873df254190e2203e14", + "bytes": 6649 + }, + { + "local_path": "inputs/reversal/inputs/controller_reference.py", + "origin_repository": "CrocSwap/integer-mult-bounds", + "origin_commit": "7662d01d827c95d90032579c168cae78aa531f2f", + "origin_path": "research/literal-row-reversal/inputs/controller_reference.py", + "origin_url": "https://github.com/CrocSwap/integer-mult-bounds/blob/7662d01d827c95d90032579c168cae78aa531f2f/research/literal-row-reversal/inputs/controller_reference.py", + "sha256": "e664a748e6b6797d4b60f60a7a7dd68b59a5608acf56b9c5d8b466f363755f73", + "git_blob": "3ab6d0361f35038ffcdf0cf81a157f7a17b40e72", + "bytes": 5938 + }, + { + "local_path": "inputs/reversal/NOTICE.md", + "origin_repository": "CrocSwap/integer-mult-bounds", + "origin_commit": "7662d01d827c95d90032579c168cae78aa531f2f", + "origin_path": "research/literal-row-reversal/NOTICE.md", + "origin_url": "https://github.com/CrocSwap/integer-mult-bounds/blob/7662d01d827c95d90032579c168cae78aa531f2f/research/literal-row-reversal/NOTICE.md", + "sha256": "940493cde2626cb55438be8abda72b9ad971bf059f7c9046591665163e266904", + "git_blob": "45c98a1b3ebf215989afaa966fe413af072a0973", + "bytes": 2009 + } + ] +} diff --git a/research/row-reversal-rejection-cleanup/TASK.json b/research/row-reversal-rejection-cleanup/TASK.json new file mode 100644 index 0000000000..5637f7a384 --- /dev/null +++ b/research/row-reversal-rejection-cleanup/TASK.json @@ -0,0 +1,108 @@ +{ + "schema_version": 1, + "task_id": "formal-interface-lemma", + "priority_revision": 8, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "original_card": { + "id": "formal-interface-lemma", + "question": "Can one uncovered interface implication be formalized with exact caller and certificate bindings?", + "starting_points": [ + "docs/research/research-family-status.md", + "certificates/selected-result.json", + "research/gate-operand-parity-lean/README.md", + "research/staged544-certified-endpoint/README.md", + "research/unconditional-batched-crt/README.md" + ], + "methods": [ + "Formalize a missing boundary lemma identified by the selected review.", + "Audit a formal theorem-to-certificate binding independently." + ], + "acceptance_gate": "State the exact formalized proposition and remaining assumptions; avoid duplicate arithmetic formalizations already present.", + "first_step": { + "command": [ + "python3", + "-B", + "scripts/research_selected_baseline.py" + ], + "expected": "PASS_RESEARCH_BASELINE_BINDINGS_ONLY", + "inspect": "Resolve the current selected review, separate complex/ordinary BIT/admitted BIT/outer budgets, and compare the card against live handoffs before starting. Historical ceilings require exact source/model equivalence.", + "scope": "Source-binding orientation only; not a scientific replay or all-size proof. Materialize selected inputs if this checkout is sparse." + }, + "first_experiment": "Write one missing statement with quantified hypotheses, actual caller and existing coverage. A compact-switch lemma is a candidate only after its mathematical contract is reviewed. Establish a bounded proof plan before a separately budgeted proof-assistant build; do not rerun large Lean jobs as orientation.", + "bottleneck_link": "A missing interface proof can reduce the conditional gap even if it does not change kappa.", + "allowed_variations": [ + "Narrow to one formal lemma or one theorem-to-certificate binding." + ], + "scope_change_triggers": [ + "Formalizing already-covered arithmetic and claiming the full multiplication theorem." + ], + "overlap_terms": [ + "hyperplane end", + "formal interface", + "Lean binding", + "3807", + "3857", + "4100", + "gate-operand-parity-lean", + "staged544-certified-endpoint", + "unconditional-batched-crt" + ], + "existing_checks": [ + { + "scope": "PR #3807: scoped gate-operand parity formalization.", + "evidence": "research/gate-operand-parity-lean/README.md", + "remaining": "Exact theorem-to-caller binding and genuinely uncovered interface lemmas.", + "status": "author-checked", + "source_commit": "4c3530f42a6abcc48e7a6bcffd6c901911dc8269", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + }, + { + "scope": "PR #3857: certified real-power moment/endpoint arithmetic.", + "evidence": "research/staged544-certified-endpoint/README.md", + "remaining": "Uniform algorithmic implications, not another endpoint digit.", + "status": "author-checked", + "source_commit": "ef4315b8caa605e47a2515004845eb2d2ed71a86", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + }, + { + "scope": "PR #4100: compact-switch formalization proposed as future validation.", + "evidence": "research/unconditional-batched-crt/README.md", + "remaining": "Audit the statement and assumptions before a formal proof campaign.", + "status": "author-checked", + "source_commit": "337d04939571a637aeab54a0f58f54fde811663a", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + } + ] + }, + "scope_status": "changed", + "actual_scope": "Fixed local-symbol simulation and retirement graph for both terminal outcomes of the supplied whole-record reversal, including malformed-then-valid private-bank reuse.", + "scope_change_reason": "The card proposes a formal proof obligation from the selected review. This package instead supplies a written simulation proof and executable local graph for the explicitly open failure-retirement interface in CubeJerry PR7427; no proof-assistant or complete selected-assumption claim is made.", + "bottleneck_link": "Reusable private-bank lifetimes require head return and erasure after a rejected call. This fills that local reversal contract while charging an additional thirteen monitor tapes, their history and every cleanup instruction.", + "budget_minutes": 60, + "stop_rule": "Stop at the first verified retirement/reuse construction. Do not extend to other native factors or optimize its tape count.", + "outcome": "completed", + "evidence": "PROOF.md; program.py emitted 2145-location graph; verify.py and generated RESULT.json, including 25 malformed packets and same-bank rejected-then-valid reuse.", + "author": "Nick Petalas", + "ai_assistance": "Independent human and formal proof-kernel review are unclaimed.", + "open_questions": [ + { + "question": "Can reversal rejection retirement use fewer than thirteen monitor tapes while retaining the original four-symbol alphabet and constant-factor time?", + "why_it_matters": "The present construction buys a stronger reuse contract with a larger fixed tape inventory.", + "first_step": "Identify two source heads with provably synchronized displacements throughout the entire reversal, including malformed paths.", + "blocked_by": "No such all-path synchronization is proved here." + }, + { + "question": "Can a caller supply a checked work bound before processing malformed binary shape descriptors?", + "why_it_matters": "Linear time in the rejected execution is not linear time in actual DATA length when a descriptor requests excessive work.", + "first_step": "State an encoded resource cap and a pre-write rejection contract for one concrete caller.", + "blocked_by": "No caller resource-cap interface is supplied." + } + ], + "claim_url": "https://github.com/CrocSwap/integer-mult-bounds/discussions/1166#discussioncomment-19572921", + "environment": { + "python": "3.12.15", + "implementation": "CPython", + "platform": "macOS-27.0.1-arm64-arm-64bit", + "interpreter": "/Users/nick/git/integer-mult-bounds/.venv/bin/python3.12" + } +} diff --git a/research/row-reversal-rejection-cleanup/VERIFY.json b/research/row-reversal-rejection-cleanup/VERIFY.json new file mode 100644 index 0000000000..110963bf83 --- /dev/null +++ b/research/row-reversal-rejection-cleanup/VERIFY.json @@ -0,0 +1,34 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [], + "commands": [ + { + "argv": [ + "{python}", + "-I", + "-B", + "-W", + "error", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "Execute the emitted retirement graph on 518 valid packets, 25 malformed packets, one rejected-then-valid reuse chain, 16 generic left/right fixtures and semantic/compiler-boundary rejection controls; compare generated hash-bound receipt." + }, + { + "argv": [ + "{python}", + "-I", + "-O", + "-B", + "-W", + "error", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "Same complete verification under optimized Python; all acceptance conditions use explicit exceptions." + } + ] +} diff --git a/research/row-reversal-rejection-cleanup/inputs/reversal/NOTICE.md b/research/row-reversal-rejection-cleanup/inputs/reversal/NOTICE.md new file mode 100644 index 0000000000..45c98a1b3e --- /dev/null +++ b/research/row-reversal-rejection-cleanup/inputs/reversal/NOTICE.md @@ -0,0 +1,36 @@ +# Attribution and source notices + +Prepared for Jerry Chen / @CubeJerry with substantial OpenAI assistance. +New package material is under the repository's Apache-2.0 license. Exact +predecessor files retain their original notices and licenses. + +The canonical `02-streams.tex` already defines the collapsed binary-length +ABI, complete rows, the high-level two-stack reversal for ordered-affine +negation, and the linear nested-scan analysis. These ideas are prior work; +this contribution claims their scoped literal lowering and complete +same-owner/retained-history census, not mathematical priority for reversal. + +jwr404's controlled-block-shear package in +CrocSwap/integer-mult-bounds#3834 records controlled block/XOR map evidence +and credits Matarener's CrocSwap/integer-mult-bounds#3825 predecessor. Its +finite algebraic checks are distinct from this tape implementation. +JoyboyBrian's CrocSwap/integer-mult-bounds#5188 supplies a different literal +elementary field interchange and informs the bounded overlap check. + +The retained selected-complex-compact adapter and its contributors are +credited for the exact source `flip_digit` interface used in map checks. +Its original files are copied without changes, authenticated and retained +as references. The existing caller's Python control is not represented as +a literal machine service by this package. + +The finite Builder/Machine export is pinned to CubeJerry's commit +`9dfe6747b8553fd11b408f2b045c5954ef1e6eaa`. Unary copy, clear, trace return +and staged commit patterns follow the literal S_D package at CubeJerry's +verified commit `8b549ca6557ccbb3017b104b27ea35051f990416`, which in turn +credits the literal layer-egress package at +`51ab0539059214fcfa044938c36a0b6017232be5`. Neither package has an invented +upstream PR number in this submission. + +Independent review contributions, their exact tested bytes, and remaining +limitations are recorded in REVIEW.md. AI-assisted checks are not described +as human approval or formal proof-kernel verification. diff --git a/research/row-reversal-rejection-cleanup/inputs/reversal/inputs/controller_reference.py b/research/row-reversal-rejection-cleanup/inputs/reversal/inputs/controller_reference.py new file mode 100644 index 0000000000..3ab6d0361f --- /dev/null +++ b/research/row-reversal-rejection-cleanup/inputs/reversal/inputs/controller_reference.py @@ -0,0 +1,112 @@ +"""Finite three-tape online rank-recursion control; Apache-2.0. +Only PC and local symbols affect execution. Metrics/event logs are observers. +""" +from dataclasses import dataclass, field +BLANK, ONE, MARK = '_', '1', '|' +WIDTH, CHILD, STACK = range(3) + +class Builder: + def __init__(self): self.code, self.labels, self.serial = [], {}, 0 + def mark(self,n): + if n in self.labels: raise ValueError('duplicate label') + self.labels[n]=len(self.code) + def op(self,*x): self.code.append(x) + def rewind(self,t,symbols): + self.serial+=1; loop=f'rw{self.serial}'; done=loop+'done' + self.op('move',t,-1); self.mark(loop) + self.op('read',t,{s:loop+'step' for s in symbols}|{MARK:done}) + self.mark(loop+'step'); self.op('move',t,-1); self.op('goto',loop) + self.mark(done); self.op('move',t,1) + def finish(self,alphabet): + result=[] + for op,*a in self.code: + if op=='goto': a[0]=self.labels[a[0]] + elif op=='read': a[1]={s:self.labels[n] for s,n in a[1].items()} + result.append((op,*a)) + return tuple(result),tuple(alphabet) + +def compile_controller(m,ranks): + """Parameters are compile-time constants, absent from run-time state.""" + if type(m) is not int or m<2 or not ranks: raise ValueError('bad fixed profile') + if any(type(r) is not int or not 1<=r=budget: raise ValueError('finite verifier budget') + self.step() + return self + +def initial_tapes(width,origins=(0,0,0),ancestor=('0','1','t0','_','|','0')): + if width<1: raise ValueError('positive width') + u,c,p=origins + return [Tape({u-1:MARK,**{u+i:ONE for i in range(width)}},u),Tape({c-1:MARK},c), + Tape({p-1:MARK,**{p-2-i:s for i,s in enumerate(ancestor) if s!=BLANK}},p)] diff --git a/research/row-reversal-rejection-cleanup/inputs/reversal/reverse.py b/research/row-reversal-rejection-cleanup/inputs/reversal/reverse.py new file mode 100644 index 0000000000..60fce51dd8 --- /dev/null +++ b/research/row-reversal-rejection-cleanup/inputs/reversal/reverse.py @@ -0,0 +1,207 @@ +"""Literal complete-record reversal from three encoded binary descriptors. + +Prepared for Jerry Chen / CubeJerry with substantial OpenAI assistance. +Apache-2.0. The two-stack algorithm is classical and already in 02-streams; +the unary/trace helper patterns come from the credited literal S_D package. +This zero-argument compiler emits one fixed local-symbol instruction graph. +""" +from pathlib import Path +import hashlib +import sys + +HERE = Path(__file__).resolve().parent +MACHINE = HERE / 'inputs' / 'controller_reference.py' +EXPECTED_MACHINE = 'e664a748e6b6797d4b60f60a7a7dd68b59a5608acf56b9c5d8b466f363755f73' +if hashlib.sha256(MACHINE.read_bytes()).hexdigest() != EXPECTED_MACHINE: + raise ValueError('frozen literal machine source drift') +sys.path.insert(0, str(MACHINE.parent)) +from controller_reference import Builder, Machine, Tape, BLANK, ONE, MARK + +(PDESC, RDESC, BDESC, DATA, OUTPUT, PTR, RTR, BTR, DOUBLE, + HTRACE, GROUP, RECORD, DTRACE) = range(13) +PRIVATE = tuple(range(4, 13)) +BITS = ('0', ONE) + + +def fresh(a, stem): + a.serial += 1 + return stem + str(a.serial) + + +def clear(a, tape, symbols=(ONE,)): + k = fresh(a, 'clear') + a.mark(k) + a.op('read', tape, {s: k+'bit' for s in symbols} | {BLANK: k+'done'}) + a.mark(k+'bit') + a.op('write', tape, BLANK) + a.op('move', tape, 1) + a.op('goto', k) + a.mark(k+'done') + a.rewind(tape, (BLANK,)) + + +def unary_copy(a, source, target, *, repeat=1, extra=0, erase=False): + k = fresh(a, 'copy') + a.mark(k) + a.op('read', source, {ONE: k+'bit', BLANK: k+'done'}) + a.mark(k+'bit') + for _ in range(repeat): + a.op('write', target, ONE) + a.op('move', target, 1) + if erase: + a.op('write', source, BLANK) + a.op('move', source, 1) + a.op('goto', k) + a.mark(k+'done') + for _ in range(extra): + a.op('write', target, ONE) + a.op('move', target, 1) + a.rewind(source, (BLANK,) if erase else (ONE,)) + a.rewind(target, (ONE,)) + + +def trace_return(a, tape, trace): + k = fresh(a, 'return') + a.op('move', trace, -1) + a.mark(k) + a.op('read', trace, {ONE: k+'bit', MARK: k+'done'}) + a.mark(k+'bit') + a.op('write', trace, BLANK) + a.op('move', trace, -1) + a.op('move', tape, -1) + a.op('goto', k) + a.mark(k+'done') + a.op('move', trace, 1) + + +def descriptor_step(a, descriptor): + a.op('write', HTRACE, ONE) + a.op('move', HTRACE, 1) + a.op('move', descriptor, 1) + + +def binary_descriptor(a, descriptor, target): + """A positive canonical MSB-first binary word to a unary guide.""" + k = fresh(a, 'binary') + a.op('read', descriptor, {ONE: k+'first'}) + a.mark(k+'first') + a.op('write', target, ONE) + descriptor_step(a, descriptor) + a.mark(k+'digit') + a.op('read', descriptor, {str(b): k+str(b) for b in (0, 1)} | + {BLANK: k+'done'}) + for bit in (0, 1): + a.mark(k+str(bit)) + unary_copy(a, target, DOUBLE, repeat=2, extra=bit) + clear(a, target) + unary_copy(a, DOUBLE, target, erase=True) + descriptor_step(a, descriptor) + a.op('goto', k+'digit') + a.mark(k+'done') + trace_return(a, descriptor, HTRACE) + + +def compile_reverse(): + """Compile once; no descriptor, shape, payload or origin argument.""" + a = Builder() + for tape in PRIVATE: + a.op('move', tape, -1) + a.op('write', tape, MARK) + a.op('move', tape, 1) + for descriptor, target in ((PDESC, PTR), (RDESC, RTR), (BDESC, BTR)): + binary_descriptor(a, descriptor, target) + a.mark('prefix') + a.op('read', PTR, {ONE: 'load_record', BLANK: 'finish'}) + a.mark('load_record') + a.op('read', RTR, {ONE: 'load_bit', BLANK: 'group_loaded'}) + a.mark('load_bit') + a.op('read', BTR, {ONE: 'read_bit', BLANK: 'record_loaded'}) + a.mark('read_bit') + a.op('read', DATA, {str(b): 'load'+str(b) for b in (0, 1)}) + for bit in ('0', ONE): + a.mark('load'+bit) + a.op('write', GROUP, bit) + a.op('move', GROUP, 1) + a.op('move', DATA, 1) + a.op('write', DTRACE, ONE) + a.op('move', DTRACE, 1) + a.op('move', BTR, 1) + a.op('goto', 'load_bit') + a.mark('record_loaded') + a.rewind(BTR, (ONE,)) + a.op('move', RTR, 1) + a.op('goto', 'load_record') + a.mark('group_loaded') + a.rewind(RTR, (ONE,)) + a.op('move', GROUP, -1) + a.mark('pop_record') + a.op('read', RTR, {ONE: 'pop_bit', BLANK: 'group_popped'}) + a.mark('pop_bit') + a.op('read', BTR, {ONE: 'pop_read', BLANK: 'record_popped'}) + a.mark('pop_read') + a.op('read', GROUP, {str(b): 'pop'+str(b) for b in (0, 1)}) + for bit in ('0', ONE): + a.mark('pop'+bit) + a.op('write', RECORD, bit) + a.op('move', RECORD, 1) + a.op('write', GROUP, BLANK) + a.op('move', GROUP, -1) + a.op('move', BTR, 1) + a.op('goto', 'pop_bit') + a.mark('record_popped') + a.rewind(BTR, (ONE,)) + a.op('move', RECORD, -1) + a.mark('emit_record') + a.op('read', RECORD, {str(b): 'emit'+str(b) for b in (0, 1)} | + {MARK: 'record_emitted'}) + for bit in ('0', ONE): + a.mark('emit'+bit) + a.op('write', OUTPUT, bit) + a.op('move', OUTPUT, 1) + a.op('write', RECORD, BLANK) + a.op('move', RECORD, -1) + a.op('goto', 'emit_record') + a.mark('record_emitted') + a.op('move', RECORD, 1) + a.op('move', RTR, 1) + a.op('goto', 'pop_record') + a.mark('group_popped') + a.op('read', GROUP, {MARK: 'prefix_done'}) + a.mark('prefix_done') + a.op('move', GROUP, 1) + a.rewind(RTR, (ONE,)) + a.op('move', PTR, 1) + a.op('goto', 'prefix') + a.mark('finish') + # Exact cardinality is derived from descriptor guides before DATA writes. + a.op('read', DATA, {BLANK: 'verified', '0': 'reject', ONE: 'reject'}) + a.mark('verified') + trace_return(a, DATA, DTRACE) + a.rewind(OUTPUT, BITS) + a.mark('commit') + a.op('read', OUTPUT, {str(b): 'commit'+str(b) for b in (0, 1)} | + {BLANK: 'committed'}) + for bit in ('0', ONE): + a.mark('commit'+bit) + a.op('write', DATA, bit) + a.op('write', OUTPUT, BLANK) + a.op('move', OUTPUT, 1) + a.op('move', DATA, 1) + a.op('write', DTRACE, ONE) + a.op('move', DTRACE, 1) + a.op('goto', 'commit') + a.mark('committed') + trace_return(a, DATA, DTRACE) + a.rewind(OUTPUT, (BLANK,)) + a.rewind(PTR, (ONE,)) + for tape in (PTR, RTR, BTR): + clear(a, tape) + for tape in PRIVATE: + a.op('move', tape, -1) + a.op('write', tape, BLANK) + a.op('move', tape, 1) + a.op('halt') + a.mark('reject') + a.op('read', DATA, {}) + return a.finish((BLANK, '0', ONE, MARK)) + diff --git a/research/row-reversal-rejection-cleanup/program.py b/research/row-reversal-rejection-cleanup/program.py new file mode 100644 index 0000000000..1b020a9d90 --- /dev/null +++ b/research/row-reversal-rejection-cleanup/program.py @@ -0,0 +1,148 @@ +"""Compile local visit tracking and retirement on acceptance or rejection. + +The graph, not the Python compiler, executes the cleanup. The visit-marker +technique is classical. This transformer and its reversal application were +produced by Nick Petalas. Apache-2.0. +""" +from pathlib import Path +import hashlib +import importlib.util + +HERE = Path(__file__).resolve().parent +SOURCE = HERE / "inputs/reversal/reverse.py" +MACHINE_SOURCE = HERE / "inputs/reversal/inputs/controller_reference.py" +PINS = { + "inputs/reversal/NOTICE.md": "940493cde2626cb55438be8abda72b9ad971bf059f7c9046591665163e266904", + "inputs/reversal/reverse.py": "4b516d85baf3303db809bc1174394009b1fc71a8f7d17fb6c729ec8bb6aba245", + "inputs/reversal/inputs/controller_reference.py": + "e664a748e6b6797d4b60f60a7a7dd68b59a5608acf56b9c5d8b466f363755f73", +} + + +def load_source(): + for name, digest in PINS.items(): + if hashlib.sha256((HERE / name).read_bytes()).hexdigest() != digest: + raise ValueError("retained source drift: " + name) + spec = importlib.util.spec_from_file_location("retained_reverse", SOURCE) + if spec is None or spec.loader is None: + raise ValueError("missing retained source loader") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def validate(code, alphabet, tapes, private): + if type(tapes) is not int or not 1 <= tapes <= 32 or not 1 <= len(code) <= 10000: + raise ValueError("compiler size outside supported boundary") + if (len(set(alphabet)) != len(alphabet) or not 1 <= len(alphabet) <= 16 + or "_" not in alphabet): + raise ValueError("invalid finite alphabet") + if any(type(t) is not int or not 0 <= t < tapes for t in private): + raise ValueError("invalid private tape") + for instruction in code: + if not isinstance(instruction, (tuple, list)) or not instruction: + raise ValueError("invalid instruction shape") + op, *args = instruction + arities = {"read": 2, "write": 2, "move": 2, "goto": 1, "halt": 0} + if op not in arities or len(args) != arities[op]: + raise ValueError("invalid instruction arity") + if op in ("read", "write", "move"): + if type(args[0]) is not int or not 0 <= args[0] < tapes: + raise ValueError("invalid tape index") + if op == "read": + if not isinstance(args[1], dict) or not set(args[1]).issubset(alphabet): + raise ValueError("invalid read branches") + targets = tuple(args[1].values()) + elif op == "goto": + targets = (args[0],) + elif op == "write" and len(args) == 2 and args[1] in alphabet: + targets = () + elif op == "move" and len(args) == 2 and args[1] in (-1, 1): + targets = () + elif op == "halt" and not args: + targets = () + else: + raise ValueError("unsupported local instruction") + if any(type(pc) is not int or not 0 <= pc < len(code) for pc in targets): + raise ValueError("invalid control target") + if code[-1][0] not in ("read", "goto", "halt"): + raise ValueError("fallthrough outside program") + + +def cleanup(builder, tapes, private, status): + """Retire one interval at a time, retaining its origin until the return.""" + for tape in range(tapes): + tag = tapes + tape + stem = f"{status}_{tape}_" + builder.mark(stem + "left") + builder.op("read", tag, {"_": stem + "begin", "1": stem + "back", + "|": stem + "back"}) + builder.mark(stem + "back") + builder.op("move", tape, -1) + builder.op("move", tag, -1) + builder.op("goto", stem + "left") + builder.mark(stem + "begin") + builder.op("move", tape, 1) + builder.op("move", tag, 1) + builder.mark(stem + "sweep") + builder.op("read", tag, {"1": stem + "erase", "|": stem + "origin", + "_": stem + "end"}) + builder.mark(stem + "erase") + builder.op("write", tag, "_") + builder.op("goto", stem + "cell") + builder.mark(stem + "origin") + builder.op("goto", stem + "cell") + builder.mark(stem + "cell") + if tape in private: + builder.op("write", tape, "_") + builder.op("move", tape, 1) + builder.op("move", tag, 1) + builder.op("goto", stem + "sweep") + builder.mark(stem + "end") + builder.op("move", tape, -1) + builder.op("move", tag, -1) + builder.mark(stem + "return") + builder.op("read", tag, {"_": stem + "return_step", "|": stem + "done"}) + builder.mark(stem + "return_step") + builder.op("move", tape, -1) + builder.op("move", tag, -1) + builder.op("goto", stem + "return") + builder.mark(stem + "done") + builder.op("write", tag, "_") + builder.mark(status + "_halt") + builder.op("halt") + + +def compile_tidy(source, code, alphabet, tapes=13, private=tuple(range(4, 13))): + validate(code, alphabet, tapes, private) + builder = source.Builder() + for tape in range(tapes): + builder.op("write", tapes + tape, "|") + for pc, instruction in enumerate(code): + builder.mark(f"source_{pc}") + op, *args = instruction + if op == "read": + branches = {s: f"source_{target}" for s, target in args[1].items()} + builder.op("read", args[0], {s: branches.get(s, "reject_0_left") + for s in alphabet}) + elif op == "goto": + builder.op("goto", f"source_{args[0]}") + elif op == "halt": + builder.op("goto", "accept_0_left") + elif op == "move": + tape, direction = args + builder.op("move", tape, direction) + builder.op("move", tapes + tape, direction) + builder.op("read", tapes + tape, + {"_": f"new_{pc}", "1": f"source_{pc+1}", + "|": f"source_{pc+1}"}) + builder.mark(f"new_{pc}") + builder.op("write", tapes + tape, "1") + builder.op("goto", f"source_{pc+1}") + else: + builder.op(*instruction) + cleanup(builder, tapes, private, "accept") + cleanup(builder, tapes, private, "reject") + graph, result_alphabet = builder.finish(tuple(dict.fromkeys((*alphabet, "_", "1", "|")))) + halts = {status: builder.labels[status + "_halt"] for status in ("accept", "reject")} + return graph, result_alphabet, halts diff --git a/research/row-reversal-rejection-cleanup/verify.py b/research/row-reversal-rejection-cleanup/verify.py new file mode 100644 index 0000000000..610c09bf99 --- /dev/null +++ b/research/row-reversal-rejection-cleanup/verify.py @@ -0,0 +1,240 @@ +"""Replay the new retirement graph, including rejected-then-valid reuse. + +Produced by Nick Petalas. Apache-2.0. Uses only the standard library. +""" +from pathlib import Path +import hashlib +import importlib.util +import itertools +import json +import sys + +HERE = Path(__file__).resolve().parent +SPEC = importlib.util.spec_from_file_location("tidy_program", HERE / "program.py") +if SPEC is None or SPEC.loader is None: + raise ValueError("missing program loader") +p = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(p) +r = p.load_source() +CODE, ALPHABET = r.compile_reverse() +GRAPH, _, HALTS = p.compile_tidy(r, CODE, ALPHABET) +LIMIT = 2_000_000 + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def packet(descriptors, payload, count=26): + origins = tuple(7 * i - 51 for i in range(count)) + tapes = [r.Tape({o - 20: "1", o + 10000: "|"}, o) for o in origins] + for tape, word in enumerate((*descriptors, payload)): + tapes[tape].cells.update({origins[tape] + j: s for j, s in enumerate(word) + if s != "_"}) + return tapes, origins + + +def execute(code, tapes, budget=LIMIT): + cpu = r.Machine(code, tapes) + for tape in tapes: + tape.local_low = tape.local_high = tape.head + rejected, last_pc = False, None + for _ in range(budget): + last_pc = cpu.pc + instruction = code[cpu.pc] + try: + cpu.step() + except ValueError as error: + require(str(error) == "invalid scanned symbol", "unexpected machine error") + rejected = True + break + if instruction[0] == "move": + tape = tapes[instruction[1]] + tape.local_low = min(tape.local_low, tape.head) + tape.local_high = max(tape.local_high, tape.head) + if cpu.halted: + break + else: + raise ValueError("bounded replay exhausted") + return cpu.steps, last_pc, rejected + + +def check_run(descriptors, payload, expected, *, tapes=None, origins=None, graph=GRAPH): + if tapes is None: + tapes, origins = packet(descriptors, payload) + before = [dict(t.cells) for t in tapes] + owners = tuple(map(id, tapes)) + shadow = [r.Tape(dict(t.cells), t.head) for t in tapes[:13]] + old_steps, _, old_rejected = execute(CODE, shadow) + steps, last_pc, invalid = execute(graph, tapes) + require(not invalid, "new graph fell through a symbol branch") + status = "reject" if old_rejected else "accept" + require(last_pc == HALTS[status], "wrong terminal status") + require(tuple(map(id, tapes)) == owners, "replaced physical tape owner") + require(all(t.head == o for t, o in zip(tapes, origins)), "head was not restored") + for tape in range(3): + require(tapes[tape].cells == before[tape], "descriptor was modified") + for tape in range(4, 26): + require(tapes[tape].cells == before[tape], "private or monitor was not erased") + want = dict(before[3]) + if expected is not None: + for j, symbol in enumerate(expected): + want[origins[3] + j] = symbol + require(tapes[3].cells == want, "public data or exterior changed incorrectly") + span = sum(t.local_high - t.local_low + 1 for t in shadow) + require(steps <= 5 * old_steps + 16 * span + 6 * 13, "simulation time bound") + require(steps <= 21 * old_steps + 22 * 13, "linear time corollary") + for i in range(13): + require(tapes[i].local_low >= shadow[i].local_low - 1, "left cleanup excursion") + require(tapes[i].local_high <= shadow[i].local_high + 1, "right cleanup excursion") + return {"status": status, "steps": steps, "source_steps": old_steps, + "source_span": span}, tapes, origins + + +def successful_fixtures(): + rows, calls, transitions = [], 0, 0 + for prefix, count, width in itertools.product(range(1, 5), repeat=3): + volume = prefix * count * width + if volume > 6: + continue + for bits in itertools.product("01", repeat=volume): + word = "".join(bits) + expected = "".join(word[(group * count + row) * width + j] + for group in range(prefix) + for row in reversed(range(count)) + for j in range(width)) + evidence, _, _ = check_run(tuple(bin(n)[2:] for n in (prefix, count, width)), + word, expected) + require(evidence["status"] == "accept", "valid packet rejected") + rows.append(evidence) + calls += 1 + transitions += evidence["steps"] + return {"calls": calls, "transitions": transitions, + "evidence_sha256": digest(rows)} + + +def malformed_fixtures(): + cases = [] + for tape in range(3): + for bad in ("", "0", "|", "1|", "10|", "01"): + descriptors = ["10", "11", "10"] + descriptors[tape] = bad + cases.append((tuple(descriptors), "010101010101")) + for payload in ("", "0", "01010101010", "0101010101010", + "|10101010101", "01010|010101", "01010101010|"): + cases.append((("10", "11", "10"), payload)) + records = [] + for descriptors, payload in cases: + evidence, _, _ = check_run(descriptors, payload, None) + require(evidence["status"] == "reject", "malformed packet accepted") + records.append(evidence) + return {"calls": len(records), "transitions": sum(x["steps"] for x in records), + "evidence_sha256": digest(records)} + + +def reuse_fixture(): + evidence, tapes, origins = check_run(("100", "11", "10"), "0101", None) + require(evidence["status"] == "reject", "reuse setup must reject") + prior_history = sum(t.high - t.low + 1 for t in tapes) + # A caller supplies the next public packet. No private cell or head is reset. + for i, word in enumerate(("1", "10", "10", "0011")): + for j in range(32): + tapes[i].cells.pop(origins[i] + j, None) + tapes[i].cells.update({origins[i] + j: s for j, s in enumerate(word)}) + after, _, _ = check_run(("1", "10", "10"), "0011", "1100", + tapes=tapes, origins=origins) + require(after["status"] == "accept", "valid call after rejection failed") + require(sum(t.high - t.low + 1 for t in tapes) >= prior_history, + "cleanup reset retained history") + return {"first": evidence, "second": after, "prior_history": prior_history, + "final_history": sum(t.high - t.low + 1 for t in tapes)} + + +def generic_fixtures(): + records = [] + for count in range(1, 5): + for direction in (-1, 1): + for reject in (False, True): + code = [] + for tape in range(count): + code.extend((("move", tape, direction), ("write", tape, "1"), + ("move", tape, direction), ("write", tape, "0"))) + code.extend((("read", 0, {"1" if reject else "0": len(code) + 1}), + ("halt",))) + private = tuple(range(1, count)) + graph, _, halts = p.compile_tidy(r, tuple(code), ALPHABET, count, private) + tapes, origins = packet((), "", 2 * count) + shadow = [r.Tape(dict(t.cells), t.head) for t in tapes[:count]] + old, _, old_reject = execute(tuple(code), shadow) + steps, pc, invalid = execute(graph, tapes) + require(not invalid and old_reject == reject, "generic terminal mismatch") + require(pc == halts["reject" if reject else "accept"], "generic halt") + require(tapes[0].cells == shadow[0].cells, "public final state changed") + for i in range(1, 2 * count): + require(tapes[i].cells == {origins[i]-20: "1", origins[i]+10000: "|"}, + "generic private cleanup") + require(all(t.head == o for t, o in zip(tapes, origins)), "generic head") + span = sum(t.high-t.low+1 for t in shadow) + require(steps <= 5*old + 16*span + 6*count, "generic time bound") + records.append({"tapes": count, "direction": direction, + "rejected": reject, "steps": steps}) + return {"calls": len(records), "evidence_sha256": digest(records)} + + +def controls(): + caught = [] + # These mutations target the added contract, not predecessor mathematics. + for name, message, change in ( + ("private_erasure", "private or monitor was not erased", lambda i, op: ("goto", i + 1) + if op == ("write", 4, "_") and i > HALTS["accept"] else op), + ("origin_retirement", "private or monitor was not erased", lambda i, op: ("goto", i + 1) + if op == ("write", 13, "_") and i > HALTS["accept"] + and GRAPH[i+1][0:2] == ("read", 14) else op), + ): + mutant = tuple(change(i, op) for i, op in enumerate(GRAPH)) + try: + check_run(("10", "11", "10"), "01010", None, graph=mutant) + except ValueError as error: + require(str(error) == message, "mutation failed for an unexpected reason") + caught.append(name) + for name, code in ( + ("bad_jump", (("goto", 4),)), + ("long_move", (("move", 0, 2), ("halt",))), + ("unknown_write", (("write", 0, "x"), ("halt",))), + ("fallthrough", (("write", 0, "1"),)), + ("missing_operand", (("read",),)), + ("nonlocal_opcode", (("callback",),)), + ): + try: + p.compile_tidy(r, code, ALPHABET) + except ValueError: + caught.append(name) + require(len(caught) == 8, "a control survived") + return caught + + +def digest(value): + return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest() + + +def main(): + if sys.argv[1:] not in ([], ["--record"]): + raise ValueError("usage: verify.py [--record]") + result = {"status": "PASS_ROW_REVERSAL_REJECTION_CLEANUP", "tapes": 26, + "locations": len(GRAPH), "source_locations": len(CODE), + "success": successful_fixtures(), "rejection": malformed_fixtures(), + "reuse": reuse_fixture(), "generic": generic_fixtures(), + "controls": controls(), "pins": p.PINS} + result["bindings"] = {name: hashlib.sha256((HERE/name).read_bytes()).hexdigest() + for name in ("program.py", "verify.py", "PROOF.md", "SOURCES.json")} + receipt = HERE / "RESULT.json" + if sys.argv[1:]: + receipt.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n") + else: + require(json.loads(receipt.read_text()) == result, "receipt differs") + print(json.dumps(result, sort_keys=True)) + + +if __name__ == "__main__": + main()