From abff67b31fa781e950c82d95eccb6f168950943c Mon Sep 17 00:00:00 2001 From: Chris R Date: Mon, 2 Nov 2026 10:45:45 +1100 Subject: [PATCH] Repair bounded G12 custody cleanup and publication size checks Retain exact PR6339 predecessor bytes, implement the three narrow consultation repairs, and add normal/optimized source-function controls with explicit unresolved allocation counterexamples. No integrated source acceptance, H25 execution, adoption, performance or kappa claim. --- research/h25-g12-custody-repairs/README.md | 78 + .../SOURCE-IDENTITIES.json | 41 + research/h25-g12-custody-repairs/SOURCES.json | 522 +++++ research/h25-g12-custody-repairs/TASK.json | 66 + .../h25-g12-custody-repairs/VALIDATION.json | 1160 +++++++++++ research/h25-g12-custody-repairs/VERIFY.json | 119 ++ .../g12_reference_cold_consumer_v3.py | 1128 +++++++++++ .../corrected/g12_reference_parent_v3.py | 1779 +++++++++++++++++ .../g12_reference_cold_consumer_v2.py.txt | 1127 +++++++++++ .../g12_reference_parent_v2.py.txt | 1763 ++++++++++++++++ .../repairs-from-pr6339.patch | 146 ++ .../review/PRO-COMPOSED-REVIEW.json | 19 + .../review/PRO-SOURCE-REVIEW.txt | 449 +++++ research/h25-g12-custody-repairs/verify.py | 384 ++++ 14 files changed, 8781 insertions(+) create mode 100644 research/h25-g12-custody-repairs/README.md create mode 100644 research/h25-g12-custody-repairs/SOURCE-IDENTITIES.json create mode 100644 research/h25-g12-custody-repairs/SOURCES.json create mode 100644 research/h25-g12-custody-repairs/TASK.json create mode 100644 research/h25-g12-custody-repairs/VALIDATION.json create mode 100644 research/h25-g12-custody-repairs/VERIFY.json create mode 100644 research/h25-g12-custody-repairs/corrected/g12_reference_cold_consumer_v3.py create mode 100644 research/h25-g12-custody-repairs/corrected/g12_reference_parent_v3.py create mode 100644 research/h25-g12-custody-repairs/predecessor/g12_reference_cold_consumer_v2.py.txt create mode 100644 research/h25-g12-custody-repairs/predecessor/g12_reference_parent_v2.py.txt create mode 100644 research/h25-g12-custody-repairs/repairs-from-pr6339.patch create mode 100644 research/h25-g12-custody-repairs/review/PRO-COMPOSED-REVIEW.json create mode 100644 research/h25-g12-custody-repairs/review/PRO-SOURCE-REVIEW.txt create mode 100644 research/h25-g12-custody-repairs/verify.py diff --git a/research/h25-g12-custody-repairs/README.md b/research/h25-g12-custody-repairs/README.md new file mode 100644 index 0000000000..3dbf98fcc8 --- /dev/null +++ b/research/h25-g12-custody-repairs/README.md @@ -0,0 +1,78 @@ +# H25 G12 custody repairs and retained allocation counterexamples + +**Bounded source repair. Full P07/N22 integration remains open. No H25 execution or gain.** + +This is the explicitly assigned source follow-up to [PR6321](https://github.com/CrocSwap/integer-mult-bounds/pull/6321) and unpaidmoon's [PR6339](https://github.com/CrocSwap/integer-mult-bounds/pull/6339), frozen at `608ad23adc6c01264c8195daf7f18e29c17464a7`. It implements the three narrow repairs proposed by a ChatGPT Pro source consultation, adds executable source-function failure controls, and preserves the counterexamples that prevent a full-source acceptance claim. + +## Result and exact scope + +The corrected parent and consumer are new **unselected** successors. Their bytes are the consultation's reviewed proposal, now under v3 filenames. The predecessor's internal v2 description remains unchanged so the proposal hashes are preserved. Frozen H25 sources and PR6339 are not edited. + +- Seven raw-error ledgers are allocated before their function acquires new resources. A failure of that initial allocation therefore cannot strand those subsequently acquired resources or replace a previously caught local body error. +- P09 has an independent final release phase for recorded pidfds after its last process-disposal attempt. Persistent observation denial no longer bypasses the known release loop when snapshotting and error recording succeed. Numeric ownership is removed before close to avoid a blind retry after an ambiguous outcome. Failed or unknown cleanup stays unknown. +- The consumer requires an exact nonnegative integer `publication_size`, rejecting equal-valued floats, booleans and foreign integer subclasses. + +These are **conditional local repairs**, not a complete allocation-failure solution. `_close_known_descriptors` still allocates its ledger and snapshot while a primary can be pending; recording a close error can also fail. The verifier deliberately reproduces all three retained counterexamples. Acquisition-to-registration gaps and later raw-journal allocation remain open. Hoisting a ledger adds successful-path allocation and memory cost; no improvement or unchanged allocation availability is claimed. + +The tuple-to-dictionary conversion inherited from PR6339 remains intact. Both original exports, source/oracle checks and original producer are retained. Launch/handoff remain `None`. The old candidate authority/transport/mount graph is not silently selected or claimed adopted. + +## Reproduce + +Python 3.12, standard library only: + +```sh +python3 scripts/research_package.py --package research/h25-g12-custody-repairs --check-only +python3 scripts/research_package.py --package research/h25-g12-custody-repairs +``` + +The registered hook runs normal and optimized modes. Direct commands: + +```sh +python3 -I -W error -B research/h25-g12-custody-repairs/verify.py +python3 -I -O -W error -B research/h25-g12-custody-repairs/verify.py +``` + +Expected final line: + +```text +PASS_G12_BOUNDED_SOURCE_REPAIRS source_cases=41 metadata_checks=94 unresolved_preflight_allocation=3 no_integrated_acceptance +``` + +There are 41 source-function/window cases, including **three expected refutations of the stronger cleanup contract**, and 94 separate byte/AST/diff checks. These counts do not replace the original 52 helper bodies, add accepted N22/P07 body credit or certify all18 G12 branches. + +The verifier executes explicitly named **AST-extracted source functions/windows** with synthetic descriptor/process tokens. It does not import the full parent/consumer modules, invoke the H25 parent or original scientific CLI, call real close/signal/process operations, acquire a provider, compile native code or replay the author's old verifier. The original guarded/scientific budget is not used. + +## Evidence and source availability + +- [SOURCE-IDENTITIES.json](SOURCE-IDENTITIES.json): exact retained PR6339 bytes and corrected-source hashes, external commit and proposal provenance. +- [repairs-from-pr6339.patch](repairs-from-pr6339.patch): the complete146-line proposal diff. Verification applies it **in memory** to the retained v2 texts and compares every byte with v3. +- [verify.py](verify.py): normal/optimized source-function controls, negative predecessors, exact source deltas, closed selections and preserved unresolved witnesses. +- [review/PRO-SOURCE-REVIEW.txt](review/PRO-SOURCE-REVIEW.txt): the detailed prior AI source review, all18 branch categories, CP01-CP15 reasoning, source pins, counterexamples and unreviewed obligations. +- [review/PRO-COMPOSED-REVIEW.json](review/PRO-COMPOSED-REVIEW.json): a distinct consultation agent's bounded review of the exact composed draft. This is agent evidence, not human or proof-kernel acceptance. +- [VALIDATION.json](VALIDATION.json): actual local execution record and limits. + +The two PR6339 source inputs are retained as inert text because that commit is not an ancestor of canonical main. No private Git object cache or fetch of an unmerged commit is needed by the verifier. The external head is explicit provenance, not an ancestry claim. [SOURCES.json](SOURCES.json) and [VERIFY.json](VERIFY.json) declare all84 consulted archive files as live byte-bound inputs for CI invalidation, plus the fixed canonical catalogue/selected-result provenance. Hashing those inputs is not re-execution or semantic acceptance of them. + +The common frozen baseline remains PR6029. PR6316/6317 are independent usable log/archive packages, not dependencies. P02 is a separate lane. Source counts, complete adoption, actual execution, full-caller qualification, measured wall/CPU costs and kappa/frontier changes remain distinct. + +## Why this does not close P07/G12 + +A successful one-yield P07 local continuation checks the observed remainder after the same original CLI and validates its final `StopIteration.value`. Its intentional completion marker bypasses the normal driver's later full-native/full-anchor/late-last completion. Do not remove that marker as an assumed repair or count the local control as full caller qualification. + +The remaining source gate needs exception-safe acquisition/registration, a raw first-primary/secondary journal robust under the original failure model, complete nested-schema/alias review and an explicit parent/consumer/authority/driver pin-and-mount derivation. The source review's category matrix is coverage of questions, not acceptance of every predicate. + +Original C01-C15 costs, including added recorder allocation, retained traceback graphs, both exports, failed cleanup and final tails, remain required. Unknown physical/final costs are **OPEN_NOT_ZERO**; historical allowances are nontransferable. The original scope clarification does not require building a new generic enclosing accounting API. + +## Open next questions + +Structured questions and blockers are in [TASK.json](TASK.json). + +1. Can a finite preallocated ownership/raw-error journal meet the original allocation-failure contract without an additional interpreter or atomic-acquisition guarantee? First prove the exact failure boundary and acquisition-to-registration rule. A generic Python impossibility claim is not established by the current counterexamples. +2. After that gate, freeze and independently review the complete corrected source/mount/pin derivation for both N22 and P07. Genuine runtime/custody/admission remains a separate blocker, not a fabricated fixture. +3. Under separate future authorization, qualify the actual full caller and all original controls/costs. Nothing in this package authorizes an H25 replay or transfers historical budget. + +## Credit and license + +Chris R / Clear1nsight, with substantial OpenAI Codex implementation/verification assistance and ChatGPT Pro consultation assistance. The exact predecessor repairs and their attribution are retained from unpaidmoon with substantial Cursor Grok assistance (PR6339). Credit PR6321, PR6029, retained source/review contributors, Douglas R. Colkitt and the original circuit/network/native/verification lineage. Apache-2.0. + +The consultation's AI reviewers and the present checks do not establish independent human or formal proof-kernel acceptance. diff --git a/research/h25-g12-custody-repairs/SOURCE-IDENTITIES.json b/research/h25-g12-custody-repairs/SOURCE-IDENTITIES.json new file mode 100644 index 0000000000..4304ebf769 --- /dev/null +++ b/research/h25-g12-custody-repairs/SOURCE-IDENTITIES.json @@ -0,0 +1,41 @@ +{ + "schema": "h25-g12-custody-repair-source-identities-v1", + "upstream_base": "626e936ce4d61f2584316914fc71baf96940c512", + "external_pr": 6339, + "external_head": "608ad23adc6c01264c8195daf7f18e29c17464a7", + "cold_availability": "Exact two unmerged predecessor sources are retained here; no private object cache or external commit fetch is needed by verify.py. External head is provenance, not a claim of publication ancestry.", + "files": [ + { + "path": "predecessor/g12_reference_parent_v2.py.txt", + "bytes": 95532, + "sha256": "176f0ae0748e8f02a9a89b23e0d0fa684b6c6734ad0a68f705a802695046005e" + }, + { + "path": "corrected/g12_reference_parent_v3.py", + "bytes": 96341, + "sha256": "8b6b196c50d616e12d7966ea35bf6d65fd799a18556f362a7e17d2b1273a8bb8" + }, + { + "path": "predecessor/g12_reference_cold_consumer_v2.py.txt", + "bytes": 62128, + "sha256": "dc8a0b62d4175ee447469b7e66798160b85777f44e34d34e98b08af83a9f5a6d" + }, + { + "path": "corrected/g12_reference_cold_consumer_v3.py", + "bytes": 62156, + "sha256": "dcf00eb57fa3a0ebb7e35006125155c7843ede6602e90ae303a1fe49e673af3a" + } + ], + "pro_package_sha256": "789f352fb552eec32606f1726b299fcf5d3f478aace08b23779d362ea664da3c", + "source_adoption": false, + "full_source_acceptance": false, + "original_h25_execution": false, + "unresolved_preflight_oom": true, + "credit": [ + "Chris R / Clear1nsight", + "Douglas R. Colkitt and retained circuit/network/native lineage", + "PR6321 source/review contributors", + "unpaidmoon with substantial Cursor Grok assistance (PR6339)", + "OpenAI ChatGPT Pro and Codex assistance" + ] +} diff --git a/research/h25-g12-custody-repairs/SOURCES.json b/research/h25-g12-custody-repairs/SOURCES.json new file mode 100644 index 0000000000..22c0315341 --- /dev/null +++ b/research/h25-g12-custody-repairs/SOURCES.json @@ -0,0 +1,522 @@ +{ + "schema_version": 1, + "base_commit": "626e936ce4d61f2584316914fc71baf96940c512", + "files": [ + { + "path": "certificates/selected-result.json", + "usage": "provenance", + "git_blob": "d59b5035e7b4cbaa9d688a1d32dd0d6eb79c466a", + "sha256": "9b8d0eea95b3bf0dfcb7938a732a6439b87a2685dec2a5ab9e525b3b34debbfa" + }, + { + "path": "docs/research/agent-task-catalog.json", + "usage": "provenance", + "git_blob": "3404fbdd5e7529a0674eef26114b5071e4586cec", + "sha256": "ead6cdc9d0af6d58e8a49744d8ec8c7c15e13d2ba93c276c434bcf9b51b93a81" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-epoch-genuine-context-v1/cache_epoch_context_assembly_v1.py.txt", + "usage": "input", + "git_blob": "01f1e1ba2a9f2afc7322cbc5c09f7d96297ccc31", + "sha256": "9c2c5ffdbfc692b48ddba780258df7694ba376ef43e7d5ab14e8760a041851ad" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-epoch-products-v5/SOURCE-CASE-CONTEXTS.json", + "usage": "input", + "git_blob": "1d9202a3013b1e0135831b87bc6e61cad3c12702", + "sha256": "4eeb55857ff84aff47c17aaa3736bbeba2d525d1ed9ea129ffd35272669b00ff" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-epoch-products-v5/epoch_authority_products_v1.py.txt", + "usage": "input", + "git_blob": "5f825d8e9c7168017a8005944b594212116e84fa", + "sha256": "f279ab86fc17c6a517b035f19d56863919cbd8304de4e7d5332457c6159aec10" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-epoch-products-v5/epoch_cache_products_v1.py.txt", + "usage": "input", + "git_blob": "e35baaa9e335cd4bf56ec356228c459b57ab4384", + "sha256": "d317c9866566cd6147c96566879f26f364e7e6801ac3eed0800b6ed8eedd01a2" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-epoch-products-v5/epoch_data_products_v1.py.txt", + "usage": "input", + "git_blob": "33a9042bfcce6e4fed7fb439f5cf1c3e9f1e0e97", + "sha256": "18679fd1eb6ae99c4b375756511427c26718f77674c2d8fcc490e25ceb47cba5" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-epoch-products-v5/epoch_scientific_driver_v1.py.txt", + "usage": "input", + "git_blob": "3ae194abcc02a463552be1bd45c0abbf13e47d28", + "sha256": "1e8202b7a4c17fc8dfb0a001085c26bf2ec26a69eb6c8501763773324c2bd9a1" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-full-contract-completion-v1/cache_epoch_source_controls.py.txt", + "usage": "input", + "git_blob": "def9b50770981308480713a082a286e300a8aa00", + "sha256": "fcffe77b6a84d5b422b03e3d068924a701c1594cdb9ec305115827e3fad7d4b6" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v1/contracts/CALLER-EQUALITY-DEFINITION-v1.json", + "usage": "input", + "git_blob": "3ad1c33d32debc6a3930d29f923df31410d68f8c", + "sha256": "4a11f90727c636bdbaaf683d1ac95aa9234324698fb594a7da92a92f6a45c7eb" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v1/contracts/COMPLETE-SYMBOLIC-COST-DEFINITION-v1.json", + "usage": "input", + "git_blob": "929b3b08357e8503aba862ac15e644182c790f0c", + "sha256": "6ab22ebb387f15f9a1fd91e257ecae649eb4b177af32d4652c2eaec061e3b48c" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v1/coverage/COVERAGE-SPEC-v1.json", + "usage": "input", + "git_blob": "4af4b782e8f5f2d8b81feae57f9ec235cf791fe1", + "sha256": "e4599f79a9dd46a66c9b6cf63ceb7c03d19a0b98a550315b66d5b43dd544d691" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/continuation/candidate-protocol-v1/FREEZE-v1.json", + "usage": "input", + "git_blob": "b2f9027a0dbaf5f0751034de857ffe1adb2fa6c9", + "sha256": "4ee86e91c36c1651da2fa31506da27b3e479ae1883b0a0563818508cda839124" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/continuation/candidate-protocol-v1/g12_epoch_authority_selector_v1.py.txt", + "usage": "input", + "git_blob": "6ff0f5a0727840b954c79806be2c9839921a9cea", + "sha256": "65b3d33068b0549ddb4a9e7e18a9912bebad69c309a8a29ae4fd532e9f428211" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/continuation/candidate-protocol-v1/g12_epoch_cache_selector_v1.py.txt", + "usage": "input", + "git_blob": "d4d03997403b1e487f2aa0821d30a41c0b6b97e8", + "sha256": "20a8a94e96bfa6213d4f04244dabecf059b4c8c7e8ffa7e9409a8b87cfeef494" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/continuation/reference-producer-v2/g12_reference_driver_v2.py.txt", + "usage": "input", + "git_blob": "ddff4223b04b6e28d1e93a765b318d2cc6fb19bc", + "sha256": "a346025d5b6e2b26246521c6af6292643a4c2c3286b33ff3996dcf051cd6be26" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/COST-BILL-v1.json", + "usage": "input", + "git_blob": "405aa5e2f0cf03089b0e62d1177066fd3c7414df", + "sha256": "63abb4fb916b4b661dd47c0eadb62498c6adb96b2d6f0db338f1d89704e90f12" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/DESIGN-CORRECTION-v2.json", + "usage": "input", + "git_blob": "0d8dca016816ca7a392f28bf351725c55ed8fef5", + "sha256": "f7a71e8cf29b002fc98fb9a4a847c2257e5f8daa366bef60339b4e321067f02f" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/FREEZE-v1.json", + "usage": "input", + "git_blob": "7ee0493cd6496e113cd6f8c71fd519ef29f128de", + "sha256": "31afc1a99450482602b8403482a748fa245c1a6cb4bd6ff42afbb1d143232c49" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/NEGATIVE-BRANCHES-v1.json", + "usage": "input", + "git_blob": "f7a5a1b67819bef21a1c498574f6142cef2278b6", + "sha256": "998972cf17cca61c10d17978e900390c6e22e8f48a2682de0fc591fba9d12ca2" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/SOURCE-INVERSE-v1.json", + "usage": "input", + "git_blob": "01aab65deebf538a582c930b8317172544e205b8", + "sha256": "380416b2020654151afb95b716020ce5cdfaf68100e1841eb50a267d1af0b132" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/SOURCE-MAP-v1.json", + "usage": "input", + "git_blob": "126e53d8d3184d02ba77bdf5a51737ea9c4bc396", + "sha256": "71e6de8edd7c3ac2f6a2b4aa859373e48f1b7caeec3e515ae4ad53466df40228" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/SOURCE-READY-PINS-v1.json", + "usage": "input", + "git_blob": "2b4d53c4a822e441e0f9efd2c4c9b04a9b3b95cb", + "sha256": "5080c15fc408ed0bae011c055920f410c57237150172c1d56da57f569caecd4c" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/STAGE-DERIVATION-v1.json", + "usage": "input", + "git_blob": "77125db56319e227459b65680fb03ae7fc289adb", + "sha256": "8bb604ba1b101ba228e9a3b26a24f4369bb9712cf4f0381d2b0f504bfd925441" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/STATIC-VERIFICATION-v1.json", + "usage": "input", + "git_blob": "47f369b665890bd7a1f8346374ad7a0ec75ef9c4", + "sha256": "c5cc97adcc7648bb0a140253a78ef4433414dd9f8b079181c7ded42fc88b10f4" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/INTEGRATION-EDGES-v1.json", + "usage": "input", + "git_blob": "1b90cba3d9bb00f3aff336f9be19fb775942f3c7", + "sha256": "a998407a80692769a6ff4000a6af06a2a567b21f28677eb13075de6e7b27c392" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_candidate_driver_N22_custody_v1.py.txt", + "usage": "input", + "git_blob": "75735b75cd72b04758a529bc801d1d7cd69806c3", + "sha256": "c9d72a79ce3a828815d3d0370a1f95f210e1a41edeed767c55ff9d0614126fa4" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_candidate_driver_P07_custody_v1.py.txt", + "usage": "input", + "git_blob": "19f72875cabaf98bfd8d4f295a3ac4a8c18bae07", + "sha256": "2a5d202dabd78d5de54fac29db7fdfaf8836866425d93842f2b22d747fa52d0c" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_candidate_driver_support_N22_custody_v1.py.txt", + "usage": "input", + "git_blob": "e41bd6362fe90fe511b5ec223bc16624a5baa759", + "sha256": "28c1a44750b9745a5ad6e930f9a83cf256b3a90905f5f30d08a89aca54c828da" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_candidate_driver_support_P07_custody_v1.py.txt", + "usage": "input", + "git_blob": "52c25fdbed28f5b9fdd62a891f968efcbfbe5e35", + "sha256": "cae88bf247ee775d6d7fc1264cb2af1d487e4c19168ca787c7c16aba16452220" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_epoch_authority_custody_v1.py.txt", + "usage": "input", + "git_blob": "fa8bda2f0c3e27fd4343ecc7b20844bf7b653d85", + "sha256": "3079a096df1072a83056f3f8a8cbf9e766fdddb488e36dddb36544c7929f988a" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/g12_reference_cold_consumer_v1.py.txt", + "usage": "input", + "git_blob": "19cb9376c2d757e1deb354608a1351c39e4daae1", + "sha256": "89ad17cfa90e895e2cb105e80cc57c82be4bf1a4a85a9d44322016c4344e3849" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/g12_reference_parent_v1.py.txt", + "usage": "input", + "git_blob": "80482f9a9af1f471bc567c52cc31e6dc8a39c26f", + "sha256": "160b8c5de808b9b31532608a89fa5e209110caea132145cd431ffade4403079e" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/integration/g12_reference_adapter_v1.py.txt", + "usage": "input", + "git_blob": "2a6a22290082562143eb0f561f2f038f3c131b82", + "sha256": "43aaabc69841b0a90fae599011de85f4736f42ced64344c49d6cd93f20297f9f" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/pre-correction-source-v1/FREEZE.json", + "usage": "input", + "git_blob": "9d62b1726b951579a3a3cfb6ef1090e6931a45d1", + "sha256": "033cf284a1c011b861743efcee0281bea8859583e3fcad423cf80a1a80c24a92" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/pre-correction-source-v1/g12_reference_cold_consumer_v1.py.txt", + "usage": "input", + "git_blob": "eebf9c24359baa4e684a860d2d140d4f673142ec", + "sha256": "70f16a3c6e699f7dfbf66137af957323e244d039a647e75e8481855e6d61a610" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/pre-correction-source-v1/g12_reference_parent_v1.py.txt", + "usage": "input", + "git_blob": "bee9d0bb1d2c3d1df6a1b1da9b5bd6e7c894b460", + "sha256": "5210fe391ef0361639676f6736cd6de1a6dfcb1f6bdaa58f2ced086e7cc35859" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/pre-correction-source-v1/integration/g12_reference_adapter_v1.py.txt", + "usage": "input", + "git_blob": "cd582600f72358b5a502eeea092e63a88a0fa230", + "sha256": "055e8192e28f2076c45ca22cf4dd1692e0a10e93eb9a2a1153d84229a72ef6fa" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody/DESIGN-v1.json", + "usage": "input", + "git_blob": "df7b078d5cb61f3da3f2a01f8a173bcb774d89f2", + "sha256": "1f88ec187415abfd058728b7bf37fb6d9550e8bb3a080da4841d32be4019fe72" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/DELTA-v2.json", + "usage": "input", + "git_blob": "2da782a7edbb89b04ad971e04eb642c360d2c71c", + "sha256": "ab8420e82d30e04185dcb1f42b213906c36b3103dc90cf1523c4d72c3efbe097" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/FREEZE-v2.json", + "usage": "input", + "git_blob": "89538c3648789f87e8c8fec64aec8fef31b67072", + "sha256": "716dfb49f659651eb41c0965a2189db6efcad1587b25e307b19523bfbd05c7d3" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/SOURCE-INVERSE-v2.json", + "usage": "input", + "git_blob": "0387b383712bbed418ba29f86ac73972d6195898", + "sha256": "baa1dcf93dd4246be19f75fcedba9fdb614267c39ac89882ed22d234461b0466" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/SOURCE-MAP-v2.json", + "usage": "input", + "git_blob": "12b6bd095f6c0747eeb6d9e86e827ece9b53a226", + "sha256": "04f0e573d6df6c0ef278758db0ac0b991e79a9904f5da3ce50d122b046f70c29" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/STATIC-VERIFICATION-v2.json", + "usage": "input", + "git_blob": "85176b796a138dac39c4b41798e80d84b9166905", + "sha256": "7589715b307f4e840634b0ad8686cf0e3e5b4981076dc6300f7f38a4b246d2f7" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/g12_candidate_driver_N22_v2.py.txt", + "usage": "input", + "git_blob": "e130c27986786bbf8a8f69245423550256804ddf", + "sha256": "a2d7fcaa1d3267bb43f14bfa1422759f77ede73641ed1f2a4fe55448792eec4a" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/g12_candidate_driver_P07_v2.py.txt", + "usage": "input", + "git_blob": "de2da17a30d5dc3c61b0efba5fcd4d7703bc3f16", + "sha256": "dc0e3c32a2412d8a872f8568ecbaff99a41785fadd79b0bbfc2341e0e51ede74" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/g12_candidate_driver_support_N22_v2.py.txt", + "usage": "input", + "git_blob": "10326e618d9248a31b37e794cda158e34cfdc48d", + "sha256": "5b7709012375e7e6600840c2c86bf90f44382499d1670b15ce325b30c14a2b48" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/g12_candidate_driver_support_P07_v2.py.txt", + "usage": "input", + "git_blob": "c7b1a5349f1f434f41127fa5ad714cffb836b7cc", + "sha256": "7c41cb423b18df69de48573817f92fae1a21be2751af7ad97768480ffa0b4a19" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/parent/AUTHORIZATION-v2.json", + "usage": "input", + "git_blob": "303abfcf9f779b6390c78df38b9c90ffc3aaf310", + "sha256": "9e32514288fed2b1d2873387bf81861ffcd9e1b56d2ab4828be13a311e629106" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/parent/BOUNDED-SOURCE-CANDIDATE-COVERAGE-v3.json", + "usage": "input", + "git_blob": "0176939fd26ff752636b99514d78b34560511995", + "sha256": "a849c4c78e1f150d305217bb7ebf29dec5f96a896dc888c2cfb9c564267a1336" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/fresh-controller-composition-v2/composed_controller.py.txt", + "usage": "input", + "git_blob": "ac4c8b2a5ec92a3137c1e23ac772b1a6dc5e875c", + "sha256": "c88736fce81d737ae13ac1bf47500dc9d72920bd4910efe1b49074797d6e3231" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/areas/fresh-round-consumer-integration-v2/fresh_supervisor.py.txt", + "usage": "input", + "git_blob": "55173752deff594adef2a439c0144e7262abf926", + "sha256": "7b3304eaf4884e3029df5095e2b0950c18d1544ad21431a07c033b85e53bd4f7" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/fixed-case-independent/COLD-SOURCE-REVIEW-v2.json", + "usage": "input", + "git_blob": "038d080696c4b7bdea47aa3075714f62c3cb24f1", + "sha256": "8c3c6420cbf9eeb978e3b4d6e1a8a47d409ef48714823bc3d781034084d602c2" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/fixed-case-independent/REQUEST-PENDING-SOURCE-REVIEW-v2.json", + "usage": "input", + "git_blob": "991759b45640b970619b2e4947e902427bf65adb", + "sha256": "fa4213006b1d524e0b0a23460947c5f1fcb29bbd4ecff57fff21c9d2333b29e1" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/fresh-independent/G08-DISPOSITION-REVIEW-v1.json", + "usage": "input", + "git_blob": "cc873f2c92b1448b0d2c2b4ba8374208e6966d83", + "sha256": "b607426361abe712116326629ddb016615000c160fd4670545d4afc3a18be411" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/fresh-independent/P08-CONTROLLER-REVIEW-v2.json", + "usage": "input", + "git_blob": "d956c123913b9ecfadd129284ac79ba6ef00da40", + "sha256": "8889df7287b97c7af56f02f6eec5b5ef464bdcea7e21d47a3ddb3adcca7b41b9" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-independent/G12-CUSTODY-DESIGN-CLARIFICATION-v1.json", + "usage": "input", + "git_blob": "55ea8fe86d9f7bc3e07ae4fabdfe65be01ab1efb", + "sha256": "dd78fbbe4060e16f58294ee4e8e0c667943e50ed0052d10500a1ac50da9f1a75" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-independent/G12-CUSTODY-DESIGN-REVIEW-v1.json", + "usage": "input", + "git_blob": "dbb270f8523cae6130da193f352734791eae75ce", + "sha256": "748af02d5766eae9a1f60890780817e3230e91d61b374e0c5e0b4621852e1ae3" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-independent/G12-CUSTODY-SOURCE-SCOPE-CLARIFICATION-v1.json", + "usage": "input", + "git_blob": "66737f17c039d7157233648c46e0192e50e0e2dc", + "sha256": "a9261f686d4fbe6ca40258335231a730dc7e3319be7cedf7c39e189a57c7f367" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-independent/SOURCE-SCOPE-CLARIFICATION-FREEZE-v1.json", + "usage": "input", + "git_blob": "c4a1d9304b0f5d6daaa2d948c66172e1c22fd555", + "sha256": "0d611f41462951d2d875947ba0e156121d876324afa21a4713fd546c873736ad" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-source-independent/G12-CUSTODY-SOURCE-REVIEW-v1.json", + "usage": "input", + "git_blob": "5cc2d9c40be45f1e0bae405ec2464d76dadb8263", + "sha256": "197247e53e93e0a4385adce804ae278fe48806d6ba829d3827c7ea8a7fb727d2" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-source-independent/STATIC-SOURCE-VERIFICATION-v1.json", + "usage": "input", + "git_blob": "4282d146a41ea82896d9f91c84c27e81c23228bb", + "sha256": "37303886fe57deff19a59f0b1c37974ee5550ce637ac626ce0aa183a5a654f4f" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/FREEZE-v2.json", + "usage": "input", + "git_blob": "6d1e67f5038a3b5b786cf159a78b0ed1aa967fd2", + "sha256": "add8245e21be2a902556837090dd454989bb5e4f97e4821fefdcf7b41c2b308d" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/G12-CANDIDATE-PROTOCOL-REVIEW-v1.json", + "usage": "input", + "git_blob": "583dfc3936d478ffba6726470b454d0d99247b37", + "sha256": "feecd63be55243fe2a7d07da8ac1f7cfcec6558362e694b82219a1be232ab7bc" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/G12-CANDIDATE-PROTOCOL-REVIEW-v2.json", + "usage": "input", + "git_blob": "80d9b3e7d4d9657cd73875d06727a98d6360d612", + "sha256": "9b9043fa83f1a052a6708105431db20efd37b88bc0f23adc36491edd27b867ee" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/GRAPH-ADDENDUM-v1.json", + "usage": "input", + "git_blob": "dc95e6613f21e0262b4fadfc27a4f8e79bec2266", + "sha256": "d78a97545c84854b5da0905485c232030f7b4d3884bd51088c2d3ffa604632dd" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/SUCCESSOR-DELTA-STATIC-v2.json", + "usage": "input", + "git_blob": "5067ee5963a58dcde361b1a38c6bdd522d9ee5d5", + "sha256": "435dc0887b9d8c97c9304fc047b2d9e3e64e7a21c475037b50b9df36c4c0b858" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/verify_candidate_delta_v2.py.txt", + "usage": "input", + "git_blob": "576d388ab6331fca0a1257815f9a0fb3fe8b3b58", + "sha256": "fce81e866a7dac29721db03f18d6d720ae78a61b81f1f84333f34b626364a227" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g13-binding-independent/REVIEW-v1.json", + "usage": "input", + "git_blob": "6c78e07b18d2727c689f7921ee380c382e3ca70a", + "sha256": "b8ba9b1fcea3b386c0fd360ea15fae0d56651fd85bba039671a4bc43cd6bf65a" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/late-independent/SOURCE-REVIEW-v2.json", + "usage": "input", + "git_blob": "0795327d19439aa8542d86d4732059b36d01cefb", + "sha256": "3449872d91c4d6425fea5126cae70192ebd959cf5af2e1f69ec85c795c86b4c9" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/roles-armed-independent/SC4-SOURCE-REVIEW-v1.json", + "usage": "input", + "git_blob": "570dc9b41b4336adc409f2467b43da8cc0bff569", + "sha256": "13d8887ad7a9869de5710aa7713a93ec3e723d2f75433196a6158579d26a3a95" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/roles-armed-independent/SMALL-CASES-SOURCE-REVIEW-v1.json", + "usage": "input", + "git_blob": "1c21d0cbf1d2376b398cfc7bca80fbae708ee4d4", + "sha256": "3ed0d29f385508c96eb940ee31d7d4b142374a1b636f295af57f4660c2575bd9" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/review/strict-source-review-20261030T231709Z/parent/NEXT-SOURCE-CHECKLIST-v1.json", + "usage": "input", + "git_blob": "d38dbb743f1169062bf9705864efaa13249e319b", + "sha256": "0c0ed109bd6d1bdbfa457c2f25c437b5a97cad44fd590b989d0fb74cd20544ce" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/run_guarded_v3.py.txt", + "usage": "input", + "git_blob": "8d16367cac7ac99ef8104d3ce439943125a9bb7e", + "sha256": "bd882e3dadb1b6aeaa63ee824f1a1c58f8ef2546b6840a2bffa46885a184d3eb" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/areas/cache-validity/cache_controls_v8.py.txt", + "usage": "input", + "git_blob": "b277b6ba43577cf73a00807b299bf0511715d85b", + "sha256": "8ac3ccf5a3923d46c3f470d2cb1d2d1440fb72ad4344f4c08501c12d7be6ad1d" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/compare_side_verifier.py.txt", + "usage": "input", + "git_blob": "d94920c274c0a47db9763dd595230d52df0bd073", + "sha256": "6e507bb0c7e00d090a60289fddb6c55e90c946d0850c42c3c5e3e15c27604a68" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/finite_controls.py.txt", + "usage": "input", + "git_blob": "4168f5c7e4cec0f182750c6908315735011ff061", + "sha256": "df989a831aac43cc1af95169dad8c64a7548760e6e1f96976da996703f2c8f7a" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/native_backend.py.txt", + "usage": "input", + "git_blob": "77e55ce9d0afb48f220f6e7416437562b41b67d3", + "sha256": "e473c38245c3668715b5a78dfe980b2fe3ed0d0c9b8c97c666fbae6ecf1fffd5" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/native_gf2.c.txt", + "usage": "input", + "git_blob": "0b6a835981d54ce7d807a3f54947eddb9eda4f9d", + "sha256": "e9c3c9194a08718bd1575c1cf08c6c6772d3b644c2e274c25a84a1f9249d06cc" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/profile_side_verifier.py.txt", + "usage": "input", + "git_blob": "807855eb875673c47da0ed1b5a890a417e28a846", + "sha256": "9c994378171c20a91539418d93cb8387e1daa93465d6862beefea90e12999c2a" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/source/complex_circuit.py.txt", + "usage": "input", + "git_blob": "9e83a1065cd5b5f337b39de58d61bac335feb7ce", + "sha256": "d623617f7c5cb3189580883a8ab30c0bd3832688ae3f1f0c1f881bbbbff8e0c1" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/source/complex_network.py.txt", + "usage": "input", + "git_blob": "af9bb6d7b31f3006189761d99bdd919da84656a8", + "sha256": "0da395e67ac04fa213494e71012c1b19b544596d34cdce5a3b172b1fb6af5f1b" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/full_driver.py.txt", + "usage": "input", + "git_blob": "f4ff2a4313fc216712c42aceb9cbd7eb3b4544df", + "sha256": "0d976d2eb6b845f20d4a3396591a806f966688b88693cd6a5f8a0c9e48925e36" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/integration/data_adapters.py.txt", + "usage": "input", + "git_blob": "c3c94bbda73dc3480fe74ce15d30961850c7aae2", + "sha256": "c00c9c215d0b81a91dd5dffddacfd2225c4bc40fe3ba43c7b93677bb686591cc" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/integration/full_driver.py.txt", + "usage": "input", + "git_blob": "89146269ee968fbf69a4fa3523fd483381d2295e", + "sha256": "f5a2d33f2b4d3651f214156a0e7094c2bb516ce2d5ab7698d18c11f98f35dee0" + }, + { + "path": "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/integration/probe_binding_v3.py.txt", + "usage": "input", + "git_blob": "09ee846fc0b24b8fa6966244e0a18316bcdd6c48", + "sha256": "9cbb7368f89e71d1e6cc46db5dc77efed3e03ed2a801c98c88fe316e4d9f3ef2" + } + ] +} diff --git a/research/h25-g12-custody-repairs/TASK.json b/research/h25-g12-custody-repairs/TASK.json new file mode 100644 index 0000000000..7eeb6e28ee --- /dev/null +++ b/research/h25-g12-custody-repairs/TASK.json @@ -0,0 +1,66 @@ +{ + "schema_version": 1, + "task_id": "portable-replay", + "priority_revision": 8, + "base_commit": "626e936ce4d61f2584316914fc71baf96940c512", + "original_card": { + "id": "portable-replay", + "question": "Can one reproducible environment or artifact-comparison failure be repaired?", + "starting_points": [ + "research/gzip-container-reproducibility/README.md", + "docs/ci-verification.md" + ], + "methods": [ + "Reproduce one portability failure and add a minimal cross-environment fix.", + "Audit one canonical-payload comparison for omitted proof-relevant fields." + ], + "acceptance_gate": "Preserve immutable source hashes and proof-relevant content; a different compressed byte stream alone is not a mathematical mismatch.", + "first_step": { + "command": [ + "python3", + "-B", + "scripts/research_selected_baseline.py" + ], + "expected": "PASS_RESEARCH_BASELINE_BINDINGS_ONLY", + "inspect": "Resolve the current selected review, separate complex/ordinary BIT/admitted BIT/outer budgets, and compare the card against live handoffs before starting. Historical ceilings require exact source/model equivalence.", + "scope": "Source-binding orientation only; not a scientific replay or all-size proof. Materialize selected inputs if this checkout is sparse." + }, + "first_experiment": "Reproduce one specific mismatch or audit one canonical comparison for omitted proof-relevant fields.", + "bottleneck_link": "Portable exact checks prevent environment failures from blocking valid contributions.", + "allowed_variations": [ + "One interpreter/version mismatch or one payload field comparison." + ], + "scope_change_triggers": [ + "Removing immutable-source pins because generated compressed bytes differ." + ], + "overlap_terms": [ + "gzip container", + "reproducibility", + "canonical payload" + ] + }, + "scope_status": "changed", + "actual_scope": "Explicit user-assigned P07/G12 source follow-up: implement the consultation\u2019s seven allocation hoists, final known-pidfd release and publication-size domain check, and preserve executable counterexamples to the still-open full allocation/cleanup contract.", + "scope_change_reason": "The user explicitly assigned the P07/G12 roadblock. The portable-replay card is retained as provenance only; this is a fixed-source custody repair and review, not a gzip comparison or multiplication supplier.", + "bottleneck_link": "Side result on verifier custody, not a supplier. N22/P07 cannot compare a cache candidate with the original reference while the parent and consumer disagree on identity type or a close error can erase the first failure. Selected kappa and the five framework assumptions are unchanged. Complex remains the binding supplier.", + "budget_minutes": 60, + "stop_rule": "No historical H25/native/scientific execution or automatic grant use. Do not claim complete source acceptance from the narrow controls; retain unresolved allocation/registration counterexamples.", + "outcome": "partial", + "evidence": "See VERIFY.json and VALIDATION.json; exact source/diff/AST binding and controlled AST-extracted helper failure paths, without importing full target modules.", + "author": "Chris R / Clear1nsight", + "ai_assistance": "ChatGPT Pro consultation and substantial OpenAI Codex implementation/verification assistance; predecessor PR6339 by unpaidmoon with Cursor Grok assistance.", + "open_questions": [ + { + "question": "Can the original first-primary and every-known-cleanup obligations be met under the original allocation-failure model?", + "why_it_matters": "The minimal repairs leave the preflight ledger/snapshot/error-record counterexamples open; no P07/N22 source credit follows.", + "first_step": "Design exception-safe acquisition/registration and a raw journal, then prove the permitted interpreter/fault boundary without assuming infallible allocation.", + "blocked_by": "Source feasibility and exact contract obligations; not a new generic accounting API." + }, + { + "question": "How should the corrected parent/consumer be derived into the actual P07/N22 source graph?", + "why_it_matters": "The old transport and authority pins remain None and fixed mounts do not select this successor.", + "first_step": "Freeze a complete independently reviewed mount/pin/inverse derivation, preserving both exports and original references.", + "blocked_by": "Complete source review and later genuine custody/admission." + } + ] +} diff --git a/research/h25-g12-custody-repairs/VALIDATION.json b/research/h25-g12-custody-repairs/VALIDATION.json new file mode 100644 index 0000000000..46f3189674 --- /dev/null +++ b/research/h25-g12-custody-repairs/VALIDATION.json @@ -0,0 +1,1160 @@ +{ + "schema": "h25-g12-local-validation-v1", + "created_utc": "2026-11-01T23:39:21.923205+00:00", + "runs": [ + { + "argv": [ + "/usr/bin/python3", + "-I", + "-W", + "error", + "-B", + "outputs/p07-g12-source-repair-20261102/publication/research/h25-g12-custody-repairs/verify.py" + ], + "exit_code": 0, + "report": { + "N22_P07_body_credit": false, + "author_verifier_replayed": false, + "checks": [ + { + "classification": "byte-identity", + "name": "source bytes predecessor/g12_reference_parent_v2.py.txt" + }, + { + "classification": "byte-identity", + "name": "source bytes corrected/g12_reference_parent_v3.py" + }, + { + "classification": "byte-identity", + "name": "source bytes predecessor/g12_reference_cold_consumer_v2.py.txt" + }, + { + "classification": "byte-identity", + "name": "source bytes corrected/g12_reference_cold_consumer_v3.py" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-epoch-genuine-context-v1/cache_epoch_context_assembly_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-epoch-products-v5/SOURCE-CASE-CONTEXTS.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-epoch-products-v5/epoch_authority_products_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-epoch-products-v5/epoch_cache_products_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-epoch-products-v5/epoch_data_products_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-epoch-products-v5/epoch_scientific_driver_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-full-contract-completion-v1/cache_epoch_source_controls.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v1/contracts/CALLER-EQUALITY-DEFINITION-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v1/contracts/COMPLETE-SYMBOLIC-COST-DEFINITION-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v1/coverage/COVERAGE-SPEC-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/continuation/candidate-protocol-v1/FREEZE-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/continuation/candidate-protocol-v1/g12_epoch_authority_selector_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/continuation/candidate-protocol-v1/g12_epoch_cache_selector_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/continuation/reference-producer-v2/g12_reference_driver_v2.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/COST-BILL-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/DESIGN-CORRECTION-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/FREEZE-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/NEGATIVE-BRANCHES-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/SOURCE-INVERSE-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/SOURCE-MAP-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/SOURCE-READY-PINS-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/STAGE-DERIVATION-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/STATIC-VERIFICATION-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/INTEGRATION-EDGES-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_candidate_driver_N22_custody_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_candidate_driver_P07_custody_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_candidate_driver_support_N22_custody_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_candidate_driver_support_P07_custody_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_epoch_authority_custody_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/g12_reference_cold_consumer_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/g12_reference_parent_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/integration/g12_reference_adapter_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/pre-correction-source-v1/FREEZE.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/pre-correction-source-v1/g12_reference_cold_consumer_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/pre-correction-source-v1/g12_reference_parent_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/pre-correction-source-v1/integration/g12_reference_adapter_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody/DESIGN-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/DELTA-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/FREEZE-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/SOURCE-INVERSE-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/SOURCE-MAP-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/STATIC-VERIFICATION-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/g12_candidate_driver_N22_v2.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/g12_candidate_driver_P07_v2.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/g12_candidate_driver_support_N22_v2.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/g12_candidate_driver_support_P07_v2.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/parent/AUTHORIZATION-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/parent/BOUNDED-SOURCE-CANDIDATE-COVERAGE-v3.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/fresh-controller-composition-v2/composed_controller.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/fresh-round-consumer-integration-v2/fresh_supervisor.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/fixed-case-independent/COLD-SOURCE-REVIEW-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/fixed-case-independent/REQUEST-PENDING-SOURCE-REVIEW-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/fresh-independent/G08-DISPOSITION-REVIEW-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/fresh-independent/P08-CONTROLLER-REVIEW-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-independent/G12-CUSTODY-DESIGN-CLARIFICATION-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-independent/G12-CUSTODY-DESIGN-REVIEW-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-independent/G12-CUSTODY-SOURCE-SCOPE-CLARIFICATION-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-independent/SOURCE-SCOPE-CLARIFICATION-FREEZE-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-source-independent/G12-CUSTODY-SOURCE-REVIEW-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-source-independent/STATIC-SOURCE-VERIFICATION-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/FREEZE-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/G12-CANDIDATE-PROTOCOL-REVIEW-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/G12-CANDIDATE-PROTOCOL-REVIEW-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/GRAPH-ADDENDUM-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/SUCCESSOR-DELTA-STATIC-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/verify_candidate_delta_v2.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g13-binding-independent/REVIEW-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/late-independent/SOURCE-REVIEW-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/roles-armed-independent/SC4-SOURCE-REVIEW-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/roles-armed-independent/SMALL-CASES-SOURCE-REVIEW-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/strict-source-review-20261030T231709Z/parent/NEXT-SOURCE-CHECKLIST-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/run_guarded_v3.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/areas/cache-validity/cache_controls_v8.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/compare_side_verifier.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/finite_controls.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/native_backend.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/native_gf2.c.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/profile_side_verifier.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/source/complex_circuit.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/source/complex_network.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/full_driver.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/integration/data_adapters.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/integration/full_driver.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/integration/probe_binding_v3.py.txt" + }, + { + "classification": "complete-AST-delta", + "name": "only declared parent definitions changed" + }, + { + "classification": "closed-selection", + "name": "parent selection remains closed" + }, + { + "classification": "complete-AST-delta", + "name": "only declared cold_consumer definitions changed" + }, + { + "classification": "closed-selection", + "name": "cold_consumer selection remains closed" + }, + { + "classification": "complete-byte-delta", + "name": "exact in-memory diff g12_reference_parent_v2.py" + }, + { + "classification": "complete-byte-delta", + "name": "exact in-memory diff g12_reference_cold_consumer_v2.py" + }, + { + "classification": "source-function-fault-injection", + "name": "parent/_directory_chain/predecessor ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "parent/_read_file/predecessor ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "parent/_exclusive_directory/predecessor ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "parent/_copy_file/predecessor ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "parent/_directory_chain/corrected ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "parent/_read_file/corrected ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "parent/_exclusive_directory/corrected ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "parent/_copy_file/corrected ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "cold_consumer/_directory_chain/predecessor ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "cold_consumer/_read_file/predecessor ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "cold_consumer/load_original_g12_reference/predecessor ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "cold_consumer/_directory_chain/corrected ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "cold_consumer/_read_file/corrected ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "cold_consumer/load_original_g12_reference/corrected ledger-failure boundary" + }, + { + "classification": "source-function-positive-control", + "name": "ordinary preflight keeps same primary and attempts all known closes" + }, + { + "classification": "source-function-positive-control", + "name": "successful body promotes first close failure once" + }, + { + "classification": "retained-contract-counterexample", + "name": "UNRESOLVED preflight ledger masks primary/skips later closes" + }, + { + "classification": "retained-contract-counterexample", + "name": "UNRESOLVED preflight snapshot masks primary/skips later closes" + }, + { + "classification": "retained-contract-counterexample", + "name": "UNRESOLVED preflight record masks primary/skips later closes" + }, + { + "classification": "source-function-positive-control", + "name": "pidfd release attempts all/retains raw failures []" + }, + { + "classification": "source-function-negative-control", + "name": "ambiguous pidfd close is never blindly retried []" + }, + { + "classification": "source-function-positive-control", + "name": "pidfd release attempts all/retains raw failures [901]" + }, + { + "classification": "source-function-negative-control", + "name": "ambiguous pidfd close is never blindly retried [901]" + }, + { + "classification": "source-function-positive-control", + "name": "pidfd release attempts all/retains raw failures [901, 902]" + }, + { + "classification": "source-function-negative-control", + "name": "ambiguous pidfd close is never blindly retried [901, 902]" + }, + { + "classification": "source-function-regression-control", + "name": "actual P09 persistent-denial pidfd cleanup predecessor" + }, + { + "classification": "source-function-regression-control", + "name": "actual P09 persistent-denial pidfd cleanup corrected" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size predecessor/int/1234" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size predecessor/int/0" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size predecessor/float/1234.0" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size predecessor/bool/True" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size predecessor/ForeignInt/1234" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size predecessor/str/'1234'" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size predecessor/int/-1" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size corrected/int/1234" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size corrected/int/0" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size corrected/float/1234.0" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size corrected/bool/True" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size corrected/ForeignInt/1234" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size corrected/str/'1234'" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size corrected/int/-1" + } + ], + "checks_total": 135, + "environment": { + "optimize": 0, + "python": "3.12.3 (main, Aug 31 2026, 10:18:26) [GCC 13.3.0]" + }, + "executed_scope": "Named AST-extracted source functions/windows with synthetic tokens", + "full_target_module_imports": 0, + "integrated_source_acceptance": false, + "metadata_checks": 94, + "native_or_process_operations": 0, + "original_H25_scientific_invocations": 0, + "performance_or_kappa": false, + "schema": "h25-g12-bounded-source-controls-v1", + "source_function_cases": 41, + "status": "PARTIAL_SOURCE_REPAIR_WITH_RETAINED_COUNTEREXAMPLES", + "unknown_costs": "OPEN_NOT_ZERO" + }, + "stdout_sha256": "11704ab7ebf8c6f765c30b9b4c1319c26bf3643fa6ef4ab2b99b4355e9841ec1" + }, + { + "argv": [ + "/usr/bin/python3", + "-I", + "-O", + "-W", + "error", + "-B", + "outputs/p07-g12-source-repair-20261102/publication/research/h25-g12-custody-repairs/verify.py" + ], + "exit_code": 0, + "report": { + "N22_P07_body_credit": false, + "author_verifier_replayed": false, + "checks": [ + { + "classification": "byte-identity", + "name": "source bytes predecessor/g12_reference_parent_v2.py.txt" + }, + { + "classification": "byte-identity", + "name": "source bytes corrected/g12_reference_parent_v3.py" + }, + { + "classification": "byte-identity", + "name": "source bytes predecessor/g12_reference_cold_consumer_v2.py.txt" + }, + { + "classification": "byte-identity", + "name": "source bytes corrected/g12_reference_cold_consumer_v3.py" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-epoch-genuine-context-v1/cache_epoch_context_assembly_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-epoch-products-v5/SOURCE-CASE-CONTEXTS.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-epoch-products-v5/epoch_authority_products_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-epoch-products-v5/epoch_cache_products_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-epoch-products-v5/epoch_data_products_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-epoch-products-v5/epoch_scientific_driver_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-full-contract-completion-v1/cache_epoch_source_controls.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v1/contracts/CALLER-EQUALITY-DEFINITION-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v1/contracts/COMPLETE-SYMBOLIC-COST-DEFINITION-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v1/coverage/COVERAGE-SPEC-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/continuation/candidate-protocol-v1/FREEZE-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/continuation/candidate-protocol-v1/g12_epoch_authority_selector_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/continuation/candidate-protocol-v1/g12_epoch_cache_selector_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/continuation/reference-producer-v2/g12_reference_driver_v2.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/COST-BILL-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/DESIGN-CORRECTION-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/FREEZE-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/NEGATIVE-BRANCHES-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/SOURCE-INVERSE-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/SOURCE-MAP-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/SOURCE-READY-PINS-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/STAGE-DERIVATION-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/STATIC-VERIFICATION-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/INTEGRATION-EDGES-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_candidate_driver_N22_custody_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_candidate_driver_P07_custody_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_candidate_driver_support_N22_custody_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_candidate_driver_support_P07_custody_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_epoch_authority_custody_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/g12_reference_cold_consumer_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/g12_reference_parent_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/integration/g12_reference_adapter_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/pre-correction-source-v1/FREEZE.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/pre-correction-source-v1/g12_reference_cold_consumer_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/pre-correction-source-v1/g12_reference_parent_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/pre-correction-source-v1/integration/g12_reference_adapter_v1.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody/DESIGN-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/DELTA-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/FREEZE-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/SOURCE-INVERSE-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/SOURCE-MAP-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/STATIC-VERIFICATION-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/g12_candidate_driver_N22_v2.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/g12_candidate_driver_P07_v2.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/g12_candidate_driver_support_N22_v2.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/g12_candidate_driver_support_P07_v2.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/parent/AUTHORIZATION-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/parent/BOUNDED-SOURCE-CANDIDATE-COVERAGE-v3.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/fresh-controller-composition-v2/composed_controller.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/areas/fresh-round-consumer-integration-v2/fresh_supervisor.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/fixed-case-independent/COLD-SOURCE-REVIEW-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/fixed-case-independent/REQUEST-PENDING-SOURCE-REVIEW-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/fresh-independent/G08-DISPOSITION-REVIEW-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/fresh-independent/P08-CONTROLLER-REVIEW-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-independent/G12-CUSTODY-DESIGN-CLARIFICATION-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-independent/G12-CUSTODY-DESIGN-REVIEW-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-independent/G12-CUSTODY-SOURCE-SCOPE-CLARIFICATION-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-independent/SOURCE-SCOPE-CLARIFICATION-FREEZE-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-source-independent/G12-CUSTODY-SOURCE-REVIEW-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-source-independent/STATIC-SOURCE-VERIFICATION-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/FREEZE-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/G12-CANDIDATE-PROTOCOL-REVIEW-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/G12-CANDIDATE-PROTOCOL-REVIEW-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/GRAPH-ADDENDUM-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/SUCCESSOR-DELTA-STATIC-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/verify_candidate_delta_v2.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g13-binding-independent/REVIEW-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/late-independent/SOURCE-REVIEW-v2.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/roles-armed-independent/SC4-SOURCE-REVIEW-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/roles-armed-independent/SMALL-CASES-SOURCE-REVIEW-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/review/strict-source-review-20261030T231709Z/parent/NEXT-SOURCE-CHECKLIST-v1.json" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/run_guarded_v3.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/areas/cache-validity/cache_controls_v8.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/compare_side_verifier.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/finite_controls.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/native_backend.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/native_gf2.c.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/profile_side_verifier.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/source/complex_circuit.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/source/complex_network.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/full_driver.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/integration/data_adapters.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/integration/full_driver.py.txt" + }, + { + "classification": "byte-identity", + "name": "canonical input research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/integration/probe_binding_v3.py.txt" + }, + { + "classification": "complete-AST-delta", + "name": "only declared parent definitions changed" + }, + { + "classification": "closed-selection", + "name": "parent selection remains closed" + }, + { + "classification": "complete-AST-delta", + "name": "only declared cold_consumer definitions changed" + }, + { + "classification": "closed-selection", + "name": "cold_consumer selection remains closed" + }, + { + "classification": "complete-byte-delta", + "name": "exact in-memory diff g12_reference_parent_v2.py" + }, + { + "classification": "complete-byte-delta", + "name": "exact in-memory diff g12_reference_cold_consumer_v2.py" + }, + { + "classification": "source-function-fault-injection", + "name": "parent/_directory_chain/predecessor ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "parent/_read_file/predecessor ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "parent/_exclusive_directory/predecessor ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "parent/_copy_file/predecessor ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "parent/_directory_chain/corrected ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "parent/_read_file/corrected ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "parent/_exclusive_directory/corrected ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "parent/_copy_file/corrected ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "cold_consumer/_directory_chain/predecessor ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "cold_consumer/_read_file/predecessor ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "cold_consumer/load_original_g12_reference/predecessor ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "cold_consumer/_directory_chain/corrected ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "cold_consumer/_read_file/corrected ledger-failure boundary" + }, + { + "classification": "source-function-fault-injection", + "name": "cold_consumer/load_original_g12_reference/corrected ledger-failure boundary" + }, + { + "classification": "source-function-positive-control", + "name": "ordinary preflight keeps same primary and attempts all known closes" + }, + { + "classification": "source-function-positive-control", + "name": "successful body promotes first close failure once" + }, + { + "classification": "retained-contract-counterexample", + "name": "UNRESOLVED preflight ledger masks primary/skips later closes" + }, + { + "classification": "retained-contract-counterexample", + "name": "UNRESOLVED preflight snapshot masks primary/skips later closes" + }, + { + "classification": "retained-contract-counterexample", + "name": "UNRESOLVED preflight record masks primary/skips later closes" + }, + { + "classification": "source-function-positive-control", + "name": "pidfd release attempts all/retains raw failures []" + }, + { + "classification": "source-function-negative-control", + "name": "ambiguous pidfd close is never blindly retried []" + }, + { + "classification": "source-function-positive-control", + "name": "pidfd release attempts all/retains raw failures [901]" + }, + { + "classification": "source-function-negative-control", + "name": "ambiguous pidfd close is never blindly retried [901]" + }, + { + "classification": "source-function-positive-control", + "name": "pidfd release attempts all/retains raw failures [901, 902]" + }, + { + "classification": "source-function-negative-control", + "name": "ambiguous pidfd close is never blindly retried [901, 902]" + }, + { + "classification": "source-function-regression-control", + "name": "actual P09 persistent-denial pidfd cleanup predecessor" + }, + { + "classification": "source-function-regression-control", + "name": "actual P09 persistent-denial pidfd cleanup corrected" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size predecessor/int/1234" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size predecessor/int/0" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size predecessor/float/1234.0" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size predecessor/bool/True" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size predecessor/ForeignInt/1234" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size predecessor/str/'1234'" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size predecessor/int/-1" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size corrected/int/1234" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size corrected/int/0" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size corrected/float/1234.0" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size corrected/bool/True" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size corrected/ForeignInt/1234" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size corrected/str/'1234'" + }, + { + "classification": "actual-source-schema-control", + "name": "publication exact-size corrected/int/-1" + } + ], + "checks_total": 135, + "environment": { + "optimize": 1, + "python": "3.12.3 (main, Aug 31 2026, 10:18:26) [GCC 13.3.0]" + }, + "executed_scope": "Named AST-extracted source functions/windows with synthetic tokens", + "full_target_module_imports": 0, + "integrated_source_acceptance": false, + "metadata_checks": 94, + "native_or_process_operations": 0, + "original_H25_scientific_invocations": 0, + "performance_or_kappa": false, + "schema": "h25-g12-bounded-source-controls-v1", + "source_function_cases": 41, + "status": "PARTIAL_SOURCE_REPAIR_WITH_RETAINED_COUNTEREXAMPLES", + "unknown_costs": "OPEN_NOT_ZERO" + }, + "stdout_sha256": "0b050f6c1d089b01643711ceb015cc6277a2097b67d0bd4cf45df1b5c9bbd505" + } + ], + "meaning": "41 synthetic source-function/window cases and94 byte/AST/diff checks per mode, including3 preserved contract counterexamples; not full source acceptance or original H25 execution.", + "full_target_module_imports": 0, + "original_H25_scientific_invocations": 0, + "new_scientific_budget": false, + "publication": "Not yet submitted at this checkpoint." +} diff --git a/research/h25-g12-custody-repairs/VERIFY.json b/research/h25-g12-custody-repairs/VERIFY.json new file mode 100644 index 0000000000..3c4702bb59 --- /dev/null +++ b/research/h25-g12-custody-repairs/VERIFY.json @@ -0,0 +1,119 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [ + "research/h25-cache-source-handoff/snapshot/areas/cache-epoch-genuine-context-v1/cache_epoch_context_assembly_v1.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-epoch-products-v5/SOURCE-CASE-CONTEXTS.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-epoch-products-v5/epoch_authority_products_v1.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-epoch-products-v5/epoch_cache_products_v1.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-epoch-products-v5/epoch_data_products_v1.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-epoch-products-v5/epoch_scientific_driver_v1.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-full-contract-completion-v1/cache_epoch_source_controls.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v1/contracts/CALLER-EQUALITY-DEFINITION-v1.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v1/contracts/COMPLETE-SYMBOLIC-COST-DEFINITION-v1.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v1/coverage/COVERAGE-SPEC-v1.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/continuation/candidate-protocol-v1/FREEZE-v1.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/continuation/candidate-protocol-v1/g12_epoch_authority_selector_v1.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/continuation/candidate-protocol-v1/g12_epoch_cache_selector_v1.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/continuation/reference-producer-v2/g12_reference_driver_v2.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/COST-BILL-v1.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/DESIGN-CORRECTION-v2.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/FREEZE-v1.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/NEGATIVE-BRANCHES-v1.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/SOURCE-INVERSE-v1.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/SOURCE-MAP-v1.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/SOURCE-READY-PINS-v1.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/STAGE-DERIVATION-v1.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/STATIC-VERIFICATION-v1.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/INTEGRATION-EDGES-v1.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_candidate_driver_N22_custody_v1.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_candidate_driver_P07_custody_v1.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_candidate_driver_support_N22_custody_v1.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_candidate_driver_support_P07_custody_v1.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_epoch_authority_custody_v1.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/g12_reference_cold_consumer_v1.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/g12_reference_parent_v1.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/integration/g12_reference_adapter_v1.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/pre-correction-source-v1/FREEZE.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/pre-correction-source-v1/g12_reference_cold_consumer_v1.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/pre-correction-source-v1/g12_reference_parent_v1.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/pre-correction-source-v1/integration/g12_reference_adapter_v1.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-custody/DESIGN-v1.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/DELTA-v2.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/FREEZE-v2.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/SOURCE-INVERSE-v2.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/SOURCE-MAP-v2.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/STATIC-VERIFICATION-v2.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/g12_candidate_driver_N22_v2.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/g12_candidate_driver_P07_v2.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/g12_candidate_driver_support_N22_v2.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/g12_candidate_driver_support_P07_v2.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/parent/AUTHORIZATION-v2.json", + "research/h25-cache-source-handoff/snapshot/areas/cache-s0308-source-completion-v2/parent/BOUNDED-SOURCE-CANDIDATE-COVERAGE-v3.json", + "research/h25-cache-source-handoff/snapshot/areas/fresh-controller-composition-v2/composed_controller.py.txt", + "research/h25-cache-source-handoff/snapshot/areas/fresh-round-consumer-integration-v2/fresh_supervisor.py.txt", + "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/fixed-case-independent/COLD-SOURCE-REVIEW-v2.json", + "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/fixed-case-independent/REQUEST-PENDING-SOURCE-REVIEW-v2.json", + "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/fresh-independent/G08-DISPOSITION-REVIEW-v1.json", + "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/fresh-independent/P08-CONTROLLER-REVIEW-v2.json", + "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-independent/G12-CUSTODY-DESIGN-CLARIFICATION-v1.json", + "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-independent/G12-CUSTODY-DESIGN-REVIEW-v1.json", + "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-independent/G12-CUSTODY-SOURCE-SCOPE-CLARIFICATION-v1.json", + "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-independent/SOURCE-SCOPE-CLARIFICATION-FREEZE-v1.json", + "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-source-independent/G12-CUSTODY-SOURCE-REVIEW-v1.json", + "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-custody-source-independent/STATIC-SOURCE-VERIFICATION-v1.json", + "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/FREEZE-v2.json", + "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/G12-CANDIDATE-PROTOCOL-REVIEW-v1.json", + "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/G12-CANDIDATE-PROTOCOL-REVIEW-v2.json", + "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/GRAPH-ADDENDUM-v1.json", + "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/SUCCESSOR-DELTA-STATIC-v2.json", + "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g12-protocol-independent/verify_candidate_delta_v2.py.txt", + "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/g13-binding-independent/REVIEW-v1.json", + "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/late-independent/SOURCE-REVIEW-v2.json", + "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/roles-armed-independent/SC4-SOURCE-REVIEW-v1.json", + "research/h25-cache-source-handoff/snapshot/review/cache-s0308-source-completion-v2/roles-armed-independent/SMALL-CASES-SOURCE-REVIEW-v1.json", + "research/h25-cache-source-handoff/snapshot/review/strict-source-review-20261030T231709Z/parent/NEXT-SOURCE-CHECKLIST-v1.json", + "research/h25-cache-source-handoff/snapshot/run_guarded_v3.py.txt", + "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/areas/cache-validity/cache_controls_v8.py.txt", + "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/compare_side_verifier.py.txt", + "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/finite_controls.py.txt", + "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/native_backend.py.txt", + "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/native_gf2.c.txt", + "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/profile_side_verifier.py.txt", + "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/source/complex_circuit.py.txt", + "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/engine/source/complex_network.py.txt", + "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/baseline/full_driver.py.txt", + "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/integration/data_adapters.py.txt", + "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/integration/full_driver.py.txt", + "research/h25-cache-source-handoff/snapshot/stages/combined-finite-v8/integration/probe_binding_v3.py.txt" + ], + "commands": [ + { + "argv": [ + "{python}", + "-I", + "-W", + "error", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 60, + "checks": "Exact source/diff binding, seven pre-acquisition allocation controls, raw primary ordering, known-pidfd release, exact-size schema controls and preserved unresolved failure witnesses. Selected AST-extracted helpers execute only against synthetic tokens; no full module import, parent launch or scientific entry." + }, + { + "argv": [ + "{python}", + "-I", + "-O", + "-W", + "error", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 60, + "checks": "Exact source/diff binding, seven pre-acquisition allocation controls, raw primary ordering, known-pidfd release, exact-size schema controls and preserved unresolved failure witnesses. Selected AST-extracted helpers execute only against synthetic tokens; no full module import, parent launch or scientific entry." + } + ] +} diff --git a/research/h25-g12-custody-repairs/corrected/g12_reference_cold_consumer_v3.py b/research/h25-g12-custody-repairs/corrected/g12_reference_cold_consumer_v3.py new file mode 100644 index 0000000000..8bc67b3cf8 --- /dev/null +++ b/research/h25-g12-custody-repairs/corrected/g12_reference_cold_consumer_v3.py @@ -0,0 +1,1128 @@ +"""Fixed G12 two-export consumer, v2 checked identity conversion. + +SOURCE ONLY; all selections stay closed. + +The selected cold registered-source executor must inject the actual initial +Root/capability/API before candidate exposure, authenticate these exact source +bytes and this entry, and pass those same objects. Python shapes do not prove +that premise. No result registry, setter, caller success flag or new oracle. +""" +import os +import sys +import stat +import json +import hashlib +import math +from types import FunctionType, CodeType, ModuleType + +G12_REFERENCE_HANDOFF = None +# Future immutable nine-tuple exactly as accepted DESIGN-v1; never a setter. +# Independent selected consumer identity is injected by the fixed original +# cold loader BEFORE exec. It is not stored inside its own source (no hash cycle). +_BOOTSTRAP = (globals().get('bootstrap_root'), globals().get('bootstrap_capability'), + globals().get('bootstrap_api'), globals().get('bootstrap_g12_source_identity')) +_ROOT_PIN = 'f5a2d33f2b4d3651f214156a0e7094c2bb516ce2d5ab7698d18c11f98f35dee0' +_PROVIDER_PIN = '9cbb7368f89e71d1e6cc46db5dc77efed3e03ed2a801c98c88fe316e4d9f3ef2' +_PRODUCER_PIN = 'a346025d5b6e2b26246521c6af6292643a4c2c3286b33ff3996dcf051cd6be26' +_GUARD_PIN = 'bd882e3dadb1b6aeaa63ee824f1a1c58f8ef2546b6840a2bffa46885a184d3eb' +_AUTHORITY_PIN = 'f279ab86fc17c6a517b035f19d56863919cbd8304de4e7d5332457c6159aec10' +_META_CAP = 262144 +_PAIR_CAP = 268435456 +_CHUNK = 65536 +_LOG_CAP = 2097152 +_MISSING = object() +_ID_NAMES = ('dev', 'ino', 'full_st_mode', 'size', 'mtime_ns', 'ctime_ns') +# BEGIN FIXED G12 FILE AND PAIR LEAF + +class _RawG12Errors: + """Fixed error-retention slots; storing raw failures precedes formatting/IO.""" + __slots__ = ('slots', 'count') + def __init__(self): + self.slots = [None] * 4096 + self.count = 0 + def append(self, value): + # All fixed directory/process/stream paths together have fewer than 4096 + # close sites under the 256-component/128-generation source ceilings. + if self.count >= len(self.slots): + raise RuntimeError('G12-N09: fixed raw secondary retention exhausted') + self.slots[self.count] = value + self.count += 1 + def __bool__(self): + return self.count != 0 + def __len__(self): + return self.count + def __getitem__(self, index): + if type(index) is not int or not 0 <= index < self.count: + raise IndexError(index) + return self.slots[index] + def __iter__(self): + for index in range(self.count): + yield self.slots[index] + def __repr__(self): + return repr(tuple(self)) + + +def _need(condition, message): + if not condition: + raise RuntimeError(message) + + +def _exact(value, expected): + if type(value) is not type(expected): + return False + if type(value) in (list, tuple): + return len(value) == len(expected) and all(_exact(a, b) for a, b in zip(value, expected)) + if type(value) is dict: + return set(value) == set(expected) and all(_exact(value[k], expected[k]) for k in expected) + return value == expected + + +def _fields(value, fields): + _need(type(value) is dict and all(type(k) is str for k in value) and + set(value) == set(fields), 'G12-N12: exact field domain differs') + + +def _digest(value): + return type(value) is str and len(value) == 64 and all(c in '0123456789abcdef' for c in value) + + +def _uint(value, positive=False): + _need(type(value) is int and value >= (1 if positive else 0), 'G12-N12: exact integer domain') + + +def _number(value): + _need(type(value) in (int, float) and math.isfinite(value) and value >= 0, + 'G12-N12: finite nonnegative exact number required') + + +def _path(path): + _need(type(path) is str and path.startswith('/') and + all(p not in ('', '.', '..') for p in path.split('/')[1:]), 'G12-N11: absolute canonical path') + return path + + +def _identity(info): + return dict(zip(_ID_NAMES, (info.st_dev, info.st_ino, info.st_mode, info.st_size, + info.st_mtime_ns, info.st_ctime_ns))) + + +def _identity_dict_from_handoff(value): + """Convert the parent's ordered identity tuple into a FileRecord dictionary. + + Field 4 of the accepted nine-tuple is (dev, ino, full_st_mode, size, + mtime_ns, ctime_ns). `_file_record` then requires those values under + string keys. A dictionary is rejected so this boundary stays the only + conversion and cannot be skipped. + """ + _need(type(value) is tuple and len(value) == len(_ID_NAMES), + 'G12-N11: handoff identity must be the ordered six-tuple') + for item in value: + _need(type(item) is int, 'G12-N11: exact stat value') + identity = {name: item for name, item in zip(_ID_NAMES, value)} + _fields(identity, _ID_NAMES) + _uint(identity['dev']) + _uint(identity['ino'], True) + _need(stat.S_ISREG(identity['full_st_mode']), 'G12-N11: file identity type') + return identity + + +def _directory_key(info): + return info.st_dev, info.st_ino, info.st_mode + + +def _directory_chain(path): + """Held no-follow chain; no later absolute path silently changes its owner.""" + _path(path) + _need(len(path.split('/')) <= 257, 'G12-N11: finite directory-component bound') + fds, rows = [], [] + primary = None + secondary = _RawG12Errors() + try: + fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC) + fds.append(fd) + for part in path.split('/')[1:]: + before = os.stat(part, dir_fd=fd, follow_symlinks=False) + _need(stat.S_ISDIR(before.st_mode), 'G12-N11: directory component type') + child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, + dir_fd=fd) + fds.append(child) + opened = os.fstat(child) + _need(_directory_key(before) == _directory_key(opened), 'G12-N11: directory replaced') + rows.append((fd, part, child, _directory_key(opened))) + fd = child + return fds, rows + except BaseException as error: + primary = (error, error.__traceback__) + for descriptor in reversed(fds): + try: + os.close(descriptor) + except BaseException as error: + secondary.append((error, error.__traceback__)) + _raise_preserved(primary, secondary) + + +def _check_chain(rows): + for parent, name, descriptor, key in rows: + _need(_directory_key(os.fstat(descriptor)) == key == + _directory_key(os.stat(name, dir_fd=parent, follow_symlinks=False)), + 'G12-N11: directory binding changed') + + +def _raise_preserved(primary, secondaries): + """Never replace first raw failure if evidence formatting or retention fails.""" + if primary is not None: + error, traceback = primary + try: + error.add_note('G12 ordered secondary failures: ' + repr(secondaries)) + except BaseException: + pass + raise error.with_traceback(traceback) + if secondaries: + error, traceback = secondaries[0][:2] + raise error.with_traceback(traceback) + + +def _read_file(path, cap, mode=None): + _path(path) + parent, name = path.rsplit('/', 1) + descriptor, primary, secondary, result = None, None, _RawG12Errors(), None + fds, rows = _directory_chain(parent) + try: + before = os.stat(name, dir_fd=fds[-1], follow_symlinks=False) + _need(stat.S_ISREG(before.st_mode) and before.st_nlink == 1 and + 0 <= before.st_size <= cap and (mode is None or before.st_mode == stat.S_IFREG | mode), + 'G12-N11: regular-file size/mode/link domain') + descriptor = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, + dir_fd=fds[-1]) + opened = os.fstat(descriptor) + _need(_identity(before) == _identity(opened) and opened.st_nlink == 1, + 'G12-N11: file changed on open') + count, blocks, hasher = 0, [], hashlib.sha256() + while count < opened.st_size: + block = os.read(descriptor, min(_CHUNK, opened.st_size - count)) + _need(bool(block), 'G12-N11: short file read') + count += len(block) + hasher.update(block) + blocks.append(block) + _need(os.read(descriptor, 1) == b'', 'G12-N11: file grew') + after = os.fstat(descriptor) + ending = os.stat(name, dir_fd=fds[-1], follow_symlinks=False) + _need(_identity(before) == _identity(after) == _identity(ending) and + after.st_nlink == ending.st_nlink == 1, 'G12-N11: full file identity changed') + _check_chain(rows) + result = ({'path': path, 'sha256': hasher.hexdigest(), 'bytes': count, + 'identity': _identity(after), 'nlink': 1}, b''.join(blocks)) + except BaseException as error: + primary = (error, error.__traceback__) + for fd in ([descriptor] if descriptor is not None else []) + list(reversed(fds)): + try: + os.close(fd) + except BaseException as error: + secondary.append((error, error.__traceback__)) + _raise_preserved(primary, secondary) + return result + + +def _file_record(value): + _fields(value, ('path', 'sha256', 'bytes', 'identity', 'nlink')) + _path(value['path']) + _need(_digest(value['sha256']) and type(value['nlink']) is int and value['nlink'] == 1, + 'G12-N11: file digest/link record') + _uint(value['bytes']) + _fields(value['identity'], _ID_NAMES) + for key in _ID_NAMES: + _need(type(value['identity'][key]) is int, 'G12-N11: exact stat value') + _uint(value['identity']['dev']) + _uint(value['identity']['ino'], True) + _need(stat.S_ISREG(value['identity']['full_st_mode']) and + value['identity']['size'] == value['bytes'], 'G12-N11: file identity size/type') + + +def _root_read(root, api, record, cap): + _file_record(record) + _need(api[0]() == _ROOT_PIN, 'G12-N04: actual Root currentness') + before = root._hash_regular(record['path'], cap, False) + observed, raw = _read_file(record['path'], cap, 0o444) + after = root._hash_regular(record['path'], cap, False) + _need(_exact(observed, record) and before[:2] == after[:2] == + (record['sha256'], record['bytes']), 'G12-N17: Root/read/full-identity join') + _need(api[0]() == _ROOT_PIN, 'G12-N04: actual Root changed after file read') + return raw + + +def _pairs(items): + result = {} + for key, value in items: + _need(type(key) is str and key not in result, 'G12-N12: duplicate JSON key') + result[key] = value + return result + + +def _nonfinite(value): + raise ValueError('G12-N12: nonfinite JSON token: ' + value) + + +def _canonical(value): + return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True, + allow_nan=False).encode('ascii') + + +def _json(raw, cap, canonical=False, newline=False): + _need(type(raw) is bytes and len(raw) <= cap, 'G12-N12: raw JSON bound') + # Scan lexical nesting before json.loads recursion or object materialization. + depth, quoted, escaped = 0, False, False + for char in raw: + if quoted: + if escaped: + escaped = False + elif char == 92: + escaped = True + elif char == 34: + quoted = False + elif char == 34: + quoted = True + elif char in (91, 123): + depth += 1 + _need(depth <= 256, 'G12-N12: JSON depth limit') + elif char in (93, 125): + depth -= 1 + _need(depth >= 0, 'G12-N12: JSON nesting') + _need(depth == 0 and not quoted, 'G12-N12: incomplete JSON') + value = json.loads(raw.decode('utf-8'), object_pairs_hook=_pairs, parse_constant=_nonfinite) + pending, count = [(value, 0)], 0 + while pending: + item, depth = pending.pop() + count += 1 + _need(count <= cap and depth <= 256, 'G12-N12: JSON node/depth limit') + if type(item) is dict: + pending.extend((x, depth + 1) for pair in item.items() for x in pair) + elif type(item) is list: + pending.extend((x, depth + 1) for x in item) + elif type(item) is str: + _need(len(item) <= cap, 'G12-N12: JSON string limit') + elif type(item) is float: + _need(math.isfinite(item), 'G12-N12: overflowed JSON number') + else: + _need(item is None or type(item) in (bool, int), 'G12-N12: JSON primitive') + if canonical: + _need(raw == _canonical(value) + (b'\n' if newline else b''), 'G12-N12: canonical JSON bytes') + return value + + +def _hex(value, cap): + _need(type(value) is str and len(value) <= cap and len(value) % 2 == 0 and + all(c in '0123456789abcdef' for c in value), 'G12-N12: complete lowercase hex') + return bytes.fromhex(value) + + +def _decimal(value, positive=False): + _need(type(value) is str and bool(value), 'G12-N12: integer tag text') + digits = value[1:] if value.startswith('-') else value + _need(bool(digits) and all(c in '0123456789' for c in digits) and + (digits == '0' or digits[0] != '0') and value != '-0' and + (not positive or (not value.startswith('-') and value != '0')), 'G12-N12: canonical integer') + + +def _tagged(raw, cap): + value = _json(raw, cap, True) + pending = [(value, 0)] + count = 0 + while pending: + node, depth = pending.pop() + count += 1 + _need(count <= cap and depth <= 256 and type(node) is list and len(node) >= 1 and + type(node[0]) is str, 'G12-N12: tagged primitive bound/shape') + tag = node[0] + if tag == 'None': + _need(len(node) == 1, 'G12-N12: None arity') + continue + _need(len(node) == (3 if tag == 'Fraction' else 2), 'G12-N12: primitive arity') + arg = node[1] + if tag == 'bool': + _need(type(arg) is bool, 'G12-N12: bool tag') + elif tag == 'int': + _decimal(arg) + elif tag == 'Fraction': + _decimal(arg) + _decimal(node[2], True) + elif tag == 'str': + _need(type(arg) is str, 'G12-N12: string tag') + elif tag == 'bytes': + _hex(arg, cap) + elif tag == 'float': + _need(type(arg) is str and float.fromhex(arg).hex() == arg, 'G12-N12: float.hex domain') + elif tag in ('tuple', 'list'): + _need(type(arg) is list, 'G12-N12: sequence tag') + pending.extend((item, depth + 1) for item in arg) + elif tag == 'dict': + _need(type(arg) is list, 'G12-N12: ordered dict tag') + for pair in arg: + _need(type(pair) is list and len(pair) == 2, 'G12-N12: dict pair') + pending.extend((item, depth + 1) for item in pair) + else: + raise ValueError('G12-N12: unknown primitive tag') + return value + + +def _rank_events(encoded): + value = _tagged(_hex(encoded, _PAIR_CAP), _PAIR_CAP) + _need(value[0] == 'tuple', 'G12-N12: rank tuple') + for event in value[1]: + _need(event[0] == 'tuple' and len(event[1]) == 2 and event[1][0][0] == 'tuple' and + all(x[0] == 'int' for x in event[1][0][1]) and event[1][1][0] == 'int', + 'G12-N12: rank-event grammar') + return len(value[1]) + + +def _validate_pair(common_raw, diagnostic_raw): + common = _json(common_raw, _PAIR_CAP, True, True) + diagnostic = _json(diagnostic_raw, _PAIR_CAP, True, True) + spec = _PAIR_SCHEMA + _fields(common, spec['common_exact_fields']) + _fields(diagnostic, spec['diagnostic_exact_fields']) + for key, expected in spec['common_constants'].items(): + _need(_exact(common[key], expected), 'G12-N13: original common source/workload binding') + for key, expected in spec['diagnostic_constants'].items(): + _need(_exact(diagnostic[key], expected), 'G12-N13: diagnostic source/role binding') + _need(type(common['literal_original_value']) is bool, 'G12-N12: observed literal exact bool') + _uint(common['remaining_original_case_count'], True) + payload = _hex(common['common_payload_hex'], _PAIR_CAP) + _need(_digest(common['common_payload_sha256']) and + hashlib.sha256(payload).hexdigest() == common['common_payload_sha256'] == + diagnostic['common_payload_sha256'], 'G12-N13: complete common digest join') + tagged = _tagged(payload, _PAIR_CAP) + _need(tagged[0] == 'tuple' and len(tagged[1]) == 10, 'G12-N13: common tuple arity') + prefix = [['str', 'g12-original-remainder-common-v1'], + ['tuple', [['str', p] for p in spec['common_constants']['original_scientific_pins']]], + ['int', '25'], ['tuple', [['int', '0'], ['int', '2'], ['int', '1']]]] + _need(_exact(tagged[1][:4], prefix), 'G12-N13: common inner source/workload prefix') + suffix = ['tuple', [['str', name] for name in ('verify_role_frames', 'full_log_integer_bounds', + 'original_upstream_verify_sources', 'original_serializable', 'complete_original_cli')]] + _need(_exact(tagged[1][-1], suffix), 'G12-N13: original suffix phase order') + for key in ('prefix_end', 'suffix_start', 'cli_end'): + row = diagnostic[key] + _fields(row, spec['diagnostic_snapshot_exact_fields']) + _uint(row['rank_event_count']) + _need(_rank_events(row['ordered_rank_events_hex']) == row['rank_event_count'] and + row['native_binding'] is None and row['cache_binding'] is None, + 'G12-N12: original diagnostic rank/binding domain') + receipt = row['complement_receipt'] + _fields(receipt, spec['complement_receipt_exact_fields']) + _uint(receipt['calls']) + _uint(receipt['canonical_stream_bytes']) + _need(_digest(receipt['sha256']) and receipt['schema'] == + 'v2-jsonl:call,us,vs,result(type=list+values or type=None); ordered exact integer vectors', 'G12-N12: complement receipt') + _rank_events(diagnostic['ordered_rank_suffix_hex']) + _fields(diagnostic['phases'], spec['phase_exact_names']) + for row in diagnostic['phases'].values(): + _fields(row, ('calls', 'wall_seconds', 'cpu_seconds_with_children')) + _need(type(row['calls']) is int and row['calls'] == 1, 'G12-N12: phase calls') + _number(row['wall_seconds']) + _number(row['cpu_seconds_with_children']) + return common, diagnostic, payload + + +def _source_pin(value): + _fields(value, ('path', 'sha256', 'bytes', 'mode')) + _path(value['path']) + _uint(value['bytes']) + _need(_digest(value['sha256']) and type(value['mode']) is str and len(value['mode']) == 4 and + all(c in '01234567' for c in value['mode']), 'G12-N02: exact source pin') + + +def _validate_guard(start, receipt, usage, stdout, stderr, root_argv, invocation, source_pins, phase_sha): + _fields(start, _GUARD_SCHEMA['START_exact_fields']) + _fields(receipt, _GUARD_SCHEMA['receipt_exact_fields']) + _fields(usage, ('user_seconds', 'system_seconds', 'kernel_max_rss_kib', 'exit')) + for key in start: + _need(_exact(start[key], receipt[key]), 'G12-N07: original START/receipt field join') + for key, expected in _GUARD_SCHEMA['required_values'].items(): + _need(_exact(receipt[key], expected), 'G12-N07: original guard success predicate') + for key in ('job', 'label', 'stage_sha256'): + _need(_exact(start[key], invocation[key]), 'G12-N07: selected invocation mismatch') + expected_launch = {'contract': 'trusted-clean-nosite-safe-path-fixedseed-v1', + 'no_site': 1, 'no_user_site': 1, 'safe_path': True, 'ignore_environment': 0, + 'isolated': 0, 'hash_seed_environment': '0', 'hash_randomization': 0, + 'initial_sys_path': ['/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload'], + 'environment': dict(_ENV), + 'trust_boundary': 'Authenticated parent launcher, OS, interpreter and system stdlib before this module; no Python self-authentication claim'} + _need(_exact(start['parent_launch'], expected_launch), 'G12-N07: exact original clean parent launch') + _need(_exact(start['command'], root_argv) and start['runner_sha256'] == _GUARD_PIN and + start['budget_phase_sha256'] == phase_sha and _digest(start['fractions_sha256']), + 'G12-N07: selected command/source/phase binding') + _need(type(start['phase_cap_seconds']) is int and start['phase_cap_seconds'] in (600, 2400), + 'G12-N05: original aggregate cap') + _number(start['spent_before_seconds']) + _need(start['spent_before_seconds'] < start['phase_cap_seconds'], 'G12-N05: consumed budget') + for key in ('wall_seconds', 'runner_wall_seconds', 'runner_user_seconds', 'runner_system_seconds', + 'runner_lifetime_max_rss_kib', 'sampled_process_group_rss_bytes'): + _number(receipt[key]) + limit = min(180, start['phase_cap_seconds'] - start['spent_before_seconds']) + _need(receipt['wall_seconds'] <= limit and receipt['runner_wall_seconds'] <= limit and + receipt['runner_lifetime_max_rss_kib'] * 1024 <= 1073741824 and + receipt['sampled_process_group_rss_bytes'] <= 1073741824, + 'G12-N07: original guard resource caps') + for key in ('user_seconds', 'system_seconds', 'kernel_max_rss_kib'): + _number(usage[key]) + _need(type(usage['exit']) is int and usage['exit'] == 0 and _exact(usage, receipt['usage']), + 'G12-N07: complete original usage join') + for name, raw in (('stdout', stdout), ('stderr', stderr)): + _need(len(raw) <= _LOG_CAP and receipt[name + '_bytes'] == len(raw) and + type(receipt[name + '_bytes']) is int and receipt[name + '_final_bytes'] == len(raw) and + type(receipt[name + '_final_bytes']) is int and + receipt[name + '_sha256'] == hashlib.sha256(raw).hexdigest(), 'G12-N07: complete raw log join') + _need(stderr == b'' and type(receipt['python']) is str and type(receipt['platform']) is str, + 'G12-N07: original stderr/platform fields') + + +def _capture_graph(namespace): + """Capture the fixed own/JSON function graph before candidate exposure.""" + modules = (json, json.decoder, json.encoder, json.scanner, hashlib, os, stat, math) + tuple( + namespace[name] for name in ('subprocess', 'fcntl', 'signal', 'resource', 'time') if name in namespace) + namespaces = [namespace] + [module.__dict__ for module in modules] + namespaces.extend((json._default_decoder.__dict__, json._default_encoder.__dict__)) + records, members, seen = [], [], set() + for mapping in namespaces: + members.append((mapping, tuple(mapping.items()))) + for value in mapping.values(): + candidates = [value] + if type(value) is type: + candidates.extend(value.__dict__.values()) + if value.__module__ in (__name__, 'json.decoder', 'json.encoder', 'subprocess'): + members.append((value.__dict__, tuple(value.__dict__.items()))) + for function in candidates: + if type(function) is not FunctionType or id(function) in seen: + continue + seen.add(id(function)) + records.append((function, function.__code__, function.__globals__, function.__builtins__, + function.__defaults__, function.__kwdefaults__, function.__closure__, + tuple(function.__dict__.items()), + () if function.__kwdefaults__ is None else tuple(function.__kwdefaults__.items()), + () if function.__closure__ is None else tuple((c, c.cell_contents) for c in function.__closure__))) + data = tuple((name, _canonical(namespace[name])) for name in + ('_PAIR_SCHEMA', '_MANIFEST_SCHEMA', '_GUARD_SCHEMA', '_PUBLICATION_SCHEMA', + '_ENGINE_PINS', '_OTHER_SOURCE_PINS', '_ENV', '_EVIDENCE_NAMES') if name in namespace) + return tuple(records), tuple(members), data + + +def _current_graph(graph): + records, members, data = graph + for mapping, rows in members: + # The capture itself is assigned once after this snapshot. + expected = dict(rows) + for name, value in rows: + _need(mapping.get(name, _MISSING) is value, 'G12-N04: captured namespace member changed: ' + name) + extra = set(mapping) - set(expected) + _need(not extra or mapping is globals() and extra == {'_INITIAL_GRAPH'}, + 'G12-N04: captured namespace census changed') + for name, expected in data: + _need(_canonical(globals()[name]) == expected, 'G12-N04: source-owned schema constant changed') + for f, code, namespace, builtin, defaults, kw, cells, attrs, kws, contents in records: + _need(f.__code__ is code and f.__globals__ is namespace and f.__builtins__ is builtin and + f.__defaults__ is defaults and f.__kwdefaults__ is kw and f.__closure__ is cells and + len(f.__dict__) == len(attrs), 'G12-N04: captured function graph changed') + for name, value in attrs: + _need(f.__dict__.get(name, _MISSING) is value, 'G12-N04: function attributes changed') + if kw is not None: + _need(len(kw) == len(kws), 'G12-N04: keyword-default census changed') + for name, value in kws: + _need(kw.get(name, _MISSING) is value, 'G12-N04: keyword defaults changed') + for cell, value in contents: + _need(cell.cell_contents is value, 'G12-N04: captured closure changed') +# END FIXED G12 FILE AND PAIR LEAF + +_PAIR_SCHEMA = {'common_constants': {'authority_source_sha256': 'f279ab86fc17c6a517b035f19d56863919cbd8304de4e7d5332457c6159aec10', + 'extra_target': [0, 2, 1], + 'h': 25, + 'literal_original_type': 'bool', + 'original_driver_sha256': '0d976d2eb6b845f20d4a3396591a806f966688b88693cd6a5f8a0c9e48925e36', + 'original_scientific_pins': ['d623617f7c5cb3189580883a8ab30c0bd3832688ae3f1f0c1f881bbbbff8e0c1', + '0da395e67ac04fa213494e71012c1b19b544596d34cdce5a3b172b1fb6af5f1b', + '88bba3caf5975f30fa7abceaea9454110cf3b069233e8241a2ca13d1dff171a7', + 'adc7f1241b42e322a6451854ab7e4b4c146bf78a'], + 'producer_role': 'independent-original-uncached', + 'schema': 'g12-independent-original-reference-envelope-v1', + 'scope': 'Actual original N22 literal and P07 common remainder observations only; ' + 'no original PROFILE_ANCHOR_PASS, FULL_PASS, native qualification or G12 ' + 'approval.', + 'selected_driver_sha256': 'a346025d5b6e2b26246521c6af6292643a4c2c3286b33ff3996dcf051cd6be26'}, + 'common_exact_fields': ['schema', + 'producer_role', + 'selected_driver_sha256', + 'original_driver_sha256', + 'authority_source_sha256', + 'original_scientific_pins', + 'h', + 'extra_target', + 'literal_original_type', + 'literal_original_value', + 'remaining_original_case_count', + 'common_payload_sha256', + 'common_payload_hex', + 'scope'], + 'complement_receipt_exact_fields': ['calls', 'canonical_stream_bytes', 'sha256', 'schema'], + 'diagnostic_constants': {'complement_suffix_limit': 'Only cumulative original start/end receipts; no ' + 'digest subtraction or suffix-stream claim.', + 'completion': 'Exact source-owned intentional marker followed by original ' + 'finally, exact observer restoration, both cold2 checks and ' + 'original source/output custody.', + 'producer_role': 'independent-original-uncached', + 'schema': 'g12-independent-original-reference-diagnostics-v1', + 'selected_driver_sha256': 'a346025d5b6e2b26246521c6af6292643a4c2c3286b33ff3996dcf051cd6be26'}, + 'diagnostic_exact_fields': ['schema', + 'producer_role', + 'selected_driver_sha256', + 'common_payload_sha256', + 'prefix_end', + 'suffix_start', + 'cli_end', + 'ordered_rank_suffix_hex', + 'complement_suffix_limit', + 'phases', + 'completion'], + 'diagnostic_snapshot_exact_fields': ['rank_event_count', + 'ordered_rank_events_hex', + 'complement_receipt', + 'native_binding', + 'cache_binding'], + 'phase_exact_names': ['input_custody', + 'engine_custody', + 'fresh_root_copy', + 'fresh_engine_copy', + 'cold_engine_import', + 'cold_complex_module_load', + 'cold_certify_import', + 'cold_prepare_import', + 'side_construction', + 'checks_initialization', + 'compile_roles', + 'verify_map', + 'verify_labels', + 'verify_role_frames', + 'original_upstream_verify_sources', + 'full_log_integer_bounds', + 'original_serializable', + 'complete_original_cli']} + +_MANIFEST_SCHEMA = {'accounting_exact_fields': ['clock', + 'parent_entry_ns', + 'preseal_end_ns', + 'parent_preseal_wall_ns', + 'parent_self_user_seconds', + 'parent_self_system_seconds', + 'parent_children_user_seconds', + 'parent_children_system_seconds', + 'parent_lifetime_max_rss_kib', + 'guard_usage', + 'guard_runner_wall_seconds', + 'categories', + 'complete_tail_accounting_required', + 'unmeasured_final_tail'], + 'cleanup_exact_fields': ['operating_premises', + 'owned_generations', + 'observed_groups', + 'remaining', + 'current_children', + 'known_streams_closed', + 'known_pidfds_closed', + 'io_unknown', + 'lease_identity', + 'science_directory_identity', + 'observations_record'], + 'custody_exact_fields': ['retained_directory', + 'retained_directory_identity', + 'retained_file_mode', + 'created_after_known_cleanup', + 'source_selection_required', + 'known_close_policy'], + 'exact_top_level_fields': ['schema', + 'invocation', + 'selected_sources', + 'workload', + 'launch', + 'terminal', + 'guard', + 'cleanup', + 'pair', + 'retained_evidence', + 'custody', + 'accounting', + 'scope'], + 'guard_exact_fields': ['start', + 'receipt', + 'start_fields', + 'receipt_fields', + 'stdout', + 'stderr', + 'usage'], + 'invocation_exact_fields': ['stage', + 'job', + 'label', + 'stage_sha256', + 'jobs_sha256', + 'launch_selection_sha256'], + 'launch_exact_fields': ['parent_pid', + 'parent_start_ticks', + 'guard_pid', + 'guard_start_ticks', + 'guard_pgid', + 'guard_sid', + 'parent_guard_argv', + 'guard_root_argv', + 'adapter_producer_argv', + 'cwd', + 'environment', + 'flags', + 'launch_record'], + 'pair_exact_fields': ['common', 'diagnostics', 'common_payload_sha256'], + 'retained_evidence_exact_keys': ['guard_START', + 'guard_receipt', + 'guard_stdout', + 'guard_stderr', + 'guard_usage', + 'parent_launch', + 'parent_outer_stdout', + 'parent_outer_stderr', + 'parent_owned_observations', + 'parent_preseal_accounting'], + 'schema_literal': 'g12-parent-two-export-custody-v2', + 'selected_sources_exact_fields': ['parent', + 'guard', + 'root', + 'provider', + 'adapter', + 'producer', + 'authority', + 'source_pins', + 'reference', + 'engine', + 'runtime_profile', + 'cleanup_leaf_origin'], + 'terminal_exact_fields': ['actual_popen_returncode', + 'wait_completed', + 'parent_stop', + 'primary_error', + 'secondary_errors', + 'guard_receipt_missing'], + 'workload_exact_fields': ['role', + 'h', + 'extra_target', + 'mode', + 'anchor', + 'optimize', + 'original_scientific_pins'], + 'workload_values': {'anchor': None, + 'extra_target': [0, 2, 1], + 'h': 25, + 'mode': 'profile', + 'optimize': 0, + 'original_scientific_pins': ['d623617f7c5cb3189580883a8ab30c0bd3832688ae3f1f0c1f881bbbbff8e0c1', + '0da395e67ac04fa213494e71012c1b19b544596d34cdce5a3b172b1fb6af5f1b', + '88bba3caf5975f30fa7abceaea9454110cf3b069233e8241a2ca13d1dff171a7', + 'adc7f1241b42e322a6451854ab7e4b4c146bf78a'], + 'role': 'independent-original-uncached'}} + +_GUARD_SCHEMA = {'START_exact_fields': ['command', + 'parent_launch', + 'stage_sha256', + 'runner_sha256', + 'fractions_sha256', + 'budget_phase_sha256', + 'spent_before_seconds', + 'phase_cap_seconds', + 'job', + 'label'], + 'receipt_exact_fields': ['command', + 'parent_launch', + 'stage_sha256', + 'runner_sha256', + 'fractions_sha256', + 'budget_phase_sha256', + 'spent_before_seconds', + 'phase_cap_seconds', + 'job', + 'label', + 'exit', + 'wall_seconds', + 'usage', + 'termination', + 'sampled_process_group_rss_bytes', + 'source_bytes_and_modes_unchanged', + 'stdout_sha256', + 'stdout_bytes', + 'stderr_sha256', + 'stderr_bytes', + 'stdout_final_bytes', + 'stderr_final_bytes', + 'retained_log_bytes_stable', + 'output_cap_observed_at', + 'log_read_chunk_bytes', + 'runner_wall_seconds', + 'runner_user_seconds', + 'runner_system_seconds', + 'runner_lifetime_max_rss_kib', + 'python', + 'platform', + 'status'], + 'required_values': {'exit': 0, + 'log_read_chunk_bytes': 65536, + 'output_cap_observed_at': None, + 'retained_log_bytes_stable': True, + 'source_bytes_and_modes_unchanged': True, + 'status': 'PASS', + 'stderr_bytes': 0, + 'stderr_final_bytes': 0, + 'termination': None}} + +_PUBLICATION_SCHEMA = {'exact_fields': ['schema', + 'parent_source_sha256', + 'launch_selection_sha256', + 'manifest_path', + 'manifest_sha256', + 'manifest_bytes', + 'manifest_identity', + 'retained_pair_sha256', + 'final_pair_recheck_complete', + 'known_lease_close_completed', + 'primary_error', + 'secondary_errors', + 'measured_through_ns', + 'actual_costs_through_ns', + 'unmeasured_final_tail', + 'complete_cost_qualification'], + 'schema_literal': 'g12-parent-custody-publication-v2'} + +_COST_CATEGORIES = ('source/stage/plan/authentication and dependency preflight', 'parent invocation setup and known lease operations', 'adapter bootstrap source read/hash/compile/exec and argv/module alias custody/restoration', 'entire independent uncached reference including fresh copies/engine imports/original CLI/trace capture/original checks/finally/restoration/cold2', 'guard launch/time/monitoring/STOP/final original source inventory/usage/raw-log hashing/receipt', 'actual parent wait and known descendant/group/FD cleanup', 'canonical receipt and START joins plus all complete raw evidence retention', 'both exports full reads/hashes/JSON/schema/payload decode/crosslinks and repeated pair checks', 'new parent copies/write/fsync/chmod/close/directory sync/readback', 'manifest schema/write/hash/fsync/close/readback and source-selection publication tail', 'parent failure/secondary-error retention and necessary cleanup after deadline', 'cold consumer complete manifest/pair/publication read/hash/parse/decode/recheck and all retained alias lifetimes') + + +def _validate_manifest(manifest, parent_path, parent_sha): + spec = _MANIFEST_SCHEMA + _fields(manifest, spec['exact_top_level_fields']) + _need(manifest['schema'] == spec['schema_literal'], 'G12-N12: custody schema') + for name in ('invocation', 'selected_sources', 'workload', 'launch', 'terminal', 'guard', + 'cleanup', 'pair', 'custody', 'accounting'): + _fields(manifest[name], spec[name + '_exact_fields']) + _fields(manifest['retained_evidence'], spec['retained_evidence_exact_keys']) + _need(_exact(manifest['workload'], spec['workload_values']), 'G12-N13: fixed workload') + invocation = manifest['invocation'] + _need(invocation['stage'] == 'g12-reference-custody-v1' and invocation['job'] == 'g12-reference' and + type(invocation['label']) is str and bool(invocation['label']) and + all(c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_' for c in invocation['label']), + 'G12-N13: fixed invocation role') + for name in ('stage_sha256', 'jobs_sha256', 'launch_selection_sha256'): + _need(_digest(invocation[name]), 'G12-N12: invocation digest') + sources = manifest['selected_sources'] + for name, pin in sources.items(): + if name != 'engine': + _source_pin(pin) + for name, expected in (('guard', _GUARD_PIN), ('root', _ROOT_PIN), ('provider', _PROVIDER_PIN), + ('producer', _PRODUCER_PIN), ('authority', _AUTHORITY_PIN)): + _need(sources[name]['sha256'] == expected and sources[name]['mode'] == '0444', + 'G12-N02: selected original source mismatch') + _need(sources['producer']['bytes'] == 70246 and sources['parent']['path'] == parent_path and + sources['parent']['sha256'] == parent_sha, 'G12-N02: selected producer/parent identity') + _need(_exact(sources['engine'], _ENGINE_PINS), 'G12-N02: exact original engine source pins') + for name, expected in _OTHER_SOURCE_PINS.items(): + _need(sources[name]['sha256'] == expected, 'G12-N02: selected original dependency mismatch') + terminal = {'actual_popen_returncode': 0, 'wait_completed': True, 'parent_stop': None, + 'primary_error': None, 'secondary_errors': [], 'guard_receipt_missing': False} + _need(_exact(manifest['terminal'], terminal), 'G12-N06: authenticated terminal data rejects') + cleanup = manifest['cleanup'] + _need(_exact(cleanup['remaining'], []) and _exact(cleanup['current_children'], []) and + cleanup['known_streams_closed'] is True and cleanup['known_pidfds_closed'] is True and + cleanup['io_unknown'] is False and type(cleanup['owned_generations']) is list and + bool(cleanup['owned_generations']) and _exact(cleanup['operating_premises'], _OPERATING_PREMISES), + 'G12-N08: known selected chain custody rejects') + for name in ('parent_pid', 'parent_start_ticks', 'guard_pid', 'guard_start_ticks', 'guard_pgid', 'guard_sid'): + _uint(manifest['launch'][name], True) + label = invocation['label'] + stage = _R + '/stages/g12-reference-custody-v1' + science = _R + '/runtime/runs/' + label + '/science' + parent_argv, root_argv, producer_argv = _fixed_argv(label, sources) + launch = manifest['launch'] + _need(_exact(launch['parent_guard_argv'], parent_argv) and _exact(launch['guard_root_argv'], root_argv) and + _exact(launch['adapter_producer_argv'], producer_argv) and launch['cwd'] == _R and + _exact(launch['environment'], _ENV) and _exact(launch['flags'], list(_FLAGS)), + 'G12-N03: exact fixed launch/adapter argv') + retained = _R + '/runtime/g12-reference-parent-custody-v1/' + label + custody = manifest['custody'] + _need(custody['retained_directory'] == retained and custody['retained_file_mode'] == '0444' and + custody['created_after_known_cleanup'] is True and custody['source_selection_required'] is True and + custody['known_close_policy'] == 'Any unknown close rejects publication', 'G12-N14: custody ownership') + _fields(custody['retained_directory_identity'], _ID_NAMES) + _need(custody['retained_directory_identity']['full_st_mode'] == stat.S_IFDIR | 0o500, + 'G12-N14: final retained directory mode') + for name in ('common', 'diagnostics'): + pair = manifest['pair'][name] + _fields(pair, ('original', 'retained')) + _file_record(pair['original']) + _file_record(pair['retained']) + filename = 'g12-reference.' + name + '.json' + _need(pair['original']['path'] == science + '/' + filename and + pair['retained']['path'] == retained + '/' + filename and + pair['original']['sha256'] == pair['retained']['sha256'] and + pair['original']['bytes'] == pair['retained']['bytes'] and + pair['retained']['identity']['full_st_mode'] == stat.S_IFREG | 0o444, + 'G12-N13: original/retained complete pair join') + _need(_digest(manifest['pair']['common_payload_sha256']), 'G12-N13: payload pin') + for name, record in manifest['retained_evidence'].items(): + _file_record(record) + _need(record['path'] == retained + '/' + _EVIDENCE_NAMES[name] and + record['identity']['full_st_mode'] == stat.S_IFREG | 0o444, + 'G12-N14: retained raw evidence path/mode') + for name, evidence_name in (('start', 'guard_START'), ('receipt', 'guard_receipt'), + ('stdout', 'guard_stdout'), ('stderr', 'guard_stderr'), ('usage', 'guard_usage')): + _need(_exact(manifest['guard'][name], manifest['retained_evidence'][evidence_name]), + 'G12-N07: guard retained record join') + _need(_exact(launch['launch_record'], manifest['retained_evidence']['parent_launch']) and + _exact(cleanup['observations_record'], manifest['retained_evidence']['parent_owned_observations']), + 'G12-N08: parent observation record join') + account = manifest['accounting'] + _need(account['clock'] == 'monotonic_ns' and account['complete_tail_accounting_required'] is True and + _exact(account['categories'], list(_COST_CATEGORIES)), 'G12-N15: full cost categories/tail') + for name in ('parent_entry_ns', 'preseal_end_ns', 'parent_preseal_wall_ns'): + _uint(account[name]) + _need(account['preseal_end_ns'] >= account['parent_entry_ns'] and + account['parent_preseal_wall_ns'] == account['preseal_end_ns'] - account['parent_entry_ns'], + 'G12-N15: actual parent clock endpoints') + for name in ('parent_self_user_seconds', 'parent_self_system_seconds', 'parent_children_user_seconds', + 'parent_children_system_seconds', 'parent_lifetime_max_rss_kib', 'guard_runner_wall_seconds'): + _number(account[name]) + _need(account['unmeasured_final_tail'] is None, 'G12-N15: unmeasured tail must stay explicitly unknown') + _need(_exact(account['guard_usage'], manifest['guard']['receipt_fields']['usage']) and + _exact(account['guard_runner_wall_seconds'], manifest['guard']['receipt_fields']['runner_wall_seconds']), + 'G12-N15: actual guard cost join') + _need(manifest['scope'] == _SCOPE, 'G12-N18: custody scope cannot become scientific approval') + + +def _fixed_argv(label, sources): + stage = _R + '/stages/g12-reference-custody-v1' + science = _R + '/runtime/runs/' + label + '/science' + parent = ['/usr/bin/python3.12', *_FLAGS, _R + '/run_guarded_v3.py', + 'g12-reference-custody-v1', 'g12-reference', label] + root = ['/usr/bin/python3.12', *_FLAGS, stage + '/integration/full_driver.py', + '--root-sha256', _ROOT_PIN, '--provider', stage + '/integration/probe_binding_v3.py', + _PROVIDER_PIN, '--driver', stage + '/integration/g12_reference_adapter_v1.py', + sources['adapter']['sha256'], '--integration', stage + '/integration', '--', + '--output', science, '--lanes', 'g12-reference'] + producer = [stage + '/baseline/full_driver.py', '--frozen-root', stage + '/baseline/frozen', + '--reference', stage + '/baseline/reference/certificates/complex-network.json', + '--mode', 'profile', '--output', science] + return parent, root, producer + + +def _validate_publication(publication, manifest, manifest_record): + _fields(publication, _PUBLICATION_SCHEMA['exact_fields']) + _need(publication['schema'] == _PUBLICATION_SCHEMA['schema_literal'] and + publication['parent_source_sha256'] == manifest['selected_sources']['parent']['sha256'] and + publication['launch_selection_sha256'] == manifest['invocation']['launch_selection_sha256'] and + publication['manifest_path'] == manifest_record['path'] and + publication['manifest_sha256'] == manifest_record['sha256'] and + publication['manifest_bytes'] == manifest_record['bytes'] and + _exact(publication['manifest_identity'], manifest_record['identity']) and + _exact(publication['retained_pair_sha256'], {name: manifest['pair'][name]['retained']['sha256'] + for name in ('common', 'diagnostics')}) and + publication['final_pair_recheck_complete'] is True and publication['known_lease_close_completed'] is True and + publication['primary_error'] is None and _exact(publication['secondary_errors'], []) and + publication['complete_cost_qualification'] is False and + _exact(publication['unmeasured_final_tail'], manifest['accounting']['unmeasured_final_tail']), + 'G12-N15: exact publication/manifest/final-tail join') + _uint(publication['measured_through_ns']) + _need(publication['measured_through_ns'] >= manifest['accounting']['preseal_end_ns'], + 'G12-N15: publication clock precedes preseal') + costs = publication['actual_costs_through_ns'] + _fields(costs, ('entry_ns', 'through_ns', 'wall_ns', 'self_user_seconds', 'self_system_seconds', + 'children_user_seconds', 'children_system_seconds', 'lifetime_max_rss_kib')) + for name in ('entry_ns', 'through_ns', 'wall_ns'): + _uint(costs[name]) + _need(costs['entry_ns'] == manifest['accounting']['parent_entry_ns'] and + costs['through_ns'] == publication['measured_through_ns'] and + costs['wall_ns'] == costs['through_ns'] - costs['entry_ns'], 'G12-N15: publication actual clock join') + for name in ('self_user_seconds', 'self_system_seconds', 'children_user_seconds', + 'children_system_seconds', 'lifetime_max_rss_kib'): + _number(costs[name]) + + +def _source_code_shape(code): + _need(type(code) is CodeType, 'G12-N04: exact code type') + def constant(value): + kind = type(value) + if value is None or value is Ellipsis: + return ('singleton', value is Ellipsis) + if kind in (int, bool, str, bytes): + return (kind.__name__, value) + if kind is float: + return ('float', value.hex()) + if kind is tuple: + return ('tuple', tuple(constant(item) for item in value)) + if kind is frozenset: + return ('frozenset', tuple(sorted(constant(item) for item in value))) + if kind is CodeType: + return ('code', _source_code_shape(value)) + raise RuntimeError('G12-N04: unsupported source code constant') + return tuple(constant(value) for value in ( + code.co_argcount, code.co_posonlyargcount, code.co_kwonlyargcount, + code.co_nlocals, code.co_stacksize, code.co_flags, code.co_code, + code.co_names, code.co_varnames, code.co_freevars, code.co_cellvars, + code.co_exceptiontable, code.co_linetable, code.co_firstlineno, + code.co_filename, code.co_name, code.co_qualname, code.co_consts)) + + +def _authenticate_own_functions(root, api, source, path): + _need(api[0]() == _ROOT_PIN, 'G12-N04: Root before selected-source compilation') + code = root._COMPILE(source, path, 'exec', dont_inherit=True, optimize=0) + declared = {item.co_name: item for item in code.co_consts if type(item) is CodeType} + for name, function in tuple(globals().items()): + if type(function) is FunctionType and function.__globals__ is globals(): + _need(name in declared and function.__builtins__ is root.builtins.__dict__ and + _source_code_shape(function.__code__) == _source_code_shape(declared[name]), + 'G12-N04: actual entire own callable differs from selected source: ' + name) + _need(api[0]() == _ROOT_PIN, 'G12-N04: Root after selected-source compilation') + + +def load_original_g12_reference(root, capability, api): + """Return only original literal/count/opaque common/provenance, after joint custody.""" + config = G12_REFERENCE_HANDOFF + selected = _BOOTSTRAP[3] + _need(type(config) is tuple and len(config) == 9 and type(selected) is tuple and len(selected) == 3, + 'G12-N01: actual parent handoff and cold source remain unselected') + _need(root is _BOOTSTRAP[0] and capability is _BOOTSTRAP[1] and api is _BOOTSTRAP[2] and + type(root) is ModuleType and type(api) is tuple and len(api) == 4 and + all(type(f) is FunctionType and f.__globals__ is root.__dict__ for f in api), + 'G12-N04: initial actual cold Root/capability/API identities differ') + _need(api[0]() == _ROOT_PIN and sys.flags.optimize == 0, 'G12-N04: authentic Root/assertions') + api[1](capability, _PROVIDER_PIN) + _current_graph(_INITIAL_GRAPH) + source_path, source_sha, source_size = selected + source_record, source_raw = _read_file(source_path, 1048576, 0o444) + _need(source_path == __file__ and source_record['sha256'] == source_sha and + source_record['bytes'] == source_size, 'G12-N04: exact independently selected consumer source') + _authenticate_own_functions(root, api, source_raw, source_path) + path, sha, size, identity_tuple, parent_path, parent_sha, publication_path, publication_sha, publication_size = config + _need(_digest(sha) and _digest(parent_sha) and _digest(publication_sha), 'G12-N16: source selection digest domain') + _uint(publication_size) + identity = _identity_dict_from_handoff(identity_tuple) + manifest_record = {'path': path, 'sha256': sha, 'bytes': size, 'identity': identity, 'nlink': 1} + manifest_raw = _root_read(root, api, manifest_record, _META_CAP) + manifest = _json(manifest_raw, _META_CAP, True, True) + _validate_manifest(manifest, parent_path, parent_sha) + retained = manifest['custody']['retained_directory'] + _need(path == retained + '/manifest.json' and publication_path == retained + '/publication.json', + 'G12-N16: exact fixed publication/manifest paths') + primary, secondaries, result = None, _RawG12Errors(), None + dirs, rows = _directory_chain(retained) + try: + _need(_exact(_identity(os.fstat(dirs[-1])), manifest['custody']['retained_directory_identity']), + 'G12-N17: final retained directory identity') + publication_record, _ = _read_file(publication_path, _META_CAP, 0o444) + _need(publication_record['sha256'] == publication_sha and publication_record['bytes'] == publication_size, + 'G12-N15: source-selected final publication bytes') + publication_raw = _root_read(root, api, publication_record, _META_CAP) + publication = _json(publication_raw, _META_CAP, True, True) + _validate_publication(publication, manifest, manifest_record) + evidence = {} + for name, record in manifest['retained_evidence'].items(): + cap = _LOG_CAP if name in ('guard_stdout', 'guard_stderr', 'parent_outer_stdout', 'parent_outer_stderr') else _META_CAP + evidence[name] = _root_read(root, api, record, cap) + launch_data = _json(evidence['parent_launch'], _META_CAP, True, True) + _fields(launch_data, ('schema', 'selection_sha256', 'source_selection', 'launch')) + _need(launch_data['schema'] == 'g12-parent-actual-launch-v1' and + launch_data['selection_sha256'] == manifest['invocation']['launch_selection_sha256'] == + hashlib.sha256(_canonical(launch_data['source_selection'])).hexdigest() and + _exact(launch_data['source_selection']['source_pins'], manifest['selected_sources']) and + _exact(launch_data['launch'], {k: v for k, v in manifest['launch'].items() if k != 'launch_record'}), + 'G12-N07: actual source-selected launch/raw evidence binding') + start = _json(evidence['guard_START'], _META_CAP) + receipt = _json(evidence['guard_receipt'], _META_CAP) + usage = _json(evidence['guard_usage'], 16384) + _need(_exact(start, manifest['guard']['start_fields']) and + _exact(receipt, manifest['guard']['receipt_fields']), 'G12-N07: original raw evidence joins') + _validate_guard(start, receipt, usage, evidence['guard_stdout'], evidence['guard_stderr'], + manifest['launch']['guard_root_argv'], manifest['invocation'], manifest['selected_sources'], + launch_data['source_selection']['phase_pin']['sha256']) + _need(_exact(_json(evidence['parent_outer_stdout'], _LOG_CAP), receipt) and + evidence['parent_outer_stderr'] == b'', 'G12-N07: actual outer raw log join') + common_record = manifest['pair']['common']['retained'] + diagnostic_record = manifest['pair']['diagnostics']['retained'] + common_raw = _root_read(root, api, common_record, _PAIR_CAP) + diagnostic_raw = _root_read(root, api, diagnostic_record, _PAIR_CAP) + common, diagnostics, payload = _validate_pair(common_raw, diagnostic_raw) + _need(common['common_payload_sha256'] == manifest['pair']['common_payload_sha256'], 'G12-N13: pair/manifest payload') + # Joint final reread includes diagnostics even after common decoding. + for record, raw, cap in ((manifest_record, manifest_raw, _META_CAP), + (common_record, common_raw, _PAIR_CAP), + (diagnostic_record, diagnostic_raw, _PAIR_CAP), + (publication_record, publication_raw, _META_CAP)): + _need(_root_read(root, api, record, cap) == raw, 'G12-N17: final full custody set changed') + for name, record in manifest['retained_evidence'].items(): + cap = _LOG_CAP if name in ('guard_stdout', 'guard_stderr', 'parent_outer_stdout', 'parent_outer_stderr') else _META_CAP + _need(_root_read(root, api, record, cap) == evidence[name], 'G12-N17: raw retained evidence drift') + _check_chain(rows) + _need(_exact(_identity(os.fstat(dirs[-1])), manifest['custody']['retained_directory_identity']), + 'G12-N17: final namespace changed after decode') + _need(_read_file(source_path, 1048576, 0o444) == (source_record, source_raw), 'G12-N04: consumer source drift') + _current_graph(_INITIAL_GRAPH) + api[1](capability, _PROVIDER_PIN) + _need(api[0]() == _ROOT_PIN, 'G12-N17: final actual Root currentness') + # Full diagnostic raw bytes stay retained; their hash is part of immutable + # provenance, and no diagnostic counter becomes an equality oracle. + provenance = (path, sha, size, tuple(identity[k] for k in _ID_NAMES), parent_path, parent_sha, + publication_path, publication_sha, publication_size, common_record['sha256'], + diagnostic_record['sha256'], common['common_payload_sha256'], + tuple(common['original_scientific_pins']), _PRODUCER_PIN, _AUTHORITY_PIN) + result = common['literal_original_value'], common['remaining_original_case_count'], payload, provenance + except BaseException as error: + primary = error, error.__traceback__ + for descriptor in reversed(dirs): + try: + os.close(descriptor) + except BaseException as error: + secondaries.append((error, error.__traceback__)) + _raise_preserved(primary, secondaries) + return result + +_R = '/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/h25-data-handling-20261028' + +_ENGINE_PINS = {'compare_side_verifier.py': '6e507bb0c7e00d090a60289fddb6c55e90c946d0850c42c3c5e3e15c27604a68', + 'finite_controls.py': 'df989a831aac43cc1af95169dad8c64a7548760e6e1f96976da996703f2c8f7a', + 'native_backend.py': 'e473c38245c3668715b5a78dfe980b2fe3ed0d0c9b8c97c666fbae6ecf1fffd5', + 'native_gf2.c': 'e9c3c9194a08718bd1575c1cf08c6c6772d3b644c2e274c25a84a1f9249d06cc', + 'profile_side_verifier.py': '9c994378171c20a91539418d93cb8387e1daa93465d6862beefea90e12999c2a', + 'source/complex_circuit.py': 'd623617f7c5cb3189580883a8ab30c0bd3832688ae3f1f0c1f881bbbbff8e0c1', + 'source/complex_network.py': '0da395e67ac04fa213494e71012c1b19b544596d34cdce5a3b172b1fb6af5f1b'} + +_OTHER_SOURCE_PINS = {'cleanup_leaf_origin': '7b3304eaf4884e3029df5095e2b0950c18d1544ad21431a07c033b85e53bd4f7', + 'reference': '1f763d95c7ff163aa71d13cd82784f16665be8afb21f75e76941e2119562098f', + 'runtime_profile': 'ad0ec2aea01b83f97bdeafd9e9208360127fee870d024d353879b5ed99237109', + 'source_pins': '88bba3caf5975f30fa7abceaea9454110cf3b069233e8241a2ca13d1dff171a7'} + +_OPERATING_PREMISES = ('Selected fixed scientific sources, adapter and ordinary profile branch do not fork/spawn threads, ' + 'daemonize, pass writable descriptors to outsiders, or enlist external writers. Trusted ' + 'OS/loader/interpreter/stdlib and cooperating same-user parent launch domain exclude unrelated writer ' + 'interference. This is an explicit finite source/operating premise, not established merely by a clean /proc ' + 'snapshot.') + +_SCOPE = ('Fixed source-data custody only. No G12/P02/full-positive/native/performance/scientific admission; no ' + 'universal writers theorem.') + +_FLAGS = ('-S', '-s', '-P', '-B') + +_ENV = {'LANG': 'C.UTF-8', + 'LC_ALL': 'C.UTF-8', + 'PATH': '/usr/bin:/bin', + 'PYTHONDONTWRITEBYTECODE': '1', + 'PYTHONHASHSEED': '0', + 'TZ': 'UTC'} + +_EVIDENCE_NAMES = {'guard_START': 'guard-START.json', + 'guard_receipt': 'guard-receipt.json', + 'guard_stderr': 'guard-stderr.txt', + 'guard_stdout': 'guard-stdout.txt', + 'guard_usage': 'guard-usage.json', + 'parent_launch': 'parent-LAUNCH.json', + 'parent_outer_stderr': 'parent-outer-stderr.txt', + 'parent_outer_stdout': 'parent-outer-stdout.txt', + 'parent_owned_observations': 'parent-owned-observations.json', + 'parent_preseal_accounting': 'parent-preseal-accounting.json'} + +_INITIAL_GRAPH = _capture_graph(globals()) diff --git a/research/h25-g12-custody-repairs/corrected/g12_reference_parent_v3.py b/research/h25-g12-custody-repairs/corrected/g12_reference_parent_v3.py new file mode 100644 index 0000000000..abd5582346 --- /dev/null +++ b/research/h25-g12-custody-repairs/corrected/g12_reference_parent_v3.py @@ -0,0 +1,1779 @@ +"""Fixed G12 parent custody source, v2 identity and preflight-close repair. + +No execution or publication authority. + +Only a later independently reviewed literal may select the launch. All actual +authorization, phase, resource-fit, custody and final-cost gates remain closed. +Unknown final tails remain unknown in the complete original symbolic invoice. +No manifest, receipt dictionary or success flag is accepted from a caller. +""" +import time +import resource +import signal +import subprocess +import fcntl +G12_REFERENCE_LAUNCH_SELECTION = None +_INITIAL_PARENT_SOURCE_PIN = globals().get('bootstrap_g12_parent_source_pin') +# Actual initial parent source identity comes only from the trusted external +# selected launcher; its future literal parent slot is None (no own-hash cycle). +import os + + +import sys + + +import stat + + +import json + + +import hashlib + + +import math + + +from types import FunctionType, CodeType, ModuleType + + +_ROOT_PIN = 'f5a2d33f2b4d3651f214156a0e7094c2bb516ce2d5ab7698d18c11f98f35dee0' + + +_PROVIDER_PIN = '9cbb7368f89e71d1e6cc46db5dc77efed3e03ed2a801c98c88fe316e4d9f3ef2' + + +_PRODUCER_PIN = 'a346025d5b6e2b26246521c6af6292643a4c2c3286b33ff3996dcf051cd6be26' + + +_GUARD_PIN = 'bd882e3dadb1b6aeaa63ee824f1a1c58f8ef2546b6840a2bffa46885a184d3eb' + + +_AUTHORITY_PIN = 'f279ab86fc17c6a517b035f19d56863919cbd8304de4e7d5332457c6159aec10' + + +_META_CAP = 262144 + + +_PAIR_CAP = 268435456 + + +_CHUNK = 65536 + + +_LOG_CAP = 2097152 + + +_MISSING = object() + + +_ID_NAMES = ('dev', 'ino', 'full_st_mode', 'size', 'mtime_ns', 'ctime_ns') + + +class _RawG12Errors: + """Fixed error-retention slots; storing raw failures precedes formatting/IO.""" + __slots__ = ('slots', 'count') + def __init__(self): + self.slots = [None] * 4096 + self.count = 0 + def append(self, value): + # All fixed directory/process/stream paths together have fewer than 4096 + # close sites under the 256-component/128-generation source ceilings. + if self.count >= len(self.slots): + raise RuntimeError('G12-N09: fixed raw secondary retention exhausted') + self.slots[self.count] = value + self.count += 1 + def __bool__(self): + return self.count != 0 + def __len__(self): + return self.count + def __getitem__(self, index): + if type(index) is not int or not 0 <= index < self.count: + raise IndexError(index) + return self.slots[index] + def __iter__(self): + for index in range(self.count): + yield self.slots[index] + def __repr__(self): + return repr(tuple(self)) + + +def _need(condition, message): + if not condition: + raise RuntimeError(message) + + +def _exact(value, expected): + if type(value) is not type(expected): + return False + if type(value) in (list, tuple): + return len(value) == len(expected) and all(_exact(a, b) for a, b in zip(value, expected)) + if type(value) is dict: + return set(value) == set(expected) and all(_exact(value[k], expected[k]) for k in expected) + return value == expected + + +def _fields(value, fields): + _need(type(value) is dict and all(type(k) is str for k in value) and + set(value) == set(fields), 'G12-N12: exact field domain differs') + + +def _digest(value): + return type(value) is str and len(value) == 64 and all(c in '0123456789abcdef' for c in value) + + +def _uint(value, positive=False): + _need(type(value) is int and value >= (1 if positive else 0), 'G12-N12: exact integer domain') + + +def _number(value): + _need(type(value) in (int, float) and math.isfinite(value) and value >= 0, + 'G12-N12: finite nonnegative exact number required') + + +def _path(path): + _need(type(path) is str and path.startswith('/') and + all(p not in ('', '.', '..') for p in path.split('/')[1:]), 'G12-N11: absolute canonical path') + return path + + +def _identity(info): + return dict(zip(_ID_NAMES, (info.st_dev, info.st_ino, info.st_mode, info.st_size, + info.st_mtime_ns, info.st_ctime_ns))) + + +def _directory_key(info): + return info.st_dev, info.st_ino, info.st_mode + + +def _directory_chain(path): + """Held no-follow chain; no later absolute path silently changes its owner.""" + _path(path) + _need(len(path.split('/')) <= 257, 'G12-N11: finite directory-component bound') + fds, rows = [], [] + primary = None + secondary = _RawG12Errors() + try: + fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC) + fds.append(fd) + for part in path.split('/')[1:]: + before = os.stat(part, dir_fd=fd, follow_symlinks=False) + _need(stat.S_ISDIR(before.st_mode), 'G12-N11: directory component type') + child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, + dir_fd=fd) + fds.append(child) + opened = os.fstat(child) + _need(_directory_key(before) == _directory_key(opened), 'G12-N11: directory replaced') + rows.append((fd, part, child, _directory_key(opened))) + fd = child + return fds, rows + except BaseException as error: + primary = (error, error.__traceback__) + for descriptor in reversed(fds): + try: + os.close(descriptor) + except BaseException as error: + secondary.append((error, error.__traceback__)) + _raise_preserved(primary, secondary) + + +def _check_chain(rows): + for parent, name, descriptor, key in rows: + _need(_directory_key(os.fstat(descriptor)) == key == + _directory_key(os.stat(name, dir_fd=parent, follow_symlinks=False)), + 'G12-N11: directory binding changed') + + +def _raise_preserved(primary, secondaries): + """Never replace first raw failure if evidence formatting or retention fails.""" + if primary is not None: + error, traceback = primary + try: + error.add_note('G12 ordered secondary failures: ' + repr(secondaries)) + except BaseException: + pass + raise error.with_traceback(traceback) + if secondaries: + error, traceback = secondaries[0][:2] + raise error.with_traceback(traceback) + + +def _handoff_identity_tuple(record): + """Pack a FileRecord identity as the immutable six-tuple handoff field. + + The accepted nine-tuple keeps this field positional. The cold consumer + converts it back to a string-keyed dictionary; this parent does not emit + a second, dictionary representation. + """ + _fields(record['identity'], _ID_NAMES) + return tuple(record['identity'][key] for key in _ID_NAMES) + + +def _close_known_descriptors(descriptors): + """Attempt every close. Ordered failures never stop the remaining closes.""" + failures = _RawG12Errors() + for descriptor in reversed(tuple(descriptors)): + try: + os.close(descriptor) + except BaseException as error: + failures.append((error, error.__traceback__)) + return failures + + +def _finally_close_known(descriptors, secondaries): + """Preflight finally: close all, keep a pending primary, fail if the body succeeded. + + A pending body error stays the propagating primary. Every close failure is + then an ordered secondary. If the body succeeded, the first close failure + propagates and only the later close failures are secondaries. + """ + failures = _close_known_descriptors(descriptors) + if sys.exc_info()[1] is None and failures: + error, traceback = failures[0] + for item in list(failures)[1:]: + secondaries.append(item) + raise error.with_traceback(traceback) + for item in failures: + secondaries.append(item) + + + + +def _read_file(path, cap, mode=None): + _path(path) + parent, name = path.rsplit('/', 1) + descriptor, primary, secondary, result = None, None, _RawG12Errors(), None + fds, rows = _directory_chain(parent) + try: + before = os.stat(name, dir_fd=fds[-1], follow_symlinks=False) + _need(stat.S_ISREG(before.st_mode) and before.st_nlink == 1 and + 0 <= before.st_size <= cap and (mode is None or before.st_mode == stat.S_IFREG | mode), + 'G12-N11: regular-file size/mode/link domain') + descriptor = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, + dir_fd=fds[-1]) + opened = os.fstat(descriptor) + _need(_identity(before) == _identity(opened) and opened.st_nlink == 1, + 'G12-N11: file changed on open') + count, blocks, hasher = 0, [], hashlib.sha256() + while count < opened.st_size: + block = os.read(descriptor, min(_CHUNK, opened.st_size - count)) + _need(bool(block), 'G12-N11: short file read') + count += len(block) + hasher.update(block) + blocks.append(block) + _need(os.read(descriptor, 1) == b'', 'G12-N11: file grew') + after = os.fstat(descriptor) + ending = os.stat(name, dir_fd=fds[-1], follow_symlinks=False) + _need(_identity(before) == _identity(after) == _identity(ending) and + after.st_nlink == ending.st_nlink == 1, 'G12-N11: full file identity changed') + _check_chain(rows) + result = ({'path': path, 'sha256': hasher.hexdigest(), 'bytes': count, + 'identity': _identity(after), 'nlink': 1}, b''.join(blocks)) + except BaseException as error: + primary = (error, error.__traceback__) + for fd in ([descriptor] if descriptor is not None else []) + list(reversed(fds)): + try: + os.close(fd) + except BaseException as error: + secondary.append((error, error.__traceback__)) + _raise_preserved(primary, secondary) + return result + + +def _file_record(value): + _fields(value, ('path', 'sha256', 'bytes', 'identity', 'nlink')) + _path(value['path']) + _need(_digest(value['sha256']) and type(value['nlink']) is int and value['nlink'] == 1, + 'G12-N11: file digest/link record') + _uint(value['bytes']) + _fields(value['identity'], _ID_NAMES) + for key in _ID_NAMES: + _need(type(value['identity'][key]) is int, 'G12-N11: exact stat value') + _uint(value['identity']['dev']) + _uint(value['identity']['ino'], True) + _need(stat.S_ISREG(value['identity']['full_st_mode']) and + value['identity']['size'] == value['bytes'], 'G12-N11: file identity size/type') + + +def _pairs(items): + result = {} + for key, value in items: + _need(type(key) is str and key not in result, 'G12-N12: duplicate JSON key') + result[key] = value + return result + + +def _nonfinite(value): + raise ValueError('G12-N12: nonfinite JSON token: ' + value) + + +def _canonical(value): + return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True, + allow_nan=False).encode('ascii') + + +def _json(raw, cap, canonical=False, newline=False): + _need(type(raw) is bytes and len(raw) <= cap, 'G12-N12: raw JSON bound') + # Scan lexical nesting before json.loads recursion or object materialization. + depth, quoted, escaped = 0, False, False + for char in raw: + if quoted: + if escaped: + escaped = False + elif char == 92: + escaped = True + elif char == 34: + quoted = False + elif char == 34: + quoted = True + elif char in (91, 123): + depth += 1 + _need(depth <= 256, 'G12-N12: JSON depth limit') + elif char in (93, 125): + depth -= 1 + _need(depth >= 0, 'G12-N12: JSON nesting') + _need(depth == 0 and not quoted, 'G12-N12: incomplete JSON') + value = json.loads(raw.decode('utf-8'), object_pairs_hook=_pairs, parse_constant=_nonfinite) + pending, count = [(value, 0)], 0 + while pending: + item, depth = pending.pop() + count += 1 + _need(count <= cap and depth <= 256, 'G12-N12: JSON node/depth limit') + if type(item) is dict: + pending.extend((x, depth + 1) for pair in item.items() for x in pair) + elif type(item) is list: + pending.extend((x, depth + 1) for x in item) + elif type(item) is str: + _need(len(item) <= cap, 'G12-N12: JSON string limit') + elif type(item) is float: + _need(math.isfinite(item), 'G12-N12: overflowed JSON number') + else: + _need(item is None or type(item) in (bool, int), 'G12-N12: JSON primitive') + if canonical: + _need(raw == _canonical(value) + (b'\n' if newline else b''), 'G12-N12: canonical JSON bytes') + return value + + +def _hex(value, cap): + _need(type(value) is str and len(value) <= cap and len(value) % 2 == 0 and + all(c in '0123456789abcdef' for c in value), 'G12-N12: complete lowercase hex') + return bytes.fromhex(value) + + +def _decimal(value, positive=False): + _need(type(value) is str and bool(value), 'G12-N12: integer tag text') + digits = value[1:] if value.startswith('-') else value + _need(bool(digits) and all(c in '0123456789' for c in digits) and + (digits == '0' or digits[0] != '0') and value != '-0' and + (not positive or (not value.startswith('-') and value != '0')), 'G12-N12: canonical integer') + + +def _tagged(raw, cap): + value = _json(raw, cap, True) + pending = [(value, 0)] + count = 0 + while pending: + node, depth = pending.pop() + count += 1 + _need(count <= cap and depth <= 256 and type(node) is list and len(node) >= 1 and + type(node[0]) is str, 'G12-N12: tagged primitive bound/shape') + tag = node[0] + if tag == 'None': + _need(len(node) == 1, 'G12-N12: None arity') + continue + _need(len(node) == (3 if tag == 'Fraction' else 2), 'G12-N12: primitive arity') + arg = node[1] + if tag == 'bool': + _need(type(arg) is bool, 'G12-N12: bool tag') + elif tag == 'int': + _decimal(arg) + elif tag == 'Fraction': + _decimal(arg) + _decimal(node[2], True) + elif tag == 'str': + _need(type(arg) is str, 'G12-N12: string tag') + elif tag == 'bytes': + _hex(arg, cap) + elif tag == 'float': + _need(type(arg) is str and float.fromhex(arg).hex() == arg, 'G12-N12: float.hex domain') + elif tag in ('tuple', 'list'): + _need(type(arg) is list, 'G12-N12: sequence tag') + pending.extend((item, depth + 1) for item in arg) + elif tag == 'dict': + _need(type(arg) is list, 'G12-N12: ordered dict tag') + for pair in arg: + _need(type(pair) is list and len(pair) == 2, 'G12-N12: dict pair') + pending.extend((item, depth + 1) for item in pair) + else: + raise ValueError('G12-N12: unknown primitive tag') + return value + + +def _rank_events(encoded): + value = _tagged(_hex(encoded, _PAIR_CAP), _PAIR_CAP) + _need(value[0] == 'tuple', 'G12-N12: rank tuple') + for event in value[1]: + _need(event[0] == 'tuple' and len(event[1]) == 2 and event[1][0][0] == 'tuple' and + all(x[0] == 'int' for x in event[1][0][1]) and event[1][1][0] == 'int', + 'G12-N12: rank-event grammar') + return len(value[1]) + + +def _validate_pair(common_raw, diagnostic_raw): + common = _json(common_raw, _PAIR_CAP, True, True) + diagnostic = _json(diagnostic_raw, _PAIR_CAP, True, True) + spec = _PAIR_SCHEMA + _fields(common, spec['common_exact_fields']) + _fields(diagnostic, spec['diagnostic_exact_fields']) + for key, expected in spec['common_constants'].items(): + _need(_exact(common[key], expected), 'G12-N13: original common source/workload binding') + for key, expected in spec['diagnostic_constants'].items(): + _need(_exact(diagnostic[key], expected), 'G12-N13: diagnostic source/role binding') + _need(type(common['literal_original_value']) is bool, 'G12-N12: observed literal exact bool') + _uint(common['remaining_original_case_count'], True) + payload = _hex(common['common_payload_hex'], _PAIR_CAP) + _need(_digest(common['common_payload_sha256']) and + hashlib.sha256(payload).hexdigest() == common['common_payload_sha256'] == + diagnostic['common_payload_sha256'], 'G12-N13: complete common digest join') + tagged = _tagged(payload, _PAIR_CAP) + _need(tagged[0] == 'tuple' and len(tagged[1]) == 10, 'G12-N13: common tuple arity') + prefix = [['str', 'g12-original-remainder-common-v1'], + ['tuple', [['str', p] for p in spec['common_constants']['original_scientific_pins']]], + ['int', '25'], ['tuple', [['int', '0'], ['int', '2'], ['int', '1']]]] + _need(_exact(tagged[1][:4], prefix), 'G12-N13: common inner source/workload prefix') + suffix = ['tuple', [['str', name] for name in ('verify_role_frames', 'full_log_integer_bounds', + 'original_upstream_verify_sources', 'original_serializable', 'complete_original_cli')]] + _need(_exact(tagged[1][-1], suffix), 'G12-N13: original suffix phase order') + for key in ('prefix_end', 'suffix_start', 'cli_end'): + row = diagnostic[key] + _fields(row, spec['diagnostic_snapshot_exact_fields']) + _uint(row['rank_event_count']) + _need(_rank_events(row['ordered_rank_events_hex']) == row['rank_event_count'] and + row['native_binding'] is None and row['cache_binding'] is None, + 'G12-N12: original diagnostic rank/binding domain') + receipt = row['complement_receipt'] + _fields(receipt, spec['complement_receipt_exact_fields']) + _uint(receipt['calls']) + _uint(receipt['canonical_stream_bytes']) + _need(_digest(receipt['sha256']) and receipt['schema'] == + 'v2-jsonl:call,us,vs,result(type=list+values or type=None); ordered exact integer vectors', 'G12-N12: complement receipt') + _rank_events(diagnostic['ordered_rank_suffix_hex']) + _fields(diagnostic['phases'], spec['phase_exact_names']) + for row in diagnostic['phases'].values(): + _fields(row, ('calls', 'wall_seconds', 'cpu_seconds_with_children')) + _need(type(row['calls']) is int and row['calls'] == 1, 'G12-N12: phase calls') + _number(row['wall_seconds']) + _number(row['cpu_seconds_with_children']) + return common, diagnostic, payload + + +def _source_pin(value): + _fields(value, ('path', 'sha256', 'bytes', 'mode')) + _path(value['path']) + _uint(value['bytes']) + _need(_digest(value['sha256']) and type(value['mode']) is str and len(value['mode']) == 4 and + all(c in '01234567' for c in value['mode']), 'G12-N02: exact source pin') + + +def _validate_guard(start, receipt, usage, stdout, stderr, root_argv, invocation, source_pins, phase_sha): + _fields(start, _GUARD_SCHEMA['START_exact_fields']) + _fields(receipt, _GUARD_SCHEMA['receipt_exact_fields']) + _fields(usage, ('user_seconds', 'system_seconds', 'kernel_max_rss_kib', 'exit')) + for key in start: + _need(_exact(start[key], receipt[key]), 'G12-N07: original START/receipt field join') + for key, expected in _GUARD_SCHEMA['required_values'].items(): + _need(_exact(receipt[key], expected), 'G12-N07: original guard success predicate') + for key in ('job', 'label', 'stage_sha256'): + _need(_exact(start[key], invocation[key]), 'G12-N07: selected invocation mismatch') + expected_launch = {'contract': 'trusted-clean-nosite-safe-path-fixedseed-v1', + 'no_site': 1, 'no_user_site': 1, 'safe_path': True, 'ignore_environment': 0, + 'isolated': 0, 'hash_seed_environment': '0', 'hash_randomization': 0, + 'initial_sys_path': ['/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload'], + 'environment': dict(_ENV), + 'trust_boundary': 'Authenticated parent launcher, OS, interpreter and system stdlib before this module; no Python self-authentication claim'} + _need(_exact(start['parent_launch'], expected_launch), 'G12-N07: exact original clean parent launch') + _need(_exact(start['command'], root_argv) and start['runner_sha256'] == _GUARD_PIN and + start['budget_phase_sha256'] == phase_sha and _digest(start['fractions_sha256']), + 'G12-N07: selected command/source/phase binding') + _need(type(start['phase_cap_seconds']) is int and start['phase_cap_seconds'] in (600, 2400), + 'G12-N05: original aggregate cap') + _number(start['spent_before_seconds']) + _need(start['spent_before_seconds'] < start['phase_cap_seconds'], 'G12-N05: consumed budget') + for key in ('wall_seconds', 'runner_wall_seconds', 'runner_user_seconds', 'runner_system_seconds', + 'runner_lifetime_max_rss_kib', 'sampled_process_group_rss_bytes'): + _number(receipt[key]) + limit = min(180, start['phase_cap_seconds'] - start['spent_before_seconds']) + _need(receipt['wall_seconds'] <= limit and receipt['runner_wall_seconds'] <= limit and + receipt['runner_lifetime_max_rss_kib'] * 1024 <= 1073741824 and + receipt['sampled_process_group_rss_bytes'] <= 1073741824, + 'G12-N07: original guard resource caps') + for key in ('user_seconds', 'system_seconds', 'kernel_max_rss_kib'): + _number(usage[key]) + _need(type(usage['exit']) is int and usage['exit'] == 0 and _exact(usage, receipt['usage']), + 'G12-N07: complete original usage join') + for name, raw in (('stdout', stdout), ('stderr', stderr)): + _need(len(raw) <= _LOG_CAP and receipt[name + '_bytes'] == len(raw) and + type(receipt[name + '_bytes']) is int and receipt[name + '_final_bytes'] == len(raw) and + type(receipt[name + '_final_bytes']) is int and + receipt[name + '_sha256'] == hashlib.sha256(raw).hexdigest(), 'G12-N07: complete raw log join') + _need(stderr == b'' and type(receipt['python']) is str and type(receipt['platform']) is str, + 'G12-N07: original stderr/platform fields') + + +def _capture_graph(namespace): + """Capture the fixed own/JSON function graph before candidate exposure.""" + modules = (json, json.decoder, json.encoder, json.scanner, hashlib, os, stat, math) + tuple( + namespace[name] for name in ('subprocess', 'fcntl', 'signal', 'resource', 'time') if name in namespace) + namespaces = [namespace] + [module.__dict__ for module in modules] + namespaces.extend((json._default_decoder.__dict__, json._default_encoder.__dict__)) + records, members, seen = [], [], set() + for mapping in namespaces: + members.append((mapping, tuple(mapping.items()))) + for value in mapping.values(): + candidates = [value] + if type(value) is type: + candidates.extend(value.__dict__.values()) + if value.__module__ in (__name__, 'json.decoder', 'json.encoder', 'subprocess'): + members.append((value.__dict__, tuple(value.__dict__.items()))) + for function in candidates: + if type(function) is not FunctionType or id(function) in seen: + continue + seen.add(id(function)) + records.append((function, function.__code__, function.__globals__, function.__builtins__, + function.__defaults__, function.__kwdefaults__, function.__closure__, + tuple(function.__dict__.items()), + () if function.__kwdefaults__ is None else tuple(function.__kwdefaults__.items()), + () if function.__closure__ is None else tuple((c, c.cell_contents) for c in function.__closure__))) + data = tuple((name, _canonical(namespace[name])) for name in + ('_PAIR_SCHEMA', '_MANIFEST_SCHEMA', '_GUARD_SCHEMA', '_PUBLICATION_SCHEMA', + '_ENGINE_PINS', '_OTHER_SOURCE_PINS', '_ENV', '_EVIDENCE_NAMES') if name in namespace) + return tuple(records), tuple(members), data + + + +def _current_graph(graph): + records, members, data = graph + for mapping, rows in members: + # The capture itself is assigned once after this snapshot. + expected = dict(rows) + for name, value in rows: + _need(mapping.get(name, _MISSING) is value, 'G12-N04: captured namespace member changed: ' + name) + extra = set(mapping) - set(expected) + _need(not extra or mapping is globals() and extra == {'_INITIAL_GRAPH'}, + 'G12-N04: captured namespace census changed') + for name, expected in data: + _need(_canonical(globals()[name]) == expected, 'G12-N04: source-owned schema constant changed') + for f, code, namespace, builtin, defaults, kw, cells, attrs, kws, contents in records: + _need(f.__code__ is code and f.__globals__ is namespace and f.__builtins__ is builtin and + f.__defaults__ is defaults and f.__kwdefaults__ is kw and f.__closure__ is cells and + len(f.__dict__) == len(attrs), 'G12-N04: captured function graph changed') + for name, value in attrs: + _need(f.__dict__.get(name, _MISSING) is value, 'G12-N04: function attributes changed') + if kw is not None: + _need(len(kw) == len(kws), 'G12-N04: keyword-default census changed') + for name, value in kws: + _need(kw.get(name, _MISSING) is value, 'G12-N04: keyword defaults changed') + for cell, value in contents: + _need(cell.cell_contents is value, 'G12-N04: captured closure changed') + + + +_PAIR_SCHEMA = {'common_constants': {'authority_source_sha256': 'f279ab86fc17c6a517b035f19d56863919cbd8304de4e7d5332457c6159aec10', + 'extra_target': [0, 2, 1], + 'h': 25, + 'literal_original_type': 'bool', + 'original_driver_sha256': '0d976d2eb6b845f20d4a3396591a806f966688b88693cd6a5f8a0c9e48925e36', + 'original_scientific_pins': ['d623617f7c5cb3189580883a8ab30c0bd3832688ae3f1f0c1f881bbbbff8e0c1', + '0da395e67ac04fa213494e71012c1b19b544596d34cdce5a3b172b1fb6af5f1b', + '88bba3caf5975f30fa7abceaea9454110cf3b069233e8241a2ca13d1dff171a7', + 'adc7f1241b42e322a6451854ab7e4b4c146bf78a'], + 'producer_role': 'independent-original-uncached', + 'schema': 'g12-independent-original-reference-envelope-v1', + 'scope': 'Actual original N22 literal and P07 common remainder observations only; ' + 'no original PROFILE_ANCHOR_PASS, FULL_PASS, native qualification or G12 ' + 'approval.', + 'selected_driver_sha256': 'a346025d5b6e2b26246521c6af6292643a4c2c3286b33ff3996dcf051cd6be26'}, + 'common_exact_fields': ['schema', + 'producer_role', + 'selected_driver_sha256', + 'original_driver_sha256', + 'authority_source_sha256', + 'original_scientific_pins', + 'h', + 'extra_target', + 'literal_original_type', + 'literal_original_value', + 'remaining_original_case_count', + 'common_payload_sha256', + 'common_payload_hex', + 'scope'], + 'complement_receipt_exact_fields': ['calls', 'canonical_stream_bytes', 'sha256', 'schema'], + 'diagnostic_constants': {'complement_suffix_limit': 'Only cumulative original start/end receipts; no ' + 'digest subtraction or suffix-stream claim.', + 'completion': 'Exact source-owned intentional marker followed by original ' + 'finally, exact observer restoration, both cold2 checks and ' + 'original source/output custody.', + 'producer_role': 'independent-original-uncached', + 'schema': 'g12-independent-original-reference-diagnostics-v1', + 'selected_driver_sha256': 'a346025d5b6e2b26246521c6af6292643a4c2c3286b33ff3996dcf051cd6be26'}, + 'diagnostic_exact_fields': ['schema', + 'producer_role', + 'selected_driver_sha256', + 'common_payload_sha256', + 'prefix_end', + 'suffix_start', + 'cli_end', + 'ordered_rank_suffix_hex', + 'complement_suffix_limit', + 'phases', + 'completion'], + 'diagnostic_snapshot_exact_fields': ['rank_event_count', + 'ordered_rank_events_hex', + 'complement_receipt', + 'native_binding', + 'cache_binding'], + 'phase_exact_names': ['input_custody', + 'engine_custody', + 'fresh_root_copy', + 'fresh_engine_copy', + 'cold_engine_import', + 'cold_complex_module_load', + 'cold_certify_import', + 'cold_prepare_import', + 'side_construction', + 'checks_initialization', + 'compile_roles', + 'verify_map', + 'verify_labels', + 'verify_role_frames', + 'original_upstream_verify_sources', + 'full_log_integer_bounds', + 'original_serializable', + 'complete_original_cli']} + + +_MANIFEST_SCHEMA = {'accounting_exact_fields': ['clock', + 'parent_entry_ns', + 'preseal_end_ns', + 'parent_preseal_wall_ns', + 'parent_self_user_seconds', + 'parent_self_system_seconds', + 'parent_children_user_seconds', + 'parent_children_system_seconds', + 'parent_lifetime_max_rss_kib', + 'guard_usage', + 'guard_runner_wall_seconds', + 'categories', + 'complete_tail_accounting_required', + 'unmeasured_final_tail'], + 'cleanup_exact_fields': ['operating_premises', + 'owned_generations', + 'observed_groups', + 'remaining', + 'current_children', + 'known_streams_closed', + 'known_pidfds_closed', + 'io_unknown', + 'lease_identity', + 'science_directory_identity', + 'observations_record'], + 'custody_exact_fields': ['retained_directory', + 'retained_directory_identity', + 'retained_file_mode', + 'created_after_known_cleanup', + 'source_selection_required', + 'known_close_policy'], + 'exact_top_level_fields': ['schema', + 'invocation', + 'selected_sources', + 'workload', + 'launch', + 'terminal', + 'guard', + 'cleanup', + 'pair', + 'retained_evidence', + 'custody', + 'accounting', + 'scope'], + 'guard_exact_fields': ['start', + 'receipt', + 'start_fields', + 'receipt_fields', + 'stdout', + 'stderr', + 'usage'], + 'invocation_exact_fields': ['stage', + 'job', + 'label', + 'stage_sha256', + 'jobs_sha256', + 'launch_selection_sha256'], + 'launch_exact_fields': ['parent_pid', + 'parent_start_ticks', + 'guard_pid', + 'guard_start_ticks', + 'guard_pgid', + 'guard_sid', + 'parent_guard_argv', + 'guard_root_argv', + 'adapter_producer_argv', + 'cwd', + 'environment', + 'flags', + 'launch_record'], + 'pair_exact_fields': ['common', 'diagnostics', 'common_payload_sha256'], + 'retained_evidence_exact_keys': ['guard_START', + 'guard_receipt', + 'guard_stdout', + 'guard_stderr', + 'guard_usage', + 'parent_launch', + 'parent_outer_stdout', + 'parent_outer_stderr', + 'parent_owned_observations', + 'parent_preseal_accounting'], + 'schema_literal': 'g12-parent-two-export-custody-v2', + 'selected_sources_exact_fields': ['parent', + 'guard', + 'root', + 'provider', + 'adapter', + 'producer', + 'authority', + 'source_pins', + 'reference', + 'engine', + 'runtime_profile', + 'cleanup_leaf_origin'], + 'terminal_exact_fields': ['actual_popen_returncode', + 'wait_completed', + 'parent_stop', + 'primary_error', + 'secondary_errors', + 'guard_receipt_missing'], + 'workload_exact_fields': ['role', + 'h', + 'extra_target', + 'mode', + 'anchor', + 'optimize', + 'original_scientific_pins'], + 'workload_values': {'anchor': None, + 'extra_target': [0, 2, 1], + 'h': 25, + 'mode': 'profile', + 'optimize': 0, + 'original_scientific_pins': ['d623617f7c5cb3189580883a8ab30c0bd3832688ae3f1f0c1f881bbbbff8e0c1', + '0da395e67ac04fa213494e71012c1b19b544596d34cdce5a3b172b1fb6af5f1b', + '88bba3caf5975f30fa7abceaea9454110cf3b069233e8241a2ca13d1dff171a7', + 'adc7f1241b42e322a6451854ab7e4b4c146bf78a'], + 'role': 'independent-original-uncached'}} + + +_GUARD_SCHEMA = {'START_exact_fields': ['command', + 'parent_launch', + 'stage_sha256', + 'runner_sha256', + 'fractions_sha256', + 'budget_phase_sha256', + 'spent_before_seconds', + 'phase_cap_seconds', + 'job', + 'label'], + 'receipt_exact_fields': ['command', + 'parent_launch', + 'stage_sha256', + 'runner_sha256', + 'fractions_sha256', + 'budget_phase_sha256', + 'spent_before_seconds', + 'phase_cap_seconds', + 'job', + 'label', + 'exit', + 'wall_seconds', + 'usage', + 'termination', + 'sampled_process_group_rss_bytes', + 'source_bytes_and_modes_unchanged', + 'stdout_sha256', + 'stdout_bytes', + 'stderr_sha256', + 'stderr_bytes', + 'stdout_final_bytes', + 'stderr_final_bytes', + 'retained_log_bytes_stable', + 'output_cap_observed_at', + 'log_read_chunk_bytes', + 'runner_wall_seconds', + 'runner_user_seconds', + 'runner_system_seconds', + 'runner_lifetime_max_rss_kib', + 'python', + 'platform', + 'status'], + 'required_values': {'exit': 0, + 'log_read_chunk_bytes': 65536, + 'output_cap_observed_at': None, + 'retained_log_bytes_stable': True, + 'source_bytes_and_modes_unchanged': True, + 'status': 'PASS', + 'stderr_bytes': 0, + 'stderr_final_bytes': 0, + 'termination': None}} + + +_PUBLICATION_SCHEMA = {'exact_fields': ['schema', + 'parent_source_sha256', + 'launch_selection_sha256', + 'manifest_path', + 'manifest_sha256', + 'manifest_bytes', + 'manifest_identity', + 'retained_pair_sha256', + 'final_pair_recheck_complete', + 'known_lease_close_completed', + 'primary_error', + 'secondary_errors', + 'measured_through_ns', + 'actual_costs_through_ns', + 'unmeasured_final_tail', + 'complete_cost_qualification'], + 'schema_literal': 'g12-parent-custody-publication-v2'} + + +_COST_CATEGORIES = ('source/stage/plan/authentication and dependency preflight', 'parent invocation setup and known lease operations', 'adapter bootstrap source read/hash/compile/exec and argv/module alias custody/restoration', 'entire independent uncached reference including fresh copies/engine imports/original CLI/trace capture/original checks/finally/restoration/cold2', 'guard launch/time/monitoring/STOP/final original source inventory/usage/raw-log hashing/receipt', 'actual parent wait and known descendant/group/FD cleanup', 'canonical receipt and START joins plus all complete raw evidence retention', 'both exports full reads/hashes/JSON/schema/payload decode/crosslinks and repeated pair checks', 'new parent copies/write/fsync/chmod/close/directory sync/readback', 'manifest schema/write/hash/fsync/close/readback and source-selection publication tail', 'parent failure/secondary-error retention and necessary cleanup after deadline', 'cold consumer complete manifest/pair/publication read/hash/parse/decode/recheck and all retained alias lifetimes') + + +def _validate_manifest(manifest, parent_path, parent_sha): + spec = _MANIFEST_SCHEMA + _fields(manifest, spec['exact_top_level_fields']) + _need(manifest['schema'] == spec['schema_literal'], 'G12-N12: custody schema') + for name in ('invocation', 'selected_sources', 'workload', 'launch', 'terminal', 'guard', + 'cleanup', 'pair', 'custody', 'accounting'): + _fields(manifest[name], spec[name + '_exact_fields']) + _fields(manifest['retained_evidence'], spec['retained_evidence_exact_keys']) + _need(_exact(manifest['workload'], spec['workload_values']), 'G12-N13: fixed workload') + invocation = manifest['invocation'] + _need(invocation['stage'] == 'g12-reference-custody-v1' and invocation['job'] == 'g12-reference' and + type(invocation['label']) is str and bool(invocation['label']) and + all(c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_' for c in invocation['label']), + 'G12-N13: fixed invocation role') + for name in ('stage_sha256', 'jobs_sha256', 'launch_selection_sha256'): + _need(_digest(invocation[name]), 'G12-N12: invocation digest') + sources = manifest['selected_sources'] + for name, pin in sources.items(): + if name != 'engine': + _source_pin(pin) + for name, expected in (('guard', _GUARD_PIN), ('root', _ROOT_PIN), ('provider', _PROVIDER_PIN), + ('producer', _PRODUCER_PIN), ('authority', _AUTHORITY_PIN)): + _need(sources[name]['sha256'] == expected and sources[name]['mode'] == '0444', + 'G12-N02: selected original source mismatch') + _need(sources['producer']['bytes'] == 70246 and sources['parent']['path'] == parent_path and + sources['parent']['sha256'] == parent_sha, 'G12-N02: selected producer/parent identity') + _need(_exact(sources['engine'], _ENGINE_PINS), 'G12-N02: exact original engine source pins') + for name, expected in _OTHER_SOURCE_PINS.items(): + _need(sources[name]['sha256'] == expected, 'G12-N02: selected original dependency mismatch') + terminal = {'actual_popen_returncode': 0, 'wait_completed': True, 'parent_stop': None, + 'primary_error': None, 'secondary_errors': [], 'guard_receipt_missing': False} + _need(_exact(manifest['terminal'], terminal), 'G12-N06: authenticated terminal data rejects') + cleanup = manifest['cleanup'] + _need(_exact(cleanup['remaining'], []) and _exact(cleanup['current_children'], []) and + cleanup['known_streams_closed'] is True and cleanup['known_pidfds_closed'] is True and + cleanup['io_unknown'] is False and type(cleanup['owned_generations']) is list and + bool(cleanup['owned_generations']) and _exact(cleanup['operating_premises'], _OPERATING_PREMISES), + 'G12-N08: known selected chain custody rejects') + for name in ('parent_pid', 'parent_start_ticks', 'guard_pid', 'guard_start_ticks', 'guard_pgid', 'guard_sid'): + _uint(manifest['launch'][name], True) + label = invocation['label'] + stage = _R + '/stages/g12-reference-custody-v1' + science = _R + '/runtime/runs/' + label + '/science' + parent_argv, root_argv, producer_argv = _fixed_argv(label, sources) + launch = manifest['launch'] + _need(_exact(launch['parent_guard_argv'], parent_argv) and _exact(launch['guard_root_argv'], root_argv) and + _exact(launch['adapter_producer_argv'], producer_argv) and launch['cwd'] == _R and + _exact(launch['environment'], _ENV) and _exact(launch['flags'], list(_FLAGS)), + 'G12-N03: exact fixed launch/adapter argv') + retained = _R + '/runtime/g12-reference-parent-custody-v1/' + label + custody = manifest['custody'] + _need(custody['retained_directory'] == retained and custody['retained_file_mode'] == '0444' and + custody['created_after_known_cleanup'] is True and custody['source_selection_required'] is True and + custody['known_close_policy'] == 'Any unknown close rejects publication', 'G12-N14: custody ownership') + _fields(custody['retained_directory_identity'], _ID_NAMES) + _need(custody['retained_directory_identity']['full_st_mode'] == stat.S_IFDIR | 0o500, + 'G12-N14: final retained directory mode') + for name in ('common', 'diagnostics'): + pair = manifest['pair'][name] + _fields(pair, ('original', 'retained')) + _file_record(pair['original']) + _file_record(pair['retained']) + filename = 'g12-reference.' + name + '.json' + _need(pair['original']['path'] == science + '/' + filename and + pair['retained']['path'] == retained + '/' + filename and + pair['original']['sha256'] == pair['retained']['sha256'] and + pair['original']['bytes'] == pair['retained']['bytes'] and + pair['retained']['identity']['full_st_mode'] == stat.S_IFREG | 0o444, + 'G12-N13: original/retained complete pair join') + _need(_digest(manifest['pair']['common_payload_sha256']), 'G12-N13: payload pin') + for name, record in manifest['retained_evidence'].items(): + _file_record(record) + _need(record['path'] == retained + '/' + _EVIDENCE_NAMES[name] and + record['identity']['full_st_mode'] == stat.S_IFREG | 0o444, + 'G12-N14: retained raw evidence path/mode') + for name, evidence_name in (('start', 'guard_START'), ('receipt', 'guard_receipt'), + ('stdout', 'guard_stdout'), ('stderr', 'guard_stderr'), ('usage', 'guard_usage')): + _need(_exact(manifest['guard'][name], manifest['retained_evidence'][evidence_name]), + 'G12-N07: guard retained record join') + _need(_exact(launch['launch_record'], manifest['retained_evidence']['parent_launch']) and + _exact(cleanup['observations_record'], manifest['retained_evidence']['parent_owned_observations']), + 'G12-N08: parent observation record join') + account = manifest['accounting'] + _need(account['clock'] == 'monotonic_ns' and account['complete_tail_accounting_required'] is True and + _exact(account['categories'], list(_COST_CATEGORIES)), 'G12-N15: full cost categories/tail') + for name in ('parent_entry_ns', 'preseal_end_ns', 'parent_preseal_wall_ns'): + _uint(account[name]) + _need(account['preseal_end_ns'] >= account['parent_entry_ns'] and + account['parent_preseal_wall_ns'] == account['preseal_end_ns'] - account['parent_entry_ns'], + 'G12-N15: actual parent clock endpoints') + for name in ('parent_self_user_seconds', 'parent_self_system_seconds', 'parent_children_user_seconds', + 'parent_children_system_seconds', 'parent_lifetime_max_rss_kib', 'guard_runner_wall_seconds'): + _number(account[name]) + _need(account['unmeasured_final_tail'] is None, 'G12-N15: unmeasured tail must stay explicitly unknown') + _need(_exact(account['guard_usage'], manifest['guard']['receipt_fields']['usage']) and + _exact(account['guard_runner_wall_seconds'], manifest['guard']['receipt_fields']['runner_wall_seconds']), + 'G12-N15: actual guard cost join') + _need(manifest['scope'] == _SCOPE, 'G12-N18: custody scope cannot become scientific approval') + + +def _fixed_argv(label, sources): + stage = _R + '/stages/g12-reference-custody-v1' + science = _R + '/runtime/runs/' + label + '/science' + parent = ['/usr/bin/python3.12', *_FLAGS, _R + '/run_guarded_v3.py', + 'g12-reference-custody-v1', 'g12-reference', label] + root = ['/usr/bin/python3.12', *_FLAGS, stage + '/integration/full_driver.py', + '--root-sha256', _ROOT_PIN, '--provider', stage + '/integration/probe_binding_v3.py', + _PROVIDER_PIN, '--driver', stage + '/integration/g12_reference_adapter_v1.py', + sources['adapter']['sha256'], '--integration', stage + '/integration', '--', + '--output', science, '--lanes', 'g12-reference'] + producer = [stage + '/baseline/full_driver.py', '--frozen-root', stage + '/baseline/frozen', + '--reference', stage + '/baseline/reference/certificates/complex-network.json', + '--mode', 'profile', '--output', science] + return parent, root, producer + + +def _validate_publication(publication, manifest, manifest_record): + _fields(publication, _PUBLICATION_SCHEMA['exact_fields']) + _need(publication['schema'] == _PUBLICATION_SCHEMA['schema_literal'] and + publication['parent_source_sha256'] == manifest['selected_sources']['parent']['sha256'] and + publication['launch_selection_sha256'] == manifest['invocation']['launch_selection_sha256'] and + publication['manifest_path'] == manifest_record['path'] and + publication['manifest_sha256'] == manifest_record['sha256'] and + publication['manifest_bytes'] == manifest_record['bytes'] and + _exact(publication['manifest_identity'], manifest_record['identity']) and + _exact(publication['retained_pair_sha256'], {name: manifest['pair'][name]['retained']['sha256'] + for name in ('common', 'diagnostics')}) and + publication['final_pair_recheck_complete'] is True and publication['known_lease_close_completed'] is True and + publication['primary_error'] is None and _exact(publication['secondary_errors'], []) and + publication['complete_cost_qualification'] is False and + _exact(publication['unmeasured_final_tail'], manifest['accounting']['unmeasured_final_tail']), + 'G12-N15: exact publication/manifest/final-tail join') + _uint(publication['measured_through_ns']) + _need(publication['measured_through_ns'] >= manifest['accounting']['preseal_end_ns'], + 'G12-N15: publication clock precedes preseal') + costs = publication['actual_costs_through_ns'] + _fields(costs, ('entry_ns', 'through_ns', 'wall_ns', 'self_user_seconds', 'self_system_seconds', + 'children_user_seconds', 'children_system_seconds', 'lifetime_max_rss_kib')) + for name in ('entry_ns', 'through_ns', 'wall_ns'): + _uint(costs[name]) + _need(costs['entry_ns'] == manifest['accounting']['parent_entry_ns'] and + costs['through_ns'] == publication['measured_through_ns'] and + costs['wall_ns'] == costs['through_ns'] - costs['entry_ns'], 'G12-N15: publication actual clock join') + for name in ('self_user_seconds', 'self_system_seconds', 'children_user_seconds', + 'children_system_seconds', 'lifetime_max_rss_kib'): + _number(costs[name]) + + +def _source_code_shape(code): + _need(type(code) is CodeType, 'G12-N04: exact code type') + def constant(value): + kind = type(value) + if value is None or value is Ellipsis: + return ('singleton', value is Ellipsis) + if kind in (int, bool, str, bytes): + return (kind.__name__, value) + if kind is float: + return ('float', value.hex()) + if kind is tuple: + return ('tuple', tuple(constant(item) for item in value)) + if kind is frozenset: + return ('frozenset', tuple(sorted(constant(item) for item in value))) + if kind is CodeType: + return ('code', _source_code_shape(value)) + raise RuntimeError('G12-N04: unsupported source code constant') + return tuple(constant(value) for value in ( + code.co_argcount, code.co_posonlyargcount, code.co_kwonlyargcount, + code.co_nlocals, code.co_stacksize, code.co_flags, code.co_code, + code.co_names, code.co_varnames, code.co_freevars, code.co_cellvars, + code.co_exceptiontable, code.co_linetable, code.co_firstlineno, + code.co_filename, code.co_name, code.co_qualname, code.co_consts)) + + +_R = '/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/h25-data-handling-20261028' + + +_ENGINE_PINS = {'compare_side_verifier.py': '6e507bb0c7e00d090a60289fddb6c55e90c946d0850c42c3c5e3e15c27604a68', + 'finite_controls.py': 'df989a831aac43cc1af95169dad8c64a7548760e6e1f96976da996703f2c8f7a', + 'native_backend.py': 'e473c38245c3668715b5a78dfe980b2fe3ed0d0c9b8c97c666fbae6ecf1fffd5', + 'native_gf2.c': 'e9c3c9194a08718bd1575c1cf08c6c6772d3b644c2e274c25a84a1f9249d06cc', + 'profile_side_verifier.py': '9c994378171c20a91539418d93cb8387e1daa93465d6862beefea90e12999c2a', + 'source/complex_circuit.py': 'd623617f7c5cb3189580883a8ab30c0bd3832688ae3f1f0c1f881bbbbff8e0c1', + 'source/complex_network.py': '0da395e67ac04fa213494e71012c1b19b544596d34cdce5a3b172b1fb6af5f1b'} + + +_OTHER_SOURCE_PINS = {'cleanup_leaf_origin': '7b3304eaf4884e3029df5095e2b0950c18d1544ad21431a07c033b85e53bd4f7', + 'reference': '1f763d95c7ff163aa71d13cd82784f16665be8afb21f75e76941e2119562098f', + 'runtime_profile': 'ad0ec2aea01b83f97bdeafd9e9208360127fee870d024d353879b5ed99237109', + 'source_pins': '88bba3caf5975f30fa7abceaea9454110cf3b069233e8241a2ca13d1dff171a7'} + + +_OPERATING_PREMISES = ('Selected fixed scientific sources, adapter and ordinary profile branch do not fork/spawn threads, ' + 'daemonize, pass writable descriptors to outsiders, or enlist external writers. Trusted ' + 'OS/loader/interpreter/stdlib and cooperating same-user parent launch domain exclude unrelated writer ' + 'interference. This is an explicit finite source/operating premise, not established merely by a clean /proc ' + 'snapshot.') + + +_SCOPE = ('Fixed source-data custody only. No G12/P02/full-positive/native/performance/scientific admission; no ' + 'universal writers theorem.') + + +_FLAGS = ('-S', '-s', '-P', '-B') + + +_ENV = {'LANG': 'C.UTF-8', + 'LC_ALL': 'C.UTF-8', + 'PATH': '/usr/bin:/bin', + 'PYTHONDONTWRITEBYTECODE': '1', + 'PYTHONHASHSEED': '0', + 'TZ': 'UTC'} + + +_EVIDENCE_NAMES = {'guard_START': 'guard-START.json', + 'guard_receipt': 'guard-receipt.json', + 'guard_stderr': 'guard-stderr.txt', + 'guard_stdout': 'guard-stdout.txt', + 'guard_usage': 'guard-usage.json', + 'parent_launch': 'parent-LAUNCH.json', + 'parent_outer_stderr': 'parent-outer-stderr.txt', + 'parent_outer_stdout': 'parent-outer-stdout.txt', + 'parent_owned_observations': 'parent-owned-observations.json', + 'parent_preseal_accounting': 'parent-preseal-accounting.json'} + + + +def _proc(pid): + # Derived from original supervisor proc; PermissionError is never absence. + descriptor, primary, secondaries, result = None, None, _RawG12Errors(), None + try: + descriptor = os.open('/proc/' + str(pid) + '/stat', os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC) + raw = os.read(descriptor, 8193) + _need(len(raw) <= 8192 and os.read(descriptor, 1) == b'', 'G12-N08: process-stat finite bound') + end = raw.rfind(b') ') + _need(end >= 0 and raw.split(b' ', 1)[0] == str(pid).encode('ascii'), 'G12-N08: process-stat PID') + fields = raw[end + 2:].split() + _need(len(fields) >= 22 and fields[0] in (b'R', b'S', b'D', b'Z', b'T', b't', b'X', b'x', b'I', b'K', b'W', b'P'), + 'G12-N08: process-stat shape/state') + result = {'pid': pid, 'ppid': int(fields[1]), 'pgid': int(fields[2]), 'sid': int(fields[3]), + 'start_ticks': int(fields[19]), 'state': fields[0].decode('ascii'), + 'rss_bytes': int(fields[21]) * os.sysconf('SC_PAGE_SIZE')} + for key in ('pid', 'ppid', 'pgid', 'sid', 'start_ticks', 'rss_bytes'): + _uint(result[key], key in ('pid', 'start_ticks')) + except (FileNotFoundError, ProcessLookupError): + result = None + except BaseException as error: + primary = error, error.__traceback__ + if descriptor is not None: + try: + os.close(descriptor) + except BaseException as error: + secondaries.append((error, error.__traceback__)) + _raise_preserved(primary, secondaries) + return result + + +def _census(): + rows = {} + with os.scandir('/proc') as entries: + for entry in entries: + if entry.name.isdecimal(): + _need(len(rows) < 65536, 'G12-N08: finite process census bound') + row = _proc(int(entry.name)) + if row is not None: + rows[row['pid']] = row + return rows + + +def _children(): + return [row for row in _census().values() if row['ppid'] == os.getpid()] + + +class _KnownG12Chain: + """Scoped generation/pidfd observation only; never universal writer proof.""" + def __init__(self): + _need(not _children(), 'G12-N08: initial parent child domain must be empty') + _need(os.listdir('/proc/self/task') == [str(os.getpid())], 'G12-N08: single initial parent task') + self.rows, self.fds, self.groups, self.observations = {}, {}, set(), [] + self.parent_pid = os.getpid() + self.parent_group = os.getpgrp() + self.closed = False + self.unknown = False + + def add(self, row): + key = row['pid'], row['start_ticks'] + if key in self.rows: + _need(self.rows[key]['pid'] == row['pid'], 'G12-N08: owned generation identity') + if row['pgid'] != self.parent_group: + self.groups.add((row['pgid'], row['sid'])) + return + _need(row['pid'] != self.parent_pid and len(self.rows) < 128, 'G12-N08: fixed owned process bound') + descriptor = os.pidfd_open(row['pid'], 0) + # A failed/ambiguous adoption rejects; never treat it as known closure. + self.fds[key] = descriptor + current = _proc(row['pid']) + _need(current is not None and (current['pid'], current['start_ticks']) == key, + 'G12-N08: process generation changed during pidfd adoption') + self.rows[key] = dict(current) + if current['pgid'] != self.parent_group: + self.groups.add((current['pgid'], current['sid'])) + + def observe(self): + _need(not self.closed, 'G12-N08: closed observation domain') + rows = _census() + known = {pid for pid, start in self.rows if pid in rows and rows[pid]['start_ticks'] == start} + for pid in known: + self.add(rows[pid]) + changed = True + while changed: + changed = False + for pid, row in rows.items(): + if pid not in known and (row['ppid'] == self.parent_pid or row['ppid'] in known): + self.add(row) + known.add(pid) + changed = True + occupied = [row for row in rows.values() if (row['pgid'], row['sid']) in self.groups] + current = [rows[pid] for pid in known] + _need(len(self.observations) < 4096, 'G12-N08: finite observation retention') + self.observations.append({'monotonic_ns': time.monotonic_ns(), 'current': current, 'occupied_groups': occupied}) + return rows, current, occupied + + def stop_known(self): + self.observe() + for key, descriptor in self.fds.items(): + current = _proc(key[0]) + if current is not None: + _need((current['pid'], current['start_ticks']) == key, 'G12-N08: generation ambiguity before signal') + if current['state'] != 'Z': + try: + signal.pidfd_send_signal(descriptor, signal.SIGKILL, None, 0) + except ProcessLookupError: + pass + + def release_known_pidfds(self, secondaries): + """Release known descriptors after the final process-disposal attempt. + + A close error leaves custody unknown. Retire numeric ownership before + close so that an ambiguous close cannot cause a later blind FD retry. + This does not establish process exit or turn unknown cleanup into success. + """ + for key, descriptor in tuple(self.fds.items()): + del self.fds[key] + try: + os.close(descriptor) + except BaseException as error: + self.unknown = True + secondaries.append((error, error.__traceback__)) + + def finish(self, process, deadline, failed): + _need(type(deadline) is int, 'G12-N08: selected paid cleanup deadline') + current, occupied = [], [] + while True: + if failed: + self.stop_known() + if process is not None: + process.poll() + _, current, occupied = self.observe() + if not current and not occupied and not _children(): + break + if not failed or time.monotonic_ns() >= deadline: + raise RuntimeError('G12-N08: selected-chain cleanup UNKNOWN') + time.sleep(0.01) + primary, secondaries = None, _RawG12Errors() + self.release_known_pidfds(secondaries) + self.closed = not self.fds and not self.unknown + _raise_preserved(primary, secondaries) + return {'operating_premises': _OPERATING_PREMISES, + 'owned_generations': list(self.rows.values()), + 'observed_groups': [{'pgid': g, 'sid': s} for g, s in sorted(self.groups)], + 'remaining': [], 'current_children': [], 'known_streams_closed': False, + 'known_pidfds_closed': self.closed, 'io_unknown': self.unknown, + 'lease_identity': None, 'science_directory_identity': None, + 'observations_record': None} + + +def _trusted_parent_launch(): + _need(sys.executable == '/usr/bin/python3.12' and sys.flags.optimize == 0 and + sys.flags.no_site == sys.flags.no_user_site == sys.flags.dont_write_bytecode == 1 and + sys.flags.safe_path and sys.flags.ignore_environment == sys.flags.isolated == sys.flags.hash_randomization == 0, + 'G12-N02: original clean parent interpreter flags') + _need(dict(os.environ) == _ENV and tuple(sys.path) == + ('/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload'), + 'G12-N02: original clean environment/search path') + _need(sys.gettrace() is None and sys.getprofile() is None, 'G12-N04: no parent tracing callbacks') + + +def _exclusive_directory(path): + parent, name = _path(path).rsplit('/', 1) + primary, secondaries, result = None, _RawG12Errors(), None + fds, rows = _directory_chain(parent) + try: + os.mkdir(name, 0o700, dir_fd=fds[-1]) + descriptor = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=fds[-1]) + fds.append(descriptor) + current = os.fstat(descriptor) + _need(current.st_mode == stat.S_IFDIR | 0o700, 'G12-N14: new parent directory mode') + rows.append((fds[-2], name, descriptor, _directory_key(current))) + _check_chain(rows) + result = fds, rows + except BaseException as error: + primary = error, error.__traceback__ + if primary is not None: + for descriptor in reversed(fds): + try: + os.close(descriptor) + except BaseException as error: + secondaries.append((error, error.__traceback__)) + _raise_preserved(primary, secondaries) + return result + + +def _write_fd(descriptor, raw): + _need(type(raw) is bytes, 'G12-N14: exact retained byte copy') + offset, hasher = 0, hashlib.sha256() + while offset < len(raw): + block = raw[offset:offset + _CHUNK] + written = os.write(descriptor, block) + _need(type(written) is int and 0 < written <= len(block), 'G12-N14: complete copy write progress') + hasher.update(block[:written]) + offset += written + _need(offset == len(raw) and hasher.hexdigest() == hashlib.sha256(raw).hexdigest(), + 'G12-N14: complete copied byte digest') + os.fsync(descriptor) + os.fchmod(descriptor, 0o444) + os.fsync(descriptor) + + +def _copy_file(directory, name, raw): + fds, rows = directory + primary, secondaries = None, _RawG12Errors() + descriptor = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, dir_fd=fds[-1]) + try: + _write_fd(descriptor, raw) + _check_chain(rows) + except BaseException as error: + primary = error, error.__traceback__ + try: + os.close(descriptor) + except BaseException as error: + secondaries.append((error, error.__traceback__)) + _raise_preserved(primary, secondaries) + os.fsync(fds[-1]) + + +def _actual_costs(entry_ns, own_start, children_start): + through = time.monotonic_ns() + own, children = resource.getrusage(resource.RUSAGE_SELF), resource.getrusage(resource.RUSAGE_CHILDREN) + return {'entry_ns': entry_ns, 'through_ns': through, 'wall_ns': through - entry_ns, + 'self_user_seconds': own.ru_utime - own_start.ru_utime, + 'self_system_seconds': own.ru_stime - own_start.ru_stime, + 'children_user_seconds': children.ru_utime - children_start.ru_utime, + 'children_system_seconds': children.ru_stime - children_start.ru_stime, + 'lifetime_max_rss_kib': own.ru_maxrss} + + +def run_g12_reference(): + """P01: one source-private invocation; accepts no caller completion data.""" + configured = G12_REFERENCE_LAUNCH_SELECTION + _need(type(configured) is dict, 'G12-N01: exact immutable launch source literal remains None') + _need(type(_INITIAL_PARENT_SOURCE_PIN) is dict and configured['source_pins']['parent'] is None, + 'G12-N02: independent initial external parent source pin; no self-hash literal') + _source_pin(_INITIAL_PARENT_SOURCE_PIN) + configured_bytes = _canonical(configured) + selection = dict(configured) + selection['source_pins'] = dict(configured['source_pins']) + selection['source_pins']['parent'] = dict(_INITIAL_PARENT_SOURCE_PIN) + # Actual launch remains closed. The independently reviewed source scope + # correction requires the complete symbolic bill, not a new financial API. + entry_ns = time.monotonic_ns() + own_start, children_start = resource.getrusage(resource.RUSAGE_SELF), resource.getrusage(resource.RUSAGE_CHILDREN) + selection_bytes = _canonical(selection) + selection_sha = hashlib.sha256(selection_bytes).hexdigest() + parent_graph = _capture_graph(globals()) + phase, stage_data, stage_record, jobs_record, phase_record = None, None, None, None, None + source_records, originals, evidence, retained_records = {}, {}, {}, {} + parent_identity = _proc(os.getpid()) + process, chain, lease, lease_identity = None, None, None, None + lease_closed, attempted, wait_completed = False, False, False + outer = {} + observation, retained, science_directory, run_directory = None, None, None, None + primary, secondaries, parent_stop = None, _RawG12Errors(), None + cleanup, common, diagnostic, common_payload = None, None, None, None + start, receipt, usage, launch = None, None, None, None + manifest, manifest_record, publication_record = None, None, None + reserved = {} + candidate_pin = None + + def current(): + _need(G12_REFERENCE_LAUNCH_SELECTION is configured and _canonical(configured) == configured_bytes and + _canonical(selection) == selection_bytes and _exact(selection['source_pins']['parent'], _INITIAL_PARENT_SOURCE_PIN), + 'G12-N16: selected launch source changed') + _current_graph(parent_graph) + _need(_proc(os.getpid())['start_ticks'] == parent_identity['start_ticks'], 'G12-N08: parent generation') + _need(os.listdir('/proc/self/task') == [str(os.getpid())], 'G12-N08: parent thread domain changed') + if lease is not None and not lease_closed: + _need(_identity(os.fstat(lease)) == lease_identity and os.fstat(lease).st_nlink == 1, + 'G12-N08: actual parent lease identity changed') + for domain in (observation, retained, science_directory, run_directory): + if domain is not None: + _check_chain(domain[1]) + + def _g12_preflight_and_claim(): + """P02: exact source/phase/namespace gate; separate parent-queue lease.""" + nonlocal phase, stage_data, stage_record, jobs_record, phase_record, chain + nonlocal lease, lease_identity, observation + _fields(selection, ('schema', 'stage', 'job', 'label', 'stage_sha256', 'jobs_sha256', 'source_pins', + 'phase_pin', 'body_deadline_ns', 'retention_tail_allowance_ns', + 'parent_observation_directory', 'parent_retained_directory')) + _need(selection['schema'] == 'g12-one-reference-launch-selection-v1' and + selection['stage'] == 'g12-reference-custody-v1' and selection['job'] == 'g12-reference', + 'G12-N02: fixed G12 launch role') + label = selection['label'] + _need(type(label) is str and bool(label) and + all(c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_' for c in label), + 'G12-N03: fixed selected guard label') + _need(selection['parent_observation_directory'] == _R + '/runtime/g12-reference-parent-observation-v1/' + label and + selection['parent_retained_directory'] == _R + '/runtime/g12-reference-parent-custody-v1/' + label, + 'G12-N02: fixed parent namespace') + _uint(selection['body_deadline_ns'], True) + _uint(selection['retention_tail_allowance_ns'], True) + _need(selection['body_deadline_ns'] > entry_ns, 'G12-N05: no remaining complete body allowance') + _trusted_parent_launch() + sources = selection['source_pins'] + _fields(sources, _MANIFEST_SCHEMA['selected_sources_exact_fields']) + _need(_exact(sources['engine'], _ENGINE_PINS), 'G12-N02: exact seven original engine pins') + for name, pin in sources.items(): + if name == 'engine': + continue + _source_pin(pin) + observed, raw = _read_file(pin['path'], max(pin['bytes'], 1), int(pin['mode'], 8)) + _need(observed['sha256'] == pin['sha256'] and observed['bytes'] == pin['bytes'], + 'G12-N02: selected source bytes/modes') + source_records[name] = observed, raw + _need(sources['parent']['path'] == __file__, 'G12-N04: external parent source selection') + for name, expected in (('guard', _GUARD_PIN), ('root', _ROOT_PIN), ('provider', _PROVIDER_PIN), + ('producer', _PRODUCER_PIN), ('authority', _AUTHORITY_PIN)): + _need(sources[name]['sha256'] == expected and sources[name]['mode'] == '0444', 'G12-N02: original source pin') + for name, expected in _OTHER_SOURCE_PINS.items(): + _need(sources[name]['sha256'] == expected, 'G12-N02: original dependency pin') + _source_pin(selection['phase_pin']) + phase_record, phase_raw = _read_file(selection['phase_pin']['path'], _META_CAP, + int(selection['phase_pin']['mode'], 8)) + _need(selection['phase_pin']['path'] == _R + '/control/EXECUTION-PHASE.json' and + phase_record['sha256'] == selection['phase_pin']['sha256'] and + phase_record['bytes'] == selection['phase_pin']['bytes'], 'G12-N05: original phase identity') + phase = _json(phase_raw, _META_CAP) + _need(type(phase['aggregate_cap_seconds']) is int and phase['aggregate_cap_seconds'] in (600, 2400), + 'G12-N05: original unchanged aggregate cap') + stage = _R + '/stages/g12-reference-custody-v1' + stage_record, stage_raw = _read_file(stage + '/STAGE.json', _META_CAP, 0o444) + jobs_record, jobs_raw = _read_file(stage + '/JOBS.json', _META_CAP, 0o444) + _need(stage_record['sha256'] == selection['stage_sha256'] and + jobs_record['sha256'] == selection['jobs_sha256'], 'G12-N02: independently selected stage/jobs') + stage_data = _json(stage_raw, _META_CAP) + jobs = _json(jobs_raw, _META_CAP) + _need(_exact(jobs, {'g12-reference': {'bootstrap': {'driver': 'integration/g12_reference_adapter_v1.py', + 'provider': 'integration/probe_binding_v3.py'}, 'lanes': 'g12-reference', 'optimized': False}}), + 'G12-N03: exact only-job bootstrap/lanes/no-finite/no-optimization') + _need(stage_data['runner_sha256'] == _GUARD_PIN, 'G12-N02: original runner source') + for relative, row in stage_data['files'].items(): + _need(type(relative) is str and all(x not in ('', '.', '..') for x in relative.split('/')) and + not relative.startswith('/'), 'G12-N02: stage closure relative path') + _fields(row, ('sha256', 'mode')) + _need(type(row['mode']) is int, 'G12-N02: original source mode') + observed, _ = _read_file(stage + '/' + relative, 16777216, row['mode']) + _need(observed['sha256'] == row['sha256'], 'G12-N02: complete staged source closure') + # Exact census rejects undeclared files/directories/symlinks, including an + # alternate staged authority. Walk source paths only; no runtime payloads. + actual = set() + for path, dirs, files in os.walk(stage, followlinks=False): + for name in dirs: + _need(stat.S_ISDIR(os.lstat(path + '/' + name).st_mode), 'G12-N02: stage directory symlink') + for name in files: + full = path + '/' + name + _need(stat.S_ISREG(os.lstat(full).st_mode), 'G12-N02: stage nonregular source') + relative = full[len(stage) + 1:] + if relative != 'STAGE.json': + actual.add(relative) + _need(actual == set(stage_data['files']), 'G12-N02: exact staged closure census') + for name, pin in sources.items(): + if name not in ('engine', 'parent', 'guard', 'cleanup_leaf_origin'): + _need(pin['path'].startswith(stage + '/'), 'G12-N02: selected source outside new stage') + relative = pin['path'][len(stage) + 1:] + _need(stage_data['files'][relative] == {'sha256': pin['sha256'], 'mode': int(pin['mode'], 8)}, + 'G12-N02: selected source/stage binding') + chain = _KnownG12Chain() + for path in (_R + '/runtime/runs/' + label, selection['parent_observation_directory'], + selection['parent_retained_directory']): + parent, name = path.rsplit('/', 1) + fds, rows = _directory_chain(parent) + try: + try: + os.stat(name, dir_fd=fds[-1], follow_symlinks=False) + except FileNotFoundError: + pass + else: + raise RuntimeError('G12-N05: prior output/evidence/custody path exists') + _check_chain(rows) + finally: + _finally_close_known(fds, secondaries) + # Separate from the original guard's science.lock. No contention wait. + lock_path = _R + '/runtime/parent-queue.lock' + parent_fds, parent_rows = _directory_chain(_R + '/runtime') + try: + lease = os.open('parent-queue.lock', os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, dir_fd=parent_fds[-1]) + info = os.fstat(lease) + _need(stat.S_ISREG(info.st_mode) and info.st_nlink == 1, 'G12-N08: parent lease type/link') + lease_identity = _identity(info) + fcntl.flock(lease, fcntl.LOCK_EX | fcntl.LOCK_NB) + _check_chain(parent_rows) + _need(_identity(os.stat('parent-queue.lock', dir_fd=parent_fds[-1], follow_symlinks=False)) == lease_identity, + 'G12-N08: parent lease name identity') + finally: + _finally_close_known(parent_fds, secondaries) + observation = _exclusive_directory(selection['parent_observation_directory']) + current() + + def _g12_launch_once(): + """P03: retain the actual Popen, actual descriptors and generation.""" + nonlocal process, attempted, launch + _need(not attempted and process is None, 'G12-N06: no second launch attempt') + current() + parent_argv, root_argv, producer_argv = _fixed_argv(selection['label'], selection['source_pins']) + for name in ('stdout', 'stderr'): + outer[name] = os.open('outer-' + name + '.txt', + os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, dir_fd=observation[0][-1]) + attempted = True + process = subprocess.Popen(parent_argv, cwd=_R, env=dict(_ENV), stdout=outer['stdout'], + stderr=outer['stderr'], close_fds=True, start_new_session=True) + _need(type(process) is subprocess.Popen and type(process.pid) is int and process.pid > 0, + 'G12-N06: actual Popen object/PID') + row = _proc(process.pid) + _need(row is not None and row['ppid'] == os.getpid() and + row['pgid'] == process.pid and row['sid'] == process.pid, 'G12-N06: actual new guard generation/session') + chain.add(row) + launch = {'parent_pid': parent_identity['pid'], 'parent_start_ticks': parent_identity['start_ticks'], + 'guard_pid': row['pid'], 'guard_start_ticks': row['start_ticks'], + 'guard_pgid': row['pgid'], 'guard_sid': row['sid'], 'parent_guard_argv': parent_argv, + 'guard_root_argv': root_argv, 'adapter_producer_argv': producer_argv, + 'cwd': _R, 'environment': dict(_ENV), 'flags': list(_FLAGS), 'launch_record': None} + raw = _canonical({'schema': 'g12-parent-actual-launch-v1', 'selection_sha256': selection_sha, 'source_selection': selection, + 'launch': {k: v for k, v in launch.items() if k != 'launch_record'}}) + b'\n' + _copy_file(observation, 'LAUNCH.json', raw) + evidence['parent_launch'] = _read_file(selection['parent_observation_directory'] + '/LAUNCH.json', _META_CAP, 0o444) + + def _g12_observe_wait_and_close(): + """P04: actual wait and scoped known-chain closure; no status substitute.""" + nonlocal wait_completed, cleanup, parent_stop + _need(process is not None and type(process) is subprocess.Popen, 'G12-N06: missing retained actual Popen') + while process.poll() is None: + _, children, occupied = chain.observe() + if time.monotonic_ns() >= selection['body_deadline_ns']: + parent_stop = 'selected_complete_body_deadline' + elif sum(row['rss_bytes'] for row in children) > 1073741824: + parent_stop = 'selected_known_chain_rss_cap' + elif resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * 1024 > 1073741824: + parent_stop = 'parent_lifetime_rss_cap' + elif any(os.fstat(descriptor).st_size > _LOG_CAP for descriptor in outer.values()): + parent_stop = 'parent_outer_log_cap' + if parent_stop: + raise RuntimeError('G12-N06: parent STOP: ' + parent_stop) + current() + time.sleep(0.05) + code = process.wait() + wait_completed = True + _need(type(code) is int and code == 0 and type(process.returncode) is int and process.returncode == 0, + 'G12-N06: actual guard wait returncode') + cleanup = chain.finish(process, selection['body_deadline_ns'] + selection['retention_tail_allowance_ns'], False) + for name, descriptor in tuple(outer.items()): + os.fsync(descriptor) + os.close(descriptor) + del outer[name] + cleanup['known_streams_closed'] = not outer + cleanup['lease_identity'] = lease_identity + _need(parent_stop is None and cleanup['known_pidfds_closed'] and not cleanup['io_unknown'], + 'G12-N08: complete known closes') + current() + + def _g12_join_original_guard_evidence(): + """P05: retain complete canonical originals; never reconstruct receipt.""" + nonlocal start, receipt, usage, science_directory, run_directory + run = _R + '/runtime/runs/' + selection['label'] + run_directory = _directory_chain(run) + science_directory = _directory_chain(run + '/science') + cleanup['science_directory_identity'] = _identity(os.fstat(science_directory[0][-1])) + fixed = {'guard_START': ('START.json', _META_CAP), 'guard_receipt': ('receipt.json', _META_CAP), + 'guard_stdout': ('stdout.txt', _LOG_CAP), 'guard_stderr': ('stderr.txt', _LOG_CAP), + 'guard_usage': ('usage.json', 16384)} + for name, (filename, cap) in fixed.items(): + evidence[name] = _read_file(run + '/' + filename, cap) + for name in ('stdout', 'stderr'): + evidence['parent_outer_' + name] = _read_file(selection['parent_observation_directory'] + '/outer-' + name + '.txt', _LOG_CAP) + start = _json(evidence['guard_START'][1], _META_CAP) + receipt = _json(evidence['guard_receipt'][1], _META_CAP) + usage = _json(evidence['guard_usage'][1], 16384) + invocation = {'job': selection['job'], 'label': selection['label'], 'stage_sha256': selection['stage_sha256']} + _validate_guard(start, receipt, usage, evidence['guard_stdout'][1], evidence['guard_stderr'][1], + launch['guard_root_argv'], invocation, selection['source_pins'], selection['phase_pin']['sha256']) + fraction, _ = _read_file('/usr/lib/python3.12/fractions.py', 1048576) + _need(start['fractions_sha256'] == fraction['sha256'], 'G12-N07: original fractions source join') + _need(_exact(_json(evidence['parent_outer_stdout'][1], _LOG_CAP), receipt) and + evidence['parent_outer_stderr'][1] == b'', 'G12-N07: actual outer stdout/empty stderr') + current() + + def _g12_collect_complete_pair(): + """P06: complete original common AND diagnostics, followed by joint recheck.""" + nonlocal common, diagnostic, common_payload + _need(wait_completed and process.returncode == 0 and cleanup is not None and receipt is not None, + 'G12-N10: original successful owner/receipt join must precede pair') + science = _R + '/runtime/runs/' + selection['label'] + '/science' + for name in ('common', 'diagnostics'): + originals[name] = _read_file(science + '/g12-reference.' + name + '.json', _PAIR_CAP) + common, diagnostic, common_payload = _validate_pair(originals['common'][1], originals['diagnostics'][1]) + for name in ('common', 'diagnostics'): + _need(_read_file(originals[name][0]['path'], _PAIR_CAP) == originals[name], 'G12-N11: original joint pair changed') + current() + + def _g12_retain_parent_pair_and_evidence(): + """P07: fresh parent directory only after all selected writers are known closed.""" + nonlocal retained + _need(not _children() and cleanup['known_pidfds_closed'] and cleanup['known_streams_closed'], + 'G12-N08: no retained directory until known selected cleanup') + current() + retained = _exclusive_directory(selection['parent_retained_directory']) + for name in ('common', 'diagnostics'): + filename = 'g12-reference.' + name + '.json' + _copy_file(retained, filename, originals[name][1]) + record, raw = _read_file(selection['parent_retained_directory'] + '/' + filename, _PAIR_CAP, 0o444) + _need(raw == originals[name][1] and record['sha256'] == originals[name][0]['sha256'], 'G12-N14: complete retained pair readback') + retained_records[name] = record + observation_raw = _canonical({'schema': 'g12-known-chain-observations-v1', 'cleanup': cleanup, + 'observations': chain.observations}) + b'\n' + _copy_file(observation, 'owned-observations.json', observation_raw) + evidence['parent_owned_observations'] = _read_file(selection['parent_observation_directory'] + '/owned-observations.json', _META_CAP, 0o444) + costs = _actual_costs(entry_ns, own_start, children_start) + accounting_raw = _canonical(costs) + b'\n' + _copy_file(observation, 'preseal-accounting.json', accounting_raw) + evidence['parent_preseal_accounting'] = _read_file(selection['parent_observation_directory'] + '/preseal-accounting.json', _META_CAP, 0o444) + for name in _MANIFEST_SCHEMA['retained_evidence_exact_keys']: + _copy_file(retained, _EVIDENCE_NAMES[name], evidence[name][1]) + record, raw = _read_file(selection['parent_retained_directory'] + '/' + _EVIDENCE_NAMES[name], + max(len(evidence[name][1]), 1), 0o444) + _need(raw == evidence[name][1], 'G12-N14: raw evidence copy differs') + retained_records[name] = record + # Reserve BOTH metadata names before recording final directory identity. + # Existing FD writes/file chmod do not change parent directory entries. + for name in ('manifest.json', 'publication.json'): + reserved[name] = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, dir_fd=retained[0][-1]) + os.fsync(retained[0][-1]) + current() + + def _g12_seal_once(): + """P08: private actual owner seal; returns only a candidate for later adoption.""" + nonlocal manifest, manifest_record, publication_record, candidate_pin, lease_closed + _need(process is not None and type(process) is subprocess.Popen and process.returncode == 0 and + wait_completed and primary is None and not secondaries and parent_stop is None and not _children() and + not outer and not chain.fds and not chain.unknown, 'G12-N08: actual owner final conjunction') + current() + for name, original in originals.items(): + _need(_read_file(original[0]['path'], _PAIR_CAP) == original, 'G12-N11: original pair final drift') + _need(_read_file(retained_records[name]['path'], _PAIR_CAP, 0o444)[0] == retained_records[name], + 'G12-N14: retained pair final drift') + for name, (record, raw) in source_records.items(): + _need(_read_file(record['path'], max(record['bytes'], 1), record['identity']['full_st_mode'] & 0o7777) == (record, raw), + 'G12-N02: complete selected source drift') + for record, raw in evidence.values(): + _need(_read_file(record['path'], max(record['bytes'], 1), record['identity']['full_st_mode'] & 0o7777) == (record, raw), + 'G12-N07: final complete original raw evidence drift') + for record in (stage_record, jobs_record, phase_record): + _need(_read_file(record['path'], _META_CAP, record['identity']['full_st_mode'] & 0o7777)[0] == record, + 'G12-N02: stage/jobs/phase final identity drift') + os.fchmod(retained[0][-1], 0o500) + # Update exactly our owned mode transition, retaining dev/inode binding. + parent, name, descriptor, old = retained[1][-1] + final_dir_info = os.fstat(descriptor) + _need((final_dir_info.st_dev, final_dir_info.st_ino) == old[:2], 'G12-N14: retained directory owner transition') + retained[1][-1] = (parent, name, descriptor, _directory_key(final_dir_info)) + os.fsync(descriptor) + directory_identity = _identity(final_dir_info) + costs = _actual_costs(entry_ns, own_start, children_start) + account = {'clock': 'monotonic_ns', 'parent_entry_ns': entry_ns, + 'preseal_end_ns': costs['through_ns'], 'parent_preseal_wall_ns': costs['wall_ns'], + 'parent_self_user_seconds': costs['self_user_seconds'], 'parent_self_system_seconds': costs['self_system_seconds'], + 'parent_children_user_seconds': costs['children_user_seconds'], 'parent_children_system_seconds': costs['children_system_seconds'], + 'parent_lifetime_max_rss_kib': costs['lifetime_max_rss_kib'], 'guard_usage': usage, + 'guard_runner_wall_seconds': receipt['runner_wall_seconds'], 'categories': list(_COST_CATEGORIES), + 'complete_tail_accounting_required': True, 'unmeasured_final_tail': None} + launch['launch_record'] = retained_records['parent_launch'] + cleanup['observations_record'] = retained_records['parent_owned_observations'] + manifest = {'schema': 'g12-parent-two-export-custody-v2', + 'invocation': {'stage': selection['stage'], 'job': selection['job'], 'label': selection['label'], + 'stage_sha256': selection['stage_sha256'], 'jobs_sha256': selection['jobs_sha256'], + 'launch_selection_sha256': selection_sha}, + 'selected_sources': selection['source_pins'], 'workload': _MANIFEST_SCHEMA['workload_values'], + 'launch': launch, 'terminal': {'actual_popen_returncode': process.returncode, 'wait_completed': wait_completed, + 'parent_stop': parent_stop, 'primary_error': None, 'secondary_errors': [], 'guard_receipt_missing': False}, + 'guard': {'start': retained_records['guard_START'], 'receipt': retained_records['guard_receipt'], + 'start_fields': start, 'receipt_fields': receipt, 'stdout': retained_records['guard_stdout'], + 'stderr': retained_records['guard_stderr'], 'usage': retained_records['guard_usage']}, + 'cleanup': cleanup, + 'pair': {name: {'original': originals[name][0], 'retained': retained_records[name]} for name in ('common', 'diagnostics')}, + 'retained_evidence': {name: retained_records[name] for name in _MANIFEST_SCHEMA['retained_evidence_exact_keys']}, + 'custody': {'retained_directory': selection['parent_retained_directory'], 'retained_directory_identity': directory_identity, + 'retained_file_mode': '0444', 'created_after_known_cleanup': True, 'source_selection_required': True, + 'known_close_policy': 'Any unknown close rejects publication'}, 'accounting': account, 'scope': _SCOPE} + manifest['pair']['common_payload_sha256'] = common['common_payload_sha256'] + _validate_manifest(manifest, selection['source_pins']['parent']['path'], selection['source_pins']['parent']['sha256']) + raw = _canonical(manifest) + b'\n' + _need(len(raw) <= _META_CAP, 'G12-N14: manifest finite metadata cap') + _write_fd(reserved['manifest.json'], raw) + os.close(reserved['manifest.json']) + del reserved['manifest.json'] + os.fsync(retained[0][-1]) + manifest_record, reread = _read_file(selection['parent_retained_directory'] + '/manifest.json', _META_CAP, 0o444) + _need(reread == raw, 'G12-N14: complete manifest readback') + current() + _need(not _children(), 'G12-N08: unexpected child at final lease close') + fcntl.flock(lease, fcntl.LOCK_UN) + os.close(lease) + lease_closed = True + costs = _actual_costs(entry_ns, own_start, children_start) + publication = {'schema': 'g12-parent-custody-publication-v2', + 'parent_source_sha256': selection['source_pins']['parent']['sha256'], 'launch_selection_sha256': selection_sha, + 'manifest_path': manifest_record['path'], 'manifest_sha256': manifest_record['sha256'], + 'manifest_bytes': manifest_record['bytes'], 'manifest_identity': manifest_record['identity'], + 'retained_pair_sha256': {name: retained_records[name]['sha256'] for name in ('common', 'diagnostics')}, + 'final_pair_recheck_complete': True, 'known_lease_close_completed': lease_closed, + 'primary_error': None, 'secondary_errors': [], 'measured_through_ns': costs['through_ns'], + 'actual_costs_through_ns': costs, 'unmeasured_final_tail': None, + 'complete_cost_qualification': False} + _validate_publication(publication, manifest, manifest_record) + publication_raw = _canonical(publication) + b'\n' + _need(len(publication_raw) <= _META_CAP, 'G12-N15: publication metadata cap') + _write_fd(reserved['publication.json'], publication_raw) + os.close(reserved['publication.json']) + del reserved['publication.json'] + os.fsync(retained[0][-1]) + publication_record, observed = _read_file(selection['parent_retained_directory'] + '/publication.json', _META_CAP, 0o444) + _need(observed == publication_raw and _identity(os.fstat(retained[0][-1])) == directory_identity, + 'G12-N15: final publication readback/directory identity') + current() + # This candidate is not a source selection or completed enclosing invoice. + candidate_pin = (manifest_record['path'], manifest_record['sha256'], manifest_record['bytes'], + _handoff_identity_tuple(manifest_record), selection['source_pins']['parent']['path'], + selection['source_pins']['parent']['sha256'], publication_record['path'], + publication_record['sha256'], publication_record['bytes']) + + def _g12_finish_failure(): + """P09: always preserve actual first failure, known cleanup and partial originals.""" + nonlocal lease_closed + # Every later error is retained separately; no receipt or PASS replacement. + if chain is not None and not chain.closed: + try: + chain.finish(process, selection['body_deadline_ns'] + selection['retention_tail_allowance_ns'], True) + except BaseException as error: + secondaries.append((error, error.__traceback__)) + finally: + if chain.fds: + # No further process-disposal retry follows this point. + # Retained pidfds must still be attempted when observation + # or signalling failed; closed processes remain unproved. + chain.unknown = True + chain.release_known_pidfds(secondaries) + for name, descriptor in tuple(outer.items()): + try: + os.close(descriptor) + del outer[name] + except BaseException as error: + secondaries.append((error, error.__traceback__)) + for name, descriptor in tuple(reserved.items()): + try: + os.close(descriptor) + del reserved[name] + except BaseException as error: + secondaries.append((error, error.__traceback__)) + if lease is not None and not lease_closed: + try: + os.close(lease) + lease_closed = True + except BaseException as error: + secondaries.append((error, error.__traceback__)) + # Failure-tail raw records are never advertised as canonical guard data. + if observation is not None and (primary is not None or secondaries): + try: + failures = {'schema': 'g12-parent-failed-attempt-v1', 'attempted': attempted, + 'actual_returncode': None if process is None else process.returncode, + 'primary': None if primary is None else repr(primary[0]), + 'ordered_secondaries': [repr(item[0]) for item in secondaries], + 'known_cleanup': 'UNKNOWN' if chain is None or not chain.closed else 'KNOWN_SELECTED_CHAIN_ONLY', + 'actual_costs_through_prewrite': _actual_costs(entry_ns, own_start, children_start), + 'enclosing_full_failure_tail_required': True} + _copy_file(observation, 'FAILED-ATTEMPT.json', _canonical(failures) + b'\n') + except BaseException as error: + secondaries.append((error, error.__traceback__)) + for domain in (science_directory, run_directory, retained, observation): + if domain is not None: + for descriptor in reversed(domain[0]): + try: + os.close(descriptor) + except BaseException as error: + secondaries.append((error, error.__traceback__)) + + try: + _g12_preflight_and_claim() + _g12_launch_once() + _g12_observe_wait_and_close() + _g12_join_original_guard_evidence() + _g12_collect_complete_pair() + _g12_retain_parent_pair_and_evidence() + _g12_seal_once() + except BaseException as error: + primary = error, error.__traceback__ + try: + _g12_finish_failure() + except BaseException as error: + # Preserve primary even if a secondary bookkeeping append itself failed. + if primary is None: + primary = error, error.__traceback__ + else: + try: + primary[0].add_note('P09 bookkeeping failure: ' + repr(error)) + except BaseException: + pass + _raise_preserved(primary, secondaries) + _need(candidate_pin is not None and lease_closed and not outer and not reserved, + 'G12-N15: final tail incomplete; manifest remains unselected') + return candidate_pin diff --git a/research/h25-g12-custody-repairs/predecessor/g12_reference_cold_consumer_v2.py.txt b/research/h25-g12-custody-repairs/predecessor/g12_reference_cold_consumer_v2.py.txt new file mode 100644 index 0000000000..a95f079b3c --- /dev/null +++ b/research/h25-g12-custody-repairs/predecessor/g12_reference_cold_consumer_v2.py.txt @@ -0,0 +1,1127 @@ +"""Fixed G12 two-export consumer, v2 checked identity conversion. + +SOURCE ONLY; all selections stay closed. + +The selected cold registered-source executor must inject the actual initial +Root/capability/API before candidate exposure, authenticate these exact source +bytes and this entry, and pass those same objects. Python shapes do not prove +that premise. No result registry, setter, caller success flag or new oracle. +""" +import os +import sys +import stat +import json +import hashlib +import math +from types import FunctionType, CodeType, ModuleType + +G12_REFERENCE_HANDOFF = None +# Future immutable nine-tuple exactly as accepted DESIGN-v1; never a setter. +# Independent selected consumer identity is injected by the fixed original +# cold loader BEFORE exec. It is not stored inside its own source (no hash cycle). +_BOOTSTRAP = (globals().get('bootstrap_root'), globals().get('bootstrap_capability'), + globals().get('bootstrap_api'), globals().get('bootstrap_g12_source_identity')) +_ROOT_PIN = 'f5a2d33f2b4d3651f214156a0e7094c2bb516ce2d5ab7698d18c11f98f35dee0' +_PROVIDER_PIN = '9cbb7368f89e71d1e6cc46db5dc77efed3e03ed2a801c98c88fe316e4d9f3ef2' +_PRODUCER_PIN = 'a346025d5b6e2b26246521c6af6292643a4c2c3286b33ff3996dcf051cd6be26' +_GUARD_PIN = 'bd882e3dadb1b6aeaa63ee824f1a1c58f8ef2546b6840a2bffa46885a184d3eb' +_AUTHORITY_PIN = 'f279ab86fc17c6a517b035f19d56863919cbd8304de4e7d5332457c6159aec10' +_META_CAP = 262144 +_PAIR_CAP = 268435456 +_CHUNK = 65536 +_LOG_CAP = 2097152 +_MISSING = object() +_ID_NAMES = ('dev', 'ino', 'full_st_mode', 'size', 'mtime_ns', 'ctime_ns') +# BEGIN FIXED G12 FILE AND PAIR LEAF + +class _RawG12Errors: + """Fixed error-retention slots; storing raw failures precedes formatting/IO.""" + __slots__ = ('slots', 'count') + def __init__(self): + self.slots = [None] * 4096 + self.count = 0 + def append(self, value): + # All fixed directory/process/stream paths together have fewer than 4096 + # close sites under the 256-component/128-generation source ceilings. + if self.count >= len(self.slots): + raise RuntimeError('G12-N09: fixed raw secondary retention exhausted') + self.slots[self.count] = value + self.count += 1 + def __bool__(self): + return self.count != 0 + def __len__(self): + return self.count + def __getitem__(self, index): + if type(index) is not int or not 0 <= index < self.count: + raise IndexError(index) + return self.slots[index] + def __iter__(self): + for index in range(self.count): + yield self.slots[index] + def __repr__(self): + return repr(tuple(self)) + + +def _need(condition, message): + if not condition: + raise RuntimeError(message) + + +def _exact(value, expected): + if type(value) is not type(expected): + return False + if type(value) in (list, tuple): + return len(value) == len(expected) and all(_exact(a, b) for a, b in zip(value, expected)) + if type(value) is dict: + return set(value) == set(expected) and all(_exact(value[k], expected[k]) for k in expected) + return value == expected + + +def _fields(value, fields): + _need(type(value) is dict and all(type(k) is str for k in value) and + set(value) == set(fields), 'G12-N12: exact field domain differs') + + +def _digest(value): + return type(value) is str and len(value) == 64 and all(c in '0123456789abcdef' for c in value) + + +def _uint(value, positive=False): + _need(type(value) is int and value >= (1 if positive else 0), 'G12-N12: exact integer domain') + + +def _number(value): + _need(type(value) in (int, float) and math.isfinite(value) and value >= 0, + 'G12-N12: finite nonnegative exact number required') + + +def _path(path): + _need(type(path) is str and path.startswith('/') and + all(p not in ('', '.', '..') for p in path.split('/')[1:]), 'G12-N11: absolute canonical path') + return path + + +def _identity(info): + return dict(zip(_ID_NAMES, (info.st_dev, info.st_ino, info.st_mode, info.st_size, + info.st_mtime_ns, info.st_ctime_ns))) + + +def _identity_dict_from_handoff(value): + """Convert the parent's ordered identity tuple into a FileRecord dictionary. + + Field 4 of the accepted nine-tuple is (dev, ino, full_st_mode, size, + mtime_ns, ctime_ns). `_file_record` then requires those values under + string keys. A dictionary is rejected so this boundary stays the only + conversion and cannot be skipped. + """ + _need(type(value) is tuple and len(value) == len(_ID_NAMES), + 'G12-N11: handoff identity must be the ordered six-tuple') + for item in value: + _need(type(item) is int, 'G12-N11: exact stat value') + identity = {name: item for name, item in zip(_ID_NAMES, value)} + _fields(identity, _ID_NAMES) + _uint(identity['dev']) + _uint(identity['ino'], True) + _need(stat.S_ISREG(identity['full_st_mode']), 'G12-N11: file identity type') + return identity + + +def _directory_key(info): + return info.st_dev, info.st_ino, info.st_mode + + +def _directory_chain(path): + """Held no-follow chain; no later absolute path silently changes its owner.""" + _path(path) + _need(len(path.split('/')) <= 257, 'G12-N11: finite directory-component bound') + fds, rows = [], [] + primary = None + try: + fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC) + fds.append(fd) + for part in path.split('/')[1:]: + before = os.stat(part, dir_fd=fd, follow_symlinks=False) + _need(stat.S_ISDIR(before.st_mode), 'G12-N11: directory component type') + child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, + dir_fd=fd) + fds.append(child) + opened = os.fstat(child) + _need(_directory_key(before) == _directory_key(opened), 'G12-N11: directory replaced') + rows.append((fd, part, child, _directory_key(opened))) + fd = child + return fds, rows + except BaseException as error: + primary = (error, error.__traceback__) + secondary = _RawG12Errors() + for descriptor in reversed(fds): + try: + os.close(descriptor) + except BaseException as error: + secondary.append((error, error.__traceback__)) + _raise_preserved(primary, secondary) + + +def _check_chain(rows): + for parent, name, descriptor, key in rows: + _need(_directory_key(os.fstat(descriptor)) == key == + _directory_key(os.stat(name, dir_fd=parent, follow_symlinks=False)), + 'G12-N11: directory binding changed') + + +def _raise_preserved(primary, secondaries): + """Never replace first raw failure if evidence formatting or retention fails.""" + if primary is not None: + error, traceback = primary + try: + error.add_note('G12 ordered secondary failures: ' + repr(secondaries)) + except BaseException: + pass + raise error.with_traceback(traceback) + if secondaries: + error, traceback = secondaries[0][:2] + raise error.with_traceback(traceback) + + +def _read_file(path, cap, mode=None): + _path(path) + parent, name = path.rsplit('/', 1) + fds, rows = _directory_chain(parent) + descriptor, primary, secondary, result = None, None, _RawG12Errors(), None + try: + before = os.stat(name, dir_fd=fds[-1], follow_symlinks=False) + _need(stat.S_ISREG(before.st_mode) and before.st_nlink == 1 and + 0 <= before.st_size <= cap and (mode is None or before.st_mode == stat.S_IFREG | mode), + 'G12-N11: regular-file size/mode/link domain') + descriptor = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, + dir_fd=fds[-1]) + opened = os.fstat(descriptor) + _need(_identity(before) == _identity(opened) and opened.st_nlink == 1, + 'G12-N11: file changed on open') + count, blocks, hasher = 0, [], hashlib.sha256() + while count < opened.st_size: + block = os.read(descriptor, min(_CHUNK, opened.st_size - count)) + _need(bool(block), 'G12-N11: short file read') + count += len(block) + hasher.update(block) + blocks.append(block) + _need(os.read(descriptor, 1) == b'', 'G12-N11: file grew') + after = os.fstat(descriptor) + ending = os.stat(name, dir_fd=fds[-1], follow_symlinks=False) + _need(_identity(before) == _identity(after) == _identity(ending) and + after.st_nlink == ending.st_nlink == 1, 'G12-N11: full file identity changed') + _check_chain(rows) + result = ({'path': path, 'sha256': hasher.hexdigest(), 'bytes': count, + 'identity': _identity(after), 'nlink': 1}, b''.join(blocks)) + except BaseException as error: + primary = (error, error.__traceback__) + for fd in ([descriptor] if descriptor is not None else []) + list(reversed(fds)): + try: + os.close(fd) + except BaseException as error: + secondary.append((error, error.__traceback__)) + _raise_preserved(primary, secondary) + return result + + +def _file_record(value): + _fields(value, ('path', 'sha256', 'bytes', 'identity', 'nlink')) + _path(value['path']) + _need(_digest(value['sha256']) and type(value['nlink']) is int and value['nlink'] == 1, + 'G12-N11: file digest/link record') + _uint(value['bytes']) + _fields(value['identity'], _ID_NAMES) + for key in _ID_NAMES: + _need(type(value['identity'][key]) is int, 'G12-N11: exact stat value') + _uint(value['identity']['dev']) + _uint(value['identity']['ino'], True) + _need(stat.S_ISREG(value['identity']['full_st_mode']) and + value['identity']['size'] == value['bytes'], 'G12-N11: file identity size/type') + + +def _root_read(root, api, record, cap): + _file_record(record) + _need(api[0]() == _ROOT_PIN, 'G12-N04: actual Root currentness') + before = root._hash_regular(record['path'], cap, False) + observed, raw = _read_file(record['path'], cap, 0o444) + after = root._hash_regular(record['path'], cap, False) + _need(_exact(observed, record) and before[:2] == after[:2] == + (record['sha256'], record['bytes']), 'G12-N17: Root/read/full-identity join') + _need(api[0]() == _ROOT_PIN, 'G12-N04: actual Root changed after file read') + return raw + + +def _pairs(items): + result = {} + for key, value in items: + _need(type(key) is str and key not in result, 'G12-N12: duplicate JSON key') + result[key] = value + return result + + +def _nonfinite(value): + raise ValueError('G12-N12: nonfinite JSON token: ' + value) + + +def _canonical(value): + return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True, + allow_nan=False).encode('ascii') + + +def _json(raw, cap, canonical=False, newline=False): + _need(type(raw) is bytes and len(raw) <= cap, 'G12-N12: raw JSON bound') + # Scan lexical nesting before json.loads recursion or object materialization. + depth, quoted, escaped = 0, False, False + for char in raw: + if quoted: + if escaped: + escaped = False + elif char == 92: + escaped = True + elif char == 34: + quoted = False + elif char == 34: + quoted = True + elif char in (91, 123): + depth += 1 + _need(depth <= 256, 'G12-N12: JSON depth limit') + elif char in (93, 125): + depth -= 1 + _need(depth >= 0, 'G12-N12: JSON nesting') + _need(depth == 0 and not quoted, 'G12-N12: incomplete JSON') + value = json.loads(raw.decode('utf-8'), object_pairs_hook=_pairs, parse_constant=_nonfinite) + pending, count = [(value, 0)], 0 + while pending: + item, depth = pending.pop() + count += 1 + _need(count <= cap and depth <= 256, 'G12-N12: JSON node/depth limit') + if type(item) is dict: + pending.extend((x, depth + 1) for pair in item.items() for x in pair) + elif type(item) is list: + pending.extend((x, depth + 1) for x in item) + elif type(item) is str: + _need(len(item) <= cap, 'G12-N12: JSON string limit') + elif type(item) is float: + _need(math.isfinite(item), 'G12-N12: overflowed JSON number') + else: + _need(item is None or type(item) in (bool, int), 'G12-N12: JSON primitive') + if canonical: + _need(raw == _canonical(value) + (b'\n' if newline else b''), 'G12-N12: canonical JSON bytes') + return value + + +def _hex(value, cap): + _need(type(value) is str and len(value) <= cap and len(value) % 2 == 0 and + all(c in '0123456789abcdef' for c in value), 'G12-N12: complete lowercase hex') + return bytes.fromhex(value) + + +def _decimal(value, positive=False): + _need(type(value) is str and bool(value), 'G12-N12: integer tag text') + digits = value[1:] if value.startswith('-') else value + _need(bool(digits) and all(c in '0123456789' for c in digits) and + (digits == '0' or digits[0] != '0') and value != '-0' and + (not positive or (not value.startswith('-') and value != '0')), 'G12-N12: canonical integer') + + +def _tagged(raw, cap): + value = _json(raw, cap, True) + pending = [(value, 0)] + count = 0 + while pending: + node, depth = pending.pop() + count += 1 + _need(count <= cap and depth <= 256 and type(node) is list and len(node) >= 1 and + type(node[0]) is str, 'G12-N12: tagged primitive bound/shape') + tag = node[0] + if tag == 'None': + _need(len(node) == 1, 'G12-N12: None arity') + continue + _need(len(node) == (3 if tag == 'Fraction' else 2), 'G12-N12: primitive arity') + arg = node[1] + if tag == 'bool': + _need(type(arg) is bool, 'G12-N12: bool tag') + elif tag == 'int': + _decimal(arg) + elif tag == 'Fraction': + _decimal(arg) + _decimal(node[2], True) + elif tag == 'str': + _need(type(arg) is str, 'G12-N12: string tag') + elif tag == 'bytes': + _hex(arg, cap) + elif tag == 'float': + _need(type(arg) is str and float.fromhex(arg).hex() == arg, 'G12-N12: float.hex domain') + elif tag in ('tuple', 'list'): + _need(type(arg) is list, 'G12-N12: sequence tag') + pending.extend((item, depth + 1) for item in arg) + elif tag == 'dict': + _need(type(arg) is list, 'G12-N12: ordered dict tag') + for pair in arg: + _need(type(pair) is list and len(pair) == 2, 'G12-N12: dict pair') + pending.extend((item, depth + 1) for item in pair) + else: + raise ValueError('G12-N12: unknown primitive tag') + return value + + +def _rank_events(encoded): + value = _tagged(_hex(encoded, _PAIR_CAP), _PAIR_CAP) + _need(value[0] == 'tuple', 'G12-N12: rank tuple') + for event in value[1]: + _need(event[0] == 'tuple' and len(event[1]) == 2 and event[1][0][0] == 'tuple' and + all(x[0] == 'int' for x in event[1][0][1]) and event[1][1][0] == 'int', + 'G12-N12: rank-event grammar') + return len(value[1]) + + +def _validate_pair(common_raw, diagnostic_raw): + common = _json(common_raw, _PAIR_CAP, True, True) + diagnostic = _json(diagnostic_raw, _PAIR_CAP, True, True) + spec = _PAIR_SCHEMA + _fields(common, spec['common_exact_fields']) + _fields(diagnostic, spec['diagnostic_exact_fields']) + for key, expected in spec['common_constants'].items(): + _need(_exact(common[key], expected), 'G12-N13: original common source/workload binding') + for key, expected in spec['diagnostic_constants'].items(): + _need(_exact(diagnostic[key], expected), 'G12-N13: diagnostic source/role binding') + _need(type(common['literal_original_value']) is bool, 'G12-N12: observed literal exact bool') + _uint(common['remaining_original_case_count'], True) + payload = _hex(common['common_payload_hex'], _PAIR_CAP) + _need(_digest(common['common_payload_sha256']) and + hashlib.sha256(payload).hexdigest() == common['common_payload_sha256'] == + diagnostic['common_payload_sha256'], 'G12-N13: complete common digest join') + tagged = _tagged(payload, _PAIR_CAP) + _need(tagged[0] == 'tuple' and len(tagged[1]) == 10, 'G12-N13: common tuple arity') + prefix = [['str', 'g12-original-remainder-common-v1'], + ['tuple', [['str', p] for p in spec['common_constants']['original_scientific_pins']]], + ['int', '25'], ['tuple', [['int', '0'], ['int', '2'], ['int', '1']]]] + _need(_exact(tagged[1][:4], prefix), 'G12-N13: common inner source/workload prefix') + suffix = ['tuple', [['str', name] for name in ('verify_role_frames', 'full_log_integer_bounds', + 'original_upstream_verify_sources', 'original_serializable', 'complete_original_cli')]] + _need(_exact(tagged[1][-1], suffix), 'G12-N13: original suffix phase order') + for key in ('prefix_end', 'suffix_start', 'cli_end'): + row = diagnostic[key] + _fields(row, spec['diagnostic_snapshot_exact_fields']) + _uint(row['rank_event_count']) + _need(_rank_events(row['ordered_rank_events_hex']) == row['rank_event_count'] and + row['native_binding'] is None and row['cache_binding'] is None, + 'G12-N12: original diagnostic rank/binding domain') + receipt = row['complement_receipt'] + _fields(receipt, spec['complement_receipt_exact_fields']) + _uint(receipt['calls']) + _uint(receipt['canonical_stream_bytes']) + _need(_digest(receipt['sha256']) and receipt['schema'] == + 'v2-jsonl:call,us,vs,result(type=list+values or type=None); ordered exact integer vectors', 'G12-N12: complement receipt') + _rank_events(diagnostic['ordered_rank_suffix_hex']) + _fields(diagnostic['phases'], spec['phase_exact_names']) + for row in diagnostic['phases'].values(): + _fields(row, ('calls', 'wall_seconds', 'cpu_seconds_with_children')) + _need(type(row['calls']) is int and row['calls'] == 1, 'G12-N12: phase calls') + _number(row['wall_seconds']) + _number(row['cpu_seconds_with_children']) + return common, diagnostic, payload + + +def _source_pin(value): + _fields(value, ('path', 'sha256', 'bytes', 'mode')) + _path(value['path']) + _uint(value['bytes']) + _need(_digest(value['sha256']) and type(value['mode']) is str and len(value['mode']) == 4 and + all(c in '01234567' for c in value['mode']), 'G12-N02: exact source pin') + + +def _validate_guard(start, receipt, usage, stdout, stderr, root_argv, invocation, source_pins, phase_sha): + _fields(start, _GUARD_SCHEMA['START_exact_fields']) + _fields(receipt, _GUARD_SCHEMA['receipt_exact_fields']) + _fields(usage, ('user_seconds', 'system_seconds', 'kernel_max_rss_kib', 'exit')) + for key in start: + _need(_exact(start[key], receipt[key]), 'G12-N07: original START/receipt field join') + for key, expected in _GUARD_SCHEMA['required_values'].items(): + _need(_exact(receipt[key], expected), 'G12-N07: original guard success predicate') + for key in ('job', 'label', 'stage_sha256'): + _need(_exact(start[key], invocation[key]), 'G12-N07: selected invocation mismatch') + expected_launch = {'contract': 'trusted-clean-nosite-safe-path-fixedseed-v1', + 'no_site': 1, 'no_user_site': 1, 'safe_path': True, 'ignore_environment': 0, + 'isolated': 0, 'hash_seed_environment': '0', 'hash_randomization': 0, + 'initial_sys_path': ['/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload'], + 'environment': dict(_ENV), + 'trust_boundary': 'Authenticated parent launcher, OS, interpreter and system stdlib before this module; no Python self-authentication claim'} + _need(_exact(start['parent_launch'], expected_launch), 'G12-N07: exact original clean parent launch') + _need(_exact(start['command'], root_argv) and start['runner_sha256'] == _GUARD_PIN and + start['budget_phase_sha256'] == phase_sha and _digest(start['fractions_sha256']), + 'G12-N07: selected command/source/phase binding') + _need(type(start['phase_cap_seconds']) is int and start['phase_cap_seconds'] in (600, 2400), + 'G12-N05: original aggregate cap') + _number(start['spent_before_seconds']) + _need(start['spent_before_seconds'] < start['phase_cap_seconds'], 'G12-N05: consumed budget') + for key in ('wall_seconds', 'runner_wall_seconds', 'runner_user_seconds', 'runner_system_seconds', + 'runner_lifetime_max_rss_kib', 'sampled_process_group_rss_bytes'): + _number(receipt[key]) + limit = min(180, start['phase_cap_seconds'] - start['spent_before_seconds']) + _need(receipt['wall_seconds'] <= limit and receipt['runner_wall_seconds'] <= limit and + receipt['runner_lifetime_max_rss_kib'] * 1024 <= 1073741824 and + receipt['sampled_process_group_rss_bytes'] <= 1073741824, + 'G12-N07: original guard resource caps') + for key in ('user_seconds', 'system_seconds', 'kernel_max_rss_kib'): + _number(usage[key]) + _need(type(usage['exit']) is int and usage['exit'] == 0 and _exact(usage, receipt['usage']), + 'G12-N07: complete original usage join') + for name, raw in (('stdout', stdout), ('stderr', stderr)): + _need(len(raw) <= _LOG_CAP and receipt[name + '_bytes'] == len(raw) and + type(receipt[name + '_bytes']) is int and receipt[name + '_final_bytes'] == len(raw) and + type(receipt[name + '_final_bytes']) is int and + receipt[name + '_sha256'] == hashlib.sha256(raw).hexdigest(), 'G12-N07: complete raw log join') + _need(stderr == b'' and type(receipt['python']) is str and type(receipt['platform']) is str, + 'G12-N07: original stderr/platform fields') + + +def _capture_graph(namespace): + """Capture the fixed own/JSON function graph before candidate exposure.""" + modules = (json, json.decoder, json.encoder, json.scanner, hashlib, os, stat, math) + tuple( + namespace[name] for name in ('subprocess', 'fcntl', 'signal', 'resource', 'time') if name in namespace) + namespaces = [namespace] + [module.__dict__ for module in modules] + namespaces.extend((json._default_decoder.__dict__, json._default_encoder.__dict__)) + records, members, seen = [], [], set() + for mapping in namespaces: + members.append((mapping, tuple(mapping.items()))) + for value in mapping.values(): + candidates = [value] + if type(value) is type: + candidates.extend(value.__dict__.values()) + if value.__module__ in (__name__, 'json.decoder', 'json.encoder', 'subprocess'): + members.append((value.__dict__, tuple(value.__dict__.items()))) + for function in candidates: + if type(function) is not FunctionType or id(function) in seen: + continue + seen.add(id(function)) + records.append((function, function.__code__, function.__globals__, function.__builtins__, + function.__defaults__, function.__kwdefaults__, function.__closure__, + tuple(function.__dict__.items()), + () if function.__kwdefaults__ is None else tuple(function.__kwdefaults__.items()), + () if function.__closure__ is None else tuple((c, c.cell_contents) for c in function.__closure__))) + data = tuple((name, _canonical(namespace[name])) for name in + ('_PAIR_SCHEMA', '_MANIFEST_SCHEMA', '_GUARD_SCHEMA', '_PUBLICATION_SCHEMA', + '_ENGINE_PINS', '_OTHER_SOURCE_PINS', '_ENV', '_EVIDENCE_NAMES') if name in namespace) + return tuple(records), tuple(members), data + + +def _current_graph(graph): + records, members, data = graph + for mapping, rows in members: + # The capture itself is assigned once after this snapshot. + expected = dict(rows) + for name, value in rows: + _need(mapping.get(name, _MISSING) is value, 'G12-N04: captured namespace member changed: ' + name) + extra = set(mapping) - set(expected) + _need(not extra or mapping is globals() and extra == {'_INITIAL_GRAPH'}, + 'G12-N04: captured namespace census changed') + for name, expected in data: + _need(_canonical(globals()[name]) == expected, 'G12-N04: source-owned schema constant changed') + for f, code, namespace, builtin, defaults, kw, cells, attrs, kws, contents in records: + _need(f.__code__ is code and f.__globals__ is namespace and f.__builtins__ is builtin and + f.__defaults__ is defaults and f.__kwdefaults__ is kw and f.__closure__ is cells and + len(f.__dict__) == len(attrs), 'G12-N04: captured function graph changed') + for name, value in attrs: + _need(f.__dict__.get(name, _MISSING) is value, 'G12-N04: function attributes changed') + if kw is not None: + _need(len(kw) == len(kws), 'G12-N04: keyword-default census changed') + for name, value in kws: + _need(kw.get(name, _MISSING) is value, 'G12-N04: keyword defaults changed') + for cell, value in contents: + _need(cell.cell_contents is value, 'G12-N04: captured closure changed') +# END FIXED G12 FILE AND PAIR LEAF + +_PAIR_SCHEMA = {'common_constants': {'authority_source_sha256': 'f279ab86fc17c6a517b035f19d56863919cbd8304de4e7d5332457c6159aec10', + 'extra_target': [0, 2, 1], + 'h': 25, + 'literal_original_type': 'bool', + 'original_driver_sha256': '0d976d2eb6b845f20d4a3396591a806f966688b88693cd6a5f8a0c9e48925e36', + 'original_scientific_pins': ['d623617f7c5cb3189580883a8ab30c0bd3832688ae3f1f0c1f881bbbbff8e0c1', + '0da395e67ac04fa213494e71012c1b19b544596d34cdce5a3b172b1fb6af5f1b', + '88bba3caf5975f30fa7abceaea9454110cf3b069233e8241a2ca13d1dff171a7', + 'adc7f1241b42e322a6451854ab7e4b4c146bf78a'], + 'producer_role': 'independent-original-uncached', + 'schema': 'g12-independent-original-reference-envelope-v1', + 'scope': 'Actual original N22 literal and P07 common remainder observations only; ' + 'no original PROFILE_ANCHOR_PASS, FULL_PASS, native qualification or G12 ' + 'approval.', + 'selected_driver_sha256': 'a346025d5b6e2b26246521c6af6292643a4c2c3286b33ff3996dcf051cd6be26'}, + 'common_exact_fields': ['schema', + 'producer_role', + 'selected_driver_sha256', + 'original_driver_sha256', + 'authority_source_sha256', + 'original_scientific_pins', + 'h', + 'extra_target', + 'literal_original_type', + 'literal_original_value', + 'remaining_original_case_count', + 'common_payload_sha256', + 'common_payload_hex', + 'scope'], + 'complement_receipt_exact_fields': ['calls', 'canonical_stream_bytes', 'sha256', 'schema'], + 'diagnostic_constants': {'complement_suffix_limit': 'Only cumulative original start/end receipts; no ' + 'digest subtraction or suffix-stream claim.', + 'completion': 'Exact source-owned intentional marker followed by original ' + 'finally, exact observer restoration, both cold2 checks and ' + 'original source/output custody.', + 'producer_role': 'independent-original-uncached', + 'schema': 'g12-independent-original-reference-diagnostics-v1', + 'selected_driver_sha256': 'a346025d5b6e2b26246521c6af6292643a4c2c3286b33ff3996dcf051cd6be26'}, + 'diagnostic_exact_fields': ['schema', + 'producer_role', + 'selected_driver_sha256', + 'common_payload_sha256', + 'prefix_end', + 'suffix_start', + 'cli_end', + 'ordered_rank_suffix_hex', + 'complement_suffix_limit', + 'phases', + 'completion'], + 'diagnostic_snapshot_exact_fields': ['rank_event_count', + 'ordered_rank_events_hex', + 'complement_receipt', + 'native_binding', + 'cache_binding'], + 'phase_exact_names': ['input_custody', + 'engine_custody', + 'fresh_root_copy', + 'fresh_engine_copy', + 'cold_engine_import', + 'cold_complex_module_load', + 'cold_certify_import', + 'cold_prepare_import', + 'side_construction', + 'checks_initialization', + 'compile_roles', + 'verify_map', + 'verify_labels', + 'verify_role_frames', + 'original_upstream_verify_sources', + 'full_log_integer_bounds', + 'original_serializable', + 'complete_original_cli']} + +_MANIFEST_SCHEMA = {'accounting_exact_fields': ['clock', + 'parent_entry_ns', + 'preseal_end_ns', + 'parent_preseal_wall_ns', + 'parent_self_user_seconds', + 'parent_self_system_seconds', + 'parent_children_user_seconds', + 'parent_children_system_seconds', + 'parent_lifetime_max_rss_kib', + 'guard_usage', + 'guard_runner_wall_seconds', + 'categories', + 'complete_tail_accounting_required', + 'unmeasured_final_tail'], + 'cleanup_exact_fields': ['operating_premises', + 'owned_generations', + 'observed_groups', + 'remaining', + 'current_children', + 'known_streams_closed', + 'known_pidfds_closed', + 'io_unknown', + 'lease_identity', + 'science_directory_identity', + 'observations_record'], + 'custody_exact_fields': ['retained_directory', + 'retained_directory_identity', + 'retained_file_mode', + 'created_after_known_cleanup', + 'source_selection_required', + 'known_close_policy'], + 'exact_top_level_fields': ['schema', + 'invocation', + 'selected_sources', + 'workload', + 'launch', + 'terminal', + 'guard', + 'cleanup', + 'pair', + 'retained_evidence', + 'custody', + 'accounting', + 'scope'], + 'guard_exact_fields': ['start', + 'receipt', + 'start_fields', + 'receipt_fields', + 'stdout', + 'stderr', + 'usage'], + 'invocation_exact_fields': ['stage', + 'job', + 'label', + 'stage_sha256', + 'jobs_sha256', + 'launch_selection_sha256'], + 'launch_exact_fields': ['parent_pid', + 'parent_start_ticks', + 'guard_pid', + 'guard_start_ticks', + 'guard_pgid', + 'guard_sid', + 'parent_guard_argv', + 'guard_root_argv', + 'adapter_producer_argv', + 'cwd', + 'environment', + 'flags', + 'launch_record'], + 'pair_exact_fields': ['common', 'diagnostics', 'common_payload_sha256'], + 'retained_evidence_exact_keys': ['guard_START', + 'guard_receipt', + 'guard_stdout', + 'guard_stderr', + 'guard_usage', + 'parent_launch', + 'parent_outer_stdout', + 'parent_outer_stderr', + 'parent_owned_observations', + 'parent_preseal_accounting'], + 'schema_literal': 'g12-parent-two-export-custody-v2', + 'selected_sources_exact_fields': ['parent', + 'guard', + 'root', + 'provider', + 'adapter', + 'producer', + 'authority', + 'source_pins', + 'reference', + 'engine', + 'runtime_profile', + 'cleanup_leaf_origin'], + 'terminal_exact_fields': ['actual_popen_returncode', + 'wait_completed', + 'parent_stop', + 'primary_error', + 'secondary_errors', + 'guard_receipt_missing'], + 'workload_exact_fields': ['role', + 'h', + 'extra_target', + 'mode', + 'anchor', + 'optimize', + 'original_scientific_pins'], + 'workload_values': {'anchor': None, + 'extra_target': [0, 2, 1], + 'h': 25, + 'mode': 'profile', + 'optimize': 0, + 'original_scientific_pins': ['d623617f7c5cb3189580883a8ab30c0bd3832688ae3f1f0c1f881bbbbff8e0c1', + '0da395e67ac04fa213494e71012c1b19b544596d34cdce5a3b172b1fb6af5f1b', + '88bba3caf5975f30fa7abceaea9454110cf3b069233e8241a2ca13d1dff171a7', + 'adc7f1241b42e322a6451854ab7e4b4c146bf78a'], + 'role': 'independent-original-uncached'}} + +_GUARD_SCHEMA = {'START_exact_fields': ['command', + 'parent_launch', + 'stage_sha256', + 'runner_sha256', + 'fractions_sha256', + 'budget_phase_sha256', + 'spent_before_seconds', + 'phase_cap_seconds', + 'job', + 'label'], + 'receipt_exact_fields': ['command', + 'parent_launch', + 'stage_sha256', + 'runner_sha256', + 'fractions_sha256', + 'budget_phase_sha256', + 'spent_before_seconds', + 'phase_cap_seconds', + 'job', + 'label', + 'exit', + 'wall_seconds', + 'usage', + 'termination', + 'sampled_process_group_rss_bytes', + 'source_bytes_and_modes_unchanged', + 'stdout_sha256', + 'stdout_bytes', + 'stderr_sha256', + 'stderr_bytes', + 'stdout_final_bytes', + 'stderr_final_bytes', + 'retained_log_bytes_stable', + 'output_cap_observed_at', + 'log_read_chunk_bytes', + 'runner_wall_seconds', + 'runner_user_seconds', + 'runner_system_seconds', + 'runner_lifetime_max_rss_kib', + 'python', + 'platform', + 'status'], + 'required_values': {'exit': 0, + 'log_read_chunk_bytes': 65536, + 'output_cap_observed_at': None, + 'retained_log_bytes_stable': True, + 'source_bytes_and_modes_unchanged': True, + 'status': 'PASS', + 'stderr_bytes': 0, + 'stderr_final_bytes': 0, + 'termination': None}} + +_PUBLICATION_SCHEMA = {'exact_fields': ['schema', + 'parent_source_sha256', + 'launch_selection_sha256', + 'manifest_path', + 'manifest_sha256', + 'manifest_bytes', + 'manifest_identity', + 'retained_pair_sha256', + 'final_pair_recheck_complete', + 'known_lease_close_completed', + 'primary_error', + 'secondary_errors', + 'measured_through_ns', + 'actual_costs_through_ns', + 'unmeasured_final_tail', + 'complete_cost_qualification'], + 'schema_literal': 'g12-parent-custody-publication-v2'} + +_COST_CATEGORIES = ('source/stage/plan/authentication and dependency preflight', 'parent invocation setup and known lease operations', 'adapter bootstrap source read/hash/compile/exec and argv/module alias custody/restoration', 'entire independent uncached reference including fresh copies/engine imports/original CLI/trace capture/original checks/finally/restoration/cold2', 'guard launch/time/monitoring/STOP/final original source inventory/usage/raw-log hashing/receipt', 'actual parent wait and known descendant/group/FD cleanup', 'canonical receipt and START joins plus all complete raw evidence retention', 'both exports full reads/hashes/JSON/schema/payload decode/crosslinks and repeated pair checks', 'new parent copies/write/fsync/chmod/close/directory sync/readback', 'manifest schema/write/hash/fsync/close/readback and source-selection publication tail', 'parent failure/secondary-error retention and necessary cleanup after deadline', 'cold consumer complete manifest/pair/publication read/hash/parse/decode/recheck and all retained alias lifetimes') + + +def _validate_manifest(manifest, parent_path, parent_sha): + spec = _MANIFEST_SCHEMA + _fields(manifest, spec['exact_top_level_fields']) + _need(manifest['schema'] == spec['schema_literal'], 'G12-N12: custody schema') + for name in ('invocation', 'selected_sources', 'workload', 'launch', 'terminal', 'guard', + 'cleanup', 'pair', 'custody', 'accounting'): + _fields(manifest[name], spec[name + '_exact_fields']) + _fields(manifest['retained_evidence'], spec['retained_evidence_exact_keys']) + _need(_exact(manifest['workload'], spec['workload_values']), 'G12-N13: fixed workload') + invocation = manifest['invocation'] + _need(invocation['stage'] == 'g12-reference-custody-v1' and invocation['job'] == 'g12-reference' and + type(invocation['label']) is str and bool(invocation['label']) and + all(c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_' for c in invocation['label']), + 'G12-N13: fixed invocation role') + for name in ('stage_sha256', 'jobs_sha256', 'launch_selection_sha256'): + _need(_digest(invocation[name]), 'G12-N12: invocation digest') + sources = manifest['selected_sources'] + for name, pin in sources.items(): + if name != 'engine': + _source_pin(pin) + for name, expected in (('guard', _GUARD_PIN), ('root', _ROOT_PIN), ('provider', _PROVIDER_PIN), + ('producer', _PRODUCER_PIN), ('authority', _AUTHORITY_PIN)): + _need(sources[name]['sha256'] == expected and sources[name]['mode'] == '0444', + 'G12-N02: selected original source mismatch') + _need(sources['producer']['bytes'] == 70246 and sources['parent']['path'] == parent_path and + sources['parent']['sha256'] == parent_sha, 'G12-N02: selected producer/parent identity') + _need(_exact(sources['engine'], _ENGINE_PINS), 'G12-N02: exact original engine source pins') + for name, expected in _OTHER_SOURCE_PINS.items(): + _need(sources[name]['sha256'] == expected, 'G12-N02: selected original dependency mismatch') + terminal = {'actual_popen_returncode': 0, 'wait_completed': True, 'parent_stop': None, + 'primary_error': None, 'secondary_errors': [], 'guard_receipt_missing': False} + _need(_exact(manifest['terminal'], terminal), 'G12-N06: authenticated terminal data rejects') + cleanup = manifest['cleanup'] + _need(_exact(cleanup['remaining'], []) and _exact(cleanup['current_children'], []) and + cleanup['known_streams_closed'] is True and cleanup['known_pidfds_closed'] is True and + cleanup['io_unknown'] is False and type(cleanup['owned_generations']) is list and + bool(cleanup['owned_generations']) and _exact(cleanup['operating_premises'], _OPERATING_PREMISES), + 'G12-N08: known selected chain custody rejects') + for name in ('parent_pid', 'parent_start_ticks', 'guard_pid', 'guard_start_ticks', 'guard_pgid', 'guard_sid'): + _uint(manifest['launch'][name], True) + label = invocation['label'] + stage = _R + '/stages/g12-reference-custody-v1' + science = _R + '/runtime/runs/' + label + '/science' + parent_argv, root_argv, producer_argv = _fixed_argv(label, sources) + launch = manifest['launch'] + _need(_exact(launch['parent_guard_argv'], parent_argv) and _exact(launch['guard_root_argv'], root_argv) and + _exact(launch['adapter_producer_argv'], producer_argv) and launch['cwd'] == _R and + _exact(launch['environment'], _ENV) and _exact(launch['flags'], list(_FLAGS)), + 'G12-N03: exact fixed launch/adapter argv') + retained = _R + '/runtime/g12-reference-parent-custody-v1/' + label + custody = manifest['custody'] + _need(custody['retained_directory'] == retained and custody['retained_file_mode'] == '0444' and + custody['created_after_known_cleanup'] is True and custody['source_selection_required'] is True and + custody['known_close_policy'] == 'Any unknown close rejects publication', 'G12-N14: custody ownership') + _fields(custody['retained_directory_identity'], _ID_NAMES) + _need(custody['retained_directory_identity']['full_st_mode'] == stat.S_IFDIR | 0o500, + 'G12-N14: final retained directory mode') + for name in ('common', 'diagnostics'): + pair = manifest['pair'][name] + _fields(pair, ('original', 'retained')) + _file_record(pair['original']) + _file_record(pair['retained']) + filename = 'g12-reference.' + name + '.json' + _need(pair['original']['path'] == science + '/' + filename and + pair['retained']['path'] == retained + '/' + filename and + pair['original']['sha256'] == pair['retained']['sha256'] and + pair['original']['bytes'] == pair['retained']['bytes'] and + pair['retained']['identity']['full_st_mode'] == stat.S_IFREG | 0o444, + 'G12-N13: original/retained complete pair join') + _need(_digest(manifest['pair']['common_payload_sha256']), 'G12-N13: payload pin') + for name, record in manifest['retained_evidence'].items(): + _file_record(record) + _need(record['path'] == retained + '/' + _EVIDENCE_NAMES[name] and + record['identity']['full_st_mode'] == stat.S_IFREG | 0o444, + 'G12-N14: retained raw evidence path/mode') + for name, evidence_name in (('start', 'guard_START'), ('receipt', 'guard_receipt'), + ('stdout', 'guard_stdout'), ('stderr', 'guard_stderr'), ('usage', 'guard_usage')): + _need(_exact(manifest['guard'][name], manifest['retained_evidence'][evidence_name]), + 'G12-N07: guard retained record join') + _need(_exact(launch['launch_record'], manifest['retained_evidence']['parent_launch']) and + _exact(cleanup['observations_record'], manifest['retained_evidence']['parent_owned_observations']), + 'G12-N08: parent observation record join') + account = manifest['accounting'] + _need(account['clock'] == 'monotonic_ns' and account['complete_tail_accounting_required'] is True and + _exact(account['categories'], list(_COST_CATEGORIES)), 'G12-N15: full cost categories/tail') + for name in ('parent_entry_ns', 'preseal_end_ns', 'parent_preseal_wall_ns'): + _uint(account[name]) + _need(account['preseal_end_ns'] >= account['parent_entry_ns'] and + account['parent_preseal_wall_ns'] == account['preseal_end_ns'] - account['parent_entry_ns'], + 'G12-N15: actual parent clock endpoints') + for name in ('parent_self_user_seconds', 'parent_self_system_seconds', 'parent_children_user_seconds', + 'parent_children_system_seconds', 'parent_lifetime_max_rss_kib', 'guard_runner_wall_seconds'): + _number(account[name]) + _need(account['unmeasured_final_tail'] is None, 'G12-N15: unmeasured tail must stay explicitly unknown') + _need(_exact(account['guard_usage'], manifest['guard']['receipt_fields']['usage']) and + _exact(account['guard_runner_wall_seconds'], manifest['guard']['receipt_fields']['runner_wall_seconds']), + 'G12-N15: actual guard cost join') + _need(manifest['scope'] == _SCOPE, 'G12-N18: custody scope cannot become scientific approval') + + +def _fixed_argv(label, sources): + stage = _R + '/stages/g12-reference-custody-v1' + science = _R + '/runtime/runs/' + label + '/science' + parent = ['/usr/bin/python3.12', *_FLAGS, _R + '/run_guarded_v3.py', + 'g12-reference-custody-v1', 'g12-reference', label] + root = ['/usr/bin/python3.12', *_FLAGS, stage + '/integration/full_driver.py', + '--root-sha256', _ROOT_PIN, '--provider', stage + '/integration/probe_binding_v3.py', + _PROVIDER_PIN, '--driver', stage + '/integration/g12_reference_adapter_v1.py', + sources['adapter']['sha256'], '--integration', stage + '/integration', '--', + '--output', science, '--lanes', 'g12-reference'] + producer = [stage + '/baseline/full_driver.py', '--frozen-root', stage + '/baseline/frozen', + '--reference', stage + '/baseline/reference/certificates/complex-network.json', + '--mode', 'profile', '--output', science] + return parent, root, producer + + +def _validate_publication(publication, manifest, manifest_record): + _fields(publication, _PUBLICATION_SCHEMA['exact_fields']) + _need(publication['schema'] == _PUBLICATION_SCHEMA['schema_literal'] and + publication['parent_source_sha256'] == manifest['selected_sources']['parent']['sha256'] and + publication['launch_selection_sha256'] == manifest['invocation']['launch_selection_sha256'] and + publication['manifest_path'] == manifest_record['path'] and + publication['manifest_sha256'] == manifest_record['sha256'] and + publication['manifest_bytes'] == manifest_record['bytes'] and + _exact(publication['manifest_identity'], manifest_record['identity']) and + _exact(publication['retained_pair_sha256'], {name: manifest['pair'][name]['retained']['sha256'] + for name in ('common', 'diagnostics')}) and + publication['final_pair_recheck_complete'] is True and publication['known_lease_close_completed'] is True and + publication['primary_error'] is None and _exact(publication['secondary_errors'], []) and + publication['complete_cost_qualification'] is False and + _exact(publication['unmeasured_final_tail'], manifest['accounting']['unmeasured_final_tail']), + 'G12-N15: exact publication/manifest/final-tail join') + _uint(publication['measured_through_ns']) + _need(publication['measured_through_ns'] >= manifest['accounting']['preseal_end_ns'], + 'G12-N15: publication clock precedes preseal') + costs = publication['actual_costs_through_ns'] + _fields(costs, ('entry_ns', 'through_ns', 'wall_ns', 'self_user_seconds', 'self_system_seconds', + 'children_user_seconds', 'children_system_seconds', 'lifetime_max_rss_kib')) + for name in ('entry_ns', 'through_ns', 'wall_ns'): + _uint(costs[name]) + _need(costs['entry_ns'] == manifest['accounting']['parent_entry_ns'] and + costs['through_ns'] == publication['measured_through_ns'] and + costs['wall_ns'] == costs['through_ns'] - costs['entry_ns'], 'G12-N15: publication actual clock join') + for name in ('self_user_seconds', 'self_system_seconds', 'children_user_seconds', + 'children_system_seconds', 'lifetime_max_rss_kib'): + _number(costs[name]) + + +def _source_code_shape(code): + _need(type(code) is CodeType, 'G12-N04: exact code type') + def constant(value): + kind = type(value) + if value is None or value is Ellipsis: + return ('singleton', value is Ellipsis) + if kind in (int, bool, str, bytes): + return (kind.__name__, value) + if kind is float: + return ('float', value.hex()) + if kind is tuple: + return ('tuple', tuple(constant(item) for item in value)) + if kind is frozenset: + return ('frozenset', tuple(sorted(constant(item) for item in value))) + if kind is CodeType: + return ('code', _source_code_shape(value)) + raise RuntimeError('G12-N04: unsupported source code constant') + return tuple(constant(value) for value in ( + code.co_argcount, code.co_posonlyargcount, code.co_kwonlyargcount, + code.co_nlocals, code.co_stacksize, code.co_flags, code.co_code, + code.co_names, code.co_varnames, code.co_freevars, code.co_cellvars, + code.co_exceptiontable, code.co_linetable, code.co_firstlineno, + code.co_filename, code.co_name, code.co_qualname, code.co_consts)) + + +def _authenticate_own_functions(root, api, source, path): + _need(api[0]() == _ROOT_PIN, 'G12-N04: Root before selected-source compilation') + code = root._COMPILE(source, path, 'exec', dont_inherit=True, optimize=0) + declared = {item.co_name: item for item in code.co_consts if type(item) is CodeType} + for name, function in tuple(globals().items()): + if type(function) is FunctionType and function.__globals__ is globals(): + _need(name in declared and function.__builtins__ is root.builtins.__dict__ and + _source_code_shape(function.__code__) == _source_code_shape(declared[name]), + 'G12-N04: actual entire own callable differs from selected source: ' + name) + _need(api[0]() == _ROOT_PIN, 'G12-N04: Root after selected-source compilation') + + +def load_original_g12_reference(root, capability, api): + """Return only original literal/count/opaque common/provenance, after joint custody.""" + config = G12_REFERENCE_HANDOFF + selected = _BOOTSTRAP[3] + _need(type(config) is tuple and len(config) == 9 and type(selected) is tuple and len(selected) == 3, + 'G12-N01: actual parent handoff and cold source remain unselected') + _need(root is _BOOTSTRAP[0] and capability is _BOOTSTRAP[1] and api is _BOOTSTRAP[2] and + type(root) is ModuleType and type(api) is tuple and len(api) == 4 and + all(type(f) is FunctionType and f.__globals__ is root.__dict__ for f in api), + 'G12-N04: initial actual cold Root/capability/API identities differ') + _need(api[0]() == _ROOT_PIN and sys.flags.optimize == 0, 'G12-N04: authentic Root/assertions') + api[1](capability, _PROVIDER_PIN) + _current_graph(_INITIAL_GRAPH) + source_path, source_sha, source_size = selected + source_record, source_raw = _read_file(source_path, 1048576, 0o444) + _need(source_path == __file__ and source_record['sha256'] == source_sha and + source_record['bytes'] == source_size, 'G12-N04: exact independently selected consumer source') + _authenticate_own_functions(root, api, source_raw, source_path) + path, sha, size, identity_tuple, parent_path, parent_sha, publication_path, publication_sha, publication_size = config + _need(_digest(sha) and _digest(parent_sha) and _digest(publication_sha), 'G12-N16: source selection digest domain') + identity = _identity_dict_from_handoff(identity_tuple) + manifest_record = {'path': path, 'sha256': sha, 'bytes': size, 'identity': identity, 'nlink': 1} + manifest_raw = _root_read(root, api, manifest_record, _META_CAP) + manifest = _json(manifest_raw, _META_CAP, True, True) + _validate_manifest(manifest, parent_path, parent_sha) + retained = manifest['custody']['retained_directory'] + _need(path == retained + '/manifest.json' and publication_path == retained + '/publication.json', + 'G12-N16: exact fixed publication/manifest paths') + dirs, rows = _directory_chain(retained) + primary, secondaries, result = None, _RawG12Errors(), None + try: + _need(_exact(_identity(os.fstat(dirs[-1])), manifest['custody']['retained_directory_identity']), + 'G12-N17: final retained directory identity') + publication_record, _ = _read_file(publication_path, _META_CAP, 0o444) + _need(publication_record['sha256'] == publication_sha and publication_record['bytes'] == publication_size, + 'G12-N15: source-selected final publication bytes') + publication_raw = _root_read(root, api, publication_record, _META_CAP) + publication = _json(publication_raw, _META_CAP, True, True) + _validate_publication(publication, manifest, manifest_record) + evidence = {} + for name, record in manifest['retained_evidence'].items(): + cap = _LOG_CAP if name in ('guard_stdout', 'guard_stderr', 'parent_outer_stdout', 'parent_outer_stderr') else _META_CAP + evidence[name] = _root_read(root, api, record, cap) + launch_data = _json(evidence['parent_launch'], _META_CAP, True, True) + _fields(launch_data, ('schema', 'selection_sha256', 'source_selection', 'launch')) + _need(launch_data['schema'] == 'g12-parent-actual-launch-v1' and + launch_data['selection_sha256'] == manifest['invocation']['launch_selection_sha256'] == + hashlib.sha256(_canonical(launch_data['source_selection'])).hexdigest() and + _exact(launch_data['source_selection']['source_pins'], manifest['selected_sources']) and + _exact(launch_data['launch'], {k: v for k, v in manifest['launch'].items() if k != 'launch_record'}), + 'G12-N07: actual source-selected launch/raw evidence binding') + start = _json(evidence['guard_START'], _META_CAP) + receipt = _json(evidence['guard_receipt'], _META_CAP) + usage = _json(evidence['guard_usage'], 16384) + _need(_exact(start, manifest['guard']['start_fields']) and + _exact(receipt, manifest['guard']['receipt_fields']), 'G12-N07: original raw evidence joins') + _validate_guard(start, receipt, usage, evidence['guard_stdout'], evidence['guard_stderr'], + manifest['launch']['guard_root_argv'], manifest['invocation'], manifest['selected_sources'], + launch_data['source_selection']['phase_pin']['sha256']) + _need(_exact(_json(evidence['parent_outer_stdout'], _LOG_CAP), receipt) and + evidence['parent_outer_stderr'] == b'', 'G12-N07: actual outer raw log join') + common_record = manifest['pair']['common']['retained'] + diagnostic_record = manifest['pair']['diagnostics']['retained'] + common_raw = _root_read(root, api, common_record, _PAIR_CAP) + diagnostic_raw = _root_read(root, api, diagnostic_record, _PAIR_CAP) + common, diagnostics, payload = _validate_pair(common_raw, diagnostic_raw) + _need(common['common_payload_sha256'] == manifest['pair']['common_payload_sha256'], 'G12-N13: pair/manifest payload') + # Joint final reread includes diagnostics even after common decoding. + for record, raw, cap in ((manifest_record, manifest_raw, _META_CAP), + (common_record, common_raw, _PAIR_CAP), + (diagnostic_record, diagnostic_raw, _PAIR_CAP), + (publication_record, publication_raw, _META_CAP)): + _need(_root_read(root, api, record, cap) == raw, 'G12-N17: final full custody set changed') + for name, record in manifest['retained_evidence'].items(): + cap = _LOG_CAP if name in ('guard_stdout', 'guard_stderr', 'parent_outer_stdout', 'parent_outer_stderr') else _META_CAP + _need(_root_read(root, api, record, cap) == evidence[name], 'G12-N17: raw retained evidence drift') + _check_chain(rows) + _need(_exact(_identity(os.fstat(dirs[-1])), manifest['custody']['retained_directory_identity']), + 'G12-N17: final namespace changed after decode') + _need(_read_file(source_path, 1048576, 0o444) == (source_record, source_raw), 'G12-N04: consumer source drift') + _current_graph(_INITIAL_GRAPH) + api[1](capability, _PROVIDER_PIN) + _need(api[0]() == _ROOT_PIN, 'G12-N17: final actual Root currentness') + # Full diagnostic raw bytes stay retained; their hash is part of immutable + # provenance, and no diagnostic counter becomes an equality oracle. + provenance = (path, sha, size, tuple(identity[k] for k in _ID_NAMES), parent_path, parent_sha, + publication_path, publication_sha, publication_size, common_record['sha256'], + diagnostic_record['sha256'], common['common_payload_sha256'], + tuple(common['original_scientific_pins']), _PRODUCER_PIN, _AUTHORITY_PIN) + result = common['literal_original_value'], common['remaining_original_case_count'], payload, provenance + except BaseException as error: + primary = error, error.__traceback__ + for descriptor in reversed(dirs): + try: + os.close(descriptor) + except BaseException as error: + secondaries.append((error, error.__traceback__)) + _raise_preserved(primary, secondaries) + return result + +_R = '/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/h25-data-handling-20261028' + +_ENGINE_PINS = {'compare_side_verifier.py': '6e507bb0c7e00d090a60289fddb6c55e90c946d0850c42c3c5e3e15c27604a68', + 'finite_controls.py': 'df989a831aac43cc1af95169dad8c64a7548760e6e1f96976da996703f2c8f7a', + 'native_backend.py': 'e473c38245c3668715b5a78dfe980b2fe3ed0d0c9b8c97c666fbae6ecf1fffd5', + 'native_gf2.c': 'e9c3c9194a08718bd1575c1cf08c6c6772d3b644c2e274c25a84a1f9249d06cc', + 'profile_side_verifier.py': '9c994378171c20a91539418d93cb8387e1daa93465d6862beefea90e12999c2a', + 'source/complex_circuit.py': 'd623617f7c5cb3189580883a8ab30c0bd3832688ae3f1f0c1f881bbbbff8e0c1', + 'source/complex_network.py': '0da395e67ac04fa213494e71012c1b19b544596d34cdce5a3b172b1fb6af5f1b'} + +_OTHER_SOURCE_PINS = {'cleanup_leaf_origin': '7b3304eaf4884e3029df5095e2b0950c18d1544ad21431a07c033b85e53bd4f7', + 'reference': '1f763d95c7ff163aa71d13cd82784f16665be8afb21f75e76941e2119562098f', + 'runtime_profile': 'ad0ec2aea01b83f97bdeafd9e9208360127fee870d024d353879b5ed99237109', + 'source_pins': '88bba3caf5975f30fa7abceaea9454110cf3b069233e8241a2ca13d1dff171a7'} + +_OPERATING_PREMISES = ('Selected fixed scientific sources, adapter and ordinary profile branch do not fork/spawn threads, ' + 'daemonize, pass writable descriptors to outsiders, or enlist external writers. Trusted ' + 'OS/loader/interpreter/stdlib and cooperating same-user parent launch domain exclude unrelated writer ' + 'interference. This is an explicit finite source/operating premise, not established merely by a clean /proc ' + 'snapshot.') + +_SCOPE = ('Fixed source-data custody only. No G12/P02/full-positive/native/performance/scientific admission; no ' + 'universal writers theorem.') + +_FLAGS = ('-S', '-s', '-P', '-B') + +_ENV = {'LANG': 'C.UTF-8', + 'LC_ALL': 'C.UTF-8', + 'PATH': '/usr/bin:/bin', + 'PYTHONDONTWRITEBYTECODE': '1', + 'PYTHONHASHSEED': '0', + 'TZ': 'UTC'} + +_EVIDENCE_NAMES = {'guard_START': 'guard-START.json', + 'guard_receipt': 'guard-receipt.json', + 'guard_stderr': 'guard-stderr.txt', + 'guard_stdout': 'guard-stdout.txt', + 'guard_usage': 'guard-usage.json', + 'parent_launch': 'parent-LAUNCH.json', + 'parent_outer_stderr': 'parent-outer-stderr.txt', + 'parent_outer_stdout': 'parent-outer-stdout.txt', + 'parent_owned_observations': 'parent-owned-observations.json', + 'parent_preseal_accounting': 'parent-preseal-accounting.json'} + +_INITIAL_GRAPH = _capture_graph(globals()) diff --git a/research/h25-g12-custody-repairs/predecessor/g12_reference_parent_v2.py.txt b/research/h25-g12-custody-repairs/predecessor/g12_reference_parent_v2.py.txt new file mode 100644 index 0000000000..42795e5d3a --- /dev/null +++ b/research/h25-g12-custody-repairs/predecessor/g12_reference_parent_v2.py.txt @@ -0,0 +1,1763 @@ +"""Fixed G12 parent custody source, v2 identity and preflight-close repair. + +No execution or publication authority. + +Only a later independently reviewed literal may select the launch. All actual +authorization, phase, resource-fit, custody and final-cost gates remain closed. +Unknown final tails remain unknown in the complete original symbolic invoice. +No manifest, receipt dictionary or success flag is accepted from a caller. +""" +import time +import resource +import signal +import subprocess +import fcntl +G12_REFERENCE_LAUNCH_SELECTION = None +_INITIAL_PARENT_SOURCE_PIN = globals().get('bootstrap_g12_parent_source_pin') +# Actual initial parent source identity comes only from the trusted external +# selected launcher; its future literal parent slot is None (no own-hash cycle). +import os + + +import sys + + +import stat + + +import json + + +import hashlib + + +import math + + +from types import FunctionType, CodeType, ModuleType + + +_ROOT_PIN = 'f5a2d33f2b4d3651f214156a0e7094c2bb516ce2d5ab7698d18c11f98f35dee0' + + +_PROVIDER_PIN = '9cbb7368f89e71d1e6cc46db5dc77efed3e03ed2a801c98c88fe316e4d9f3ef2' + + +_PRODUCER_PIN = 'a346025d5b6e2b26246521c6af6292643a4c2c3286b33ff3996dcf051cd6be26' + + +_GUARD_PIN = 'bd882e3dadb1b6aeaa63ee824f1a1c58f8ef2546b6840a2bffa46885a184d3eb' + + +_AUTHORITY_PIN = 'f279ab86fc17c6a517b035f19d56863919cbd8304de4e7d5332457c6159aec10' + + +_META_CAP = 262144 + + +_PAIR_CAP = 268435456 + + +_CHUNK = 65536 + + +_LOG_CAP = 2097152 + + +_MISSING = object() + + +_ID_NAMES = ('dev', 'ino', 'full_st_mode', 'size', 'mtime_ns', 'ctime_ns') + + +class _RawG12Errors: + """Fixed error-retention slots; storing raw failures precedes formatting/IO.""" + __slots__ = ('slots', 'count') + def __init__(self): + self.slots = [None] * 4096 + self.count = 0 + def append(self, value): + # All fixed directory/process/stream paths together have fewer than 4096 + # close sites under the 256-component/128-generation source ceilings. + if self.count >= len(self.slots): + raise RuntimeError('G12-N09: fixed raw secondary retention exhausted') + self.slots[self.count] = value + self.count += 1 + def __bool__(self): + return self.count != 0 + def __len__(self): + return self.count + def __getitem__(self, index): + if type(index) is not int or not 0 <= index < self.count: + raise IndexError(index) + return self.slots[index] + def __iter__(self): + for index in range(self.count): + yield self.slots[index] + def __repr__(self): + return repr(tuple(self)) + + +def _need(condition, message): + if not condition: + raise RuntimeError(message) + + +def _exact(value, expected): + if type(value) is not type(expected): + return False + if type(value) in (list, tuple): + return len(value) == len(expected) and all(_exact(a, b) for a, b in zip(value, expected)) + if type(value) is dict: + return set(value) == set(expected) and all(_exact(value[k], expected[k]) for k in expected) + return value == expected + + +def _fields(value, fields): + _need(type(value) is dict and all(type(k) is str for k in value) and + set(value) == set(fields), 'G12-N12: exact field domain differs') + + +def _digest(value): + return type(value) is str and len(value) == 64 and all(c in '0123456789abcdef' for c in value) + + +def _uint(value, positive=False): + _need(type(value) is int and value >= (1 if positive else 0), 'G12-N12: exact integer domain') + + +def _number(value): + _need(type(value) in (int, float) and math.isfinite(value) and value >= 0, + 'G12-N12: finite nonnegative exact number required') + + +def _path(path): + _need(type(path) is str and path.startswith('/') and + all(p not in ('', '.', '..') for p in path.split('/')[1:]), 'G12-N11: absolute canonical path') + return path + + +def _identity(info): + return dict(zip(_ID_NAMES, (info.st_dev, info.st_ino, info.st_mode, info.st_size, + info.st_mtime_ns, info.st_ctime_ns))) + + +def _directory_key(info): + return info.st_dev, info.st_ino, info.st_mode + + +def _directory_chain(path): + """Held no-follow chain; no later absolute path silently changes its owner.""" + _path(path) + _need(len(path.split('/')) <= 257, 'G12-N11: finite directory-component bound') + fds, rows = [], [] + primary = None + try: + fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC) + fds.append(fd) + for part in path.split('/')[1:]: + before = os.stat(part, dir_fd=fd, follow_symlinks=False) + _need(stat.S_ISDIR(before.st_mode), 'G12-N11: directory component type') + child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, + dir_fd=fd) + fds.append(child) + opened = os.fstat(child) + _need(_directory_key(before) == _directory_key(opened), 'G12-N11: directory replaced') + rows.append((fd, part, child, _directory_key(opened))) + fd = child + return fds, rows + except BaseException as error: + primary = (error, error.__traceback__) + secondary = _RawG12Errors() + for descriptor in reversed(fds): + try: + os.close(descriptor) + except BaseException as error: + secondary.append((error, error.__traceback__)) + _raise_preserved(primary, secondary) + + +def _check_chain(rows): + for parent, name, descriptor, key in rows: + _need(_directory_key(os.fstat(descriptor)) == key == + _directory_key(os.stat(name, dir_fd=parent, follow_symlinks=False)), + 'G12-N11: directory binding changed') + + +def _raise_preserved(primary, secondaries): + """Never replace first raw failure if evidence formatting or retention fails.""" + if primary is not None: + error, traceback = primary + try: + error.add_note('G12 ordered secondary failures: ' + repr(secondaries)) + except BaseException: + pass + raise error.with_traceback(traceback) + if secondaries: + error, traceback = secondaries[0][:2] + raise error.with_traceback(traceback) + + +def _handoff_identity_tuple(record): + """Pack a FileRecord identity as the immutable six-tuple handoff field. + + The accepted nine-tuple keeps this field positional. The cold consumer + converts it back to a string-keyed dictionary; this parent does not emit + a second, dictionary representation. + """ + _fields(record['identity'], _ID_NAMES) + return tuple(record['identity'][key] for key in _ID_NAMES) + + +def _close_known_descriptors(descriptors): + """Attempt every close. Ordered failures never stop the remaining closes.""" + failures = _RawG12Errors() + for descriptor in reversed(tuple(descriptors)): + try: + os.close(descriptor) + except BaseException as error: + failures.append((error, error.__traceback__)) + return failures + + +def _finally_close_known(descriptors, secondaries): + """Preflight finally: close all, keep a pending primary, fail if the body succeeded. + + A pending body error stays the propagating primary. Every close failure is + then an ordered secondary. If the body succeeded, the first close failure + propagates and only the later close failures are secondaries. + """ + failures = _close_known_descriptors(descriptors) + if sys.exc_info()[1] is None and failures: + error, traceback = failures[0] + for item in list(failures)[1:]: + secondaries.append(item) + raise error.with_traceback(traceback) + for item in failures: + secondaries.append(item) + + + + +def _read_file(path, cap, mode=None): + _path(path) + parent, name = path.rsplit('/', 1) + fds, rows = _directory_chain(parent) + descriptor, primary, secondary, result = None, None, _RawG12Errors(), None + try: + before = os.stat(name, dir_fd=fds[-1], follow_symlinks=False) + _need(stat.S_ISREG(before.st_mode) and before.st_nlink == 1 and + 0 <= before.st_size <= cap and (mode is None or before.st_mode == stat.S_IFREG | mode), + 'G12-N11: regular-file size/mode/link domain') + descriptor = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, + dir_fd=fds[-1]) + opened = os.fstat(descriptor) + _need(_identity(before) == _identity(opened) and opened.st_nlink == 1, + 'G12-N11: file changed on open') + count, blocks, hasher = 0, [], hashlib.sha256() + while count < opened.st_size: + block = os.read(descriptor, min(_CHUNK, opened.st_size - count)) + _need(bool(block), 'G12-N11: short file read') + count += len(block) + hasher.update(block) + blocks.append(block) + _need(os.read(descriptor, 1) == b'', 'G12-N11: file grew') + after = os.fstat(descriptor) + ending = os.stat(name, dir_fd=fds[-1], follow_symlinks=False) + _need(_identity(before) == _identity(after) == _identity(ending) and + after.st_nlink == ending.st_nlink == 1, 'G12-N11: full file identity changed') + _check_chain(rows) + result = ({'path': path, 'sha256': hasher.hexdigest(), 'bytes': count, + 'identity': _identity(after), 'nlink': 1}, b''.join(blocks)) + except BaseException as error: + primary = (error, error.__traceback__) + for fd in ([descriptor] if descriptor is not None else []) + list(reversed(fds)): + try: + os.close(fd) + except BaseException as error: + secondary.append((error, error.__traceback__)) + _raise_preserved(primary, secondary) + return result + + +def _file_record(value): + _fields(value, ('path', 'sha256', 'bytes', 'identity', 'nlink')) + _path(value['path']) + _need(_digest(value['sha256']) and type(value['nlink']) is int and value['nlink'] == 1, + 'G12-N11: file digest/link record') + _uint(value['bytes']) + _fields(value['identity'], _ID_NAMES) + for key in _ID_NAMES: + _need(type(value['identity'][key]) is int, 'G12-N11: exact stat value') + _uint(value['identity']['dev']) + _uint(value['identity']['ino'], True) + _need(stat.S_ISREG(value['identity']['full_st_mode']) and + value['identity']['size'] == value['bytes'], 'G12-N11: file identity size/type') + + +def _pairs(items): + result = {} + for key, value in items: + _need(type(key) is str and key not in result, 'G12-N12: duplicate JSON key') + result[key] = value + return result + + +def _nonfinite(value): + raise ValueError('G12-N12: nonfinite JSON token: ' + value) + + +def _canonical(value): + return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True, + allow_nan=False).encode('ascii') + + +def _json(raw, cap, canonical=False, newline=False): + _need(type(raw) is bytes and len(raw) <= cap, 'G12-N12: raw JSON bound') + # Scan lexical nesting before json.loads recursion or object materialization. + depth, quoted, escaped = 0, False, False + for char in raw: + if quoted: + if escaped: + escaped = False + elif char == 92: + escaped = True + elif char == 34: + quoted = False + elif char == 34: + quoted = True + elif char in (91, 123): + depth += 1 + _need(depth <= 256, 'G12-N12: JSON depth limit') + elif char in (93, 125): + depth -= 1 + _need(depth >= 0, 'G12-N12: JSON nesting') + _need(depth == 0 and not quoted, 'G12-N12: incomplete JSON') + value = json.loads(raw.decode('utf-8'), object_pairs_hook=_pairs, parse_constant=_nonfinite) + pending, count = [(value, 0)], 0 + while pending: + item, depth = pending.pop() + count += 1 + _need(count <= cap and depth <= 256, 'G12-N12: JSON node/depth limit') + if type(item) is dict: + pending.extend((x, depth + 1) for pair in item.items() for x in pair) + elif type(item) is list: + pending.extend((x, depth + 1) for x in item) + elif type(item) is str: + _need(len(item) <= cap, 'G12-N12: JSON string limit') + elif type(item) is float: + _need(math.isfinite(item), 'G12-N12: overflowed JSON number') + else: + _need(item is None or type(item) in (bool, int), 'G12-N12: JSON primitive') + if canonical: + _need(raw == _canonical(value) + (b'\n' if newline else b''), 'G12-N12: canonical JSON bytes') + return value + + +def _hex(value, cap): + _need(type(value) is str and len(value) <= cap and len(value) % 2 == 0 and + all(c in '0123456789abcdef' for c in value), 'G12-N12: complete lowercase hex') + return bytes.fromhex(value) + + +def _decimal(value, positive=False): + _need(type(value) is str and bool(value), 'G12-N12: integer tag text') + digits = value[1:] if value.startswith('-') else value + _need(bool(digits) and all(c in '0123456789' for c in digits) and + (digits == '0' or digits[0] != '0') and value != '-0' and + (not positive or (not value.startswith('-') and value != '0')), 'G12-N12: canonical integer') + + +def _tagged(raw, cap): + value = _json(raw, cap, True) + pending = [(value, 0)] + count = 0 + while pending: + node, depth = pending.pop() + count += 1 + _need(count <= cap and depth <= 256 and type(node) is list and len(node) >= 1 and + type(node[0]) is str, 'G12-N12: tagged primitive bound/shape') + tag = node[0] + if tag == 'None': + _need(len(node) == 1, 'G12-N12: None arity') + continue + _need(len(node) == (3 if tag == 'Fraction' else 2), 'G12-N12: primitive arity') + arg = node[1] + if tag == 'bool': + _need(type(arg) is bool, 'G12-N12: bool tag') + elif tag == 'int': + _decimal(arg) + elif tag == 'Fraction': + _decimal(arg) + _decimal(node[2], True) + elif tag == 'str': + _need(type(arg) is str, 'G12-N12: string tag') + elif tag == 'bytes': + _hex(arg, cap) + elif tag == 'float': + _need(type(arg) is str and float.fromhex(arg).hex() == arg, 'G12-N12: float.hex domain') + elif tag in ('tuple', 'list'): + _need(type(arg) is list, 'G12-N12: sequence tag') + pending.extend((item, depth + 1) for item in arg) + elif tag == 'dict': + _need(type(arg) is list, 'G12-N12: ordered dict tag') + for pair in arg: + _need(type(pair) is list and len(pair) == 2, 'G12-N12: dict pair') + pending.extend((item, depth + 1) for item in pair) + else: + raise ValueError('G12-N12: unknown primitive tag') + return value + + +def _rank_events(encoded): + value = _tagged(_hex(encoded, _PAIR_CAP), _PAIR_CAP) + _need(value[0] == 'tuple', 'G12-N12: rank tuple') + for event in value[1]: + _need(event[0] == 'tuple' and len(event[1]) == 2 and event[1][0][0] == 'tuple' and + all(x[0] == 'int' for x in event[1][0][1]) and event[1][1][0] == 'int', + 'G12-N12: rank-event grammar') + return len(value[1]) + + +def _validate_pair(common_raw, diagnostic_raw): + common = _json(common_raw, _PAIR_CAP, True, True) + diagnostic = _json(diagnostic_raw, _PAIR_CAP, True, True) + spec = _PAIR_SCHEMA + _fields(common, spec['common_exact_fields']) + _fields(diagnostic, spec['diagnostic_exact_fields']) + for key, expected in spec['common_constants'].items(): + _need(_exact(common[key], expected), 'G12-N13: original common source/workload binding') + for key, expected in spec['diagnostic_constants'].items(): + _need(_exact(diagnostic[key], expected), 'G12-N13: diagnostic source/role binding') + _need(type(common['literal_original_value']) is bool, 'G12-N12: observed literal exact bool') + _uint(common['remaining_original_case_count'], True) + payload = _hex(common['common_payload_hex'], _PAIR_CAP) + _need(_digest(common['common_payload_sha256']) and + hashlib.sha256(payload).hexdigest() == common['common_payload_sha256'] == + diagnostic['common_payload_sha256'], 'G12-N13: complete common digest join') + tagged = _tagged(payload, _PAIR_CAP) + _need(tagged[0] == 'tuple' and len(tagged[1]) == 10, 'G12-N13: common tuple arity') + prefix = [['str', 'g12-original-remainder-common-v1'], + ['tuple', [['str', p] for p in spec['common_constants']['original_scientific_pins']]], + ['int', '25'], ['tuple', [['int', '0'], ['int', '2'], ['int', '1']]]] + _need(_exact(tagged[1][:4], prefix), 'G12-N13: common inner source/workload prefix') + suffix = ['tuple', [['str', name] for name in ('verify_role_frames', 'full_log_integer_bounds', + 'original_upstream_verify_sources', 'original_serializable', 'complete_original_cli')]] + _need(_exact(tagged[1][-1], suffix), 'G12-N13: original suffix phase order') + for key in ('prefix_end', 'suffix_start', 'cli_end'): + row = diagnostic[key] + _fields(row, spec['diagnostic_snapshot_exact_fields']) + _uint(row['rank_event_count']) + _need(_rank_events(row['ordered_rank_events_hex']) == row['rank_event_count'] and + row['native_binding'] is None and row['cache_binding'] is None, + 'G12-N12: original diagnostic rank/binding domain') + receipt = row['complement_receipt'] + _fields(receipt, spec['complement_receipt_exact_fields']) + _uint(receipt['calls']) + _uint(receipt['canonical_stream_bytes']) + _need(_digest(receipt['sha256']) and receipt['schema'] == + 'v2-jsonl:call,us,vs,result(type=list+values or type=None); ordered exact integer vectors', 'G12-N12: complement receipt') + _rank_events(diagnostic['ordered_rank_suffix_hex']) + _fields(diagnostic['phases'], spec['phase_exact_names']) + for row in diagnostic['phases'].values(): + _fields(row, ('calls', 'wall_seconds', 'cpu_seconds_with_children')) + _need(type(row['calls']) is int and row['calls'] == 1, 'G12-N12: phase calls') + _number(row['wall_seconds']) + _number(row['cpu_seconds_with_children']) + return common, diagnostic, payload + + +def _source_pin(value): + _fields(value, ('path', 'sha256', 'bytes', 'mode')) + _path(value['path']) + _uint(value['bytes']) + _need(_digest(value['sha256']) and type(value['mode']) is str and len(value['mode']) == 4 and + all(c in '01234567' for c in value['mode']), 'G12-N02: exact source pin') + + +def _validate_guard(start, receipt, usage, stdout, stderr, root_argv, invocation, source_pins, phase_sha): + _fields(start, _GUARD_SCHEMA['START_exact_fields']) + _fields(receipt, _GUARD_SCHEMA['receipt_exact_fields']) + _fields(usage, ('user_seconds', 'system_seconds', 'kernel_max_rss_kib', 'exit')) + for key in start: + _need(_exact(start[key], receipt[key]), 'G12-N07: original START/receipt field join') + for key, expected in _GUARD_SCHEMA['required_values'].items(): + _need(_exact(receipt[key], expected), 'G12-N07: original guard success predicate') + for key in ('job', 'label', 'stage_sha256'): + _need(_exact(start[key], invocation[key]), 'G12-N07: selected invocation mismatch') + expected_launch = {'contract': 'trusted-clean-nosite-safe-path-fixedseed-v1', + 'no_site': 1, 'no_user_site': 1, 'safe_path': True, 'ignore_environment': 0, + 'isolated': 0, 'hash_seed_environment': '0', 'hash_randomization': 0, + 'initial_sys_path': ['/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload'], + 'environment': dict(_ENV), + 'trust_boundary': 'Authenticated parent launcher, OS, interpreter and system stdlib before this module; no Python self-authentication claim'} + _need(_exact(start['parent_launch'], expected_launch), 'G12-N07: exact original clean parent launch') + _need(_exact(start['command'], root_argv) and start['runner_sha256'] == _GUARD_PIN and + start['budget_phase_sha256'] == phase_sha and _digest(start['fractions_sha256']), + 'G12-N07: selected command/source/phase binding') + _need(type(start['phase_cap_seconds']) is int and start['phase_cap_seconds'] in (600, 2400), + 'G12-N05: original aggregate cap') + _number(start['spent_before_seconds']) + _need(start['spent_before_seconds'] < start['phase_cap_seconds'], 'G12-N05: consumed budget') + for key in ('wall_seconds', 'runner_wall_seconds', 'runner_user_seconds', 'runner_system_seconds', + 'runner_lifetime_max_rss_kib', 'sampled_process_group_rss_bytes'): + _number(receipt[key]) + limit = min(180, start['phase_cap_seconds'] - start['spent_before_seconds']) + _need(receipt['wall_seconds'] <= limit and receipt['runner_wall_seconds'] <= limit and + receipt['runner_lifetime_max_rss_kib'] * 1024 <= 1073741824 and + receipt['sampled_process_group_rss_bytes'] <= 1073741824, + 'G12-N07: original guard resource caps') + for key in ('user_seconds', 'system_seconds', 'kernel_max_rss_kib'): + _number(usage[key]) + _need(type(usage['exit']) is int and usage['exit'] == 0 and _exact(usage, receipt['usage']), + 'G12-N07: complete original usage join') + for name, raw in (('stdout', stdout), ('stderr', stderr)): + _need(len(raw) <= _LOG_CAP and receipt[name + '_bytes'] == len(raw) and + type(receipt[name + '_bytes']) is int and receipt[name + '_final_bytes'] == len(raw) and + type(receipt[name + '_final_bytes']) is int and + receipt[name + '_sha256'] == hashlib.sha256(raw).hexdigest(), 'G12-N07: complete raw log join') + _need(stderr == b'' and type(receipt['python']) is str and type(receipt['platform']) is str, + 'G12-N07: original stderr/platform fields') + + +def _capture_graph(namespace): + """Capture the fixed own/JSON function graph before candidate exposure.""" + modules = (json, json.decoder, json.encoder, json.scanner, hashlib, os, stat, math) + tuple( + namespace[name] for name in ('subprocess', 'fcntl', 'signal', 'resource', 'time') if name in namespace) + namespaces = [namespace] + [module.__dict__ for module in modules] + namespaces.extend((json._default_decoder.__dict__, json._default_encoder.__dict__)) + records, members, seen = [], [], set() + for mapping in namespaces: + members.append((mapping, tuple(mapping.items()))) + for value in mapping.values(): + candidates = [value] + if type(value) is type: + candidates.extend(value.__dict__.values()) + if value.__module__ in (__name__, 'json.decoder', 'json.encoder', 'subprocess'): + members.append((value.__dict__, tuple(value.__dict__.items()))) + for function in candidates: + if type(function) is not FunctionType or id(function) in seen: + continue + seen.add(id(function)) + records.append((function, function.__code__, function.__globals__, function.__builtins__, + function.__defaults__, function.__kwdefaults__, function.__closure__, + tuple(function.__dict__.items()), + () if function.__kwdefaults__ is None else tuple(function.__kwdefaults__.items()), + () if function.__closure__ is None else tuple((c, c.cell_contents) for c in function.__closure__))) + data = tuple((name, _canonical(namespace[name])) for name in + ('_PAIR_SCHEMA', '_MANIFEST_SCHEMA', '_GUARD_SCHEMA', '_PUBLICATION_SCHEMA', + '_ENGINE_PINS', '_OTHER_SOURCE_PINS', '_ENV', '_EVIDENCE_NAMES') if name in namespace) + return tuple(records), tuple(members), data + + + +def _current_graph(graph): + records, members, data = graph + for mapping, rows in members: + # The capture itself is assigned once after this snapshot. + expected = dict(rows) + for name, value in rows: + _need(mapping.get(name, _MISSING) is value, 'G12-N04: captured namespace member changed: ' + name) + extra = set(mapping) - set(expected) + _need(not extra or mapping is globals() and extra == {'_INITIAL_GRAPH'}, + 'G12-N04: captured namespace census changed') + for name, expected in data: + _need(_canonical(globals()[name]) == expected, 'G12-N04: source-owned schema constant changed') + for f, code, namespace, builtin, defaults, kw, cells, attrs, kws, contents in records: + _need(f.__code__ is code and f.__globals__ is namespace and f.__builtins__ is builtin and + f.__defaults__ is defaults and f.__kwdefaults__ is kw and f.__closure__ is cells and + len(f.__dict__) == len(attrs), 'G12-N04: captured function graph changed') + for name, value in attrs: + _need(f.__dict__.get(name, _MISSING) is value, 'G12-N04: function attributes changed') + if kw is not None: + _need(len(kw) == len(kws), 'G12-N04: keyword-default census changed') + for name, value in kws: + _need(kw.get(name, _MISSING) is value, 'G12-N04: keyword defaults changed') + for cell, value in contents: + _need(cell.cell_contents is value, 'G12-N04: captured closure changed') + + + +_PAIR_SCHEMA = {'common_constants': {'authority_source_sha256': 'f279ab86fc17c6a517b035f19d56863919cbd8304de4e7d5332457c6159aec10', + 'extra_target': [0, 2, 1], + 'h': 25, + 'literal_original_type': 'bool', + 'original_driver_sha256': '0d976d2eb6b845f20d4a3396591a806f966688b88693cd6a5f8a0c9e48925e36', + 'original_scientific_pins': ['d623617f7c5cb3189580883a8ab30c0bd3832688ae3f1f0c1f881bbbbff8e0c1', + '0da395e67ac04fa213494e71012c1b19b544596d34cdce5a3b172b1fb6af5f1b', + '88bba3caf5975f30fa7abceaea9454110cf3b069233e8241a2ca13d1dff171a7', + 'adc7f1241b42e322a6451854ab7e4b4c146bf78a'], + 'producer_role': 'independent-original-uncached', + 'schema': 'g12-independent-original-reference-envelope-v1', + 'scope': 'Actual original N22 literal and P07 common remainder observations only; ' + 'no original PROFILE_ANCHOR_PASS, FULL_PASS, native qualification or G12 ' + 'approval.', + 'selected_driver_sha256': 'a346025d5b6e2b26246521c6af6292643a4c2c3286b33ff3996dcf051cd6be26'}, + 'common_exact_fields': ['schema', + 'producer_role', + 'selected_driver_sha256', + 'original_driver_sha256', + 'authority_source_sha256', + 'original_scientific_pins', + 'h', + 'extra_target', + 'literal_original_type', + 'literal_original_value', + 'remaining_original_case_count', + 'common_payload_sha256', + 'common_payload_hex', + 'scope'], + 'complement_receipt_exact_fields': ['calls', 'canonical_stream_bytes', 'sha256', 'schema'], + 'diagnostic_constants': {'complement_suffix_limit': 'Only cumulative original start/end receipts; no ' + 'digest subtraction or suffix-stream claim.', + 'completion': 'Exact source-owned intentional marker followed by original ' + 'finally, exact observer restoration, both cold2 checks and ' + 'original source/output custody.', + 'producer_role': 'independent-original-uncached', + 'schema': 'g12-independent-original-reference-diagnostics-v1', + 'selected_driver_sha256': 'a346025d5b6e2b26246521c6af6292643a4c2c3286b33ff3996dcf051cd6be26'}, + 'diagnostic_exact_fields': ['schema', + 'producer_role', + 'selected_driver_sha256', + 'common_payload_sha256', + 'prefix_end', + 'suffix_start', + 'cli_end', + 'ordered_rank_suffix_hex', + 'complement_suffix_limit', + 'phases', + 'completion'], + 'diagnostic_snapshot_exact_fields': ['rank_event_count', + 'ordered_rank_events_hex', + 'complement_receipt', + 'native_binding', + 'cache_binding'], + 'phase_exact_names': ['input_custody', + 'engine_custody', + 'fresh_root_copy', + 'fresh_engine_copy', + 'cold_engine_import', + 'cold_complex_module_load', + 'cold_certify_import', + 'cold_prepare_import', + 'side_construction', + 'checks_initialization', + 'compile_roles', + 'verify_map', + 'verify_labels', + 'verify_role_frames', + 'original_upstream_verify_sources', + 'full_log_integer_bounds', + 'original_serializable', + 'complete_original_cli']} + + +_MANIFEST_SCHEMA = {'accounting_exact_fields': ['clock', + 'parent_entry_ns', + 'preseal_end_ns', + 'parent_preseal_wall_ns', + 'parent_self_user_seconds', + 'parent_self_system_seconds', + 'parent_children_user_seconds', + 'parent_children_system_seconds', + 'parent_lifetime_max_rss_kib', + 'guard_usage', + 'guard_runner_wall_seconds', + 'categories', + 'complete_tail_accounting_required', + 'unmeasured_final_tail'], + 'cleanup_exact_fields': ['operating_premises', + 'owned_generations', + 'observed_groups', + 'remaining', + 'current_children', + 'known_streams_closed', + 'known_pidfds_closed', + 'io_unknown', + 'lease_identity', + 'science_directory_identity', + 'observations_record'], + 'custody_exact_fields': ['retained_directory', + 'retained_directory_identity', + 'retained_file_mode', + 'created_after_known_cleanup', + 'source_selection_required', + 'known_close_policy'], + 'exact_top_level_fields': ['schema', + 'invocation', + 'selected_sources', + 'workload', + 'launch', + 'terminal', + 'guard', + 'cleanup', + 'pair', + 'retained_evidence', + 'custody', + 'accounting', + 'scope'], + 'guard_exact_fields': ['start', + 'receipt', + 'start_fields', + 'receipt_fields', + 'stdout', + 'stderr', + 'usage'], + 'invocation_exact_fields': ['stage', + 'job', + 'label', + 'stage_sha256', + 'jobs_sha256', + 'launch_selection_sha256'], + 'launch_exact_fields': ['parent_pid', + 'parent_start_ticks', + 'guard_pid', + 'guard_start_ticks', + 'guard_pgid', + 'guard_sid', + 'parent_guard_argv', + 'guard_root_argv', + 'adapter_producer_argv', + 'cwd', + 'environment', + 'flags', + 'launch_record'], + 'pair_exact_fields': ['common', 'diagnostics', 'common_payload_sha256'], + 'retained_evidence_exact_keys': ['guard_START', + 'guard_receipt', + 'guard_stdout', + 'guard_stderr', + 'guard_usage', + 'parent_launch', + 'parent_outer_stdout', + 'parent_outer_stderr', + 'parent_owned_observations', + 'parent_preseal_accounting'], + 'schema_literal': 'g12-parent-two-export-custody-v2', + 'selected_sources_exact_fields': ['parent', + 'guard', + 'root', + 'provider', + 'adapter', + 'producer', + 'authority', + 'source_pins', + 'reference', + 'engine', + 'runtime_profile', + 'cleanup_leaf_origin'], + 'terminal_exact_fields': ['actual_popen_returncode', + 'wait_completed', + 'parent_stop', + 'primary_error', + 'secondary_errors', + 'guard_receipt_missing'], + 'workload_exact_fields': ['role', + 'h', + 'extra_target', + 'mode', + 'anchor', + 'optimize', + 'original_scientific_pins'], + 'workload_values': {'anchor': None, + 'extra_target': [0, 2, 1], + 'h': 25, + 'mode': 'profile', + 'optimize': 0, + 'original_scientific_pins': ['d623617f7c5cb3189580883a8ab30c0bd3832688ae3f1f0c1f881bbbbff8e0c1', + '0da395e67ac04fa213494e71012c1b19b544596d34cdce5a3b172b1fb6af5f1b', + '88bba3caf5975f30fa7abceaea9454110cf3b069233e8241a2ca13d1dff171a7', + 'adc7f1241b42e322a6451854ab7e4b4c146bf78a'], + 'role': 'independent-original-uncached'}} + + +_GUARD_SCHEMA = {'START_exact_fields': ['command', + 'parent_launch', + 'stage_sha256', + 'runner_sha256', + 'fractions_sha256', + 'budget_phase_sha256', + 'spent_before_seconds', + 'phase_cap_seconds', + 'job', + 'label'], + 'receipt_exact_fields': ['command', + 'parent_launch', + 'stage_sha256', + 'runner_sha256', + 'fractions_sha256', + 'budget_phase_sha256', + 'spent_before_seconds', + 'phase_cap_seconds', + 'job', + 'label', + 'exit', + 'wall_seconds', + 'usage', + 'termination', + 'sampled_process_group_rss_bytes', + 'source_bytes_and_modes_unchanged', + 'stdout_sha256', + 'stdout_bytes', + 'stderr_sha256', + 'stderr_bytes', + 'stdout_final_bytes', + 'stderr_final_bytes', + 'retained_log_bytes_stable', + 'output_cap_observed_at', + 'log_read_chunk_bytes', + 'runner_wall_seconds', + 'runner_user_seconds', + 'runner_system_seconds', + 'runner_lifetime_max_rss_kib', + 'python', + 'platform', + 'status'], + 'required_values': {'exit': 0, + 'log_read_chunk_bytes': 65536, + 'output_cap_observed_at': None, + 'retained_log_bytes_stable': True, + 'source_bytes_and_modes_unchanged': True, + 'status': 'PASS', + 'stderr_bytes': 0, + 'stderr_final_bytes': 0, + 'termination': None}} + + +_PUBLICATION_SCHEMA = {'exact_fields': ['schema', + 'parent_source_sha256', + 'launch_selection_sha256', + 'manifest_path', + 'manifest_sha256', + 'manifest_bytes', + 'manifest_identity', + 'retained_pair_sha256', + 'final_pair_recheck_complete', + 'known_lease_close_completed', + 'primary_error', + 'secondary_errors', + 'measured_through_ns', + 'actual_costs_through_ns', + 'unmeasured_final_tail', + 'complete_cost_qualification'], + 'schema_literal': 'g12-parent-custody-publication-v2'} + + +_COST_CATEGORIES = ('source/stage/plan/authentication and dependency preflight', 'parent invocation setup and known lease operations', 'adapter bootstrap source read/hash/compile/exec and argv/module alias custody/restoration', 'entire independent uncached reference including fresh copies/engine imports/original CLI/trace capture/original checks/finally/restoration/cold2', 'guard launch/time/monitoring/STOP/final original source inventory/usage/raw-log hashing/receipt', 'actual parent wait and known descendant/group/FD cleanup', 'canonical receipt and START joins plus all complete raw evidence retention', 'both exports full reads/hashes/JSON/schema/payload decode/crosslinks and repeated pair checks', 'new parent copies/write/fsync/chmod/close/directory sync/readback', 'manifest schema/write/hash/fsync/close/readback and source-selection publication tail', 'parent failure/secondary-error retention and necessary cleanup after deadline', 'cold consumer complete manifest/pair/publication read/hash/parse/decode/recheck and all retained alias lifetimes') + + +def _validate_manifest(manifest, parent_path, parent_sha): + spec = _MANIFEST_SCHEMA + _fields(manifest, spec['exact_top_level_fields']) + _need(manifest['schema'] == spec['schema_literal'], 'G12-N12: custody schema') + for name in ('invocation', 'selected_sources', 'workload', 'launch', 'terminal', 'guard', + 'cleanup', 'pair', 'custody', 'accounting'): + _fields(manifest[name], spec[name + '_exact_fields']) + _fields(manifest['retained_evidence'], spec['retained_evidence_exact_keys']) + _need(_exact(manifest['workload'], spec['workload_values']), 'G12-N13: fixed workload') + invocation = manifest['invocation'] + _need(invocation['stage'] == 'g12-reference-custody-v1' and invocation['job'] == 'g12-reference' and + type(invocation['label']) is str and bool(invocation['label']) and + all(c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_' for c in invocation['label']), + 'G12-N13: fixed invocation role') + for name in ('stage_sha256', 'jobs_sha256', 'launch_selection_sha256'): + _need(_digest(invocation[name]), 'G12-N12: invocation digest') + sources = manifest['selected_sources'] + for name, pin in sources.items(): + if name != 'engine': + _source_pin(pin) + for name, expected in (('guard', _GUARD_PIN), ('root', _ROOT_PIN), ('provider', _PROVIDER_PIN), + ('producer', _PRODUCER_PIN), ('authority', _AUTHORITY_PIN)): + _need(sources[name]['sha256'] == expected and sources[name]['mode'] == '0444', + 'G12-N02: selected original source mismatch') + _need(sources['producer']['bytes'] == 70246 and sources['parent']['path'] == parent_path and + sources['parent']['sha256'] == parent_sha, 'G12-N02: selected producer/parent identity') + _need(_exact(sources['engine'], _ENGINE_PINS), 'G12-N02: exact original engine source pins') + for name, expected in _OTHER_SOURCE_PINS.items(): + _need(sources[name]['sha256'] == expected, 'G12-N02: selected original dependency mismatch') + terminal = {'actual_popen_returncode': 0, 'wait_completed': True, 'parent_stop': None, + 'primary_error': None, 'secondary_errors': [], 'guard_receipt_missing': False} + _need(_exact(manifest['terminal'], terminal), 'G12-N06: authenticated terminal data rejects') + cleanup = manifest['cleanup'] + _need(_exact(cleanup['remaining'], []) and _exact(cleanup['current_children'], []) and + cleanup['known_streams_closed'] is True and cleanup['known_pidfds_closed'] is True and + cleanup['io_unknown'] is False and type(cleanup['owned_generations']) is list and + bool(cleanup['owned_generations']) and _exact(cleanup['operating_premises'], _OPERATING_PREMISES), + 'G12-N08: known selected chain custody rejects') + for name in ('parent_pid', 'parent_start_ticks', 'guard_pid', 'guard_start_ticks', 'guard_pgid', 'guard_sid'): + _uint(manifest['launch'][name], True) + label = invocation['label'] + stage = _R + '/stages/g12-reference-custody-v1' + science = _R + '/runtime/runs/' + label + '/science' + parent_argv, root_argv, producer_argv = _fixed_argv(label, sources) + launch = manifest['launch'] + _need(_exact(launch['parent_guard_argv'], parent_argv) and _exact(launch['guard_root_argv'], root_argv) and + _exact(launch['adapter_producer_argv'], producer_argv) and launch['cwd'] == _R and + _exact(launch['environment'], _ENV) and _exact(launch['flags'], list(_FLAGS)), + 'G12-N03: exact fixed launch/adapter argv') + retained = _R + '/runtime/g12-reference-parent-custody-v1/' + label + custody = manifest['custody'] + _need(custody['retained_directory'] == retained and custody['retained_file_mode'] == '0444' and + custody['created_after_known_cleanup'] is True and custody['source_selection_required'] is True and + custody['known_close_policy'] == 'Any unknown close rejects publication', 'G12-N14: custody ownership') + _fields(custody['retained_directory_identity'], _ID_NAMES) + _need(custody['retained_directory_identity']['full_st_mode'] == stat.S_IFDIR | 0o500, + 'G12-N14: final retained directory mode') + for name in ('common', 'diagnostics'): + pair = manifest['pair'][name] + _fields(pair, ('original', 'retained')) + _file_record(pair['original']) + _file_record(pair['retained']) + filename = 'g12-reference.' + name + '.json' + _need(pair['original']['path'] == science + '/' + filename and + pair['retained']['path'] == retained + '/' + filename and + pair['original']['sha256'] == pair['retained']['sha256'] and + pair['original']['bytes'] == pair['retained']['bytes'] and + pair['retained']['identity']['full_st_mode'] == stat.S_IFREG | 0o444, + 'G12-N13: original/retained complete pair join') + _need(_digest(manifest['pair']['common_payload_sha256']), 'G12-N13: payload pin') + for name, record in manifest['retained_evidence'].items(): + _file_record(record) + _need(record['path'] == retained + '/' + _EVIDENCE_NAMES[name] and + record['identity']['full_st_mode'] == stat.S_IFREG | 0o444, + 'G12-N14: retained raw evidence path/mode') + for name, evidence_name in (('start', 'guard_START'), ('receipt', 'guard_receipt'), + ('stdout', 'guard_stdout'), ('stderr', 'guard_stderr'), ('usage', 'guard_usage')): + _need(_exact(manifest['guard'][name], manifest['retained_evidence'][evidence_name]), + 'G12-N07: guard retained record join') + _need(_exact(launch['launch_record'], manifest['retained_evidence']['parent_launch']) and + _exact(cleanup['observations_record'], manifest['retained_evidence']['parent_owned_observations']), + 'G12-N08: parent observation record join') + account = manifest['accounting'] + _need(account['clock'] == 'monotonic_ns' and account['complete_tail_accounting_required'] is True and + _exact(account['categories'], list(_COST_CATEGORIES)), 'G12-N15: full cost categories/tail') + for name in ('parent_entry_ns', 'preseal_end_ns', 'parent_preseal_wall_ns'): + _uint(account[name]) + _need(account['preseal_end_ns'] >= account['parent_entry_ns'] and + account['parent_preseal_wall_ns'] == account['preseal_end_ns'] - account['parent_entry_ns'], + 'G12-N15: actual parent clock endpoints') + for name in ('parent_self_user_seconds', 'parent_self_system_seconds', 'parent_children_user_seconds', + 'parent_children_system_seconds', 'parent_lifetime_max_rss_kib', 'guard_runner_wall_seconds'): + _number(account[name]) + _need(account['unmeasured_final_tail'] is None, 'G12-N15: unmeasured tail must stay explicitly unknown') + _need(_exact(account['guard_usage'], manifest['guard']['receipt_fields']['usage']) and + _exact(account['guard_runner_wall_seconds'], manifest['guard']['receipt_fields']['runner_wall_seconds']), + 'G12-N15: actual guard cost join') + _need(manifest['scope'] == _SCOPE, 'G12-N18: custody scope cannot become scientific approval') + + +def _fixed_argv(label, sources): + stage = _R + '/stages/g12-reference-custody-v1' + science = _R + '/runtime/runs/' + label + '/science' + parent = ['/usr/bin/python3.12', *_FLAGS, _R + '/run_guarded_v3.py', + 'g12-reference-custody-v1', 'g12-reference', label] + root = ['/usr/bin/python3.12', *_FLAGS, stage + '/integration/full_driver.py', + '--root-sha256', _ROOT_PIN, '--provider', stage + '/integration/probe_binding_v3.py', + _PROVIDER_PIN, '--driver', stage + '/integration/g12_reference_adapter_v1.py', + sources['adapter']['sha256'], '--integration', stage + '/integration', '--', + '--output', science, '--lanes', 'g12-reference'] + producer = [stage + '/baseline/full_driver.py', '--frozen-root', stage + '/baseline/frozen', + '--reference', stage + '/baseline/reference/certificates/complex-network.json', + '--mode', 'profile', '--output', science] + return parent, root, producer + + +def _validate_publication(publication, manifest, manifest_record): + _fields(publication, _PUBLICATION_SCHEMA['exact_fields']) + _need(publication['schema'] == _PUBLICATION_SCHEMA['schema_literal'] and + publication['parent_source_sha256'] == manifest['selected_sources']['parent']['sha256'] and + publication['launch_selection_sha256'] == manifest['invocation']['launch_selection_sha256'] and + publication['manifest_path'] == manifest_record['path'] and + publication['manifest_sha256'] == manifest_record['sha256'] and + publication['manifest_bytes'] == manifest_record['bytes'] and + _exact(publication['manifest_identity'], manifest_record['identity']) and + _exact(publication['retained_pair_sha256'], {name: manifest['pair'][name]['retained']['sha256'] + for name in ('common', 'diagnostics')}) and + publication['final_pair_recheck_complete'] is True and publication['known_lease_close_completed'] is True and + publication['primary_error'] is None and _exact(publication['secondary_errors'], []) and + publication['complete_cost_qualification'] is False and + _exact(publication['unmeasured_final_tail'], manifest['accounting']['unmeasured_final_tail']), + 'G12-N15: exact publication/manifest/final-tail join') + _uint(publication['measured_through_ns']) + _need(publication['measured_through_ns'] >= manifest['accounting']['preseal_end_ns'], + 'G12-N15: publication clock precedes preseal') + costs = publication['actual_costs_through_ns'] + _fields(costs, ('entry_ns', 'through_ns', 'wall_ns', 'self_user_seconds', 'self_system_seconds', + 'children_user_seconds', 'children_system_seconds', 'lifetime_max_rss_kib')) + for name in ('entry_ns', 'through_ns', 'wall_ns'): + _uint(costs[name]) + _need(costs['entry_ns'] == manifest['accounting']['parent_entry_ns'] and + costs['through_ns'] == publication['measured_through_ns'] and + costs['wall_ns'] == costs['through_ns'] - costs['entry_ns'], 'G12-N15: publication actual clock join') + for name in ('self_user_seconds', 'self_system_seconds', 'children_user_seconds', + 'children_system_seconds', 'lifetime_max_rss_kib'): + _number(costs[name]) + + +def _source_code_shape(code): + _need(type(code) is CodeType, 'G12-N04: exact code type') + def constant(value): + kind = type(value) + if value is None or value is Ellipsis: + return ('singleton', value is Ellipsis) + if kind in (int, bool, str, bytes): + return (kind.__name__, value) + if kind is float: + return ('float', value.hex()) + if kind is tuple: + return ('tuple', tuple(constant(item) for item in value)) + if kind is frozenset: + return ('frozenset', tuple(sorted(constant(item) for item in value))) + if kind is CodeType: + return ('code', _source_code_shape(value)) + raise RuntimeError('G12-N04: unsupported source code constant') + return tuple(constant(value) for value in ( + code.co_argcount, code.co_posonlyargcount, code.co_kwonlyargcount, + code.co_nlocals, code.co_stacksize, code.co_flags, code.co_code, + code.co_names, code.co_varnames, code.co_freevars, code.co_cellvars, + code.co_exceptiontable, code.co_linetable, code.co_firstlineno, + code.co_filename, code.co_name, code.co_qualname, code.co_consts)) + + +_R = '/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/h25-data-handling-20261028' + + +_ENGINE_PINS = {'compare_side_verifier.py': '6e507bb0c7e00d090a60289fddb6c55e90c946d0850c42c3c5e3e15c27604a68', + 'finite_controls.py': 'df989a831aac43cc1af95169dad8c64a7548760e6e1f96976da996703f2c8f7a', + 'native_backend.py': 'e473c38245c3668715b5a78dfe980b2fe3ed0d0c9b8c97c666fbae6ecf1fffd5', + 'native_gf2.c': 'e9c3c9194a08718bd1575c1cf08c6c6772d3b644c2e274c25a84a1f9249d06cc', + 'profile_side_verifier.py': '9c994378171c20a91539418d93cb8387e1daa93465d6862beefea90e12999c2a', + 'source/complex_circuit.py': 'd623617f7c5cb3189580883a8ab30c0bd3832688ae3f1f0c1f881bbbbff8e0c1', + 'source/complex_network.py': '0da395e67ac04fa213494e71012c1b19b544596d34cdce5a3b172b1fb6af5f1b'} + + +_OTHER_SOURCE_PINS = {'cleanup_leaf_origin': '7b3304eaf4884e3029df5095e2b0950c18d1544ad21431a07c033b85e53bd4f7', + 'reference': '1f763d95c7ff163aa71d13cd82784f16665be8afb21f75e76941e2119562098f', + 'runtime_profile': 'ad0ec2aea01b83f97bdeafd9e9208360127fee870d024d353879b5ed99237109', + 'source_pins': '88bba3caf5975f30fa7abceaea9454110cf3b069233e8241a2ca13d1dff171a7'} + + +_OPERATING_PREMISES = ('Selected fixed scientific sources, adapter and ordinary profile branch do not fork/spawn threads, ' + 'daemonize, pass writable descriptors to outsiders, or enlist external writers. Trusted ' + 'OS/loader/interpreter/stdlib and cooperating same-user parent launch domain exclude unrelated writer ' + 'interference. This is an explicit finite source/operating premise, not established merely by a clean /proc ' + 'snapshot.') + + +_SCOPE = ('Fixed source-data custody only. No G12/P02/full-positive/native/performance/scientific admission; no ' + 'universal writers theorem.') + + +_FLAGS = ('-S', '-s', '-P', '-B') + + +_ENV = {'LANG': 'C.UTF-8', + 'LC_ALL': 'C.UTF-8', + 'PATH': '/usr/bin:/bin', + 'PYTHONDONTWRITEBYTECODE': '1', + 'PYTHONHASHSEED': '0', + 'TZ': 'UTC'} + + +_EVIDENCE_NAMES = {'guard_START': 'guard-START.json', + 'guard_receipt': 'guard-receipt.json', + 'guard_stderr': 'guard-stderr.txt', + 'guard_stdout': 'guard-stdout.txt', + 'guard_usage': 'guard-usage.json', + 'parent_launch': 'parent-LAUNCH.json', + 'parent_outer_stderr': 'parent-outer-stderr.txt', + 'parent_outer_stdout': 'parent-outer-stdout.txt', + 'parent_owned_observations': 'parent-owned-observations.json', + 'parent_preseal_accounting': 'parent-preseal-accounting.json'} + + + +def _proc(pid): + # Derived from original supervisor proc; PermissionError is never absence. + descriptor, primary, secondaries, result = None, None, _RawG12Errors(), None + try: + descriptor = os.open('/proc/' + str(pid) + '/stat', os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC) + raw = os.read(descriptor, 8193) + _need(len(raw) <= 8192 and os.read(descriptor, 1) == b'', 'G12-N08: process-stat finite bound') + end = raw.rfind(b') ') + _need(end >= 0 and raw.split(b' ', 1)[0] == str(pid).encode('ascii'), 'G12-N08: process-stat PID') + fields = raw[end + 2:].split() + _need(len(fields) >= 22 and fields[0] in (b'R', b'S', b'D', b'Z', b'T', b't', b'X', b'x', b'I', b'K', b'W', b'P'), + 'G12-N08: process-stat shape/state') + result = {'pid': pid, 'ppid': int(fields[1]), 'pgid': int(fields[2]), 'sid': int(fields[3]), + 'start_ticks': int(fields[19]), 'state': fields[0].decode('ascii'), + 'rss_bytes': int(fields[21]) * os.sysconf('SC_PAGE_SIZE')} + for key in ('pid', 'ppid', 'pgid', 'sid', 'start_ticks', 'rss_bytes'): + _uint(result[key], key in ('pid', 'start_ticks')) + except (FileNotFoundError, ProcessLookupError): + result = None + except BaseException as error: + primary = error, error.__traceback__ + if descriptor is not None: + try: + os.close(descriptor) + except BaseException as error: + secondaries.append((error, error.__traceback__)) + _raise_preserved(primary, secondaries) + return result + + +def _census(): + rows = {} + with os.scandir('/proc') as entries: + for entry in entries: + if entry.name.isdecimal(): + _need(len(rows) < 65536, 'G12-N08: finite process census bound') + row = _proc(int(entry.name)) + if row is not None: + rows[row['pid']] = row + return rows + + +def _children(): + return [row for row in _census().values() if row['ppid'] == os.getpid()] + + +class _KnownG12Chain: + """Scoped generation/pidfd observation only; never universal writer proof.""" + def __init__(self): + _need(not _children(), 'G12-N08: initial parent child domain must be empty') + _need(os.listdir('/proc/self/task') == [str(os.getpid())], 'G12-N08: single initial parent task') + self.rows, self.fds, self.groups, self.observations = {}, {}, set(), [] + self.parent_pid = os.getpid() + self.parent_group = os.getpgrp() + self.closed = False + self.unknown = False + + def add(self, row): + key = row['pid'], row['start_ticks'] + if key in self.rows: + _need(self.rows[key]['pid'] == row['pid'], 'G12-N08: owned generation identity') + if row['pgid'] != self.parent_group: + self.groups.add((row['pgid'], row['sid'])) + return + _need(row['pid'] != self.parent_pid and len(self.rows) < 128, 'G12-N08: fixed owned process bound') + descriptor = os.pidfd_open(row['pid'], 0) + # A failed/ambiguous adoption rejects; never treat it as known closure. + self.fds[key] = descriptor + current = _proc(row['pid']) + _need(current is not None and (current['pid'], current['start_ticks']) == key, + 'G12-N08: process generation changed during pidfd adoption') + self.rows[key] = dict(current) + if current['pgid'] != self.parent_group: + self.groups.add((current['pgid'], current['sid'])) + + def observe(self): + _need(not self.closed, 'G12-N08: closed observation domain') + rows = _census() + known = {pid for pid, start in self.rows if pid in rows and rows[pid]['start_ticks'] == start} + for pid in known: + self.add(rows[pid]) + changed = True + while changed: + changed = False + for pid, row in rows.items(): + if pid not in known and (row['ppid'] == self.parent_pid or row['ppid'] in known): + self.add(row) + known.add(pid) + changed = True + occupied = [row for row in rows.values() if (row['pgid'], row['sid']) in self.groups] + current = [rows[pid] for pid in known] + _need(len(self.observations) < 4096, 'G12-N08: finite observation retention') + self.observations.append({'monotonic_ns': time.monotonic_ns(), 'current': current, 'occupied_groups': occupied}) + return rows, current, occupied + + def stop_known(self): + self.observe() + for key, descriptor in self.fds.items(): + current = _proc(key[0]) + if current is not None: + _need((current['pid'], current['start_ticks']) == key, 'G12-N08: generation ambiguity before signal') + if current['state'] != 'Z': + try: + signal.pidfd_send_signal(descriptor, signal.SIGKILL, None, 0) + except ProcessLookupError: + pass + + def finish(self, process, deadline, failed): + _need(type(deadline) is int, 'G12-N08: selected paid cleanup deadline') + current, occupied = [], [] + while True: + if failed: + self.stop_known() + if process is not None: + process.poll() + _, current, occupied = self.observe() + if not current and not occupied and not _children(): + break + if not failed or time.monotonic_ns() >= deadline: + raise RuntimeError('G12-N08: selected-chain cleanup UNKNOWN') + time.sleep(0.01) + primary, secondaries = None, _RawG12Errors() + for key, descriptor in tuple(self.fds.items()): + try: + os.close(descriptor) + del self.fds[key] + except BaseException as error: + self.unknown = True + secondaries.append((error, error.__traceback__)) + self.closed = not self.fds and not self.unknown + _raise_preserved(primary, secondaries) + return {'operating_premises': _OPERATING_PREMISES, + 'owned_generations': list(self.rows.values()), + 'observed_groups': [{'pgid': g, 'sid': s} for g, s in sorted(self.groups)], + 'remaining': [], 'current_children': [], 'known_streams_closed': False, + 'known_pidfds_closed': self.closed, 'io_unknown': self.unknown, + 'lease_identity': None, 'science_directory_identity': None, + 'observations_record': None} + + +def _trusted_parent_launch(): + _need(sys.executable == '/usr/bin/python3.12' and sys.flags.optimize == 0 and + sys.flags.no_site == sys.flags.no_user_site == sys.flags.dont_write_bytecode == 1 and + sys.flags.safe_path and sys.flags.ignore_environment == sys.flags.isolated == sys.flags.hash_randomization == 0, + 'G12-N02: original clean parent interpreter flags') + _need(dict(os.environ) == _ENV and tuple(sys.path) == + ('/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload'), + 'G12-N02: original clean environment/search path') + _need(sys.gettrace() is None and sys.getprofile() is None, 'G12-N04: no parent tracing callbacks') + + +def _exclusive_directory(path): + parent, name = _path(path).rsplit('/', 1) + fds, rows = _directory_chain(parent) + primary, secondaries, result = None, _RawG12Errors(), None + try: + os.mkdir(name, 0o700, dir_fd=fds[-1]) + descriptor = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=fds[-1]) + fds.append(descriptor) + current = os.fstat(descriptor) + _need(current.st_mode == stat.S_IFDIR | 0o700, 'G12-N14: new parent directory mode') + rows.append((fds[-2], name, descriptor, _directory_key(current))) + _check_chain(rows) + result = fds, rows + except BaseException as error: + primary = error, error.__traceback__ + if primary is not None: + for descriptor in reversed(fds): + try: + os.close(descriptor) + except BaseException as error: + secondaries.append((error, error.__traceback__)) + _raise_preserved(primary, secondaries) + return result + + +def _write_fd(descriptor, raw): + _need(type(raw) is bytes, 'G12-N14: exact retained byte copy') + offset, hasher = 0, hashlib.sha256() + while offset < len(raw): + block = raw[offset:offset + _CHUNK] + written = os.write(descriptor, block) + _need(type(written) is int and 0 < written <= len(block), 'G12-N14: complete copy write progress') + hasher.update(block[:written]) + offset += written + _need(offset == len(raw) and hasher.hexdigest() == hashlib.sha256(raw).hexdigest(), + 'G12-N14: complete copied byte digest') + os.fsync(descriptor) + os.fchmod(descriptor, 0o444) + os.fsync(descriptor) + + +def _copy_file(directory, name, raw): + fds, rows = directory + descriptor = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, dir_fd=fds[-1]) + primary, secondaries = None, _RawG12Errors() + try: + _write_fd(descriptor, raw) + _check_chain(rows) + except BaseException as error: + primary = error, error.__traceback__ + try: + os.close(descriptor) + except BaseException as error: + secondaries.append((error, error.__traceback__)) + _raise_preserved(primary, secondaries) + os.fsync(fds[-1]) + + +def _actual_costs(entry_ns, own_start, children_start): + through = time.monotonic_ns() + own, children = resource.getrusage(resource.RUSAGE_SELF), resource.getrusage(resource.RUSAGE_CHILDREN) + return {'entry_ns': entry_ns, 'through_ns': through, 'wall_ns': through - entry_ns, + 'self_user_seconds': own.ru_utime - own_start.ru_utime, + 'self_system_seconds': own.ru_stime - own_start.ru_stime, + 'children_user_seconds': children.ru_utime - children_start.ru_utime, + 'children_system_seconds': children.ru_stime - children_start.ru_stime, + 'lifetime_max_rss_kib': own.ru_maxrss} + + +def run_g12_reference(): + """P01: one source-private invocation; accepts no caller completion data.""" + configured = G12_REFERENCE_LAUNCH_SELECTION + _need(type(configured) is dict, 'G12-N01: exact immutable launch source literal remains None') + _need(type(_INITIAL_PARENT_SOURCE_PIN) is dict and configured['source_pins']['parent'] is None, + 'G12-N02: independent initial external parent source pin; no self-hash literal') + _source_pin(_INITIAL_PARENT_SOURCE_PIN) + configured_bytes = _canonical(configured) + selection = dict(configured) + selection['source_pins'] = dict(configured['source_pins']) + selection['source_pins']['parent'] = dict(_INITIAL_PARENT_SOURCE_PIN) + # Actual launch remains closed. The independently reviewed source scope + # correction requires the complete symbolic bill, not a new financial API. + entry_ns = time.monotonic_ns() + own_start, children_start = resource.getrusage(resource.RUSAGE_SELF), resource.getrusage(resource.RUSAGE_CHILDREN) + selection_bytes = _canonical(selection) + selection_sha = hashlib.sha256(selection_bytes).hexdigest() + parent_graph = _capture_graph(globals()) + phase, stage_data, stage_record, jobs_record, phase_record = None, None, None, None, None + source_records, originals, evidence, retained_records = {}, {}, {}, {} + parent_identity = _proc(os.getpid()) + process, chain, lease, lease_identity = None, None, None, None + lease_closed, attempted, wait_completed = False, False, False + outer = {} + observation, retained, science_directory, run_directory = None, None, None, None + primary, secondaries, parent_stop = None, _RawG12Errors(), None + cleanup, common, diagnostic, common_payload = None, None, None, None + start, receipt, usage, launch = None, None, None, None + manifest, manifest_record, publication_record = None, None, None + reserved = {} + candidate_pin = None + + def current(): + _need(G12_REFERENCE_LAUNCH_SELECTION is configured and _canonical(configured) == configured_bytes and + _canonical(selection) == selection_bytes and _exact(selection['source_pins']['parent'], _INITIAL_PARENT_SOURCE_PIN), + 'G12-N16: selected launch source changed') + _current_graph(parent_graph) + _need(_proc(os.getpid())['start_ticks'] == parent_identity['start_ticks'], 'G12-N08: parent generation') + _need(os.listdir('/proc/self/task') == [str(os.getpid())], 'G12-N08: parent thread domain changed') + if lease is not None and not lease_closed: + _need(_identity(os.fstat(lease)) == lease_identity and os.fstat(lease).st_nlink == 1, + 'G12-N08: actual parent lease identity changed') + for domain in (observation, retained, science_directory, run_directory): + if domain is not None: + _check_chain(domain[1]) + + def _g12_preflight_and_claim(): + """P02: exact source/phase/namespace gate; separate parent-queue lease.""" + nonlocal phase, stage_data, stage_record, jobs_record, phase_record, chain + nonlocal lease, lease_identity, observation + _fields(selection, ('schema', 'stage', 'job', 'label', 'stage_sha256', 'jobs_sha256', 'source_pins', + 'phase_pin', 'body_deadline_ns', 'retention_tail_allowance_ns', + 'parent_observation_directory', 'parent_retained_directory')) + _need(selection['schema'] == 'g12-one-reference-launch-selection-v1' and + selection['stage'] == 'g12-reference-custody-v1' and selection['job'] == 'g12-reference', + 'G12-N02: fixed G12 launch role') + label = selection['label'] + _need(type(label) is str and bool(label) and + all(c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_' for c in label), + 'G12-N03: fixed selected guard label') + _need(selection['parent_observation_directory'] == _R + '/runtime/g12-reference-parent-observation-v1/' + label and + selection['parent_retained_directory'] == _R + '/runtime/g12-reference-parent-custody-v1/' + label, + 'G12-N02: fixed parent namespace') + _uint(selection['body_deadline_ns'], True) + _uint(selection['retention_tail_allowance_ns'], True) + _need(selection['body_deadline_ns'] > entry_ns, 'G12-N05: no remaining complete body allowance') + _trusted_parent_launch() + sources = selection['source_pins'] + _fields(sources, _MANIFEST_SCHEMA['selected_sources_exact_fields']) + _need(_exact(sources['engine'], _ENGINE_PINS), 'G12-N02: exact seven original engine pins') + for name, pin in sources.items(): + if name == 'engine': + continue + _source_pin(pin) + observed, raw = _read_file(pin['path'], max(pin['bytes'], 1), int(pin['mode'], 8)) + _need(observed['sha256'] == pin['sha256'] and observed['bytes'] == pin['bytes'], + 'G12-N02: selected source bytes/modes') + source_records[name] = observed, raw + _need(sources['parent']['path'] == __file__, 'G12-N04: external parent source selection') + for name, expected in (('guard', _GUARD_PIN), ('root', _ROOT_PIN), ('provider', _PROVIDER_PIN), + ('producer', _PRODUCER_PIN), ('authority', _AUTHORITY_PIN)): + _need(sources[name]['sha256'] == expected and sources[name]['mode'] == '0444', 'G12-N02: original source pin') + for name, expected in _OTHER_SOURCE_PINS.items(): + _need(sources[name]['sha256'] == expected, 'G12-N02: original dependency pin') + _source_pin(selection['phase_pin']) + phase_record, phase_raw = _read_file(selection['phase_pin']['path'], _META_CAP, + int(selection['phase_pin']['mode'], 8)) + _need(selection['phase_pin']['path'] == _R + '/control/EXECUTION-PHASE.json' and + phase_record['sha256'] == selection['phase_pin']['sha256'] and + phase_record['bytes'] == selection['phase_pin']['bytes'], 'G12-N05: original phase identity') + phase = _json(phase_raw, _META_CAP) + _need(type(phase['aggregate_cap_seconds']) is int and phase['aggregate_cap_seconds'] in (600, 2400), + 'G12-N05: original unchanged aggregate cap') + stage = _R + '/stages/g12-reference-custody-v1' + stage_record, stage_raw = _read_file(stage + '/STAGE.json', _META_CAP, 0o444) + jobs_record, jobs_raw = _read_file(stage + '/JOBS.json', _META_CAP, 0o444) + _need(stage_record['sha256'] == selection['stage_sha256'] and + jobs_record['sha256'] == selection['jobs_sha256'], 'G12-N02: independently selected stage/jobs') + stage_data = _json(stage_raw, _META_CAP) + jobs = _json(jobs_raw, _META_CAP) + _need(_exact(jobs, {'g12-reference': {'bootstrap': {'driver': 'integration/g12_reference_adapter_v1.py', + 'provider': 'integration/probe_binding_v3.py'}, 'lanes': 'g12-reference', 'optimized': False}}), + 'G12-N03: exact only-job bootstrap/lanes/no-finite/no-optimization') + _need(stage_data['runner_sha256'] == _GUARD_PIN, 'G12-N02: original runner source') + for relative, row in stage_data['files'].items(): + _need(type(relative) is str and all(x not in ('', '.', '..') for x in relative.split('/')) and + not relative.startswith('/'), 'G12-N02: stage closure relative path') + _fields(row, ('sha256', 'mode')) + _need(type(row['mode']) is int, 'G12-N02: original source mode') + observed, _ = _read_file(stage + '/' + relative, 16777216, row['mode']) + _need(observed['sha256'] == row['sha256'], 'G12-N02: complete staged source closure') + # Exact census rejects undeclared files/directories/symlinks, including an + # alternate staged authority. Walk source paths only; no runtime payloads. + actual = set() + for path, dirs, files in os.walk(stage, followlinks=False): + for name in dirs: + _need(stat.S_ISDIR(os.lstat(path + '/' + name).st_mode), 'G12-N02: stage directory symlink') + for name in files: + full = path + '/' + name + _need(stat.S_ISREG(os.lstat(full).st_mode), 'G12-N02: stage nonregular source') + relative = full[len(stage) + 1:] + if relative != 'STAGE.json': + actual.add(relative) + _need(actual == set(stage_data['files']), 'G12-N02: exact staged closure census') + for name, pin in sources.items(): + if name not in ('engine', 'parent', 'guard', 'cleanup_leaf_origin'): + _need(pin['path'].startswith(stage + '/'), 'G12-N02: selected source outside new stage') + relative = pin['path'][len(stage) + 1:] + _need(stage_data['files'][relative] == {'sha256': pin['sha256'], 'mode': int(pin['mode'], 8)}, + 'G12-N02: selected source/stage binding') + chain = _KnownG12Chain() + for path in (_R + '/runtime/runs/' + label, selection['parent_observation_directory'], + selection['parent_retained_directory']): + parent, name = path.rsplit('/', 1) + fds, rows = _directory_chain(parent) + try: + try: + os.stat(name, dir_fd=fds[-1], follow_symlinks=False) + except FileNotFoundError: + pass + else: + raise RuntimeError('G12-N05: prior output/evidence/custody path exists') + _check_chain(rows) + finally: + _finally_close_known(fds, secondaries) + # Separate from the original guard's science.lock. No contention wait. + lock_path = _R + '/runtime/parent-queue.lock' + parent_fds, parent_rows = _directory_chain(_R + '/runtime') + try: + lease = os.open('parent-queue.lock', os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, dir_fd=parent_fds[-1]) + info = os.fstat(lease) + _need(stat.S_ISREG(info.st_mode) and info.st_nlink == 1, 'G12-N08: parent lease type/link') + lease_identity = _identity(info) + fcntl.flock(lease, fcntl.LOCK_EX | fcntl.LOCK_NB) + _check_chain(parent_rows) + _need(_identity(os.stat('parent-queue.lock', dir_fd=parent_fds[-1], follow_symlinks=False)) == lease_identity, + 'G12-N08: parent lease name identity') + finally: + _finally_close_known(parent_fds, secondaries) + observation = _exclusive_directory(selection['parent_observation_directory']) + current() + + def _g12_launch_once(): + """P03: retain the actual Popen, actual descriptors and generation.""" + nonlocal process, attempted, launch + _need(not attempted and process is None, 'G12-N06: no second launch attempt') + current() + parent_argv, root_argv, producer_argv = _fixed_argv(selection['label'], selection['source_pins']) + for name in ('stdout', 'stderr'): + outer[name] = os.open('outer-' + name + '.txt', + os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, dir_fd=observation[0][-1]) + attempted = True + process = subprocess.Popen(parent_argv, cwd=_R, env=dict(_ENV), stdout=outer['stdout'], + stderr=outer['stderr'], close_fds=True, start_new_session=True) + _need(type(process) is subprocess.Popen and type(process.pid) is int and process.pid > 0, + 'G12-N06: actual Popen object/PID') + row = _proc(process.pid) + _need(row is not None and row['ppid'] == os.getpid() and + row['pgid'] == process.pid and row['sid'] == process.pid, 'G12-N06: actual new guard generation/session') + chain.add(row) + launch = {'parent_pid': parent_identity['pid'], 'parent_start_ticks': parent_identity['start_ticks'], + 'guard_pid': row['pid'], 'guard_start_ticks': row['start_ticks'], + 'guard_pgid': row['pgid'], 'guard_sid': row['sid'], 'parent_guard_argv': parent_argv, + 'guard_root_argv': root_argv, 'adapter_producer_argv': producer_argv, + 'cwd': _R, 'environment': dict(_ENV), 'flags': list(_FLAGS), 'launch_record': None} + raw = _canonical({'schema': 'g12-parent-actual-launch-v1', 'selection_sha256': selection_sha, 'source_selection': selection, + 'launch': {k: v for k, v in launch.items() if k != 'launch_record'}}) + b'\n' + _copy_file(observation, 'LAUNCH.json', raw) + evidence['parent_launch'] = _read_file(selection['parent_observation_directory'] + '/LAUNCH.json', _META_CAP, 0o444) + + def _g12_observe_wait_and_close(): + """P04: actual wait and scoped known-chain closure; no status substitute.""" + nonlocal wait_completed, cleanup, parent_stop + _need(process is not None and type(process) is subprocess.Popen, 'G12-N06: missing retained actual Popen') + while process.poll() is None: + _, children, occupied = chain.observe() + if time.monotonic_ns() >= selection['body_deadline_ns']: + parent_stop = 'selected_complete_body_deadline' + elif sum(row['rss_bytes'] for row in children) > 1073741824: + parent_stop = 'selected_known_chain_rss_cap' + elif resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * 1024 > 1073741824: + parent_stop = 'parent_lifetime_rss_cap' + elif any(os.fstat(descriptor).st_size > _LOG_CAP for descriptor in outer.values()): + parent_stop = 'parent_outer_log_cap' + if parent_stop: + raise RuntimeError('G12-N06: parent STOP: ' + parent_stop) + current() + time.sleep(0.05) + code = process.wait() + wait_completed = True + _need(type(code) is int and code == 0 and type(process.returncode) is int and process.returncode == 0, + 'G12-N06: actual guard wait returncode') + cleanup = chain.finish(process, selection['body_deadline_ns'] + selection['retention_tail_allowance_ns'], False) + for name, descriptor in tuple(outer.items()): + os.fsync(descriptor) + os.close(descriptor) + del outer[name] + cleanup['known_streams_closed'] = not outer + cleanup['lease_identity'] = lease_identity + _need(parent_stop is None and cleanup['known_pidfds_closed'] and not cleanup['io_unknown'], + 'G12-N08: complete known closes') + current() + + def _g12_join_original_guard_evidence(): + """P05: retain complete canonical originals; never reconstruct receipt.""" + nonlocal start, receipt, usage, science_directory, run_directory + run = _R + '/runtime/runs/' + selection['label'] + run_directory = _directory_chain(run) + science_directory = _directory_chain(run + '/science') + cleanup['science_directory_identity'] = _identity(os.fstat(science_directory[0][-1])) + fixed = {'guard_START': ('START.json', _META_CAP), 'guard_receipt': ('receipt.json', _META_CAP), + 'guard_stdout': ('stdout.txt', _LOG_CAP), 'guard_stderr': ('stderr.txt', _LOG_CAP), + 'guard_usage': ('usage.json', 16384)} + for name, (filename, cap) in fixed.items(): + evidence[name] = _read_file(run + '/' + filename, cap) + for name in ('stdout', 'stderr'): + evidence['parent_outer_' + name] = _read_file(selection['parent_observation_directory'] + '/outer-' + name + '.txt', _LOG_CAP) + start = _json(evidence['guard_START'][1], _META_CAP) + receipt = _json(evidence['guard_receipt'][1], _META_CAP) + usage = _json(evidence['guard_usage'][1], 16384) + invocation = {'job': selection['job'], 'label': selection['label'], 'stage_sha256': selection['stage_sha256']} + _validate_guard(start, receipt, usage, evidence['guard_stdout'][1], evidence['guard_stderr'][1], + launch['guard_root_argv'], invocation, selection['source_pins'], selection['phase_pin']['sha256']) + fraction, _ = _read_file('/usr/lib/python3.12/fractions.py', 1048576) + _need(start['fractions_sha256'] == fraction['sha256'], 'G12-N07: original fractions source join') + _need(_exact(_json(evidence['parent_outer_stdout'][1], _LOG_CAP), receipt) and + evidence['parent_outer_stderr'][1] == b'', 'G12-N07: actual outer stdout/empty stderr') + current() + + def _g12_collect_complete_pair(): + """P06: complete original common AND diagnostics, followed by joint recheck.""" + nonlocal common, diagnostic, common_payload + _need(wait_completed and process.returncode == 0 and cleanup is not None and receipt is not None, + 'G12-N10: original successful owner/receipt join must precede pair') + science = _R + '/runtime/runs/' + selection['label'] + '/science' + for name in ('common', 'diagnostics'): + originals[name] = _read_file(science + '/g12-reference.' + name + '.json', _PAIR_CAP) + common, diagnostic, common_payload = _validate_pair(originals['common'][1], originals['diagnostics'][1]) + for name in ('common', 'diagnostics'): + _need(_read_file(originals[name][0]['path'], _PAIR_CAP) == originals[name], 'G12-N11: original joint pair changed') + current() + + def _g12_retain_parent_pair_and_evidence(): + """P07: fresh parent directory only after all selected writers are known closed.""" + nonlocal retained + _need(not _children() and cleanup['known_pidfds_closed'] and cleanup['known_streams_closed'], + 'G12-N08: no retained directory until known selected cleanup') + current() + retained = _exclusive_directory(selection['parent_retained_directory']) + for name in ('common', 'diagnostics'): + filename = 'g12-reference.' + name + '.json' + _copy_file(retained, filename, originals[name][1]) + record, raw = _read_file(selection['parent_retained_directory'] + '/' + filename, _PAIR_CAP, 0o444) + _need(raw == originals[name][1] and record['sha256'] == originals[name][0]['sha256'], 'G12-N14: complete retained pair readback') + retained_records[name] = record + observation_raw = _canonical({'schema': 'g12-known-chain-observations-v1', 'cleanup': cleanup, + 'observations': chain.observations}) + b'\n' + _copy_file(observation, 'owned-observations.json', observation_raw) + evidence['parent_owned_observations'] = _read_file(selection['parent_observation_directory'] + '/owned-observations.json', _META_CAP, 0o444) + costs = _actual_costs(entry_ns, own_start, children_start) + accounting_raw = _canonical(costs) + b'\n' + _copy_file(observation, 'preseal-accounting.json', accounting_raw) + evidence['parent_preseal_accounting'] = _read_file(selection['parent_observation_directory'] + '/preseal-accounting.json', _META_CAP, 0o444) + for name in _MANIFEST_SCHEMA['retained_evidence_exact_keys']: + _copy_file(retained, _EVIDENCE_NAMES[name], evidence[name][1]) + record, raw = _read_file(selection['parent_retained_directory'] + '/' + _EVIDENCE_NAMES[name], + max(len(evidence[name][1]), 1), 0o444) + _need(raw == evidence[name][1], 'G12-N14: raw evidence copy differs') + retained_records[name] = record + # Reserve BOTH metadata names before recording final directory identity. + # Existing FD writes/file chmod do not change parent directory entries. + for name in ('manifest.json', 'publication.json'): + reserved[name] = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, dir_fd=retained[0][-1]) + os.fsync(retained[0][-1]) + current() + + def _g12_seal_once(): + """P08: private actual owner seal; returns only a candidate for later adoption.""" + nonlocal manifest, manifest_record, publication_record, candidate_pin, lease_closed + _need(process is not None and type(process) is subprocess.Popen and process.returncode == 0 and + wait_completed and primary is None and not secondaries and parent_stop is None and not _children() and + not outer and not chain.fds and not chain.unknown, 'G12-N08: actual owner final conjunction') + current() + for name, original in originals.items(): + _need(_read_file(original[0]['path'], _PAIR_CAP) == original, 'G12-N11: original pair final drift') + _need(_read_file(retained_records[name]['path'], _PAIR_CAP, 0o444)[0] == retained_records[name], + 'G12-N14: retained pair final drift') + for name, (record, raw) in source_records.items(): + _need(_read_file(record['path'], max(record['bytes'], 1), record['identity']['full_st_mode'] & 0o7777) == (record, raw), + 'G12-N02: complete selected source drift') + for record, raw in evidence.values(): + _need(_read_file(record['path'], max(record['bytes'], 1), record['identity']['full_st_mode'] & 0o7777) == (record, raw), + 'G12-N07: final complete original raw evidence drift') + for record in (stage_record, jobs_record, phase_record): + _need(_read_file(record['path'], _META_CAP, record['identity']['full_st_mode'] & 0o7777)[0] == record, + 'G12-N02: stage/jobs/phase final identity drift') + os.fchmod(retained[0][-1], 0o500) + # Update exactly our owned mode transition, retaining dev/inode binding. + parent, name, descriptor, old = retained[1][-1] + final_dir_info = os.fstat(descriptor) + _need((final_dir_info.st_dev, final_dir_info.st_ino) == old[:2], 'G12-N14: retained directory owner transition') + retained[1][-1] = (parent, name, descriptor, _directory_key(final_dir_info)) + os.fsync(descriptor) + directory_identity = _identity(final_dir_info) + costs = _actual_costs(entry_ns, own_start, children_start) + account = {'clock': 'monotonic_ns', 'parent_entry_ns': entry_ns, + 'preseal_end_ns': costs['through_ns'], 'parent_preseal_wall_ns': costs['wall_ns'], + 'parent_self_user_seconds': costs['self_user_seconds'], 'parent_self_system_seconds': costs['self_system_seconds'], + 'parent_children_user_seconds': costs['children_user_seconds'], 'parent_children_system_seconds': costs['children_system_seconds'], + 'parent_lifetime_max_rss_kib': costs['lifetime_max_rss_kib'], 'guard_usage': usage, + 'guard_runner_wall_seconds': receipt['runner_wall_seconds'], 'categories': list(_COST_CATEGORIES), + 'complete_tail_accounting_required': True, 'unmeasured_final_tail': None} + launch['launch_record'] = retained_records['parent_launch'] + cleanup['observations_record'] = retained_records['parent_owned_observations'] + manifest = {'schema': 'g12-parent-two-export-custody-v2', + 'invocation': {'stage': selection['stage'], 'job': selection['job'], 'label': selection['label'], + 'stage_sha256': selection['stage_sha256'], 'jobs_sha256': selection['jobs_sha256'], + 'launch_selection_sha256': selection_sha}, + 'selected_sources': selection['source_pins'], 'workload': _MANIFEST_SCHEMA['workload_values'], + 'launch': launch, 'terminal': {'actual_popen_returncode': process.returncode, 'wait_completed': wait_completed, + 'parent_stop': parent_stop, 'primary_error': None, 'secondary_errors': [], 'guard_receipt_missing': False}, + 'guard': {'start': retained_records['guard_START'], 'receipt': retained_records['guard_receipt'], + 'start_fields': start, 'receipt_fields': receipt, 'stdout': retained_records['guard_stdout'], + 'stderr': retained_records['guard_stderr'], 'usage': retained_records['guard_usage']}, + 'cleanup': cleanup, + 'pair': {name: {'original': originals[name][0], 'retained': retained_records[name]} for name in ('common', 'diagnostics')}, + 'retained_evidence': {name: retained_records[name] for name in _MANIFEST_SCHEMA['retained_evidence_exact_keys']}, + 'custody': {'retained_directory': selection['parent_retained_directory'], 'retained_directory_identity': directory_identity, + 'retained_file_mode': '0444', 'created_after_known_cleanup': True, 'source_selection_required': True, + 'known_close_policy': 'Any unknown close rejects publication'}, 'accounting': account, 'scope': _SCOPE} + manifest['pair']['common_payload_sha256'] = common['common_payload_sha256'] + _validate_manifest(manifest, selection['source_pins']['parent']['path'], selection['source_pins']['parent']['sha256']) + raw = _canonical(manifest) + b'\n' + _need(len(raw) <= _META_CAP, 'G12-N14: manifest finite metadata cap') + _write_fd(reserved['manifest.json'], raw) + os.close(reserved['manifest.json']) + del reserved['manifest.json'] + os.fsync(retained[0][-1]) + manifest_record, reread = _read_file(selection['parent_retained_directory'] + '/manifest.json', _META_CAP, 0o444) + _need(reread == raw, 'G12-N14: complete manifest readback') + current() + _need(not _children(), 'G12-N08: unexpected child at final lease close') + fcntl.flock(lease, fcntl.LOCK_UN) + os.close(lease) + lease_closed = True + costs = _actual_costs(entry_ns, own_start, children_start) + publication = {'schema': 'g12-parent-custody-publication-v2', + 'parent_source_sha256': selection['source_pins']['parent']['sha256'], 'launch_selection_sha256': selection_sha, + 'manifest_path': manifest_record['path'], 'manifest_sha256': manifest_record['sha256'], + 'manifest_bytes': manifest_record['bytes'], 'manifest_identity': manifest_record['identity'], + 'retained_pair_sha256': {name: retained_records[name]['sha256'] for name in ('common', 'diagnostics')}, + 'final_pair_recheck_complete': True, 'known_lease_close_completed': lease_closed, + 'primary_error': None, 'secondary_errors': [], 'measured_through_ns': costs['through_ns'], + 'actual_costs_through_ns': costs, 'unmeasured_final_tail': None, + 'complete_cost_qualification': False} + _validate_publication(publication, manifest, manifest_record) + publication_raw = _canonical(publication) + b'\n' + _need(len(publication_raw) <= _META_CAP, 'G12-N15: publication metadata cap') + _write_fd(reserved['publication.json'], publication_raw) + os.close(reserved['publication.json']) + del reserved['publication.json'] + os.fsync(retained[0][-1]) + publication_record, observed = _read_file(selection['parent_retained_directory'] + '/publication.json', _META_CAP, 0o444) + _need(observed == publication_raw and _identity(os.fstat(retained[0][-1])) == directory_identity, + 'G12-N15: final publication readback/directory identity') + current() + # This candidate is not a source selection or completed enclosing invoice. + candidate_pin = (manifest_record['path'], manifest_record['sha256'], manifest_record['bytes'], + _handoff_identity_tuple(manifest_record), selection['source_pins']['parent']['path'], + selection['source_pins']['parent']['sha256'], publication_record['path'], + publication_record['sha256'], publication_record['bytes']) + + def _g12_finish_failure(): + """P09: always preserve actual first failure, known cleanup and partial originals.""" + nonlocal lease_closed + # Every later error is retained separately; no receipt or PASS replacement. + if chain is not None and not chain.closed: + try: + chain.finish(process, selection['body_deadline_ns'] + selection['retention_tail_allowance_ns'], True) + except BaseException as error: + secondaries.append((error, error.__traceback__)) + for name, descriptor in tuple(outer.items()): + try: + os.close(descriptor) + del outer[name] + except BaseException as error: + secondaries.append((error, error.__traceback__)) + for name, descriptor in tuple(reserved.items()): + try: + os.close(descriptor) + del reserved[name] + except BaseException as error: + secondaries.append((error, error.__traceback__)) + if lease is not None and not lease_closed: + try: + os.close(lease) + lease_closed = True + except BaseException as error: + secondaries.append((error, error.__traceback__)) + # Failure-tail raw records are never advertised as canonical guard data. + if observation is not None and (primary is not None or secondaries): + try: + failures = {'schema': 'g12-parent-failed-attempt-v1', 'attempted': attempted, + 'actual_returncode': None if process is None else process.returncode, + 'primary': None if primary is None else repr(primary[0]), + 'ordered_secondaries': [repr(item[0]) for item in secondaries], + 'known_cleanup': 'UNKNOWN' if chain is None or not chain.closed else 'KNOWN_SELECTED_CHAIN_ONLY', + 'actual_costs_through_prewrite': _actual_costs(entry_ns, own_start, children_start), + 'enclosing_full_failure_tail_required': True} + _copy_file(observation, 'FAILED-ATTEMPT.json', _canonical(failures) + b'\n') + except BaseException as error: + secondaries.append((error, error.__traceback__)) + for domain in (science_directory, run_directory, retained, observation): + if domain is not None: + for descriptor in reversed(domain[0]): + try: + os.close(descriptor) + except BaseException as error: + secondaries.append((error, error.__traceback__)) + + try: + _g12_preflight_and_claim() + _g12_launch_once() + _g12_observe_wait_and_close() + _g12_join_original_guard_evidence() + _g12_collect_complete_pair() + _g12_retain_parent_pair_and_evidence() + _g12_seal_once() + except BaseException as error: + primary = error, error.__traceback__ + try: + _g12_finish_failure() + except BaseException as error: + # Preserve primary even if a secondary bookkeeping append itself failed. + if primary is None: + primary = error, error.__traceback__ + else: + try: + primary[0].add_note('P09 bookkeeping failure: ' + repr(error)) + except BaseException: + pass + _raise_preserved(primary, secondaries) + _need(candidate_pin is not None and lease_closed and not outer and not reserved, + 'G12-N15: final tail incomplete; manifest remains unselected') + return candidate_pin diff --git a/research/h25-g12-custody-repairs/repairs-from-pr6339.patch b/research/h25-g12-custody-repairs/repairs-from-pr6339.patch new file mode 100644 index 0000000000..d743bb8437 --- /dev/null +++ b/research/h25-g12-custody-repairs/repairs-from-pr6339.patch @@ -0,0 +1,146 @@ +--- a/research/h25-g12-identity-cleanup/corrected/g12_reference_parent_v2.py ++++ b/research/h25-g12-identity-cleanup/corrected/g12_reference_parent_v2.py +@@ -152,6 +152,7 @@ + _need(len(path.split('/')) <= 257, 'G12-N11: finite directory-component bound') + fds, rows = [], [] + primary = None ++ secondary = _RawG12Errors() + try: + fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC) + fds.append(fd) +@@ -168,7 +169,6 @@ + return fds, rows + except BaseException as error: + primary = (error, error.__traceback__) +- secondary = _RawG12Errors() + for descriptor in reversed(fds): + try: + os.close(descriptor) +@@ -242,8 +242,8 @@ + def _read_file(path, cap, mode=None): + _path(path) + parent, name = path.rsplit('/', 1) ++ descriptor, primary, secondary, result = None, None, _RawG12Errors(), None + fds, rows = _directory_chain(parent) +- descriptor, primary, secondary, result = None, None, _RawG12Errors(), None + try: + before = os.stat(name, dir_fd=fds[-1], follow_symlinks=False) + _need(stat.S_ISREG(before.st_mode) and before.st_nlink == 1 and +@@ -1179,6 +1179,21 @@ + except ProcessLookupError: + pass + ++ def release_known_pidfds(self, secondaries): ++ """Release known descriptors after the final process-disposal attempt. ++ ++ A close error leaves custody unknown. Retire numeric ownership before ++ close so that an ambiguous close cannot cause a later blind FD retry. ++ This does not establish process exit or turn unknown cleanup into success. ++ """ ++ for key, descriptor in tuple(self.fds.items()): ++ del self.fds[key] ++ try: ++ os.close(descriptor) ++ except BaseException as error: ++ self.unknown = True ++ secondaries.append((error, error.__traceback__)) ++ + def finish(self, process, deadline, failed): + _need(type(deadline) is int, 'G12-N08: selected paid cleanup deadline') + current, occupied = [], [] +@@ -1194,13 +1209,7 @@ + raise RuntimeError('G12-N08: selected-chain cleanup UNKNOWN') + time.sleep(0.01) + primary, secondaries = None, _RawG12Errors() +- for key, descriptor in tuple(self.fds.items()): +- try: +- os.close(descriptor) +- del self.fds[key] +- except BaseException as error: +- self.unknown = True +- secondaries.append((error, error.__traceback__)) ++ self.release_known_pidfds(secondaries) + self.closed = not self.fds and not self.unknown + _raise_preserved(primary, secondaries) + return {'operating_premises': _OPERATING_PREMISES, +@@ -1225,8 +1234,8 @@ + + def _exclusive_directory(path): + parent, name = _path(path).rsplit('/', 1) ++ primary, secondaries, result = None, _RawG12Errors(), None + fds, rows = _directory_chain(parent) +- primary, secondaries, result = None, _RawG12Errors(), None + try: + os.mkdir(name, 0o700, dir_fd=fds[-1]) + descriptor = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=fds[-1]) +@@ -1266,9 +1275,9 @@ + + def _copy_file(directory, name, raw): + fds, rows = directory ++ primary, secondaries = None, _RawG12Errors() + descriptor = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, dir_fd=fds[-1]) +- primary, secondaries = None, _RawG12Errors() + try: + _write_fd(descriptor, raw) + _check_chain(rows) +@@ -1697,6 +1706,13 @@ + chain.finish(process, selection['body_deadline_ns'] + selection['retention_tail_allowance_ns'], True) + except BaseException as error: + secondaries.append((error, error.__traceback__)) ++ finally: ++ if chain.fds: ++ # No further process-disposal retry follows this point. ++ # Retained pidfds must still be attempted when observation ++ # or signalling failed; closed processes remain unproved. ++ chain.unknown = True ++ chain.release_known_pidfds(secondaries) + for name, descriptor in tuple(outer.items()): + try: + os.close(descriptor) +--- a/research/h25-g12-identity-cleanup/corrected/g12_reference_cold_consumer_v2.py ++++ b/research/h25-g12-identity-cleanup/corrected/g12_reference_cold_consumer_v2.py +@@ -136,6 +136,7 @@ + _need(len(path.split('/')) <= 257, 'G12-N11: finite directory-component bound') + fds, rows = [], [] + primary = None ++ secondary = _RawG12Errors() + try: + fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC) + fds.append(fd) +@@ -152,7 +153,6 @@ + return fds, rows + except BaseException as error: + primary = (error, error.__traceback__) +- secondary = _RawG12Errors() + for descriptor in reversed(fds): + try: + os.close(descriptor) +@@ -185,8 +185,8 @@ + def _read_file(path, cap, mode=None): + _path(path) + parent, name = path.rsplit('/', 1) ++ descriptor, primary, secondary, result = None, None, _RawG12Errors(), None + fds, rows = _directory_chain(parent) +- descriptor, primary, secondary, result = None, None, _RawG12Errors(), None + try: + before = os.stat(name, dir_fd=fds[-1], follow_symlinks=False) + _need(stat.S_ISREG(before.st_mode) and before.st_nlink == 1 and +@@ -1000,6 +1000,7 @@ + _authenticate_own_functions(root, api, source_raw, source_path) + path, sha, size, identity_tuple, parent_path, parent_sha, publication_path, publication_sha, publication_size = config + _need(_digest(sha) and _digest(parent_sha) and _digest(publication_sha), 'G12-N16: source selection digest domain') ++ _uint(publication_size) + identity = _identity_dict_from_handoff(identity_tuple) + manifest_record = {'path': path, 'sha256': sha, 'bytes': size, 'identity': identity, 'nlink': 1} + manifest_raw = _root_read(root, api, manifest_record, _META_CAP) +@@ -1008,8 +1009,8 @@ + retained = manifest['custody']['retained_directory'] + _need(path == retained + '/manifest.json' and publication_path == retained + '/publication.json', + 'G12-N16: exact fixed publication/manifest paths') ++ primary, secondaries, result = None, _RawG12Errors(), None + dirs, rows = _directory_chain(retained) +- primary, secondaries, result = None, _RawG12Errors(), None + try: + _need(_exact(_identity(os.fstat(dirs[-1])), manifest['custody']['retained_directory_identity']), + 'G12-N17: final retained directory identity') diff --git a/research/h25-g12-custody-repairs/review/PRO-COMPOSED-REVIEW.json b/research/h25-g12-custody-repairs/review/PRO-COMPOSED-REVIEW.json new file mode 100644 index 0000000000..e0271ea9a2 --- /dev/null +++ b/research/h25-g12-custody-repairs/review/PRO-COMPOSED-REVIEW.json @@ -0,0 +1,19 @@ +{ + "schema": "independent-composed-patch-source-review-v1", + "reviewer": "/root/successor_repairs", + "disposition": "ACCEPT_BOUNDED_COMPOSED_DRAFT_ONLY", + "patch_lines": 146, + "exact_diff_matches_proposed_files": true, + "proposed_hashes_and_sizes_match": true, + "only_intended_definitions_changed": true, + "launch_and_handoff_remain_null": true, + "target_imports_or_executions": 0, + "integrated_source_acceptance": false, + "human_or_proof_kernel_acceptance": false, + "remaining_limits": [ + "Preflight allocation and error-recording counterexamples remain", + "Pidfd-release proof assumes successful snapshot and recording", + "Publication-size repair is a schema-domain correction, not a forged-origin exploit", + "Historical verifier PASS does not apply to proposed bytes" + ] +} diff --git a/research/h25-g12-custody-repairs/review/PRO-SOURCE-REVIEW.txt b/research/h25-g12-custody-repairs/review/PRO-SOURCE-REVIEW.txt new file mode 100644 index 0000000000..ce1616e443 --- /dev/null +++ b/research/h25-g12-custody-repairs/review/PRO-SOURCE-REVIEW.txt @@ -0,0 +1,449 @@ +P07/G12 independent source consultation +2 November 2026, Australia/Sydney + +DISPOSITION + +Partial source progress. PR6339 resolves the original identity representation defect locally and repairs ordinary preflight close-error ordering when bookkeeping succeeds. It does not establish integrated source acceptance. A single allocation failure can still replace the original primary and skip known descriptor closes. A separate ordinary denied-observation trace skips known pidfd closes. The proposed successor repairs three narrower issues without claiming to close the full allocation, error, or custody obligations. + +This consultation preserves h=25, extra_target=(0,2,1), optimise zero, original profile/no-anchor invocation, the unchanged independent uncached reference producer, all original oracles, both exports, and the shared N22/P07 protocol. No source selection, runtime, grant, provider/native activity, repository mutation, or publication was performed. P02 is excluded. Historical 49/52 coverage, the 81 predecessor checks, and 126 static delta checks remain historical claims with their original scopes. + +ACCESS AND EXACT SOURCES + +H is research/h25-cache-source-handoff at ca9d90e93dc495e1e5e5ef6d271ff1e4f089cd0c. +S is research/h25-g12-identity-cleanup at 608ad23adc6c01264c8195daf7f18e29c17464a7. +B is research/h25-bookkeeping at e05aad954689d0ee21baff19b4674f1fcb2e838f. + +Direct GitHub API observations confirmed PR6321 merged, PR6339 open/unmerged, and PR6029 merged at those exact heads. PR6339 review, inline-comment, and conversation-comment endpoints were empty. All-state repository PR searches for P07/G12/N22 returned 2/4/2 results, with no newer relevant successor. This is a scoped search, not a global absence proof. + +All nine S files were fetched completely and read. Their nine Git blob identities were checked. Eighty-four non-P02 H manifest files were fetched completely, with all SHA-256 and byte lengths matching, alongside the complete README, CONTRIBUTOR-TASKS, and MANIFEST. The 27 P02-specific manifest entries were excluded. Fourteen additional B files were retrieved, comprising SOURCE-PINS, the 12 frozen Python scripts, and the original reference certificate. Their script/certificate pins match the named original inputs. No historical runtime output or performance result was adopted. + +The complete corrected parent, corrected consumer, adapter, original guard, required G12 design/review material, relevant loader and authority functions, and the complete P07 support were reviewed. Whole-file byte comparisons and selected function-boundary reads were used for the larger driver/cache/authority closure. Retrieval and a hash match do not imply whole-file semantic acceptance. The READ-COVERAGE section below identifies the remaining unreviewed spans. Initial oversized API presentations were truncated; full raw contents were separately retrieved and hash-checked. No denied source fetch blocks the reviewed readable scope. + +EXACT RECONSTRUCTIONS + +Seven of the eleven named omissions were resolved without user upload. The P07 helper follows exactly the supplied one-replacement rule and matches 65,607 bytes and SHA-256 eae1fca1f951a572a3487e5136454d80f16124cc02fef296793830c50431b061. Four predecessor drivers/support files match their recorded hashes after the published v2 reverse splices. The common and C3-selector standalone components match their original hashes when extracted from their complete embedded blocks. These are exact reconstructions, not claims that their standalone missing blobs were published. + +Four named items remain unavailable as standalone original bytes. + +1. continuation/candidate-transport-v1/g12_reference_transport_v1.py + SHA-256 c4fcac756671cb8927158b11952eb9795222d76ba1d102523a2313d8dad358d2. + Needed to certify exact historical two-argument transport behaviour or equivalence to it. It is not a mandatory current executable leaf when the reviewed custody consumer explicitly replaces it. Any claim that still retains this old transport must first obtain and review its bytes. + +2. review/cache-s0308-source-completion-v2/g12-protocol-independent/verify_candidate_source_v1.py + SHA-256 74c36c6aa47797c11d68a8116db1a338e591a63cf79ced28f6c80713b30c8f8a. + Needed to independently reproduce the historical 81-check verifier claim. It is not a substitute for current source reasoning and was not executed. + +3. areas/cache-s0308-source-completion-v2/g12-custody/SOURCE-PINS-v1.json + SHA-256 e586cb66935781f85668822ba8f118353652e223d9aa57835d206c714cc2c702. + +4. areas/cache-s0308-source-completion-v2/g12-custody/FREEZE-v1.json + SHA-256 08a58558e04168894152a3478823a3eb6d99a328e9c38b23447a84ec7f8ec8f1. + The last two are needed to certify the exact earlier design freeze inventory. The later complete implementation source and current source-ready pins are separately available. + +There is also an unbundled candidate-protocol-v1/SOURCE-INVERSE-v1.json with SHA-256 083d171828102a8c138810d05f9110fc6136c2017a09ab11d8d63c433afd387e. Its absence limits the historical inverse-certificate claim. A complete direct diff against the bundled original scientific driver is available and was performed. + +The precise optional missing-text follow-up is the original transport first if historical transport equivalence is desired, followed by the three historical evidence records if their original audit claims must be reproduced. These are not four invented blockers to the available successor code. Original runtime-profile and externally admitted interpreter/system dependency bytes remain later admission inputs. No runtime profile was acquired or substituted, and their absence is not being used as a reason to refuse conditional source analysis. + +TRACE RELATION AND FAILURE MODEL + +Let R_CP be the original conjunction CP01 through CP15 over the admitted original and candidate traces. P07's remaining-count and complete-output equalities are required observations within that relation, not its definition. Raw objects, tracebacks, frame owners, source graphs, and channel identities are preserved within the run that owns them. No raw identity equality between separate processes is asserted. + +The original boundary assumes an authentic pristine Root/capability/bootstrap, source-owned closures and typed owners, trusted Python/OS/loader/stdlib, serial cooperating ownership, and the stated exclusion of unrelated callbacks, finalisers, signals, and ambient mutable interference. The selected profile sources do not enlist external writers, daemonise, or create arbitrary concurrent work. Those premises do not exclude ordinary OS failure, denied observations, close errors, partial acquisition, MemoryError, or failed evidence recording. A finite single allocation failure followed by ordinary exception propagation suffices for the new counterexample. No theorem of progress through process death or arbitrary repeated asynchronous interruption is claimed. + +The already original Root wrapper has its own exception translation and finally-close semantics at Root full_driver.py lines 480-506. This proposal preserves that original boundary. It does not retrospectively redefine its errors or patch Root/provider code. + +PATCH CONTENT AND CORRECTNESS LIMIT + +p07_g12_minimal_source_repairs.patch is a 146-line unified source proposal against the exact two S corrected files. PROPOSAL.json identifies the exact composed bytes. Inert full proposed files are included. + +The first change hoists seven existing error-ledger allocations before the corresponding function acquires new descriptors. If that ledger allocation fails, the function has not acquired those new resources and has not yet caught a local body failure that this allocation could replace. This does not protect resources already owned by a caller or fix acquisition-to-registration gaps. Moving _directory_chain's recorder earlier introduces an allocation on its success path, and that work and memory must be charged. + +The second change gives the parent an independent final known-pidfd release phase. It executes after the last process-disposal attempt even when observation failed, and removes numeric ownership before close so an ambiguous close cannot cause a blind retry. Unknown process custody remains unknown. Descriptor draining cannot set a false process-success result. This narrower argument assumes snapshot creation, normal exception handling, and raw recording complete. It does not repair all allocation or journal failures. + +The third change adds _uint(publication_size) at the consumer's nine-tuple boundary. The old equality accepts an equal-valued float and preserves it in provenance. Every genuine parent emits an exact nonnegative integer, so the added guard preserves genuine handoffs and rejects the malformed type. This is an exact-domain correction, not a demonstrated forged-origin attack. + +The optional explicit body_failed helper-ABI proposal is excluded. It addresses ambient exception classification only, while original caller admission of that situation has not been established and it would require verifier-call changes. Its absence does not affect the two established cleanup counterexamples. + +The combined proposal was reviewed independently by another agent and passively checked for exact patch application and Python AST syntax. Source selections remain None. The old S verifier and SOURCES metadata still describe the old S bytes, so their reported PASS cannot be attached to these proposed bytes. The proposal's own hash manifest is authoritative for this unselected artefact; an eventual new repository package must regenerate its source maps, inverses, freezes, and verifier metadata. This consultation does not apply that package or populate runtime selection literals. + +INTEGRATED DESIGN PROPOSAL + +Keep the original reference authority f279ab86fc17c6a517b035f19d56863919cbd8304de4e7d5332457c6159aec10 separate from the candidate custody authority 3079a096df1072a83056f3f8a8cbf9e766fdddb488e36dddb36544c7929f988a. The former is part of the unchanged independent producer stage. The latter owns the candidate's cold transport loader. + +The actual candidate edge is driver -> captured custody authority -> fixed areas/cache-validity/g12_reference_transport.py mount -> corrected consumer. The authority injects the originally captured Root/capability/API and consumer source identity before execution, then checks the three argument identities and cold currentness. A new consumer file elsewhere in S does not alter this edge. + +A future authorised source selection has a non-cyclic derivation. Freeze the reviewed parent and its external initial source pin, retain a genuine complete parent custody result, freeze a consumer containing exactly that nine-tuple, compute its digest, insert that digest in the candidate authority's transport literal, compute the authority digest, and propagate both digests into both N22/P07 drivers/support and their stage inventories. Regenerate source-ready pins, maps, exact inverses, and freeze records at each changed edge. Consumer own source identity stays loader-injected, avoiding a self-hash cycle. Preserve the unchanged independent producer, adapter's original argv, both exports, and the two distinct authority roles. + +This is conditional integration design. All launch, handoff, and transport literals remain None here. The existing closed branches are fail-closed evidence, not a non-vacuous positive-path witness. A clean hypothetical trace can satisfy the inspected tuple, file, bootstrap ABI, directory sealing, and same-CLI protocol steps when their original premises and operations succeed, but this review has not established the complete selected-path theorem. + +COMPLETE REPAIR STILL NEEDED + +The remaining cleanup repair must make acquisition and ownership publication exception-safe, keep the immediate open/pidfd return owned until registration succeeds, and provide a coherent first-primary/ordered-secondary raw journal before resources are acquired. Cleanup attempts must not depend on optional formatting, copying secondary lists, or a successful process census. Attempted, known closed, and unknown outcomes must remain distinct, and no uncertain close may be retried only from its integer descriptor. + +No pure source assertion or finite test supplies an infallible allocation premise. If a proposed bounded journal requires a different allocation/failure model, that is an explicit proposed problem change needing review. It must not be silently inserted into the original theorem. + +Nested cleanup ProcessRecord/group/lease/science-directory validation, allocation-sensitive source/closure graph handling, full transitive alias closure, and all original caller predicates remain incompletely discharged. The matrices below give each branch and caller obligation an explicit independent disposition rather than converting coverage into acceptance. + +ACTUALLY EXECUTED CHECKS + +Only passive text, JSON, hashes, diffs, extraction, AST parsing, and one independent six-case exception-semantics model ran. The model uses descriptor tokens and pre-existing exceptions; it makes no OS close, target import, target execution, or scientific call. Its six finite examples illustrate ordinary primary/secondary order and allocation/recording failures. They are not target regression results or a general correctness proof. All proposed integration and fault-injection controls remain unrun. + +COSTS AND QUALIFICATION + +Original C01-C15 remain intact. In particular, C01/C02 cover source and initial custody, C05/C07/C12 cover retained contexts and raw error graphs, C13 covers both complete exports and evidence I/O, C14 covers every successful or failed cleanup attempt, and C15 covers all final parent/publication tails. Existing symbolic categories already accommodate the proposed work. No new generic enclosing accounting API is made an original prerequisite. + +Actual complete wall time, all-process CPU, aggregate peak memory, final physical costs, admission, source adoption, full-caller qualification, measured performance, and kappa remain unqualified. Unknown costs remain OPEN_NOT_ZERO. Historical allowances and measurements do not transfer. + +Credit remains with Chris R/Clear1nsight, Douglas R. Colkitt's circuit/network lineage, PR6029/6321, retained source authors and reviewers, and unpaidmoon with substantial Cursor Grok assistance for PR6339. This Pro consultation and its agent reviews are not independent human acceptance or a proof-kernel certificate. + +DETAILED SOURCE FINDINGS AND MATRICES FOLLOW + + + +INDEPENDENT SUCCESSOR REPAIRS + +# Independent PR6339 successor audit + +## Scope and executed checks + +The source pin is `608ad23adc6c01264c8195daf7f18e29c17464a7`. I inspected all nine S files as inert text. The two predecessor files were compared completely with their corresponding successors. I read every changed statement, the complete parent, the consumer's distinct sections, and the shared consumer sections by exact text/AST comparison with the corresponding complete parent sections. No target import, target execution, `verify.py`, original control, guard, provider, native code, or scientific code was run. + +Passive byte checks reproduce the four claimed SHA256 values. Parent v1 is 94,080 bytes with SHA256 `160b8c5de808b9b31532608a89fa5e209110caea132145cd431ffade4403079e`. Parent v2 is 95,532 bytes with SHA256 `176f0ae0748e8f02a9a89b23e0d0fa684b6c6734ad0a68f705a802695046005e`. Consumer v1 is 61,159 bytes with SHA256 `89ad17cfa90e895e2cb105e80cc57c82be4bf1a4a85a9d44322016c4344e3849`. Consumer v2 is 62,128 bytes with SHA256 `dc8a0b62d4175ee447469b7e66798160b85777f44e34d34e98b08af83a9f5a6d`. + +The independent six-case exception model in `semantics_model.py` ran on Python 3.12.14. It neither imports nor executes target source, and uses integer descriptor tokens, pre-created exceptions, and a fake recorder. Its results are in `semantics_model_results.json`. These finite cases illustrate exception mechanics, not a full target correctness proof or a rerun of the author's PASS claim. + +## Identity repair + +The exact successor resolves SOURCE-001 at its local boundary. Parent lines 201-209 explicitly pack the six dictionary values in `_ID_NAMES` order, and the nine-tuple construction at 1686-1689 uses that packer. Consumer lines 109-126 accept only an exact six-element tuple and exact built-in integers, so bool and integer subclasses do not qualify. The conversion uses the exact six string keys and preserves each value, including `full_st_mode` and signed nanosecond timestamps. It does not reduce full mode to permissions, stringify values, or manufacture identity evidence. + +The converter by itself does not establish every FileRecord predicate. It checks nonnegative device, positive inode, and regular-file type. Size is only checked for exact-int type there. Consumer `_file_record`, lines 226-238, subsequently requires exact nonnegative `bytes`, exact string-key identity domain, exact ints, and equality of size and bytes. That entails nonnegative size on the accepted integrated path. `_root_read`, lines 241-250, requires the original Root digest/currentness before and after the complete held-chain read, full exact record equality, actual mode `S_IFREG|0444`, and original digest/size joins. The final rereads are at 1051-1065. Provenance reconstructs the exact six values by string keys at 1068-1071. + +Therefore the representation repair has a straightforward conditional valid-path argument. Let I be the genuine FileRecord dictionary already returned by the parent's checked read, with the six exact keys. Packing I and converting that tuple returns an exact dictionary D with D[k] = I[k] for every key. The unmodified FileRecord and currentness checks can then run. The predecessor's tuple fails the dictionary predicate. This establishes local representational compatibility, conditional on genuine bootstrap, source selection, live source/custody, and the rest of the checks. It does not itself authenticate the parent, select the successor, or prove integrated P07. + +The parent packer does not independently recheck all value domains. Its call site receives a record produced by `_read_file` and used in manifest/publication checks. Requiring another independent integer validator there is unnecessary for the stated local round-trip proof. Conversely, accepting a dictionary at the consumer boundary would silently enlarge the agreed handoff representation and is not needed. + +## Cleanup repair under successful bookkeeping + +For the exact two enclosing finally clauses at parent lines 1431-1440 and 1444-1455, the ordinary synchronous close-error repair is correct provided its bookkeeping completes. The descriptor sequence is the owned list returned by `_directory_chain`. + +If body error E is pending, `_close_known_descriptors` at 212-220 attempts the descriptors in reverse order and records close errors C1, C2, and so on. After that function returns, Python restores the surrounding active-exception context. `sys.exc_info()[1]` at 231 is E, so the helper appends every close error and returns. The enclosing finally propagates the same E object to 1747-1748. Failure-tail work then appends its errors, and 1760 raises the preserved E. Raw traceback objects captured at each close are retained in the ordered records. + +If the body succeeds, the helper promotes C1 at 232-235 and appends only C2 onward. The enclosing handler at 1747-1748 captures C1 as primary. Failure-tail errors follow the already recorded C2 onward. No duplication or ordinary reordering was found in this specified subcase, including two or more close errors. If all closes succeed, the helper returns normally and adds no failure. An error path remains non-successful even where a close was physically completed before the OS reported an error. + +These statements are conditional arguments from the complete enclosing source, not the author's finite test. Author `verify.py` covers a single failed close with body failure and one failed close with body success at lines 191-229. It does not check the two real preflight handlers, multiple failed closes, partial acquisition, allocation failures, or complete raw traceback identity. It imports both target modules at 246-247, and was deliberately not run here. + +## New counterexample S-ALLOC-01 + +The broader claim that every known close is attempted and the first primary is preserved is false if allocation failure is admitted. Parent `_close_known_descriptors` allocates a 4096-slot `_RawG12Errors` at line 214, then allocates `tuple(descriptors)` at line 215. These operations execute within the finally path after the body may already have raised E. Let three owned descriptors be live, let the body raise E at 1437, and let the ledger allocation at 214 raise MemoryError M. Then no close is attempted. M replaces E as the propagating exception and the outer handler at 1748 records M as primary. E may remain in M's exception context, but that is not preservation of E as the first-primary channel. The preflight `fds` list is a local and is not included in `_g12_finish_failure`'s cleanup domains at 1731-1737. The outer handler therefore does not repair the skipped attempts. + +The analogous counterexample exists at line 219 when construction of `(error, error.__traceback__)` or recording that pair fails after the first close error. Later descriptors are skipped and M replaces E or the earlier close error. If all closes have been attempted but `list(failures)[1:]` at 233 fails, C1 is replaced by M in the success-body branch. If copying records into `secondaries` at 234 or 237 fails, the pending first error can likewise be displaced before the outer handler sees it. The guarded bookkeeping note at 1752-1759 concerns failures in `_g12_finish_failure`, not these earlier failures in preflight finally. + +This does not require arbitrary hostile callbacks, signals, threads, or process interference. The original CP14 explicitly excludes unrelated callbacks/finalisers/signals only under the original premises. The inspected operating premise at parent 1040-1044 and DESIGN-v1 lines 218-225 describes trusted sources/OS and cooperating ownership, not guaranteed successful allocation. The source handoff explicitly leaves allocation failure for independent review. A full theorem cannot silently add 'cleanup bookkeeping never fails'. Nor can a pure Python patch promise progress through arbitrary process death or endlessly repeated asynchronous interruption, which are not the original permitted interference model. + +## Partial acquisition and inherited cleanup defects + +Parent `_directory_chain` acquires the root descriptor at 156, then registers it with `fds.append` at 157. A failure of that append leaves the just-acquired descriptor outside the cleanup list. The same window occurs at 161-163 for a child. An exception from acquisition or identity checking is captured at 170, but `_RawG12Errors()` at 171 can then fail before any cleanup, replacing the earlier primary. Consumer lines 140-155 have the same structure. + +Parent `_read_file` obtains a complete directory chain at 245 and allocates its error ledger at 246 before entering its try block. Consumer lines 188-190 are identical in structure. `_exclusive_directory` does this at parent 1228-1230. `_copy_file` acquires its new file descriptor at 1269-1270 and allocates its ledger at 1271 before its protected body. Consumer `load_original_g12_reference` obtains its retained chain at 1011 and allocates its ledger at 1012. A failed ledger allocation in any of those windows skips that scope's cleanup. + +Additional pre-existing allocation-sensitive cleanup exists in parent 274, 1196-1203, 1700, 1706, and 1721-1737, including temporary tuple/list creation and failure-record allocation. These require a coherent ownership/journal design, not just one substituted finally helper. Acquisition also precedes dictionary registration at parent 1140-1142, 1466-1468, and 1590-1591. The responsible owner must hold a newly acquired descriptor directly until it has been registered, so a registration failure cannot lose it. The repair must preserve failure identity and keep an unsuccessful or unknown close distinct from a known-closed descriptor. + +## Concrete narrower proposed diff + +`allocation_hoists_partial.diff` moves seven existing error-ledger allocations before their respective scopes acquire new descriptors. The two `_directory_chain` changes additionally move the allocation out of error propagation. No scientific source, oracle, source selection, or successful syscall order is changed. The patch is justified as a narrower repair of the identified ledger-allocation leak windows. It does not fix the new preflight helper, unregistered acquisitions, record allocation, ambient exception context, or all failure-tail bookkeeping. It must not be labelled an integrated correction or SOURCE-002 closure. + +The proposed bytes were created by exact text substitutions and AST-parsed only. Both launch and handoff remain None. Publishing this patch would require new source hashes and propagation through every authoritative loader/pin/map, followed by review. The patch allocates the directory-chain ledger even on successful chain acquisition, so its costs and lifetime must be charged and no performance improvement is claimed. Its conditional behavioural argument assumes the moved allocation succeeds; when it does fail, no new descriptor in that scope has yet been acquired. + +## Required complete repair and proposed controls + +A second narrowly proposed diff is `explicit_preflight_outcome_partial.diff`. It replaces the helper's inference from ambient `sys.exc_info()` with an explicit boolean set locally around each actual preflight body. Neither body has an early return. Thus the flag remains True on a body exception and becomes False only after that body's checks succeed. This avoids treating an unrelated exception currently handled by a trusted invoking caller as a pending failure of the preflight body. Such an ambient-handler invocation has not been established as an admitted original trace, so this is conditional hardening rather than a proved defect in the original fixed caller. It does not repair the allocation counterexamples. The private helper signature changes; proposed successor controls must pass the explicit flag and all successor pins must be regenerated. Original S verification code is untouched and unrun. + +A complete successor needs a single explicit first-primary/ordered-secondary journal that is acquired before the corresponding resources, preserves raw exception and traceback references without first allocating tuple/list snapshots during cleanup, and has a source-derived sufficient capacity or an explicit overflow failure path that continues all owned cleanup attempts. Resource registration itself needs an exception-safe ownership transfer, retaining the immediate return from open or pidfd_open until registration succeeds. Cleanup should record attempted, known-closed, and unknown outcomes separately. Parent output publication remains forbidden whenever any cleanup/error-evidence obligation is incomplete. Failure-tail formatting must occur only after the raw record has safe ownership and cannot prevent later resource attempts. No change to Root/capability provenance or original continuation semantics is needed for this design. + +Proposed controls should inject body error plus two close errors; successful body plus two close errors; each acquisition/registration failure; ledger initialisation failure; record-pair allocation failure; ledger append/copy failure; error-formatting failure; a close that raises after releasing its descriptor; and a close whose final state is unknown. Each control must observe the exact raw first error, its original traceback tail, raw ordered secondary references, and the complete ordered attempt set through the actual two enclosing handlers and final cleanup. Avoid treating the author's `closed(fd)` routine at verify.py 153-158 as a state oracle for arbitrary OSError. That routine performs a second close and treats every OSError as already closed, which is only justified for its narrow local test arrangement. + +The exact original failure model and all source-owned raw-channel obligations must be stated before any resulting robustness claim. A bounded operational proof with explicitly available error-recording resources could be a useful conditional result; it is not automatically the original admitted-execution theorem. No missing runtime authorisation is being treated as a source blocker here. + + +ALL EIGHTEEN CUSTODY BRANCHES + +# G12 custody branch review at H and S + +This is an independent source disposition, not an integrated acceptance. Every G12-N01 through G12-N18 category has been inspected in the available parent, adapter, consumer, and relevant authority/driver edges. The review does not establish the complete transitive source and alias proof, an actual selected invocation, universal OS cleanup, full caller equality, or measured costs. No target source was imported or executed. Proposed regression controls below have not been run. + +## Exact source aliases + +- P is S `corrected/g12_reference_parent_v2.py`, SHA256 `176f0ae0748e8f02a9a89b23e0d0fa684b6c6734ad0a68f705a802695046005e`. +- C is S `corrected/g12_reference_cold_consumer_v2.py`, SHA256 `dc8a0b62d4175ee447469b7e66798160b85777f44e34d34e98b08af83a9f5a6d`. +- A is H `snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/integration/g12_reference_adapter_v1.py.txt`, SHA256 `43aaabc69841b0a90fae599011de85f4736f42ced64344c49d6cd93f20297f9f`. +- U is H `snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_epoch_authority_custody_v1.py.txt`, SHA256 `3079a096df1072a83056f3f8a8cbf9e766fdddb488e36dddb36544c7929f988a`. +- D is H `snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_candidate_driver_P07_custody_v1.py.txt`, SHA256 `2a5d202dabd78d5de54fac29db7fdfaf8836866425d93842f2b22d747fa52d0c`. +- G is H `snapshot/run_guarded_v3.py.txt`, SHA256 `bd882e3dadb1b6aeaa63ee824f1a1c58f8ef2546b6840a2bffa46885a184d3eb`. + +All line numbers refer to those exact files before proposed patches. + +## Failure model and interpretation + +The operating premise is explicit at P1040 to 1044 and C1098 to 1102. It assumes trusted selected sources, OS, loader, interpreter, and standard library, a cooperating same-user launch domain, and no unrelated writers. The selected profile sources do not fork, spawn threads, daemonise, or transfer writable descriptors to outsiders. Original CP14 excludes unrelated callbacks, finalisers, signals, and ambient mutable substitutions only under its original premises. These assumptions do not exclude the explicitly required denied observations, close errors, partial acquisitions, allocation failures, or evidence-recording failures. No argument below treats a clean process census as a universal writer theorem or a close attempt as proof of closed state. Exact origin cannot be manufactured by a well-shaped dictionary, boolean, module, function, or restored namespace. + +Conditional rejection means that the inspected predicate rejects its stated bad value if the authentic source graph and ordinary evaluation are available. It is weaker than complete preservation of every raw error and every cleanup attempt. An error that aborts later cleanup is a counterexample even if publication stays closed. + +## G12-N01 through G12-N18 + +| Branch | Required invariant | Exact evidence | Independent disposition | Proposed regression control | +|---|---|---|---|---| +| G12-N01 | A missing, None, or foreign selection cannot launch or expose expected data. | P15 to 18, 1296 to 1302; C18 to 23, 983 to 990; U1578 to 1579; D1371 to 1373, 1831 to 1845. | The actual None gates reject before the selected body or returned reference. This establishes the closed branch only. It gives no non-vacuous selected-path proof. S does not select or mount itself. | Keep all selections None; a proposed source control should confirm no launch or reference result is reached for each absent/wrong-domain selection, without treating refusal as P07 success. | +| G12-N02 | Exact Root, provider, guard, independent producer, authority, source, and stage identities must agree before science. | P1350 to 1426 and 1606 to 1614; C814 to 826; A344 to 407; U2129 to 2139; D124 to 145. | Digests, modes, staged paths, and census checks are present. The original reference authority `f279ab86…` is distinct from candidate custody authority `3079a096…`. S supplies new leaf bytes without an updated integrated source/mount/pin map. An exact prospective mount/pin map and a full transitive closure review remain open. | Change one source byte, mode, mount path, stage key, or authority digest at a time, including the historical wrong authority; require refusal before scientific entry. Independently reconstruct all pin changes for a future successor. | +| G12-N03 | Preserve the exact profile/no-anchor, optimise-zero guard and producer arguments; reject extra or substituted options. | P949 to 962, 1215 to 1223, 1396 to 1398; C898 to 911; A354 to 363 and 398 to 400. | The adapter requires exactly five argv elements with fixed output/lanes positions. It builds the original producer argv rather than deleting unrecognised options. The preflight checks the exact job dictionary. No deterministic valid-path ABI mismatch was found here. | Propose wrong lanes, `--finite-only`, `-O`, an anchor, reordered or added arguments, and a foreign label; require rejection rather than argument repair. | +| G12-N04 | Only the actual initially captured Root/capability/API and source-owned function graph may confer authority. | C22 to 23, 478 to 531, 971 to 1000; A14, 248 to 340, 344 to 352, 407 to 448; U2130 to 2139 and 2361 to 2381. | The three-argument candidate edge, pre-exec bootstrap injection, identity checks, and cold recheck are explicit in H. They remain conditional on genuine original bootstrap provenance. Parent source injection is an external trusted-launcher prerequisite, not self-authentication. Full transitive alias closure remains unproved. | Replace the Root/API tuple, one closure cell, code object, default, namespace entry, or initial bootstrap object, and require the original ownership checks to reject. Include same-shape reconstructed objects. | +| G12-N05 | Prior output, orphan attempts, consumed phase budget, lease contention, and inadequate admission must remain nonqualifying. | P1359 to 1361, 1380 to 1388, 1430 to 1465; G180 to 207; C449 to 456. | Absent-path checks, exclusive acquisition, nonblocking flock, and the original guard's orphan/budget checks are present. Positive body/tail numbers do not prove a genuine allowance or resource fit. Parent tail I/O is not itself bounded by a new deadline check. This remains a later original admission obligation, not grounds to invent an accounting API. Cleanup-failure preservation is refuted separately. | Proposed path-exists, orphan receipt, flock contention, spent-cap, and inadequate authorised-tail cases. Require no selected handoff and preserve the first error plus every known cleanup attempt. | +| G12-N06 | Failed or ambiguous Popen, nonzero wait, STOP, and resource violations cannot become canonical success. | P1468 to 1520, 1691 to 1763. | Actual Popen, PID generation, wait returncode, and parent STOP are retained. The failure path does not invent a guard receipt. However, the stronger all-known-cleanup requirement is false when process observation or signalling fails before pidfd release. | Inject Popen failure before and after known descriptor acquisition, nonzero wait, missing generation, each STOP condition, and denied observation with existing pidfds. Compare the first raw error and ordered cleanup trace. | +| G12-N07 | Original START, receipt, usage, complete stdout/stderr, phase, and source predicates must agree. | P478 to 520 and 1522 to 1545; C433 to 475, 1022 to 1043; G250 to 310. | The exact START/receipt field join, original success conjunction, numerical caps, complete log lengths/hashes, empty stderr, and outer receipt join are present. An outer returncode alone does not satisfy them. Parent additionally hashes original fractions source. These are data checks following authenticated parent custody, not independent provenance creation. | Remove a receipt, add GNU time diagnostics to usage, alter START/receipt fields, stdout/stderr, fractions digest, resource values, or source-drift predicates; require nonpublication. | +| G12-N08 | Denied/unknown observation, generation ambiguity, residual writers, failed closes, and ownership loss remain unknown; every known cleanup attempt still occurs. | P1075 to 1212, 1333 to 1341, 1510 to 1520, 1695 to 1737; C830 to 835. | **Counterexample established.** `finish` reaches pidfd closes only after a successful observation/disposal loop. A persistent denied observation raises during the main call and P09 retry; known pidfds are never attempted. The narrow supplied patch separates final descriptor release from the success of process disposal, and keeps custody unknown. | Retain at least two known pidfds, make process observation fail persistently, and require both close attempts after the final process-disposal attempt. If close outcome is ambiguous, require unknown state and no blind retry of its integer descriptor. | +| G12-N09 | Preserve the raw first primary, ordered raw secondaries, owned restoration, and both original cold checks. | A409 to 455; P187 to 198, 212 to 240, 1691 to 1760; C171 to 182, 1073 to 1080. | Ordinary source control flow retains primaries when bookkeeping succeeds. The stronger obligation is not established. Error tuple allocation, fixed-slot bookkeeping, secondary transfer, and formatting can fail, and structured secondary objects are not returned through every wrapper boundary. The sibling successor audit contains exact counterexamples. | Body error plus multiple closes; successful body plus multiple closes; nested read error plus its closes; evidence-retention failure; and both alias restoration failures. Check within-run object/traceback identity and ordering, not formatted equality. | +| G12-N10 | Both common and diagnostics are mandatory, including complete bytes and preserved partial originals. | P1547 to 1558 and 1561 to 1572; C1044 to 1055. | Both fixed names are read before pair validation and neither common-only fallback nor diagnostic synthesis exists. A missing/partial second file prevents sealing and return. This local branch argument does not cure cleanup errors encountered after the missing-file primary. | Omit each export independently, truncate diagnostics after a valid common file, and change diagnostics between initial and joint reread. Require no handoff and preservation of partial original evidence. | +| G12-N11 | Nofollow directory custody, full file identity, regular single-link files, complete size-bounded hashing, and closed readers are required. | P149 to 184, 242 to 295; C109 to 251; A96 to 186; P1556 to 1557, 1602 to 1614. | S fixes the parent tuple to dict conversion without weakening subsequent full-mode/currentness checks. Directory and file observations are jointly rechecked. The trusted no-interference premise is needed across observation intervals. Partial acquisition and allocation can still bypass known closes, so this is not an all-failure proof. | Symlink, hardlink, nonregular file, wrong full mode, short read, growth, directory rebinding, identical-content inode replacement, close failure, and failure immediately after each open. | +| G12-N12 | Exact schemas, integer domains, known primitive tags, bounded parsing, canonical hex/JSON, and explicit failures must be preserved. | C65 to 127, 226 to 238, 253 to 422, 798 to 895, 1001 to 1018; P shared validators are AST-identical. | Duplicate keys, nonfinite JSON tokens, unknown fields/tags, boolean-as-integer in checked integer fields, malformed hex, and depth limits have explicit rejection paths. Coverage is incomplete. The nested ProcessRecord/group/lease/science-directory values are not fully schema-validated; outer `publication_size` lacks an exact integer check. These are schema gaps, not a demonstrated forged-origin path under a genuine selected parent. Tagged float hex intentionally permits the producer's domain and is distinct from JSON NaN/Infinity tokens. | Exact malformed-schema controls at each nesting level, publication_size as equal-valued float, bool integer fields, unknown tags, duplicate keys, excessive depth, malformed UTF-8, and allocation failure during parse. Do not run scientific decoders. | +| G12-N13 | Pair/manifest source, role, workload, full payload hash, inner prefix, and suffix order must agree. | C377 to 422, 806 to 826, 855 to 867, 1044 to 1049; P422 to 467. | Fixed source/workload constants, exact ten-member tagged common tuple, first four members, suffix phase tuple, common/diagnostic digest join, and original/retained size/hash joins are explicit. Opaque complete payload bytes remain the caller comparison object. Other common members are preserved rather than recomputed as a new oracle. | Perturb one scientific pin, role, h, target, literal type, inner tuple member, suffix order, payload byte, or digest; require refusal while leaving the original producer unchanged. | +| G12-N14 | Copies, metadata reservation, fsync/chmod/known closes, readback, and final alias checks must precede qualification. | P1226 to 1282, 1561 to 1689; C847 to 879, 1011 to 1021. | Two metadata names are reserved before the final directory identity is recorded. The owned mode transition updates the last held chain record, and subsequent writes use existing FDs. No deterministic success incompatibility was found in those steps. Close/allocation failure branches are not fully correct, and surviving metadata bytes never establish selection. | Partial writes, zero progress, fsync/chmod/readback failure, new child, mode drift, manifest/publication close errors, and failure after only one reserved metadata descriptor is acquired. | +| G12-N15 | A failed final tail or absent authority cannot select a manifest; unknown final costs stay unknown. | P965 to 994, 1649 to 1689, 1749 to 1763; C880 to 895, 914 to 943, 1016 to 1021. | Publication joins the exact manifest/pair and requires recorded lease close; `complete_cost_qualification` stays False and `unmeasured_final_tail` stays None. P09 runs before candidate return. These fields correctly refuse a completed-cost claim, but P09 cleanup preservation is still defective. No generic enclosing accounting API is made a prerequisite here. | Fail publication write, readback, close, final directory checks, or final cleanup after manifest creation. Require no accepted handoff and OPEN_NOT_ZERO final costs. | +| G12-N16 | A runtime success flag, arbitrary path, or fabricated registry cannot replace immutable source selection. | P1296 to 1332; C985 to 1010; U2129 to 2139; D1831 to 1845. | No caller arguments are accepted by the parent, no handoff setter exists in the consumer, and the loader injects actual captured bootstrap objects. Paths are tied to retained fixed namespaces. Future source selection still needs independent custody evidence; a copied literal alone is not an admission proof. | Attempt caller keyword flags, foreign manifest/publication paths, an altered global selection after capture, and a copied module with different initial bootstrap. | +| G12-N17 | After decode, all retained files, source, namespaces, Root, and owned consumer graph must still agree before exposure. | C241 to 251, 1050 to 1081; U2370 to 2381. | Manifest, common, diagnostics, publication, and every retained evidence file are reread after decoding. Root/source/current graph checks follow, then reader closes and `_raise_preserved` precede return. This is a conditional valid-path custody chain, subject to original no-interference and allocation/cleanup limitations. | Mutate each file between reads, including diagnostics after common decoding; alter source or bootstrap between check points; fail a final close. Require no exposed reference tuple. | +| G12-N18 | G12 diagnostics cannot establish P02, native/full-positive, performance, or mathematical improvement claims. | C895, 1104 to 1105; P946, 1047 to 1048; D1804 to 1814; H DESIGN-CORRECTION-v2.json. | Scope strings and caller output explicitly retain the boundary. Strings do not enforce human interpretation, so the review must also withhold those claims. P02 remains excluded. | Proposed documentation/source review confirms no native/performance/P02 success is inferred from diagnostics, first yield, or transport result. | + +## Concrete counterexample and narrow repair + +In P1182 to 1205, the pidfd close loop is reachable only after `stop_known`, `process.poll`, `observe`, and `_children` successfully establish an empty process domain. Choose an admitted trace in which the chain already owns two pidfds and a later `/proc` observation raises `PermissionError`. The main call exits with that error. P1695 to 1699 makes a final failure-disposal attempt, but the same denial raises again before the pidfd loop. P1700 to 1737 closes other domains but contains no chain-pidfd release. Neither known pidfd has received a close attempt. Publication remains closed, but the every-known-cleanup-attempt property is false. + +`pidfd_release.patch` is a proposed minimal successor against the exact S parent. It introduces a separate known-pidfd release phase, calls it on the original successful process-empty path, and calls it in a P09 `finally` after the last process-disposal attempt. It retires each integer descriptor from the owned table before the close call so an ambiguous close cannot be retried blindly. A failure or unknown process state keeps `chain.unknown` true and does not set `chain.closed` merely because the descriptor table is empty. It preserves the existing successful cleanup record shape and all selection None values. + +The narrow proof assumes creation of the descriptor snapshot, execution of exception handling, and raw secondary storage succeed. Under those assumptions each remaining known descriptor is visited once, failed observation cannot bypass the final descriptor phase, and an ambiguous close is never retried. The patch does not solve allocation exhaustion, failing raw-secondary storage, process disposal after lost observation, or earlier failed acquisition registration. It has only been AST-parsed as inert text. It must not be described as integrated acceptance or a complete cleanup repair. + +`publication_size.patch` is a separate one-line successor for C1002. It adds `_uint(publication_size)` before publication consumption. Without that check, an equal-valued float passes the equality at C1017 and is retained in provenance at C1069. A genuine parent emits an exact integer, so the additional predicate preserves every genuine parent handoff while excluding that larger domain. This is a narrower exact-domain repair, not evidence that a foreign caller can create source provenance, and it leaves the remaining nested-schema gaps open. The proposed consumer was AST-parsed only. + +An additional allocation/ownership gap remains at P1134 to 1144. A pidfd is inserted in `self.fds` before `_proc` and before `self.rows[key] = dict(current)`. If the latter allocation fails with the child still live, a later `observe` can call `add` again because the duplicate test consults only `self.rows`. That can open and overwrite the `self.fds` entry for the same key, losing the first descriptor. Final descriptor release alone cannot repair this acquisition-state defect. + +## Exact integrated propagation still required + +The unchanged reference producer must retain reference authority `f279ab86…`. The reference stage mounts the adapter and original authority; the parent source is separately authenticated outside the child stage. The candidate path is independently `D -> U -> g12_reference_transport.py -> C`. H provides the correct three-argument ownership edge, but its transport pins remain None and its source map still names H's old consumer. S publishes replacement leaf files without a revised mount/pin map. + +A later authorised selection can be acyclic. First freeze the reviewed parent and its external source pin, then obtain genuine parent custody. Freeze a consumer with the exact resulting nine-tuple. Its digest then becomes the custody authority's transport pin. The authority digest and same consumer digest then propagate to both N22 and P07 drivers/support, followed by candidate stage inventories, source-ready pins, and inverse/map records. Consumer own identity remains injected by the loader, avoiding a self-hash cycle. These are future conditional steps only; this source consultation changes none of the selections. + +## Passive checks actually performed in this subreview + +The complete corrected consumer and adapter were read as text. Parent-specific process, launch, retention, publication, and failure-tail bodies were read as text. Passive AST comparison confirmed that all 32 common parent/consumer functions and classes are structurally identical, including all schema validators, file readers, and graph checks. The manifest, negative map, source-ready pins, source inverse, stage derivation, integration edges, design correction, design finite-I/O/ownership/schema contracts, original guard, and relevant independent-review findings were inspected. The pidfd proposal alone was AST-parsed. No target module, verifier, scientific decoder, original control, guard, or provider was run. + + +P07/N22 CONTRACT AND ALL FIFTEEN CALLER PREDICATES + +# P07 and N22 source-contract review + +This is a passive source review at H `ca9d90e93dc495e1e5e5ef6d271ff1e4f089cd0c`. It does not execute the helper, driver, authority, guard, native code, or verifier. The conclusions below concern the visible control flow and exact byte derivations. They are conditional on the original typed ownership and source-currentness premises, and do not supply genuine Root, capability, provider, or execution admission. + +## Source aliases + +All paths below are relative to `research/h25-cache-source-handoff` at H, unless explicitly described as a reconstruction. + +| Alias | Path | +| --- | --- | +| D | `snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_candidate_driver_P07_custody_v1.py.txt` | +| S | `snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_candidate_driver_support_P07_custody_v1.py.txt` | +| A | `snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_epoch_authority_custody_v1.py.txt` | +| K | `snapshot/areas/cache-s0308-source-completion-v2/continuation/candidate-protocol-v1/g12_epoch_cache_selector_v1.py.txt` | +| R | `snapshot/areas/cache-s0308-source-completion-v2/continuation/reference-producer-v2/g12_reference_driver_v2.py.txt` | +| O | `snapshot/areas/cache-epoch-products-v5/epoch_scientific_driver_v1.py.txt` | +| E | `snapshot/stages/combined-finite-v8/baseline/engine/source/complex_circuit.py.txt` | +| B | `snapshot/areas/cache-full-contract-completion-v1/cache_epoch_source_controls.py.txt` | +| Y | Exact reconstructed P07 yield helper, derived from B by the user-specified single replacement | +| CE | `snapshot/areas/cache-s0308-source-completion-v1/contracts/CALLER-EQUALITY-DEFINITION-v1.json` | +| CC | `snapshot/areas/cache-s0308-source-completion-v1/contracts/COMPLETE-SYMBOLIC-COST-DEFINITION-v1.json` | + +S is the same appended support block as D after its line 1365, with an offset of 1365 lines. The N22 support has the same mechanism with its selected case and helper pin changed. The surrounding sources were read at the relevant complete function boundaries. No claim is made here to have independently re-reviewed every line of every original native or scientific dependency. + +## Exact source completion achieved without missing-file uploads + +Seven of the eleven expressly identified omitted files can be recovered exactly. The archive still has `bundled_path = null` for their original standalone files. The recovery uses their actual published successor or embedded bytes, then independently compares the resulting SHA-256 with the original recorded hash. These are exact reconstructions, not a claim that the missing standalone blobs were retrieved. + +| Reconstructed file | Derivation | Bytes | SHA-256 | +| --- | --- | --- | --- | +| `cache_epoch_source_controls_p07_yield_v1.py` | B has one occurrence of `def P07(c):\n observed=N22(c)`. Replace it with `def P07(c):\n observed=N22(c); yield observed`. Base hash is `fcffe77b6a84d5b422b03e3d068924a701c1594cdb9ec305115827e3fad7d4b6`. | 65,607 | `eae1fca1f951a572a3487e5136454d80f16124cc02fef296793830c50431b061` | +| `g12_candidate_driver_N22_v1.py` | Reverse the six unique literal replacements in published `g12-protocol-repair/SOURCE-INVERSE-v2.json` on the complete N22 v2 file. | 126,735 | `46f515efa7ebdc60e20b64ef2ebdfb542ecb8c90371d339a951ccabb2a205e09` | +| `g12_candidate_driver_P07_v1.py` | Same exact reverse replacement procedure on the P07 v2 file. | 126,735 | `e6f1038f5a75466d95fd3e8c3d44df483d76f97deff9f966bd6140b2d0bc28a7` | +| `g12_candidate_driver_support_N22_v1.py` | Same six inverse replacements on complete support v2. | 31,921 | `b4a8ec11d4b390d8a8f7167d8149b067be0572f977a1f2286c1719052437fccb` | +| `g12_candidate_driver_support_P07_v1.py` | Same six inverse replacements on complete support v2. | 31,921 | `a918ff01875267c4945a0dbc6d914a904c3eb38b9f5de8256bdc47394b19dcb7` | +| `g12_common_source_v1.py` | Extract the bytes between `BEGIN G12 EXACT COMMON SOURCE` and `END G12 EXACT COMMON SOURCE` in the complete P07 v2 driver, removing only the additional final separator newline. | 4,517 | `8ac6902915ec8afb09914fc5f229e175d864e6aae9fe367f127e1bbd654ed42a` | +| `g12_cache_selector_source_v1.py` | Extract the analogous `G12 EXACT SOURCE-OWNED C3 SELECTOR` block from K, removing only the additional separator newline. | 1,537 | `a9b4019ce368b6f89553ceb98c5451593d0d11ebda699dcb626cab323297375c` | + +The four remaining named omissions are `g12-custody/SOURCE-PINS-v1.json`, `g12-custody/FREEZE-v1.json`, the old `candidate-transport-v1/g12_reference_transport_v1.py`, and `review/g12-protocol-independent/verify_candidate_source_v1.py`. The first two are historical design freeze evidence. The old transport is not the corrected consumer implementation if the proposed custody graph explicitly supersedes it. The old verifier is evidence about historical checks, not a substitute for inspecting the successor. These omissions prevent corresponding historical-evidence claims, but should not automatically be declared necessary current implementation sources without following a real import or authority edge. + +The manifest additionally lists an unbundled `continuation/candidate-protocol-v1/SOURCE-INVERSE-v1.json`, hash `083d171828102a8c138810d05f9110fc6136c2017a09ab11d8d63c433afd387e`. This is a further archival gap in the prior inverse certificate. It does not prevent direct current comparison because O and the reconstructed v1 driver are complete. That direct comparison found exactly the authority pin at line 124, cache pin at line 183, phase hook at line 369, selected-argument hook at line 925, captured phase pairs at lines 1112, 1116, and 1124, main-local binding at line 1167, appended common/support blocks, and the entry change at original line 1270. Original CLI boundary lines 838-898 and original outer cleanup/STOP lines 1225-1267 remain unchanged. This is byte-preservation evidence, not a general execution-equivalence proof. + +## Conditional valid-path argument + +Assume the original Root/capability/bootstrap and typed FULL ownership are independently genuine, all selected bytes and effective function graphs are authenticated before use and remain current, the original serial non-interference premises hold, and the independent reference transfer has actually come through the accepted custody chain. The source does not obtain these premises from booleans, JSON data, or Python shape checks. The current transport selections remain `None`, so this argument concerns a future admitted selection rather than a currently executable positive path. + +The capacity checkpoint is an object census. S212-241 checks 82,895 original active nodes, 2,300 canonical target tuples, the original cache key set, and every exact Label/basis/key/Checks/generation identity. S265-285 requires 85,195 cache entries plus the separately retained `checks.everything` Label, producing 85,196 distinct registry identities. This is the meaning of C. It is not the count of remaining scientific cases. The original target tuple `(0, 2, 1)` is absent because the canonical triples are strictly ordered. S294 invokes the actual installed `checks.target_frame((0, 2, 1))`. + +Original E288-294 first performs the genuine Label construction and original store. The authenticated constructor product preserves that order and uses the source-owned C3 selector captured before product publication, K1813-1838 and K2745-2766. At S86-103, the selected handler checks that the pending Label is the same object just stored in the original cache, while the registry still contains exactly C entries. The 85,197th constructed Label has not been added to the retained registry. No fabricated fill loop or manual pending state supplies this checkpoint. + +Y227-233 calls genuine `_live`, then `s.commit` once. K2106-2121 verifies the original stored object, observes capacity, increments the retirement counter, and takes `retire`. K2195-2199 sets inactive/terminal, clears pending and registry, and drops the retained Checks context. The unchanged helper then calls the public original `label_ok` and compares both exact type and value with the independent literal. S132-139 requires the exact returned observation shape and terminal state, then returns without another commit. The original outer C3 store therefore completes only once. + +For P07, Y330-334 performs N22 and yields that same observation object. S69-83 and S112-126 validate the exact generator type, code, frame, globals, context, and yielded object. Candidate remainder fields are absent at the first advance. The selected handler returns, the same original target-frame call returns, and S299-303 enters the suffix. Original E376-411 then continues the role work through the existing source-owned caller, with its original assertions and callbacks. + +Only S304-308 handles the actual return of the same `runpy.run_path` invocation, checking its function, caller, arguments, and phase owner. S314-347 checks the actual returned namespace, same circuit/Checks/code objects, raw `full_return['role_frames'] is roles`, certificate bytes, stdout, original phase counts, source imports, and retained rank-prefix integrity. S352-369 installs the actual remainder count and bytes, resumes exactly the saved generator once, requires `StopIteration.value is record['observed']`, and requires its frame to be closed. The first yield cannot satisfy this completion proof. + +The count at D1339-1344 has an exact source interpretation. For original E376-411, let G be the compiled gate list, O the output mapping, R the number of role slots, and S the source mapping. On a successful `optimize == 0` return, the forward and reverse gate loops each perform one predicate for every distinct slot in `ins + outs`, followed by one predicate for every output, one for every final role frame, and one source equality at the end. Thus the count is + +`2 * sum(len(set(ins + outs)) for _, ins, outs in G) + len(O) + R + len(S)`. + +It is a source-derived census under unchanged loops and successful completion, not an observed per-assert trace. `_g12_code_snapshot` binds the actual compiled map before and after. The independent uncached producer uses the same complete common component but obtains its own objects and computations, R895-1016. Cross-process equality concerns lossless tagged values and bytes. Raw object, frame, traceback, and channel identities are within each run only. + +The common payload includes the typed compiled code, role and full returns, certificate bytes, stdout, source pins, fixed h/target, and suffix phase order. D1286-1312 distinguishes tuple from list, bool from int, and preserves dictionary iteration order in explicit tagged entries. That is stronger than untyped JSON value equality. It still does not imply every CP relation below. + +## Important reachability boundary + +After the same original CLI has returned and P07 has completed, S309-311 raises the intentional control marker. The marker follows original argv restoration, disarm, inner and outer retirement, owned cleanup, and STOP handling. The newly added error handlers preserve the already-caught outer primary with a bare raise after guarded bookkeeping, S408-507. The exact repaired handlers retain raw slots before optional journals and block observation export when the journal is incomplete, subject to the original interpreter and non-interference premises. No universal allocation-equivalence claim follows. + +The marker makes D1169-1224 unreachable in the intended control trace. Those source bytes remain present, but their full-caller qualification is not executed by this local control. In particular, D1186-1188 holds the full native runtime/counter check, D1190-1193 constructs and serialises the full side witness, D1194-1195 checks the complete ordered complement transcript, D1201-1203 compares the independent full anchor, and D1213-1215 performs normal finalisation and late-last. S448-449 expressly leaves disposition qualification open and disclaims full-positive/native credit. R similarly uses its intentional marker before its original full-positive publication path. This is the already declared local-control boundary, not a new PR6339 regression. + +Consequently, retaining the source text of stronger checks and completing P07's two comparisons is insufficient to establish full CP01-CP15 acceptance. Removing the marker would change the original control protocol and could expose intentionally changed native/cache counts to the full-positive checks. No such patch is justified by this review. A later full-caller activity must preserve and qualify the original checks in their original admitted activity, and must not relabel the local G12 observation as that qualification. + +## Consequential CP coverage + +`Conditional` means an inspected source argument under stated original premises, not an observed run or acceptance of the integrated custody graph. `Open` identifies what is not established by this review. + +| Predicate | Inspected source and invariant | Disposition and consequential obligation | +| --- | --- | --- | +| CP01, source and owner identity | A2111-2157 authenticates the exact transport path/hash before executing it and inserts the captured Root/capability/API objects. A2361-2381 rechecks invocation identity and result shape. S24-66 checks helper and suite graph/currentness. | Conditional local edge compatibility. Current transport pins are `None`; every actual staged source, authority pin, typed full owner, bootstrap dependency, and function graph still needs a single coherent integration. Shape is not authority. | +| CP02, fresh complete callers | R858-860 restricts the independent producer to profile/no-anchor. R895-1016 derives observations from its original uncached objects. S151-189 binds a fresh unconsumed main-local generation and its exact token. S304-369 resumes after that same CLI returns. | Conditional local independence and continuation argument. Actual separate fresh processes, genuine reference custody, original controls, and admission remain open. No candidate-produced result or historical finite observation can replace reference bytes. | +| CP03, assertions and modes | S147-149 refuses finite-only or optimised selected control. D925-929 retains the original full-mode assertion and CPython 3.12 gates. R1153-1160 also requires optimise zero for the producer. | Source gate preserved. Neither a `None` selection refusal nor an optimised refusal is valid-path evidence. A future positive must run the original assertion scope. | +| CP04, arithmetic oracle | Y227-233 compares original public `label_ok` type/value with the independent literal. K2133-2140 and K2174-2180 retain public fallback/Owner data after retirement. E376-411 retains original role predicates. | Conditional local oracle path. Genuine native/current-data/Fraction/kernel checks and the full source/owner closure are prerequisites; typed values alone do not establish provenance. | +| CP05, original outputs | S314-347 and D1347-1362 bind same-run return/role identity and exact typed common payload, certificate, stdout, phases, and code. | Partial. Full side witness, complete ordered complement comparison, and independent full anchor at D1190-1203 are bypassed by the local marker. They remain full-caller gates. Diagnostics custody is not a proof of equality of these observations. | +| CP06, phases and imports | S304-341 checks the actual returned CLI namespace and original phase completions. S375-405 checks source import paths and final exactly-once phase counts after original finally. | Conditional local same-CLI source argument. Requires authentic source/closure graphs. Complete scientific caller equality remains bounded by CP05/07/15 and the external source closure. | +| CP07, native and fallback | K2058-2061 retains current source/native guard before admitted accesses. K2133-2193 retires metadata before real public fallback. S192-208 records counters; S348-351 records native suffix deltas. | Partial. Counter diagnostics are not the full equality check. D1186-1188's exact counts and zero fallback belong to later original full-caller qualification and are not established by P07's common bytes. | +| CP08, enrolment and lifetime | K2084-2121 gives one genuine construction/normalisation and store, at most one pending record, and fixed seven-field committed records. S212-241 checks retained original identities. Y227-233 and S132-139 enforce terminal capacity retirement. | Conditional local proof of the required capacity seam and sole commit. All other public escape/re-entry/error/lifetime branches and their source/currentness premises still need their own complete coverage. | +| CP09, genuine P08 | D and O preserve the same original CLI/arm source. `SOURCE-CASE-CONTEXTS.json` distinguishes the original prearm P08 fixture from the full candidate body. | Inherited obligation, not exercised or independently accepted here. P07's genuine armed context cannot stand in for P08's source-owned prearm relation. | +| CP10, P08 errors and cleanup | D838-898 retains actual argv restoration, disarm, inner retirement, raw fields, and channels. D1225-1267 retains outer retirement, owned cleanup, and STOP. | Source preserved, P08 body oracle open. Same raw P/S/R and labels frame, argv pointer identity, original outer cleanup, and terminal discard remain the separate original P08 requirements. | +| CP11, absent-record cold entry | D1246-1267 retains cold STOP entry and the state/packet-dependent cleanup route. Original context document explicitly distinguishes the five-image absent-record case from finite or P08 cases. | Not requalified. Requires exact cold `state=None`, `packet=None`, genuine source images, raw P/R1/J1/R2/J2 identities, transfer-before-ACK, and no replay. G12 cannot substitute for this case. | +| CP12, raw failures | S408-507 protects all newly added secondary handlers and uses pre-existing raw slots plus a conservative no-export flag. D838-898/1225-1267 retain original raw cleanup ownership. | Conditional narrow preservation of the already-caught primary only. Integrated parent/consumer errors, partial acquisition, failed journalling, all known cleanup attempts, original dispositions, and retained traceback graphs still require review. Formatted STOP JSON is not raw identity evidence. | +| CP13, all original cache bodies | Y differs from B by one yield, with original N22/P07 comparisons/return retained. No source IDs or other helper bodies were removed by this derivation. | Text preservation only, not 52-body acceptance. Original variant multiplicity, fresh N24, retired N18, other controls, and closed full-contract gates remain. Historical 49/52 does not transfer. | +| CP14, alias boundaries | K2745-2766 closes over the genuine driver handler, suite, and original commit before publication. S42-66 adds actual entry/exit/custody function edges to the captured graph. S69-83 checks exact frame/context identity. | Conditional local graph closure. Every new custody/transport/error/descriptor alias and effective global must satisfy original T1-T4 scope. Original exclusions of unrelated callbacks, finalisers, signals, pending callbacks, concurrent mutation, and private corruption must not be silently strengthened. | +| CP15, terminal and side effects | S384-405 checks exact source inventories/modes, runtime file set, reference bytes, imports, and phase counts after original error cleanup. | Partial. Normal full-path finalisation and late-last at D1213-1215 are not reached by the marker trace. Later qualification must establish complete native cleanup and forbid native/provider/Root work after late-last. A close attempt alone cannot prove closed state. | + +## Proposed regression controls, not executed + +The next independent source controls should verify both cases use the same authenticated support block, that C3 does exactly one original store/commit, and that a P07 generator cannot advance twice before the actual original CLI return. They should retain raw object identities for the first yield and final `StopIteration.value`, reject an early stop or second yield, and prove suffix-output publication cannot be manufactured before the return hook. They should test omitted, duplicated, and reordered original phases; wrong types with equal-looking values; changed return-role identity; and stale reference/transport ownership. Error controls should retain the exact escaping primary while injecting failure into each added optional secondary journal, require later known cleanup attempts, and prevent clean observation export after incomplete evidence. These controls remain proposals, and do not include scientific or native execution here. + +No new P07/N22 semantic patch is recommended by this lane. The existing one-yield protocol is coherent at its stated local scope. The justified work is completing custody and exact pin propagation while preserving the protocol, then separately reviewing the original full-caller obligations. Changing scientific equality, replacing the uncached reference producer, relaxing the capacity census, or removing the marker to force a positive would change the problem. + +## Costs and credit boundaries + +C01-C15 in CC remain the original complete symbolic cost obligations. In particular, the retained generator/context/error graphs enter C05/C07/C12, both payloads and evidence enter C13, every failed cleanup enters C14, and all parent and publication tails enter C15. Physical time, CPU, aggregate peak memory, and final tails are unknown and remain `OPEN_NOT_ZERO`. This source consultation supplies no funding, execution, adoption, performance, or kappa credit. The narrow six-edit v2 review's 81 carried checks and 126 static delta checks are historical review claims, not rerun results here. + +Credit remains with Chris R/Clear1nsight, Douglas R. Colkitt's circuit/network lineage, the original source and verification contributors, PR6029/6321, and the retained reviewers. PR6339 remains attributed to unpaidmoon with substantial Cursor Grok assistance. This agent analysis is not human acceptance or a proof-kernel certificate. + + +INDEPENDENT REVIEW OF PARTIAL PATCHES + +# Independent review of the proposed partial successor + +The proposed diffs were reviewed as text against their actual enclosing functions in S `608ad23adc6c01264c8195daf7f18e29c17464a7`. No target function, verifier, or patched target was imported or run. This is an independent source review of the precise changes below, not acceptance of the whole successor. + +## Recommended disposition + +| Proposal | Recommendation | Exact claim supported | +| --- | --- | --- | +| `allocation_hoists_partial.diff` | Include as a deliberately partial repair. | Allocate error-retention storage before the affected local function acquires descriptors, so failure of that initial allocation cannot strand descriptors acquired by that function or replace an already captured local body error. | +| `pidfd_release.patch` | Include with explicit failure-model qualifications. | After the final process-disposal attempt, already recorded pidfds receive a release attempt even when observation or signalling failed. Retiring numeric ownership before close prevents the same stored number being blindly retried after an ambiguous close error. Unknown process or descriptor disposition remains unknown. | +| `publication_size.patch` | Include. | Enforce exact nonnegative integer type for the handoff publication size before its equality comparison and later inclusion in provenance. | +| `explicit_preflight_outcome_partial.diff` | Include if its private helper ABI change is carried through the proposed verifier controls, or clearly identify those controls as stale and unrun. | Classify cleanup failures by the outcome of the protected body, rather than by an unrelated ambient handled exception visible through `sys.exc_info`. This does not fix the helper's remaining allocation and recording failures. | + +## Allocation hoists + +In S parent `_directory_chain`, lines 149-177, the new allocation precedes the first `os.open`. In S parent `_read_file`, lines 242-280, and `_exclusive_directory`, lines 1226-1248, it precedes the call that returns the held directory chain. In `_copy_file`, lines 1267-1282, it precedes the created file descriptor. The consumer hoists have the same relationship at lines 133-161 and 185-223, and put the consumer's final recorder before the retained directory acquisition at lines 1011-1013. The ordinary success path and subsequent original file/schema checks remain in the same order once the allocation succeeds. + +This does not make acquisition atomic. An `os.open` can still succeed before a subsequent `fds.append` or dictionary publication fails. Existing primary tuple creation, close-list materialisation, raw error tuples, and recorder count updates remain fallible. Those failures need their own source disposition. The hoists also do not protect descriptors already owned by a caller when it invokes the function. They establish only that the specific initial recorder allocation is earlier than each function's new local acquisitions. + +There is a real resource consequence. `_directory_chain` originally allocated its recorder only on failure; the hoist allocates the 4,096-slot recorder on successful directory-chain calls as well. The other moved recorders were already allocated on their successful paths. This extra allocation must be charged, and may cause an earlier source refusal under memory pressure. The patch must not be described as universal allocation-equivalence or a measured performance improvement. A non-vacuous clean trace remains compatible when the allocation and original operations succeed. + +## Pidfd release + +S `_KnownG12Chain.finish`, lines 1182-1212, reaches its close loop only after observations report the owned processes, occupied groups, and current children absent. A failure of observation or signalling prevents that loop. S `_g12_finish_failure`, lines 1695-1699, catches the final `finish` failure but has no subsequent pidfd close loop. The proposed `finally` therefore addresses a genuine reachable ownership gap. + +The new `release_known_pidfds` snapshots the currently recorded owners, removes each numeric descriptor from `self.fds`, then attempts `os.close`. Under the original serial ownership premise and functioning bookkeeping, each recorded descriptor is attempted once in the snapshot's insertion order. On an ambiguous close error, retaining the number as active ownership would permit an unsafe later retry; deleting it before the attempt prevents that particular repeated-close error. The failure sets `unknown=True`, retains the raw exception and traceback in order, and does not infer process termination. + +The normal `finish` path recomputes `closed` as `not self.fds and not self.unknown`. The final exceptional cleanup path deliberately sets `unknown=True` before releasing remaining pidfds. Thus an empty descriptor dictionary cannot produce success when either process cleanup or a close remains uncertain. No later process-disposal retry follows this final release site. Under original cooperating-source/no-external-alias premises, I found no newly introduced normal-path ownership or ordering defect in these edits. + +The added method is included in the parent's existing initial class/function graph capture. S523-550 traverses class dictionaries and captures exact function fields, and S554-577 checks those captured members and fields. A future selected parent must nevertheless receive an updated hash and coherent source selection. The patch itself does not select it. + +The limits are material. `tuple(self.fds.items())`, raw error tuple construction, and recorder updates can still fail. A recording failure can stop later pidfd attempts and abort the rest of `_g12_finish_failure`, including streams, reserved outputs, the lease, and directory chains. The enclosing S1749-1759 protects an already recorded parent primary, but does not preserve every additional raw error or ensure every known cleanup attempt after such an abort. Acquisition at S1140-1142 can also succeed before the pidfd is published in `self.fds`. This partial patch cannot justify the claim that every acquired pidfd is always closed, or that all 18 branches are now accepted. + +## Explicit preflight outcome + +The current helper at S223-237 consults `sys.exc_info()[1]` to decide whether a body failure is pending. Python's handled-exception state can instead come from an enclosing caller's `except`, even when the local preflight body succeeded. In that case, the helper appends a close error as a secondary and permits preflight to return instead of raising the close error at that boundary. The final parent may still refuse later, but the original requirement that body success plus close failure stops preflight is not proved by ambient exception state. + +Initialising `body_failed=True` immediately before the protected `try`, and setting it to `False` only at the end of the successful body, gives the helper the right local outcome under the original non-asynchronous-interference premises. It keeps the pending body error propagating on local failure, and makes a first close error primary on body success. It does not rely on cross-process or newly fabricated identity. It changes no scientific code, oracle, or selection. + +The signature change makes S `verify.py` calls at lines 203, 223, and 234 incompatible. The corresponding proposed controls should pass `True` for the test with a pending body error and `False` for the body-success and clean-close tests. That verifier imports target modules and is expressly prohibited from execution in this consultation. Its previously reported PASS cannot be reused after any of these source changes. The exact corrected-source hashes in the verifier and package metadata would also require regeneration if a new package were authored. + +This optional patch retains the unresolved allocation sites in S214-219 and S230-237. Initial recorder/snapshot allocation can still mask a pending body error and skip all closes. Failure while retaining one close error can still skip later descriptors. `body_failed` solves outcome classification only. + +## Publication-size domain + +S consumer line 1001 unpacks `publication_size`. The next check validates the three digest fields, but there is no exact-type check for the publication size. At line 1017, `publication_record['bytes'] == publication_size` allows a finite float `N.0` equal to the genuine integer byte count `N`. Lines 1068-1071 then preserve that float in the returned provenance. A future source-selected handoff containing that float is not rejected at this schema boundary when the rest of its evidence is genuine. This is a type-domain counterexample, not a demonstrated way to forge source or custody. + +The one-line `_uint(publication_size)` fix uses the existing exact `type(value) is int` and nonnegative-domain guard at lines 89-90. It rejects booleans, floats, and foreign equality domains before the later size comparison, while accepting every genuine parent-emitted integer size. All byte, hash, identity, currentness, and schema checks remain in place. A separate positive-domain check is unnecessary here because the subsequent exact byte comparison and JSON/publication schema already reject an empty file. No new ownership or order defect was found in this line. + +## Combined result + +The allocation hoists, pidfd release, and publication-size guard address disjoint local defects and can be composed without altering the independent uncached reference producer or P07/N22 scientific protocol. The parent has elected to exclude the optional helper-ABI change from the concrete three-part proposal. The ambient-exception classification issue therefore remains open. The combined proposal remains a partial successor. Its source inventory and hashes must identify the exact composed bytes, preserve predecessor provenance and the original `None` selections, and keep every unresolved cleanup, allocation, authority, and custody obligation explicit. Proposed regression controls and passive byte/AST checks must be labelled separately from target executions, of which there were none. + + +CONTRACT READ-COVERAGE INVENTORY + +# Contract-lane read coverage + +This inventory separates byte handling from semantic source reading. Complete source bytes were already fetched and verified by the parent. This lane made no additional GitHub retrievals. It did not run any target code or original verifier. + +## Complete textual component or document reads + +The following complete components/documents were read, allowing repeated pin tables and equivalent counterpart files to be handled by passive comparison as stated. + +- `H/snapshot/areas/cache-s0308-source-completion-v1/contracts/CALLER-EQUALITY-DEFINITION-v1.json`. +- `H/snapshot/areas/cache-s0308-source-completion-v1/contracts/COMPLETE-SYMBOLIC-COST-DEFINITION-v1.json`. +- `H/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/DELTA-v2.json`. +- `H/snapshot/areas/cache-s0308-source-completion-v2/g12-protocol-repair/SOURCE-INVERSE-v2.json`. +- `H/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/INTEGRATION-EDGES-v1.json`. +- `H/snapshot/areas/cache-s0308-source-completion-v2/g12-custody-implementation/candidate-integration/g12_candidate_driver_support_P07_custody_v1.py.txt`, all 508 lines. A truncated intermediate display was resolved by rereading the omitted 255-312 span. +- The reconstructed `g12_common_source_v1.py`, all 92 lines, from the complete embedded driver component. +- The reconstructed `g12_cache_selector_source_v1.py`, all 26 lines, from the complete embedded cache component. +- All four proposed patch files named in `PARTIAL-PATCH-INDEPENDENT-REVIEW.md`, including the optional helper-ABI proposal that the parent excluded from its concrete three-part successor. + +## Complete passive byte comparisons and reconstructions + +- The public `cache_epoch_source_controls.py.txt` was read in full as bytes, modified by exactly the user-specified P07 replacement, and compared with both expected SHA-256 values and lengths. Semantic reading focused on `_dispatch`, `_live`, N22, P07, and the relevant context/error helper boundaries. This is not a full independent semantic audit of every original helper body. +- All four `g12-protocol-repair` driver/support files were read in full as bytes, their six inverse replacements were checked as unique, and the resulting complete v1 predecessors matched the original length/hash pins. +- Both v2 drivers, both v2 support files, both custody drivers, and both custody support files were compared within each N22/P07 pair. Each pair differed only in the two contiguous selected-case/helper-pin lines. This transfers the inspected common support mechanism but is not an independent semantic reread of every identical line. +- The full reconstructed P07 v1 driver was compared with the full bundled original `epoch_scientific_driver_v1.py.txt`. Exact differences were enumerated in the contract report. Original CLI/cleanup/STOP spans are unchanged. +- `H/MANIFEST.json` was parsed as JSON and its relevant omission/reference entries read. This is not a line-by-line semantic review of all 316 reference rows. + +## Source spans and selected review sections + +| File | Read scope | +| --- | --- | +| Custody `g12_candidate_driver_P07_custody_v1.py.txt` | Full appended common/support components; original CLI boundary 838-898; entry/argument/full-mode gates 900-944; phase/constructor/native binding, original post-CLI and terminal flow 1100-1267. Earlier initial TCB and full native build/control closure were not independently re-reviewed here. | +| `epoch_scientific_driver_v1.py.txt` | Relevant original main/CLI/post-CLI/cleanup spans, plus complete passive diff. | +| `g12_epoch_cache_selector_v1.py.txt` | Original stated serial/non-interference premises at 1-27; constructor-product capture; suite construction/products/currentness, construction/commit, request/fallback/retirement at 1984-2206; complete C3 selector 2741-2768. Remaining full V8/native/factory closure not independently re-reviewed. | +| Custody `g12_epoch_authority_custody_v1.py.txt` | Fixed loader and invoke paths 2108-2157 and 2361-2397, plus exact source references to the original graph/capture mechanism. Full 2,459-line authority not independently re-reviewed. | +| `g12_reference_driver_v2.py.txt` | Original main and full qualification boundary 255-352; exact common component; profile/no-anchor gate; original prefix, same-CLI return, restoration, exports, and entry at 895-1150; bootstrap assertion/currentness dependencies identified. Entire producer authentication closure was not independently re-proved. | +| Original `source/complex_circuit.py.txt` | Checks construction/cache, `label_ok`, label verification, compile_roles, and full role loops 265-411. | +| `SOURCE-CASE-CONTEXTS.json` | Original P08, V4/V5 raw/absent-record relations, mandatory ownership/admission, and inherited-control boundaries. | +| `cache_epoch_context_assembly_v1.py.txt` | Function/source inventory and relevant control-context references were searched. No complete assembler proof is claimed. | +| `G12-CANDIDATE-PROTOCOL-REVIEW-v1.json` | Blocking findings, stated scope/open obligations, and all independently established source-check narratives and source spans. Exact input inventory/pin repetition was inspected selectively. | +| `G12-CANDIDATE-PROTOCOL-REVIEW-v2.json` | Six-edit disposition, raw bookkeeping and graph reasoning, scope and preservation limits, static-count claims, and relevant source spans. Static-count claims were not rerun. | +| `GRAPH-ADDENDUM-v1.json` | Disconnected-function graph finding, original capture mechanism, required narrow repair, and scope limits. | +| S corrected parent | Independent patch review read complete `_RawG12Errors`, `_directory_chain`, `_raise_preserved`, both new close helpers, `_read_file`, `_capture_graph`/`_current_graph`, `_KnownG12Chain`, `_exclusive_directory`, `_copy_file`, relevant preflight/launch/observe flow, and complete final failure handler plus enclosing catches. S schemas and broader parser code were not all independently reread by this lane. | +| S corrected consumer | Directory acquisition/read cleanup functions, final retained-directory body and enclosing setup relevant to allocation hoists. Broader complete consumer audit belongs to the custody lane. | +| S `verify.py` | The three changed-ABI call sites and the helper-source-shape assertion. This lane did not rerun or fully re-review the verifier. | + +Any display truncation not resolved by a subsequent targeted read is treated as a span/section read, not complete-file reading. No completeness claim is based on search excerpts or static counts alone. diff --git a/research/h25-g12-custody-repairs/verify.py b/research/h25-g12-custody-repairs/verify.py new file mode 100644 index 0000000000..564c7b35e4 --- /dev/null +++ b/research/h25-g12-custody-repairs/verify.py @@ -0,0 +1,384 @@ +"""Bounded source-function controls. No full target import or scientific entry. + +The source functions selected below execute against synthetic descriptor/process +tokens. The retained allocation witnesses are EXPECTED REFUTATIONS of stronger +claims; a passing verifier does not grant integrated G12/P07 acceptance. +""" +import ast +import builtins +import copy +import hashlib +import json +from pathlib import Path +import sys +from types import SimpleNamespace + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +ROWS = [] + + +def need(value, message): + if not value: + raise RuntimeError(message) + + +def check(name, predicate, classification="bounded-control"): + need(predicate, "CONTROL FAILED: " + name) + ROWS.append({"name": name, "classification": classification}) + + +def capture(function): + try: + function() + except BaseException as error: + return error + return None + + +def read_sources(): + manifest = json.loads((HERE / "SOURCE-IDENTITIES.json").read_text()) + sources = {} + for row in manifest["files"]: + raw = (HERE / row["path"]).read_bytes() + check("source bytes " + row["path"], len(raw) == row["bytes"] and + hashlib.sha256(raw).hexdigest() == row["sha256"], "byte-identity") + sources[row["path"]] = ast.parse(raw.decode(), filename=row["path"]) + source_pins = json.loads((HERE / "SOURCES.json").read_text()) + for row in source_pins["files"]: + if row["usage"] == "input": + raw = (ROOT / row["path"]).read_bytes() + check("canonical input " + row["path"], + hashlib.sha256(raw).hexdigest() == row["sha256"], "byte-identity") + return sources + + +def definition(tree, name): + if "." in name: + parent, child = name.split(".", 1) + owner = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == parent) + return next(n for n in owner.body if isinstance(n, ast.FunctionDef) and n.name == child) + return next(n for n in tree.body + if isinstance(n, (ast.FunctionDef, ast.ClassDef)) and n.name == name) + + +def execute_definitions(tree, names, extra=None): + # Only the explicitly named definitions, not imports or module-level entries. + body = [copy.deepcopy(definition(tree, name)) for name in names] + env = {"__builtins__": builtins.__dict__, "__name__": "_g12_synthetic_controls", + "_need": need, "sys": sys} + if extra: + env.update(extra) + exec(compile(ast.fix_missing_locations(ast.Module(body=body, type_ignores=[])), + "", "exec"), env) + return env + + +def source_binding(sources): + for kind, allowed in [ + ("parent", {"_directory_chain", "_read_file", "_KnownG12Chain", + "_exclusive_directory", "_copy_file", "run_g12_reference"}), + ("cold_consumer", {"_directory_chain", "_read_file", "load_original_g12_reference"}), + ]: + old = sources["predecessor/g12_reference_" + kind + "_v2.py.txt"] + new = sources["corrected/g12_reference_" + kind + "_v3.py"] + def index(tree): + return {getattr(n, "name", "item-" + str(i)): ast.dump(n, include_attributes=False) + for i, n in enumerate(tree.body)} + a, b = index(old), index(new) + changed = {k for k in a.keys() | b.keys() if a.get(k) != b.get(k)} + check("only declared " + kind + " definitions changed", changed == allowed, + "complete-AST-delta") + selections = {t.id: n.value for n in new.body if isinstance(n, ast.Assign) + for t in n.targets if isinstance(t, ast.Name) + and t.id in {"G12_REFERENCE_HANDOFF", "G12_REFERENCE_LAUNCH_SELECTION"}} + check(kind + " selection remains closed", bool(selections) and + all(isinstance(v, ast.Constant) and v.value is None for v in selections.values()), + "closed-selection") + + # Apply the literal upstream-path diff IN MEMORY to the two retained sources. + patch = (HERE / "repairs-from-pr6339.patch").read_text().splitlines(True) + import re + position = 0 + while position < len(patch): + need(patch[position].startswith("--- a/"), "expected old patch path") + name = Path(patch[position].split()[1]).name + position += 1 + need(patch[position].startswith("+++ b/"), "expected new patch path") + position += 1 + base = (HERE / "predecessor" / (name + ".txt")).read_text().splitlines(True) + cursor, output = 0, [] + while position < len(patch) and not patch[position].startswith("--- a/"): + match = re.match(r"@@ -(\d+)(?:,\d+)? \+\d+(?:,\d+)? @@", patch[position]) + need(match is not None, "malformed patch hunk") + first = int(match.group(1)) - 1 + need(first >= cursor, "overlapping patch hunk") + output.extend(base[cursor:first]) + cursor = first + position += 1 + while position < len(patch) and not patch[position].startswith(("@@ ", "--- a/")): + line = patch[position] + position += 1 + need(line[:1] in (" ", "+", "-"), "unsupported patch line") + if line[0] in " -": + need(cursor < len(base) and base[cursor] == line[1:], "patch base mismatch") + cursor += 1 + if line[0] in " +": + output.append(line[1:]) + output.extend(base[cursor:]) + target = (HERE / "corrected" / name.replace("_v2.py", "_v3.py")).read_text() + check("exact in-memory diff " + name, "".join(output) == target, "complete-byte-delta") + + +def allocation_controls(tree, kind, version): + names = ["_directory_chain", "_read_file"] + if kind == "parent": + names += ["_exclusive_directory", "_copy_file"] + else: + names += ["load_original_g12_reference"] + for name in names: + acquired, closed = [], [] + primary = RuntimeError("synthetic original body failure") + allocation = MemoryError("injected raw-ledger allocation failure") + + def allocate(): + raise allocation + + def opened(*args, **kwargs): + acquired.append(901) + return 901 + + def directory(*args, **kwargs): + acquired.append(902) + return [902], [] + + def denied(*args, **kwargs): + raise primary + + fake_os = SimpleNamespace(open=opened, close=closed.append, stat=denied, + O_RDONLY=0, O_DIRECTORY=0, O_CLOEXEC=0, + O_NOFOLLOW=0, O_WRONLY=0, O_CREAT=0, O_EXCL=0) + extra = {"_RawG12Errors": allocate, "_path": lambda p: p, "os": fake_os, + "_directory_chain": directory} + if name == "load_original_g12_reference": + # Isolate the actual two allocation/acquisition statements at the + # retained-directory boundary, not the genuine Root-authentication entry. + node = definition(tree, name) + statements = [] + for statement in node.body: + if isinstance(statement, ast.Assign): + ids = [n.id for n in ast.walk(statement.targets[0]) + if isinstance(n, ast.Name)] + if "dirs" in ids or {"primary", "secondaries", "result"} <= set(ids): + statements.append(copy.deepcopy(statement)) + need(len(statements) == 2, "consumer allocation-window source changed") + env = {"__builtins__": builtins.__dict__, "_RawG12Errors": allocate, + "_directory_chain": directory, "retained": "/synthetic/retained"} + unit = compile(ast.fix_missing_locations(ast.Module(body=statements, + type_ignores=[])), + "", "exec") + error = capture(lambda: exec(unit, env)) + else: + env = execute_definitions(tree, [name], extra) + args = (([900], []), "new", b"x") if name == "_copy_file" else ( + ("/synthetic/file", 10) if name == "_read_file" else ("/synthetic",)) + error = capture(lambda: env[name](*args)) + expected_acquisitions = 1 if version == "predecessor" else 0 + check(kind + "/" + name + "/" + version + " ledger-failure boundary", + error is allocation and len(acquired) == expected_acquisitions and not closed, + "source-function-fault-injection") + + +def cleanup_controls(parent): + closes = [] + first_close = OSError("synthetic close failure") + late_close = OSError("synthetic later close failure") + errors = {903: first_close, 901: late_close} + + def close(fd): + closes.append(fd) + if fd in errors: + raise errors[fd] + + env = execute_definitions( + parent, ["_RawG12Errors", "_close_known_descriptors", "_finally_close_known"], + {"os": SimpleNamespace(close=close)}) + primary = ValueError("synthetic body primary") + secondaries = env["_RawG12Errors"]() + + def failing_body(): + try: + raise primary + finally: + env["_finally_close_known"]([901, 902, 903], secondaries) + actual = capture(failing_body) + check("ordinary preflight keeps same primary and attempts all known closes", + actual is primary and closes == [903, 902, 901] and + [item[0] for item in secondaries] == [first_close, late_close], + "source-function-positive-control") + + closes.clear() + secondaries = env["_RawG12Errors"]() + actual = capture(lambda: env["_finally_close_known"]([901, 902, 903], secondaries)) + check("successful body promotes first close failure once", + actual is first_close and closes == [903, 902, 901] and + [item[0] for item in secondaries] == [late_close], + "source-function-positive-control") + + # Deliberately retain the still-failing stronger contract as a red witness. + for fault in ["ledger", "snapshot", "record"]: + closes.clear() + allocation = MemoryError("retained " + fault + " failure witness") + env = execute_definitions( + parent, ["_RawG12Errors", "_close_known_descriptors", "_finally_close_known"], + {"os": SimpleNamespace(close=close)}) + if fault == "ledger": + def bad_ledger(): + raise allocation + env["_RawG12Errors"] = bad_ledger + elif fault == "snapshot": + def bad_snapshot(values): + raise allocation + env["tuple"] = bad_snapshot + else: + class BadRecorder: + def append(self, value): + raise allocation + env["_RawG12Errors"] = BadRecorder + secondaries = [] + def witness(): + try: + raise primary + finally: + env["_finally_close_known"]([901, 902, 903], secondaries) + actual = capture(witness) + check("UNRESOLVED preflight " + fault + " masks primary/skips later closes", + actual is allocation and actual is not primary and + closes == ([903] if fault == "record" else []), + "retained-contract-counterexample") + + +def pidfd_controls(old, new): + release = execute_definitions(new, ["_KnownG12Chain.release_known_pidfds"]) + for failures in [set(), {901}, {901, 902}]: + attempts, errors = [], {} + chain = SimpleNamespace(fds={(1, 11): 901, (2, 12): 902}, + unknown=False, closed=False) + def close(fd): + need(fd not in chain.fds.values(), "numeric owner was not retired before close") + attempts.append(fd) + if fd in failures: + errors[fd] = OSError("synthetic ambiguous close") + raise errors[fd] + release["os"] = SimpleNamespace(close=close) + secondaries = [] + release["release_known_pidfds"](chain, secondaries) + check("pidfd release attempts all/retains raw failures " + str(sorted(failures)), + attempts == [901, 902] and not chain.fds and + chain.unknown == bool(failures) and chain.closed is False and + [item[0] for item in secondaries] == [errors[fd] for fd in [901, 902] + if fd in failures], + "source-function-positive-control") + release["release_known_pidfds"](chain, secondaries) + check("ambiguous pidfd close is never blindly retried " + str(sorted(failures)), + attempts == [901, 902], "source-function-negative-control") + + for tree, label in [(old, "predecessor"), (new, "corrected")]: + attempts, secondaries = [], [] + denial = PermissionError("persistent synthetic process-observation denial") + chain = SimpleNamespace(fds={(1, 11): 901, (2, 12): 902}, + unknown=False, closed=False) + def denied_finish(*args): + raise denial + chain.finish = denied_finish + rel_env = execute_definitions(new, ["_KnownG12Chain.release_known_pidfds"], + {"os": SimpleNamespace(close=attempts.append)}) + chain.release_known_pidfds = lambda journal: rel_env["release_known_pidfds"](chain, journal) + owner = definition(tree, "run_g12_reference") + nested = next(n for n in owner.body if isinstance(n, ast.FunctionDef) + and n.name == "_g12_finish_failure") + nested = copy.deepcopy(nested) + nested.body = [n for n in nested.body if not isinstance(n, ast.Nonlocal)] + namespace = {"__builtins__": builtins.__dict__, "chain": chain, + "selection": {"body_deadline_ns": 1, "retention_tail_allowance_ns": 1}, + "process": None, "secondaries": secondaries, "outer": {}, "reserved": {}, + "lease": None, "lease_closed": False, "observation": None, + "science_directory": None, "run_directory": None, "retained": None, + "os": SimpleNamespace(close=attempts.append)} + exec(compile(ast.fix_missing_locations(ast.Module(body=[nested], type_ignores=[])), + "", "exec"), namespace) + namespace["_g12_finish_failure"]() + expected = [] if label == "predecessor" else [901, 902] + check("actual P09 persistent-denial pidfd cleanup " + label, + attempts == expected and secondaries[0][0] is denial and + (label == "predecessor" or (not chain.fds and chain.unknown and + chain.closed is False)), + "source-function-regression-control") + + +def publication_size_controls(old, new): + for tree, label in [(old, "predecessor"), (new, "corrected")]: + fn = definition(tree, "load_original_g12_reference") + size_gate = [copy.deepcopy(n) for n in fn.body if isinstance(n, ast.Expr) + and isinstance(n.value, ast.Call) + and isinstance(n.value.func, ast.Name) and n.value.func.id == "_uint" + and n.value.args and isinstance(n.value.args[0], ast.Name) + and n.value.args[0].id == "publication_size"] + comparison = next(n for n in ast.walk(fn) if isinstance(n, ast.Expr) + and isinstance(n.value, ast.Call) and + any(isinstance(a, ast.Constant) and + a.value == "G12-N15: source-selected final publication bytes" + for a in n.value.args)) + code = compile(ast.fix_missing_locations(ast.Module( + body=size_gate + [copy.deepcopy(comparison)], type_ignores=[])), + "", "exec") + class ForeignInt(int): + pass + for value, observed, accepted in [(1234, 1234, True), (0, 0, True), + (1234.0, 1234, False), (True, 1, False), + (ForeignInt(1234), 1234, False), + ("1234", 1234, False), (-1, 1234, False)]: + env = execute_definitions(tree, ["_uint"]) + env.update({"publication_size": value, "publication_sha": "digest", + "publication_record": {"sha256": "digest", "bytes": observed}}) + error = capture(lambda: exec(code, env)) + old_accepts = observed == value + check("publication exact-size " + label + "/" + type(value).__name__ + "/" + repr(value), + (error is None) == (old_accepts if label == "predecessor" else accepted), + "actual-source-schema-control") + + +def main(): + sources = read_sources() + source_binding(sources) + for kind in ["parent", "cold_consumer"]: + allocation_controls(sources["predecessor/g12_reference_" + kind + "_v2.py.txt"], + kind, "predecessor") + allocation_controls(sources["corrected/g12_reference_" + kind + "_v3.py"], + kind, "corrected") + parent = sources["corrected/g12_reference_parent_v3.py"] + cleanup_controls(parent) + pidfd_controls(sources["predecessor/g12_reference_parent_v2.py.txt"], parent) + publication_size_controls(sources["predecessor/g12_reference_cold_consumer_v2.py.txt"], + sources["corrected/g12_reference_cold_consumer_v3.py"]) + need(len({row['name'] for row in ROWS}) == len(ROWS), "duplicate check identity") + cases = sum(row['classification'].startswith(('source-function-', 'actual-source-')) + or row['classification'] == 'retained-contract-counterexample' for row in ROWS) + report = {"schema": "h25-g12-bounded-source-controls-v1", + "status": "PARTIAL_SOURCE_REPAIR_WITH_RETAINED_COUNTEREXAMPLES", + "checks_total": len(ROWS), "source_function_cases": cases, + "metadata_checks": len(ROWS) - cases, "checks": ROWS, + "executed_scope": "Named AST-extracted source functions/windows with synthetic tokens", + "full_target_module_imports": 0, "original_H25_scientific_invocations": 0, + "native_or_process_operations": 0, "author_verifier_replayed": False, + "integrated_source_acceptance": False, "N22_P07_body_credit": False, + "performance_or_kappa": False, "unknown_costs": "OPEN_NOT_ZERO", + "environment": {"python": sys.version, "optimize": sys.flags.optimize}} + print(json.dumps(report, sort_keys=True)) + print("PASS_G12_BOUNDED_SOURCE_REPAIRS source_cases=" + str(cases) + + " metadata_checks=" + str(len(ROWS) - cases) + + " unresolved_preflight_allocation=3 no_integrated_acceptance") + + +if __name__ == "__main__": + main()