From 49d91bc8fadb6b631059c576a4cb2120c40c189a Mon Sep 17 00:00:00 2001 From: antunishdPursuit <122734610+antunishdPursuit@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:18:42 -0400 Subject: [PATCH] Independently derive G20 MAIN-bank target ranks --- research/g20-main-target-ranks/README.md | 105 +++++++++ research/g20-main-target-ranks/RESULT.json | 70 ++++++ research/g20-main-target-ranks/SOURCES.json | 66 ++++++ research/g20-main-target-ranks/TASK.json | 77 +++++++ research/g20-main-target-ranks/VERIFY.json | 43 ++++ research/g20-main-target-ranks/verify.py | 226 ++++++++++++++++++++ 6 files changed, 587 insertions(+) create mode 100644 research/g20-main-target-ranks/README.md create mode 100644 research/g20-main-target-ranks/RESULT.json create mode 100644 research/g20-main-target-ranks/SOURCES.json create mode 100644 research/g20-main-target-ranks/TASK.json create mode 100644 research/g20-main-target-ranks/VERIFY.json create mode 100644 research/g20-main-target-ranks/verify.py diff --git a/research/g20-main-target-ranks/README.md b/research/g20-main-target-ranks/README.md new file mode 100644 index 0000000000..cf1dcc1dad --- /dev/null +++ b/research/g20-main-target-ranks/README.md @@ -0,0 +1,105 @@ +# G20 MAIN-bank target ranks + +**Independent finite source-bound audit; no new bound or supplier admission.** +This answers open question 2 of Matarener's [PR5955](https://github.com/CrocSwap/integer-mult-bounds/pull/5955), +head `52115896549090117a3f3101b17106cad4466408`. Every one of the 3,552 MAIN +owners in each PR5679/PR5708 inventory agrees with a rank derived from its +retained controller. The MAIN rank mass is 154,290 in each candidate. + +| Address-projector rank | MAIN targets per candidate | +| --- | ---: | +| 15, 22, 29, 36, 43, 50, 57 | 444 each | +| 64, 127 | 222 each | + +## Derivation and its contract + +The retained source proof describes a central line and eighteen disjoint +seven-dimensional stage spaces. The ambient address space is their direct +sum, of dimension 127. Let z reflect the central line and let x_s reflect +stage s's block, acting identically on every other block. These commuting +involutions are the stated controller model, not newly admitted primitives. + +The checker first reconstructs all 32 labeled output polynomials from the +154 physical events and both boundary programs. Coefficients are in F2; +each term retains its original input-bank label. ADD is symmetric difference, +SWAP is three ADDs, and multiplying an involution toggles its monomial bit. +A LOCAL event applies the central shear and its stage factor; IDLE applies +its listed stage factors. Every off-diagonal coefficient must cancel, and +each remaining diagonal monomial must equal the source declaration. No +predecessor Python module or rank routine is imported. + +For a surviving monomial z times the product of x_s over S, evaluate its +sign on each of the 127 coordinate basis columns. It is negative exactly +on the central line and the disjoint blocks indexed by S. Thus +P = (I - R)/2 is diagonal, with an identity minor on those columns and all +other columns zero. Its rank is exactly 1 + 7|S|. The code evaluates the +signed columns and cross-checks this formula rather than trusting a target +rank or the controller's invoice. This rank is the **address projector's +native job rank**, not the rank of a full FUNCTION permutation matrix. + +Every bank has 111 ports. For each MAIN descriptor, the checker verifies +owner = 111*bank + port, uniqueness, complete owner coverage, its individual +rank, both candidate invoice histograms and the controller's MAIN histogram. +Both retained controllers are byte-identical. The full per-bank list and +15 rejecting controls are in [RESULT.json](RESULT.json). + +## Scope, evidence and reproduction + +Base: `e21a287a7c4883c24cec069113ac7cfd5efcb3ca`, priority revision 8. +PR5679 source head: `715dda75fc4cefb1e492349fa0e331d5f15d0f53`. +PR5708 source head: `829d01fc031f7323ffcfa423fdfd1f24dcbe3190`. +Exact retained source paths, Git blobs and SHA256 pins are in SOURCES.json. +The verifier authenticates every live input before parsing it. TASK.json +records the explicit refinement from the current BIT card. + +```sh +python3.12 -B scripts/research_package.py --package research/g20-main-target-ranks +``` + +Expected marker: `PASS_G20_MAIN_TARGET_RANKS`. Each registered command has +a 60-second timeout and uses only the standard library. Normal and optimized +commands recompute the result and reject changed diagonals, missing or duplicate +stages, wrong ambient dimensions, changed boundary gates, unknown opcodes, +wrong target ranks/ports/owners, operator labels or route obligations, an equal-rank bank alias, missing targets, +a count-and-rank-mass-preserving invoice change, and changed source bytes. +`--write-result` explicitly regenerates RESULT.json; ordinary replay writes +no package artifact. Semantic controls operate on copies after authentication. + +This closes only the source-relative MAIN rank input, including the formal +controller endpoint that PR5955 did not replicate. It does not reprove the +physical orthogonal-block realization, native all-column/whole-job adapters, +FRAMES geometry, OWNED erasure, paid query ranks, global stream, finite fees, +compiler, precision/tape, modulus domain, ordinary-to-admitted BIT conversion +or outer assembly. The five framework assumptions remain. No selected record, +frozen predecessor or original invoice is changed. Independent human and +formal proof-kernel review are unclaimed. Hosted CI is separate from local checks. + +## Open next questions + +Bind one actual MAIN bank's physical projector and whole-job adapter to its +all-column, arbitrary-spectator contract. This matters for physical admission; +start from the exact coordinate action above and its retained native wrapper. +The inherited native/compiler/precision obligations require a separate audit. +The structured question and blocker are in TASK.json. + +## Credit and overlap + +Matarener supplied the independent review and explicit open question. Ali +Romman, Dugongue, ai-nanachi and the retained G20 controller/native lineage +supplied the constructions. JoyboyBrian's earlier bit-paid-owner-binding +already emits productive ranks from the supplied controller diagonal; this +package adds a separate complete polynomial reconstruction and current +per-owner comparison, rather than claiming the rank formula is new. +DreamingOfClouds, eumemic, Cinna Davis and the retained compiler/ownership +authors keep their original attribution; no predecessor source is copied. + +Remote overlap refresh covered 315 open PRs, 5,221 closed PRs and 5,694 +Discussion records. Sparse local notes covered 7/8,346 paths; exact-gap +searches of pinned Git notes and relevant older owner-binding code supplement +that limited coverage. No competing exact-gap derivation was identified; +this is not a global novelty guarantee. Coordination: +https://github.com/CrocSwap/integer-mult-bounds/discussions/1166#discussioncomment-19231258 + +New checker and exposition by Dennis / antunishdPursuit with substantial +OpenAI Codex assistance, no subagents. Apache-2.0. Orthogonal direct sums, +reflection projectors and rank by an identity minor are standard methods. diff --git a/research/g20-main-target-ranks/RESULT.json b/research/g20-main-target-ranks/RESULT.json new file mode 100644 index 0000000000..68a5ac304f --- /dev/null +++ b/research/g20-main-target-ranks/RESULT.json @@ -0,0 +1,70 @@ +{ + "banks": 32, + "ports_per_bank": 111, + "MAIN_targets_per_candidate": 3552, + "controller_physical_events": 154, + "ambient_rank": 127, + "bank_ranks": [ + 15, + 15, + 22, + 22, + 29, + 29, + 36, + 36, + 43, + 43, + 50, + 50, + 57, + 57, + 15, + 15, + 22, + 22, + 29, + 29, + 36, + 36, + 43, + 43, + 50, + 50, + 57, + 57, + 64, + 64, + 127, + 127 + ], + "MAIN_histogram": { + "15": 444, + "22": 444, + "29": 444, + "36": 444, + "43": 444, + "50": 444, + "57": 444, + "64": 222, + "127": 222 + }, + "rank_mass_per_candidate": 154290, + "rejected_controls": [ + "declared diagonal changed", + "missing thick call", + "duplicate thick stage", + "wrong ambient dimension", + "wrong boundary gate", + "unknown physical opcode", + "wrong target rank", + "wrong MAIN operator", + "missing route obligation", + "duplicate original owner", + "wrong target port", + "equal-rank bank alias", + "missing MAIN target", + "count-and-mass-preserving wrong invoice", + "changed source bytes" + ] +} diff --git a/research/g20-main-target-ranks/SOURCES.json b/research/g20-main-target-ranks/SOURCES.json new file mode 100644 index 0000000000..796b769e1d --- /dev/null +++ b/research/g20-main-target-ranks/SOURCES.json @@ -0,0 +1,66 @@ +{ + "schema_version": 1, + "base_commit": "e21a287a7c4883c24cec069113ac7cfd5efcb3ca", + "files": [ + { + "path": "certificates/selected-result.json", + "usage": "provenance", + "git_blob": "581f8d87008354eb5b869f7ed9de1317ad837ce8", + "sha256": "2a0220e866417774606e0f991e41b9c1d26b1f43b97857238cf478dbc7d330b5" + }, + { + "path": "docs/research/agent-task-catalog.json", + "usage": "provenance", + "git_blob": "3404fbdd5e7529a0674eef26114b5071e4586cec", + "sha256": "ead6cdc9d0af6d58e8a49744d8ec8c7c15e13d2ba93c276c434bcf9b51b93a81" + }, + { + "path": "research/g20-conjugation-admission/INVOICE.json", + "usage": "input", + "git_blob": "08ed5c4b9b0b03e16cd74b35880839c08a7125f4", + "sha256": "a2a9559bdc3b3293eae111c927e02e7cccecbaa0d35299c352421a58b3609296" + }, + { + "path": "research/g20-conjugation-admission/TARGET-OWNERS.json", + "usage": "input", + "git_blob": "5721485cc27c49600d5c4d8e54c815175403f5de", + "sha256": "2918dc7e7e36551be7c9b5ea91a4df516d29573b8fd35e5a290a8d9944812754" + }, + { + "path": "research/g20-conjugation-admission/prior/prior/prior/source/PROOF.md", + "usage": "input", + "git_blob": "951ce90c64428d596c678cca25a072930c45b794", + "sha256": "ebee57b34141253a90b0a72d959546362f236b5ee03c94fc0ff2b99f58149d37" + }, + { + "path": "research/g20-conjugation-admission/prior/prior/prior/source/vendor/g20/inputs/CONTROLLER.json", + "usage": "input", + "git_blob": "89c400d5970024b3debe870c36ce43889beed001", + "sha256": "39ac84fb848b908f7ba051fae4556d507900c421dc5d23501a9c0cb1d61fd08d" + }, + { + "path": "research/g20-helper-split/INVOICE.json", + "usage": "input", + "git_blob": "a4d9214abaab86dcd597b9533549ae1fe85672b5", + "sha256": "7213965618c196f2eb5528d6fdee8deab9152beca301e7a3ecddd7f8847e4803" + }, + { + "path": "research/g20-helper-split/TARGET-OWNERS.json", + "usage": "input", + "git_blob": "5721485cc27c49600d5c4d8e54c815175403f5de", + "sha256": "2918dc7e7e36551be7c9b5ea91a4df516d29573b8fd35e5a290a8d9944812754" + }, + { + "path": "research/g20-helper-split/prior/prior/source/vendor/g20/inputs/CONTROLLER.json", + "usage": "input", + "git_blob": "89c400d5970024b3debe870c36ce43889beed001", + "sha256": "39ac84fb848b908f7ba051fae4556d507900c421dc5d23501a9c0cb1d61fd08d" + }, + { + "path": "research/g20-independent-review/README.md", + "usage": "input", + "git_blob": "92deccb3ac4712b2047922fa9c426e046ebc7119", + "sha256": "d0a007f675f433372679f71686283a2b0150e9200cfe86a0d9b92d945489d41e" + } + ] +} diff --git a/research/g20-main-target-ranks/TASK.json b/research/g20-main-target-ranks/TASK.json new file mode 100644 index 0000000000..d09a5d577a --- /dev/null +++ b/research/g20-main-target-ranks/TASK.json @@ -0,0 +1,77 @@ +{ + "schema_version": 1, + "task_id": "bit-helper-contract", + "priority_revision": 8, + "base_commit": "e21a287a7c4883c24cec069113ac7cfd5efcb3ca", + "original_card": { + "id": "bit-helper-contract", + "question": "Can a changed G20 helper path or independent-target split improve the complete BIT moment without losing its physical endpoint?", + "starting_points": [ + "docs/research/current-priorities.md", + "docs/research/research-family-status.md", + "certificates/selected-result.json", + "docs/research/pr-intake-evidence/pr5599-completion/PROOF-REVIEW.md", + "research/g20-helper-split/README.md", + "research/g20-conjugation-admission/README.md" + ], + "methods": [ + "Construct and independently check one source-bound instance of the stated first experiment.", + "Seek an exact counterexample or target-specific complete-budget obstruction to that same proposed change." + ], + "acceptance_gate": "A full boundary contract and paid profile; unchanged scalar counts alone are insufficient. A scoped local result may be retained without a complete supplier. Expanding it into further construction rounds requires the family-level budget and obligation gate in research-family-status.md; an optimistic passing relaxation alone is not acceptance.", + "first_step": { + "command": [ + "python3", + "-B", + "scripts/research_selected_baseline.py" + ], + "expected": "PASS_RESEARCH_BASELINE_BINDINGS_ONLY", + "inspect": "Read revision 8, the selected review and live exact-source handoffs. Then follow this card's bounded first_experiment.", + "scope": "Source-bound orientation only, not a supplier replay or theorem proof." + }, + "first_experiment": "First read #5679/#5708 and their audits as pending component proposals. Choose one uncovered helper group/cut on an exact word; compare arbitrary-input native action, targets, owned storage, both orientations and full signed bill. Stop if the gain is only a scalar count or repaid by lost targets. Do not rerun the frozen #5609 common-frame domain without changing its hypothesis.", + "bottleneck_link": "Judge the actual current supplier contract and complete signed target/paid bill; frozen-profile ceilings require an applicability proof.", + "allowed_variations": [ + "One exact source head, helper/cut region or quantified proposition and changed hypothesis; check live handoffs first. Different seeds are not different scopes." + ], + "scope_change_triggers": [ + "Changing source head, helper/cut domain, operation alphabet or caller boundary without recording the new scope.", + "Treating an archived proposal or local numerical pass as complete supplier admission." + ], + "overlap_terms": [ + "G20", + "helper split", + "5679", + "5708", + "independent target" + ], + "existing_checks": [ + { + "scope": "Selected PR5599: complete helper-subspace construction and independent caller replay; five framework assumptions remain.", + "evidence": "docs/research/pr-intake-evidence/pr5599-completion/PROOF-REVIEW.md", + "remaining": "The next experiment must identify uncovered source-specific work. Successor archive intake does not transfer this admission.", + "status": "reviewed", + "source_commit": "09dd0965711ca7eeb169057a420abab1c9052137", + "selected_record_sha256": "2a0220e866417774606e0f991e41b9c1d26b1f43b97857238cf478dbc7d330b5" + } + ] + }, + "scope_status": "refined", + "actual_scope": "Independently derive all 3,552 MAIN-bank target ranks in each exact PR5679/PR5708 inventory from the retained controller, addressing PR5955 open question 2.", + "scope_change_reason": "Explicit user assignment follows the largest unchecked input in PR5955; this is a target-rank audit, not a new helper search or supplier admission.", + "bottleneck_link": "Removes reliance on declared MAIN ranks in the independent G20 review by rebuilding the formal endpoint and its retained orthogonal-block address projector.", + "budget_minutes": 1200, + "stop_rule": "Stop at any polynomial, owner, rank or invoice discrepancy, or after every MAIN target in both frozen candidates and the rejection controls pass. Do not expand into native/compiler admission.", + "outcome": "completed", + "evidence": "verify.py, RESULT.json and the proof and scope in README.md.", + "author": "Dennis / antunishdPursuit, with substantial OpenAI Codex assistance", + "ai_assistance": "Substantial OpenAI Codex assistance for source inspection, derivation, implementation, tests and writing. No subagents or independent human review claimed.", + "open_questions": [ + { + "question": "Can the physical MAIN projector and whole-job adapter contract be independently admitted for arbitrary columns and spectators?", + "why_it_matters": "The coordinate rank derivation assumes the retained direct-sum physical interpretation; it does not implement its ROW or FUNCTION adapters.", + "first_step": "Choose one actual MAIN bank and bind its coordinate projector to the retained native all-column/address-to-FUNCTION contract, preserving routes and spectators.", + "blocked_by": "Inherited native/compiler/precision contracts and the need for a separately scoped physical audit." + } + ] +} diff --git a/research/g20-main-target-ranks/VERIFY.json b/research/g20-main-target-ranks/VERIFY.json new file mode 100644 index 0000000000..ad307490ee --- /dev/null +++ b/research/g20-main-target-ranks/VERIFY.json @@ -0,0 +1,43 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [ + "research/g20-conjugation-admission/INVOICE.json", + "research/g20-conjugation-admission/TARGET-OWNERS.json", + "research/g20-conjugation-admission/prior/prior/prior/source/PROOF.md", + "research/g20-conjugation-admission/prior/prior/prior/source/vendor/g20/inputs/CONTROLLER.json", + "research/g20-helper-split/INVOICE.json", + "research/g20-helper-split/TARGET-OWNERS.json", + "research/g20-helper-split/prior/prior/source/vendor/g20/inputs/CONTROLLER.json", + "research/g20-independent-review/README.md" + ], + "commands": [ + { + "argv": [ + "{python}", + "-W", + "error", + "-I", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 60, + "checks": "Authenticate eight source inputs; independently replay all controller coefficients; derive 127-coordinate projector ranks; compare all 3,552 MAIN owners in both candidates; reject 15 semantic/source mutations." + }, + { + "argv": [ + "{python}", + "-W", + "error", + "-I", + "-O", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 60, + "checks": "Same exact derivation and rejecting controls with optimized Python; all invariants use explicit exceptions." + } + ] +} diff --git a/research/g20-main-target-ranks/verify.py b/research/g20-main-target-ranks/verify.py new file mode 100644 index 0000000000..dafcf84026 --- /dev/null +++ b/research/g20-main-target-ranks/verify.py @@ -0,0 +1,226 @@ +"""Independent MAIN-bank polynomial/rank audit. Dennis, with OpenAI Codex assistance. +Apache-2.0. No predecessor modules are imported; see README for the inherited contract. +""" +from collections import Counter +from copy import deepcopy +import hashlib +import json +from pathlib import Path +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +PREFIX = 'research/g20-conjugation-admission/' +CONTROLLER = PREFIX + 'prior/prior/prior/source/vendor/g20/inputs/CONTROLLER.json' +OTHER = 'research/g20-helper-split/' +OTHER_CONTROLLER = OTHER + 'prior/prior/source/vendor/g20/inputs/CONTROLLER.json' +PORTS = 111 +BANKS = 32 + + +def need(ok, message): + if not ok: + raise ValueError(message) + + +def load(root): + manifest = json.loads((HERE / 'SOURCES.json').read_text(encoding='utf-8')) + out = {} + for row in manifest['files']: + if row['usage'] != 'input': + continue + raw = (root / row['path']).read_bytes() + need(hashlib.sha256(raw).hexdigest() == row['sha256'], 'source SHA: ' + row['path']) + blob = hashlib.sha1(b'blob ' + str(len(raw)).encode() + b'\0' + raw).hexdigest() + need(blob == row['git_blob'], 'source blob: ' + row['path']) + out[row['path']] = raw + return out + + +def controller_ranks(c): + """Rebuild the complete formal polynomial, then its stated coordinate action.""" + thick = c['invoice']['thick_stages'] + need(thick == sorted(set(thick)) and len(thick) == 18, 'distinct thick stages') + need(c['ambient_rank'] == 1 + 7 * len(thick), 'ambient direct-sum dimension') + need(c['pairs'] * 2 == BANKS and c['kind'] == 'bit', 'controller shape') + stages = [e[1] for e in c['physical_events'] if e[0] == 'LOCAL'] + need(sorted(stages) == thick, 'physical LOCAL stages equal thick stages') + # Each set element is (formal monomial, labeled input bank). Symmetric + # difference adds coefficients over F2; monomial multiplication XORs bits. + rows = [{(0, i)} for i in range(BANKS)] + def add(d, s): + need(type(d) is int and type(s) is int and 0 <= d < BANKS and 0 <= s < BANKS and d != s, + 'distinct in-range boundary banks') + rows[d] = rows[d] ^ rows[s] + def gate(e): + need(len(e) == 3, 'boundary gate arity') + op, d, s = e + if op == 'ADD': + add(d, s) + else: + need(op == 'SWAP', 'boundary opcode') + # Physical XOR swap, not a free relabeling assumption. + add(d, s); add(s, d); add(d, s) + def shift(bank, monomial): + rows[bank] = {(m ^ monomial, source) for m, source in rows[bank]} + for e in c['boundaries']['right_program']: + gate(e) + for e in c['physical_events']: + op = e[0] + if op in ('LOCAL', 'QUERY_SHEAR'): + need(len(e) == 4, 'local arity') + _, stage, pair, reverse = e + need(type(pair) is int and 0 <= pair < BANKS // 2 and type(reverse) is bool, + 'local bank pair') + need(type(stage) is int and 0 <= stage <= 32, 'stage index') + if op == 'QUERY_SHEAR': + need(stage not in thick, 'thin stage outside thick stages') + x, y = 2 * pair, 2 * pair + 1 + if reverse: + x, y = y, x + rows[y] ^= {(m ^ 1, source) for m, source in rows[x]} + if op == 'LOCAL': + shift(x, 1 << (stage + 1)); shift(y, 1 << (stage + 1)) + elif op == 'IDLE': + need(len(e) == 3, 'idle arity') + _, pair, idle = e + need(type(pair) is int and 0 <= pair < BANKS // 2, 'idle pair') + need(len(idle) == len(set(idle)) and set(idle) <= set(thick), 'idle stage subset') + monomial = sum(1 << (j + 1) for j in idle) + shift(2 * pair, monomial); shift(2 * pair + 1, monomial) + else: + gate(e) + for e in c['boundaries']['left_program']: + gate(e) + declared = c['diagonal'] + need(len(declared) == BANKS, 'diagonal length') + need(rows == [{(m, i)} for i, m in enumerate(declared)], 'complete labeled polynomial endpoint') + need(declared == c['boundaries']['diagonal_monomials'], 'boundary diagonal agrees') + # Construct the retained direct-sum coordinate model: one central line and + # 18 disjoint seven-dimensional stage spaces. Each generator reflects just + # its own block. Evaluate all 127 signed coordinate columns separately. + blocks = {1: {0}} + for position, stage in enumerate(thick): + blocks[1 << (stage + 1)] = set(range(1 + 7 * position, 8 + 7 * position)) + need(set.union(*blocks.values()) == set(range(c['ambient_rank'])), 'complete coordinate cover') + need(sum(map(len, blocks.values())) == c['ambient_rank'], 'disjoint coordinate cover') + ranks = [] + for row in rows: + monomial, _ = next(iter(row)) + active = [bit for bit in blocks if monomial & bit] + need(sum(active) == monomial and monomial & 1, 'only retained stage factors and central line') + diagonal = [] + for coordinate in range(c['ambient_rank']): + value = 1 + for bit in active: + if coordinate in blocks[bit]: + value *= -1 + diagonal.append((1 - value) // 2) + # This is a diagonal projector. Its unit entries give both an explicit + # nonsingular identity minor and a spanning set of all nonzero columns. + rank = sum(diagonal) + need(rank == 1 + 7 * (len(active) - 1), 'coordinate rank versus stage formula') + ranks.append(rank) + return ranks + + +def check_targets(targets, invoice, ranks): + main = [t for t in targets if t.get('matcher', '').startswith('MAIN_BANK_')] + need(len(main) == BANKS * PORTS, 'MAIN target count') + seen = set() + for t in main: + bank = int(t['matcher'].removeprefix('MAIN_BANK_')) + port, owner = t['port'], t['original_owner'] + need(0 <= bank < BANKS and type(port) is int and 0 <= port < PORTS, 'target bank/port') + need(type(owner) is int and owner == bank * PORTS + port, 'target owner identifies bank and port') + need(owner not in seen, 'unique MAIN owner') + seen.add(owner) + need(t['operator'] == 'D_(P_line+selectedorthogonalstageblocks)' and + t['route_pair_required_in_generic_job_matching'] is True, 'MAIN operator and route contract') + need(t['rank'] == ranks[bank], 'derived MAIN target rank') + need(seen == set(range(BANKS * PORTS)), 'every MAIN owner covered') + derived = Counter(rank for rank in ranks for _ in range(PORTS)) + need(Counter(t['rank'] for t in main) == derived, 'per-owner rank histogram') + # Current invoice target keys are disjoint from helper ranks 4 and 8. + claimed = {int(k): v for k, v in invoice['targets'].items() if int(k) in set(ranks)} + need(claimed == dict(derived), 'invoice MAIN histogram') + return dict(sorted(derived.items())) + + +def checks(data): + c = json.loads(data[CONTROLLER]) + need(data[CONTROLLER] == data[OTHER_CONTROLLER], 'both source controllers identical') + ranks = controller_ranks(c) + histograms = [] + for prefix in (PREFIX, OTHER): + histograms.append(check_targets(json.loads(data[prefix + 'TARGET-OWNERS.json']), + json.loads(data[prefix + 'INVOICE.json']), ranks)) + need(histograms[0] == histograms[1], 'both candidate inventories agree') + need({int(k): v for k, v in c['invoice']['main'].items()} == histograms[0], 'controller MAIN histogram') + return {'banks': BANKS, 'ports_per_bank': PORTS, 'MAIN_targets_per_candidate': BANKS * PORTS, + 'controller_physical_events': len(c['physical_events']), 'ambient_rank': c['ambient_rank'], + 'bank_ranks': ranks, 'MAIN_histogram': {str(k): v for k, v in histograms[0].items()}, + 'rank_mass_per_candidate': sum(k * v for k, v in histograms[0].items())} + + +def controls(data): + c = json.loads(data[CONTROLLER]); targets = json.loads(data[PREFIX + 'TARGET-OWNERS.json']) + invoice = json.loads(data[PREFIX + 'INVOICE.json']); ranks = controller_ranks(c) + rejected = [] + def reject(name, f): + try: + f() + except ValueError: + rejected.append(name) + else: + raise ValueError('control survived: ' + name) + for name, mutate in [ + ('declared diagonal changed', lambda x: x['diagonal'].__setitem__(0, x['diagonal'][0] ^ 2)), + ('missing thick call', lambda x: x['physical_events'].pop(0)), + ('duplicate thick stage', lambda x: x['invoice']['thick_stages'].append(0)), + ('wrong ambient dimension', lambda x: x.__setitem__('ambient_rank', 126)), + ('wrong boundary gate', lambda x: x['boundaries']['right_program'].insert(0, ['ADD', 0, 1])), + ('unknown physical opcode', lambda x: x['physical_events'].append(['FREE', 0, 1])), + ]: + x = deepcopy(c); mutate(x); reject(name, lambda: controller_ranks(x)) + for name, mutate in [ + ('wrong target rank', lambda x: x[0].__setitem__('rank', 16)), + ('wrong MAIN operator', lambda x: x[0].__setitem__('operator', 'identity')), + ('missing route obligation', lambda x: x[0].__setitem__('route_pair_required_in_generic_job_matching', False)), + ('duplicate original owner', lambda x: x[1].__setitem__('original_owner', 0)), + ('wrong target port', lambda x: x[0].__setitem__('port', 1)), + ('equal-rank bank alias', lambda x: x[0].__setitem__('matcher', 'MAIN_BANK_1')), + ('missing MAIN target', lambda x: x.pop(0)), + ]: + x = deepcopy(targets); mutate(x); reject(name, lambda: check_targets(x, invoice, ranks)) + x = deepcopy(invoice) + for rank, count in [('15', -2), ('22', 4), ('29', -2)]: + x['targets'][rank] += count + reject('count-and-mass-preserving wrong invoice', lambda: check_targets(targets, x, ranks)) + # Source corruption must fail before any JSON parsing/controller execution. + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + for path, raw in data.items(): + p = root / path; p.parent.mkdir(parents=True, exist_ok=True); p.write_bytes(raw) + p = root / CONTROLLER; p.write_bytes(p.read_bytes() + b' ') + reject('changed source bytes', lambda: load(root)) + return rejected + + +def main(): + data = load(ROOT) + result = checks(data) + result['rejected_controls'] = controls(data) + path = HERE / 'RESULT.json' + if sys.argv[1:] == ['--write-result']: + path.write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8') + else: + need(not sys.argv[1:], 'unexpected arguments') + need(json.loads(path.read_text(encoding='utf-8')) == result, 'committed result equals fresh derivation') + print(json.dumps(result, sort_keys=True)) + print('PASS_G20_MAIN_TARGET_RANKS') + + +if __name__ == '__main__': + main()