From b4fcc9d64971fdabd0b1d82cfb749d8aac920437 Mon Sep 17 00:00:00 2001
From: Jerry Jiaheng Chen <80299683+CubeJerry@users.noreply.github.com>
Date: Fri, 13 Nov 2026 19:33:17 +1100
Subject: [PATCH] Lower complete compiler checkpoints to literal fixed-tape
permanent-home routing
---
.../CHECKSUMS.sha256 | 29 +
.../FREEZE.json | 86 ++
.../NOTICE.md | 35 +
.../OVERLAP.json | 99 ++
.../PR-TITLE.txt | 1 +
.../compiler-permanent-home-dispatch/PR.md | 56 +
.../compiler-permanent-home-dispatch/PROOF.md | 365 +++++
.../README.md | 116 ++
.../SOURCES.json | 69 +
.../VALIDATION.json | 1311 +++++++++++++++++
.../compiler-permanent-home-dispatch/emit.py | 181 +++
.../independent.py | 132 ++
.../inputs/inputs/groups.py | 286 ++++
.../source_index/inputs/pascal_codec.py | 222 +++
.../inputs/source_index/source_index.py | 205 +++
.../inputs/inputs/library.py | 305 ++++
.../inputs/leaf_index.py | 255 ++++
.../inputs/literal_oracle.py | 172 +++
.../reference/FINITE-PRECOMPILATION.md | 313 ++++
.../reference/PROOF.md | 275 ++++
.../review/AUTHOR-REPLAY.txt | 1 +
.../review/C-FIXTURE-RESULT.txt | 2 +
.../review/C-REVIEW.md | 49 +
.../review/C-check_fixture.py | 93 ++
.../review/REMOTE-SOURCE-BINDING.json | 53 +
.../review/ROOT-RESULT.json | 48 +
.../review/ROOT-REVIEW.md | 49 +
.../review/check_physical.py | 96 ++
.../tape_graph.py | 281 ++++
.../verify.py | 235 +++
30 files changed, 5420 insertions(+)
create mode 100644 research/compiler-permanent-home-dispatch/CHECKSUMS.sha256
create mode 100644 research/compiler-permanent-home-dispatch/FREEZE.json
create mode 100644 research/compiler-permanent-home-dispatch/NOTICE.md
create mode 100644 research/compiler-permanent-home-dispatch/OVERLAP.json
create mode 100644 research/compiler-permanent-home-dispatch/PR-TITLE.txt
create mode 100644 research/compiler-permanent-home-dispatch/PR.md
create mode 100644 research/compiler-permanent-home-dispatch/PROOF.md
create mode 100644 research/compiler-permanent-home-dispatch/README.md
create mode 100644 research/compiler-permanent-home-dispatch/SOURCES.json
create mode 100644 research/compiler-permanent-home-dispatch/VALIDATION.json
create mode 100644 research/compiler-permanent-home-dispatch/emit.py
create mode 100644 research/compiler-permanent-home-dispatch/independent.py
create mode 100644 research/compiler-permanent-home-dispatch/inputs/inputs/groups.py
create mode 100644 research/compiler-permanent-home-dispatch/inputs/inputs/inputs/source_index/inputs/pascal_codec.py
create mode 100644 research/compiler-permanent-home-dispatch/inputs/inputs/inputs/source_index/source_index.py
create mode 100644 research/compiler-permanent-home-dispatch/inputs/inputs/library.py
create mode 100644 research/compiler-permanent-home-dispatch/inputs/leaf_index.py
create mode 100644 research/compiler-permanent-home-dispatch/inputs/literal_oracle.py
create mode 100644 research/compiler-permanent-home-dispatch/reference/FINITE-PRECOMPILATION.md
create mode 100644 research/compiler-permanent-home-dispatch/reference/PROOF.md
create mode 100644 research/compiler-permanent-home-dispatch/review/AUTHOR-REPLAY.txt
create mode 100644 research/compiler-permanent-home-dispatch/review/C-FIXTURE-RESULT.txt
create mode 100644 research/compiler-permanent-home-dispatch/review/C-REVIEW.md
create mode 100644 research/compiler-permanent-home-dispatch/review/C-check_fixture.py
create mode 100644 research/compiler-permanent-home-dispatch/review/REMOTE-SOURCE-BINDING.json
create mode 100644 research/compiler-permanent-home-dispatch/review/ROOT-RESULT.json
create mode 100644 research/compiler-permanent-home-dispatch/review/ROOT-REVIEW.md
create mode 100644 research/compiler-permanent-home-dispatch/review/check_physical.py
create mode 100644 research/compiler-permanent-home-dispatch/tape_graph.py
create mode 100644 research/compiler-permanent-home-dispatch/verify.py
diff --git a/research/compiler-permanent-home-dispatch/CHECKSUMS.sha256 b/research/compiler-permanent-home-dispatch/CHECKSUMS.sha256
new file mode 100644
index 0000000000..b28b1c513f
--- /dev/null
+++ b/research/compiler-permanent-home-dispatch/CHECKSUMS.sha256
@@ -0,0 +1,29 @@
+5167db30b84c7e780103259c05ec31c415b23e5dc0de0cb0ee52b822cff09e3d FREEZE.json
+9d39f6596a51aa8717908431017a51e69c3091145b03157087978b8c84073a94 NOTICE.md
+25fcfd1509efda5d2a4629147f987ef029d4eb5371f68fbde37dcbd85f31daa7 OVERLAP.json
+d19f62828bc4493664b40322dae1ba19bfc7bf74ed772fb4fad67392e25b1e7d PR-TITLE.txt
+8438e09f0b120b5ee87dfe6ee3249d7395bd5fdbe12689a9c9ef98d9ad42d782 PR.md
+63f29469fd49751f267db6e26e3494e2bea567fa909d5ebfa2ec9a5924674a4e PROOF.md
+7d8120a6c06d53ffc9054cd8fe38859b36ea95549cf8ed965ca83d98c11607bb README.md
+ea1dca983da5de89dc8309f1446d67ebed52467f3d6aff339690479940a55ba5 SOURCES.json
+90c9810f14bd5fe86f3cbab07519b9d7b153637b7d7984bdc6332fb91797cd5b VALIDATION.json
+762c6c3e094e300bbe67de80597c3557413d4047c040ee5feaa4b925873c9a58 emit.py
+b15e82fa00c6b3e029efa382861fac0282edd76a2fe4549c710ffd72129d725f independent.py
+871b166c174958bb467952bebe9a2b776a0582f0c427b7dea9a94a128edad171 inputs/inputs/groups.py
+cec2c8b5e153a264127e8301ed59591fe97c9a46078ff2343b3784d177c6984d inputs/inputs/inputs/source_index/inputs/pascal_codec.py
+e978025591b06770026b9879f1e5b10827424f410794fb2b1e1f10a720f49176 inputs/inputs/inputs/source_index/source_index.py
+06e3b44704048461de0ff0ab55fe158b95df412688324b88fd3d81b929ef0d92 inputs/inputs/library.py
+fed9b8fe71f69d02bd1dc796f13d4311b8460d24860c246ce246997d5ca96724 inputs/leaf_index.py
+4183adc3bb76dff7a3e581d1eb3e830f3258cb423bd833021f7419c69602a6d9 inputs/literal_oracle.py
+4cb32f6b8e388ecf6ed41b5bbdeeb4539cb40c8424f194974afea58f7e0921e8 reference/FINITE-PRECOMPILATION.md
+e394711ee942e0779e041d0cc04adddc43ad10f2094d72fcd8bea53e1d8154b4 reference/PROOF.md
+6ffb81e2f29a5c53faf1fd31f6f7357740995200b2e195da49b4fe49f073d831 review/AUTHOR-REPLAY.txt
+a3e192d0a97bbe148c95428155a8c0a02f07b1a460e711efd7f4c6dbd7ab6751 review/C-FIXTURE-RESULT.txt
+6ea950f6efe53ba0ac8a2114385dcbfcaccf07bd31ee89dc53e332fd7fc9d31b review/C-REVIEW.md
+9380f159a70242e59d1941d144d99bd48f6a79c14a91b10b1be7dd19a5649678 review/C-check_fixture.py
+eb05cedccad7291fb94f4b063502a947c2996f57031db0aae0fd21f9ef09a831 review/REMOTE-SOURCE-BINDING.json
+450f381d08c3ee3e152f15f00891e162401bfd4bd7878f7b33c381ca600d002a review/ROOT-RESULT.json
+85cb819915d363e235df49a62f52f5634392c263cbc1d00df43d6c317f053ab6 review/ROOT-REVIEW.md
+d6cd5dca77ecb9daadb4664105b2a9df62908302ae4c1efeebe168b72f744ebb review/check_physical.py
+7d3cee3e79ba5fe410e1a6b5f4cf6a2fbe5e274f838b798cd8860344ff258b54 tape_graph.py
+e671546968ae0d334a51e3a292fe8019ab71917267077860e44356f74a22c75d verify.py
diff --git a/research/compiler-permanent-home-dispatch/FREEZE.json b/research/compiler-permanent-home-dispatch/FREEZE.json
new file mode 100644
index 0000000000..82395014c0
--- /dev/null
+++ b/research/compiler-permanent-home-dispatch/FREEZE.json
@@ -0,0 +1,86 @@
+{
+ "status": "verified-publication-snapshot",
+ "time_utc": "2026-11-13T08:21:35.923875+00:00",
+ "base": "e54523517d0f03e58352e647c403a5af3e525a57",
+ "python": "3.12.14 (main, Aug 25 2026, 14:00:49) [Clang 22.1.3 ]",
+ "commands": [
+ {
+ "argv": [
+ "python",
+ "-I",
+ "-W",
+ "error",
+ "-B",
+ "research/compiler-permanent-home-dispatch/verify.py"
+ ],
+ "exit_code": 0,
+ "marker": "PASS_COMPILER_PERMANENT_HOME_DISPATCH 33 cases; 10 rejecting controls"
+ },
+ {
+ "argv": [
+ "python",
+ "-I",
+ "-O",
+ "-W",
+ "error",
+ "-B",
+ "research/compiler-permanent-home-dispatch/verify.py"
+ ],
+ "exit_code": 0,
+ "marker": "PASS_COMPILER_PERMANENT_HOME_DISPATCH 33 cases; 10 rejecting controls"
+ }
+ ],
+ "scientific_summary": {
+ "cases": 33,
+ "events": 1380,
+ "inspected_service_returns": 1092,
+ "fixture_steps": 170556,
+ "negative_controls": 10,
+ "long_field": {
+ "roles": [
+ [
+ "x",
+ 2
+ ],
+ [
+ "y",
+ 3
+ ]
+ ],
+ "rounds": [
+ [
+ 1,
+ "x"
+ ],
+ [
+ 1,
+ "bank"
+ ]
+ ],
+ "ambient": 3,
+ "rank": 6,
+ "F": 257,
+ "B": 4,
+ "K": 8,
+ "events": 91,
+ "services": 73,
+ "leaves": 9,
+ "states": 2257,
+ "steps": 726850,
+ "audited_boundaries": 73,
+ "initial_reserved": 1037,
+ "historical_backing": 2843,
+ "events_sha256": "912e5a0bdaedc0bdc7304a25ffd916a7e988431b36017e251e60ebb0609d6d6d",
+ "values_sha256": "6cc42897160eee40620ab5f1765c56b6be5d5ffa2eda9159bb49e5a9127b52e8"
+ }
+ },
+ "scope": "source-codec/native-checkpoint physical lowering under typed native, adapter, format and uniform primitive premises; no selected full word or new kappa",
+ "external_review": "Parent root-work/compiler-review; retained separately by parent, not a claim that this worker ran its independent program.",
+ "root_review": "review/ROOT-REVIEW.md",
+ "root_checks": [
+ "PASS_ROOT_COMPILER_PHYSICAL_REVIEW",
+ "PASS_COMPILER_DISPATCH_FIXTURE",
+ "PASS_REMOTE_COMPILER_SOURCE_BINDING"
+ ],
+ "post_freeze_change": "Explicit compatible-primitive ABI premise in PROOF; portable independent review scripts, receipts and publication documentation; implementation and scientific input bytes unchanged."
+}
diff --git a/research/compiler-permanent-home-dispatch/NOTICE.md b/research/compiler-permanent-home-dispatch/NOTICE.md
new file mode 100644
index 0000000000..23bbd0b1c8
--- /dev/null
+++ b/research/compiler-permanent-home-dispatch/NOTICE.md
@@ -0,0 +1,35 @@
+# Attribution and scope
+
+New material is Apache-2.0, prepared for CubeJerry with substantial OpenAI
+Codex assistance. The separate matched-slot oracle is code-disjoint,
+source-aware corroboration using shared declared fixture/library inputs.
+No independent human or proof-kernel acceptance is asserted.
+
+Jerry Chen / CubeJerry supplied the unchanged #7423/#7348/#7347/#7346
+owner/port/source codecs and #7345/#7424 evaluated-library context. Original
+headers remain unchanged; exact commits, blobs and hashes are in SOURCES.json.
+
+Theorem 1G's mixed integer flow is credited to Jacob Alan Sussman (#4268), and
+the finite native precompilation to zxv (#4359). Chronological batching is
+Mihir Srivastava's #4507/#5071; codyw912's #4638 is a quantitative predecessor.
+Matarener / Mark's #4691 supplies live-role nesting. CubeJerry's #6878 and its
+JoyboyBrian #5480, Matarener #5445, DLamdata #6115 and retained native/compiler
+lineage supplies the occurrence-layout/node-cost bridge. These are credited
+premises, not newly audited theorems.
+
+Nick Petalas's #7464 improves plateau width divisors. Jose Manuel /
+jmbarrancoml's #3385 implements an earlier physical whole-call complex
+controller; #2989 audits a different symbolic compiler correspondence.
+JoyboyBrian's #5186 supplies a sequential-gather physical A5 caller. Nick
+Petalas's #6264 emits a generic packed TM-to-RAM backend. CubeJerry's #6879
+addresses retained ordinary BIT history. None is replayed or claimed anew.
+
+The selected #7000 application review and its retained CubeJerry,
+DreamingOfClouds, Ali Romman, zxv, Jacob Alan Sussman, frame/compiler/native
+and precision contributors supply context. Its dispatcher question is not a
+primitive implementation imported by this package.
+
+Classical copy/scan machines and finite-control unrolling are not claimed as
+new algorithms. The delta is the actual source-codec/checkpoint integration,
+permanent-home transition construction, explicit full-volume/history/emission
+ledger and its bounded evidence. All five framework assumptions remain.
diff --git a/research/compiler-permanent-home-dispatch/OVERLAP.json b/research/compiler-permanent-home-dispatch/OVERLAP.json
new file mode 100644
index 0000000000..2891d68efe
--- /dev/null
+++ b/research/compiler-permanent-home-dispatch/OVERLAP.json
@@ -0,0 +1,99 @@
+{
+ "date": "2026-11-13",
+ "canonical": "e54523517d0f03e58352e647c403a5af3e525a57",
+ "scope": "Bounded public metadata audit; no general novelty or predecessor-audit claim.",
+ "queries": [
+ {
+ "query": "repo:CrocSwap/integer-mult-bounds dispatcher is:pr",
+ "total_count": 62,
+ "incomplete_results": false,
+ "returned": 62
+ },
+ {
+ "query": "repo:CrocSwap/integer-mult-bounds gather tape is:pr",
+ "total_count": 72,
+ "incomplete_results": false,
+ "returned": 72
+ }
+ ],
+ "predecessors": [
+ {
+ "number": 3385,
+ "title": "Implement whole-call physical complex controller and root return",
+ "url": "https://github.com/CrocSwap/integer-mult-bounds/pull/3385",
+ "body_read": true
+ },
+ {
+ "number": 2989,
+ "title": "Independently audit selected compiler ordering and owner guards",
+ "url": "https://github.com/CrocSwap/integer-mult-bounds/pull/2989",
+ "body_read": true
+ },
+ {
+ "number": 6264,
+ "title": "Emit a complete packed TM backend with exact simulation costs (no κ)",
+ "url": "https://github.com/CrocSwap/integer-mult-bounds/pull/6264",
+ "body_read": true
+ },
+ {
+ "number": 5186,
+ "title": "Execute the complete A5 projector caller with fixed physical tapes and paid routing",
+ "url": "https://github.com/CrocSwap/integer-mult-bounds/pull/5186",
+ "body_read": true
+ },
+ {
+ "number": 6878,
+ "title": "Preserve node costs through compiler occurrence layouts (no new κ)",
+ "url": "https://github.com/CrocSwap/integer-mult-bounds/pull/6878",
+ "body_read": true
+ },
+ {
+ "number": 6879,
+ "title": "Prove ordinary BIT retained-space bounds with reusable origins (no new κ)",
+ "url": "https://github.com/CrocSwap/integer-mult-bounds/pull/6879",
+ "body_read": true
+ },
+ {
+ "number": 7153,
+ "title": "Specialize the encoded BIT coefficient evaluator to every fixed dimension and bound its retained continuation backing",
+ "url": "https://github.com/CrocSwap/integer-mult-bounds/pull/7153",
+ "body_read": true
+ },
+ {
+ "number": 6738,
+ "title": "Independently execute the recursive core and audit full frame restoration",
+ "url": "https://github.com/CrocSwap/integer-mult-bounds/pull/6738",
+ "body_read": true
+ },
+ {
+ "number": 6899,
+ "title": "Connect actual Core interiors to the global physical caller (no new κ)",
+ "url": "https://github.com/CrocSwap/integer-mult-bounds/pull/6899",
+ "body_read": true
+ },
+ {
+ "number": 3935,
+ "title": "Implement the complete physical Gaussian tensor transform",
+ "url": "https://github.com/CrocSwap/integer-mult-bounds/pull/3935",
+ "body_read": true
+ }
+ ],
+ "newer_pins": [
+ {
+ "number": 7423,
+ "head": "81f0b0b9a920bd1c9da583cbc3612efd5e75ea94",
+ "delta": "Full native checkpoint stream and physical gather/return remain excluded."
+ },
+ {
+ "number": 7424,
+ "head": "d622d8c62defa9defeb95741e88b33a120044866",
+ "delta": "Ambient/evaluated-width library; no physical compiler."
+ },
+ {
+ "number": 7464,
+ "head": "75aa393e808d030930879b87815e0abb7bb5742d",
+ "delta": "Improved plateau width divisor; no dispatcher."
+ }
+ ],
+ "discussion_coverage": "Parent read #1163/#1166 and shared live task coordination; this worker posted no public claim. Closed arbitrary diffs, unpublished work and literature-wide priority are excluded."
+}
diff --git a/research/compiler-permanent-home-dispatch/PR-TITLE.txt b/research/compiler-permanent-home-dispatch/PR-TITLE.txt
new file mode 100644
index 0000000000..2fc28c8600
--- /dev/null
+++ b/research/compiler-permanent-home-dispatch/PR-TITLE.txt
@@ -0,0 +1 @@
+Lower the complete compiler checkpoint stream to a fixed-tape dispatcher with permanent owned homes
diff --git a/research/compiler-permanent-home-dispatch/PR.md b/research/compiler-permanent-home-dispatch/PR.md
new file mode 100644
index 0000000000..2a92d410d1
--- /dev/null
+++ b/research/compiler-permanent-home-dispatch/PR.md
@@ -0,0 +1,56 @@
+# Execute compiler checkpoints through permanent physical homes (no κ)
+
+The current chronological source/leaf codecs preserve field identities but
+leave the native checkpoint stream and payload gather/return open. This package
+connects the unchanged #7423/#7348/#7347/#7346 resolver chain to complete local
+native segments, whole source complements, separate ordered exits, adapter
+returns and per-instance owned lifetimes, then emits literal fixed-tape scans.
+
+For R services, K total source/owned homes, B productive arrays and full root
+extent F, dispatcher overhead is at most `16(R+1)(K+b+1)(F+2)`, plus every
+primitive cost. All owned homes remain in physical backing after release.
+Arbitrary entry history is retained through an increment bound. Productive
+normalization remains V/B. R,K and finite native columns are frozen before
+varying d,f,p,F; varying format metadata is handled by charged runtime services.
+The graph has O(RK) states and can be quadratic in the logical event count.
+
+The proof assumes actual native/adapter identities, typed initialization and
+uniform complete-field primitive graphs. Raw zero homes are storage capacity;
+structured fields need explicit charged header/format initialization. No
+selected semantic field is inferred from zero bits.
+
+## Validation
+
+```sh
+python3 -I -W error -B research/compiler-permanent-home-dispatch/verify.py
+python3 -I -O -W error -B research/compiler-permanent-home-dispatch/verify.py
+```
+
+Both modes check 33 fixtures, 1,380 complete events and 1,092 physical service
+returns against a separate matched-slot recursion and the frozen leaf index.
+Actual transitions prepare private homes, gather, execute fixture primitives,
+return to the same owner and erase all work. A fixed 2,257-state graph runs at
+F=1,3,8,257; the long run takes 726,850 steps and retains 2,843 cells. Same-owner
+reuse, actual head-visit history, quadratic scan scaling and ten rejecting
+controls pass. The fixtures are synthetic binary primitives, not selected
+rational/Clifford numerical implementations.
+
+Canonical base e54523517d0f03e58352e647c403a5af3e525a57; all five selected
+assumptions and κ=.00363005817 remain. Actual selected manifest/1920-product
+word, real primitive graphs, precision/stock and analytic recovery remain open.
+No shared files, predecessors or selected records are edited.
+
+Credit the existing compiler/batching/live-role/layout work #4359/#4268,
+#4507/#5071, #4691 and #6878, and CubeJerry's #7345–#7348/#7423/#7424.
+#7464 and the earlier physical caller/backend precedents are complementary;
+NOTICE.md preserves their attribution. No first-dispatcher claim is made.
+Open next questions: actual native catalogue binding, typed primitive ABI
+composition with complete bills, and optional reduction of finite constants.
+Prepared with substantial OpenAI Codex assistance; no human/kernel acceptance.
+
+Independent review: a separate sparse-tape interpreter/exact-integer oracle
+passed fresh traces with all head visits and retained history checked. A
+second proof review requires the primitive origin/guard ABI stated in the
+final proof; different native interfaces need a paid adapter. See review/.
+
+Credit: @CubeJerry and the originating authors named in NOTICE.md.
diff --git a/research/compiler-permanent-home-dispatch/PROOF.md b/research/compiler-permanent-home-dispatch/PROOF.md
new file mode 100644
index 0000000000..7719ddc990
--- /dev/null
+++ b/research/compiler-permanent-home-dispatch/PROOF.md
@@ -0,0 +1,365 @@
+# Source-indexed compiler expansion and permanent physical homes
+
+Prepared for CubeJerry with substantial OpenAI Codex assistance. Apache-2.0.
+Canonical context: `e54523517d0f03e58352e647c403a5af3e525a57`, selected
+conditional κ = `.00363005817`. Scoped constructive bridge; no new κ.
+
+## 1. Exact gap and predecessor boundary
+
+FINITE-PRECOMPILATION sections 3–6 already give integer Pascal matching,
+integral complements and separate chronological exits, per-instance owned
+banks, completed children and a prose finite-program/parking argument. #4691
+establishes live-role nesting; #6878 gives complete occurrence layouts and a
+node-cost substitution. Those are credited premises, not results claimed here.
+
+#7423 supplies the exact chronological rank-one leaf projection and persistent
+source/owned identity resolver. Its conclusion explicitly excludes the full
+scalar/phase/adapter stream, payload gather/return and physical dispatcher.
+An owner name alone supplies no array access. The addition here is a direct
+source-codec-driven **native checkpoint expansion**, followed by an explicit
+constant-tape physical lowering, including owned-home preparation and full
+historical backing. Earlier physical callers #3385/#5186 and emitted generic
+backend #6264 are precedents; no first-dispatcher claim is made.
+
+## 2. Inputs, quantifiers and claim
+
+Fix the following before input dimension d, tensor multiplicity f, precision
+p or complete field extent F varies.
+
+1. A separated named rule, actual ordered paid sites, disjoint owned bank
+ names, ambient A at least the greatest target rank, and compiler rank N.
+2. Evaluated positive library rows `(a_n,B_n,P_n)`, `1<=n<=N`, satisfying
+ #7423's actual complement and individual-exit recurrences. For `n self.groups.rank*previous
+
+ def _local(self, state):
+ if not self.fresh(state):
+ return 0
+ h, rho, _ = state
+ words = self.groups.products[self.groups.index.height-h]
+ count = 0
+ for rank, weight in zip(self.groups.index.types, self.groups.index.weights):
+ divisor = rho*rank
+ if (self.groups.rule.ambient*self.rank <= self.groups.rank*rank
+ and self.rank % divisor == 0):
+ count += weight*words.get(self.rank//divisor)
+ return count
+
+ def blocks(self, state):
+ if not self.fresh(state):
+ return
+ h, rho, _ = state
+ for point, column, units in self.groups.index.point_data[self.groups.index.height-h]:
+ product = rho*column
+ if self.rank % product:
+ continue
+ role_rank = self.rank//product
+ i = bisect_left(self.groups.index.types, role_rank)
+ if (i < len(self.groups.index.types) and self.groups.index.types[i] == role_rank
+ and self.groups.rule.ambient*product <= self.groups.rank):
+ yield point, column, units, self.groups.index.weights[i], role_rank
+
+ def roles(self, rank):
+ return tuple(name for name, value in self.groups.rule.roles if value == rank)
+
+ def rank_source(self, unit, role):
+ self.groups.index.flow.validate_unit(unit)
+ C.require(self.groups.job_rank(unit, role) == self.rank, 'true source-rank mismatch')
+ state, offset = (0, 1, 0), 0
+ for chosen in unit.path:
+ h, rho, _ = state
+ offset += self.local[state]
+ for rank, _ in self.groups.rule.rounds[:chosen]:
+ offset += self.total[h+1, rho*rank, rank]
+ rank = self.groups.rule.rounds[chosen][0]
+ state = (h+1, rho*rank, rank)
+ for point, _, units, weight, rank in self.blocks(state):
+ if point < unit.point:
+ offset += units*weight
+ elif point == unit.point:
+ return offset+unit.ordinal*weight+self.roles(rank).index(role)
+ else:
+ break
+ raise ValueError('not a fresh source of this rank')
+
+ def unrank_source(self, ordinal):
+ C.natural(ordinal, 'rank-bucket ordinal')
+ C.require(ordinal < self.size, 'rank-bucket ordinal range')
+ state, path = (0, 1, 0), ()
+ while True:
+ if ordinal < self.local[state]:
+ for point, _, units, weight, rank in self.blocks(state):
+ if ordinal < units*weight:
+ unit, role = divmod(ordinal, weight)
+ return C.Unit(path, point, unit), self.roles(rank)[role]
+ ordinal -= units*weight
+ raise ValueError('local rank-bucket count disagreement')
+ ordinal -= self.local[state]
+ h, rho, _ = state
+ C.require(h < self.groups.index.height, 'rank-bucket has no further child')
+ for site, (rank, _) in enumerate(self.groups.rule.rounds):
+ child = h+1, rho*rank, rank
+ if ordinal < self.total[child]:
+ state, path = child, path+(site,)
+ break
+ ordinal -= self.total[child]
+ else:
+ raise ValueError('rank-bucket subtree count disagreement')
+
+
+class SourceGroups:
+ """All true source-rank counts, with at most one retained bucket DP."""
+ def __init__(self, rule, rank, replicas=1, namespace='flow'):
+ self.rule, self.rank = rule, rank
+ self.index = I.SourceIndex(rule, rank, replicas, namespace)
+ self.states = tuple(self.index.total)
+ self.products = [ProductCounts(((1, 1),))]
+ for _ in range(self.index.height+1):
+ self.products.append(ProductCounts(
+ (product*k, count*weight)
+ for product, count in self.products[-1].items()
+ for k, weight in zip(self.index.types, self.index.weights)))
+ candidates = []
+ previous = None
+ for h, rho, _ in self.states:
+ if (h, rho) == previous:
+ continue
+ previous = h, rho
+ for product in self.products[self.index.height-h+1].keys:
+ source_rank = rho*product
+ if rule.ambient*source_rank > rank and source_rank <= rank:
+ candidates.append(source_rank)
+ candidates = I.sorted_unique(candidates)
+ self.candidate_count = len(candidates)
+ self.ranks, self.counts = [], []
+ for source_rank in candidates:
+ bucket = _RankBucket(self, source_rank)
+ if bucket.size:
+ self.ranks.append(source_rank)
+ self.counts.append(bucket.size)
+ self.ranks, self.counts = tuple(self.ranks), tuple(self.counts)
+ C.require(sum(self.counts) == self.index.size, 'true-rank buckets partition sources')
+ self._active = None
+
+ def _position(self, source_rank):
+ C.natural(source_rank, 'source rank')
+ at = bisect_left(self.ranks, source_rank)
+ C.require(at < len(self.ranks) and self.ranks[at] == source_rank,
+ 'source rank absent from catalogue')
+ return at
+
+ def count(self, source_rank):
+ return self.counts[self._position(source_rank)]
+
+ def _prepare(self, source_rank):
+ self._position(source_rank)
+ if self._active is None or self._active.rank != source_rank:
+ self._active = _RankBucket(self, source_rank)
+ return self._active
+
+ def job_rank(self, unit, role):
+ i = self.rule.type_of(role)
+ return self.index.flow.dilation(unit.path)*C.column(self.rule, unit.point)*self.index.types[i]
+
+ def rank_source(self, source_rank, unit, role):
+ return self._prepare(source_rank).rank_source(unit, role)
+
+ def unrank_source(self, source_rank, ordinal):
+ return self._prepare(source_rank).unrank_source(ordinal)
+
+
+@dataclass(frozen=True)
+class ComplementPort:
+ namespace: str
+ source_rank: int
+ invocation: int
+ slot: int
+
+
+@dataclass(frozen=True)
+class NoComplement:
+ namespace: str
+ source_rank: int
+ ordinal: int
+
+
+class ComplementRouter:
+ """Logical child-port bijection for the positive complement phase only.
+
+ library lists exactly the needed positive (complement rank, program width)
+ pairs. These are supplied widths, not a proof of the smaller programs.
+ Exit-cut feasibility and all payload moves remain separate obligations.
+ """
+ def __init__(self, groups, library):
+ self.groups = groups
+ pairs = sorted(library)
+ for rank, width in pairs:
+ C.natural(rank, 'complement rank')
+ C.natural(width, 'complement program width')
+ C.require(0 < rank < groups.rank and width > 0,
+ 'positive smaller complement only; no B_0')
+ C.require(all(a[0] < b[0] for a, b in zip(pairs, pairs[1:])),
+ 'distinct complement library ranks')
+ required = tuple(sorted(groups.rank-s for s in groups.ranks if s < groups.rank))
+ C.require(tuple(rank for rank, _ in pairs) == required,
+ 'exact positive complement library')
+ self.library_ranks = tuple(rank for rank, _ in pairs)
+ self.library_widths = tuple(width for _, width in pairs)
+ for source_rank in groups.ranks:
+ if source_rank < groups.rank:
+ C.require(groups.index.replicas*groups.count(source_rank) % self.width(source_rank) == 0,
+ 'whole complement batch divisibility')
+
+ def width(self, source_rank):
+ rank = self.groups.rank-source_rank
+ at = bisect_left(self.library_ranks, rank)
+ C.require(at < len(self.library_ranks) and self.library_ranks[at] == rank,
+ 'positive complement program absent')
+ return self.library_widths[at]
+
+ def invocations(self, source_rank):
+ count = self.groups.count(source_rank)
+ C.require(source_rank < self.groups.rank, 'zero complement has no invocation')
+ return self.groups.index.replicas*count//self.width(source_rank)
+
+ def locate(self, row):
+ namespace, replica, _, path, point, ordinal, role = self.groups.index.owner(row)
+ unit = C.Unit(path, point, ordinal)
+ source_rank = self.groups.job_rank(unit, role)
+ local = self.groups.rank_source(source_rank, unit, role)
+ grouped = replica*self.groups.count(source_rank)+local
+ if source_rank == self.groups.rank:
+ return NoComplement(namespace, source_rank, grouped)
+ invocation, slot = divmod(grouped, self.width(source_rank))
+ return ComplementPort(namespace, source_rank, invocation, slot)
+
+ def row(self, location):
+ C.require(type(location) in (ComplementPort, NoComplement), 'typed complement location')
+ C.require(location.namespace == self.groups.index.namespace, 'invocation namespace')
+ source_rank = location.source_rank
+ count = self.groups.count(source_rank)
+ if type(location) is NoComplement:
+ C.require(source_rank == self.groups.rank, 'no-complement rank must be N')
+ C.natural(location.ordinal, 'no-complement ordinal')
+ grouped = location.ordinal
+ else:
+ C.require(source_rank < self.groups.rank, 'zero complement has no invocation')
+ C.natural(location.invocation, 'complement invocation')
+ C.natural(location.slot, 'complement slot')
+ width = self.width(source_rank)
+ C.require(location.slot < width, 'complement slot range')
+ grouped = location.invocation*width+location.slot
+ C.require(grouped < self.groups.index.replicas*count, 'complement group range')
+ replica, local = divmod(grouped, count)
+ unit, role = self.groups.unrank_source(source_rank, local)
+ return replica*self.groups.index.size+self.groups.index.rank_source(unit, role)
diff --git a/research/compiler-permanent-home-dispatch/inputs/inputs/inputs/source_index/inputs/pascal_codec.py b/research/compiler-permanent-home-dispatch/inputs/inputs/inputs/source_index/inputs/pascal_codec.py
new file mode 100644
index 0000000000..2fb4426cc8
--- /dev/null
+++ b/research/compiler-permanent-home-dispatch/inputs/inputs/inputs/source_index/inputs/pascal_codec.py
@@ -0,0 +1,222 @@
+"""Exact Pascal interval codec for a separated lockstep flow.
+
+Apache-2.0. Prepared for CubeJerry with substantial OpenAI assistance.
+This is an offline logical occurrence codec, not a fixed-tape dispatcher.
+"""
+from dataclasses import dataclass
+
+
+def require(condition, message):
+ if not condition:
+ raise ValueError(message)
+
+
+def natural(value, message):
+ require(type(value) is int and value >= 0, message)
+
+
+@dataclass(frozen=True)
+class Rule:
+ roles: tuple
+ rounds: tuple
+ owned: tuple = ("bank",)
+ ambient: int | None = None
+
+ def __post_init__(self):
+ require(bool(self.roles) and bool(self.rounds), "nonempty rule")
+ names = tuple(name for name, _ in self.roles)
+ require(len(set(names)) == len(names), "duplicate productive role")
+ require(len(set(self.owned)) == len(self.owned), "duplicate owned role")
+ require(not set(names) & set(self.owned), "owned/productive alias")
+ require(all(type(k) is int and k >= 2 for _, k in self.roles),
+ "target ranks are integers at least two")
+ require(all(type(r) is int and 1 <= r < min(k for _, k in self.roles)
+ and owner in names + self.owned for r, owner in self.rounds),
+ "positive separated paid rank and real owner")
+ if self.ambient is None:
+ object.__setattr__(self, "ambient", max(k for _, k in self.roles))
+ require(type(self.ambient) is int and
+ self.ambient >= max(k for _, k in self.roles), "ambient cap")
+
+ @property
+ def types(self):
+ return tuple(sorted(set(k for _, k in self.roles)))
+
+ @property
+ def weights(self):
+ return tuple(sum(k == rank for _, k in self.roles) for rank in self.types)
+
+ def type_of(self, role):
+ names = tuple(name for name, _ in self.roles)
+ require(role in names, "unknown productive role")
+ rank = self.roles[names.index(role)][1]
+ return self.types.index(rank)
+
+ def same_type_roles(self, i):
+ return tuple(name for name, k in self.roles if k == self.types[i])
+
+
+@dataclass(frozen=True)
+class Unit:
+ path: tuple
+ point: tuple
+ ordinal: int
+
+
+def validate_point(rule, point):
+ require(len(point) == len(rule.types), "point dimension")
+ for a in point:
+ natural(a, "nonnegative integer point")
+
+
+def column(rule, point):
+ validate_point(rule, point)
+ out = 1
+ for k, a in zip(rule.types, point):
+ for _ in range(a):
+ out *= k
+ return out
+
+
+def multiplicity(rule, point):
+ """Multinomial times weights, using exact small-factor arithmetic."""
+ validate_point(rule, point)
+ remaining, out = sum(point), 1
+ for a, weight in zip(point, rule.weights):
+ choose = 1
+ for j in range(1, a + 1):
+ choose = choose * (remaining - j + 1) // j
+ out *= choose
+ for _ in range(a):
+ out *= weight
+ remaining -= a
+ return out
+
+
+def remove_letter(point, i):
+ require(0 <= i < len(point) and point[i] > 0, "missing target letter")
+ return tuple(a - int(j == i) for j, a in enumerate(point))
+
+
+def encode(rule, parent_point, child_ordinal, role):
+ """Exact ordinal in the parent's Pascal bucket."""
+ validate_point(rule, parent_point)
+ i = rule.type_of(role)
+ child_point = remove_letter(parent_point, i)
+ natural(child_ordinal, "child ordinal")
+ require(child_ordinal < multiplicity(rule, child_point), "child ordinal range")
+ offset = 0
+ for j in range(i):
+ if parent_point[j]:
+ offset += rule.weights[j] * multiplicity(rule, remove_letter(parent_point, j))
+ same = rule.same_type_roles(i)
+ return offset + len(same) * child_ordinal + same.index(role)
+
+
+def decode(rule, parent_point, parent_ordinal):
+ """Inverse: (child point, child ordinal, productive role)."""
+ validate_point(rule, parent_point)
+ require(sum(parent_point) > 0, "no Pascal split of an empty word")
+ natural(parent_ordinal, "parent ordinal")
+ require(parent_ordinal < multiplicity(rule, parent_point), "parent ordinal range")
+ residual = parent_ordinal
+ for i, a in enumerate(parent_point):
+ if not a:
+ continue
+ child = remove_letter(parent_point, i)
+ names = rule.same_type_roles(i)
+ size = len(names) * multiplicity(rule, child)
+ if residual < size:
+ ordinal, role_index = divmod(residual, len(names))
+ return child, ordinal, names[role_index]
+ residual -= size
+ raise ValueError("Pascal identity failed")
+
+
+class FlowCodec:
+ def __init__(self, rule, rank):
+ natural(rank, "ambient rank")
+ require(rank >= rule.ambient, "at least one unit fits")
+ self.rule, self.rank = rule, rank
+ capacity, self.height = rank // rule.ambient, 0
+ power, smallest = 1, min(rule.types)
+ while power <= capacity // smallest:
+ power *= smallest
+ self.height += 1
+
+ def dilation(self, path):
+ value = 1
+ for j in path:
+ natural(j, "paid occurrence")
+ require(j < len(self.rule.rounds), "paid occurrence range")
+ value *= self.rule.rounds[j][0]
+ return value
+
+ def validate_unit(self, unit):
+ validate_point(self.rule, unit.point)
+ require(len(unit.path) + sum(unit.point) == self.height, "class degree")
+ natural(unit.ordinal, "unit ordinal")
+ require(unit.ordinal < multiplicity(self.rule, unit.point), "unit ordinal range")
+ require(self.rule.ambient * self.dilation(unit.path) *
+ column(self.rule, unit.point) <= self.rank, "absent unit")
+
+ def parent(self, unit, role):
+ """None means a fresh source, otherwise the exact issuing parent."""
+ self.validate_unit(unit)
+ i = self.rule.type_of(role)
+ if not unit.path:
+ return None
+ point = tuple(a + int(j == i) for j, a in enumerate(unit.point))
+ path = unit.path[:-1]
+ if self.rule.ambient * self.dilation(path) * column(self.rule, point) > self.rank:
+ return None
+ return Unit(path, point, encode(self.rule, point, unit.ordinal, role))
+
+ def owner(self, unit, role, namespace="flow", replica=0):
+ """Resolve a canonical field identity without any occurrence table."""
+ natural(replica, "replica")
+ self.validate_unit(unit)
+ self.rule.type_of(role)
+ while True:
+ parent = self.parent(unit, role)
+ if parent is None:
+ return (namespace, replica, "source", unit.path, unit.point, unit.ordinal, role)
+ parent_owner = self.rule.rounds[unit.path[-1]][1]
+ if parent_owner in self.rule.owned:
+ return (namespace, replica, "owned", parent.path, parent.point,
+ parent.ordinal, parent_owner)
+ unit, role = parent, parent_owner
+
+ def paid_owner(self, unit, j, namespace="flow", replica=0):
+ self.validate_unit(unit)
+ natural(j, "paid occurrence")
+ require(j < len(self.rule.rounds), "paid occurrence range")
+ owner = self.rule.rounds[j][1]
+ if owner in self.rule.owned:
+ return (namespace, replica, "owned", unit.path, unit.point, unit.ordinal, owner)
+ return self.owner(unit, owner, namespace, replica)
+
+ def iter_points(self, path):
+ """Stream the predecessor's lexicographic lattice order."""
+ degree = self.height - len(path)
+ require(degree >= 0, "path too deep")
+ limit = self.rank // (self.rule.ambient * self.dilation(path))
+ types = self.rule.types
+
+ def visit(i, left, value, prefix):
+ if i == len(types):
+ if left == 0:
+ yield tuple(prefix)
+ return
+ for a in range(left + 1):
+ if value > limit:
+ break
+ yield from visit(i + 1, left - a, value, prefix + [a])
+ value *= types[i]
+
+ yield from visit(0, degree, 1, [])
+
+ def iter_units(self, path):
+ for point in self.iter_points(path):
+ for ordinal in range(multiplicity(self.rule, point)):
+ yield Unit(path, point, ordinal)
diff --git a/research/compiler-permanent-home-dispatch/inputs/inputs/inputs/source_index/source_index.py b/research/compiler-permanent-home-dispatch/inputs/inputs/inputs/source_index/source_index.py
new file mode 100644
index 0000000000..4e3cb2a53f
--- /dev/null
+++ b/research/compiler-permanent-home-dispatch/inputs/inputs/inputs/source_index/source_index.py
@@ -0,0 +1,205 @@
+"""Contiguous source rows by aggregated lockstep-subtree counting.
+
+Apache-2.0. Prepared for CubeJerry with substantial OpenAI assistance.
+This is offline indexing, not a fixed-tape payload implementation.
+"""
+from collections import Counter
+from bisect import bisect_left
+import hashlib
+import importlib.util
+from pathlib import Path
+import sys
+
+HERE = Path(__file__).resolve().parent
+CODEC_HASH = "cec2c8b5e153a264127e8301ed59591fe97c9a46078ff2343b3784d177c6984d"
+CODEC_PATH = HERE / "inputs/pascal_codec.py"
+if hashlib.sha256(CODEC_PATH.read_bytes()).hexdigest() != CODEC_HASH:
+ raise ValueError("frozen occurrence codec hash")
+spec = importlib.util.spec_from_file_location("source_index_codec", CODEC_PATH)
+C = importlib.util.module_from_spec(spec)
+sys.modules[spec.name] = C
+spec.loader.exec_module(C)
+
+
+def points(degree, dimensions):
+ """Lexicographic nonnegative multiindices of one exact degree."""
+ if dimensions == 1:
+ yield (degree,)
+ return
+ for first in range(degree + 1):
+ for rest in points(degree - first, dimensions - 1):
+ yield (first,) + rest
+
+
+def sorted_unique(items):
+ """Deterministic comparison sort and adjacent deduplication; no hashing."""
+ ordered = sorted(items)
+ unique = []
+ for item in ordered:
+ if not unique or item != unique[-1]:
+ unique.append(item)
+ return unique
+
+
+class SortedStateTable:
+ """Fixed sorted integer keys, binary-search lookup and indexed values.
+
+ The two count tables share one immutable key tuple. No growing state
+ set/dictionary and no expected hash-table time enters the theorem.
+ """
+ def __init__(self, keys):
+ C.require(all(a < b for a, b in zip(keys, keys[1:])),
+ "strictly sorted distinct state keys")
+ self._keys = keys
+ self._values = [None] * len(keys)
+
+ def position(self, key):
+ at = bisect_left(self._keys, key)
+ C.require(at < len(self._keys) and self._keys[at] == key,
+ "state key absent from fixed table")
+ return at
+
+ def __getitem__(self, key):
+ value = self._values[self.position(key)]
+ C.require(value is not None, "state count not initialized")
+ return value
+
+ def __setitem__(self, key, value):
+ self._values[self.position(key)] = value
+
+ def __len__(self):
+ return len(self._keys)
+
+ def __iter__(self):
+ return iter(self._keys)
+
+ def keys(self):
+ return iter(self._keys)
+
+ def values(self):
+ return iter(self._values)
+
+ def items(self):
+ return zip(self._keys, self._values)
+
+
+class SourceIndex:
+ def __init__(self, rule, rank, replicas=1, namespace="flow"):
+ C.natural(replicas, "replica count")
+ C.require(replicas > 0, "positive replica count")
+ self.flow = C.FlowCodec(rule, rank)
+ self.rule, self.rank = rule, rank
+ self.replicas, self.namespace = replicas, namespace
+ self.height = self.flow.height
+ self.types, self.weights = rule.types, rule.weights
+ self.paid = Counter(r for r, _ in rule.rounds)
+ # Counter is confined to the fixed input list; its worst-case
+ # collision cost is covered by the specification-size factor.
+ self.point_data = []
+ for g in range(self.height + 1):
+ self.point_data.append(tuple((a, C.column(rule, a), C.multiplicity(rule, a))
+ for a in points(g, len(self.types))))
+ levels = [[(1, 0)]]
+ for _ in range(self.height):
+ # Adjacent equal dilations differ only in their last rank.
+ # Deduplicate them before generating children: (rho*r,r) is
+ # injective in rho at fixed r, and distinct r give distinct keys.
+ dilations = []
+ for rho, _ in levels[-1]:
+ if not dilations or rho != dilations[-1]:
+ dilations.append(rho)
+ levels.append(sorted_unique((rho*r, r) for rho in dilations
+ for r in self.paid))
+ keys = tuple((h, rho, previous) for h, level in enumerate(levels)
+ for rho, previous in level)
+ self.local, self.total = SortedStateTable(keys), SortedStateTable(keys)
+ for h in range(self.height, -1, -1):
+ for rho, previous in levels[h]:
+ state = (h, rho, previous)
+ local = sum(u*count for _, _, u, count in self.blocks(state))
+ total = local
+ if h < self.height:
+ total += sum(mult*self.total[h+1, rho*r, r]
+ for r, mult in self.paid.items())
+ self.local[state], self.total[state] = local, total
+ self.size = self.total[0, 1, 0]
+ C.require(self.size > 0, "nonempty source interval")
+
+ def fresh_type(self, state, column, i):
+ h, rho, previous = state
+ return h == 0 or self.rule.ambient * (rho // previous) * column * self.types[i] > self.rank
+
+ def blocks(self, state):
+ h, rho, _ = state
+ for point, column, units in self.point_data[self.height-h]:
+ if self.rule.ambient * rho * column <= self.rank:
+ count = sum(w for i, w in enumerate(self.weights)
+ if self.fresh_type(state, column, i))
+ if count:
+ yield point, column, units, count
+
+ def fresh_roles(self, state, column):
+ return tuple(name for name, k in self.rule.roles
+ if self.fresh_type(state, column, self.types.index(k)))
+
+ def rank_source(self, unit, role):
+ self.flow.validate_unit(unit)
+ self.rule.type_of(role)
+ state, offset = (0, 1, 0), 0
+ for chosen in unit.path:
+ h, rho, _ = state
+ offset += self.local[state]
+ for r, _ in self.rule.rounds[:chosen]:
+ offset += self.total[h+1, rho*r, r]
+ r = self.rule.rounds[chosen][0]
+ state = (h+1, rho*r, r)
+ for point, column, units, count in self.blocks(state):
+ if point < unit.point:
+ offset += units*count
+ continue
+ if point == unit.point:
+ roles = self.fresh_roles(state, column)
+ C.require(role in roles, "slot is matched, not a fresh source")
+ return offset + unit.ordinal*count + roles.index(role)
+ break
+ raise ValueError("slot is matched, not a fresh source")
+
+ def unrank_source(self, index):
+ C.natural(index, "source index")
+ C.require(index < self.size, "source index range")
+ state, path = (0, 1, 0), ()
+ while True:
+ if index < self.local[state]:
+ for point, column, units, count in self.blocks(state):
+ if index < units*count:
+ ordinal, role = divmod(index, count)
+ return C.Unit(path, point, ordinal), self.fresh_roles(state, column)[role]
+ index -= units*count
+ raise ValueError("local count/index disagreement")
+ index -= self.local[state]
+ h, rho, _ = state
+ C.require(h < self.height, "no child beyond the last class")
+ for j, (r, _) in enumerate(self.rule.rounds):
+ child = (h+1, rho*r, r)
+ if index < self.total[child]:
+ state, path = child, path + (j,)
+ break
+ index -= self.total[child]
+ else:
+ raise ValueError("subtree count/index disagreement")
+
+ def row(self, owner):
+ C.require(type(owner) is tuple and len(owner) == 7, "complete field identifier")
+ namespace, replica, kind, path, point, ordinal, role = owner
+ C.require(namespace == self.namespace, "invocation namespace")
+ C.natural(replica, "replica")
+ C.require(replica < self.replicas, "replica range")
+ C.require(kind == "source", "owned bank has no productive source row")
+ return replica*self.size + self.rank_source(C.Unit(path, point, ordinal), role)
+
+ def owner(self, row):
+ C.natural(row, "physical row index")
+ C.require(row < self.replicas*self.size, "physical row index range")
+ replica, index = divmod(row, self.size)
+ unit, role = self.unrank_source(index)
+ return (self.namespace, replica, "source", unit.path, unit.point, unit.ordinal, role)
diff --git a/research/compiler-permanent-home-dispatch/inputs/inputs/library.py b/research/compiler-permanent-home-dispatch/inputs/inputs/library.py
new file mode 100644
index 0000000000..e1e34aa0e6
--- /dev/null
+++ b/research/compiler-permanent-home-dispatch/inputs/inputs/library.py
@@ -0,0 +1,305 @@
+"""Exact separated chronological compiler metadata; Apache-2.0.
+
+Prepared for CubeJerry with substantial OpenAI assistance. This reference
+evaluates integers, not native programs. PROOF.md prices indexed arithmetic
+and a separately described sequential implementation.
+"""
+from dataclasses import dataclass
+from math import comb, gcd
+
+
+class BudgetError(ValueError):
+ """The bounded executable refuses an unevaluated larger instance."""
+
+
+@dataclass(frozen=True)
+class Limits:
+ max_rank: int = 4096
+ max_records: int = 200000
+ max_bits: int = 16384
+
+ def __post_init__(self):
+ if any(type(x) is not int or x < 1 for x in
+ (self.max_rank, self.max_records, self.max_bits)):
+ raise ValueError("positive integer capacities required")
+
+ def integer(self, value):
+ if abs(value).bit_length() > self.max_bits:
+ raise BudgetError("integer bit capacity")
+ return value
+
+ def records(self, count):
+ if count > self.max_records:
+ raise BudgetError("local record capacity")
+
+
+@dataclass(frozen=True)
+class Rule:
+ targets: tuple
+ paid: tuple
+
+ def __post_init__(self):
+ for alphabet in (self.targets, self.paid):
+ if type(alphabet) is not tuple or not alphabet:
+ raise ValueError("nonempty tuple histograms required")
+ previous = 0
+ for entry in alphabet:
+ if type(entry) is not tuple or len(entry) != 2:
+ raise ValueError("rank/count pairs required")
+ rank, count = entry
+ if (type(rank) is not int or type(count) is not int or
+ rank <= previous or count < 1):
+ raise ValueError("sorted distinct positive ranks/counts required")
+ previous = rank
+ if self.targets[0][0] < 2 or self.paid[-1][0] >= self.targets[0][0]:
+ raise ValueError("strict separation required")
+
+ @property
+ def m(self):
+ return self.targets[-1][0]
+
+ @property
+ def kmin(self):
+ return self.targets[0][0]
+
+ @property
+ def bits(self):
+ def gamma_length(v):
+ return 2 * v.bit_length() - 1
+ total = 0
+ for alphabet in (self.targets, self.paid):
+ total += gamma_length(len(alphabet))
+ total += sum(gamma_length(x) for row in alphabet for x in row)
+ return total
+
+
+@dataclass(frozen=True)
+class Row:
+ replication: int
+ width: int
+ leaves: int
+ units: int
+
+
+@dataclass(frozen=True)
+class Census:
+ rank: int
+ height: int
+ units: int
+ sources: tuple
+ exits: tuple
+
+
+@dataclass
+class Work:
+ product_records: int = 0
+ candidate_pairs: int = 0
+ source_contributions: int = 0
+ complement_constraints: int = 0
+ exit_constraints: int = 0
+ completed_rows: int = 0
+
+
+@dataclass(frozen=True)
+class Library:
+ rule: Rule
+ rows: tuple
+ work: Work
+
+
+def height(rule, rank):
+ if rank < rule.m:
+ raise ValueError("height requires a nonbase rank")
+ threshold = rule.m
+ result = 0
+ while threshold * rule.kmin <= rank:
+ threshold *= rule.kmin
+ result += 1
+ return result
+
+
+def merge_records(records, limits):
+ """Deterministic sort/add; input length and temporary integers charged."""
+ limits.records(len(records))
+ records.sort(key=lambda item: item[0])
+ result = []
+ key, value = None, 0
+ for next_key, next_value in records:
+ if key is not None and next_key != key:
+ if value < 0:
+ raise ValueError("negative aggregate")
+ if value:
+ result.append((key, value))
+ value = 0
+ key = next_key
+ value = limits.integer(value + next_value)
+ if key is not None:
+ if value < 0:
+ raise ValueError("negative aggregate")
+ if value:
+ result.append((key, value))
+ return tuple(result)
+
+
+def product_tables(alphabet, degree, limits, work):
+ tables = [((1, 1),)]
+ for _ in range(degree):
+ limits.records(len(tables[-1]) * len(alphabet))
+ candidates = []
+ for product, count in tables[-1]:
+ for rank, multiplicity in alphabet:
+ candidates.append((limits.integer(product * rank),
+ limits.integer(count * multiplicity)))
+ work.product_records += len(candidates)
+ tables.append(merge_records(candidates, limits))
+ return tuple(tables)
+
+
+def census(rule, rank, targets, paid, limits, work):
+ gmax = height(rule, rank)
+ d, q = len(rule.targets), len(rule.paid)
+ bound = (d + q) * comb(gmax + d + q - 1, d + q - 1)
+ limits.records(bound)
+ contributions = []
+ units = 0
+ for depth in range(gmax + 1):
+ for rho, paths in paid[depth]:
+ for column, words in targets[gmax - depth]:
+ work.candidate_pairs += 1
+ size = limits.integer(rho * column)
+ if limits.integer(rule.m * size) > rank:
+ continue
+ copies = limits.integer(paths * words)
+ units = limits.integer(units + copies)
+ for k, multiplicity in rule.targets:
+ contributions.append((limits.integer(size * k),
+ limits.integer(copies * multiplicity)))
+ if depth < gmax:
+ for r, multiplicity in rule.paid:
+ contributions.append((limits.integer(size * r),
+ -limits.integer(copies * multiplicity)))
+ work.source_contributions += len(contributions)
+ sources = merge_records(contributions, limits)
+ if not sources or any(not rank < rule.m * s <= rule.m * rank
+ for s, _ in sources):
+ raise ValueError("source band failure")
+ exits = paid[gmax + 1]
+ if any(not 0 < e * rule.m <= (rule.m - 1) * rank for e, _ in exits):
+ raise ValueError("exit contraction failure")
+ return Census(rank, gmax, units, sources, exits)
+
+
+def child(rows, parent, rank):
+ if not 1 <= rank < parent or rank >= len(rows) or rows[rank] is None:
+ raise ValueError("positive previously completed child required")
+ return rows[rank]
+
+
+def replication(flow, rows, limits, work):
+ result = 1
+ for source, count in flow.sources:
+ if source == flow.rank:
+ continue
+ width = child(rows, flow.rank, flow.rank - source).width
+ factor = width // gcd(width, count)
+ result = limits.integer((result // gcd(result, factor)) * factor)
+ work.complement_constraints += 1
+ for exit_rank, multiplicity in flow.exits:
+ factor = child(rows, flow.rank, exit_rank).width
+ result = limits.integer((result // gcd(result, factor)) * factor)
+ work.exit_constraints += 1
+ return result
+
+
+def whole_copies(arrays, width):
+ copies, remainder = divmod(arrays, width)
+ if remainder:
+ raise ValueError("nonintegral chronological child batch")
+ return copies
+
+
+def finish_row(flow, rows, scale, limits):
+ width = limits.integer(scale * sum(count for _, count in flow.sources))
+ leaves = 0
+ units = limits.integer(scale * flow.units)
+ for source, count in flow.sources:
+ if source == flow.rank:
+ continue
+ old = child(rows, flow.rank, flow.rank - source)
+ copies = whole_copies(limits.integer(scale * count), old.width)
+ leaves = limits.integer(leaves + limits.integer(copies * old.leaves))
+ units = limits.integer(units + limits.integer(copies * old.units))
+ for exit_rank, multiplicity in flow.exits:
+ old = child(rows, flow.rank, exit_rank)
+ per_cut = whole_copies(scale, old.width)
+ copies = limits.integer(multiplicity * per_cut)
+ leaves = limits.integer(leaves + limits.integer(copies * old.leaves))
+ units = limits.integer(units + limits.integer(copies * old.units))
+ return Row(scale, width, leaves, units)
+
+
+def compile_library(rule, maximum, limits=Limits()):
+ if type(maximum) is not int or maximum < 1:
+ raise ValueError("positive maximum rank required")
+ if maximum > limits.max_rank:
+ raise BudgetError("maximum rank capacity")
+ limits.records(len(rule.targets) + len(rule.paid))
+ for alphabet in (rule.targets, rule.paid):
+ for record in alphabet:
+ for value in record:
+ limits.integer(value)
+ work = Work()
+ rows = [None] # no B_0 program is constructed or queried
+ if maximum >= rule.m:
+ gmax = height(rule, maximum)
+ mt = comb(gmax + len(rule.targets), len(rule.targets))
+ mr = comb(gmax + len(rule.paid) + 1, len(rule.paid))
+ limits.records(mt + mr)
+ targets = product_tables(rule.targets, gmax, limits, work)
+ paid = product_tables(rule.paid, gmax + 1, limits, work)
+ for rank in range(1, maximum + 1):
+ if rank < rule.m:
+ row = Row(1, 1, rank, 0)
+ else:
+ flow = census(rule, rank, targets, paid, limits, work)
+ scale = replication(flow, rows, limits, work)
+ row = finish_row(flow, rows, scale, limits)
+ rows.append(row)
+ work.completed_rows += 1
+ return Library(rule, tuple(rows), work)
+
+
+def envelope(rule, maximum):
+ """Return explicit integer bounds, not the enormous powers B or F**D."""
+ if type(maximum) is not int or maximum < rule.m:
+ raise ValueError("nonbase maximum required for this envelope")
+ d, q = len(rule.targets), len(rule.paid)
+ w = sum(count for _, count in rule.targets)
+ p = sum(count for _, count in rule.paid)
+ g = height(rule, maximum)
+ length = maximum.bit_length()
+ ubar = (g + 1) * max(w, p) ** g
+ sbar = w * ubar
+ f = 1 + (w + 1) * ubar + p ** (g + 1)
+ depth = rule.m * length
+ generators = []
+ for rank in sorted(k for alphabet in (rule.targets, rule.paid)
+ for k, _ in alphabet if k >= 2):
+ if not generators or generators[-1] != rank:
+ generators.append(rank)
+ tau = rule.m * (rule.kmin - 1).bit_length()
+ beta = tau * (length + 1) ** len(generators) * sbar.bit_length()
+ mt, mr = comb(g + d, d), comb(g + q + 1, q)
+ pairs = comb(g + d + q - 1, d + q - 1)
+ exits = comb(g + q, q - 1)
+ operations = ((rule.bits + 1) ** 2 + d * mt + q * mr +
+ (maximum + 1) * ((d + q + 2) * pairs + exits + g + 2))
+ bit_cap = 8 * (rule.bits + length + (g + 2) * (rule.m + w + p + 2).bit_length()
+ + beta + rule.m.bit_length() + depth * f.bit_length()
+ + operations.bit_length() + 2)
+ local_records = mt + mr + (d + q + 2) * pairs + exits + g + rule.bits + 2
+ return {"height": g, "target_records": mt, "paid_records": mr,
+ "pairs": pairs, "exit_records": exits, "width_log_bound": beta,
+ "combined_output_bits": beta + rule.m.bit_length() + depth * f.bit_length() + 1,
+ "F": f, "D": depth, "K": operations, "Z": bit_cap,
+ "J": local_records, "L_local": local_records * bit_cap}
diff --git a/research/compiler-permanent-home-dispatch/inputs/leaf_index.py b/research/compiler-permanent-home-dispatch/inputs/leaf_index.py
new file mode 100644
index 0000000000..946fcf914a
--- /dev/null
+++ b/research/compiler-permanent-home-dispatch/inputs/leaf_index.py
@@ -0,0 +1,255 @@
+"""Lazy chronological rank-one leaf locations and persistent field identities.
+
+Prepared for CubeJerry with substantial OpenAI assistance. Apache-2.0.
+Logical descriptors only: no payload execution or unpriced adapters.
+"""
+from dataclasses import dataclass
+from hashlib import sha256
+from importlib.util import module_from_spec, spec_from_file_location
+from pathlib import Path
+import sys
+
+HERE = Path(__file__).resolve().parent
+SOURCE = HERE / 'inputs/groups.py'
+if sha256(SOURCE.read_bytes()).hexdigest() != '871b166c174958bb467952bebe9a2b776a0582f0c427b7dea9a94a128edad171':
+ raise ValueError('frozen complement-port source')
+spec = spec_from_file_location('leaf_groups', SOURCE)
+G = module_from_spec(spec)
+sys.modules[spec.name] = G
+spec.loader.exec_module(G)
+C, I = G.C, G.I
+
+
+@dataclass(frozen=True)
+class Step:
+ parent: int
+ kind: str
+ key: object # source rank, or full ordered exit path
+ invocation: int
+
+
+@dataclass(frozen=True)
+class SourceRow:
+ namespace: str
+ row: int
+
+
+@dataclass(frozen=True)
+class OwnedBank:
+ namespace: str
+ calls: tuple
+ replica: int
+ path: tuple
+ point: tuple
+ ordinal: int
+ role: str
+
+
+@dataclass(frozen=True)
+class Leaf:
+ calls: tuple
+ rank: int
+ axis: int
+ field: object
+
+
+class Node:
+ """One rank's source and weighted chronological-cut metadata."""
+ def __init__(self, compiler, rank):
+ self.compiler, self.rank = compiler, rank
+ self.row = compiler.row(rank)
+ self.groups = G.SourceGroups(compiler.rule, rank, self.row.replication, 'local')
+ self.height = self.groups.index.height
+ C.require(self.row.width == self.row.replication*self.groups.index.size,
+ 'compiled source width recurrence')
+ library = tuple((rank-s, compiler.row(rank-s).width)
+ for s in self.groups.ranks if s < rank)
+ self.complements = G.ComplementRouter(self.groups, library)
+ prefixes, self.pre = [], 0
+ for source in self.groups.ranks:
+ if source == rank:
+ continue
+ child = compiler.row(rank-source)
+ size = self.complements.invocations(source)*child.leaves
+ prefixes.append((source, self.pre, size))
+ self.pre += size
+ self.prefixes = tuple(prefixes)
+ levels = [(1,)]
+ for _ in range(self.height+1):
+ levels.append(tuple(I.sorted_unique(rho*r for rho in levels[-1]
+ for r in self.groups.index.paid)))
+ keys = tuple((h, rho) for h, level in enumerate(levels) for rho in level)
+ self.suffix = I.SortedStateTable(keys)
+ for h in range(self.height+1, -1, -1):
+ for rho in levels[h]:
+ if h == self.height+1:
+ child = compiler.row(rho)
+ copies, remainder = divmod(self.row.replication, child.width)
+ C.require(remainder == 0, 'every individual exit cut is integral')
+ value = copies*child.leaves
+ else:
+ value = sum(count*self.suffix[h+1, rho*r]
+ for r, count in self.groups.index.paid.items())
+ self.suffix[h, rho] = value
+ C.require(self.pre+self.suffix[0, 1] == self.row.leaves,
+ 'complete ordered leaf count recurrence')
+
+ def exit_rank(self, cut):
+ C.require(type(cut) is tuple and len(cut) == self.height+1,
+ 'complete chronological exit cut')
+ return self.groups.index.flow.dilation(cut)
+
+ def exit_owner(self, cut, replica):
+ self.exit_rank(cut)
+ C.natural(replica, 'replica')
+ C.require(replica < self.row.replication, 'exit replica range')
+ unit = C.Unit(cut[:-1], (0,)*len(self.groups.index.types), 0)
+ return self.groups.index.flow.paid_owner(unit, cut[-1], 'local', replica)
+
+ def exit_port(self, cut, owner):
+ e = self.exit_rank(cut)
+ C.require(type(owner) is tuple and len(owner) == 7, 'complete owner identifier')
+ replica = owner[1]
+ C.require(owner == self.exit_owner(cut, replica), 'owner at this cut')
+ return divmod(replica, self.compiler.row(e).width)
+
+ def step_data(self, step):
+ """Validate one call; return (child rank, before-call leaf offset)."""
+ C.require(type(step) is Step and step.parent == self.rank, 'correct parent rank')
+ C.natural(step.invocation, 'whole invocation ordinal')
+ if step.kind == 'complement':
+ C.natural(step.key, 'complement source rank')
+ for source, offset, _ in self.prefixes:
+ if source == step.key:
+ child = self.compiler.row(self.rank-source)
+ C.require(step.invocation < self.complements.invocations(source),
+ 'complement invocation range')
+ return self.rank-source, offset+step.invocation*child.leaves
+ raise ValueError('positive complement source absent')
+ C.require(step.kind == 'exit', 'typed chronological call')
+ e = self.exit_rank(step.key)
+ child = self.compiler.row(e)
+ C.require(step.invocation < self.row.replication//child.width,
+ 'exit invocation range')
+ rho, offset = 1, self.pre
+ for h, chosen in enumerate(step.key):
+ for r, _ in self.compiler.rule.rounds[:chosen]:
+ offset += self.suffix[h+1, rho*r]
+ rho *= self.compiler.rule.rounds[chosen][0]
+ return e, offset+step.invocation*child.leaves
+
+ def locate(self, ordinal):
+ C.natural(ordinal, 'leaf ordinal')
+ C.require(ordinal < self.row.leaves, 'leaf ordinal range')
+ for source, offset, size in self.prefixes:
+ if ordinal < offset+size:
+ child = self.compiler.row(self.rank-source)
+ invocation, local = divmod(ordinal-offset, child.leaves)
+ return Step(self.rank, 'complement', source, invocation), local
+ local, rho, path = ordinal-self.pre, 1, ()
+ for h in range(self.height+1):
+ for chosen, (r, _) in enumerate(self.compiler.rule.rounds):
+ size = self.suffix[h+1, rho*r]
+ if local < size:
+ path += (chosen,)
+ rho *= r
+ break
+ local -= size
+ else:
+ raise ValueError('weighted cut count disagreement')
+ invocation, local = divmod(local, self.compiler.row(rho).leaves)
+ return Step(self.rank, 'exit', path, invocation), local
+
+ def caller_owner(self, step, child_row):
+ e, _ = self.step_data(step)
+ C.natural(child_row, 'child productive row')
+ C.require(child_row < self.compiler.row(e).width, 'child productive row range')
+ if step.kind == 'complement':
+ row = self.complements.row(G.ComplementPort('local', step.key,
+ step.invocation, child_row))
+ return self.groups.index.owner(row)
+ replica = step.invocation*self.compiler.row(e).width+child_row
+ return self.exit_owner(step.key, replica)
+
+
+class Compiler:
+ """Supplied exact library plus unexpanded logical occurrence metadata.
+
+ A may exceed every target rank. Base ranks n= 2 and rows[0] is None, 'no rank-zero library')
+ self.rule, self.rows, self.namespace = rule, tuple(rows), namespace
+ self.maximum = len(rows)-1
+ self.nodes = [None]*len(rows)
+ for rank, row in enumerate(rows[1:], 1):
+ for value in (row.replication, row.width, row.leaves):
+ C.natural(value, 'evaluated library integer')
+ C.require(value > 0, 'positive library integer')
+ if rank < rule.ambient:
+ C.require((row.replication, row.width, row.leaves) == (1, 1, rank),
+ 'sequential base library')
+
+ def row(self, rank):
+ C.natural(rank, 'library rank')
+ C.require(0 < rank <= self.maximum, 'positive available library rank')
+ return self.rows[rank]
+
+ def node(self, rank):
+ self.row(rank)
+ C.require(rank >= self.rule.ambient, 'nonbase flow only')
+ if self.nodes[rank] is None:
+ self.nodes[rank] = Node(self, rank)
+ return self.nodes[rank]
+
+ def validate_calls(self, calls, root=None):
+ C.require(type(calls) is tuple, 'tuple call path')
+ rank = self.maximum if root is None else root
+ self.row(rank)
+ for step in calls:
+ rank, _ = self.node(rank).step_data(step)
+ return rank
+
+ def resolve_row(self, calls, row, root=None):
+ """Map a call's productive port to persistent root/owned identity."""
+ rank = self.validate_calls(calls, root)
+ C.natural(row, 'productive row')
+ C.require(row < self.row(rank).width, 'productive row range')
+ for at in range(len(calls)-1, -1, -1):
+ step = calls[at]
+ node = self.node(step.parent)
+ owner = node.caller_owner(step, row)
+ if owner[2] == 'owned':
+ _, replica, _, path, point, ordinal, role = owner
+ return OwnedBank(self.namespace, calls[:at], replica,
+ path, point, ordinal, role)
+ row = node.groups.index.row(owner)
+ return SourceRow(self.namespace, row)
+
+ def locate(self, ordinal, root=None):
+ rank = self.maximum if root is None else root
+ C.natural(ordinal, 'leaf ordinal')
+ C.require(ordinal < self.row(rank).leaves, 'leaf ordinal range')
+ calls = ()
+ while rank >= self.rule.ambient:
+ step, ordinal = self.node(rank).locate(ordinal)
+ calls += (step,)
+ rank, _ = self.node(rank).step_data(step)
+ return Leaf(calls, rank, ordinal, self.resolve_row(calls, 0, root))
+
+ def rank_leaf(self, leaf, root=None):
+ C.require(type(leaf) is Leaf, 'typed leaf descriptor')
+ rank = self.validate_calls(leaf.calls, root)
+ C.require(rank == leaf.rank and rank < self.rule.ambient, 'correct base rank')
+ C.natural(leaf.axis, 'base axis')
+ C.require(leaf.axis < rank, 'base axis range')
+ C.require(leaf.field == self.resolve_row(leaf.calls, 0, root),
+ 'leaf physical field identity')
+ ordinal = leaf.axis
+ for step in reversed(leaf.calls):
+ _, offset = self.node(step.parent).step_data(step)
+ ordinal += offset
+ return ordinal
diff --git a/research/compiler-permanent-home-dispatch/inputs/literal_oracle.py b/research/compiler-permanent-home-dispatch/inputs/literal_oracle.py
new file mode 100644
index 0000000000..cd61ca640f
--- /dev/null
+++ b/research/compiler-permanent-home-dispatch/inputs/literal_oracle.py
@@ -0,0 +1,172 @@
+"""Separate finite oracle: materialize every class, match slot lists, expand calls.
+
+No production codec, source DP, weighted suffix DP or owner resolver is imported.
+Prepared for CubeJerry with substantial OpenAI assistance. Apache-2.0.
+"""
+from collections import Counter, defaultdict
+from dataclasses import dataclass
+from itertools import product
+from math import gcd, prod
+
+
+@dataclass(frozen=True)
+class Row:
+ replication: int
+ width: int
+ leaves: int
+ units: int
+
+
+class LiteralFlow:
+ def __init__(self, roles, rounds, owned, ambient, rank, cap=100000):
+ self.roles, self.rounds, self.owned = roles, rounds, owned
+ self.ambient, self.rank = ambient, rank
+ self.types = tuple(sorted({k for _, k in roles}))
+ type_index = {k: i for i, k in enumerate(self.types)}
+ threshold, self.height = ambient, 0
+ while threshold*min(self.types) <= rank:
+ threshold *= min(self.types)
+ self.height += 1
+ points = []
+ for degree in range(self.height+1):
+ if len(roles)**degree > cap:
+ raise ValueError('literal role-word capacity')
+ counts = Counter()
+ for word in product(range(len(roles)), repeat=degree):
+ alpha = [0]*len(self.types)
+ for letter in word:
+ alpha[type_index[roles[letter][1]]] += 1
+ counts[tuple(alpha)] += 1
+ points.append(sorted(counts.items()))
+ self.classes, self.owners, self.fresh = {}, {}, []
+ self.units = 0
+
+ def construct(path, incoming=None):
+ rho = prod(rounds[j][0] for j in path)
+ units, buckets = [], defaultdict(list)
+ for alpha, count in points[self.height-len(path)]:
+ column = prod(k**a for k, a in zip(self.types, alpha))
+ if ambient*rho*column > rank:
+ continue
+ for ordinal in range(count):
+ unit = path, alpha, ordinal
+ units.append(unit)
+ for name, k in roles:
+ slot = unit+(name,)
+ beta = list(alpha)
+ beta[type_index[k]] += 1
+ buckets[tuple(beta)].append(slot)
+ self.units += len(units)
+ if self.units > cap:
+ raise ValueError('literal unit capacity')
+ self.classes[path] = units
+ if incoming is not None:
+ for alpha, supply in incoming.items():
+ targets = buckets[alpha]
+ if len(supply) != len(targets):
+ raise ValueError('literal Pascal list mismatch')
+ for value, target in zip(supply, targets):
+ self.owners[target] = value
+ for unit in units:
+ for name, k in roles:
+ slot = unit+(name,)
+ if slot not in self.owners:
+ self.owners[slot] = ('source', slot)
+ self.fresh.append((slot, rho*prod(t**a for t, a in
+ zip(self.types, unit[1]))*k))
+ if len(path) < self.height:
+ for j, (_, name) in enumerate(rounds):
+ supply = defaultdict(list)
+ for unit in units:
+ value = (('owned', unit, name) if name in owned else
+ self.owners[unit+(name,)])
+ supply[unit[1]].append(value)
+ construct(path+(j,), supply)
+ construct(())
+ self.fresh_index = {slot: i for i, (slot, _) in enumerate(self.fresh)}
+ if len(rounds)**(self.height+1) > cap:
+ raise ValueError('literal cut capacity')
+ self.cuts = tuple(product(range(len(rounds)), repeat=self.height+1))
+
+ def exit(self, cut):
+ unit = self.classes[cut[:-1]][0]
+ if len(self.classes[cut[:-1]]) != 1 or any(unit[1]):
+ raise ValueError('deepest single-unit condition')
+ name = self.rounds[cut[-1]][1]
+ value = (('owned', unit, name) if name in self.owned else
+ self.owners[unit+(name,)])
+ return prod(self.rounds[j][0] for j in cut), value
+
+
+def library(roles, rounds, owned, ambient, maximum):
+ rows, flows = [None], {}
+ for n in range(1, maximum+1):
+ if n < ambient:
+ rows.append(Row(1, 1, n, 0))
+ continue
+ flow = LiteralFlow(roles, rounds, owned, ambient, n)
+ flows[n] = flow
+ sources = Counter(s for _, s in flow.fresh)
+ batches = [(n-s, count) for s, count in sorted(sources.items()) if s < n]
+ batches += [(flow.exit(cut)[0], 1) for cut in flow.cuts]
+ a = 1
+ for q, count in batches:
+ if not 0 < q < n:
+ raise ValueError('literal rank descent')
+ factor = rows[q].width//gcd(rows[q].width, count)
+ a = a//gcd(a, factor)*factor
+ leaves = sum(a*count//rows[q].width*rows[q].leaves for q, count in batches)
+ units = a*flow.units+sum(a*count//rows[q].width*rows[q].units
+ for q, count in batches)
+ rows.append(Row(a, a*len(flow.fresh), leaves, units))
+ return tuple(rows), flows
+
+
+def expand(roles, rounds, owned, ambient, rows, flows, root, namespace='compiler',
+ leaf_cap=100000):
+ """Return fully expanded leaf descriptors and whole-call input receipts."""
+ if rows[root].leaves > leaf_cap or rows[root].width > leaf_cap:
+ raise ValueError('literal expanded-program capacity')
+ leaves, calls = [], []
+
+ def visit(n, chain, fields):
+ if len(fields) != rows[n].width or len(set(fields)) != len(fields):
+ raise ValueError('literal whole-input alias/width')
+ if n < ambient:
+ for axis in range(n):
+ leaves.append((chain, n, axis, fields[0]))
+ return
+ flow, a = flows[n], rows[n].replication
+
+ def lift(replica, value):
+ if value[0] == 'source':
+ return fields[replica*len(flow.fresh)+flow.fresh_index[value[1]]]
+ _, unit, role = value
+ path, point, ordinal = unit
+ return ('owned', namespace, chain, replica, path, point, ordinal, role)
+
+ def invoke(q, kind, key, batch):
+ width = rows[q].width
+ if len(batch) % width:
+ raise ValueError('literal incomplete child')
+ for at in range(0, len(batch), width):
+ step = n, kind, key, at//width
+ child_chain = chain+(step,)
+ inputs = tuple(batch[at:at+width])
+ calls.append((child_chain, q, inputs))
+ visit(q, child_chain, inputs)
+
+ for s in sorted({s for _, s in flow.fresh}):
+ if s < n:
+ batch = [fields[b*len(flow.fresh)+i]
+ for b in range(a) for i, (_, rank) in enumerate(flow.fresh)
+ if rank == s]
+ invoke(n-s, 'complement', s, batch)
+ for cut in flow.cuts:
+ e, value = flow.exit(cut)
+ invoke(e, 'exit', cut, [lift(b, value) for b in range(a)])
+
+ visit(root, (), tuple(('source', namespace, row) for row in range(rows[root].width)))
+ if len(leaves) != rows[root].leaves:
+ raise ValueError('literal expanded count')
+ return leaves, calls
diff --git a/research/compiler-permanent-home-dispatch/reference/FINITE-PRECOMPILATION.md b/research/compiler-permanent-home-dispatch/reference/FINITE-PRECOMPILATION.md
new file mode 100644
index 0000000000..4badb40f09
--- /dev/null
+++ b/research/compiler-permanent-home-dispatch/reference/FINITE-PRECOMPILATION.md
@@ -0,0 +1,313 @@
+# Finite precompilation of a mixed-target rule
+
+Status: constructive bridge under the precise native hypotheses below,
+independently audited in `../transfer-audit/AUDIT.md`. This is a written
+argument, not a formal proof or a completed integer-multiplication admission.
+The companion finite scheduler checks actual integer flow and ordering.
+The original immediate-normalization BIT interface failed hypothesis 3.
+`../bit/DELAYED-COVER-BRIDGE.md` supplies the distinct delayed-cover
+implementation, with a finite local-ring check and the native binding in
+`../bit/BIT-P3-NATIVE-BINDING.json`. Its fixed rational cover routes are a
+costed program schema, not dense coordinate gates in a plain native word.
+
+Substantial OpenAI assistance. Apache-2.0. The mixed-target asymptotic flow is
+Jacob Alan Sussman's Theorem 1G, PR4268, with the detailed proof at commit
+`563b4e6e913625637f36ba7869bf5fcd0dd4975a` of
+[`wht-power-saving-lean`](https://github.com/jacobalansussman/wht-power-saving-lean).
+The source, exact scheduling code and notices are preserved under `sources/`.
+The contribution proposed here is clearing the finite flow into a single
+uniform native supplier before applying the inherited outer theorem.
+
+## 1. What needs to be assumed
+
+Let a job of rank `s` apply a specified tensor operator to `s` selected
+coordinate blocks of one array, fixing all other coordinates. A block has
+an arbitrary positive tensor multiplicity `f`. A completed rank `s` job
+therefore acts on `s*f` axes. All productive inputs are arbitrary.
+
+Fix one mixed unit with productive targets `W_k` of ranks `k`, a chronological
+list of paid child ranks `r_j`, and a finite number of scalar and routing
+passes. These assumptions are required, separately from the moment inequality:
+
+1. **An all-column native word.** At every integer column count `c`, the unit
+ computes exactly its independent rank `k*c` output jobs. Its paid rounds
+ are rank `r_j*c` jobs in the stated order. All borrowed data return to the
+ declared endpoint, and owned storage is explicitly initialized and erased.
+ Its finite operation count is uniform in `c`.
+2. **Disjoint splitting and spectators.** A rank `a+b` job is a rank `a` job
+ followed by a rank `b` job on disjoint coordinates. The resulting programs
+ preserve arbitrary complete spectator fields and accept arbitrary data.
+3. **Whole-job adapters.** Any job passed between two units has an explicitly
+ priced, permitted embedding into its destination. For the intended complex
+ application these are fixed monomial binary address maps and unit quadratic
+ phases, together with role permutations. The adapters must work at every
+ tensor multiplicity. Rank equality by itself is insufficient.
+4. **Finite-program closure.** A finite composition of these words and
+ adapters is again a permitted finite supplier. Constantly many owned fields
+ may be supplied with their full cost and no productive output credit.
+ The eventual ordinary recursion must have the same arbitrary-input,
+ restoration, scalar and precision interface as the retained supplier.
+
+Put `m=max{k:W_k>0}`, `k_min=min{k:W_k>0}`, and
+`r_max=max{r_j}`. Require `r_max g*S`, keeps one
+external weight throughout the entire finite circuit, and lowers only its
+final rank-one leaves. All rational matchers, role routes and their inverses
+are fixed before choosing the odd prime and its exclusions. Every route
+uses complete equal-multiplicity cover fibers and the retained, costed row
+permutation primitive. This gives the same finite DAG argument in the
+rational-cover program category. The BIT binding supplies the actual native
+projectors; a rank count alone would not provide this implementation.
+
+## 2. Proposed conclusion
+
+Suppose the preceding hypotheses hold and the mixed balance has root
+`tau` in `(0,1)`:
+
+```
+sum_j r_j^tau = sum_k W_k k^tau.
+```
+
+For every `z` with `tau=2`, a fixed number `B_N` of productive arrays,
+and only rank-one paid children, whose number `P_N` satisfies
+
+```
+P_N < B_N * N^z.
+```
+
+Every productive output is the full rank-`N` job. The construction may have
+an enormous finite scalar word, role inventory and owned-storage requirement.
+Those quantities affect constants and the eventual input threshold. They are
+not omitted and are not credited as extra output jobs.
+
+If this uniform supplier is admitted under the retained native, precision and
+fixed-tape premises, the existing uniform recursion applies directly. A new
+dynamic RAM-to-Turing-machine simulation is not being assumed here.
+
+## 3. The integer lockstep flow at a fixed rank
+
+This is the part of Theorem 1G used by the compiler. At one fixed top rank
+`N`, its units, source jobs and exit jobs have integer multiplicities.
+For a multi-index `a` on the target types define
+
+```
+c(a) = product_k k^(a_k),
+u(a) = multinomial(|a|;a) * product_k W_k^(a_k).
+```
+
+The exact Pascal identity is
+
+```
+u(b) = sum_{k:b_k>0} W_k*u(b-e_k).
+```
+
+Let `G` be the largest `|a|` with `m*c(a)<=N`. A class is indexed by a
+sequence of paid rounds `s` of length `d<=G`; its dilation is
+`rho_s=product r_j`. It contains `u(a)` units at column `rho_s*c(a)` for
+each `a` with `|a|=G-d` and `m*rho_s*c(a)<=N`.
+
+For one parent paid round, the Pascal bijection matches its job copies to
+target roles of the child class, at exactly equal integer ranks. Missing
+demands are top sources. Separation ensures every parent job is consumed.
+The source ranks lie in `(N/m,N]`; only the deepest classes produce exit
+jobs, all strictly smaller than `N` once `N` is outside the finite base range.
+
+Process a class in word order. At round `j`, suspend every unit of that
+class, complete the entire child class fed by that round, and only then
+advance the parents to round `j+1`. This forbids a unit from requiring both
+an earlier and a later round of the same suspended parent. The resulting
+dependency graph is finite and acyclic. Its edges carry complete array jobs,
+not individual scalar values copied for free.
+
+These integer quantities exist before normalizing the sources to total
+weight one. Let `S_s` be the number of source jobs of rank `s`, let
+`S=sum_s S_s`, and let the ordered exit batches be `(e,t)` with `t` jobs
+of rank `e` each. This finite integer flow is the compiler input.
+
+## 4. Clear every batch denominator constructively
+
+Induct on the integer top rank `N`. For each smaller rank `e` the compiler
+has already constructed a uniform program on `B_e` arbitrary arrays,
+computing full rank `e` with `P_e` paid rank-one calls. For a sufficiently
+small rank use the ordinary sequential program: `B_e=1`, `P_e=e`.
+
+For the current flow choose an integer `a` divisible by every `B_e` needed
+for an exit and every `B_(N-s)` needed for a nonzero source remainder.
+The product of those finitely many positive integers is a valid choice;
+their least common multiple is a smaller optional choice. Set
+
+```
+B_N = a*S.
+```
+
+Assign `a*S_s` of the input arrays to each source rank `s`. On each of those
+arrays, first complete its `N-s` complementary coordinates using the
+already-compiled smaller uniform program. All such batches are integral
+because `a` is divisible by their program widths. This preliminary action
+commutes with the intended `s`-coordinate job and fixes its input coordinates.
+
+Make `a` copies of the integer lockstep flow. Route its source arrays to
+their exact input slots using permitted whole-array adapters. At a deepest
+exit batch, `a*t` is divisible by `B_e`; replace that batch by copies of
+the smaller uniform rank-`e` program. Restore its role ordering and adapters
+before resuming the suspended parent class. Execute the finite DAG in the
+lockstep order, and finally restore the original source-array ordering.
+
+Every array has now received its disjoint complementary job and source job,
+hence the full rank-`N` transform. No copied scalar input or blank helper is
+treated as another independent output. Every original array occurs exactly
+once as a source; interior target slots are jobs on those arrays, not new
+productive inputs.
+
+Induction removes all recursive calls: the only remaining paid children
+have rank one. Clearing denominators multiplies productive arrays and paid
+operations equally, so it preserves the per-array leaf count. In formulas,
+
+```
+P_N/B_N = (1/S) * [
+ sum_s S_s * (P_(N-s)/B_(N-s))
+ + sum_(ordered exit batches e,t) t * (P_e/B_e)
+].
+```
+
+Zero-rank terms vanish. Any plain rank-one exits are the ordinary base
+program. Scalar and routing passes have their own analogous nonnegative
+count and must be included in the asymptotic cost used to choose `N`.
+
+This construction uses full integer batches; it does not assume that
+fractional pieces of a physical array can be routed at zero cost. Its exact
+replication factors can be impractically large, which is acceptable for a
+fixed finite supplier existence statement but must be disclosed.
+
+## 5. Why some fixed N has the required saving
+
+The independent audit sharpened this step to a direct count of paid leaves.
+It does not require a running-time comparison between a RAM flow and native
+tapes. Let `L(n)=P_n/B_n`, let `w_s=S_s/S`, and let `x_e` be the exit counts
+normalized by the number S of source arrays. The actual integer compiler
+satisfies
+
+```
+L(n) = sum_s w_s L(n-s) + sum_e x_e L(e),
+sum_s w_s = 1,
+sum_e x_e e^tau = sum_s w_s s^tau.
+```
+
+The last equality follows by canceling every internal matched job in the
+exact tau-potential balance. The source ranks satisfy `n/m0`, concavity gives
+
+```
+n^z0 - sum_s w_s (n-s)^z0 >= eta * sum_s w_s s^z0.
+```
+
+Indeed, for `t=s/n` in `[1/m,1]`,
+`1-(1-t)^z0 >= z0*t >= eta*t^z0`. For every sufficiently large n the
+exit coefficient is less than `eta/2`. Every complement and exit has
+smaller rank than n, so strong induction on the exact recurrence proves
+`L(n)<=A*n^z0`, with finite A chosen to cover the smaller ranks. Eventually
+`L(N)=2, J ordered paid positions
+of positive ranks r(j)=k_max be the actual
+ambient cap. A need not be a target rank. At n>=A put
+
+`G_n=max{g:A*k_min^g<=n}`.
+
+Units have the inherited descriptors `(p,alpha,v)`, with
+`|p|+|alpha|=G_n`, `vk_max, repeated roles/sites, coincident products,
+cross-replica complements, inherited banks and ungrouped native role lists.
+It also compares default-library integers with the unchanged #7345 generator.
+
+A large singleton-rank fixture has 68,719,476,736 cuts. Base-eight digits and
+the last owned paid site give a distinct direct oracle for selected queries
+without expansion. Another fixture queries a library with huge replication
+and row counts. These formal metadata rules are not asserted realizable
+native suppliers. Executed coverage is recorded exactly in `VALIDATION.json`.
+
+Controls detect lost paid multiplicity, merged cuts/replicas, dropped owned
+call namespaces, wrong totals/axes/returns, invalid zero complements and
+range errors. A same-owner/different-cut fixture refutes the stronger global
+leaf-owner injection. Universal force comes from the interval, identity
+and rank-induction proofs, not extrapolation from finite checks.
+
+This closes a recursive logical-emission obligation: counts and source ports
+compose into the complete ordered rank-one leaf projection with persistent
+field names and inverse locations. The selected actual role manifest/library,
+full scalar/phase/adapter stream, physical gather/return, numerical endpoints,
+owned-storage realization and complete fixed-tape dispatcher remain open.
+All five selected assumptions and kappa remain unchanged.
diff --git a/research/compiler-permanent-home-dispatch/review/AUTHOR-REPLAY.txt b/research/compiler-permanent-home-dispatch/review/AUTHOR-REPLAY.txt
new file mode 100644
index 0000000000..2a472de5d2
--- /dev/null
+++ b/research/compiler-permanent-home-dispatch/review/AUTHOR-REPLAY.txt
@@ -0,0 +1 @@
+PASS_COMPILER_PERMANENT_HOME_DISPATCH 33 cases; 10 rejecting controls
diff --git a/research/compiler-permanent-home-dispatch/review/C-FIXTURE-RESULT.txt b/research/compiler-permanent-home-dispatch/review/C-FIXTURE-RESULT.txt
new file mode 100644
index 0000000000..e98e358092
--- /dev/null
+++ b/research/compiler-permanent-home-dispatch/review/C-FIXTURE-RESULT.txt
@@ -0,0 +1,2 @@
+PASS_COMPILER_DISPATCH_FIXTURE [{'first_steps': 371, 'second_steps': 321, 'initial_peaks': (10, 1, 1, 1), 'retained_peaks': (14, 5, 5, 5), 'nonprimitive_allowance': 2400, 'states': 83}, {'first_steps': 371, 'second_steps': 321, 'initial_peaks': (10, 1, 1, 1), 'retained_peaks': (14, 5, 5, 5), 'nonprimitive_allowance': 2400, 'states': 83}]
+ABI_PACKET=^010|$; origin_minus_one=rejected
diff --git a/research/compiler-permanent-home-dispatch/review/C-REVIEW.md b/research/compiler-permanent-home-dispatch/review/C-REVIEW.md
new file mode 100644
index 0000000000..903478d3b0
--- /dev/null
+++ b/research/compiler-permanent-home-dispatch/review/C-REVIEW.md
@@ -0,0 +1,49 @@
+# Targeted review: permanent-home dispatcher
+
+Reviewed only:
+
+- worker-b/research/compiler-permanent-home-dispatch/PROOF.md
+- worker-b/research/compiler-permanent-home-dispatch/emit.py
+- worker-b/research/compiler-permanent-home-dispatch/tape_graph.py
+
+SHA-256 pins:
+
+- PROOF.md: 308e74fdfd59901bcff784c4c299d892ae2637043544271c9e46fbed4516abea
+- emit.py: 762c6c3e094e300bbe67de80597c3557413d4047c040ee5feaa4b925873c9a58
+- tape_graph.py: 7d3cee3e79ba5fe410e1a6b5f4cf6a2fbe5e274f838b798cd8860344ff258b54
+
+## Decision and scope
+
+**Conditional pass** for the stated permanent-home dispatcher bound under the explicit supplied-primitive, common-format, typed-lifetime, reservation, and history premises. No selected native semantic result is established here.
+
+The parent supplied one ABI fact for comparison: native A uses a guard at operand-origin minus one. The checked literal tape model has no cell there. The general theorem must therefore restrict supplied services to the compiler ABI or include a charged representation/entry adapter. This is a real admission condition for applying the dispatcher to native A, not a contradiction to the conditional theorem.
+
+## Requested claims
+
+**Services are supplied primitives.** PROOF §2 items 3–5 require the complete native word and finite catalogue of uniform all-format primitive graphs, with complete service tariffs T_mu(F,theta). Every scalar, phase, route, INIT/CLEAR, conversion, adapter and caller action must occur in a service segment and in R; no rank-based inference supplies an unimplemented operation. emit.py accepts service names/callback results as finite compiler data. It does not prove their semantics or charge an arbitrary callback, so the uniformity and charged-descriptor restrictions in §2 are necessary premises.
+
+**Rank-N source expansion is finite.** Emitter.visit recursively calls child/visit for positive complement and exit calls, and the base case emits n sequential leaves for 1<=n SimpleNamespace:
+ return SimpleNamespace(kind=kind, service=service, owners=owners, context=())
+
+
+base = [
+ event("allocate", "ZERO", ("O",)),
+ event("native", "NOT", ("O",)),
+ event("native", "XOR", ("A", "B")),
+ event("release", "ZERO", ("O",)),
+]
+with_call_receipts = [event("call", "", ("A", "B", "O")), *base,
+ event("return", "", ("A", "B", "O"))]
+owners = ("A", "B", "O")
+reports = []
+
+for events in (base, with_call_receipts):
+ graph = tg.compile_graph(events, owners, productive_count=2)
+ tapes = tg.initial_tapes(["010", "101"], home_count=3)
+ initial_peaks = tuple(t.peak for t in tapes)
+
+ first_steps = graph.run(tapes, limit=1_000_000)
+ first = tg.decoded(tapes, 3)
+ first_peaks = tuple(t.peak for t in tapes)
+
+ second_steps = graph.run(tapes, limit=1_000_000, start=graph.execution_start)
+ second = tg.decoded(tapes, 3)
+ second_peaks = tuple(t.peak for t in tapes)
+
+ assert first == ("010", "111", "000"), first
+ assert second == ("010", "101", "000"), second
+ assert first_peaks == second_peaks
+ assert first_peaks[0] == 3 * (3 + 1) + 2
+ assert first_peaks[1:] == (3 + 2, 3 + 2, 3 + 2)
+
+ # R=4 services, B=2, O=1, K=3, b=2, F=3. The fixture's total
+ # literal transition count (including its synthetic primitive graphs)
+ # is below the claimed nonprimitive allowance alone.
+ R, B, O, b, F = 4, 2, 1, 2, 3
+ K = B + O
+ nonprimitive_allowance = 16 * (R + 1) * (K + b + 1) * (F + 2)
+ assert first_steps <= nonprimitive_allowance, (first_steps, nonprimitive_allowance)
+
+ reports.append({
+ "first_steps": first_steps,
+ "second_steps": second_steps,
+ "initial_peaks": initial_peaks,
+ "retained_peaks": first_peaks,
+ "nonprimitive_allowance": nonprimitive_allowance,
+ "states": len(graph.rules),
+ })
+
+assert reports[0]["first_steps"] == reports[1]["first_steps"]
+assert reports[0]["second_steps"] == reports[1]["second_steps"]
+
+# ABI boundary: origin is the '^' cell at relative zero, data starts to its
+# right, and the Tape implementation rejects relative origin-1 access.
+packet = tg.initial_tapes(["010"], home_count=1)[0]
+assert packet.contents() == "^010|$"
+try:
+ tg.Tape().move(-1)
+except ValueError as exc:
+ assert "crossed permanent origin" in str(exc)
+else:
+ raise AssertionError("relative origin-1 movement unexpectedly allowed")
+
+print("PASS_COMPILER_DISPATCH_FIXTURE", reports)
+print("ABI_PACKET=^010|$; origin_minus_one=rejected")
diff --git a/research/compiler-permanent-home-dispatch/review/REMOTE-SOURCE-BINDING.json b/research/compiler-permanent-home-dispatch/review/REMOTE-SOURCE-BINDING.json
new file mode 100644
index 0000000000..c08afc24f0
--- /dev/null
+++ b/research/compiler-permanent-home-dispatch/review/REMOTE-SOURCE-BINDING.json
@@ -0,0 +1,53 @@
+{
+ "marker": "PASS_REMOTE_COMPILER_SOURCE_BINDING",
+ "files": [
+ {
+ "path": "inputs/leaf_index.py",
+ "commit": "81f0b0b9a920bd1c9da583cbc3612efd5e75ea94",
+ "blob": "946fcf914ad49ab30b190d51247c2d53790263fb",
+ "remote_matches": true
+ },
+ {
+ "path": "inputs/literal_oracle.py",
+ "commit": "81f0b0b9a920bd1c9da583cbc3612efd5e75ea94",
+ "blob": "cd61ca640fb949a83fd5f48d174533060efe7996",
+ "remote_matches": true
+ },
+ {
+ "path": "inputs/inputs/groups.py",
+ "commit": "81f0b0b9a920bd1c9da583cbc3612efd5e75ea94",
+ "blob": "bbf54125523bdf8cd6fd7239938a0a42f53a5344",
+ "remote_matches": true
+ },
+ {
+ "path": "inputs/inputs/inputs/source_index/source_index.py",
+ "commit": "81f0b0b9a920bd1c9da583cbc3612efd5e75ea94",
+ "blob": "4e3cb2a53fb1c5c90e01202eb4e51a559c8727f7",
+ "remote_matches": true
+ },
+ {
+ "path": "inputs/inputs/inputs/source_index/inputs/pascal_codec.py",
+ "commit": "81f0b0b9a920bd1c9da583cbc3612efd5e75ea94",
+ "blob": "2fb4426cc821a7e029e5c697787e235c79b4e756",
+ "remote_matches": true
+ },
+ {
+ "path": "inputs/inputs/library.py",
+ "commit": "81f0b0b9a920bd1c9da583cbc3612efd5e75ea94",
+ "blob": "e1e34aa0e6ee47999784c834ede4f8c9998c5647",
+ "remote_matches": true
+ },
+ {
+ "path": "reference/PROOF.md",
+ "commit": "81f0b0b9a920bd1c9da583cbc3612efd5e75ea94",
+ "blob": "d255ba9a273f672eb1366f93b1a7861c3b26e385",
+ "remote_matches": true
+ },
+ {
+ "path": "reference/FINITE-PRECOMPILATION.md",
+ "commit": "81f0b0b9a920bd1c9da583cbc3612efd5e75ea94",
+ "blob": "4badb40f0919c515823cb07e44c6470d4d6469ca",
+ "remote_matches": true
+ }
+ ]
+}
diff --git a/research/compiler-permanent-home-dispatch/review/ROOT-RESULT.json b/research/compiler-permanent-home-dispatch/review/ROOT-RESULT.json
new file mode 100644
index 0000000000..2a6c7d5f81
--- /dev/null
+++ b/research/compiler-permanent-home-dispatch/review/ROOT-RESULT.json
@@ -0,0 +1,48 @@
+{
+ "marker": "PASS_ROOT_COMPILER_PHYSICAL_REVIEW",
+ "base": "e54523517d0f03e58352e647c403a5af3e525a57",
+ "seed": 20261113,
+ "states": 2257,
+ "events": 91,
+ "B": 4,
+ "K": 8,
+ "receipts": [
+ {
+ "F": 1,
+ "steps": 6722,
+ "repeat_steps": 6660,
+ "history": 27
+ },
+ {
+ "F": 2,
+ "steps": 9535,
+ "repeat_steps": 9450,
+ "history": 38
+ },
+ {
+ "F": 7,
+ "steps": 23600,
+ "repeat_steps": 23400,
+ "history": 93
+ },
+ {
+ "F": 17,
+ "steps": 51730,
+ "repeat_steps": 51300,
+ "history": 203
+ },
+ {
+ "F": 73,
+ "steps": 209258,
+ "repeat_steps": 207540,
+ "history": 819
+ }
+ ],
+ "independence": "separate sparse infinite-tape interpreter and integer word oracle; chronological source equality is separate author matched-slot proof",
+ "coverage": "fixture primitives and actual emitted small compiler trace; no full scientific primitive or selected root execution",
+ "hashes": {
+ "emit.py": "762c6c3e094e300bbe67de80597c3557413d4047c040ee5feaa4b925873c9a58",
+ "tape_graph.py": "7d3cee3e79ba5fe410e1a6b5f4cf6a2fbe5e274f838b798cd8860344ff258b54",
+ "SOURCES.json": "ea1dca983da5de89dc8309f1446d67ebed52467f3d6aff339690479940a55ba5"
+ }
+}
diff --git a/research/compiler-permanent-home-dispatch/review/ROOT-REVIEW.md b/research/compiler-permanent-home-dispatch/review/ROOT-REVIEW.md
new file mode 100644
index 0000000000..4f9387fe08
--- /dev/null
+++ b/research/compiler-permanent-home-dispatch/review/ROOT-REVIEW.md
@@ -0,0 +1,49 @@
+# Orchestration review and publication changes
+
+Canonical base: e54523517d0f03e58352e647c403a5af3e525a57.
+
+The complete source-codec checkpoint expansion and physical route were reviewed
+under the stated primitive, native-word and lifetime premises. No numerical
+native semantics or selected 1920-product word is inferred from the fixtures.
+The finite unrolled calls are compile-time events, not a zero-cost runtime stack.
+
+The physical graph has complete reservation and gather/return/erase loops.
+A separate sparse infinite-tape interpreter with exact integer word operations
+passed fresh rank-6 traces at F=1,2,7,17,73, signed distinct tape origins, opaque
+exterior sentinels and same-owner reuse. ROOT-RESULT.json records the actual
+source hashes, steps and all head visits. This independent interpreter does
+not use Graph.run or the author's string-operation oracle. It does use the
+emitted event trace; the independent matched-slot chronology check is separate.
+
+The second agent review in C-REVIEW.md checked the finite proof and flagged the
+primitive ABI boundary. The publication proof explicitly requires '^' origins,
+'|' delimiters and nonnegative relative positions for its literal constructor;
+other native origins/guards/formats require an included paid adapter. This
+clarification is the only post-freeze scientific proof edit. It discharges the
+review's requested premise, not the actual native adaptation obligation.
+The actual event/graph implementations are unchanged from the frozen worker.
+
+Root review also required raw zero capacity to be distinguished from valid typed
+headers, fixed compiler columns from varying input parameters, complete entry
+history to be retained, and general fixed-b reasoning from checked b<=2 code.
+These restrictions are present in the final proof and README. The proof's loose
+16(R+1)(K+b+1)(F+2) dispatcher allowance pays both complete HOME passes and
+returns, operand preparation/erasure, and the initial reservation. All service
+costs and prior storage remain separate summands, without output-width credit
+for private homes.
+
+The two review scripts were adapted only to package-relative paths. The second
+review's source hash still pins the same tape_graph.py; its assertions explicitly
+refuse -O. Root check uses explicit ValueError gates and accepts optimized Python.
+Normal author verification was also repeated on the publication snapshot.
+
+Reproduce from the package directory:
+
+```sh
+python3 -I -W error -B review/check_physical.py
+python3 -I -W error -B review/C-check_fixture.py
+python3 -I -W error -B verify.py
+```
+
+Prepared by the Astra orchestration agent with substantial OpenAI Codex assistance.
+The independent agent reviews are not human review or proof-kernel acceptance.
diff --git a/research/compiler-permanent-home-dispatch/review/check_physical.py b/research/compiler-permanent-home-dispatch/review/check_physical.py
new file mode 100644
index 0000000000..657fc25396
--- /dev/null
+++ b/research/compiler-permanent-home-dispatch/review/check_physical.py
@@ -0,0 +1,96 @@
+"""Independent sparse infinite-tape interpretation and integer payload oracle."""
+from pathlib import Path
+import hashlib,json,random,sys
+P=Path(__file__).resolve().parents[1]
+sys.path.insert(0,str(P))
+from emit import Emitter,L
+from inputs import literal_oracle as O
+from tape_graph import compile_graph
+
+def require(ok,message):
+ if not ok:raise ValueError(message)
+
+def interpret(graph,initial,origins,entry=None,existing=None):
+ if existing is None:
+ tapes=[{o+i:c for i,c in enumerate(s)} for o,s in zip(origins,initial)]
+ heads=list(origins)
+ visited=[set(range(o,o+len(s))) for o,s in zip(origins,initial)]
+ else:tapes,heads,visited=existing
+ sentinels=[o+100000 for o in origins]
+ for tape,p in zip(tapes,sentinels):tape[p]='1'
+ pc=graph.start if entry is None else entry;steps=0
+ while pc!='HALT':
+ applicable=[]
+ for rule in graph.rules[pc]:
+ if all(tapes[t].get(heads[t],'_')==c for t,c in rule.tests):applicable.append(rule)
+ require(len(applicable)==1,'transition failed or was ambiguous')
+ rule=applicable[0]
+ for t,c in rule.writes:tapes[t][heads[t]]=c
+ for t,d in rule.moves:
+ require(d in (-1,0,1),'nonlocal head move')
+ heads[t]+=d;visited[t].add(heads[t])
+ pc=rule.target;steps+=1
+ require(steps<2000000,'bounded review execution exhausted')
+ require(heads==origins,'heads not restored')
+ for tape,p in zip(tapes,sentinels):require(tape[p]=='1','opaque exterior changed')
+ for tape,o,p in zip(tapes[1:],origins[1:],sentinels[1:]):
+ require(tape.get(o)=='^','origin marker changed')
+ require(all(c=='_' for x,c in tape.items() if x not in (o,p)),'scratch not retired')
+ return steps,(tapes,heads,visited)
+
+def values_oracle(events,homes,values,width):
+ value=dict(zip(homes,values));mask=(1<>=1
+ value[e.owners[0]]=r
+ else:raise ValueError('unknown primitive')
+ return [value[o] for o in homes]
+
+def physical_values(state,origin,k,width):
+ tape=state[0][0];pos=origin+1;out=[]
+ require(tape[origin]=='^','HOME marker')
+ for _ in range(k):
+ v=0
+ for _ in range(width):
+ c=tape.get(pos,'_');require(c in '01','binary field');v=2*v+int(c);pos+=1
+ require(tape.get(pos)=='|','field delimiter');pos+=1;out.append(v)
+ require(tape.get(pos)=='$','HOME end')
+ return out
+
+def main():
+ rng=random.Random(20261113)
+ roles=(('x',2),('y',3));rounds=((1,'x'),(1,'bank'));owned=('bank',)
+ rows,flows=O.library(roles,rounds,owned,3,6)
+ c=L.Compiler(L.C.Rule(roles,rounds,owned,3),rows,'root-independent')
+ segments=((('XOR',('x','bank')),),(('XOR',('bank','y')),('NOT',('bank',))),(('XOR',('y','bank')),('NOT',('x',))))
+ events,homes=Emitter(c,segments,lambda _: 'REV').compile()
+ b=rows[6].width;k=len(homes)
+ graph=compile_graph(events,homes,productive_count=b)
+ for rules in graph.rules.values():
+ for rule in rules:
+ require(all(0<=t<4 and s in '_01^|$' for t,s in rule.tests+rule.writes),'finite tape/alphabet set')
+ require(all(d in (-1,0,1) for t,d in rule.moves),'unit movements')
+ receipts=[]
+ for width in (1,2,7,17,73):
+ values=[rng.randrange(1<= len(self.cells):
+ self.cells.extend('_' for _ in range(self.head+1-len(self.cells)))
+ self.cells[self.head] = value
+ self.peak = max(self.peak, len(self.cells))
+
+ def move(self, delta):
+ if delta not in (-1,0,1):
+ raise ValueError('one physical transition moves at most one cell')
+ if self.head+delta < 0:
+ raise ValueError('head crossed permanent origin')
+ self.head += delta
+ self.visited.add(self.head)
+ self.peak = max(self.peak,self.head+1)
+
+ def contents(self):
+ return ''.join(self.cells)
+
+
+@dataclass(frozen=True)
+class Rule:
+ tests: tuple
+ writes: tuple
+ moves: tuple
+ target: str
+
+
+class Graph:
+ def __init__(self):
+ self.rules = {}
+ self.serial = 0
+ self.start = None
+ self.execution_start = None
+ self.checkpoints = {}
+
+ def state(self, stem):
+ result = f'{stem}.{self.serial}'
+ self.serial += 1
+ return result
+
+ def add(self, state, target, tests=(), writes=(), moves=()):
+ self.rules.setdefault(state, []).append(Rule(tuple(tests), tuple(writes),
+ tuple(moves), target))
+
+ def jump(self, target, moves=()):
+ state = self.state('jump')
+ self.add(state, target, moves=moves)
+ return state
+
+ def rewind(self, tape, target, erase=False):
+ state = self.state('erase' if erase else 'rewind')
+ self.add(state, target, tests=((tape, '^'),))
+ for symbol in ALPHABET.replace('^', ''):
+ self.add(state, state, tests=((tape, symbol),),
+ writes=((tape, '_'),) if erase else (), moves=((tape, -1),))
+ return state
+
+ def validate(self):
+ # Exact symbolic determinism: two patterns overlap iff every shared
+ # tested tape has the same symbol. No wildcard expansion is needed.
+ for state, rules in self.rules.items():
+ for i, a in enumerate(rules):
+ if a.target not in self.rules and a.target != 'HALT':
+ raise ValueError('undefined graph continuation')
+ for b in rules[:i]:
+ left, right = dict(a.tests), dict(b.tests)
+ if all(left[t] == right[t] for t in left.keys() & right.keys()):
+ raise ValueError('nondeterministic graph state '+state)
+
+ def run(self, tapes, limit=10000000, checkpoint=None, start=None):
+ state, steps = self.start if start is None else start, 0
+ while state != 'HALT':
+ if checkpoint and state in self.checkpoints:
+ checkpoint(self.checkpoints[state], tapes)
+ if steps >= limit:
+ raise ValueError('literal graph execution capacity')
+ matches = [r for r in self.rules[state]
+ if all(tapes[t].read() == value for t, value in r.tests)]
+ if len(matches) != 1:
+ raise ValueError('malformed tape or nondeterministic transition '+state)
+ rule, = matches
+ for tape, value in rule.writes:
+ tapes[tape].write(value)
+ for tape, delta in rule.moves:
+ tapes[tape].move(delta)
+ state, steps = rule.target, steps+1
+ if checkpoint and 'HALT' in self.checkpoints:
+ checkpoint(self.checkpoints['HALT'], tapes)
+ return steps
+
+
+def service(graph, name, arity, target):
+ """Four small supplied primitive graphs used ONLY by finite fixtures.
+
+ Real scientific scalar/route/leaf graphs are still premises of the theorem.
+ Tapes 1,2 are operands; tape 3 is retained private primitive scratch.
+ """
+ if name == 'REV':
+ if arity != 1:
+ raise ValueError('unary reversal')
+ cleanup = graph.rewind(3, target, erase=True)
+ back_operand = graph.rewind(1, cleanup)
+ copy = graph.state('reverse-install')
+ graph.add(copy, back_operand, tests=((3, '|'),), writes=((1, '|'),))
+ for bit in '01':
+ graph.add(copy, copy, tests=((3, bit),), writes=((1, bit),),
+ moves=((1, 1), (3, 1)))
+ install = graph.jump(copy, ((1, 1), (3, 1)))
+ rewind_scratch = graph.rewind(3, install)
+ reverse = graph.state('reverse-copy')
+ graph.add(reverse, rewind_scratch, tests=((1, '^'),), writes=((3, '|'),))
+ for bit in '01':
+ graph.add(reverse, reverse, tests=((1, bit),), writes=((3, bit),),
+ moves=((1, -1), (3, 1)))
+ begin_reverse = graph.jump(reverse, ((1, -1), (3, 1)))
+ seek = graph.state('reverse-seek')
+ graph.add(seek, begin_reverse, tests=((1, '|'),))
+ for bit in '01':
+ graph.add(seek, seek, tests=((1, bit),), moves=((1, 1),))
+ return graph.jump(seek, ((1, 1),))
+ if name == 'FIRST':
+ if arity != 1:
+ raise ValueError('unary leaf fixture')
+ at = graph.state('first-bit')
+ for bit in '01':
+ graph.add(at, target, tests=((1, bit),), writes=((1, str(1-int(bit))),),
+ moves=((1, -1),))
+ return graph.jump(at, ((1, 1),))
+ if name not in ('ZERO', 'NOT', 'XOR') or arity != (2 if name == 'XOR' else 1):
+ raise ValueError('missing supplied primitive graph')
+ cleanup = target
+ for tape in range(arity, 0, -1):
+ cleanup = graph.rewind(tape, cleanup)
+ loop = graph.state('primitive-'+name)
+ graph.add(loop, cleanup, tests=tuple((t, '|') for t in range(1, arity+1)))
+ if name == 'XOR':
+ for a in '01':
+ for b in '01':
+ graph.add(loop, loop, tests=((1, a), (2, b)),
+ writes=((2, str(int(a)^int(b))),), moves=((1, 1), (2, 1)))
+ else:
+ for bit in '01':
+ graph.add(loop, loop, tests=((1, bit),),
+ writes=((1, '0' if name == 'ZERO' else str(1-int(bit))),),
+ moves=((1, 1),))
+ return graph.jump(loop, tuple((t, 1) for t in range(1, arity+1)))
+
+
+def scan(graph, homes, selected, gather, target):
+ """Unroll finite home order; scan arbitrary F only by field delimiters."""
+ next_state = graph.rewind(0, target)
+ for home in range(homes-1, -1, -1):
+ work = selected.get(home)
+ after = next_state
+ loop = graph.state('gather' if gather else 'return')
+ if work:
+ graph.add(loop, after, tests=((0, '|'),) if gather else ((0, '|'), (work, '|')),
+ writes=((work, '|'),) if gather else (), moves=((0, 1),))
+ else:
+ graph.add(loop, after, tests=((0, '|'),), moves=((0, 1),))
+ for bit in '01':
+ if not work:
+ graph.add(loop, loop, tests=((0, bit),), moves=((0, 1),))
+ elif gather:
+ graph.add(loop, loop, tests=((0, bit),), writes=((work, bit),),
+ moves=((0, 1), (work, 1)))
+ else:
+ for output in '01':
+ graph.add(loop, loop, tests=((0, bit), (work, output)),
+ writes=((0, output),), moves=((0, 1), (work, 1)))
+ next_state = graph.jump(loop, ((work, 1),)) if work else loop
+ return graph.jump(next_state, ((0, 1),))
+
+
+def reserve(graph, extra_homes, target):
+ """Append full zero homes by copying first-field extent, without F arithmetic."""
+ if not extra_homes:
+ return target
+ return_home = graph.rewind(0, target)
+ finish = graph.state('reserve-finish')
+ graph.add(finish, return_home, writes=((0, '$'),))
+ next_state = graph.rewind(3, finish, erase=True)
+ for position in range(extra_homes-1,-1,-1):
+ loop = graph.state('reserve-zero-home')
+ graph.add(loop, loop, tests=((3, '0'),), writes=((0, '0'),), moves=((0, 1),(3, 1)))
+ graph.add(loop, next_state, tests=((3, '|'),), writes=((0, '|'),), moves=((0, 1),))
+ begin = graph.jump(loop, ((3, 1),))
+ next_state = graph.rewind(3, begin) if position else begin
+ seek = graph.state('reserve-seek-end')
+ graph.add(seek, next_state, tests=((0, '$'),))
+ for symbol in '^01|':
+ graph.add(seek, seek, tests=((0, symbol),), moves=((0, 1),))
+ rewind_template = graph.rewind(3, seek)
+ rewind_home = graph.rewind(0, rewind_template)
+ copy = graph.state('reserve-copy-extent')
+ for bit in '01':
+ graph.add(copy, copy, tests=((0, bit),), writes=((3, '0'),), moves=((0, 1),(3, 1)))
+ graph.add(copy, rewind_home, tests=((0, '|'),), writes=((3, '|'),))
+ return graph.jump(copy, ((0, 1),(3, 1)))
+
+
+def compile_graph(events, owners, primitive=service, productive_count=None):
+ """Return a real transition graph on four tapes for the fixture family.
+
+ General theorem: replace primitive by supplied finite graphs using m
+ scratch tapes; tape count is 1+b+m, independently of Q,K,F.
+ """
+ graph, next_state = Graph(), 'HALT'
+ home_index = {owner: i for i, owner in enumerate(owners)}
+ if len(home_index) != len(owners):
+ raise ValueError('permanent home owner identities must be distinct')
+ for index in range(len(events)-1, -1, -1):
+ event = events[index]
+ if not event.service:
+ continue
+ graph.checkpoints[next_state] = index
+ if not 1 <= len(event.owners) <= 2 or len(set(event.owners)) != len(event.owners):
+ raise ValueError('bounded distinct physical operands')
+ selected = {home_index[owner]: i+1 for i, owner in enumerate(event.owners)}
+ cleanup = next_state
+ for tape in range(len(event.owners), 0, -1):
+ cleanup = graph.rewind(tape, cleanup, erase=True)
+ scatter = scan(graph, len(owners), selected, False, cleanup)
+ invoke = primitive(graph, event.service, len(event.owners), scatter)
+ origin = invoke
+ for tape in range(len(event.owners), 0, -1):
+ origin = graph.rewind(tape, origin)
+ next_state = scan(graph, len(owners), selected, True, origin)
+ graph.execution_start = next_state
+ productive_count = len(owners) if productive_count is None else productive_count
+ if not 1 <= productive_count <= len(owners):
+ raise ValueError('positive productive count within permanent bank')
+ graph.start = reserve(graph,len(owners)-productive_count,next_state)
+ graph.validate()
+ return graph
+
+
+def initial_tapes(payloads, home_count, preformatted=False):
+ if not payloads or len({len(x) for x in payloads}) != 1 or not payloads[0]:
+ raise ValueError('positive common full field format')
+ if len(payloads) > home_count or any(set(x)-set('01') for x in payloads):
+ raise ValueError('binary productive bank in declared homes')
+ # Only productive fields are supplied. New private extents are prepared
+ # by the literal reserve graph. Optional preformatting is for fault tests.
+ fields = list(payloads)
+ if preformatted:
+ fields += ['0'*len(payloads[0])]*(home_count-len(payloads))
+ return [Tape('^'+'|'.join(fields)+'|$'), Tape(), Tape(), Tape()]
+
+
+def decoded(tapes, home_count):
+ raw = tapes[0].contents()
+ if raw[0] != '^' or not raw.endswith('|$'):
+ raise ValueError('home boundaries changed')
+ fields = tuple(raw[1:-2].split('|'))
+ if len(fields) != home_count:
+ raise ValueError('permanent home count changed')
+ return fields
diff --git a/research/compiler-permanent-home-dispatch/verify.py b/research/compiler-permanent-home-dispatch/verify.py
new file mode 100644
index 0000000000..b59a9aeab8
--- /dev/null
+++ b/research/compiler-permanent-home-dispatch/verify.py
@@ -0,0 +1,235 @@
+"""Exact source, chronology, literal tape and corruption checks. Apache-2.0."""
+from dataclasses import replace
+from hashlib import sha256
+import json
+from pathlib import Path
+import sys
+import shutil
+import subprocess
+import tempfile
+
+HERE = Path(__file__).resolve().parent
+sys.path.insert(0,str(HERE))
+from emit import Emitter, L
+import independent as I
+from tape_graph import compile_graph, initial_tapes, decoded, Tape
+
+def require(condition, message):
+ if not condition:
+ raise ValueError(message)
+
+
+def frozen():
+ source = json.loads((HERE/'SOURCES.json').read_text())
+ for entry in source['files']:
+ data = (HERE/entry['local']).read_bytes()
+ require(sha256(data).hexdigest() == entry['sha256'] and len(data) == entry['bytes'],
+ 'changed frozen scientific input')
+
+
+def script(roles, rounds, owned):
+ first, last, bank = roles[0][0], roles[-1][0], owned[0]
+ segments = [(('XOR', (first, bank)),)]
+ for j in range(len(rounds)):
+ segments.append((('XOR', (bank, last)), ('NOT', (bank,))))
+ return tuple(segments)
+
+
+def fixture(roles, rounds, ambient, root, field_width, adapter=lambda _: 'REV'):
+ owned = ('bank',)
+ rows, flows = I.O.library(roles, rounds, owned, ambient, root)
+ compiler = L.Compiler(L.C.Rule(roles, rounds, owned, ambient), rows, 'dispatch')
+ segments = script(roles, rounds, owned)
+ events, homes = Emitter(compiler, segments, adapter).compile()
+ payloads = tuple(''.join('1' if ((row+1)*(i+3)+i*i+row//2) % 5 < 2 else '0'
+ for i in range(field_width)) for row in range(rows[root].width))
+ expected_events, expected_homes, expected_values = I.run(
+ roles, rounds, owned, ambient, root, rows, flows, segments, adapter, payloads)
+ actual_events = tuple((e.kind, e.service, I.normalize(e.owners), I.normalize(e.context))
+ for e in events)
+ require(actual_events == expected_events, 'full native/checkpoint/frame chronology')
+ require(I.normalize(homes) == expected_homes, 'permanent home owner correspondence')
+ leaves = [e for e in events if e.kind == 'leaf']
+ require(len(leaves) == rows[root].leaves, 'actual compiler leaf census')
+ for j, event in enumerate(leaves):
+ leaf = compiler.locate(j)
+ require(event.owners == (leaf.field,) and event.context == (leaf.calls, leaf.rank, leaf.axis),
+ 'exact frozen chronological leaf projection')
+ graph = compile_graph(events, homes, productive_count=len(payloads))
+ tapes = initial_tapes(payloads, len(homes))
+ reserved = sum(t.peak for t in tapes)
+ initial = payloads+('0'*field_width,)*(len(homes)-len(payloads))
+ direct = {I.normalize(owner): bits for owner,bits in zip(homes,initial)}
+ audited_until, boundaries = -1, 0
+ def checkpoint(index, actual):
+ nonlocal audited_until, boundaries
+ for event in events[audited_until+1:index+1]:
+ I.apply(direct,event.service,I.normalize(event.owners))
+ audited_until, boundaries = index, boundaries+1
+ require(decoded(actual,len(homes)) == tuple(direct[I.normalize(o)] for o in homes),
+ 'physical boundary disagrees with exact service and parked spectators')
+ require(all(t.head == 0 for t in actual), 'interior service did not return every head')
+ require(all(set(t.contents()[1:]) <= {'_'} for t in actual[1:]),
+ 'interior service retained an unerased physical working copy')
+ steps = graph.run(tapes, checkpoint=checkpoint)
+ require(decoded(tapes, len(homes)) == expected_values, 'physical payload delivery')
+ require(all(t.head == 0 for t in tapes), 'full physical head return')
+ require(all(set(t.contents()[1:]) <= {'_'} for t in tapes[1:]), 'scratch erased physically')
+ require(all(value == '0'*field_width for value in expected_values[len(payloads):]),
+ 'all private homes retired at the full root extent')
+ require(tapes[0].peak == len(homes)*(field_width+1)+2, 'home backing retained exactly')
+ require(all(t.peak <= field_width+2 for t in tapes[1:]), 'fixed work bank backing')
+ q = sum(bool(e.service) for e in events)
+ require(boundaries == q, 'all physical service returns inspected')
+ require(steps <= 64*(q+1)*(len(homes)+1)*(field_width+2), 'universal fixture step envelope')
+ require(len(graph.rules) <= 64*(q+1)*(len(homes)+1), 'output graph state envelope')
+ receipt = {'roles':roles,'rounds':rounds,'ambient':ambient,'rank':root,'F':field_width,
+ 'B':len(payloads),'K':len(homes),'events':len(events),'services':q,
+ 'leaves':len(leaves),'states':len(graph.rules),'steps':steps,'audited_boundaries':boundaries,
+ 'initial_reserved':reserved,'historical_backing':sum(t.peak for t in tapes),
+ 'events_sha256':sha256(repr(actual_events).encode()).hexdigest(),
+ 'values_sha256':sha256(repr(expected_values).encode()).hexdigest()}
+ return receipt, events, homes, payloads, expected_values
+
+
+def controls(events, homes, payloads, expected):
+ controls = []
+ def changed(name, altered):
+ tapes = initial_tapes(payloads, len(homes))
+ try:
+ compile_graph(altered, homes,productive_count=len(payloads)).run(tapes)
+ require(decoded(tapes, len(homes)) != expected, name+' escaped detection')
+ except (KeyError, ValueError) as error:
+ if str(error).endswith('escaped detection'):
+ raise
+ controls.append(name)
+ leaf = next(i for i,e in enumerate(events) if e.kind == 'leaf')
+ changed('dropped_paid_leaf', events[:leaf]+events[leaf+1:])
+ pop = next(i for i,e in enumerate(events) if e.kind == 'pop')
+ changed('missing_whole_job_return', events[:pop]+events[pop+1:])
+ release = next(i for i,e in enumerate(events) if e.kind == 'release')
+ changed('erased_productive_home', events[:release]+(replace(events[release], owners=(homes[0],)),)+events[release+1:])
+ native = next(i for i,e in enumerate(events) if e.service == 'XOR')
+ aliased = replace(events[native], owners=(events[native].owners[0],)*2)
+ changed('simultaneous_owner_alias', events[:native]+(aliased,)+events[native+1:])
+ wrong = replace(events[leaf], owners=(homes[(homes.index(events[leaf].owners[0])+1) % len(homes)],))
+ changed('wrong_source_or_bank_route', events[:leaf]+(wrong,)+events[leaf+1:])
+ changed('same_rank_different_cut_coalescing', tuple(e for i,e in enumerate(events)
+ if i == leaf or e.kind != 'leaf'))
+ try:
+ compile_graph(events, homes+(homes[-1],))
+ except ValueError:
+ controls.append('duplicate_permanent_owner_home')
+ else:
+ raise ValueError('duplicate home was accepted')
+ graph = compile_graph(events, homes,productive_count=len(payloads))
+ first_state = next(state for state in graph.rules if state.startswith('erase'))
+ graph.rules[first_state] = [replace(rule,writes=()) for rule in graph.rules[first_state]]
+ tapes = initial_tapes(payloads,len(homes))
+ graph.run(tapes)
+ require(any(set(t.contents()[1:]) - {'_'} for t in tapes[1:]), 'scratch-retirement fault escaped')
+ controls.append('omitted_work_bank_erasure')
+ graph = compile_graph(events,homes,productive_count=len(payloads))
+ tapes = initial_tapes(payloads,len(homes))
+ try:
+ graph.run(tapes,start=graph.execution_start)
+ except ValueError:
+ controls.append('omitted_physical_home_reservation')
+ else:
+ raise ValueError('unprepared owned homes were accepted')
+ with tempfile.TemporaryDirectory(prefix='_source-fault-',dir=HERE.parent) as directory:
+ target=Path(directory)
+ for name in ('inputs','reference'):
+ shutil.copytree(HERE/name,target/name)
+ for name in ('emit.py','SOURCES.json'):
+ shutil.copy2(HERE/name,target/name)
+ damaged=target/'inputs/leaf_index.py'
+ damaged.write_bytes(damaged.read_bytes()+b'\n# altered scientific source\n')
+ command=[sys.executable,'-I','-B','-c',
+ 'import sys; sys.path.insert(0,'+repr(str(target))+'); import emit']
+ result=subprocess.run(command,capture_output=True,text=True)
+ require(result.returncode != 0 and 'changed frozen scientific input' in result.stderr,
+ 'actual frozen-input corruption was accepted')
+ controls.append('changed_frozen_owner_resolver')
+ return controls
+
+
+def main():
+ frozen()
+ cases = []
+ for roles, rounds, ambient, ranks in [
+ ((('x',2),('y',3)), ((1,'x'),(1,'bank')), 3, (3,4,5,6)),
+ ((('x',2),('y',2)), ((1,'x'),(1,'bank')), 2, (2,3,4)),
+ ((('x',3),('y',4)), ((1,'bank'),(2,'x')), 5, (4,5,6,7)),
+ ]:
+ for n in ranks:
+ for width in (1,3,8):
+ result = fixture(roles, rounds, ambient, n, width)
+ cases.append(result[0])
+ # Choose a nontrivial source/complement/owned fixture for fault controls.
+ chosen = fixture((('x',2),('y',3)), ((1,'x'),(1,'bank')), 3, 6, 8)
+ rejecting = controls(*chosen[1:])
+ long = fixture((('x',2),('y',3)), ((1,'x'),(1,'bank')), 3, 6, 257)[0]
+ width_cases = [a for a in cases if a['roles'] == (('x',2),('y',3)) and a['rank'] == 6]
+ low, mid, high = sorted(width_cases,key=lambda a:a['F'])
+ slope, rem = divmod(mid['steps']-low['steps'],mid['F']-low['F'])
+ require(rem == 0 and high['steps'] == low['steps']+slope*(high['F']-low['F'])
+ and long['steps'] == low['steps']+slope*(long['F']-low['F']), 'literal runtime is not affine in F')
+ require(long['states'] == low['states'] and long['events_sha256'] == low['events_sha256'],
+ 'template controller changed with input field extent')
+ # Exact reuse of the SAME four Tape objects, including historical capacity.
+ receipt, events, homes, payloads, expected = chosen
+ tapes = initial_tapes(payloads, len(homes))
+ graph = compile_graph(events, homes,productive_count=len(payloads))
+ graph.run(tapes)
+ previous_backing = sum(t.peak for t in tapes)
+ public_now = decoded(tapes,len(homes))[:len(payloads)]
+ values = {I.normalize(owner): data for owner,data in zip(homes,decoded(tapes,len(homes)))}
+ for event in events:
+ I.apply(values,event.service,I.normalize(event.owners))
+ graph.run(tapes,start=graph.execution_start)
+ require(decoded(tapes,len(homes)) == tuple(values[I.normalize(o)] for o in homes), 'reuse changed physical result')
+ require(sum(t.peak for t in tapes) == previous_backing and all(t.head == 0 for t in tapes),
+ 'reuse discarded historical backing or head returns')
+ scan_scaling=[]
+ from emit import Event
+ for q in (1,2,4,8):
+ owners=tuple(L.SourceRow('scan-cost',i) for i in range(q))
+ word=tuple(Event('native','NOT',(owner,),()) for owner in owners)
+ graph=compile_graph(word,owners,productive_count=q)
+ machine=initial_tapes(('01011001101',)*q,q)
+ steps=graph.run(machine)
+ require(steps >= 4*q*q*12 and len(graph.rules) >= 2*q*q,
+ 'scan route hid its output-squared factor')
+ scan_scaling.append({'Q':q,'K':q,'F':11,'steps':steps,'states':len(graph.rules)})
+ monitor=Tape()
+ for _ in range(17):
+ monitor.move(1)
+ require(monitor.read() == '_' and monitor.peak == 18 and len(monitor.visited) == 18,
+ 'historical monitor ignored blank head travel')
+ for _ in range(17):
+ monitor.move(-1)
+ require(monitor.peak == 18,'historical monitor shrank after head return')
+ result = {'claim':'source-indexed physical dispatch under supplied primitive contracts',
+ 'case_count':len(cases),'cases':cases,'negative_controls':rejecting,
+ 'same_object_reuse':True,'max_tapes':4,'long_field':long,'fixed_graph_step_slope':slope,
+ 'scan_cost_scaling':scan_scaling,
+ 'python':sys.version.split()[0],
+ 'scope':'fixture primitives only; no selected multiplier or native semantic audit'}
+ path = HERE/'VALIDATION.json'
+ if '--write' in sys.argv:
+ path.write_text(json.dumps(result,indent=2)+'\n')
+ elif path.exists():
+ saved=json.loads(path.read_text())
+ saved.pop('python',None)
+ compare=dict(result);compare.pop('python',None)
+ # Canonical JSON preserves bool/int distinctions and normalizes tuples
+ # to the array representation used by the retained receipt.
+ require(json.dumps(saved,sort_keys=True,separators=(',',':')) ==
+ json.dumps(compare,sort_keys=True,separators=(',',':')),
+ 'validation scientific payload changed')
+ print('PASS_COMPILER_PERMANENT_HOME_DISPATCH',len(cases),'cases;',len(rejecting),'rejecting controls')
+
+
+if __name__ == '__main__':
+ main()