From cb5a79f12531022c6fcd2fe592b5030d4e3ae9e7 Mon Sep 17 00:00:00 2001 From: Hanson Sun <182361798+bbMisk@users.noreply.github.com> Date: Tue, 13 Oct 2026 16:19:04 -0400 Subject: [PATCH] Tooling: cache exact historical ternary frame transitions --- research/ternary-frame-cache/CLAIM.json | 101 +++++ research/ternary-frame-cache/README.md | 59 +++ research/ternary-frame-cache/SOURCES.json | 26 ++ .../evidence/ADAPTATION.diff | 37 ++ .../evidence/benchmark-python311.json | 271 ++++++++++++ .../evidence/benchmark-python314.json | 403 ++++++++++++++++++ .../evidence/controls-python311.log | 23 + .../evidence/controls-python314.log | 23 + .../evidence/original-ternary-tests.log | 10 + .../evidence/profile-python314.txt | 28 ++ .../evidence/retained-paths-unchanged.log | 0 .../evidence/selected-source-binding.log | 1 + .../evidence/validation.json | 52 +++ research/ternary-frame-cache/fast.py | 80 ++++ research/ternary-frame-cache/frame_cache.py | 47 ++ research/ternary-frame-cache/run.py | 82 ++++ research/ternary-frame-cache/support.py | 98 +++++ research/ternary-frame-cache/test_package.py | 213 +++++++++ research/ternary-frame-cache/verify.py | 107 +++++ 19 files changed, 1661 insertions(+) create mode 100644 research/ternary-frame-cache/CLAIM.json create mode 100644 research/ternary-frame-cache/README.md create mode 100644 research/ternary-frame-cache/SOURCES.json create mode 100644 research/ternary-frame-cache/evidence/ADAPTATION.diff create mode 100644 research/ternary-frame-cache/evidence/benchmark-python311.json create mode 100644 research/ternary-frame-cache/evidence/benchmark-python314.json create mode 100644 research/ternary-frame-cache/evidence/controls-python311.log create mode 100644 research/ternary-frame-cache/evidence/controls-python314.log create mode 100644 research/ternary-frame-cache/evidence/original-ternary-tests.log create mode 100644 research/ternary-frame-cache/evidence/profile-python314.txt create mode 100644 research/ternary-frame-cache/evidence/retained-paths-unchanged.log create mode 100644 research/ternary-frame-cache/evidence/selected-source-binding.log create mode 100644 research/ternary-frame-cache/evidence/validation.json create mode 100644 research/ternary-frame-cache/fast.py create mode 100644 research/ternary-frame-cache/frame_cache.py create mode 100644 research/ternary-frame-cache/run.py create mode 100644 research/ternary-frame-cache/support.py create mode 100644 research/ternary-frame-cache/test_package.py create mode 100644 research/ternary-frame-cache/verify.py diff --git a/research/ternary-frame-cache/CLAIM.json b/research/ternary-frame-cache/CLAIM.json new file mode 100644 index 0000000000..ee4a7f8d5a --- /dev/null +++ b/research/ternary-frame-cache/CLAIM.json @@ -0,0 +1,101 @@ +{ + "track": "verification engineering", + "assignment_seed": 93, + "seed_source": "secrets.randbelow(100), OS randomness", + "base_commit": "1b59b624d21924f8e3537cdc1ac52d3be6eda2fe", + "selected_kappa": "836330098538459/500000000000000000", + "candidate_tasks": [ + { + "object": "historical ternary_side.verify_invocation_frames", + "method": "exact interned frame-pair reuse, complete h=8,9 signed edge traversals", + "choice": "selected, seed modulo 3 = 0" + }, + { + "object": "prime_field_checks.frame_control", + "method": "exact rational span reuse", + "choice": "not selected" + }, + { + "object": "verify_selected_result.check", + "method": "streaming source inventory hashing", + "choice": "not selected; fast check already, lower expected benefit" + } + ], + "scope_key": "ternary-h8-h9-physical-edge-pair-memoization", + "object": "scripts/experiments/ternary_side.py::verify_invocation_frames", + "hypothesis": "Local exact frame and ordered transition caches reduce repeated rational work without dropping any physical edge, positivity, idempotence, nesting, or ledger check.", + "domain": { + "h": [ + 8, + 9 + ], + "orientations": [ + false, + true + ], + "complete_physical_edges": 84672 + }, + "expected_deliverable": "Opt-in source-pinned checker, full before/after benchmarks, ordered edge equality, semantic failure controls; no source or certificate repins.", + "stop_rule": "One implementation, at most one evidence-driven pivot; stop optimization if no measured benefit or coverage cannot be shown.", + "budget_minutes": 50, + "verification_reserved_minutes": 12.5, + "started_utc": "2026-10-13T19:56:02Z", + "expected_finish_utc": "2026-10-13T20:46:02Z", + "coordination": { + "pinned_issue": null, + "local_claim_reason": "No pinned coordination issue; explicit posting request concerns such an issue. Read discussions 1163,1166,1167; no active matching claim found.", + "open_pr_count_at_entry": 810 + }, + "overlap": [ + { + "pr": 154, + "head": "f571bcbd6e06618aeae0b8279da48060032dc74b", + "difference": "Scheduling and paired-cube frame changes; mentions ternary build hot spot but does not edit ternary physical-frame checker." + }, + { + "pr": 367, + "head": "522285db971642c2d744cc8d45f2a5ade3a55e19", + "difference": "PR364 integer elimination adapter; no code reuse, this task preserves rational routines and reuses identical frame pairs in historical ternary controls." + }, + { + "pr": 1184, + "difference": "Emitted local audit for a different complex supplier.", + "head": "2f1c9e0e671bb10aecd452e18449130b0601932d" + } + ], + "predecessor_credit": [ + "Douglas R. Colkitt: retained historical ternary checker and exact rational frame implementation", + "Zhihao Chen (jacklightChen), PR7: earlier F3 five-subset motif and common-pair geometry, acknowledged by the retained review" + ], + "contributor": "Hanson Sun (bbMisk)", + "assistance": "Substantial OpenAI Codex assistance", + "license": "Apache-2.0", + "unrun_obligations": [ + "Large h=29 DAG and full ternary assembly", + "Selected frontier1094 cold replay", + "All-size multiplication theorem and inherited compiler/precision/analytic interfaces" + ], + "completion": { + "completed_utc": "2026-10-13T20:17:27.383097+00:00", + "status": "Completed tooling contribution; submitted source link below, PR link in handoff", + "result": "PASS_IDENTICAL_TERNARY_FRAME_REPLAY", + "result_source_url": "https://github.com/bbMisk/integer-mult-bounds/tree/hanson/ternary-frame-cache93-1b59b624-2000/research/ternary-frame-cache", + "physical_edges": 84672, + "python_versions": [ + "3.11", + "3.14" + ], + "python314_timing_pairs": 3, + "python314_ratio_of_medians": 1.7010109761129673, + "python311_timing_pairs": 1, + "python311_ratio": 1.9187589682912383, + "targeted_tests_per_python": 18, + "original_ternary_tests": 5, + "source_pins_and_selected_binding": "PASS", + "new_kappa": false, + "last_overlap_open_pr_count": 820, + "overlapping_ternary_frame_optimization_found": false, + "last_upstream_main": "1b59b624d21924f8e3537cdc1ac52d3be6eda2fe", + "coordination_update": "One local completion update; no pinned sprint issue existed." + } +} diff --git a/research/ternary-frame-cache/README.md b/research/ternary-frame-cache/README.md new file mode 100644 index 0000000000..54cf2f5dcb --- /dev/null +++ b/research/ternary-frame-cache/README.md @@ -0,0 +1,59 @@ +This opt-in tool speeds up the historical ternary frame checker by caching results for exact ordered frame pairs. It retains both orientations, every physical edge, and the existing rational arithmetic. Complete matrix-and-edge transcripts and published small-control fields for h=8 and h=9 match the retained checker. Timings use alternating fresh processes. The h=29 construction is not replayed, and kappa is unchanged. + +Douglas Colkitt wrote the retained checker. Zhihao Chen's PR7 supplied the earlier five-subset motif and common-pair geometry. Hanson Sun prepared this contribution with substantial OpenAI Codex assistance. See CLAIM.json for scope, SOURCES.json for pins, and evidence/ for checks and measurements. + +```sh +python3 -B research/ternary-frame-cache/verify.py --out /tmp/ternary-frame-cache-93 --pairs 3 +``` + +Expected: `PASS_IDENTICAL_TERNARY_FRAME_REPLAY 84672 edges; ... ratio of medians`. +Output directory: fresh. Dependencies: Python 3.11+ standard library on macOS or Linux. + +| Input | Orientations | Physical edges | Rank sum per orientation | Decreasing dimensions per orientation | +|---|---:|---:|---:|---:| +| h=8 | 2 | 9,464 | 5,936 | 224 | +| h=9 | 2 | 75,208 | 33,084 | 324 | + +```text +intern(A) = intern(B) iff A == B entrywise over Q +key(old, new) = (intern(old), intern(new)) +value(old, new) = (rank(new-old), rank(new)-rank(old)) +cache lifetime = one verify_invocation_frames call +per-edge predicate = rank(new-old) == abs(rank(new)-rank(old)) +projection key = immutable rational row tuple U; ambient H fixed within the call +``` + +[Adaptation diff](evidence/ADAPTATION.diff) · [Source pins](SOURCES.json) · [Task card](CLAIM.json) + +| Verification | Reproduction | +|---|---| +| Semantic controls, exact traces, alternating timing pairs | Command above | +| Controls only | `python3 -B research/ternary-frame-cache/test_package.py` | +| Original ternary tests | `python3 -B -m unittest discover -s tests -p test_ternary_side.py -v` | +| Source selection binding | `python3 -B scripts/verify_selected_result.py` | + +| Boundary | Status | +|---|---| +| h=8,9 graph receipts and arbitrary-input scalar controls | Replayed in both engines | +| Both full physical-frame edge streams | Compared entry by entry, including every rational numerator and denominator | +| Missing common pair, singular Gram, non-idempotence, wrong target, wrong role count | Rejected by both engines | +| Same-rank unequal frames, reversed transitions, exact hash collisions, identity reuse | Targeted cache controls | +| Source mutations | All 20 pinned dependencies individually rejected | +| Omitted, duplicated, reordered or changed edge/matrix records | Comparator controls | +| Python `-O`, existing output directory | Refused | +| h=29 DAG and complete historical ternary assembly | Not replayed | +| Selected frontier1094 construction and all-size theorem | Not replayed or proved | +| Upstream, frozen source, selected certificate, default checker | Unchanged | + +License: Apache-2.0. Source arithmetic and construction credit: Douglas R. Colkitt; prior F3 motif: Zhihao Chen, [PR7](https://github.com/CrocSwap/integer-mult-bounds/pull/7). Related tooling: [PR154](https://github.com/CrocSwap/integer-mult-bounds/pull/154) (scheduling and paired-cube frames), [PR367](https://github.com/CrocSwap/integer-mult-bounds/pull/367) (PR364 integer elimination). Exact heads and scope differences: [CLAIM.json](CLAIM.json). + +| Python 3.14.6, macOS arm64; three alternating pairs | Reference | Cached | +|---|---:|---:| +| Median wall seconds | 11.525 | 6.775 | +| Maximum observed RSS, MiB | 96.297 | 105.172 | + +Ratio of medians: **1.70**. [Timing and exact receipts](evidence/benchmark-python314.json) · [18 control tests](evidence/controls-python314.log) · [Initial bottleneck profile](evidence/profile-python314.txt). + +Measurement boundary: complete small-control worker processes, including source admission, DAG construction, scalar checks and result writing; no tracing in timed runs. Shared host; OS caches not flushed. No speed threshold. Peak memory includes the complete worker, not only the caches. + +Python 3.11: **18/18** controls; **84,672/84,672** edge records; exact transcripts equal across Python versions. [Complete replay receipt](evidence/benchmark-python311.json) · [Controls](evidence/controls-python311.log) · [Original tests and source binding](evidence/validation.json). diff --git a/research/ternary-frame-cache/SOURCES.json b/research/ternary-frame-cache/SOURCES.json new file mode 100644 index 0000000000..0231e5c6c8 --- /dev/null +++ b/research/ternary-frame-cache/SOURCES.json @@ -0,0 +1,26 @@ +{ + "base_commit": "1b59b624d21924f8e3537cdc1ac52d3be6eda2fe", + "historical_source_commit": "1a74950ce5074b848243ba89d8022fbadba66105", + "files": { + "certificates/ternary-side.json": "a01961cf95a3da641302bce643bdb9f2bfbff5094358c7029e0104a90d8a374f", + "scripts/audit_cancellation.py": "508934ee4d9514a5519813603b6192a0d53103b6e30d65b8d53a1a774de244b6", + "scripts/audit_fused_block.py": "2afb83ca8e5f193ca8a4c242becf267ad1d9dc2578ba238b820e98d5185f6288", + "scripts/audit_joint_frames.py": "3df8061392ce0ba42bbde8c02f2a30c8141145e70e9a48c18da73d3aafb14423", + "scripts/binary_phase_frames.py": "4148cfa313cf050ed25296e8db36d35871520b8318fd086c7d1facf0c6af67d7", + "scripts/certify.py": "2348d95008276c5d5764f7e028c3918e484582cd589bd4d9b82919161745e53e", + "scripts/complex_compression.py": "9b6f758a5985ba5d9fdd726fe6556b3d3b4bd9d98aaf8ba06a7bb58093c4c504", + "scripts/exclusion_circuit.py": "b253f9d7318becda1c1f3b24e2287ed44a9c27fcea00cf9d531afb950d0457a0", + "scripts/experiments/disjoint_tensor.py": "102dd59bf96033f96ba0dab4c2aba77b3a7a73b67b0f96929ff8b20a98b91cd8", + "scripts/experiments/rank_product_core.py": "7a91c1188c5d42e864a5d2e42397b09c435b526ae4f4210c44bf615de488708e", + "scripts/experiments/shared_core.py": "d3c59b61229956cb54ae1ef9145ed213abdf1ae743929de145a77c43656f01a8", + "scripts/experiments/ternary_side.py": "93379b6e70cf58bb55432d9f2d1c0e0305c20a075bfe3cc219deabd927afd375", + "scripts/incidence_rectangles.py": "5240fd33dcc3096f5685d10ca360186cad36b355a00d55686a4ea4449417d00e", + "scripts/paired_exclusion_circuit.py": "8f05f04cf06217befd6d0ee0f2d7d0c5c5eb32cfab8c9a8ca7917fd6d620b7d2", + "scripts/paired_network.py": "991223dc3c1374284c361ed017e42bf732dd971fa0bea2be2282cfb18257b3f7", + "scripts/prepare_layers.py": "a6e2adc612f264b1c0e51d18ce6315de9ae5e2ae2420aa22e99a22d8bf304947", + "scripts/rational_tensor.py": "629b3f00a1aaab32fe908a73ca8f8412918209a300e6b1e5afe6325b9cfed3c3", + "scripts/search_network.py": "3a4faa5037d9b8e7ca5828afac193a96b6966a8b114f14937921795b24ec4f6a", + "scripts/shared_point_circuit.py": "c9bb7a5df92d260a4e3ad532b53e26936730d7c93f7facfb0784957c1e81c8ba", + "scripts/shared_point_network.py": "a85e7f0d8c42d6a27e3846308571ca324a1824ac5c2d59e4daa5c7673c33c697" + } +} diff --git a/research/ternary-frame-cache/evidence/ADAPTATION.diff b/research/ternary-frame-cache/evidence/ADAPTATION.diff new file mode 100644 index 0000000000..daba467927 --- /dev/null +++ b/research/ternary-frame-cache/evidence/ADAPTATION.diff @@ -0,0 +1,37 @@ +--- scripts/experiments/ternary_side.py::verify_invocation_frames ++++ research/ternary-frame-cache/fast.py::verify_invocation_frames +@@ -1,12 +1,14 @@ +-def verify_invocation_frames(result): ++def verify_invocation_frames(result, *, observe=None, statistics=None): + """Every physical rational edge of both signed invocation directions.""" + from audit_joint_frames import eye,zero,matrix,row_basis,product,inverse,sub,rank ++ cache = FrameCache(rank, sub) + code=small_program(result);g=result['_graph'];n=result['n'];h=result['h'] + S=code['roles'];r=comb(h,2);W=2*n+S+r + H=matrix([[Q(int(i==j))-Q(2,25) for j in range(h)] for i in range(h)]) + I,Z=eye(h),zero(h) + require(rank(H)==h,'Degenerate ambient form') + lines=[(tuple(Q(int(t>>i&1)) for i in range(h)),) for t in g['labels']] ++ @lru_cache(maxsize=None) + def projection(U): + Ut=matrix(zip(*U));UH=product(U,H) + P=product(product(Ut,inverse(product(UH,Ut))),UH) +@@ -31,7 +33,8 @@ + def touch(ports,F): + nonlocal cost,lost,edges + for slot in set(ports): +- old=physical[slot];a=rank(sub(F,old));change=rank(F)-rank(old) ++ old=physical[slot];a,change=cache.transition(old,F) ++ if observe is not None: observe(reverse,slot,old,F,a,change) + require(a==abs(change),'A physical edge has a non-nested rank charge') + cost+=a;lost+=max(0,-change);edges+=1;physical[slot]=F + program=('L','J','l','R','V','G','R','L','J','l','G','V') +@@ -57,5 +60,8 @@ + require(lost==r*h and cost==W*h-2*n+2*r*h,'Invocation rank ledger failed') + evidence.append(dict(reverse=reverse,physical_edges=edges,rank_sum=cost, + decreasing_dimensions=lost,expected=W*h-2*n+2*r*h)) ++ if statistics is not None: ++ statistics.update(cache.statistics()) ++ statistics['projection_cache'] = projection.cache_info()._asdict() + return dict(h=h,ordinary_rational_frame_edges_checked=True, + common_pair_source_spans_checked=True,orientations=evidence) diff --git a/research/ternary-frame-cache/evidence/benchmark-python311.json b/research/ternary-frame-cache/evidence/benchmark-python311.json new file mode 100644 index 0000000000..1d833ad201 --- /dev/null +++ b/research/ternary-frame-cache/evidence/benchmark-python311.json @@ -0,0 +1,271 @@ +{ + "assignment_seed": 93, + "base_commit": "1b59b624d21924f8e3537cdc1ac52d3be6eda2fe", + "complete_ordered_edge_transcripts": { + "8": { + "exact_frames": 114, + "payload_sha256": "db9475eac5d9925ed94beebef92a841991a2433a2ebde43a14cd9e0a0e4387ae", + "physical_edges": 9464 + }, + "9": { + "exact_frames": 4422, + "payload_sha256": "cf7499baeffb2186e72c1f95c273a1e3ed0e7240ee76a95b93c5dfd0b23c5e8e", + "physical_edges": 75208 + } + }, + "control_exit_code": 0, + "controls_log_sha256": "0db60d28ad43a7f12d511abba8f37226e4cfb2f266ba7b0979af5e72a47f0460", + "historical_controls": [ + { + "construction": { + "active_additions": 0, + "active_sha256": "3ea776af8fb9faf012638426623731f03463b40eaa94a02980082e962ea2022f", + "allocated_additions": 1184, + "central_factor_size": 28, + "counts": { + "L": 2107392, + "N": 175616, + "W": 4039168, + "d": 8, + "deficit": -4039168, + "density": "1/4", + "m": 512, + "n": 56, + "positive": false, + "r": 28, + "relative_deficit": "-1/512", + "removed_roles": 1843968, + "s": 2072093184, + "side_roles_per_invocation": 560, + "unshared_W": 5883136 + }, + "edges_sha256": "c3d4f9b8dcb0c958447b8f9266c0f11d7096093c4539115a63b55eaf7587a5f0", + "exact_signature_controls_checked": true, + "full_small_coefficient_maps_checked": true, + "h": 8, + "local_template": { + "additions": 318, + "coefficients": 560, + "dag_sha256": "697fc47530c26f26763bc8a320c1546827b8e861f6137388dd44e60cd4a80d29", + "disjoint_additions_verified": true, + "embedding_verified": true, + "h": 8, + "inputs": 56, + "integer_coefficient_map_verified": true, + "k": 3, + "outputs": 56, + "roles": 374, + "unshared_recurrence_additions": 334 + }, + "n": 56, + "output_uses": 560, + "roots_sha256": "eefa6378d49bc39a28a339bf31e0e3e3e72d1cc7695f4c47c2027bef97d863e5", + "scalar_prime": 3, + "sharing_entries": 308, + "side_roles": 560, + "targets_sha256": "103dfd07c0c8476ccd02dc3d28dee27fad71ca1f47fa257e41c522f5fec5231d" + }, + "frames": { + "common_pair_source_spans_checked": true, + "h": 8, + "ordinary_rational_frame_edges_checked": true, + "orientations": [ + { + "decreasing_dimensions": 224, + "expected": 5936, + "physical_edges": 4732, + "rank_sum": 5936, + "reverse": false + }, + { + "decreasing_dimensions": 224, + "expected": 5936, + "physical_edges": 4732, + "rank_sum": 5936, + "reverse": true + } + ] + }, + "scalar": { + "both_signed_directions_checked": true, + "central_roles": 28, + "every_auxiliary_input_restored": true, + "h": 8, + "independent_roles": 700, + "scalar_operations": 5488, + "side_roles": 560 + } + }, + { + "construction": { + "active_additions": 2084, + "active_sha256": "e274fac6c02a575c77c7b9acf2d3c57dc0a32c3f79ab7f9cb8c6c46a2c2dde5b", + "allocated_additions": 6012, + "central_factor_size": 36, + "counts": { + "L": 15431472, + "N": 2000376, + "W": 111322512, + "d": 9, + "deficit": -28862568, + "density": "7/18", + "m": 729, + "n": 126, + "positive": false, + "r": 36, + "relative_deficit": "-101/283986", + "removed_roles": 53660880, + "s": 81182973816, + "side_roles_per_invocation": 3344, + "unshared_W": 164983392 + }, + "edges_sha256": "6b103508414c00d05d9ab126276ce524986792323a9a7566f0d92a72c31acbd6", + "exact_signature_controls_checked": true, + "full_small_coefficient_maps_checked": true, + "h": 9, + "local_template": { + "additions": 693, + "coefficients": 1680, + "dag_sha256": "f87ec07b00ef7e215aa6f4a2fc5c6672270a0e44e96c82725ecb71eca0786362", + "disjoint_additions_verified": true, + "embedding_verified": true, + "h": 9, + "inputs": 84, + "integer_coefficient_map_verified": true, + "k": 3, + "outputs": 84, + "roles": 777, + "unshared_recurrence_additions": 748 + }, + "n": 126, + "output_uses": 1260, + "roots_sha256": "6634a7c6df13b495e4342b4a008bbd308464813bad8479a3dd0efeac9e0c1b0d", + "scalar_prime": 3, + "sharing_entries": 1578, + "side_roles": 3344, + "targets_sha256": "39bf9b26dd01c0c73e4d95a6655ae6133a955d61866a3f39ab1026d912a6ec27" + }, + "frames": { + "common_pair_source_spans_checked": true, + "h": 9, + "ordinary_rational_frame_edges_checked": true, + "orientations": [ + { + "decreasing_dimensions": 324, + "expected": 33084, + "physical_edges": 37604, + "rank_sum": 33084, + "reverse": false + }, + { + "decreasing_dimensions": 324, + "expected": 33084, + "physical_edges": 37604, + "rank_sum": 33084, + "reverse": true + } + ] + }, + "scalar": { + "both_signed_directions_checked": true, + "central_roles": 36, + "every_auxiliary_input_restored": true, + "h": 9, + "independent_roles": 3632, + "scalar_operations": 29020, + "side_roles": 3344 + } + } + ], + "implementation_sha256": { + "fast.py": "82e487d9a6fde321cbbb0b0c5208c5b0471cc2b9e0cf059452174ef456b41b55", + "frame_cache.py": "859314e505cbac093aaf58f5a9037f0b5980662c769e94ed808a30e7e0022cbe", + "run.py": "d4902bc21a3f1082c22b1015a31a56d1f2ad54aeb4df840f018d336700c451d7", + "support.py": "f0211f40878af4647e66c762254d0b9db200961f450557faa1391a36708423dc", + "test_package.py": "23c514dc6482246d3f28667450b8f76457b9dd40af096686f646d42573e35270", + "verify.py": "b23846a883d7738f4d435d67fd45c3acdbafd3f60e3913814419a69c641d0f07" + }, + "limits": [ + "Historical h=8,9 small controls only; no h=29 DAG or assembly replay.", + "No selected frontier replay, new kappa, or all-size theorem proof.", + "Fresh interpreters; shared host; OS caches not flushed; no speed threshold.", + "Transcript equality includes full rational matrices; gzip bytes are not compared." + ], + "median_wall_seconds": { + "cached": 11.202519083046354, + "reference": 21.494933958048932 + }, + "platform": "macOS-27.0.1-arm64-arm-64bit", + "python": "3.11.5 (v3.11.5:cce6ba91b3, Aug 24 2023, 10:50:31) [Clang 13.0.0 (clang-1300.0.29.30)]", + "ratio_of_medians": 1.9187589682912383, + "source_manifest_sha256": "95c4d614d18d4464c7ba17c09df49b49478a203e455315489cb3db541acfe8e3", + "status": "PASS_IDENTICAL_TERNARY_FRAME_REPLAY", + "timings": [ + { + "engine": "reference", + "frame_seconds": 21.02861320890952, + "max_rss_bytes": 103628800, + "measurements": [ + { + "cache": {}, + "complete_seconds": 1.3403808750445023, + "frame_seconds": 1.3270297918934375, + "h": 8 + }, + { + "cache": {}, + "complete_seconds": 19.78705987497233, + "frame_seconds": 19.70158341701608, + "h": 9 + } + ], + "pair": 0, + "wall_seconds": 21.494933958048932 + }, + { + "engine": "cached", + "frame_seconds": 10.751473000040278, + "max_rss_bytes": 114622464, + "measurements": [ + { + "cache": { + "edge_calls": 9464, + "exact_frames": 114, + "hits": 8564, + "ordered_pairs": 900, + "projection_cache": { + "currsize": 56, + "hits": 56, + "maxsize": null, + "misses": 56 + }, + "retained_matrix_objects": 338 + }, + "complete_seconds": 0.3375280840555206, + "frame_seconds": 0.3248289580224082, + "h": 8 + }, + { + "cache": { + "edge_calls": 75208, + "exact_frames": 4422, + "hits": 58096, + "ordered_pairs": 17112, + "projection_cache": { + "currsize": 2210, + "hits": 126, + "maxsize": null, + "misses": 2210 + }, + "retained_matrix_objects": 4926 + }, + "complete_seconds": 10.52117812493816, + "frame_seconds": 10.42664404201787, + "h": 9 + } + ], + "pair": 0, + "wall_seconds": 11.202519083046354 + } + ] +} diff --git a/research/ternary-frame-cache/evidence/benchmark-python314.json b/research/ternary-frame-cache/evidence/benchmark-python314.json new file mode 100644 index 0000000000..6ac1504486 --- /dev/null +++ b/research/ternary-frame-cache/evidence/benchmark-python314.json @@ -0,0 +1,403 @@ +{ + "assignment_seed": 93, + "base_commit": "1b59b624d21924f8e3537cdc1ac52d3be6eda2fe", + "complete_ordered_edge_transcripts": { + "8": { + "exact_frames": 114, + "payload_sha256": "db9475eac5d9925ed94beebef92a841991a2433a2ebde43a14cd9e0a0e4387ae", + "physical_edges": 9464 + }, + "9": { + "exact_frames": 4422, + "payload_sha256": "cf7499baeffb2186e72c1f95c273a1e3ed0e7240ee76a95b93c5dfd0b23c5e8e", + "physical_edges": 75208 + } + }, + "control_exit_code": 0, + "controls_log_sha256": "454938c655750c7ef38aae43c47d5569028251000e57fb8a8c7855ea1d44805d", + "historical_controls": [ + { + "construction": { + "active_additions": 0, + "active_sha256": "3ea776af8fb9faf012638426623731f03463b40eaa94a02980082e962ea2022f", + "allocated_additions": 1184, + "central_factor_size": 28, + "counts": { + "L": 2107392, + "N": 175616, + "W": 4039168, + "d": 8, + "deficit": -4039168, + "density": "1/4", + "m": 512, + "n": 56, + "positive": false, + "r": 28, + "relative_deficit": "-1/512", + "removed_roles": 1843968, + "s": 2072093184, + "side_roles_per_invocation": 560, + "unshared_W": 5883136 + }, + "edges_sha256": "c3d4f9b8dcb0c958447b8f9266c0f11d7096093c4539115a63b55eaf7587a5f0", + "exact_signature_controls_checked": true, + "full_small_coefficient_maps_checked": true, + "h": 8, + "local_template": { + "additions": 318, + "coefficients": 560, + "dag_sha256": "697fc47530c26f26763bc8a320c1546827b8e861f6137388dd44e60cd4a80d29", + "disjoint_additions_verified": true, + "embedding_verified": true, + "h": 8, + "inputs": 56, + "integer_coefficient_map_verified": true, + "k": 3, + "outputs": 56, + "roles": 374, + "unshared_recurrence_additions": 334 + }, + "n": 56, + "output_uses": 560, + "roots_sha256": "eefa6378d49bc39a28a339bf31e0e3e3e72d1cc7695f4c47c2027bef97d863e5", + "scalar_prime": 3, + "sharing_entries": 308, + "side_roles": 560, + "targets_sha256": "103dfd07c0c8476ccd02dc3d28dee27fad71ca1f47fa257e41c522f5fec5231d" + }, + "frames": { + "common_pair_source_spans_checked": true, + "h": 8, + "ordinary_rational_frame_edges_checked": true, + "orientations": [ + { + "decreasing_dimensions": 224, + "expected": 5936, + "physical_edges": 4732, + "rank_sum": 5936, + "reverse": false + }, + { + "decreasing_dimensions": 224, + "expected": 5936, + "physical_edges": 4732, + "rank_sum": 5936, + "reverse": true + } + ] + }, + "scalar": { + "both_signed_directions_checked": true, + "central_roles": 28, + "every_auxiliary_input_restored": true, + "h": 8, + "independent_roles": 700, + "scalar_operations": 5488, + "side_roles": 560 + } + }, + { + "construction": { + "active_additions": 2084, + "active_sha256": "e274fac6c02a575c77c7b9acf2d3c57dc0a32c3f79ab7f9cb8c6c46a2c2dde5b", + "allocated_additions": 6012, + "central_factor_size": 36, + "counts": { + "L": 15431472, + "N": 2000376, + "W": 111322512, + "d": 9, + "deficit": -28862568, + "density": "7/18", + "m": 729, + "n": 126, + "positive": false, + "r": 36, + "relative_deficit": "-101/283986", + "removed_roles": 53660880, + "s": 81182973816, + "side_roles_per_invocation": 3344, + "unshared_W": 164983392 + }, + "edges_sha256": "6b103508414c00d05d9ab126276ce524986792323a9a7566f0d92a72c31acbd6", + "exact_signature_controls_checked": true, + "full_small_coefficient_maps_checked": true, + "h": 9, + "local_template": { + "additions": 693, + "coefficients": 1680, + "dag_sha256": "f87ec07b00ef7e215aa6f4a2fc5c6672270a0e44e96c82725ecb71eca0786362", + "disjoint_additions_verified": true, + "embedding_verified": true, + "h": 9, + "inputs": 84, + "integer_coefficient_map_verified": true, + "k": 3, + "outputs": 84, + "roles": 777, + "unshared_recurrence_additions": 748 + }, + "n": 126, + "output_uses": 1260, + "roots_sha256": "6634a7c6df13b495e4342b4a008bbd308464813bad8479a3dd0efeac9e0c1b0d", + "scalar_prime": 3, + "sharing_entries": 1578, + "side_roles": 3344, + "targets_sha256": "39bf9b26dd01c0c73e4d95a6655ae6133a955d61866a3f39ab1026d912a6ec27" + }, + "frames": { + "common_pair_source_spans_checked": true, + "h": 9, + "ordinary_rational_frame_edges_checked": true, + "orientations": [ + { + "decreasing_dimensions": 324, + "expected": 33084, + "physical_edges": 37604, + "rank_sum": 33084, + "reverse": false + }, + { + "decreasing_dimensions": 324, + "expected": 33084, + "physical_edges": 37604, + "rank_sum": 33084, + "reverse": true + } + ] + }, + "scalar": { + "both_signed_directions_checked": true, + "central_roles": 36, + "every_auxiliary_input_restored": true, + "h": 9, + "independent_roles": 3632, + "scalar_operations": 29020, + "side_roles": 3344 + } + } + ], + "implementation_sha256": { + "fast.py": "82e487d9a6fde321cbbb0b0c5208c5b0471cc2b9e0cf059452174ef456b41b55", + "frame_cache.py": "859314e505cbac093aaf58f5a9037f0b5980662c769e94ed808a30e7e0022cbe", + "run.py": "d4902bc21a3f1082c22b1015a31a56d1f2ad54aeb4df840f018d336700c451d7", + "support.py": "f0211f40878af4647e66c762254d0b9db200961f450557faa1391a36708423dc", + "test_package.py": "23c514dc6482246d3f28667450b8f76457b9dd40af096686f646d42573e35270", + "verify.py": "b23846a883d7738f4d435d67fd45c3acdbafd3f60e3913814419a69c641d0f07" + }, + "limits": [ + "Historical h=8,9 small controls only; no h=29 DAG or assembly replay.", + "No selected frontier replay, new kappa, or all-size theorem proof.", + "Fresh interpreters; shared host; OS caches not flushed; no speed threshold.", + "Transcript equality includes full rational matrices; gzip bytes are not compared." + ], + "median_wall_seconds": { + "cached": 6.775306833907962, + "reference": 11.52487129101064 + }, + "platform": "macOS-27.0.1-arm64-arm-64bit-Mach-O", + "python": "3.14.6 (main, Jun 10 2026, 10:03:53) [Clang 21.0.0 (clang-2100.0.123.102)]", + "ratio_of_medians": 1.7010109761129673, + "source_manifest_sha256": "95c4d614d18d4464c7ba17c09df49b49478a203e455315489cb3db541acfe8e3", + "status": "PASS_IDENTICAL_TERNARY_FRAME_REPLAY", + "timings": [ + { + "engine": "reference", + "frame_seconds": 10.665178249939345, + "max_rss_bytes": 100958208, + "measurements": [ + { + "cache": {}, + "complete_seconds": 0.6799633330665529, + "frame_seconds": 0.6661770000355318, + "h": 8 + }, + { + "cache": {}, + "complete_seconds": 10.083323874976486, + "frame_seconds": 9.999001249903813, + "h": 9 + } + ], + "pair": 0, + "wall_seconds": 11.072492875042371 + }, + { + "engine": "cached", + "frame_seconds": 6.188560874899849, + "max_rss_bytes": 110280704, + "measurements": [ + { + "cache": { + "edge_calls": 9464, + "exact_frames": 114, + "hits": 8564, + "ordered_pairs": 900, + "projection_cache": { + "currsize": 56, + "hits": 56, + "maxsize": null, + "misses": 56 + }, + "retained_matrix_objects": 338 + }, + "complete_seconds": 0.2024347089463845, + "frame_seconds": 0.18802366696763784, + "h": 8 + }, + { + "cache": { + "edge_calls": 75208, + "exact_frames": 4422, + "hits": 58096, + "ordered_pairs": 17112, + "projection_cache": { + "currsize": 2210, + "hits": 126, + "maxsize": null, + "misses": 2210 + }, + "retained_matrix_objects": 4926 + }, + "complete_seconds": 6.093446916900575, + "frame_seconds": 6.0005372079322115, + "h": 9 + } + ], + "pair": 0, + "wall_seconds": 6.664998500025831 + }, + { + "engine": "cached", + "frame_seconds": 6.295998542103916, + "max_rss_bytes": 110166016, + "measurements": [ + { + "cache": { + "edge_calls": 9464, + "exact_frames": 114, + "hits": 8564, + "ordered_pairs": 900, + "projection_cache": { + "currsize": 56, + "hits": 56, + "maxsize": null, + "misses": 56 + }, + "retained_matrix_objects": 338 + }, + "complete_seconds": 0.2136143749812618, + "frame_seconds": 0.1988690420985222, + "h": 8 + }, + { + "cache": { + "edge_calls": 75208, + "exact_frames": 4422, + "hits": 58096, + "ordered_pairs": 17112, + "projection_cache": { + "currsize": 2210, + "hits": 126, + "maxsize": null, + "misses": 2210 + }, + "retained_matrix_objects": 4926 + }, + "complete_seconds": 6.192647499963641, + "frame_seconds": 6.097129500005394, + "h": 9 + } + ], + "pair": 1, + "wall_seconds": 6.775306833907962 + }, + { + "engine": "reference", + "frame_seconds": 11.097046124981716, + "max_rss_bytes": 100859904, + "measurements": [ + { + "cache": {}, + "complete_seconds": 0.7043133339611813, + "frame_seconds": 0.690578458015807, + "h": 8 + }, + { + "cache": {}, + "complete_seconds": 10.503553292015567, + "frame_seconds": 10.40646766696591, + "h": 9 + } + ], + "pair": 1, + "wall_seconds": 11.52487129101064 + }, + { + "engine": "reference", + "frame_seconds": 11.472514832974412, + "max_rss_bytes": 100974592, + "measurements": [ + { + "cache": {}, + "complete_seconds": 0.6888633749913424, + "frame_seconds": 0.6740953749977052, + "h": 8 + }, + { + "cache": {}, + "complete_seconds": 10.887664875015616, + "frame_seconds": 10.798419457976706, + "h": 9 + } + ], + "pair": 2, + "wall_seconds": 11.9463620838942 + }, + { + "engine": "cached", + "frame_seconds": 6.503744499059394, + "max_rss_bytes": 109920256, + "measurements": [ + { + "cache": { + "edge_calls": 9464, + "exact_frames": 114, + "hits": 8564, + "ordered_pairs": 900, + "projection_cache": { + "currsize": 56, + "hits": 56, + "maxsize": null, + "misses": 56 + }, + "retained_matrix_objects": 338 + }, + "complete_seconds": 0.1942131669493392, + "frame_seconds": 0.17929916607681662, + "h": 8 + }, + { + "cache": { + "edge_calls": 75208, + "exact_frames": 4422, + "hits": 58096, + "ordered_pairs": 17112, + "projection_cache": { + "currsize": 2210, + "hits": 126, + "maxsize": null, + "misses": 2210 + }, + "retained_matrix_objects": 4926 + }, + "complete_seconds": 6.414872374967672, + "frame_seconds": 6.324445332982577, + "h": 9 + } + ], + "pair": 2, + "wall_seconds": 6.9345303329173476 + } + ] +} diff --git a/research/ternary-frame-cache/evidence/controls-python311.log b/research/ternary-frame-cache/evidence/controls-python311.log new file mode 100644 index 0000000000..181b2cd24c --- /dev/null +++ b/research/ternary-frame-cache/evidence/controls-python311.log @@ -0,0 +1,23 @@ +test_disabled_assertions_rejected (__main__.AdmissionControls.test_disabled_assertions_rejected) ... ok +test_each_pinned_dependency_invalidates (__main__.AdmissionControls.test_each_pinned_dependency_invalidates) ... ok +test_loaded_dependency_closure (__main__.AdmissionControls.test_loaded_dependency_closure) ... ok +test_output_reuse_rejected (__main__.AdmissionControls.test_output_reuse_rejected) ... ok +test_transcript_rejects_omission_duplication_order_and_matrix_faults (__main__.AdmissionControls.test_transcript_rejects_omission_duplication_order_and_matrix_faults) ... ok +test_all_two_by_two_binary_matrix_pairs (__main__.CacheSemantics.test_all_two_by_two_binary_matrix_pairs) ... ok +test_direction_controls_signed_dimension_change (__main__.CacheSemantics.test_direction_controls_signed_dimension_change) ... ok +test_hash_collision_uses_exact_equality (__main__.CacheSemantics.test_hash_collision_uses_exact_equality) ... ok +test_identity_entries_hold_strong_references (__main__.CacheSemantics.test_identity_entries_hold_strong_references) ... ok +test_same_rank_is_not_same_frame (__main__.CacheSemantics.test_same_rank_is_not_same_frame) ... ok +test_seeded_rational_pairs_and_equal_copies (__main__.CacheSemantics.test_seeded_rational_pairs_and_equal_copies) ... ok +test_changed_graph_after_success_is_rechecked (__main__.CheckerControls.test_changed_graph_after_success_is_rechecked) ... ok +test_complete_h8_ordered_trace (__main__.CheckerControls.test_complete_h8_ordered_trace) ... ok +test_missing_common_pair (__main__.CheckerControls.test_missing_common_pair) ... ok +test_non_idempotent_projection (__main__.CheckerControls.test_non_idempotent_projection) ... ok +test_singular_input_gram (__main__.CheckerControls.test_singular_input_gram) ... ok +test_wrong_role_count (__main__.CheckerControls.test_wrong_role_count) ... ok +test_wrong_target_frame (__main__.CheckerControls.test_wrong_target_frame) ... ok + +---------------------------------------------------------------------- +Ran 18 tests in 5.943s + +OK diff --git a/research/ternary-frame-cache/evidence/controls-python314.log b/research/ternary-frame-cache/evidence/controls-python314.log new file mode 100644 index 0000000000..1c8ffcc944 --- /dev/null +++ b/research/ternary-frame-cache/evidence/controls-python314.log @@ -0,0 +1,23 @@ +test_disabled_assertions_rejected (__main__.AdmissionControls.test_disabled_assertions_rejected) ... ok +test_each_pinned_dependency_invalidates (__main__.AdmissionControls.test_each_pinned_dependency_invalidates) ... ok +test_loaded_dependency_closure (__main__.AdmissionControls.test_loaded_dependency_closure) ... ok +test_output_reuse_rejected (__main__.AdmissionControls.test_output_reuse_rejected) ... ok +test_transcript_rejects_omission_duplication_order_and_matrix_faults (__main__.AdmissionControls.test_transcript_rejects_omission_duplication_order_and_matrix_faults) ... ok +test_all_two_by_two_binary_matrix_pairs (__main__.CacheSemantics.test_all_two_by_two_binary_matrix_pairs) ... ok +test_direction_controls_signed_dimension_change (__main__.CacheSemantics.test_direction_controls_signed_dimension_change) ... ok +test_hash_collision_uses_exact_equality (__main__.CacheSemantics.test_hash_collision_uses_exact_equality) ... ok +test_identity_entries_hold_strong_references (__main__.CacheSemantics.test_identity_entries_hold_strong_references) ... ok +test_same_rank_is_not_same_frame (__main__.CacheSemantics.test_same_rank_is_not_same_frame) ... ok +test_seeded_rational_pairs_and_equal_copies (__main__.CacheSemantics.test_seeded_rational_pairs_and_equal_copies) ... ok +test_changed_graph_after_success_is_rechecked (__main__.CheckerControls.test_changed_graph_after_success_is_rechecked) ... ok +test_complete_h8_ordered_trace (__main__.CheckerControls.test_complete_h8_ordered_trace) ... ok +test_missing_common_pair (__main__.CheckerControls.test_missing_common_pair) ... ok +test_non_idempotent_projection (__main__.CheckerControls.test_non_idempotent_projection) ... ok +test_singular_input_gram (__main__.CheckerControls.test_singular_input_gram) ... ok +test_wrong_role_count (__main__.CheckerControls.test_wrong_role_count) ... ok +test_wrong_target_frame (__main__.CheckerControls.test_wrong_target_frame) ... ok + +---------------------------------------------------------------------- +Ran 18 tests in 2.692s + +OK diff --git a/research/ternary-frame-cache/evidence/original-ternary-tests.log b/research/ternary-frame-cache/evidence/original-ternary-tests.log new file mode 100644 index 0000000000..259f8219b5 --- /dev/null +++ b/research/ternary-frame-cache/evidence/original-ternary-tests.log @@ -0,0 +1,10 @@ +test_complete_rational_frame_edges (test_ternary_side.TernarySideTest.test_complete_rational_frame_edges) ... ok +test_exact_assembly_and_guard_reuse (test_ternary_side.TernarySideTest.test_exact_assembly_and_guard_reuse) ... ok +test_global_signature_and_arbitrary_input_controls (test_ternary_side.TernarySideTest.test_global_signature_and_arbitrary_input_controls) ... ok +test_packed_field_arithmetic_exhaustive (test_ternary_side.TernarySideTest.test_packed_field_arithmetic_exhaustive) ... ok +test_resource_limits (test_ternary_side.TernarySideTest.test_resource_limits) ... ok + +---------------------------------------------------------------------- +Ran 5 tests in 10.829s + +OK diff --git a/research/ternary-frame-cache/evidence/profile-python314.txt b/research/ternary-frame-cache/evidence/profile-python314.txt new file mode 100644 index 0000000000..4280614983 --- /dev/null +++ b/research/ternary-frame-cache/evidence/profile-python314.txt @@ -0,0 +1,28 @@ +Tue Oct 13 16:00:15 2026 ../ternary-baseline.prof + + 207981650 function calls in 32.766 seconds + + Ordered by: cumulative time + List reduced from 59 to 20 due to restriction <20> + + ncalls tottime percall cumtime percall filename:lineno(function) + 1 0.038 0.038 33.609 33.609 ternary_side.py:164(verify_invocation_frames) + 25960 1.796 0.000 22.815 0.001 ternary_side.py:194(touch) + 15153470 3.429 0.000 14.736 0.000 fractions.py:697(forward) + 2336 0.031 0.000 10.110 0.004 ternary_side.py:173(projection) + 11680 0.190 0.000 9.380 0.001 audit_joint_frames.py:59(product) + 12353472 3.915 0.000 8.977 0.000 fractions.py:1000(__eq__) + 533500 0.772 0.000 8.383 0.000 {built-in method builtins.sum} + 77922 0.096 0.000 7.655 0.000 audit_joint_frames.py:24(sub) + 7012980 1.041 0.000 6.824 0.000 audit_joint_frames.py:24() + 29524835 2.772 0.000 5.515 0.000 {built-in method builtins.isinstance} + 7474712 2.219 0.000 4.914 0.000 fractions.py:810(_sub) + 15686970 3.299 0.000 4.488 0.000 fractions.py:361(_from_coprime_ints) + 9852 0.017 0.000 4.082 0.000 audit_joint_frames.py:29(rank) + 9852 0.549 0.000 4.065 0.000 audit_fused_block.py:113(rational_rank) + 3858028 0.569 0.000 3.961 0.000 audit_joint_frames.py:60() + 4487477 1.644 0.000 3.381 0.000 fractions.py:826(_mul) + 14371365 1.499 0.000 2.743 0.000 :117(__instancecheck__) + 3324528 1.061 0.000 2.224 0.000 fractions.py:794(_add) + 2044459 1.139 0.000 1.987 0.000 fractions.py:206(__new__) + 17731429 1.367 0.000 1.367 0.000 {built-in method __new__ of type object at 0x1017fc908} diff --git a/research/ternary-frame-cache/evidence/retained-paths-unchanged.log b/research/ternary-frame-cache/evidence/retained-paths-unchanged.log new file mode 100644 index 0000000000..e69de29bb2 diff --git a/research/ternary-frame-cache/evidence/selected-source-binding.log b/research/ternary-frame-cache/evidence/selected-source-binding.log new file mode 100644 index 0000000000..cb630f4f9f --- /dev/null +++ b/research/ternary-frame-cache/evidence/selected-source-binding.log @@ -0,0 +1 @@ +PASS selected record, exact kappa, original source inventory and proof supplement: 836330098538459/500000000000000000 diff --git a/research/ternary-frame-cache/evidence/validation.json b/research/ternary-frame-cache/evidence/validation.json new file mode 100644 index 0000000000..24e8734d64 --- /dev/null +++ b/research/ternary-frame-cache/evidence/validation.json @@ -0,0 +1,52 @@ +{ + "checks": [ + { + "name": "original-ternary-tests", + "command": [ + "/opt/homebrew/opt/python@3.14/bin/python3.14", + "-B", + "-m", + "unittest", + "discover", + "-s", + "tests", + "-p", + "test_ternary_side.py", + "-v" + ], + "exit_code": 0, + "seconds": 11.088661082903855, + "log_sha256": "225fd0e00e5628c6ee2cc385a71f27b9493bfbf3d39fd84850602e41e8834115" + }, + { + "name": "selected-source-binding", + "command": [ + "/opt/homebrew/opt/python@3.14/bin/python3.14", + "-B", + "scripts/verify_selected_result.py" + ], + "exit_code": 0, + "seconds": 0.8447829589713365, + "log_sha256": "af380595e879671607b258623d15268b93be53baf1f1401a62fc74e03eff86bd" + }, + { + "name": "retained-paths-unchanged", + "command": [ + "git", + "diff", + "--exit-code", + "1b59b624d21924f8e3537cdc1ac52d3be6eda2fe", + "--", + "upstream", + "scripts", + "certificates" + ], + "exit_code": 0, + "seconds": 0.06542449991684407, + "log_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + } + ], + "python": "3.14.6 (main, Jun 10 2026, 10:03:53) [Clang 21.0.0 (clang-2100.0.123.102)]", + "platform": "macOS-27.0.1-arm64-arm-64bit-Mach-O", + "full_trace_agreement_across_python311_python314": true +} diff --git a/research/ternary-frame-cache/fast.py b/research/ternary-frame-cache/fast.py new file mode 100644 index 0000000000..4c4c3cb81a --- /dev/null +++ b/research/ternary-frame-cache/fast.py @@ -0,0 +1,80 @@ +"""Opt-in adaptation of the retained historical ternary rational-frame check. + +The physical schedule and every require() are copied from the pinned +scripts/experiments/ternary_side.py by Douglas R. Colkitt. Changes: memoize +projection within this call; reuse exact ordered frame-pair arithmetic; expose +an optional observer and cache counters. No source or evidence is rewritten. +Hanson Sun, with substantial OpenAI Codex assistance. Apache-2.0. +""" +from functools import lru_cache +from experiments.ternary_side import small_program, Q, comb, require +from frame_cache import FrameCache + + +def verify_invocation_frames(result, *, observe=None, statistics=None): + """Every physical rational edge of both signed invocation directions.""" + from audit_joint_frames import eye,zero,matrix,row_basis,product,inverse,sub,rank + cache = FrameCache(rank, sub) + code=small_program(result);g=result['_graph'];n=result['n'];h=result['h'] + S=code['roles'];r=comb(h,2);W=2*n+S+r + H=matrix([[Q(int(i==j))-Q(2,25) for j in range(h)] for i in range(h)]) + I,Z=eye(h),zero(h) + require(rank(H)==h,'Degenerate ambient form') + lines=[(tuple(Q(int(t>>i&1)) for i in range(h)),) for t in g['labels']] + @lru_cache(maxsize=None) + def projection(U): + Ut=matrix(zip(*U));UH=product(U,H) + P=product(product(Ut,inverse(product(UH,Ut))),UH) + require(product(P,P)==P,'Non-idempotent frame') + return P + P=[projection(U) for U in lines];spans={};E={} + for x,is_active in enumerate(g['active']): + if not is_active:continue + if x<=n:spans[x]=lines[x-1] + else:spans[x]=row_basis(spans[g['left'][x]]+spans[g['right'][x]]) + require(g['common'][x].bit_count()>=2,'Missing common-pair positivity witness') + E[x]=projection(spans[x]) + index={t:i for i,t in enumerate(g['labels'])} + sources={index[t]:slot for t,slot in code['sources'].items()} + outputs={i:[] for i in range(n)} + for j,slot in code['outputs'].items():outputs[code['target_indices'][j]].append(slot) + evidence=[] + for reverse in (False,True): + physical=P+[Z]*n+[Z]*(S+r);cost=lost=edges=0 + X=list(range(n));Y=list(range(n,2*n));source,target=(Y,X) if reverse else (X,Y) + centers=list(range(2*n+S,W)) + def touch(ports,F): + nonlocal cost,lost,edges + for slot in set(ports): + old=physical[slot];a,change=cache.transition(old,F) + if observe is not None: observe(reverse,slot,old,F,a,change) + require(a==abs(change),'A physical edge has a non-nested rank charge') + cost+=a;lost+=max(0,-change);edges+=1;physical[slot]=F + program=('L','J','l','R','V','G','R','L','J','l','G','V') + frames=('0','0','0','0','X','1','0','u','Y','1','1','1') + if reverse: + program=tuple('l' if op=='L' else 'L' if op=='l' else op for op in reversed(program)) + frames=('0','0','0','X','u','1','0','Y','1','1','1','1') + for op,label in zip(program,frames): + if op in ('L','l'): + sequence=code['gates'] if op=='L' else reversed(code['gates']) + for node,ins,outs in sequence: + F=Z if label=='0' else I if label=='1' else sub(I,E[node]) if reverse else E[node] + touch([2*n+i for i in ins+outs],F) + elif op in ('V','J'): + for t in range(n): + slots=[sources[t]] if op=='V' else outputs[t] + data=source if op=='V' else target + F=Z if label=='0' else I if label=='1' else P[t] if label=='X' else sub(I,P[t]) + touch([data[t]]+[2*n+s for s in slots],F) + else:touch((source if op=='G' else target)+centers,Z if label=='0' else I) + ends=[I]*n+[sub(I,p) for p in P]+[I]*(S+r) + for slot,F in enumerate(ends):touch([slot],F) + require(lost==r*h and cost==W*h-2*n+2*r*h,'Invocation rank ledger failed') + evidence.append(dict(reverse=reverse,physical_edges=edges,rank_sum=cost, + decreasing_dimensions=lost,expected=W*h-2*n+2*r*h)) + if statistics is not None: + statistics.update(cache.statistics()) + statistics['projection_cache'] = projection.cache_info()._asdict() + return dict(h=h,ordinary_rational_frame_edges_checked=True, + common_pair_source_spans_checked=True,orientations=evidence) diff --git a/research/ternary-frame-cache/frame_cache.py b/research/ternary-frame-cache/frame_cache.py new file mode 100644 index 0000000000..92447280b6 --- /dev/null +++ b/research/ternary-frame-cache/frame_cache.py @@ -0,0 +1,47 @@ +"""Exact, invocation-local frame interning and ordered transition reuse. + +Hanson Sun, with substantial OpenAI Codex assistance. Apache-2.0. +The supplied rank and subtraction routines remain the retained rational ones. +""" + + +class FrameCache: + def __init__(self, rank, sub): + self.rank = rank + self.sub = sub + self.frames = [] + self.by_value = {} + # Keep the object alive alongside its index: id() reuse is impossible. + self.by_identity = {} + self.transitions = {} + self.calls = 0 + + def intern(self, frame): + identity = id(frame) + prior = self.by_identity.get(identity) + if prior is not None: + return prior[1] + # Tuple equality, not a digest or rank, identifies exact rational frames. + index = self.by_value.get(frame) + if index is None: + index = len(self.frames) + self.frames.append(frame) + self.by_value[frame] = index + self.by_identity[identity] = (frame, index) + return index + + def transition(self, old, new): + self.calls += 1 + key = (self.intern(old), self.intern(new)) + answer = self.transitions.get(key) + if answer is None: + answer = (self.rank(self.sub(new, old)), + self.rank(new) - self.rank(old)) + self.transitions[key] = answer + return answer + + def statistics(self): + return dict(edge_calls=self.calls, exact_frames=len(self.frames), + ordered_pairs=len(self.transitions), + hits=self.calls - len(self.transitions), + retained_matrix_objects=len(self.by_identity)) diff --git a/research/ternary-frame-cache/run.py b/research/ternary-frame-cache/run.py new file mode 100644 index 0000000000..47b87a33ea --- /dev/null +++ b/research/ternary-frame-cache/run.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Run all historical h=8,9 small controls with optional frame-pair reuse. + +Hanson Sun, with substantial OpenAI Codex assistance. Apache-2.0. +""" +import argparse +import gzip +import json +from pathlib import Path +import platform +import resource +import sys +import time + +from support import (ROOT, Trace, canonical, digest, expected_controls, need, + observed_reference, verify_loaded_sources, verify_sources) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--engine', choices=['reference', 'cached'], default='cached') + parser.add_argument('--out', type=Path, required=True) + parser.add_argument('--trace', action='store_true') + args = parser.parse_args() + verify_sources() + need(not args.out.exists(), 'Use a fresh output directory') + args.out.mkdir(parents=True) + start = time.perf_counter() + sys.path.insert(0, str(ROOT / 'scripts')) + from experiments import ternary_side as reference + from prepare_layers import serializable + import fast + expected = expected_controls() + controls = [] + measurements = [] + traces = {} + for h in (8, 9): + before = time.perf_counter() + graph = reference.build(h, retain_graph=True) + scalar = reference.verify_invocation(graph) + observer = Trace() if args.trace else None + stats = {} + frame_start = time.perf_counter() + if args.engine == 'reference': + checker = (reference.verify_invocation_frames if observer is None + else observed_reference(reference, observer)) + frames = checker(graph) + else: + frames = fast.verify_invocation_frames(graph, observe=observer, statistics=stats) + frame_seconds = time.perf_counter() - frame_start + graph.pop('_graph') + result = serializable(dict(construction=graph, scalar=scalar, frames=frames)) + # Match all historical fields, including exact DAG hashes and scalar + # controls, not merely a summary rank count. + need(json.loads(json.dumps(result)) == expected[h], 'Historical small controls differ') + controls.append(result) + measurements.append(dict(h=h, frame_seconds=frame_seconds, + complete_seconds=time.perf_counter() - before, + cache=stats)) + if observer is not None: + payload = observer.payload() + with gzip.open(args.out / ('trace-h%d.json.gz' % h), 'wb') as stream: + stream.write(canonical(payload)) + count = sum(x['physical_edges'] for x in frames['orientations']) + need(len(payload['edges']) == count, 'Incomplete observed physical edges') + traces[str(h)] = dict(physical_edges=count, + exact_frames=len(payload['matrices']), + payload_sha256=digest(payload)) + verify_loaded_sources() + usage = resource.getrusage(resource.RUSAGE_SELF) + result = dict(status='PASS_TERNARY_SMALL_CONTROLS', engine=args.engine, + controls=controls, trace=traces, measurements=measurements, + elapsed_seconds=time.perf_counter() - start, + max_rss_bytes=usage.ru_maxrss * (1 if sys.platform == 'darwin' else 1024), + python=sys.version, platform=platform.platform(), + source_manifest_sha256=digest(verify_sources())) + (args.out / 'RESULT.json').write_bytes(canonical(result) + b'\n') + print(result['status'], args.engine, '84672 physical edges') + + +if __name__ == '__main__': + main() diff --git a/research/ternary-frame-cache/support.py b/research/ternary-frame-cache/support.py new file mode 100644 index 0000000000..90b15bbd7a --- /dev/null +++ b/research/ternary-frame-cache/support.py @@ -0,0 +1,98 @@ +"""Source admission and exact edge transcripts for the optional checker. + +Hanson Sun, with substantial OpenAI Codex assistance. Apache-2.0. +""" +import hashlib +import inspect +import json +from pathlib import Path +import sys + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] + + +def need(ok, message): + if not ok: + raise ValueError(message) + + +def canonical(value): + return json.dumps(value, sort_keys=True, separators=(',', ':'), + allow_nan=False).encode('ascii') + + +def digest(value): + return hashlib.sha256(canonical(value)).hexdigest() + + +def verify_sources(root=ROOT): + need(not sys.flags.optimize, 'Assertions must remain enabled') + pins = json.loads((HERE / 'SOURCES.json').read_text()) + for relative, expected in pins['files'].items(): + actual = hashlib.sha256((root / relative).read_bytes()).hexdigest() + need(actual == expected, 'Pinned source changed: ' + relative) + return pins + + +def verify_loaded_sources(): + pins = verify_sources() + for module in tuple(sys.modules.values()): + filename = getattr(module, '__file__', None) + if filename is None: + continue + path = Path(filename).resolve() + if path.is_relative_to(ROOT / 'scripts') and path.suffix == '.py': + need(path.relative_to(ROOT).as_posix() in pins['files'], + 'Unpinned imported source: ' + str(path)) + + +class Trace: + """Record every visited edge, with full exact matrices rather than hashes.""" + def __init__(self): + self.matrices = [] + self.indices = {} + self.edges = [] + + def index(self, matrix): + if matrix not in self.indices: + self.indices[matrix] = len(self.matrices) + self.matrices.append(matrix) + return self.indices[matrix] + + def __call__(self, reverse, slot, old, new, rank_delta, dimension_delta): + self.edges.append([int(reverse), slot, self.index(old), self.index(new), + rank_delta, dimension_delta]) + + def payload(self): + return dict(matrices=[[[[x.numerator, x.denominator] for x in row] + for row in matrix] for matrix in self.matrices], + edges=self.edges) + + +def observed_reference(module, observe): + """Insert only a callback into the pinned original, before its edge check. + + Timed reference runs call the original function directly, without this + observer. This derived function is used solely for full trace comparison. + """ + source = inspect.getsource(module.verify_invocation_frames) + anchor = " require(a==abs(change),'A physical edge has a non-nested rank charge')" + need(source.count(anchor) == 1, 'Reference observer anchor changed') + source = source.replace(anchor, + ' observe(reverse,slot,old,F,a,change)\n' + anchor) + namespace = dict(vars(module), observe=observe) + exec(compile(source, '', 'exec', optimize=0), namespace) + return namespace['verify_invocation_frames'] + + +def expected_controls(): + certificate = json.loads((ROOT / 'certificates/ternary-side.json').read_text()) + return {control['construction']['h']: control + for control in certificate['complete_invocation_controls']} + + +def compare_traces(reference, candidate): + # Equality includes every numerator, denominator, orientation, slot, ordered + # endpoint, rank difference, and dimension change, with edge multiplicity. + need(reference == candidate, 'Complete ordered rational edge transcript differs') diff --git a/research/ternary-frame-cache/test_package.py b/research/ternary-frame-cache/test_package.py new file mode 100644 index 0000000000..01f0784fb3 --- /dev/null +++ b/research/ternary-frame-cache/test_package.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python3 +"""Differential semantic faults, cache collisions, and admission controls. + +Hanson Sun, with substantial OpenAI Codex assistance. Apache-2.0. +""" +import copy +from fractions import Fraction as Q +import itertools +import json +from pathlib import Path +import random +import shutil +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +from support import (HERE, ROOT, Trace, compare_traces, expected_controls, + observed_reference, verify_loaded_sources, verify_sources) + +verify_sources() +sys.path.insert(0, str(ROOT / 'scripts')) +from experiments import ternary_side as reference +from audit_joint_frames import matrix, rank, sub +from frame_cache import FrameCache +import fast + + +class CacheSemantics(unittest.TestCase): + def test_all_two_by_two_binary_matrix_pairs(self): + matrices = [matrix((xs[:2], xs[2:])) for xs in itertools.product((0, 1), repeat=4)] + cache = FrameCache(rank, sub) + for old, new in itertools.product(matrices, repeat=2): + expected = (rank(sub(new, old)), rank(new) - rank(old)) + self.assertEqual(cache.transition(old, new), expected) + self.assertEqual(cache.transition(old, new), expected) + self.assertEqual(cache.statistics()['ordered_pairs'], 256) + self.assertEqual(cache.statistics()['hits'], 256) + + def test_seeded_rational_pairs_and_equal_copies(self): + rng = random.Random(93) + cache = FrameCache(rank, sub) + for _ in range(200): + old, new = [matrix([[Q(rng.randrange(-3, 4), rng.randrange(1, 6)) + for _ in range(3)] for _ in range(3)]) for _ in range(2)] + expected = (rank(sub(new, old)), rank(new) - rank(old)) + self.assertEqual(cache.transition(old, new), expected) + copies = [tuple(tuple(Q(x.numerator, x.denominator) for x in row) + for row in m) for m in (old, new)] + before = cache.statistics()['ordered_pairs'] + self.assertEqual(cache.transition(*copies), expected) + self.assertEqual(cache.statistics()['ordered_pairs'], before) + + def test_same_rank_is_not_same_frame(self): + left = matrix(((1, 0), (0, 0))) + right = matrix(((0, 0), (0, 1))) + cache = FrameCache(rank, sub) + self.assertEqual(cache.transition(left, left), (0, 0)) + self.assertEqual(cache.transition(left, right), (2, 0)) + self.assertNotEqual(cache.intern(left), cache.intern(right)) + + def test_direction_controls_signed_dimension_change(self): + zero = matrix(((0, 0), (0, 0))) + line = matrix(((1, 0), (0, 0))) + cache = FrameCache(rank, sub) + self.assertEqual(cache.transition(zero, line), (1, 1)) + self.assertEqual(cache.transition(line, zero), (1, -1)) + + def test_hash_collision_uses_exact_equality(self): + modulus = sys.hash_info.modulus + zero, nonzero = matrix(((0,),)), matrix(((modulus,),)) + self.assertEqual(hash(zero), hash(nonzero)) + cache = FrameCache(rank, sub) + self.assertNotEqual(cache.intern(zero), cache.intern(nonzero)) + self.assertEqual(cache.transition(zero, zero), (0, 0)) + self.assertEqual(cache.transition(zero, nonzero), (1, 1)) + + def test_identity_entries_hold_strong_references(self): + cache = FrameCache(rank, sub) + for i in range(200): + value = matrix(((i % 3,),)) + cache.intern(value) + self.assertEqual(len(cache.frames), 3) + self.assertEqual(len(cache.by_identity), 200) + for identity, (value, index) in cache.by_identity.items(): + self.assertEqual(id(value), identity) + self.assertEqual(value, cache.frames[index]) + + +class CheckerControls(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.graph = reference.build(8, retain_graph=True) + + def reject_both(self, graph, message): + for checker in (reference.verify_invocation_frames, fast.verify_invocation_frames): + with self.subTest(checker=checker.__module__): + with self.assertRaisesRegex(ValueError, message): + checker(graph) + + def test_complete_h8_ordered_trace(self): + original, cached = Trace(), Trace() + first = observed_reference(reference, original)(self.graph) + second = fast.verify_invocation_frames(self.graph, observe=cached) + self.assertEqual(first, expected_controls()[8]['frames']) + self.assertEqual(first, second) + compare_traces(original.payload(), cached.payload()) + self.assertEqual(len(original.edges), 9464) + + def test_missing_common_pair(self): + bad = copy.deepcopy(self.graph) + bad['_graph']['common'][1] = 0 + self.reject_both(bad, 'Missing common-pair positivity witness') + + def test_singular_input_gram(self): + bad = copy.deepcopy(self.graph) + bad['_graph']['labels'][0] = 0 + self.reject_both(bad, 'Singular Gram matrix') + + def test_wrong_role_count(self): + bad = copy.deepcopy(self.graph) + bad['side_roles'] += 1 + self.reject_both(bad, 'Reversible role count failed') + + def test_wrong_target_frame(self): + bad = copy.deepcopy(self.graph) + bad['_graph']['targets'][0] = (bad['_graph']['targets'][0] + 1) % bad['n'] + self.reject_both(bad, 'A physical edge has a non-nested rank charge') + + def test_changed_graph_after_success_is_rechecked(self): + graph = copy.deepcopy(self.graph) + self.assertEqual(fast.verify_invocation_frames(graph), expected_controls()[8]['frames']) + graph['_graph']['common'][1] = 0 + with self.assertRaisesRegex(ValueError, 'Missing common-pair positivity witness'): + fast.verify_invocation_frames(graph) + + def test_non_idempotent_projection(self): + import audit_joint_frames as algebra + original = algebra.product + + def corrupt(left, right): + answer = original(left, right) + # Corrupt exactly the P*P idempotence comparison; all dimensions and + # input labels remain valid, so this must reach its semantic guard. + if left is right: + rows = [list(row) for row in answer] + rows[0][0] += 1 + return matrix(rows) + return answer + + with patch.object(algebra, 'product', corrupt): + self.reject_both(self.graph, 'Non-idempotent frame') + + +class AdmissionControls(unittest.TestCase): + def test_each_pinned_dependency_invalidates(self): + pins = verify_sources() + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + for relative in pins['files']: + destination = root / relative + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(ROOT / relative, destination) + verify_sources(root) + for relative in pins['files']: + with self.subTest(source=relative): + path = root / relative + raw = path.read_bytes() + path.write_bytes(raw + b'\n# deliberate source mutation\n') + with self.assertRaisesRegex(ValueError, 'Pinned source changed'): + verify_sources(root) + path.write_bytes(raw) + verify_sources(root) + + def test_disabled_assertions_rejected(self): + with tempfile.TemporaryDirectory() as temporary: + out = Path(temporary) / 'out' + result = subprocess.run([sys.executable, '-O', '-B', str(HERE / 'run.py'), + '--out', str(out)], capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0) + self.assertIn('Assertions must remain enabled', result.stderr) + self.assertFalse(out.exists()) + + def test_output_reuse_rejected(self): + with tempfile.TemporaryDirectory() as temporary: + result = subprocess.run([sys.executable, '-B', str(HERE / 'run.py'), + '--out', temporary], capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0) + self.assertIn('Use a fresh output directory', result.stderr) + + def test_transcript_rejects_omission_duplication_order_and_matrix_faults(self): + trace = Trace() + observed_reference(reference, trace)(reference.build(8, retain_graph=True)) + payload = trace.payload() + mutations = [] + missing = copy.deepcopy(payload); missing['edges'].pop(); mutations.append(missing) + duplicate = copy.deepcopy(payload); duplicate['edges'].append(duplicate['edges'][0]); mutations.append(duplicate) + reordered = copy.deepcopy(payload); reordered['edges'][0:2] = reordered['edges'][1::-1]; mutations.append(reordered) + changed = copy.deepcopy(payload); changed['matrices'][0][0][0][0] += 1; mutations.append(changed) + reversed_edge = copy.deepcopy(payload); reversed_edge['edges'][0][0] ^= 1; mutations.append(reversed_edge) + wrong_slot = copy.deepcopy(payload); wrong_slot['edges'][0][1] += 1; mutations.append(wrong_slot) + for i, mutation in enumerate(mutations): + with self.subTest(mutation=i): + with self.assertRaisesRegex(ValueError, 'Complete ordered rational edge transcript differs'): + compare_traces(payload, mutation) + + def test_loaded_dependency_closure(self): + verify_loaded_sources() + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/research/ternary-frame-cache/verify.py b/research/ternary-frame-cache/verify.py new file mode 100644 index 0000000000..a4a994a01f --- /dev/null +++ b/research/ternary-frame-cache/verify.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Compare complete exact edge streams and alternate fresh-process timings. + +Hanson Sun, with substantial OpenAI Codex assistance. Apache-2.0. +""" +import argparse +import gzip +import hashlib +import json +import os +from pathlib import Path +import platform +import statistics +import subprocess +import sys +import time + +from support import (HERE, ROOT, canonical, compare_traces, digest, need, + verify_sources) + + +def run(engine, path, trace=False): + command = [sys.executable, '-B', str(HERE / 'run.py'), '--engine', engine, + '--out', str(path)] + (['--trace'] if trace else []) + env = dict(os.environ, PYTHONDONTWRITEBYTECODE='1') + for key in ('PYTHONOPTIMIZE', 'PYTHONPATH', 'PYTHONSTARTUP'): + env.pop(key, None) + start = time.perf_counter() + process = subprocess.run(command, cwd=ROOT, env=env, capture_output=True, + text=True, timeout=300) + wall = time.perf_counter() - start + path.parent.joinpath(path.name + '.log').write_text(process.stdout + process.stderr) + need(process.returncode == 0, 'Worker failed: ' + path.name + '\n' + process.stderr) + report = json.loads((path / 'RESULT.json').read_text()) + need(report['status'] == 'PASS_TERNARY_SMALL_CONTROLS', 'Incomplete worker receipt') + return report, wall + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--out', type=Path, required=True) + parser.add_argument('--pairs', type=int, default=3) + args = parser.parse_args() + pins = verify_sources() + need(1 <= args.pairs <= 5, 'Use between one and five timing pairs') + need(not args.out.exists(), 'Use a fresh output directory') + args.out = args.out.resolve() + args.out.mkdir(parents=True) + controls = subprocess.run([sys.executable, '-B', str(HERE / 'test_package.py')], + cwd=ROOT, capture_output=True, text=True, timeout=300) + controls_log = controls.stdout + controls.stderr + (args.out / 'controls.log').write_text(controls_log) + need(controls.returncode == 0, 'Semantic or admission control failed\n' + controls_log) + print('PASS semantic and admission controls', flush=True) + observed = {} + for engine in ('reference', 'cached'): + observed[engine], _ = run(engine, args.out / ('observed-' + engine), True) + print('PASS complete observed replay:', engine, flush=True) + need(observed['reference']['controls'] == observed['cached']['controls'], + 'Complete mathematical control receipts differ') + trace_receipts = {} + for h in (8, 9): + payloads = [] + for engine in ('reference', 'cached'): + with gzip.open(args.out / ('observed-' + engine) / ('trace-h%d.json.gz' % h)) as stream: + payloads.append(json.load(stream)) + compare_traces(*payloads) + trace_receipts[str(h)] = observed['reference']['trace'][str(h)] + need(sum(x['physical_edges'] for x in trace_receipts.values()) == 84672, + 'Both complete historical domains required') + timings = [] + for pair in range(args.pairs): + order = ('reference', 'cached') if pair % 2 == 0 else ('cached', 'reference') + for engine in order: + report, wall = run(engine, args.out / ('pair-%d-%s' % (pair, engine))) + need(report['controls'] == observed['reference']['controls'], + 'Timed run changed a mathematical control') + timings.append(dict(pair=pair, engine=engine, wall_seconds=wall, + frame_seconds=sum(x['frame_seconds'] for x in report['measurements']), + max_rss_bytes=report['max_rss_bytes'], + measurements=report['measurements'])) + print('PASS timed replay:', pair, engine, round(wall, 3), 'seconds', flush=True) + verify_sources() + medians = {engine: statistics.median(x['wall_seconds'] for x in timings if x['engine'] == engine) + for engine in ('reference', 'cached')} + result = dict(status='PASS_IDENTICAL_TERNARY_FRAME_REPLAY', + base_commit=pins['base_commit'], assignment_seed=93, + source_manifest_sha256=digest(pins), + implementation_sha256={p.name: hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted(HERE.glob('*.py'))}, + control_exit_code=controls.returncode, + controls_log_sha256=hashlib.sha256(controls_log.encode()).hexdigest(), + historical_controls=observed['reference']['controls'], + complete_ordered_edge_transcripts=trace_receipts, + timings=timings, median_wall_seconds=medians, + ratio_of_medians=medians['reference'] / medians['cached'], + python=sys.version, platform=platform.platform(), + limits=['Historical h=8,9 small controls only; no h=29 DAG or assembly replay.', + 'No selected frontier replay, new kappa, or all-size theorem proof.', + 'Fresh interpreters; shared host; OS caches not flushed; no speed threshold.', + 'Transcript equality includes full rational matrices; gzip bytes are not compared.']) + (args.out / 'RESULT.json').write_text(json.dumps(result, indent=2, sort_keys=True) + '\n') + print(result['status'], '84672 edges;', round(result['ratio_of_medians'], 3), 'ratio of medians') + + +if __name__ == '__main__': + main()