diff --git a/research/h25-parent-waiting-entry/NEXT-QUESTIONS.md b/research/h25-parent-waiting-entry/NEXT-QUESTIONS.md new file mode 100644 index 0000000000..bf6d744186 --- /dev/null +++ b/research/h25-parent-waiting-entry/NEXT-QUESTIONS.md @@ -0,0 +1,8 @@ +# Open next questions + +1. Build the actual immutable successor assembly, including source/role/loader/controller/stage manifests and all transitive dependencies, without altering historical pins. The current isolated directory is not that assembly. +2. Independently review the exact parent caller, entry, terminal reader and deadline retirement as one chain. In particular inspect raw error precedence, inherited aliases, uncertain releases/waits, normal versus optimized dispositions and finalizer timing. +3. Exercise the genuinely authenticated parent qualification path under its complete paid, bounded attempt envelope. The current fixture deliberately substitutes those ports and provides no native or actual-instance qualification. +4. Complete the original fixed baseline/candidate ordering, full receiver/equality, symmetric primary measurements, retention and CLOSE/readback. No local helper or publication can substitute for these conditions. + +The next useful action is source-assembly and caller review, not repeating already successful unchanged fixtures or changing the acceptance criterion. Native/scientific execution remains unadmitted until its existing source, ownership, resource and funding gates close. diff --git a/research/h25-parent-waiting-entry/NOTICE.md b/research/h25-parent-waiting-entry/NOTICE.md new file mode 100644 index 0000000000..d7edfcd69b --- /dev/null +++ b/research/h25-parent-waiting-entry/NOTICE.md @@ -0,0 +1,7 @@ +# Attribution and modification notice + +This source archive extends Clear1nsight's original investigation in PR #6321 and the source/ownership/relay work in PRs #6762, #6830 and #6847. All predecessor attribution, Apache-2.0 licensing and source-specific notices remain applicable. The repository LICENSE and NOTICE are retained in the unchanged parent tree. + +The waiting-entry implementation, parent qualification connection, caller/receiver adaptation and standalone fixtures were prepared for Clear1nsight with substantial OpenAI Codex assistance. ProtectedRoot, DeadlineOwner and the common-runner starting point adapt a partial ChatGPT Pro proposal recovered on 2026-11-07. That proposal was incomplete and was changed during implementation. No independent human review or scientific admission is claimed. + +Every implementation file in this directory is a modified successor, not an unmodified upstream reference. Original local files, earlier source snapshots and failed controls were preserved. SOURCE-MANIFEST.json distinguishes authored bytes, publication notice comments and retained executed snapshots. The archive does not import the mathematical construction, licenses or notices of unrelated research packages. diff --git a/research/h25-parent-waiting-entry/PROVENANCE.json b/research/h25-parent-waiting-entry/PROVENANCE.json new file mode 100644 index 0000000000..676634f3fb --- /dev/null +++ b/research/h25-parent-waiting-entry/PROVENANCE.json @@ -0,0 +1,106 @@ +{ + "upstream_base": "7c49fe32c55de02c2c873655c804b16e4c3fef0a", + "original_pr": 6321, + "related_inspected_heads": { + "6762": "3bcf99910a95248452e955d382c59bd23792a39b", + "6830": "39fcd67c991bd72918080b1d2c02feb3d679206d", + "6847": "efb116491184bd16c5d1ada60d71efdefee61691" + }, + "reuse": "Adapt recovered Pro ProtectedRoot/DeadlineOwner/common-runner partial; retain predecessor relay/owner/source/original command contracts. Add actual lexical caller wiring rather than another dormant helper.", + "overlap_search": "All-author/all-state PR body search for ProtectedRoot returned zero at round opening; bounded search is not global novelty. Main and implicated heads refreshed.", + "external_dependencies": "Original absolute paths are preserved reference bindings. Full local source/role assembly and actual native/environment qualification are external and not shipped as executable closure.", + "test_snapshots": { + "controls-v3": { + "fresh_supervisor.py": "2483d0e26d75fa86c52148de936bebc1e3b71b988f46a7642ede2197ee590e05", + "bounded_relay.py": "2bd356f6b886c1ca417ee866c99863d96c27c7c5a59e9e22e6bfad3c2bb335ee", + "candidate_entry.py": "773afb0903991cd2751c7f398418ebe18e15aae9628c0e57902dab921796c18c", + "run_guarded_v3.py": "87e12a80e26fd6ef8df9bbb76bfd294f09533942f4504e9772f701e06b9218f1" + }, + "controls-v4": { + "fresh_supervisor.py": "2483d0e26d75fa86c52148de936bebc1e3b71b988f46a7642ede2197ee590e05", + "bounded_relay.py": "2bd356f6b886c1ca417ee866c99863d96c27c7c5a59e9e22e6bfad3c2bb335ee", + "candidate_entry.py": "0c7987aa893473c47c9785856b7be233c80991dfe97a36bd4a9953549b95ff24", + "run_guarded_v3.py": "87e12a80e26fd6ef8df9bbb76bfd294f09533942f4504e9772f701e06b9218f1" + }, + "controls-v5": { + "fresh_supervisor.py": "04406464851db70bea7c69ac02d87b070e60be30861eba9659f35dfd3781e842", + "bounded_relay.py": "2bd356f6b886c1ca417ee866c99863d96c27c7c5a59e9e22e6bfad3c2bb335ee", + "candidate_entry.py": "0c7987aa893473c47c9785856b7be233c80991dfe97a36bd4a9953549b95ff24", + "run_guarded_v3.py": "87e12a80e26fd6ef8df9bbb76bfd294f09533942f4504e9772f701e06b9218f1" + }, + "controls-v7": { + "fresh_supervisor.py": "04406464851db70bea7c69ac02d87b070e60be30861eba9659f35dfd3781e842", + "bounded_relay.py": "2bd356f6b886c1ca417ee866c99863d96c27c7c5a59e9e22e6bfad3c2bb335ee", + "candidate_entry.py": "0c7987aa893473c47c9785856b7be233c80991dfe97a36bd4a9953549b95ff24", + "run_guarded_v3.py": "87e12a80e26fd6ef8df9bbb76bfd294f09533942f4504e9772f701e06b9218f1" + } + }, + "source_rows": [ + { + "path": "implementation/bindings/private_loader.py", + "sha256": "f0b31dc974d774bdceed784d626e00688619281d3baa9ece58c002b04d24af16", + "bytes": 41243, + "local_authored_sha256": "a4589101ccbe56f96b457eaa83e1a663cae263ae5cccf693b45fa7ead47b58b6", + "publication_difference": "one leading modification-notice comment; AST equal" + }, + { + "path": "implementation/bootstrap/controller_entry.py", + "sha256": "a8432c30466e88753398a7b2641918e07823060b6ffc522ec3ea6cdfd946fd9f", + "bytes": 10604, + "local_authored_sha256": "153ab8da6e919188b436d30f9dab3e2d746a47809a3f2b42d267c51c74dfe9fe", + "publication_difference": "one leading modification-notice comment; AST equal" + }, + { + "path": "implementation/controller/composed_controller.py", + "sha256": "f136fc84eeea8bb318df7f4fdec32cc78f1aa7b11ef3f143778ea498576dffb7", + "bytes": 100729, + "local_authored_sha256": "6763de293acec9c8284e83a065d394f0d6821136998a0c490312432bb4a93788", + "publication_difference": "one leading modification-notice comment; AST equal" + }, + { + "path": "implementation/source/bounded_relay.py", + "sha256": "db49147c02d70e3494375cb203b1501a143c4c7c66074f6cb5e6c3c2e9ef362e", + "bytes": 16280, + "local_authored_sha256": "2bd356f6b886c1ca417ee866c99863d96c27c7c5a59e9e22e6bfad3c2bb335ee", + "publication_difference": "one leading modification-notice comment; AST equal" + }, + { + "path": "implementation/source/candidate_entry.py", + "sha256": "048e5020c8424e168a614809aaab8c3c188b78de1269a2bf73f7393389b58120", + "bytes": 24755, + "local_authored_sha256": "0c7987aa893473c47c9785856b7be233c80991dfe97a36bd4a9953549b95ff24", + "publication_difference": "one leading modification-notice comment; AST equal" + }, + { + "path": "implementation/source/composed_queue.py", + "sha256": "06cb0bc8393dad361470719fb7d9603bd33314bb191ef91eecb301992618775a", + "bytes": 17167, + "local_authored_sha256": "0d25e6a02df4af018d649abbe884a2abb84e9a32089fb4e94a90a080b2d2938c", + "publication_difference": "one leading modification-notice comment; AST equal" + }, + { + "path": "implementation/source/fresh_supervisor.py", + "sha256": "73741e77533eb7022c583842e01e120bdaa24461d68fac8fb0af784ae93c9163", + "bytes": 126369, + "local_authored_sha256": "8588ac0a24cb039bed87d42145ec37c935b66cb40b16057565d955e185d46566", + "publication_difference": "one leading modification-notice comment; AST equal" + }, + { + "path": "implementation/source/full_result_receiver.py", + "sha256": "368c1d4668b13ba47fef6e6b7e0dd80096c63a2e323f042a99716b4513bf7e2f", + "bytes": 26088, + "local_authored_sha256": "4bf578dad37abe7b933e7034cebcf5885eb1788d12cab1ffb0e44d578e172b64", + "publication_difference": "one leading modification-notice comment; AST equal" + }, + { + "path": "implementation/source/run_guarded_v3.py", + "sha256": "1bd63a710f5e2d8124ec32637cfc01d9932e976554c5307f828a19b7e6993304", + "bytes": 21276, + "local_authored_sha256": "87e12a80e26fd6ef8df9bbb76bfd294f09533942f4504e9772f701e06b9218f1", + "publication_difference": "one leading modification-notice comment; AST equal" + } + ], + "independent_source_review": "Bounded Pro source review of initial commit; concrete first-error defect locally corrected/tested. No complete successor acceptance.", + "original_completion_credit": 0, + "unwind_fixture_publication_delta": "Only source lookup path changes from the colocated guarded snapshot to implementation/source/fresh_supervisor.py; all injected body and production-node selection logic retained." +} diff --git a/research/h25-parent-waiting-entry/README.md b/research/h25-parent-waiting-entry/README.md new file mode 100644 index 0000000000..030be8b9e1 --- /dev/null +++ b/research/h25-parent-waiting-entry/README.md @@ -0,0 +1,33 @@ +# Parent-owned waiting entry and qualification wiring + +This source archive makes the common-runner candidate entry stop before inner native/scientific birth. The actual parent then qualifies the stopped generation, retires its property-query subtree without disturbing the protected runner/time/entry chain, writes and reads back immutable intent and release records, and sends one pidfd SIGCONT. The implementation connects those operations to the bootstrap, loader, controller and terminal reader. Original investigation: https://github.com/CrocSwap/integer-mult-bounds/pull/6321. + +The source is a concrete implementation candidate. It is not an installed, independently accepted full execution tuple. Its original absolute paths and historical scientific pins are deliberately retained. Do not execute the archived controller or replace a frozen predecessor tree with this directory. A separately declared source assembly, role manifests and complete native/funding qualification are still required. + +## Changed behavior + +- The intent producer waits for an actual stopped entry and held R/time/entry generations. A JSON arrival token alone cannot release work. +- Query cleanup borrows a protected exclusion set. It does not own the root pidfds or the parent execution owner. +- One absolute alarm owner spans launch, qualification and caller validation. A nested query can shorten the working deadline; it cannot give the parent a fresh interval or remove its retirement cutoff. +- The entry uses bounded pipes and inherited capture aliases, retains first failures, and emits closure/result records only after known local retirement. Envelope failures exit 125, distinct from the original optimized refusal exit 1. +- The receiver binds both the common entry command and the original inner command. The original optimized STOP is never rewritten as positive PASS. Parent wall and SELF+CHILDREN CPU endpoints extend through validation. Concurrent waiting/query RSS samples are retained in the owned-forest peak; no new parent RSS admission criterion is introduced. + +## Executed controls and limits + +Standalone fixtures use the new source and the actual private qualification body, with explicitly inert Context/association/schema/funding ports. Real owned processes, pidfds, SIGSTOP/SIGCONT and query descendants execute. The native payload is a fixture-owned byte-identical copy of /usr/bin/false; the scientific driver, compiler, native view and actual property observer do not run. + +The two readback failure controls passed in controls-v3: intent and release-seal readback errors retain the raw error and leave the entry stopped. The positive query-retirement/release control passed in controls-v4 and, after the changed RSS reporting, controls-v7. The two real timer controls passed in controls-v5. These are five distinct bounded behaviors across explicitly pinned snapshots, not a complete caller or resource qualification. + +Earlier failures are retained under evidence/: descriptor-census lifetime, moved-local name, fixture image ownership, missing retention directory and wrong frozen-source modes. The last two were fixture preparation mistakes; production source guards were preserved. Successful unchanged timer and readback controls were not rerun. + +Each fixture dispatch used clean environment, Python 3.12 -S -s -P -B, AS 256 MiB, soft FSIZE 2 MiB/hard 512 MiB, core 0, umask 077 and an outer timeout with kill tail. The file cap applies to capture; complete artifact-fit proof remains open. These settings are test conditions, not universal resource bounds. Costs outside the recorded guard debit remain OPEN_NOT_ZERO. + +Suggested fixture reproduction after deliberate local review: create validation/tmp, set the four source files loaded by the fixture to mode 0444, then run validation/test_waiting_boundary.py under the stated guard. This is not a registered research replay package; no VERIFY hook executes the unqualified scientific images. + +## Remaining decisive check + +See NEXT-QUESTIONS.md. The full authenticated source/role assembly, real parent qualification, baseline/candidate comparison, funding, retention and final CLOSE remain uncompleted. This contribution establishes no speedup, multiplication bound, complete resource admission or original-activity credit. + +## Bounded Pro review and correction + +Pro inspected the exact initial public source and found a first-error ordering defect in both query and root timer unwind. The successor captures the original raw working error before fallible timer pop and records a pop error afterwards. A deterministic collision regression executes both actual production try/except/finally nodes with an injected body error and actual DeadlineOwner expiry against inert clock/signal ports; both preserve the exact original exception object. This correction has local regression evidence, not independent review of the complete successor. Pro did not fully review relay, loader/bootstrap authentication, external dependencies or the full assembly. No such acceptance is claimed. diff --git a/research/h25-parent-waiting-entry/SOURCE-MANIFEST.json b/research/h25-parent-waiting-entry/SOURCE-MANIFEST.json new file mode 100644 index 0000000000..4593d16f85 --- /dev/null +++ b/research/h25-parent-waiting-entry/SOURCE-MANIFEST.json @@ -0,0 +1,105 @@ +{ + "schema": "source-archive-integrity-v1", + "files": { + "NEXT-QUESTIONS.md": { + "bytes": 1223, + "sha256": "d6b48bb81dc0d529c7e7610d346317c2b8555b221b272e58d88077379f59d5f1" + }, + "NOTICE.md": { + "bytes": 1224, + "sha256": "3190854cada01c345ab88e080fe07c713285715494e18a3c70bf1df58c95ead9" + }, + "PROVENANCE.json": { + "bytes": 6284, + "sha256": "648cd29a06b04866622f8fbfb0b9bf0cd2ff8ae4cde8034153813c9cf7707270" + }, + "README.md": { + "bytes": 5046, + "sha256": "7a4a222e9e8e005481eb1e4ffeeb96b2471ba1106a2f51799613b24b597d9b29" + }, + "evidence/controls-v1-stderr.txt": { + "bytes": 6225, + "sha256": "6fb40bdc33fa6d1998ab9227c061d463f95cab04027294964164c7f71ee6a869" + }, + "evidence/controls-v2-stderr.txt": { + "bytes": 5404, + "sha256": "1da30707887c874936049e65fc27732ec1d6b1cdb1362c47e394232bda15a646" + }, + "evidence/controls-v3-stderr.txt": { + "bytes": 2366, + "sha256": "534792d2e9ed5dba0fc34857b1d239798bd9b9f11dd602d4b4c2b9cf95d5ea09" + }, + "evidence/controls-v4-stderr.txt": { + "bytes": 226, + "sha256": "73bc5f0ed489aafb2d146c2bdb64b67955d708ca6855cd22ba39b209ae42bf2f" + }, + "evidence/controls-v5-stderr.txt": { + "bytes": 2340, + "sha256": "7d1d0eeabe38dbd84e65c14f80c1ed54d4603300d1dd3106338f7853650b85e9" + }, + "evidence/controls-v6-stderr.txt": { + "bytes": 1389, + "sha256": "37d1053ac6bba46dacae879c684100b3d074825ee542bd63d0e1ad8177ad4160" + }, + "evidence/controls-v7-stderr.txt": { + "bytes": 226, + "sha256": "043364646aa5207729b32ad863d945267e9c27629a3bb407ae0c9230f3114109" + }, + "evidence/controls-v8-stderr.txt": { + "bytes": 209, + "sha256": "44590b08255f50a968bb68a3f992c62e2a2dc4c2522ce4f2bc446fe629c8e01f" + }, + "implementation/bindings/private_loader.py": { + "bytes": 41243, + "sha256": "f0b31dc974d774bdceed784d626e00688619281d3baa9ece58c002b04d24af16" + }, + "implementation/bootstrap/controller_entry.py": { + "bytes": 10604, + "sha256": "a8432c30466e88753398a7b2641918e07823060b6ffc522ec3ea6cdfd946fd9f" + }, + "implementation/controller/composed_controller.py": { + "bytes": 100729, + "sha256": "f136fc84eeea8bb318df7f4fdec32cc78f1aa7b11ef3f143778ea498576dffb7" + }, + "implementation/source/bounded_relay.py": { + "bytes": 16280, + "sha256": "db49147c02d70e3494375cb203b1501a143c4c7c66074f6cb5e6c3c2e9ef362e" + }, + "implementation/source/candidate_entry.py": { + "bytes": 24755, + "sha256": "048e5020c8424e168a614809aaab8c3c188b78de1269a2bf73f7393389b58120" + }, + "implementation/source/composed_queue.py": { + "bytes": 17167, + "sha256": "06cb0bc8393dad361470719fb7d9603bd33314bb191ef91eecb301992618775a" + }, + "implementation/source/fresh_supervisor.py": { + "bytes": 126369, + "sha256": "73741e77533eb7022c583842e01e120bdaa24461d68fac8fb0af784ae93c9163" + }, + "implementation/source/full_result_receiver.py": { + "bytes": 26088, + "sha256": "368c1d4668b13ba47fef6e6b7e0dd80096c63a2e323f042a99716b4513bf7e2f" + }, + "implementation/source/run_guarded_v3.py": { + "bytes": 21276, + "sha256": "1bd63a710f5e2d8124ec32637cfc01d9932e976554c5307f828a19b7e6993304" + }, + "review/PRO-REVIEW-DISPOSITION.md": { + "bytes": 1670, + "sha256": "e50f963f4d408c86c44669476945af985e9200a5425d577ff56695e2adbd9795" + }, + "validation/test_unwind.py": { + "bytes": 2130, + "sha256": "ca5372e68b36ff7b4a52e821a887c8a4bec86e812621c424819bf7aaa98f651a" + }, + "validation/test_waiting_boundary.py": { + "bytes": 17121, + "sha256": "c02c5149dba92893139d9965bf599c606086a338d3ff4491e4859f54dc67415c" + } + }, + "manifest_excludes_itself": true, + "source_history_complete": false, + "scientific_replay": false, + "modes": "Git100644; deliberate fixture reconstruction uses source0444" +} diff --git a/research/h25-parent-waiting-entry/evidence/controls-v1-stderr.txt b/research/h25-parent-waiting-entry/evidence/controls-v1-stderr.txt new file mode 100644 index 0000000000..ae8e7d399c --- /dev/null +++ b/research/h25-parent-waiting-entry/evidence/controls-v1-stderr.txt @@ -0,0 +1,56 @@ +test_intent_readback_failure_never_releases_stopped_entry (__main__.Boundary.test_intent_readback_failure_never_releases_stopped_entry) ... ERROR +test_release_after_actual_query_subtree_retirement (__main__.Boundary.test_release_after_actual_query_subtree_retirement) ... ERROR +test_release_seal_readback_failure_never_releases_stopped_entry (__main__.Boundary.test_release_seal_readback_failure_never_releases_stopped_entry) ... ERROR + +====================================================================== +ERROR: test_intent_readback_failure_never_releases_stopped_entry (__main__.Boundary.test_intent_readback_failure_never_releases_stopped_entry) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v1/frozen/validation/test_waiting_boundary.py", line 189, in test_intent_readback_failure_never_releases_stopped_entry + def test_intent_readback_failure_never_releases_stopped_entry(self):self.exercise('INTENT.json') + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v1/frozen/validation/test_waiting_boundary.py", line 166, in exercise + with self.assertRaises(OSError) as caught:qualify({'stage':'fixture','job':'normal','label':'FixtureN'},domain,process,outer) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v1/frozen/implementation/source/fresh_supervisor.py", line 1336, in qualify_waiting_candidate + need(registry.poll_root(process) is None,'common runner died before arrival') + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v1/frozen/implementation/source/fresh_supervisor.py", line 51, in need + raise RuntimeError(message) +RuntimeError: common runner died before arrival + +====================================================================== +ERROR: test_release_after_actual_query_subtree_retirement (__main__.Boundary.test_release_after_actual_query_subtree_retirement) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v1/frozen/validation/test_waiting_boundary.py", line 188, in test_release_after_actual_query_subtree_retirement + def test_release_after_actual_query_subtree_retirement(self):self.exercise() + ^^^^^^^^^^^^^^^ + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v1/frozen/validation/test_waiting_boundary.py", line 170, in exercise + protected=qualify({'stage':'fixture','job':'normal','label':'FixtureN'},domain,process,outer) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v1/frozen/implementation/source/fresh_supervisor.py", line 1336, in qualify_waiting_candidate + need(registry.poll_root(process) is None,'common runner died before arrival') + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v1/frozen/implementation/source/fresh_supervisor.py", line 51, in need + raise RuntimeError(message) +RuntimeError: common runner died before arrival + +====================================================================== +ERROR: test_release_seal_readback_failure_never_releases_stopped_entry (__main__.Boundary.test_release_seal_readback_failure_never_releases_stopped_entry) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v1/frozen/validation/test_waiting_boundary.py", line 190, in test_release_seal_readback_failure_never_releases_stopped_entry + def test_release_seal_readback_failure_never_releases_stopped_entry(self):self.exercise('RELEASE.json') + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v1/frozen/validation/test_waiting_boundary.py", line 166, in exercise + with self.assertRaises(OSError) as caught:qualify({'stage':'fixture','job':'normal','label':'FixtureN'},domain,process,outer) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v1/frozen/implementation/source/fresh_supervisor.py", line 1336, in qualify_waiting_candidate + need(registry.poll_root(process) is None,'common runner died before arrival') + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v1/frozen/implementation/source/fresh_supervisor.py", line 51, in need + raise RuntimeError(message) +RuntimeError: common runner died before arrival + +---------------------------------------------------------------------- +Ran 3 tests in 1.015s + +FAILED (errors=3) diff --git a/research/h25-parent-waiting-entry/evidence/controls-v2-stderr.txt b/research/h25-parent-waiting-entry/evidence/controls-v2-stderr.txt new file mode 100644 index 0000000000..921fa4b1e5 --- /dev/null +++ b/research/h25-parent-waiting-entry/evidence/controls-v2-stderr.txt @@ -0,0 +1,53 @@ +test_intent_readback_failure_never_releases_stopped_entry (__main__.Boundary.test_intent_readback_failure_never_releases_stopped_entry) ... ERROR +test_release_after_actual_query_subtree_retirement (__main__.Boundary.test_release_after_actual_query_subtree_retirement) ... ERROR +test_release_seal_readback_failure_never_releases_stopped_entry (__main__.Boundary.test_release_seal_readback_failure_never_releases_stopped_entry) ... ERROR + +====================================================================== +ERROR: test_intent_readback_failure_never_releases_stopped_entry (__main__.Boundary.test_intent_readback_failure_never_releases_stopped_entry) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v2/frozen/validation/test_waiting_boundary.py", line 189, in test_intent_readback_failure_never_releases_stopped_entry + def test_intent_readback_failure_never_releases_stopped_entry(self):self.exercise('INTENT.json') + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v2/frozen/validation/test_waiting_boundary.py", line 166, in exercise + with self.assertRaises(OSError) as caught:qualify({'stage':'fixture','job':'normal','label':'FixtureN'},domain,process,outer) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v2/frozen/implementation/source/fresh_supervisor.py", line 1399, in qualify_waiting_candidate + intent_path = row.intent_path + ^^^ +NameError: name 'row' is not defined. Did you mean: 'pow'? + +====================================================================== +ERROR: test_release_after_actual_query_subtree_retirement (__main__.Boundary.test_release_after_actual_query_subtree_retirement) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v2/frozen/validation/test_waiting_boundary.py", line 188, in test_release_after_actual_query_subtree_retirement + def test_release_after_actual_query_subtree_retirement(self):self.exercise() + ^^^^^^^^^^^^^^^ + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v2/frozen/validation/test_waiting_boundary.py", line 170, in exercise + protected=qualify({'stage':'fixture','job':'normal','label':'FixtureN'},domain,process,outer) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v2/frozen/implementation/source/fresh_supervisor.py", line 1399, in qualify_waiting_candidate + intent_path = row.intent_path + ^^^ +NameError: name 'row' is not defined. Did you mean: 'rows'? + +====================================================================== +ERROR: test_release_seal_readback_failure_never_releases_stopped_entry (__main__.Boundary.test_release_seal_readback_failure_never_releases_stopped_entry) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v2/frozen/validation/test_waiting_boundary.py", line 190, in test_release_seal_readback_failure_never_releases_stopped_entry + def test_release_seal_readback_failure_never_releases_stopped_entry(self):self.exercise('RELEASE.json') + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v2/frozen/validation/test_waiting_boundary.py", line 166, in exercise + with self.assertRaises(OSError) as caught:qualify({'stage':'fixture','job':'normal','label':'FixtureN'},domain,process,outer) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v2/frozen/implementation/source/fresh_supervisor.py", line 1399, in qualify_waiting_candidate + intent_path = row.intent_path + ^^^ +NameError: name 'row' is not defined. Did you mean: 'pow'? + +---------------------------------------------------------------------- +Ran 3 tests in 0.944s + +FAILED (errors=3) diff --git a/research/h25-parent-waiting-entry/evidence/controls-v3-stderr.txt b/research/h25-parent-waiting-entry/evidence/controls-v3-stderr.txt new file mode 100644 index 0000000000..7964d74376 --- /dev/null +++ b/research/h25-parent-waiting-entry/evidence/controls-v3-stderr.txt @@ -0,0 +1,26 @@ +test_intent_readback_failure_never_releases_stopped_entry (__main__.Boundary.test_intent_readback_failure_never_releases_stopped_entry) ... ok +test_release_after_actual_query_subtree_retirement (__main__.Boundary.test_release_after_actual_query_subtree_retirement) ... ERROR +test_release_seal_readback_failure_never_releases_stopped_entry (__main__.Boundary.test_release_seal_readback_failure_never_releases_stopped_entry) ... ok + +====================================================================== +ERROR: test_release_after_actual_query_subtree_retirement (__main__.Boundary.test_release_after_actual_query_subtree_retirement) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v3/frozen/validation/test_waiting_boundary.py", line 189, in test_release_after_actual_query_subtree_retirement + def test_release_after_actual_query_subtree_retirement(self):self.exercise() + ^^^^^^^^^^^^^^^ + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v3/frozen/validation/test_waiting_boundary.py", line 176, in exercise + entry_result=json.loads((case/'runner/ENTRY.json').read_text());self.assertEqual(entry_result['inner_exit'],1) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/pathlib.py", line 1029, in read_text + with self.open(mode='r', encoding=encoding, errors=errors) as f: + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/pathlib.py", line 1015, in open + return io.open(self, mode, buffering, encoding, errors, newline) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +FileNotFoundError: [Errno 2] No such file or directory: '/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v3/frozen/validation/tmp/connected-unuz4ngb/cases/FixtureN/runner/ENTRY.json' + +---------------------------------------------------------------------- +Ran 3 tests in 1.252s + +FAILED (errors=1) diff --git a/research/h25-parent-waiting-entry/evidence/controls-v4-stderr.txt b/research/h25-parent-waiting-entry/evidence/controls-v4-stderr.txt new file mode 100644 index 0000000000..f05a3863b0 --- /dev/null +++ b/research/h25-parent-waiting-entry/evidence/controls-v4-stderr.txt @@ -0,0 +1,6 @@ +test_release_after_actual_query_subtree_retirement (__main__.Boundary.test_release_after_actual_query_subtree_retirement) ... ok + +---------------------------------------------------------------------- +Ran 1 test in 0.421s + +OK diff --git a/research/h25-parent-waiting-entry/evidence/controls-v5-stderr.txt b/research/h25-parent-waiting-entry/evidence/controls-v5-stderr.txt new file mode 100644 index 0000000000..22b57d65b2 --- /dev/null +++ b/research/h25-parent-waiting-entry/evidence/controls-v5-stderr.txt @@ -0,0 +1,27 @@ +test_release_after_actual_query_subtree_retirement (__main__.Boundary.test_release_after_actual_query_subtree_retirement) ... ERROR +test_nested_pop_retains_original_absolute_timer (__main__.Deadlines.test_nested_pop_retains_original_absolute_timer) ... ok +test_work_expiry_keeps_only_original_retirement_deadline (__main__.Deadlines.test_work_expiry_keeps_only_original_retirement_deadline) ... ok + +====================================================================== +ERROR: test_release_after_actual_query_subtree_retirement (__main__.Boundary.test_release_after_actual_query_subtree_retirement) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v5/frozen/validation/test_waiting_boundary.py", line 195, in test_release_after_actual_query_subtree_retirement + def test_release_after_actual_query_subtree_retirement(self):self.exercise() + ^^^^^^^^^^^^^^^ + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v5/frozen/validation/test_waiting_boundary.py", line 102, in exercise + with retained_directory(prefix='connected-',dir=D/'validation/tmp') as temporary: + File "/usr/lib/python3.12/contextlib.py", line 137, in __enter__ + return next(self.gen) + ^^^^^^^^^^^^^^ + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v5/frozen/validation/test_waiting_boundary.py", line 28, in retained_directory + yield tempfile.mkdtemp(*args,**kwargs) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.12/tempfile.py", line 523, in mkdtemp + _os.mkdir(file, 0o700) +FileNotFoundError: [Errno 2] No such file or directory: '/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v5/frozen/validation/tmp/connected-2kfxyvkp' + +---------------------------------------------------------------------- +Ran 3 tests in 0.027s + +FAILED (errors=1) diff --git a/research/h25-parent-waiting-entry/evidence/controls-v6-stderr.txt b/research/h25-parent-waiting-entry/evidence/controls-v6-stderr.txt new file mode 100644 index 0000000000..8ba9ae9d21 --- /dev/null +++ b/research/h25-parent-waiting-entry/evidence/controls-v6-stderr.txt @@ -0,0 +1,18 @@ +test_release_after_actual_query_subtree_retirement (__main__.Boundary.test_release_after_actual_query_subtree_retirement) ... FAIL + +====================================================================== +FAIL: test_release_after_actual_query_subtree_retirement (__main__.Boundary.test_release_after_actual_query_subtree_retirement) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v6/frozen/validation/test_waiting_boundary.py", line 195, in test_release_after_actual_query_subtree_retirement + def test_release_after_actual_query_subtree_retirement(self):self.exercise() + ^^^^^^^^^^^^^^^ + File "/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/connected-supervisor-wiring-20261107T1931Z/validation/controls-v6/frozen/validation/test_waiting_boundary.py", line 180, in exercise + self.assertIsNotNone(process.poll());self.assertTrue(marker.exists()) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +AssertionError: False is not true + +---------------------------------------------------------------------- +Ran 1 test in 0.415s + +FAILED (failures=1) diff --git a/research/h25-parent-waiting-entry/evidence/controls-v7-stderr.txt b/research/h25-parent-waiting-entry/evidence/controls-v7-stderr.txt new file mode 100644 index 0000000000..74cdb48757 --- /dev/null +++ b/research/h25-parent-waiting-entry/evidence/controls-v7-stderr.txt @@ -0,0 +1,6 @@ +test_release_after_actual_query_subtree_retirement (__main__.Boundary.test_release_after_actual_query_subtree_retirement) ... ok + +---------------------------------------------------------------------- +Ran 1 test in 0.458s + +OK diff --git a/research/h25-parent-waiting-entry/evidence/controls-v8-stderr.txt b/research/h25-parent-waiting-entry/evidence/controls-v8-stderr.txt new file mode 100644 index 0000000000..966598b49a --- /dev/null +++ b/research/h25-parent-waiting-entry/evidence/controls-v8-stderr.txt @@ -0,0 +1,6 @@ +test_real_query_and_root_unwind_collision (__main__.Collision.test_real_query_and_root_unwind_collision) ... ok + +---------------------------------------------------------------------- +Ran 1 test in 0.042s + +OK diff --git a/research/h25-parent-waiting-entry/implementation/bindings/private_loader.py b/research/h25-parent-waiting-entry/implementation/bindings/private_loader.py new file mode 100644 index 0000000000..f7eb72c884 --- /dev/null +++ b/research/h25-parent-waiting-entry/implementation/bindings/private_loader.py @@ -0,0 +1,707 @@ +# Modified 2026-11-07: Clear1nsight, with OpenAI Codex and ChatGPT Pro assistance. See NOTICE.md. +"""Actual fixed source transport for the finite joined entry roster. + +All path choices are source-owned. Detached manifests bind already frozen leaf +bytes; no leaf contains its own/future hash. The original exact launcher/OS and +pristine interpreter are the external trust root. This loader corroborates that +selection and creates actual private module namespaces, never JSON contexts. +No import, native operation or execution grant is performed by authoring it. +""" +import builtins +import hashlib +import json +import os +from pathlib import Path +import signal +import stat +import sys +from types import ModuleType, FunctionType + +W = Path('/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453') +R = W / 'outputs/caller-proof-completion-20261107T0155Z' +MANIFEST = R / 'implementation/bindings/SOURCE-MANIFEST-v2.json' +CONTRACTS = R / 'implementation/bindings/ROLE-CONTRACTS-v1.json' +ADMIN = R / 'runtime/admin/IndependentPrefixDATAComposedV1' +RUNTIME = ADMIN / 'control/G-RUNTIME.json' +ENV = {'PATH':'/usr/bin:/bin','PYTHONHASHSEED':'0','LANG':'C.UTF-8', + 'LC_ALL':'C.UTF-8','TZ':'UTC','PYTHONDONTWRITEBYTECODE':'1'} +INITIAL_PATH = ('/usr/lib/python312.zip','/usr/lib/python3.12','/usr/lib/python3.12/lib-dynload') +USED, FIRST, UNKNOWN = [False], [None], [False] +SECONDARY, SLOTS, RETAINED = [None] * 32, [[None,'FREE',None] for _ in range(48)], [] +ROLE = {'M':'M','CAPTURE':'K','PUBLISHER':'P','CONTROLLER':'C2'} +ENTRY = {'M':'pre_m','CAPTURE':'capture_bootstrap','PUBLISHER':'publisher_bootstrap', + 'CONTROLLER':'controller_bootstrap'} +FIXED_PYTHON_PATHS = { + 'C':R/'implementation/controller/composed_controller.py', + 'F':R/'implementation/controller/funding_current.py', + 'A':R/'implementation/controller/active_current.py', + 'publisher':R/'implementation/controller/publisher.py', + 'capture':R/'implementation/carrier/capture.py', + 'inner_meter':R/'implementation/carrier/inner_meter.py', + 'guardian_channel':R/'implementation/bootstrap/guardian_channel.py', + 'layout':R/'implementation/source/layout.py', + 'attempt_registry':R/'implementation/source/attempt_registry.py', + 'supervisor':R/'implementation/source/fresh_supervisor.py', + 'runner':R/'implementation/source/run_guarded_v3.py', + 'common_runner':R/'implementation/source/run_guarded_v3.py', + 'waiting_entry':R/'implementation/source/candidate_entry.py', + 'bounded_relay':R/'implementation/source/bounded_relay.py', + 'full_receiver':R/'implementation/source/full_result_receiver.py', + 'environment_association':R/'implementation/bindings/environment_association.py', + 'compiler_policy':R/'implementation/bindings/compiler_policy.py', + 'query_receiver':R/'implementation/source/property_query_receiver.py', + 'wrapper':R/'implementation/source/composed_wrapper.py', + 'queue':R/'implementation/source/composed_queue.py', + 'envelope':W/'outputs/h25-data-handling-20261028/integration/source_packet_envelope_v2.py', +} +for _role in ('production_issuer','parent_authority','postrun_hook','fork_borrower', + 'archive','oracle','actual_consumer','error_custody','native_io_custody', + 'plain_boundary','reuse_v2'): + FIXED_PYTHON_PATHS[_role] = R/('implementation/retention/' + _role + '.py') + + +class BootstrapStop(RuntimeError): + pass + + +def need(ok, message): + if ok is not True: + raise BootstrapStop(message) + + +def remember(error): + if FIRST[0] is None: + FIRST[0] = error + elif error is not FIRST[0]: + for i, old in enumerate(SECONDARY): + if old is error: + break + if old is None: + SECONDARY[i] = error + break + else: + UNKNOWN[0] = True + return FIRST[0] + + +def exact(obj, keys): + need(type(obj) is dict and all(type(k) is str for k in obj) and + set(obj) == set(keys), 'exact metadata keys') + + +def pairs(values): + obj = {} + for key, value in values: + need(key not in obj, 'duplicate metadata key') + obj[key] = value + return obj + + +def decode(raw): + value = json.loads(raw.decode('utf8'), object_pairs_hook=pairs, + parse_constant=lambda unused: (_ for _ in ()).throw(BootstrapStop('nonfinite metadata'))) + plain(value) + return value + + +def plain(value, depth=0, nodes=None): + if nodes is None: + nodes = [0] + nodes[0] += 1 + need(depth <= 24 and nodes[0] <= 65536, 'bounded metadata tree') + if type(value) is dict: + need(len(value) <= 512 and all(type(k) is str for k in value), 'plain metadata dictionary') + for key, item in value.items(): + need(len(key) <= 512, 'metadata key length') + plain(item, depth + 1, nodes) + elif type(value) is list: + need(len(value) <= 8192, 'metadata list bound') + for item in value: + plain(item, depth + 1, nodes) + elif type(value) is str: + need(len(value) <= 16384, 'metadata text bound') + else: + need(value is None or type(value) in (int, bool), 'plain exact metadata scalar') + + +def canonical(value): + return (json.dumps(value, sort_keys=True, separators=(',', ':'), + allow_nan=False) + '\n').encode('utf8') + + +def identity(info): + return (info.st_dev, info.st_ino, info.st_mode, info.st_nlink, info.st_uid, + info.st_size, info.st_mtime_ns, info.st_ctime_ns) + + +def pin(value): + exact(value, ('path','bytes','sha256','mode')) + need(type(value['path']) is str and Path(value['path']).is_absolute() and + type(value['bytes']) is int and 0 <= value['bytes'] <= 8 * 1024 * 1024 and + type(value['mode']) is int and value['mode'] in (0o444,0o600), 'bounded fixed pin') + need(type(value['sha256']) is str and len(value['sha256']) == 64 and + all(c in '0123456789abcdef' for c in value['sha256']), 'exact pin digest') + + +def read_fixed(path, cap, expected=None, mode=0o444): + need(not UNKNOWN[0] and FIRST[0] is None, 'unknown source transport cannot acquire') + path = Path(path) + need(path.is_absolute() and path.resolve(strict=True) == path, 'canonical selected path') + before = path.lstat() + need(stat.S_ISREG(before.st_mode) and stat.S_IMODE(before.st_mode) == mode and + before.st_uid in (0, os.getuid()) and before.st_nlink == 1 and + 0 <= before.st_size <= cap, 'fixed regular source owner/mode/link/size') + if expected is not None: + pin(expected) + need(expected['path'] == str(path) and expected['mode'] == mode, + 'source-owned fixed path and exact pin mode') + slot = next(item for item in SLOTS if item[1] in ('FREE','CLOSED')) + slot[:] = [None, 'OPEN_PENDING', str(path)] + try: + slot[0] = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC | os.O_NONBLOCK) + slot[1] = 'OWNED' + need(identity(os.fstat(slot[0])) == identity(before), 'source descriptor/path identity') + parts, count = [], 0 + while True: + part = os.read(slot[0], min(65536, cap + 1 - count)) + if not part: + break + parts.append(part) + count += len(part) + need(count <= cap, 'source bound') + raw = b''.join(parts) + need(count == before.st_size and identity(os.fstat(slot[0])) == + identity(path.lstat()) == identity(before), 'stable complete source read') + if expected is not None: + need(count == expected['bytes'] and hashlib.sha256(raw).hexdigest() == + expected['sha256'], 'actual complete source bytes/digest') + except BaseException as error: + remember(error) + if slot[1] == 'OPEN_PENDING': + UNKNOWN[0] = True + raise FIRST[0] + finally: + if slot[1] == 'OWNED': + slot[1] = 'CLOSE_ENTERED' + try: + os.close(slot[0]) + slot[1] = 'CLOSED' + except BaseException as error: + slot[1], UNKNOWN[0] = 'CLOSE_UNKNOWN', True + remember(error) + if FIRST[0] is not None: + raise FIRST[0] + need(not UNKNOWN[0], 'source close must be known before load') + return raw + + +def actual_pin(path, mode=0o444): + raw = read_fixed(path, 8 * 1024 * 1024, mode=mode) + return raw, {'path':str(path),'bytes':len(raw),'sha256':hashlib.sha256(raw).hexdigest(),'mode':mode} + + +def corroborate_image(expected): + """Read a selected ordinary image in bounded chunks, without executing it. + + The original operating TCB selects the subject and proves its semantics. + This check only joins actual stable bytes to that externally selected pin. + A large cc1 or loader image is never accumulated as a source-file body. + """ + exact(expected, ('path','bytes','sha256','mode')) + need(type(expected['path']) is str and Path(expected['path']).is_absolute() and + type(expected['bytes']) is int and 0 < expected['bytes'] <= 536870912 and + type(expected['mode']) is int and 0 <= expected['mode'] <= 0o7777 and + type(expected['sha256']) is str and len(expected['sha256']) == 64 and + all(c in '0123456789abcdef' for c in expected['sha256']), 'exact selected image pin') + need(not UNKNOWN[0] and FIRST[0] is None, 'known loader custody before image read') + slot = next(item for item in SLOTS if item[1] in ('FREE','CLOSED')) + slot[:] = [None, 'RESERVED', expected['path']] + try: + path = Path(expected['path']) + need(path.resolve(strict=True) == path, 'canonical selected image, not a path alias') + before = path.lstat() + need(stat.S_ISREG(before.st_mode) and stat.S_IMODE(before.st_mode) == expected['mode'] and + before.st_uid in (0,os.getuid()) and before.st_nlink == 1 and + before.st_size == expected['bytes'], 'actual ordinary image mode, size and owner') + slot[1] = 'OPEN_PENDING' + slot[0] = os.open(path, os.O_RDONLY|os.O_NOFOLLOW|os.O_CLOEXEC|os.O_NONBLOCK) + slot[1] = 'OWNED' + need(identity(os.fstat(slot[0])) == identity(before), 'actual image descriptor identity') + total, hasher = 0, hashlib.sha256() + while True: + raw = os.read(slot[0], min(65536, expected['bytes']+1-total)) + if not raw: + break + total += len(raw) + need(total <= expected['bytes'], 'image read cannot exceed selected bound') + hasher.update(raw) + need(total == expected['bytes'] and hasher.hexdigest() == expected['sha256'] and + identity(os.fstat(slot[0])) == identity(path.lstat()) == identity(before), + 'complete stable selected image digest') + except BaseException as error: + remember(error) + if slot[1] == 'OPEN_PENDING': + UNKNOWN[0] = True + elif slot[1] == 'RESERVED': + slot[1] = 'NOT_ENTERED' + raise FIRST[0] + finally: + if slot[1] == 'OWNED': + slot[1] = 'CLOSE_ENTERED' + try: + os.close(slot[0]) + slot[1] = 'CLOSED' + except BaseException as error: + slot[1], UNKNOWN[0] = 'CLOSE_UNKNOWN', True + remember(error) + if FIRST[0] is not None: + raise FIRST[0] + need(not UNKNOWN[0], 'known image close before use') + return dict(expected) + + +def derive_fixed_role_data(manifest_pin, inputs_pin): + """Parent-owned prelaunch derivation from actual separately issued inputs. + + The authenticated original parent selects these two exact pins before this + operation. Complete rereads corroborate provenance; they never issue native + qualification, funding, a grant or command admission. The result is only + canonical DATA for that parent's existing publication owner to publish. + """ + need(USED[0] is False, 'prelaunch derivation precedes all fixed runtime startup') + pin(manifest_pin); pin(inputs_pin) + need(manifest_pin['path'] == str(MANIFEST) and manifest_pin['mode'] == 0o444, + 'fixed final detached manifest selected by the original parent') + manifest = decode(read_fixed(MANIFEST,8*1024*1024,manifest_pin)) + exact(manifest, ('schema','source_pins','profiles','argv_shapes','control_pins', + 'source_only','execution_permission')) + need(manifest['schema'] == 's03-joined-source-manifest-v1' and + manifest['source_only'] is True and manifest['execution_permission'] is False, + 'source selections issue no authority') + inputs = decode(read_fixed(Path(inputs_pin['path']),8*1024*1024,inputs_pin, + mode=inputs_pin['mode'])) + exact(inputs, ('schema','source_manifest_pin','original','joined_native_subject', + 'joined_native_dependencies','compiler_subject','query_profile', + 'manual','delegation_path','domain_name')) + need(inputs['schema'] == 'original-parent-role-derivation-inputs-v1' and + inputs['source_manifest_pin'] == manifest_pin, + 'genuine original parent inputs select this exact frozen source graph') + for row in list(manifest['source_pins'].values()) + list(manifest['profiles'].values()): + pin(row) + read_fixed(Path(row['path']),row['bytes'],row) + # These original issued records are preserved, never manufactured or repaired. + original = inputs['original'] + records = [original['candidate_document_pin'],original['capture_actual_grant_pin'], + original['original_actual_grant_pin'],original['expected_head_pin']] + records.extend(original['pins'].values()) + records.extend((original['approved_opening']['opening_pin'], + original['approved_opening']['adoption_pin'])) + records.extend((inputs['manual']['closed_state_pin'],inputs['manual']['registration_pin'])) + for row in records: + pin(row) + read_fixed(Path(row['path']),row['bytes'],row,mode=row['mode']) + selected = manifest['source_pins']['role_contracts'] + need(selected['path'] == str(R/'implementation/bindings/role_contracts.py'), + 'fixed pure constructor source') + raw = read_fixed(Path(selected['path']),selected['bytes'],selected) + name = '_original_parent_role_constructor' + need(name not in sys.modules, 'one actual original-parent derivation namespace') + module = ModuleType(name) + module.__dict__.update(__file__=selected['path'],__name__=name, + __package__=None,__spec__=None) + RETAINED.append((module,raw)) + sys.modules[name] = module + exec(compile(raw,selected['path'],'exec',dont_inherit=True),module.__dict__) + contracts = module.construct(manifest_pin,manifest['source_pins'],original, + joined_native_subject=inputs['joined_native_subject'], + joined_native_dependencies=inputs['joined_native_dependencies'], + operating_profiles=manifest['profiles'],compiler_subject=inputs['compiler_subject'], + query_profile=inputs['query_profile']) + contract_raw = canonical(contracts) + contract_pin = {'path':str(CONTRACTS),'bytes':len(contract_raw), + 'sha256':hashlib.sha256(contract_raw).hexdigest(),'mode':0o444} + config = module.guardian_config(manifest,manifest_pin,contracts,contract_pin, + inputs['manual'],inputs['delegation_path'],inputs['domain_name']) + config_raw = canonical(config) + config_pin = {'path':str(R/'control/ORIGINAL-GUARDIAN-CONFIG.json'),'bytes':len(config_raw), + 'sha256':hashlib.sha256(config_raw).hexdigest(),'mode':0o444} + return {'schema':'original-parent-derived-role-data-v1','source_manifest_pin':dict(manifest_pin), + 'original_input_pin':dict(inputs_pin),'contracts':contracts,'contracts_pin':contract_pin, + 'guardian_config':config,'guardian_config_pin':config_pin, + 'source_only':True,'execution_permission':False} + + +def arguments(argv=None): + argv = sys.argv if argv is None else argv + need(type(argv) is list and len(argv) >= 3 and len(argv) % 2 == 1, 'fixed entry key/value argv') + allowed = {'--source-sha256','--loader-sha256','--loader-bytes','--manifest-sha256', + '--manifest-bytes','--contracts-sha256','--contracts-bytes', + '--handoff-path','--plan','--admission','--grant-sha256'} + out = {} + for i in range(1, len(argv), 2): + need(argv[i] in allowed and argv[i] not in out and type(argv[i+1]) is str and + 0 < len(argv[i+1]) <= 4096, 'fixed unique entry arguments') + out[argv[i]] = argv[i+1] + required = {'--source-sha256','--loader-sha256','--loader-bytes','--manifest-sha256', + '--manifest-bytes','--contracts-sha256','--contracts-bytes'} + need(required <= set(out), 'actual detached binding pins required') + return out + + +def clean_launch(): + need(sys.executable == '/usr/bin/python3.12' and sys.implementation.name == 'cpython' and + sys.version_info[:2] == (3,12) and sys.base_prefix == '/usr' 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 + tuple(sys.path) == INITIAL_PATH and dict(os.environ) == ENV and + os.getcwd() == str(W), 'selected pristine ordinary interpreter/argv/environment') + need(signal.getitimer(signal.ITIMER_REAL) == (0.0,0.0) and + signal.getsignal(signal.SIGALRM) == signal.SIG_DFL and + signal.getsignal(signal.SIGCHLD) == signal.SIG_DFL, 'original signal owners') + for fd in (1,2): + info = os.fstat(fd) + need(stat.S_ISREG(info.st_mode) and stat.S_IMODE(info.st_mode) == 0o600 and + info.st_uid == os.getuid() and info.st_nlink == 1, + 'actual regular0600 inherited captures') + + +class PrivateBundle: + def __init__(self, role, manifest, contract, manual, runtime): + self.role, self.manifest, self.contract = role, manifest, contract + self.manual, self.runtime, self.modules = manual, runtime, {} + self._images, self._functions, self._classes = {}, {}, {} + self._runtime_seen, self._pid = {}, os.getpid() + self._environment_association = None + self.C = self.load('C') + need(self.C.FIRST[0] is None and self.C.IO_UNKNOWN[0] is False and + self.C.SOFT_DEADLINE[0] is None and self.C.ACTIVE_CASE[0] is None and + not self.C.RETAINED_MODULES and all(row[1] in ('FREE','CLOSED') for row in self.C.IO.slots), + 'actual pristine complete C2 private namespace') + self.F, self.A = self.load('F'), self.load('A') + self.guardian_module = self.load('guardian_channel') + self.guardian = self.guardian_module.open_fixed(ROLE[role], + manifest['source_pins'][{'M':'inner_meter','CAPTURE':'capture','PUBLISHER':'publisher','CONTROLLER':'C'}[role]]['sha256'], runtime) + self.guardian_pair = (self.guardian_module, self.guardian) + if role != 'M': + self.actor = self.C if role == 'CONTROLLER' else self.load({'CAPTURE':'capture','PUBLISHER':'publisher'}[role]) + else: + self.actor = self.load('inner_meter') + self.guardian.continuation(manual['request'], manual['provenance']['original_start_pin'], 'BOOTSTRAP') + + def associate_environment(self): + need(self._pid == os.getpid() and self.role == 'CONTROLLER' and + self._environment_association is None, + 'one genuine current C2 environment association') + module = self.load('environment_association') + association = module.open_parent(self) + self._environment_association = association + return association + + def joined_native_profile_template(self): + """Corroborate selected current images; this issues no native admission. + + The original authenticated parent operating-TCB/current-profile and + actual source-to-installed-image qualification remain independent gates. + This method verifies their selected ordinary-file subject bytes and the + fixed source tuple, not a compatible flag from serialized DATA. + """ + need(self._pid == os.getpid() and self.role == 'CONTROLLER', + 'genuine same-process C2 native subject selection') + value = self.contract['native_entry_profile'] + exact(value, ('schema','entry_path','entry_sha256','entry_bytes', + 'time_path','time_sha256','time_bytes','source_sha256')) + need(value['schema'] == 'joined-native-entry-profile-v1' and + value['entry_path'] == str(R/'runtime/native/science_view_entry') and + value['time_path'] == '/usr/bin/time', 'fixed native entry/time paths') + source = self.manifest['source_pins']['science_view_source'] + need(value['source_sha256'] == source['sha256'], 'selected exact view C source') + read_fixed(Path(source['path']), source['bytes'], source) + for prefix in ('entry','time'): + path = Path(value[prefix+'_path']) + count, expected = value[prefix+'_bytes'], value[prefix+'_sha256'] + need(type(count) is int and 0 < count <= 8*1024*1024 and + type(expected) is str and len(expected) == 64 and + all(c in '0123456789abcdef' for c in expected), + 'selected bounded actual native image pin') + mode = stat.S_IMODE(path.lstat().st_mode) + need(bool(mode & 0o111) and not (mode & 0o022), + 'ordinary selected immutable-to-group native image') + raw = read_fixed(path, count, mode=mode) + need(len(raw) == count and hashlib.sha256(raw).hexdigest() == expected, + 'actual stable complete selected image bytes') + return decode(canonical(value)) + + def joined_property_query_profile(self): + need(self._pid == os.getpid() and self.role == 'CONTROLLER', + 'actual C2 selects its property observer') + value = self.contract['property_query_profile'] + exact(value, ('schema','observer_pin','observer_source_pin','program_pins', + 'source_tuple_sha256','profile_sha256')) + need(value['schema'] == 'joined-property-query-profile-v1' and + value['source_tuple_sha256'] == hashlib.sha256(canonical(self.manifest['source_pins'])).hexdigest() and + value['profile_sha256'] == hashlib.sha256(canonical(self.manifest['profiles'])).hexdigest(), + 'query selection joins the complete exact source and operating profiles') + source = self.manifest['source_pins']['property_query_source'] + need(value['observer_source_pin'] == source and + value['observer_pin']['path'] == str(R/'runtime/native/property_query_observer'), + 'fixed native observer source and selected image path') + read_fixed(Path(source['path']),source['bytes'],source) + need(type(value['program_pins']) is list and 1 <= len(value['program_pins']) <= 16, + 'finite source-selected compiler query programs') + paths = set() + for image in [value['observer_pin']] + value['program_pins']: + need(image['path'] not in paths and image['mode'] & 0o111 != 0 and image['mode'] & 0o022 == 0, + 'unique executable query image with ordinary permissions') + paths.add(image['path']) + corroborate_image(image) + return decode(canonical(value)) + + def load(self, key): + need(self._pid == os.getpid() and type(key) is str and key in FIXED_PYTHON_PATHS and key in self.manifest['source_pins'], + 'source-owned selected dependency key; same process') + if key in self.modules: + self.check(key) + return self.modules[key] + expected = self.manifest['source_pins'][key] + need(expected['path'] == str(FIXED_PYTHON_PATHS[key]), 'actual source-owned fixed Python dependency path') + raw = read_fixed(Path(expected['path']), expected['bytes'], expected) + need(expected['path'].endswith('.py'), 'only exact selected Python leaf may load') + name = '_s03_joined_private_' + key + need(name not in sys.modules, 'fresh actual private source namespace') + module = ModuleType(name) + aliases = {'plain_boundary':'plain_boundary','native_io_custody':'native_io_custody', + 'error_custody':'error_custody','parent_authority':'parent_authority', + 'actual_consumer':'actual_consumer','postrun_hook':'postrun_hook', + 'bounded_relay':'bounded_relay','full_result_receiver':'full_receiver', + 'compiler_policy':'compiler_policy','property_query_receiver':'query_receiver', + 'fork_borrower':'fork_borrower','production_issuer':'production_issuer', + 'reuse_v2':'reuse_v2'} + original_import = builtins.__import__ + def source_import(name, global_ns=None, local_ns=None, fromlist=(), level=0): + if level == 0 and name in aliases: + if self._pid != os.getpid(): + # The one no-exec borrower may import already authenticated + # cached aliases only. It cannot open/compile new source or + # call a copied parent context/lease/channel. + need(self.role == 'CONTROLLER' and aliases[name] in self.modules and + 'parent_authority' in self.modules, 'no new or standalone child source import') + authority = self.modules['parent_authority'] + fn = self._images['parent_authority']['borrower_import_allowed'] + image = next(row for row in self._functions['parent_authority'] if row[0] is fn) + need(authority.__dict__['borrower_import_allowed'] is fn and + fn.__globals__ is authority.__dict__ and fn.__code__ is image[1] and + fn.__defaults__ is image[2] and fn.__kwdefaults__ is image[3] and + fn.__closure__ is image[4] and fn() is True, 'actual sealed one-fork cached-import branch') + return self.modules[aliases[name]] + return self.load(aliases[name]) + return original_import(name, global_ns, local_ns, fromlist, level) + private_builtins = dict(vars(builtins)) + private_builtins['__import__'] = source_import + module.__dict__.update(__file__=expected['path'], __name__=name, + __package__=None, __spec__=None, __builtins__=private_builtins) + self.modules[key] = module + RETAINED.append((module,raw)) # Before compile/top-level error; no failed-load retry. + sys.modules[name] = module + exec(compile(raw, expected['path'], 'exec', dont_inherit=True), module.__dict__) + self._images[key] = dict(module.__dict__) + self._functions[key] = [(fn,fn.__code__,fn.__defaults__,fn.__kwdefaults__,fn.__closure__) + for fn in module.__dict__.values() if type(fn) is FunctionType and fn.__globals__ is module.__dict__] + self._classes[key] = [(cls,dict(type.__getattribute__(cls,'__dict__'))) + for cls in module.__dict__.values() if type(cls) is type and + type.__getattribute__(cls,'__module__') == name] + for cls,image in self._classes[key]: + self._functions[key].extend((fn,fn.__code__,fn.__defaults__,fn.__kwdefaults__,fn.__closure__) + for fn in image.values() if type(fn) is FunctionType and fn.__globals__ is module.__dict__) + for member in image.values(): + if type(member) is property: + self._functions[key].extend((fn,fn.__code__,fn.__defaults__,fn.__kwdefaults__,fn.__closure__) + for fn in (member.fget,member.fset,member.fdel) if fn is not None and fn.__globals__ is module.__dict__) + return module + + def check(self, key): + module = self.modules[key] + saved, current = self._images[key], module.__dict__ + # Source-owned lifecycle containers may be installed once after startup. + # Functions, classes, native primitives and every other global stay exact. + allowed = {'native_io_custody':{'_PROCESS'}, + 'parent_authority':{'_OWNER','_FORK','_JOINED_BINDINGS'}, + 'C':{'_JOINED','_JOINED_RUN','_FULL_RECEIVER','_FULL_RECEIVER_IMAGE','_ENVIRONMENT_ASSOCIATION'}, + 'queue':{'_COMPLETED','_FULL_RECEIVER'}, + 'supervisor':{'_COMPLETED','_JOINED','_JOINED_STATE','_QUERY_JOINED'}, + 'production_issuer':{'_CONTEXT','_CONNECTED','_RETENTION_ENTERED','_RAW', + '_ERROR_COUNT','_IO_POISON','_ERROR_OVERFLOW', + '_RETENTION_FAILURE','_PROJECTION_FAILURE'}, + 'error_custody':{'_EXPORTED_BYTES','_REVIEWED_SOURCE_TYPES'}}.get(key,set()) + need(set(saved) == set(current) and all(current[k] is saved[k] for k in saved if k not in allowed), + 'actual source-private immutable globals not substituted') + for name in allowed: + value = current[name] + prior = self._runtime_seen.get((key,name), saved[name]) + if name == '_PROCESS': + need(value is None or (type(value) is current['Context'] and + any(value is item for item in current['_LIVE'])), 'actual registered native IO context') + need(prior is None or value is prior, 'one native IO process context') + elif name == '_COMPLETED' and key in ('queue','supervisor'): + need(value is None or (type(value) is tuple and len(value) == 3 and + value[2] is self.guardian), 'actual layout/registry/guardian completion tuple') + need(prior is None or value is prior, 'one irreversible completed-source binding') + elif name == '_JOINED' and key == 'supervisor': + need(value is None or (type(value) is tuple and len(value) == 9 and + value[0] is self.modules.get('bounded_relay') and + value[3] is self.modules.get('full_receiver') and + value[5] is self._environment_association and value[8] == self._pid), + 'actual same-process supervisor module/association tuple') + need(prior is None or value is prior, 'one irreversible supervisor binding') + elif name in ('_OWNER','_FORK','_JOINED','_JOINED_RUN','_CONTEXT','_CONNECTED','_COMPLETED','_ENVIRONMENT_ASSOCIATION'): + need(value is None or type(value) is dict, 'source-private lifecycle record') + need(prior is None or value is prior, 'one irreversible private lifecycle record') + if name == '_OWNER' and value is not None: + need(value['pid'] == self._pid and value['phase'] in + ('OPEN','SEALED','BIRTH_PENDING','FORK_PENDING','BORROWER','READBACK','COMPLETE','UNCERTAIN','RELEASED'), + 'actual owner PID and finite lifecycle') + elif name == '_QUERY_JOINED': + need(value is None or (type(value) is tuple and len(value) == 4 and + value[0] is self.modules.get('query_receiver')), 'actual once-bound query module/profile') + need(prior is None or value is prior, 'one irreversible property-query binding') + elif name == '_JOINED_STATE': + need(value in ('UNENTERED','ENTERED','BOUND') and + ('UNENTERED','ENTERED','BOUND').index(value) >= ('UNENTERED','ENTERED','BOUND').index(prior), + 'monotone genuine joined configuration lifecycle') + elif name == '_FULL_RECEIVER': + need(value is None or (type(value) is ModuleType and + self.modules.get('full_receiver') is value), + 'actual authenticated full receiver module') + need(prior is None or value is prior, 'one receiver binding') + elif name == '_FULL_RECEIVER_IMAGE': + need(value is None or type(value) is tuple, 'source captured receiver function image') + need(prior is None or value is prior, 'one receiver function image') + elif name in ('_RETENTION_ENTERED','_IO_POISON'): + need(type(value) is bool and (prior is False or value is True), 'monotone source-owned one-use/poison flag') + elif name == '_ERROR_COUNT': + need(type(value) is int and type(prior) is int and prior <= value <= len(current['_ERRORS']), + 'monotone bounded actual error slots') + elif name == '_RAW': + need(value is None or type(value) is dict, 'source-owned raw snapshot DATA') + elif name in ('_ERROR_OVERFLOW','_RETENTION_FAILURE','_PROJECTION_FAILURE'): + need(value is None or BaseException in type.__getattribute__(type(value),'__mro__'), + 'actual retained exception only') + need(prior is None or value is prior, 'first actual exception retained') + elif name == '_EXPORTED_BYTES': + need(type(value) is int and type(prior) is int and prior <= value <= current['_EXPORT_CAP'], + 'monotone bounded actual error export count') + else: + need(type(value) is tuple and len(value) <= 256, 'bounded source-owned lifecycle tuple') + need(type(prior) is tuple and len(value) >= len(prior) and all(value[i] is prior[i] for i in range(len(prior))), 'source-owned tuple grows only') + self._runtime_seen[(key,name)] = value + for fn,code,defaults,kwdefaults,closure in self._functions[key]: + need(fn.__globals__ is current and fn.__code__ is code and fn.__defaults__ is defaults and + fn.__kwdefaults__ is kwdefaults and fn.__closure__ is closure, 'actual selected function code/globals') + for cls,image in self._classes[key]: + now = type.__getattribute__(cls,'__dict__') + need(set(now) == set(image) and all(now[name] is image[name] for name in image), + 'actual selected class/method/descriptor identities') + return module + + +def load_fixed(role): + need(USED[0] is False and role in ROLE, 'one fixed startup including failed load') + USED[0] = True + clean_launch() + args = arguments() + raw, mp = actual_pin(MANIFEST) + need(str(mp['bytes']) == args['--manifest-bytes'] and + mp['sha256'] == args['--manifest-sha256'], 'externally selected detached source manifest') + manifest = decode(raw) + exact(manifest, ('schema','source_pins','profiles','argv_shapes','control_pins', + 'source_only','execution_permission')) + need(manifest['schema'] == 's03-joined-source-manifest-v1' and + manifest['source_only'] is True and manifest['execution_permission'] is False, + 'source binding never grants command execution') + need(type(manifest['source_pins']) is dict and ENTRY[role] in manifest['source_pins'], + 'actual entry leaf selected') + for row in manifest['source_pins'].values(): + pin(row) + need(row['mode'] == 0o444, 'every selected source immutable0444') + own = manifest['source_pins'][ENTRY[role]] + need(str(Path(sys.argv[0]).absolute()) == own['path'] and own['sha256'] == args['--source-sha256'], + 'actual fixed entry path and externally selected source pin') + read_fixed(Path(own['path']), own['bytes'], own) + loader = manifest['source_pins']['private_loader'] + need(loader['path'] == __file__ and loader['sha256'] == args['--loader-sha256'] and + str(loader['bytes']) == args['--loader-bytes'], 'actual fixed loader leaf selected') + read_fixed(Path(loader['path']), loader['bytes'], loader) + need(type(manifest['profiles']) is dict and set(manifest['profiles']) == + {'native','cpython','filesystem','OS','effects','clock','commands'}, 'complete finite profile binding') + for row in manifest['profiles'].values(): + read_fixed(Path(row['path']), row['bytes'], row) + for row in manifest['control_pins']: + read_fixed(Path(row['path']), row['bytes'], row) + raw, cp = actual_pin(CONTRACTS) + need(str(cp['bytes']) == args['--contracts-bytes'] and cp['sha256'] == args['--contracts-sha256'], + 'externally selected actual original role contracts') + contracts = decode(raw) + exact(contracts, ('schema','source_manifest_sha256','roles','source_only','execution_permission')) + need(contracts['schema'] == 's03-joined-role-contracts-v1' and + contracts['source_manifest_sha256'] == mp['sha256'] and + contracts['source_only'] is True and contracts['execution_permission'] is False, + 'acyclic leaf -> manifest -> immutable original role template') + need(set(contracts['roles']) == set(ROLE), 'finite four actual fixed role contracts') + runtime = decode(read_fixed(RUNTIME, 131072)) + exact(runtime, ('schema','attempt_id','original_start_pin','guardian_pid', + 'whole_deadline_ns','role_binding_pins')) + need(runtime['schema'] == 's03-guardian-runtime-v1' and + set(runtime['role_binding_pins']) == {'M','K','P','C2'}, 'actual native G runtime roster') + sp = runtime['original_start_pin'] + need(Path(sp['path']) == ADMIN / 'G/START.json', 'fixed fresh G START path') + start = decode(read_fixed(Path(sp['path']), 65536, sp, mode=sp['mode'])) + exact(start, ('schema','start_monotonic_ns','source_sha256','probe_sha256', + 'actual_grant_sha256','future_operation_blocked_until_separate_adjudication')) + need(start['schema'] == 'fresh-owner-meter-incomplete-v1' and + start['source_sha256'] == manifest['source_pins']['outer']['sha256'] and + start['probe_sha256'] == manifest['source_pins']['capture_bootstrap']['sha256'] and + start['future_operation_blocked_until_separate_adjudication'] is True and + type(start['start_monotonic_ns']) is int, 'actual original FULL_SIX GSTART source association') + rb = runtime['role_binding_pins'][ROLE[role]] + need(Path(rb['path']) == ADMIN / ('control/' + ROLE[role] + '-RUNTIME.json'), 'fixed own role runtime path') + manual = decode(read_fixed(Path(rb['path']), 131072, rb, mode=rb['mode'])) + exact(manual, ('schema','request','provenance','closed_state_pin','registration_checks','start_checks')) + need(manual['schema'] == 'fresh-active-manual-entry-binding-v1' and + manual['request']['label'] == runtime['attempt_id'] and + manual['provenance']['original_start_pin'] == sp and + runtime['whole_deadline_ns'] == start['start_monotonic_ns'] + manual['request']['body_reservation_ns'], + 'same original request/reservation/GSTART; no numeric argv authority') + runtime['start_monotonic_ns'] = start['start_monotonic_ns'] # Derived from full pinned START, never argv. + template = contracts['roles'][role] + exact(template, ('actor_contract','entry_argv','retention','runtime_paths')) + tokens = {'@CONTRACTS_SHA256@':cp['sha256'], '@CONTRACTS_BYTES@':str(cp['bytes']), + '@MANIFEST_SHA256@':mp['sha256'], '@MANIFEST_BYTES@':str(mp['bytes']), + '@LOADER_SHA256@':loader['sha256'], '@LOADER_BYTES@':str(loader['bytes'])} + for name, row in manifest['source_pins'].items(): + tokens['@SOURCE_' + name + '_SHA256@'] = row['sha256'] + tokens['@SOURCE_' + name + '_BYTES@'] = str(row['bytes']) + def resolve(value): + if type(value) is str: + return tokens.get(value, value) + if type(value) is list: + return [resolve(item) for item in value] + if type(value) is dict: + return {name:resolve(item) for name,item in value.items()} + return value + template = resolve(template) + need(type(template['entry_argv']) is list and template['entry_argv'] == list(sys.argv), + 'exact actual selected fixed role argv, including normal-mode arguments') + contract = decode(canonical(template['actor_contract'])) + need('manual_entry' not in contract and 'source_pins' not in contract, + 'templates cannot impersonate future runtime provenance or source pin') + contract.update(manual_entry=manual, source_pins=manifest['source_pins']) + need(contract['request'] == manual['request'] and contract['candidate_document_sha256'] == + manual['request']['command_sha256'], 'original exact request/candidate template association') + bundle = PrivateBundle(role, manifest, contract, manual, runtime) + bundle.retention = template['retention'] + bundle.role_data = template['runtime_paths'] + exact(bundle.role_data, ('admin_root','grant_path','accounting_path','capture_argv','outer_actor')) + need(bundle.role_data['admin_root'] == str(ADMIN) and + bundle.role_data['grant_path'] == str(R / ('control/CAPTURE-ACTUAL-GRANT.json' if role == 'CAPTURE' else 'control/ORIGINAL-FULL-SIX-GRANT.json')) and + bundle.role_data['accounting_path'] == str(ADMIN / 'C2/ACCOUNTING.json'), 'fixed prospective runtime paths only') + RETAINED.append(bundle) + return bundle diff --git a/research/h25-parent-waiting-entry/implementation/bootstrap/controller_entry.py b/research/h25-parent-waiting-entry/implementation/bootstrap/controller_entry.py new file mode 100644 index 0000000000..a11f9053aa --- /dev/null +++ b/research/h25-parent-waiting-entry/implementation/bootstrap/controller_entry.py @@ -0,0 +1,218 @@ +# Modified 2026-11-07: Clear1nsight, with OpenAI Codex and ChatGPT Pro assistance. See NOTICE.md. +"""Fixed immutable CONTROLLER entry; actual execution requires separate admission.""" +import hashlib +import os +from pathlib import Path +import resource +import stat +import sys +from types import ModuleType + +W = Path('/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453') +R = W / 'outputs/caller-proof-completion-20261107T0155Z' +LOADER = R / 'implementation/bindings/private_loader.py' +C2_AS_BYTES = 268435456 +RETAINED = [] +FIRST, SECONDARY, UNKNOWN = [None], [None] * 16, [False] +FIRST_TRACE, SECONDARY_TRACE = [None], [None] * 16 + + +def keep(error): + if FIRST[0] is None: + FIRST[0] = error + FIRST_TRACE[0] = BaseException.__dict__['__traceback__'].__get__(error,BaseException) + elif error is not FIRST[0]: + for i, old in enumerate(SECONDARY): + if old is error: + break + if old is None: + SECONDARY[i] = error + SECONDARY_TRACE[i] = BaseException.__dict__['__traceback__'].__get__(error,BaseException) + break + else: + UNKNOWN[0] = True + return FIRST[0] + + +def install_c2_as_limit(port=resource): + """Lower and read back C2's selected bound before any source/owner work. + + The selected module port is fixed by main. A lower inherited soft or hard + limit remains lower; an inability to install or read back stops this entry. + This source operation establishes no claim that the complete work will fit. + """ + inherited = port.getrlimit(port.RLIMIT_AS) + if not (type(inherited) is tuple and len(inherited) == 2 and + all(type(value) is int and (value >= 0 or value == port.RLIM_INFINITY) + for value in inherited)): + raise RuntimeError('exact inherited C2 AS limits') + soft, hard = inherited + if hard != port.RLIM_INFINITY and (soft == port.RLIM_INFINITY or soft > hard): + raise RuntimeError('ordered inherited C2 AS limits') + hard = C2_AS_BYTES if hard == port.RLIM_INFINITY else min(hard, C2_AS_BYTES) + soft = hard if soft == port.RLIM_INFINITY else min(soft, hard) + wanted = (soft, hard) + port.setrlimit(port.RLIMIT_AS, wanted) + actual = port.getrlimit(port.RLIMIT_AS) + if not (type(actual) is tuple and len(actual) == 2 and + all(type(value) is int for value in actual) and actual == wanted and + 0 <= actual[0] <= actual[1] <= C2_AS_BYTES): + raise RuntimeError('actual C2 AS soft/hard bound readback differs') + return actual + + +def authenticate_c2_pins(loader, cfg, args, controller): + """Authenticate full immutable pins, then adapt to the original C2 API.""" + published = controller.ROOT / 'control' + loader.need(args['--plan'] == str(published / (controller.NAME+'-PLAN.json')) and + args['--admission'] == str(published / (controller.NAME+'-ADMISSION.json')), + 'exact original P-published plan/admission destination') + plan_pin = dict(cfg['plan_pin'], path=args['--plan']) + admission_pin = dict(cfg['admission_pin'], path=args['--admission']) + for template_pin, actual_pin in ((cfg['plan_pin'],plan_pin),(cfg['admission_pin'],admission_pin)): + loader.need(loader.read_fixed(Path(template_pin['path']),template_pin['bytes'],template_pin) == + loader.read_fixed(Path(actual_pin['path']),actual_pin['bytes'],actual_pin), + 'full source template and actual P-published metadata agree under C2 EX') + # read_fixed above still requires every original mode=0444 four-field pin. + # The original unchanged C2 API independently requires exactly these three. + return tuple({key:pin[key] for key in ('path','bytes','sha256')} + for pin in (plan_pin, admission_pin)) + + +def transport(): + # Fixed loader pin comes from the separately admitted exact launcher argv. + # No script path, arbitrary callable, context or descriptor number is input. + args = {} + if len(sys.argv) % 2 != 1: + raise RuntimeError('fixed key/value entry argv') + for i in range(1, len(sys.argv), 2): + if sys.argv[i] in args: + raise RuntimeError('duplicate entry argument') + args[sys.argv[i]] = sys.argv[i+1] + expected_sha, expected_bytes = args['--loader-sha256'], int(args['--loader-bytes']) + if not 0 < expected_bytes <= 1048576 or len(expected_sha) != 64: + raise RuntimeError('bounded exact immutable loader pin') + before = LOADER.lstat() + if not (LOADER.resolve(strict=True) == LOADER and stat.S_ISREG(before.st_mode) and + stat.S_IMODE(before.st_mode) == 0o444 and before.st_nlink == 1 and + before.st_uid in (0, os.getuid()) and before.st_size == expected_bytes): + raise RuntimeError('fixed pristine loader owner/path/mode/link/size') + fd, phase, raw = None, 'OPEN_PENDING', None + RETAINED.append(('LOADER_OPEN_PENDING', str(LOADER))) + try: + fd = os.open(LOADER, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC) + phase = 'OWNED' + RETAINED.append(('LOADER_OWNED', fd)) + opened = os.fstat(fd) + if opened != before: + raise RuntimeError('loader descriptor/path differs') + parts, count = [], 0 + while True: + part = os.read(fd, min(65536, expected_bytes + 1 - count)) + if not part: + break + parts.append(part) + count += len(part) + if count > expected_bytes: + raise RuntimeError('loader source cap') + raw = b''.join(parts) + if not (len(raw) == expected_bytes and hashlib.sha256(raw).hexdigest() == expected_sha and + os.fstat(fd) == opened == LOADER.lstat()): + raise RuntimeError('complete stable exact selected loader source') + except BaseException as error: + keep(error) + if phase == 'OPEN_PENDING': + UNKNOWN[0] = True + finally: + if phase == 'OWNED': + phase = 'CLOSE_ENTERED' + RETAINED.append(('LOADER_CLOSE_ENTERED', fd)) + try: + os.close(fd) + phase = 'CLOSED' + except BaseException as error: + phase, UNKNOWN[0] = 'CLOSE_UNKNOWN', True + keep(error) + if FIRST[0] is not None: + raise BaseException.with_traceback(FIRST[0],FIRST_TRACE[0]) + if UNKNOWN[0] or phase != 'CLOSED': + raise RuntimeError('unknown loader descriptor forbids source execution') + name = '_s03_fixed_entry_private_loader' + if name in sys.modules: + raise RuntimeError('fresh fixed loader namespace required') + module = ModuleType(name) + module.__dict__.update(__name__=name, __file__=str(LOADER), __package__=None, __spec__=None) + sys.modules[name] = module + RETAINED.append((module,raw)) + exec(compile(raw, str(LOADER), 'exec', dont_inherit=True), module.__dict__) + return module + + +def main(): + RETAINED.append(('C2_AS_BOUND', install_c2_as_limit(resource))) + loader = transport() + bundle = loader.load_fixed('CONTROLLER') + RETAINED.append(bundle) + args, cfg = loader.arguments(), bundle.contract + loader.need(args['--handoff-path'] == cfg['handoff_path'], 'fixed original P-to-C2 intent path') + raw, handoff_pin = loader.actual_pin(Path(cfg['handoff_path'])) + handoff = bundle.F.decode(raw) + loader.need(handoff['source_role'] == 'PUBLISHER' and handoff['destination_role'] == 'CONTROLLER' and + handoff['request'] == cfg['request'] and handoff['native_capability_transferred'] is False, + 'metadata correlates same original operation; no financial owner survives exec') + factory = bundle.A.bind_api(bundle.C,bundle.F,role='CONTROLLER', + expected_head_pin=handoff['head_pin'], approved_handoff_pin=handoff_pin, + approved_opening=cfg['approved_opening'], approved_manual_entry=bundle.manual, + guardian=bundle.guardian_pair) + RETAINED.append(factory) + ctx = factory() # NEW original actual native EX in C2; no copied P ctx/OFD. + RETAINED.append(ctx) + entered = False + try: + ctx.adopt_handoff() + bundle.guardian.continuation(cfg['request'], bundle.manual['provenance']['original_start_pin'], 'ACTIVE') + joined = bundle.C.configure_joined(bundle.load('layout'),bundle.load('attempt_registry'), + bundle.load('production_issuer'),bundle.guardian,bundle.retention) + plan_pin, admission_pin = authenticate_c2_pins(loader,cfg,args,bundle.C) + supervisor, wrapper = bundle.load('supervisor'), bundle.load('wrapper') + queue, envelope = bundle.load('queue'), bundle.load('envelope') + association = bundle.associate_environment() # Cold factory; no pre-owner Q claim. + bundle.C.bind_environment_association(association) + full = bundle.load('full_receiver') + bundle.C.bind_full_receiver(full) + supervisor.configure_joined_runtime(bundle.load('bounded_relay'), + bundle.manifest['source_pins']['bounded_relay'], + bundle.joined_native_profile_template(),association=association, + full_receiver=full,full_receiver_pin=bundle.manifest['source_pins']['full_receiver'], + query_receiver=bundle.load('query_receiver'), + query_receiver_pin=bundle.manifest['source_pins']['query_receiver'], + query_profile=bundle.joined_property_query_profile(), + common_runner_pin=bundle.manifest['source_pins']['common_runner'], + waiting_entry_pin=bundle.manifest['source_pins']['waiting_entry']) + entered = True # All fallible dependency loads completed; C2 now owns actual release. + return bundle.C.run_composed(bundle.C,bundle.A,supervisor,wrapper, + queue,envelope,ctx,bundle.runtime['start_monotonic_ns'], + plan_pin,admission_pin,joined=joined) + except BaseException as error: + keep(error) + if not entered: + if bundle.C._ENVIRONMENT_ASSOCIATION is not None: + try: + bundle.C.close_environment_association() + except BaseException as secondary: + keep(secondary) + try: + ctx.release() + except BaseException as secondary: + keep(secondary) + raise BaseException.with_traceback(FIRST[0],FIRST_TRACE[0]) + + +if __name__ == '__main__': + try: + raise SystemExit(main()) + except BaseException as error: + if type(error) is SystemExit: + raise + keep(error) + raise diff --git a/research/h25-parent-waiting-entry/implementation/controller/composed_controller.py b/research/h25-parent-waiting-entry/implementation/controller/composed_controller.py new file mode 100644 index 0000000000..00bf853217 --- /dev/null +++ b/research/h25-parent-waiting-entry/implementation/controller/composed_controller.py @@ -0,0 +1,1764 @@ +# Modified 2026-11-07: Clear1nsight, with OpenAI Codex and ChatGPT Pro assistance. See NOTICE.md. +"""SOURCE ONLY owning parent for the exact adopted complete candidate caller. + +No privilege/capability is reconstructed from a plan/receipt. The historical +lease below is acquired by this process using open/flock and kept through final +original-domain custody and known accounting. Actual execution needs a separate +exact command/admission review. No universal hard-timeout/native-fault theorem. +""" +import argparse +import builtins +import fcntl +import hashlib +import json +import math +import os +from pathlib import Path +import resource +import signal +import stat +import subprocess +import sys +import time +from types import ModuleType, MethodType, FunctionType + +W = Path('/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453') +ROOT = W / 'outputs/h25-data-handling-20261028' +JOINED_ROOT = W / 'outputs/caller-proof-completion-20261107T0155Z' +JOINED_BINDINGS = JOINED_ROOT / 'implementation/bindings' +_JOINED = None +_JOINED_RUN = None +HISTORICAL_LOCK = W / 'outputs/h25-bookkeeping-swarm-20261028/runtime/science.lock' +PACKET = ROOT / 'execution-guards/build-log-queue-v2' +PACKET_SHA = '1ad9a7d536f59743df8ef7626c65c6e02fb68955a651cb927e471276ec44d416' +ENVELOPE_SHA = 'afb4f72c36bad015fdf23221a00a4730387a5e8df4999b14a4d1614ee135c84a' +PREDECESSOR_WRAPPER_SHA = 'ea4c07337ccc1865accfd1b1fe485d51057a04a49e4bfb5f10cc36dc92b5f9a8' +PREDECESSOR_QUEUE_SHA = '1348a7b4d7cc1f9fef556f5e0abdaf04411a998afdcd574d7812c76ab37dcf68' +PREDECESSOR_STAGE_SHA = 'afe1075579faed2093a885911a3558039c6a394e887705e99e85822e5eb6be5a' +TCB_SHA = 'f34d4fb2e96924ae54de33c476d4adc1ee085fa1a072e166c64dd34bd0c25467' +CLOCK_PREMISES_SHA = '0763b173d623030d3d740f6eea0676cf48a1b97d58c7f7f8c88d6e49a4b74882' +NAME = 'IndependentPrefixDATAComposedV1' +JOINED_ADMIN = JOINED_ROOT / 'runtime/admin' / NAME +BARRIER = JOINED_ADMIN / 'control/EXECUTION-BARRIER' +QUARANTINE = JOINED_ADMIN / 'control/EXECUTION-QUARANTINE' +SEALED = JOINED_ADMIN / 'control/SEALED-ONE-PARENT' +STAGE = JOINED_BINDINGS / 'stages/joined-full-candidate-v1' +EXTERNAL_BASE = JOINED_ROOT / 'runtime/completed-source/IndependentPrefixDATAComposedV1' +FLAGS = ('-S', '-s', '-P', '-B') +ENV = {'PATH': '/usr/bin:/bin', 'PYTHONHASHSEED': '0', 'LANG': 'C.UTF-8', + 'LC_ALL': 'C.UTF-8', 'TZ': 'UTC', 'PYTHONDONTWRITEBYTECODE': '1'} +INITIAL_PATH = ('/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload') +SOURCE_ONLY_FIELDS = ('qualified', 'full99_fit', 'full52prefix_qualification', + 'runtime_profile_qualified', 'native_identity_proved', + 'fullcaller_admitted', 'fullscience', 'gain', + 'execution_grant_created', 'all_costs_settled', 'native_fault_totality_qualified') +FIRST = [None] +SECONDARY = [None] * 256 +FIRST_TRACE = [None] +SECONDARY_TRACE = [None] * 256 +ERROR_OVERFLOW = [None] +IO_UNKNOWN = [False] +RETAINED_MODULES = [] + +ELIGIBILITY_PATH = Path('/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/h25-data-handling-20261028/areas/fresh-successor-eligibility-v1/historical_eligibility.py') +ELIGIBILITY_PIN = {'bytes':8682,'sha256':'bb60f3e93979fd43993a8655d3a3a82e23d74e361f7560857f975fc970607a63'} +ELIGIBILITY = [None] +PREDECESSOR_SUCCESSOR_ACTIVE = ('/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/h25-data-handling-20261028/validation/IndependentPrefixDATASuccessorV1-EXECUTION-BARRIER','/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/h25-data-handling-20261028/runtime/runs/IndependentPrefixDATASuccessorV1-EXECUTION-QUARANTINE') +PREDECESSOR_COMPOSED_ACTIVE = (str(ROOT/'validation/IndependentPrefixDATAComposedV1-EXECUTION-BARRIER'), + str(ROOT/'runtime/fresh-metered-round-v1/controller-quarantines/IndependentPrefixDATAComposedV1')) +SUCCESSOR_ACTIVE = (*PREDECESSOR_SUCCESSOR_ACTIVE,*PREDECESSOR_COMPOSED_ACTIVE,str(BARRIER),str(QUARANTINE)) +SOFT_DEADLINE = [None] +ACTIVE_CASE = [None] +INPUT_ORDER = ('artifact', 'stdout', 'metadata', 'root_receipt') + + +class AdapterStop(RuntimeError): + pass + + +def remember(error): + if FIRST[0] is None: + FIRST[0] = error + FIRST_TRACE[0] = BaseException.__traceback__.__get__(error,type(error)) + elif error is not FIRST[0]: + for index in range(len(SECONDARY)): + if SECONDARY[index] is error: + break + if SECONDARY[index] is None: + SECONDARY[index] = error + SECONDARY_TRACE[index] = BaseException.__traceback__.__get__(error,type(error)) + break + else: + if ERROR_OVERFLOW[0] is None: + ERROR_OVERFLOW[0] = error + IO_UNKNOWN[0] = True + return FIRST[0] + + +def checkpoint(): + if _JOINED_RUN is not None: + joined_integrity() + joined_budget_checkpoint() + if IO_UNKNOWN[0]: + raise AdapterStop('uncertain IO; process teardown required, no new acquisition') + if SOFT_DEADLINE[0] is not None and time.monotonic() > SOFT_DEADLINE[0]: + raise AdapterStop('owning-parent soft allowance crossed; cleanup remains paid') + if ACTIVE_CASE[0] is not None: + ACTIVE_CASE[0].check() + if resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * 1024 > 1073741824: + raise AdapterStop('owning-parent observed RSS cap') + + +class OwnedIO: + """Fixed direct-handle slots; ordinary POSIX under selected operating TCB.""" + def __init__(self): + self.slots = [[None, 'FREE', None] for unused in range(16)] + + def acquire(self, path, flags, mode=0o600, directory=False): + checkpoint() + slot = next(row for row in self.slots if row[1] in ('FREE', 'CLOSED')) + slot[0], slot[2], slot[1] = None, directory, 'PENDING' + try: + slot[0] = os.scandir(path) if directory else os.open(path, flags, mode) + slot[1] = 'OWNED' + return slot + except BaseException as error: + IO_UNKNOWN[0] = True + remember(error) + raise + + def close(self, slot): + if slot[1] != 'OWNED': + IO_UNKNOWN[0] = True + raise AdapterStop('handle close not known/replay') + slot[1] = 'CLOSING' + try: + slot[0].close() if slot[2] else os.close(slot[0]) + except BaseException as error: + IO_UNKNOWN[0] = True + remember(error) + raise + slot[1] = 'CLOSED' + + def names(self, path, cap=8192): + names, primary, slot = [], None, None + try: + slot = self.acquire(path, 0, directory=True) + for entry in slot[0]: + checkpoint() + if len(names) >= cap: + raise AdapterStop('directory census cap') + names.append(entry.name) + except BaseException as error: + primary = remember(error) + finally: + if slot is not None and slot[1] == 'OWNED': + try: + self.close(slot) + except BaseException as error: + primary = remember(error) + if primary is not None: + raise primary + return names + + def read(self, path, cap, mode=None, expected=None, materialize=False, proc=False): + checkpoint() + path = Path(path) + if not proc: + need(path.is_absolute() and path.resolve(strict=True) == path, 'canonical source/input/output path') + before = path.lstat() + if not proc: + need(stat.S_ISREG(before.st_mode) and before.st_nlink == 1 and + before.st_uid in (0, os.getuid()) and before.st_size <= cap and + (mode is None or stat.S_IMODE(before.st_mode) == mode), 'regular stable file precondition') + pieces, count, hasher, slot, primary = [], 0, hashlib.sha256(), None, None + try: + slot = self.acquire(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC) + if not proc: + need(identity(os.fstat(slot[0])) == identity(before), 'opened stable file differs') + while True: + checkpoint() + block = os.read(slot[0], min(65536, cap + 1 - count)) + if not block: + break + count += len(block) + need(count <= cap, 'file read cap') + hasher.update(block) + if materialize: + pieces.append(block) + if not proc: + need(identity(os.fstat(slot[0])) == identity(before) and count == before.st_size, + 'stable descriptor changed') + except BaseException as error: + primary = remember(error) + finally: + if slot is not None and slot[1] == 'OWNED': + try: + self.close(slot) + except BaseException as error: + primary = remember(error) + if primary is not None: + raise primary + if not proc: + need(identity(path.lstat()) == identity(before), 'stable path changed') + row = {'path': str(path), 'bytes': count, 'sha256': hasher.hexdigest(), + 'mode': stat.S_IMODE(before.st_mode), 'uid': before.st_uid, + 'nlink': before.st_nlink, 'identity': list(identity(before))} + if expected is not None: + need(type(expected['bytes']) is int and row['bytes'] == expected['bytes'] and + row['sha256'] == expected['sha256'], 'fixed file bytes/hash differs') + return row, b''.join(pieces) if materialize else None + + def write(self, path, value, cap=4194304): + checkpoint() + path = Path(path) + need(path.is_absolute() and path.parent.resolve(strict=True) == path.parent, 'canonical retained evidence parent') + raw, slot, primary, offset = canonical(value), None, None, 0 + need(len(raw) <= cap, 'retained JSON evidence cap') + try: + slot = self.acquire(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC) + while offset < len(raw): + n = os.write(slot[0], raw[offset:offset + 65536]) + need(type(n) is int and 0 < n <= min(65536, len(raw) - offset), 'retained short write') + offset += n + os.fsync(slot[0]) + except BaseException as error: + primary = remember(error) + finally: + if slot is not None and slot[1] == 'OWNED': + try: + self.close(slot) + except BaseException as error: + primary = remember(error) + if primary is not None: + raise primary + return self.read(path, cap, 0o600, {'bytes': len(raw), 'sha256': digest(raw)})[0] + + +IO = OwnedIO() + + +# Exact accepted DATA-verifier source spans, recontextualized under this owner. +FILE_CAPS = {'RAW-artifact.typed': 16777216, 'RAW-stdout.typed': 2097152, + 'RAW-metadata.json': 65536, 'RAW-root_receipt.json': 65536, + 'observations.jsonl': 4194304, 'receipt.json': 1048576} + + +OUTCOME_FALSE_FLAGS = ('complete99case_qualification', 'full52prefix_qualification', + 'current_runtime_profile_qualified', 'native_header_FFI_fullcaller_admission', + 'native_identity_proved', 'fullscience', 'gain', 'controls_waived') + + +FALSE_FLAGS = ('full99_fit', 'full52prefix_qualification', 'runtime_profile_qualified', + 'native_identity_proved', 'fullcaller_admitted', 'fullscience', 'gain', + 'execution_grant_created', 'all_costs_settled', 'native_fault_totality_qualified') + + +def need(value, message): + if not value: + raise AdapterStop(message) + + +def exact(value, keys): + need(type(value) is dict and set(value) == set(keys), 'exact DATA object keys differ') + + +def digest(raw): + return hashlib.sha256(raw).hexdigest() + + +def sha_value(value): + need(type(value) is str and len(value) == 64 and + all(c in '0123456789abcdef' for c in value), 'exact sha256 required') + + +def canonical(value): + return (json.dumps(value, sort_keys=True, separators=(',', ':'), + ensure_ascii=True, allow_nan=False) + '\n').encode('ascii') + + +def json_data(raw, cap): + """Bounded file/line before JSON parsing; post-parse node/type checks. + + json.loads allocations and recursion precede postchecks; outer 1GiB/180s + supervision remains mandatory. This is not a proved successful-fit bound. + """ + need(type(raw) is bytes and 0 < len(raw) <= cap, 'JSON byte cap') + def pairs(rows): + out = {} + for key, value in rows: + checkpoint() + need(type(key) is str and key not in out, 'duplicate or foreign JSON key') + out[key] = value + return out + def constant(value): + raise AdapterStop('nonfinite JSON constant') + checkpoint() + value = json.loads(raw.decode('ascii'), object_pairs_hook=pairs, parse_constant=constant) + checkpoint() + nodes = [0] + def walk(item, depth): + checkpoint() + nodes[0] += 1 + need(nodes[0] <= 200000 and depth <= 32, 'JSON nodes/depth') + kind = type(item) + if item is None or kind is bool: + return + if kind is int: + need(item.bit_length() <= 128, 'JSON integer bound') + elif kind is float: + need(math.isfinite(item), 'JSON finite float') + elif kind is str: + need(len(item) <= 1048576, 'JSON string bound') + elif kind in (dict, list): + need(len(item) <= 16384, 'JSON collection bound') + if kind is dict: + for key, child in item.items(): + checkpoint() + need(type(key) is str and len(key) <= 65536, 'JSON key bound') + walk(child, depth + 1) + else: + for child in item: + checkpoint() + walk(child, depth + 1) + else: + raise AdapterStop('foreign JSON type') + walk(value, 0) + return value + + +def identity(info): + return (info.st_dev, info.st_ino, info.st_mode, info.st_nlink, + info.st_uid, info.st_size, info.st_mtime_ns, info.st_ctime_ns) + + +def verify_journal(raw, inputs, inventory, mode, outcome): + """DATA journal only; never decode the typed input or invoke an oracle again.""" + need(raw.endswith(b'\n'), 'journal lacks final newline') + lines = raw.splitlines() + need(len(lines) == len(INPUT_ORDER) + 2 * len(inventory) + 1, 'complete journal inventory differs') + position = 0 + for name in INPUT_ORDER: + checkpoint() + observed = json_data(lines[position], 1048576) + position += 1 + exact(observed, ('kind', 'name', 'bytes', 'sha256', 'mode')) + expected = inputs[name] + need(observed['kind'] == 'INPUT_RAW_BEFORE_ORACLE' and observed['name'] == name and + type(observed['bytes']) is int and observed['bytes'] == expected['bytes'] and + observed['sha256'] == expected['sha256'] and observed['mode'] == mode, + 'input RAW-before-oracle journal differs') + for control in inventory: + checkpoint() + first = json_data(lines[position], 1048576) + second = json_data(lines[position + 1], 1048576) + position += 2 + exact(first, ('kind', 'name', 'scope', 'raw_hex', 'raw_bytes', 'raw_sha256', 'expected_code')) + exact(second, ('kind', 'name', 'code')) + need(first['kind'] == 'CONTROL_RAW_BEFORE_ORACLE' and first['name'] == control['name'] and + first['scope'] == control['scope'] and first['expected_code'] == control['expected_code'] and + second['kind'] == 'CONTROL_OBSERVED' and second['name'] == control['name'] and + second['code'] == control['expected_code'], 'literal RAW/order/observed code differs') + hx = first['raw_hex'] + need(type(first['raw_bytes']) is int and 0 <= first['raw_bytes'] <= 131072 and + type(hx) is str and len(hx) == first['raw_bytes'] * 2 and + all(c in '0123456789abcdef' for c in hx), 'observed RAW hex type/length') + sha_value(first['raw_sha256']) + # Observed transport consistency only. Fixture identity is source/body-pinned; + # expected code/value checks stay independently fixed, never learned here. + need(digest(bytes.fromhex(hx)) == first['raw_sha256'], 'observed RAW transport digest differs') + final = json_data(lines[position], 1048576) + exact(final, ('kind', 'outcome')) + need(final['kind'] == 'SEMANTIC_OBSERVATION' and canonical(final['outcome']) == canonical(outcome), + 'complete semantic observation cross-binding differs') + + +def verify_external(directory, spec, inputs, mode, binding): + before = external_census(directory) + manifest, material = {}, {} + for name, cap in FILE_CAPS.items(): + checkpoint() + row, raw = stable_blob(directory / name, cap, 0o600, + materialize=name in ('receipt.json', 'observations.jsonl')) + manifest[name] = row + if raw is not None: + material[name] = raw + need(sum(row['bytes'] for row in manifest.values()) <= spec['external_total_cap_bytes'], + 'external aggregate byte cap') + for name in INPUT_ORDER: + checkpoint() + filename = 'RAW-' + name + ('.typed' if name in ('artifact', 'stdout') else '.json') + expected, observed = inputs['inputs'][mode][name], manifest[filename] + need(type(expected['bytes']) is int and expected['bytes'] == observed['bytes'] and + expected['sha256'] == observed['sha256'], 'external RAW copy differs from fixed input') + receipt = json_data(material['receipt.json'], FILE_CAPS['receipt.json']) + exact(receipt, ('schema', 'status', 'mode', 'source_sha256', 'contract_sha256', + *FALSE_FLAGS, 'controls_completed', 'outcome', + 'observed_internal_wall_before_receipt_seconds', + 'observed_internal_CPU_before_receipt_seconds', 'internal_receipt_and_cleanup_tail_excluded')) + for key in ('observed_internal_wall_before_receipt_seconds', + 'observed_internal_CPU_before_receipt_seconds'): + checkpoint() + need(type(receipt[key]) in (int, float) and math.isfinite(receipt[key]) and + receipt[key] >= 0, 'internal DATA timing type/value') + need(receipt['internal_receipt_and_cleanup_tail_excluded'] is True, 'internal receipt timing scope differs') + need(type(receipt) is dict and receipt.get('schema') == 'independent-exact-prefix-DATA-outcome-v2' and + receipt.get('status') == 'EXACT_PREFIX_SERIALIZED_DATA_OBSERVED' and + receipt.get('mode') == mode and receipt.get('source_sha256') == binding['decoder']['sha256'] and + receipt.get('contract_sha256') == binding['input_contract']['sha256'], + 'external DATA receipt source/status/mode differs') + for key in FALSE_FLAGS: + checkpoint() + need(receipt.get(key) is False, 'qualified/native/science/gain flag is not exactly false') + required = [row['name'] for row in spec['control_inventory']] + need(type(receipt.get('controls_completed')) is list and + all(type(name) is str for name in receipt['controls_completed']) and + receipt['controls_completed'] == required, 'all required literal controls not completed in order') + outcome = receipt.get('outcome') + exact(outcome, ('decision', 'scope', 'mode', 'journal_rows', 'independent_documents', + 'independent_decoded_bytes', 'independent_nodes', 'documents', + 'trusted_source_lifetime_proof_separate', *OUTCOME_FALSE_FLAGS)) + need(outcome['trusted_source_lifetime_proof_separate'] is True, 'source lifetime premise scope differs') + for key in ('independent_documents', 'independent_decoded_bytes', 'independent_nodes'): + checkpoint() + need(type(outcome[key]) is int and outcome[key] >= 0, 'DATA outcome counter type') + need(type(outcome) is dict and outcome.get('decision') == receipt['status'] and + outcome.get('mode') == mode, 'semantic DATA outcome mode/status differs') + for key in OUTCOME_FALSE_FLAGS: + checkpoint() + need(outcome.get(key) is False, 'semantic qualified/native/science flag is not exactly false') + verify_journal(material['observations.jsonl'], inputs['inputs'][mode], + spec['control_inventory'], mode, outcome) + # Distinct final freshness boundary: no cached PASS across changes. + for name, cap in FILE_CAPS.items(): + checkpoint() + final, unused = stable_blob(directory / name, cap, 0o600) + need(final == manifest[name], 'external final stable bytes/identity changed') + need(external_census(directory) == before, 'external final directory/membership changed') + return {'schema': 'independent-prefix-external-DATA-manifest-v1', + 'directory': str(directory), 'directory_identity': list(before), + 'files': manifest, 'file_count': len(manifest), + 'total_bytes': sum(row['bytes'] for row in manifest.values()), + 'external_receipt_sha256': manifest['receipt.json']['sha256']}, required + +ADAPTER_SUCCESS_KEYS = ('schema', 'status', 'mode', 'optimized', 'job', 'label', 'lanes', 'finite_only', 'source_review_sha256', 'adapter_contract', 'decoder_sha256', 'input_contract_sha256', 'control_inventory_sha256', 'qualified', 'full99_fit', 'full52prefix_qualification', 'runtime_profile_qualified', 'native_identity_proved', 'fullcaller_admitted', 'fullscience', 'gain', 'execution_grant_created', 'all_costs_settled', 'native_fault_totality_qualified', 'fixture_byte_independence', 'decoder', 'decoder_control_inventory', 'input_contract', 'controls_completed', 'all_required_controls_observed', 'external_manifest', 'external_manifest_sha256', 'external_receipt') + + + +def stable_blob(path, cap, mode, expected=None, materialize=False): + return IO.read(path, cap, mode, expected, materialize) + + +def read_json(path, cap=4194304, mode=None, expected=None): + row, raw = IO.read(path, cap, mode, expected, True) + return json_data(raw, cap), row + + +def external_census(directory): + before = private_directory(directory) + names = IO.names(directory, 6) + need(len(names) == len(FILE_CAPS) and set(names) == set(FILE_CAPS), 'exact external six-file census') + need(private_directory(directory) == before, 'external directory changed') + return before + + +def private_directory(path): + checkpoint() + need(path.is_absolute() and path.resolve(strict=True) == path, 'private canonical directory') + info = path.lstat() + need(stat.S_ISDIR(info.st_mode) and stat.S_IMODE(info.st_mode) == 0o700 and + info.st_uid == os.getuid(), 'private owner0700 directory') + return identity(info) + + +def metadata(path, cap=65536): + return IO.read(Path(path), cap, materialize=True, proc=True)[1] + + +def process(pid): + raw = metadata('/proc/' + str(pid) + '/stat', 8192) + end = raw.rfind(b') ') + need(end >= 0, 'process stat syntax') + fields = raw[end + 2:].split() + return {'pid': pid, 'ppid': int(fields[1]), 'pgid': int(fields[2]), 'sid': int(fields[3]), + 'start_ticks': int(fields[19]), 'rss_bytes': int(fields[21]) * os.sysconf('SC_PAGE_SIZE')} + + +class GlobalLease: + """This process's real FD, never supplied in JSON or passed to children.""" + def __init__(self): + self.fd, self.phase, self.birth, self.lock_info = None, 'NEW', None, None + + def acquire(self): + self.phase = 'OPEN_PENDING' + try: + self.fd = os.open(HISTORICAL_LOCK, os.O_RDWR | os.O_NOFOLLOW | os.O_CLOEXEC) + self.phase = 'OPEN_RETURNED' + fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + self.phase = 'EX_HELD' + self.birth = process(os.getpid()) + self.lock_info = self.verify() + except BaseException as error: + remember(error) + raise + return self + + def verify(self): + need(self.phase == 'EX_HELD' and type(self.fd) is int, 'actual global FD is not held') + actual = os.fstat(self.fd) + need(stat.S_ISREG(actual.st_mode) and actual.st_uid == os.getuid() and actual.st_nlink == 1 and + HISTORICAL_LOCK.resolve(strict=True) == HISTORICAL_LOCK and + identity(HISTORICAL_LOCK.lstat()) == identity(actual), 'global lock canonical inode/owner differs') + need(fcntl.fcntl(self.fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC, 'global FD must close on exec') + info = metadata('/proc/self/fdinfo/' + str(self.fd), 16384).decode('ascii') + fields = dict(line.split(':', 1) for line in info.splitlines() if ':' in line) + need(int(fields['ino'].strip()) == actual.st_ino and + any('FLOCK' in line and 'WRITE' in line and (' ' + str(os.getpid()) + ' ') in line + for line in info.splitlines() if line.startswith('lock:')), 'actual held EX flock fdinfo missing') + current = process(os.getpid()) + if self.birth is not None: + need(current['pid'] == self.birth['pid'] and current['start_ticks'] == self.birth['start_ticks'], + 'global lease process generation changed') + return {'path': str(HISTORICAL_LOCK), 'fd_number_observed': self.fd, + 'fstat': list(identity(actual)), 'fdinfo': info, 'parent': current, + 'source_acquired_here': True, 'FD_CLOEXEC': True, + 'not_JSON_or_native_memory_authority': True} + + def close(self): + if self.fd is None: + return + self.phase = 'CLOSE_ENTERED' + try: + os.close(self.fd) # Only release point; no unlock/duplicate/SCM transfer. + except BaseException as error: + self.phase = 'CLOSE_UNKNOWN' + IO_UNKNOWN[0] = True + remember(error) + raise + self.phase = 'CLOSE_RETURNED' + + +def load_source(path, expected, module_name): + row, raw = IO.read(path, 2097152, 0o444, expected, True) + need(module_name not in sys.modules, 'parent module name already loaded') + module = ModuleType(module_name) + module.__dict__.update(__file__=str(path), __name__=module_name, __package__=None, + __spec__=None, __builtins__=builtins) + sys.modules[module_name] = module + exec(compile(raw, str(path), 'exec', dont_inherit=True), module.__dict__) + RETAINED_MODULES.append(module) + return module, row + + +def clean_launch(): + need(sys.executable == '/usr/bin/python3.12' and sys.implementation.name == 'cpython' and + sys.version_info[:2] == (3, 12) and sys.base_prefix == '/usr', 'actual selected interpreter/prefix') + need(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 and + tuple(sys.path) == INITIAL_PATH and dict(os.environ) == ENV, 'clean owning-parent launch differs') + need(os.getcwd() == str(W), 'exact parent working directory') + need(len(IO.names('/proc/self/task', 2)) == 1 and + signal.getitimer(signal.ITIMER_REAL) == (0.0, 0.0) and + signal.getsignal(signal.SIGALRM) == signal.SIG_DFL, + 'single-task/no prior alarm or incompatible SIGALRM owner required') + status = metadata('/proc/self/status').decode('ascii') + values = dict(line.split(':', 1) for line in status.splitlines() if ':' in line) + need(int(values['Umask'].strip(), 8) == 0o077, 'actual inherited umask must be0077') + streams = {} + for fd in (1, 2): + info = os.fstat(fd) + need(stat.S_ISREG(info.st_mode) and stat.S_IMODE(info.st_mode) == 0o600 and + info.st_uid == os.getuid() and info.st_nlink == 1, 'captured regular0600 stdout/stderr') + streams[str(fd)] = list(identity(info)) + return {'actual_parent': process(os.getpid()), 'sys_base_prefix': sys.base_prefix, + 'environment': dict(os.environ), 'initial_path': list(sys.path), 'stdio': streams, + 'umask_observed': 0o077, 'prior_SIGALRM_handler': 'SIG_DFL', + 'operating_TCB_not_loaded_image_proof': True} + + +def add_expectation(pins, path, expected): + # Independent expected manifests remain separate even for the same pathname. + if path not in pins: + pins[path] = [] + pins[path].append(expected) + + +def snapshot_domain(pins): + result = {} + for path, expectations in pins.items(): + checkpoint() + row = IO.read(Path(path), max(1, max(item['bytes'] for item in expectations)))[0] + for expected in expectations: + checkpoint() + need(row['bytes'] == expected['bytes'] and row['sha256'] == expected['sha256'] and + row['mode'] == expected['mode'], 'independent source/input expected pin differs') + result[path] = row + return result + + +def writer_probe(pins): + """Actual bounded observations under cooperative closed-world lease premise. + + Not an atomic all-host proof. Same-UID churn/permission/unknown IO fails closed; + root/admin/hostile actors and mount/namespace replacement need external scope. + """ + protected = {(row['identity'][0], row['identity'][1]) for row in pins.values()} + observations, aliases = [], [] + for name in IO.names('/proc', 65536): + checkpoint() + if not name.isdecimal(): + continue + path = Path('/proc') / name + info = path.stat() + if info.st_uid != os.getuid(): + continue + before = process(int(name)) + fd_hash, fd_count = hashlib.sha256(), 0 + for descriptor in IO.names(path / 'fd', 4096): + checkpoint() + fdpath = path / 'fd' / descriptor + try: + st = fdpath.stat() + except FileNotFoundError: + # No descriptor was acquired by stat. In particular our closed + # census/metadata FDs can disappear; this is not release proof. + fd_hash.update(canonical({'fd': descriptor, 'observation': 'FD_LINK_ABSENT_AT_STAT'})) + continue + data = metadata(path / 'fdinfo' / descriptor, 16384).decode('ascii') + fields = dict(line.split(':', 1) for line in data.splitlines() if ':' in line) + flags = int(fields['flags'].strip(), 8) + row = {'fd': descriptor, 'dev': st.st_dev, 'ino': st.st_ino, 'flags': flags} + fd_hash.update(canonical(row));fd_count += 1 + if (st.st_dev, st.st_ino) in protected and flags & os.O_ACCMODE != os.O_RDONLY: + aliases.append({'pid': int(name), 'birth': before['start_ticks'], 'fd': descriptor, 'inode': row}) + maps = metadata(path / 'maps', 2097152).decode('utf-8', 'strict') + for line in maps.splitlines(): + checkpoint() + fields = line.split(None, 5) + if len(fields) < 5 or fields[4] == '0': + continue + devparts = fields[3].split(':') + dev = os.makedev(int(devparts[0], 16), int(devparts[1], 16)) + if 'w' in fields[1] and 's' in fields[1] and (dev, int(fields[4])) in protected: + aliases.append({'pid': int(name), 'birth': before['start_ticks'], 'writable_shared_map': line[:4096]}) + after = process(int(name)) + need(before['start_ticks'] == after['start_ticks'], 'process generation churn during writer probe') + observations.append({'before': before, 'after': after, 'FD_count': fd_count, + 'FD_census_sha256': fd_hash.hexdigest(), 'maps_sha256': digest(maps.encode())}) + need(len(observations) <= 8192, 'same-UID process census cap') + need(not aliases, 'writable original/source-domain alias found') + return {'processes': observations, 'writable_aliases': aliases, + 'atomic_or_hostile_writer_exclusion_proved': False, + 'requires_reviewed_registered_writer_and_admin_exclusion_premise': True} + + +_FULL_RECEIVER = None +_FULL_RECEIVER_IMAGE = None + + +_ENVIRONMENT_ASSOCIATION = None + + +def bind_environment_association(association): + global _ENVIRONMENT_ASSOCIATION + need(_ENVIRONMENT_ASSOCIATION is None, 'one authenticated original environment association owner') + cls = type(association) + need(type(cls) is type, 'ordinary source-owned association class') + module_name = type.__getattribute__(cls,'__module__') + module = sys.modules[module_name] + need(type(module) is ModuleType and + Path(module.__file__) == JOINED_ROOT / 'implementation/bindings/environment_association.py' and + module.__dict__[type.__getattribute__(cls,'__name__')] is cls, + 'actual separately authenticated association source, never caller DATA authority') + close = type.__getattribute__(cls,'__dict__')['close'] + need(type(close) is FunctionType and close.__globals__ is module.__dict__, + 'actual source-owned association retirement function') + _ENVIRONMENT_ASSOCIATION = {'object':association,'class':cls,'module':module, + 'close':close,'close_code':close.__code__,'phase':'OPEN'} + return True + + +def close_environment_association(): + owner = _ENVIRONMENT_ASSOCIATION + need(type(owner) is dict, 'actual environment association binding required') + if owner['phase'] == 'CLOSED': + return True # Known completed source operation; no native close is replayed. + need(owner['phase'] == 'OPEN', 'unknown association close is never retried') + owner['phase'] = 'CLOSE_ENTERED' + try: + close = owner['close'] + need(type.__getattribute__(owner['class'],'__dict__')['close'] is close and + close.__code__ is owner['close_code'] and close.__globals__ is owner['module'].__dict__, + 'association source retirement identity changed') + close(owner['object']) + except BaseException as error: + owner['phase'] = 'CLOSE_FAILED' + # The actual owner registers known/unknown resource dispositions. + # A known closed STOP may retain; uncertainty still prevents the + # original registry/EX/G seal. Do not infer an FD outcome from error. + remember(error) + raise + owner['phase'] = 'CLOSED' + return True + + +def bind_full_receiver(module): + global _FULL_RECEIVER, _FULL_RECEIVER_IMAGE + need(_FULL_RECEIVER is None and type(module) is ModuleType and + Path(module.__file__) == JOINED_ROOT / 'implementation/source/full_result_receiver.py', + 'one actual authenticated complete terminal receiver') + image = [] + for name in ('stage_check','validate_terminal','command_for','job_for','case_for'): + function = module.__dict__[name] + need(type(function) is FunctionType and function.__globals__ is module.__dict__, + 'actual selected full receiver source functions') + image.append((name,function,function.__code__)) + _FULL_RECEIVER, _FULL_RECEIVER_IMAGE = module, tuple(image) + return True + + +def full_receiver(): + need(_FULL_RECEIVER is not None, 'complete terminal receiver not bound') + for name,function,code in _FULL_RECEIVER_IMAGE: + need(_FULL_RECEIVER.__dict__[name] is function and function.__code__ is code and + function.__globals__ is _FULL_RECEIVER.__dict__, 'full receiver source identity changed') + return _FULL_RECEIVER + + +def stage_check(stage_pins): + return full_receiver().stage_check(sys.modules[__name__], stage_pins) + + +def strict_data(case, inputs, adapter_spec, binding, nested_root): + # The original parent-owned custody, clock, registry and retention stay on + # this route. Actual scientific acceptance is now the complete receiver. + layout = _JOINED_RUN['layout'].case(case['label']) + runner, unused = read_json(layout.runner_root / 'receipt.json', 4194304, 0o600) + supervision, unused = read_json(layout.supervision_root / 'SUPERVISION.json', 4194304, 0o600) + return full_receiver().validate_terminal(sys.modules[__name__],case,layout,runner,supervision) + + +class CaseBudget: + """Original case_begin through retained validation; no hard-fault theorem.""" + def __init__(self): + self.begin, self.deadline, self.case = None, None, None + self.active = False + + def start(self, begin, case): + need(not self.active and type(begin) is float and math.isfinite(begin) and + 0 <= time.monotonic() - begin < 180, 'actual original case start absent/expired') + need(signal.getitimer(signal.ITIMER_REAL) == (0.0, 0.0) and + signal.getsignal(signal.SIGALRM) == signal.SIG_DFL, + 'case cannot borrow alarm or replace incompatible signal owner') + self.begin, self.deadline, self.case = begin, begin + 180, case + self.active = True + ACTIVE_CASE[0] = self + self.check() + + def check(self): + need(self.active and time.monotonic() < self.deadline, 'complete case180 exhausted') + + def close(self): + if self.active: + self.active = False + ACTIVE_CASE[0] = None + + def original_metric(self, case): + # Separate paid read of original measurement, never cached validate PASS. + path = _JOINED_RUN['layout'].case(case['label']).queue_root / (case['label'] + '.gate.json') + row, pin = read_json(path, 4194304, 0o600) + seconds = row['parent_command_wall_seconds_through_validation'] + need(type(seconds) in (int, float) and math.isfinite(seconds) and 0 <= seconds <= 180, + 'actual original complete-case measurement exceeds180; no next Root') + return {'case': case['label'], 'original_complete_seconds': seconds, 'gate': pin} + + +class ActualRootResults: + """Retain genuine run_root return objects, not restored Root capabilities.""" + def __init__(self, held_run_root, clock, case_bill): + self.original, self.clock, self.bill = held_run_root, clock, case_bill + self.results, self.entered, self.next = [None, None], [False, False], 0 + + def run_root(self, root, case, evidence, seconds, shared_deadline, + as_bytes=201326592, rss_bytes=201326592): + index = self.next + need(index < 2 and case['job'] == ('normal', 'optimized')[index] and + self.clock.active and self.clock.case == case, 'real root call order/clock') + attempt = _JOINED_RUN['registry'].attempt(case['label']) + _JOINED_RUN['registry'].assert_open(attempt,launch=True) + self.clock.check() + deadline = min(shared_deadline, self.clock.deadline) + row = self.bill[case['job']] + validation_tail = (row['validation_ns']+row['closing_ns'])/1000000000 + allowance = min(seconds,row['root_ns']/1000000000,deadline-time.monotonic()-2-validation_tail) + need(0 < allowance <= 180, 'no actual case allowance with reserved cleanup') + self.next += 1 + self.entered[index] = True + try: + self.clock.check() + self.results[index] = self.original(root, case, evidence, allowance, deadline, + as_bytes, rss_bytes) + except BaseException as error: + remember(error) + raise + # Retain actual return BEFORE cooperative post-return deadline check. + self.clock.check() + return self.results[index] # Same actual object returned unchanged. + + +class StrictQueueFacade: + """Explicit transport; held derivative validator executes once per actual case.""" + def __init__(self, queue, proxy, lease, supervisor, pins, before, inputs, spec, binding, evidence, clock): + self.queue, self.proxy, self.lease, self.s = queue, proxy, lease, supervisor + self.pins, self.before, self.inputs, self.spec = pins, before, inputs, spec + self.binding, self.evidence, self.clock = binding, evidence, clock + self.original_validate, self.original_main_code = queue.validate, queue.main.__code__ + self.nested_root = proxy.evidence + self.validated, self.observations, self.case_metrics = [], [], [] + + def run(self, command, **kwargs): + frame, local = None, None + try: + # Explicit read-only CPython frame boundary, no JSON clock/capability. + frame = sys._getframe(1) + need(frame.f_code is self.original_main_code, 'caller is not held original queue.main') + local = frame.f_locals + case = local['case'] + need(local['command'] is command and case == self.proxy.cases[self.proxy.next], + 'actual original caller case/command differs') + begin = local['case_begin'] + frame, local = None, None # Release transient references before any IO/Root. + self.clock.start(begin, case) + if self.validated: + self.case_metrics.append(self.clock.original_metric(self.proxy.cases[self.proxy.next - 1])) + self.lease.verify() + checkpoint() + need(self.proxy.next == len(self.validated), 'previous real Root has not passed strict validation') + need(snapshot_domain(self.pins) == self.before, 'before-Root original/source custody changed') + writer_probe(self.before) + checkpoint() + result = self.proxy.run(command, **kwargs) + checkpoint() # Opaque original proxy has returned; no parent alarm. + return result + except BaseException as error: + remember(error) # BEFORE unchanged queue.main finally may fail later. + try: + self.clock.close() + except BaseException as secondary: + remember(secondary) + raise + finally: + frame, local = None, None + + def validate(self, case): + try: + # Original queue already rejected nonzero/stderr before this call. + checkpoint() # Immediately before opaque held original validator. + if case['job']=='normal': + row = self.original_validate(case,self.nested_root,self.s.RUNNER_PATH) + else: + row={'label':case['label'],'job':case['job'],'gate':'REQUIRES_STRICT_ORIGINAL_REFUSAL', + 'positive_scientific_result':False} + checkpoint() + self.lease.verify() + folder = _JOINED_RUN['layout'].case(case['label']).supervision_root + supervision, unused = read_json(folder / 'SUPERVISION.json', 4194304, 0o600) + cleanup = supervision['cleanup'] + need(supervision['returncode'] == (1 if case['job']=='optimized' else 0) and supervision['failure'] is None and + cleanup['complete'] is True and cleanup['group_empty_proved'] is True and + cleanup['remaining'] == [] and cleanup['observed_after_root_exit'] == [] and + cleanup['reaped_adopted'] == [] and not self.s.children_now(), 'actual owned cleanup not complete') + data = strict_data(case, self.inputs, self.spec, self.binding, self.nested_root) + need(snapshot_domain(self.pins) == self.before, 'post-Root original/source custody changed') + writers = writer_probe(self.before) + self.lease.verify() + checkpoint() + record = {'queue_original_row': row, 'strict_full_terminal': data, 'writers': writers, + 'global_lease': self.lease.lock_info, 'cleanup': cleanup, + 'actual_original_case_begin': self.clock.begin, 'case_deadline': self.clock.deadline} + attempt = _JOINED_RUN['registry'].attempt(case['label']) + with _JOINED_RUN['registry'].writer(attempt,'strict',attempt.layout.validation_root / 'STRICT.json'): + pin = IO.write(attempt.layout.validation_root / 'STRICT.json', record) + _JOINED_RUN['registry'].required_writer_closed(attempt,'strict') + checkpoint() # Full strict record retained before success. + self.observations.append(record) + self.validated.append(case['job']) + _JOINED_RUN['validated_labels'].append(case['label']) + row['strict_parent_full_terminal_receipt'] = pin + return row + except BaseException as error: + remember(error) # Includes original_validate and each strict check. + raise + finally: + try: + self.clock.close() + except BaseException as secondary: + remember(secondary) + raise + + def primary(self,case): + need(self.validated and self.validated[-1]==case['job'], 'actual strict terminal validation before primary end') + return self.proxy.bound.finish_primary(case['label']) + + +def retain_queue_failure(error, queue): + """Keep actual native context; classify only held queue body traceback. + + No ambient sys.exception or trace hook. No universal recovery claim for + underlying caught errors. Existing facade first object always keeps priority. + """ + chain, item = [], error + while item is not None and all(item is not held for held in chain) and len(chain) < 32: + chain.append(item) + item = item.__context__ + if item is not None: + IO_UNKNOWN[0] = True + if FIRST[0] is None: + for candidate in reversed(chain): + tb = BaseException.__traceback__.__get__(candidate,type(candidate)) + while tb is not None: + # Exact pinned original queue body's try/except, not its finally. + if tb.tb_frame.f_code is queue.main.__code__: + remember(candidate) + break + tb = tb.tb_next + if FIRST[0] is not None: + break + remember(error) + for candidate in chain: + remember(candidate) + if candidate.__cause__ is not None: + remember(candidate.__cause__) + + +def safe_custody_state(root_results, supervisor, lease): + """Actual entered/results/cleanup/children observations, no restored owner.""" + need(lease.phase == 'EX_HELD' and type(lease.fd) is int and not IO_UNKNOWN[0], + 'held known lease/IO required for custody') + lease.verify() + rows = [] + if root_results is not None: + for index, entered in enumerate(root_results.entered): + if not entered: + continue + actual = root_results.results[index] + need(type(actual) is dict, 'entered real Root has no actual returned cleanup record') + cleanup = actual['cleanup'] + need(cleanup['complete'] is True and cleanup['group_empty_proved'] is True and + cleanup['remaining'] == [], 'actual Root cleanup is incomplete/unknown') + rows.append({'index': index, 'actual_cleanup': cleanup, + 'actual_captured_root': actual['captured_root'], 'actual_status': actual['status']}) + if supervisor is not None: + need(not supervisor.children_now(), 'actual children prevent safe final custody') + else: + need(metadata('/proc/self/task/' + str(os.getpid()) + '/children').strip() == b'', + 'no-Root actual parent children observation is not empty') + return {'safe_under_selected_operating_TCB': True, 'actual_roots': rows, + 'no_Root_entered': not rows, 'live_owner_reconstructed': False} + + + +def error_data(): + def item(error): + if error is None: + return None + frames, tb = [], BaseException.__traceback__.__get__(error,type(error)) + while tb is not None and len(frames) < 32: + frames.append({'file': tb.tb_frame.f_code.co_filename, 'line': tb.tb_lineno, + 'function': tb.tb_frame.f_code.co_name}) + tb = tb.tb_next + return {'actual_type_id': id(type(error)), 'foreign_type_unformatted': True, 'frames': frames} + return {'first': item(FIRST[0]), 'secondary': [item(e) for e in SECONDARY if e is not None], + 'IO_unknown': IO_UNKNOWN[0], 'actual_exception_objects_retained_until_exit': True} + + + +def successor_guard(lease): + lease.verify() # Real current GlobalLease; never the metadata probe record. + if ELIGIBILITY[0] is None: + ELIGIBILITY[0], unused = load_source(ELIGIBILITY_PATH,ELIGIBILITY_PIN, + 'exact_successor_historical_eligibility_v1') + value = ELIGIBILITY[0].full_snapshot( + lambda path, row: IO.read(Path(path),row['bytes'],row['mode'],row,True)[1], + lambda path, cap: IO.names(Path(path),cap),SUCCESSOR_ACTIVE) + lease.verify() + return value + +class ExecutionBarrier: + """Persistent closed-one-parent barrier; never a claim of orphan disposal.""" + def __init__(self): + self.slot, self.phase = None, 'NEW' + self.parent_slots = [None, None] + + def prepare(self, lease): + private_directory(QUARANTINE.parent) # Admitted initializer owns fresh sibling namespace. + successor_guard(lease) # Exact history rechecked under this actual EX before NEW marker. + need(not os.path.lexists(SEALED) and not os.path.lexists(ROOT/'validation'/(NAME+'-SEALED-ONE-PARENT')), 'own or original sealed oneuse marker already exists') + self.phase = 'PREPARING' + need(ROOT.resolve(strict=True) == ROOT and BARRIER.parent.resolve(strict=True) == BARRIER.parent and + QUARANTINE.parent.resolve(strict=True) == QUARANTINE.parent, 'canonical retained namespaces') + for index, directory in enumerate((BARRIER.parent, QUARANTINE.parent)): + self.parent_slots[index] = IO.acquire(directory, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC) + BARRIER.mkdir(mode=0o700) + IO.write(BARRIER / 'START.json', {'kind': 'persistent_execution_quarantine', + 'source_owner': lease.verify(), 'future_actual_operation_prohibited_until_resolution': True, + 'not_an_attempt_PASS_or_runtime_qualification': True}) + self.slot = IO.acquire(BARRIER / 'details.jsonl', os.O_WRONLY | os.O_CREAT | os.O_EXCL | + os.O_NOFOLLOW | os.O_CLOEXEC) + for parent_slot in self.parent_slots: + os.fsync(parent_slot[0]) + self.phase = 'PREPARED' + + def quarantine(self): + # No new FD or original-domain read is needed. Keep first evidence if + # allocation/write/fsync/rename fails; PREPARED is itself a blocking state. + self.phase = 'QUARANTINED' + if self.slot is not None and self.slot[1] == 'OWNED': + try: + raw = canonical({'status': 'EXECUTION_QUARANTINED', 'errors': error_data(), + 'future_actual_operation_prohibited': True, + 'unknown_remaining_writers_not_disposed_by_lock_release': True, + 'external_actual_teardown_and_ownership_resolution_required': True}) + offset = 0 + while offset < len(raw): + n = os.write(self.slot[0], raw[offset:offset + 65536]) + need(type(n) is int and n > 0, 'quarantine detail write') + offset += n + os.fsync(self.slot[0]) + except BaseException as error: + remember(error) + try: + if not QUARANTINE.exists(): + source = BARRIER if BARRIER.exists() else SEALED + os.rename(source, QUARANTINE) # Unclosed run: unchanged budget/runner refuse future roots. + for parent_slot in self.parent_slots: + if parent_slot is not None and parent_slot[1] == 'OWNED': + os.fsync(parent_slot[0]) + except BaseException as error: + remember(error) # Remaining canonical BARRIER still blocks registered parent admission. + self.close() + + def seal_success(self): + need(not IO_UNKNOWN[0], 'barrier ownership unknown; cannot seal success') + os.rename(BARRIER, SEALED) + for parent_slot in self.parent_slots: + if parent_slot is not None and parent_slot[1] == 'OWNED': + os.fsync(parent_slot[0]) + self.close() + need(not IO_UNKNOWN[0], 'barrier close unknown; cannot seal success') + self.phase = 'SEALED_SUCCESS' + + def close(self): + for slot in (self.slot, *self.parent_slots): + if slot is not None and slot[1] == 'OWNED': + try: + IO.close(slot) + except BaseException as error: + remember(error) + + + +def exact_pin(value): + need(type(value) is dict and len(value) == 3 and all(type(k) is str for k in value), + 'exact builtin pin keys before hashing') + exact(value,('path','bytes','sha256')) + need(type(value['path']) is str and Path(value['path']).is_absolute() and + type(value['bytes']) is int and 0 < value['bytes'] <= 2097152,'bounded fixed pin DATA') + sha_value(value['sha256']) + + +def complete_bill(plan,approval,request): + """Full exclusive symbolic bill; current physical fit stays separate.""" + value,pin = read_json(Path(plan['whole_body_bill_pin']['path']),1048576,0o444,plan['whole_body_bill_pin']) + outside = ('g_pre_m_ns','startup_preflight_ns','retention_prepare_seal_ns', + 'retention_borrower_ns','retention_parent_readback_ns', + 'controller_final_release_ns','k_capture_fee_tail_ns','m_body_tail_ns','g_terminal_tail_ns') + exact(value,('schema','selected_packet_sha256','queue_sha256','stage_sha256', + 'complete_work_review_sha256','cases','whole_command_ns',*outside)) + need(value['schema'] == 'fresh-composed-guardian-whole-command-bill-v2' and + value['selected_packet_sha256'] == plan['selected_packet_pin']['sha256'] and + value['queue_sha256'] == plan['queue_pin']['sha256'] and + value['stage_sha256'] == plan['stage_sha256'] and + value['complete_work_review_sha256'] == plan['complete_work_review_pin']['sha256'], + 'full joined source/work/command bill binding') + read_json(Path(plan['complete_work_review_pin']['path']),1048576,0o444,plan['complete_work_review_pin']) + exact(value['cases'],('normal','optimized')) + outside_total = 0 + for name in outside: + need(type(value[name]) is int and 0 < value[name] <= 180000000000, + 'complete positive exclusive outside term required') + outside_total += value[name] + queue_total = 0 + for mode in ('normal','optimized'): + row = value['cases'][mode] + exact(row,('root_ns','validation_ns','guard_ns','cleanup_ns','closing_ns')) + for name in row: + need(type(row[name]) is int and 0 <= row[name] <= 180000000000, + 'original complete nonoverlapping case term') + queue_total += row[name] + need(row['root_ns'] > 0 and row['validation_ns'] > 0 and row['cleanup_ns'] >= 2000000000, + 'full original root validation and cleanup retained') + total = outside_total + queue_total + need(outside_total <= 30000000000 and queue_total <= 390000000000, + 'separate declared outside30/queue390 retained') + need(type(value['whole_command_ns']) is int and total == value['whole_command_ns'] + and total <= request['body_reservation_ns'] <= 180000000000, + 'same genuine original whole180 reservation') + value['outside_declared_ns'],value['queue_declared_ns'] = outside_total,queue_total + value['controller_final_ns'] = sum(value[k] for k in ('retention_prepare_seal_ns', + 'retention_borrower_ns','retention_parent_readback_ns','controller_final_release_ns')) + value['outer_post_controller_ns'] = sum(value[k] for k in ('k_capture_fee_tail_ns','m_body_tail_ns','g_terminal_tail_ns')) + value['remaining_before_queue_ns'] = total-value['g_pre_m_ns']-value['startup_preflight_ns'] + return value + + +def configure_joined(layout_module,registry_module,issuer_module,guardian,retention_binding): + global _JOINED + need(_JOINED is None and all(type(m) is ModuleType for m in + (layout_module,registry_module,issuer_module)), 'one fixed private joined module binding') + need(guardian is not None and type(retention_binding) is dict, 'fixed actual G and retention DATA') + # The immutable external loader authenticates the exact source bytes before + # these source-private function/global snapshots are established. + image = [] + for module,names in ((layout_module,('LayoutSelection',)), + (registry_module,('AttemptRegistry',)), + (issuer_module,('prepare','bind_connected','completed_boundary','guardian_writer_closure'))): + for name in names: + value = module.__dict__[name] + image.append((module,name,value,getattr(value,'__code__',None))) + modules = (layout_module,registry_module,issuer_module,issuer_module.parent_authority, + issuer_module.postrun_hook,issuer_module.fork_borrower,issuer_module.actual_consumer, + issuer_module.native_io,issuer_module.actual_consumer.error_custody) + runtime = {'production_issuer':{'_CONTEXT','_ERROR_COUNT','_ERROR_OVERFLOW','_RETENTION_FAILURE', + '_PROJECTION_FAILURE','_RAW','_IO_POISON','_CONNECTED','_RETENTION_ENTERED'}, + 'parent_authority':{'_OWNER','_FORK','_JOINED_BINDINGS'}, + 'actual_consumer':{'_TOOL_CACHE','_TOOL_CACHE_OWNER','_TOOLS'}, + 'native_io_custody':{'_PROCESS'}, + 'error_custody':{'_EXPORTED_BYTES','_REVIEWED_SOURCE_TYPES'}} + module_images = [] + for module in modules: + global_image = dict(module.__dict__) + functions,classes = [],[] + for value in global_image.values(): + if type(value) is FunctionType and value.__globals__ is module.__dict__: + functions.append((value,value.__code__,value.__defaults__,value.__kwdefaults__,value.__closure__,value.__globals__)) + elif type(value) is type and type.__getattribute__(value,'__module__') == module.__name__: + class_image = dict(type.__getattribute__(value,'__dict__')) + classes.append((value,class_image)) + for member in class_image.values(): + if type(member) is FunctionType: + functions.append((member,member.__code__,member.__defaults__,member.__kwdefaults__,member.__closure__,member.__globals__)) + elif type(member) in (staticmethod,classmethod): + fn = member.__func__ + functions.append((fn,fn.__code__,fn.__defaults__,fn.__kwdefaults__,fn.__closure__,fn.__globals__)) + elif type(member) is property: + for fn in (member.fget,member.fset,member.fdel): + if fn is not None: + functions.append((fn,fn.__code__,fn.__defaults__,fn.__kwdefaults__,fn.__closure__,fn.__globals__)) + leaf = Path(module.__file__).stem + module_images.append((module,global_image,runtime.get(leaf,set()),tuple(functions),tuple(classes))) + _JOINED = dict(token=object(),layout_module=layout_module,registry_module=registry_module, + issuer=issuer_module,guardian=guardian,retention=retention_binding,image=tuple(image), + module_images=tuple(module_images),installed_runtime={}) + return _JOINED['token'] + + +def joined_integrity(): + need(_JOINED is not None, 'actual source-private joined namespace absent') + for module,saved,allowed,functions,classes in _JOINED['module_images']: + current = module.__dict__ + need(set(current) == set(saved) and all(current[name] is saved[name] for name in saved if name not in allowed), + 'joined source-private globals replaced') + for fn,code,defaults,kwdefaults,closure,namespace in functions: + need(fn.__globals__ is namespace and fn.__code__ is code and fn.__defaults__ is defaults + and fn.__kwdefaults__ is kwdefaults and fn.__closure__ is closure, + 'joined original same-reference function code/default/closure replaced') + for name in allowed.intersection(current): + key = (id(module),name) + prior = _JOINED['installed_runtime'].get(key,saved[name]) + value = current[name] + if name == '_TOOL_CACHE_OWNER': + need(value is None or (type(value) is int and value == os.getpid() + and (prior is None or value == prior)), 'same actual parent tool-cache owner') + elif name in ('_ERROR_COUNT','_EXPORTED_BYTES'): + need(type(value) is int and type(prior) is int and prior <= value <= 2097152, + 'bounded monotone actual custody counter') + elif type(saved[name]) is bool: + need(type(value) is bool and (not prior or value), 'irreversible native poison/one-shot latch') + elif name == '_REVIEWED_SOURCE_TYPES': + need(type(value) is tuple and type(prior) is tuple and len(value) <= 256 + and value[:len(prior)] == prior, 'append-only reviewed source exception classes') + elif prior is not None and not (type(prior) is tuple and len(prior) == 0): + need(value is prior, 'source-issued actual lifecycle object replaced') + else: + need(value is None or type(value) in (dict,tuple) or isinstance(value,BaseException) + or (name == '_PROCESS' and type(value) is module.__dict__['Context']), + 'finite source-owned lifecycle installation type') + _JOINED['installed_runtime'][key] = value + for cls,image in classes: + native = type.__getattribute__(cls,'__dict__') + need(set(native) == set(image) and all(native[key] is image[key] for key in image), + 'joined original class method/descriptor replaced') + + +def joined_budget_checkpoint(reserve_ns=0, outside_reserve_ns=None): + state = _JOINED_RUN + if state is None: + return + now = time.monotonic_ns() + need(type(now) is int and now >= state['whole_begin_ns'] and type(reserve_ns) is int and reserve_ns >= 0, + 'genuine same-clock full endpoint required') + need(now+reserve_ns <= state['whole_deadline_ns'], 'whole180 including reserved tails exhausted') + begin,end = state['queue_native_ns'] + if outside_reserve_ns is None: + outside_reserve_ns = reserve_ns if end is not None else 0 + need(type(outside_reserve_ns) is int and 0 <= outside_reserve_ns <= reserve_ns, + 'separate explicit whole/nonqueue reservations') + if begin is None and end is None: + outside = now-state['whole_begin_ns'] + elif begin is not None and end is None: + need(state['queue_exited'] is False, 'native queue endpoint unknown after queue exit; outside remains unknown') + need(begin <= now, 'queue native begin ordered') + outside = begin-state['whole_begin_ns'] + need(now-begin <= 390000000000, 'dynamic queue390 exhausted') + else: + need(type(begin) is int and type(end) is int and state['whole_begin_ns'] <= begin <= end <= now, + 'actual complete native queue endpoints required') + need(end-begin <= 390000000000, 'dynamic queue390 exhausted') + outside = now-state['whole_begin_ns']-(end-begin) + need(0 <= outside and outside+outside_reserve_ns <= 30000000000, + 'dynamic full outside30 including retention/release/tails exhausted') + state['last_observation'] = dict(sample_ns=now,outside_ns=outside, + queue_native_ns=list(state['queue_native_ns']),whole_elapsed_ns=now-state['whole_begin_ns'], + complete_native_exit_observed=False,financial_close_created=False) + + +def joined_continuation_check(ctx, registry, purpose): + """A2-held exact helper for same-owner failure recording and retention. + + It preserves the first actual error. It creates no producer permission and + never runs in B. A2 independently retains its own private context/PID/EX + guards after this helper returns. + """ + need(_JOINED_RUN is not None and purpose in ('CLEANUP','RETENTION') + and registry is _JOINED_RUN['registry'] + and type(registry) is _JOINED['registry_module'].AttemptRegistry + and registry.owner_context is ctx, 'actual source-private same C2 registry/context') + joined_integrity() + need(not IO_UNKNOWN[0] and ERROR_OVERFLOW[0] is None, + 'unknown C2 native IO forbids protected failure continuation') + for slot in IO.slots: + need(slot[1] in ('FREE','CLOSED','OWNED') and + (slot[1] != 'OWNED' or (slot[2] is False and type(slot[0]) is int)), + 'known original parent FD state before cleanup/retention') + need(registry.phase in ('OPEN','DRAINING','SEALING','SEALED'), + 'quarantined source has no protected continuation') + if purpose == 'RETENTION': + need(registry.phase == 'SEALED', 'retention only after irreversible full source seal') + for row in registry.snapshot()['attempts']: + attempt = registry.attempt(row['label']) + need(not attempt.uncertain, 'uncertain source writer lifetime prevents continuation') + for resource_row in attempt.resources: + never_entered = (purpose == 'CLEANUP' and resource_row['kind'] == 'process' + and resource_row['state'] == 'PENDING' and resource_row['entry_entered'] is False) + need(resource_row['state'] in ('CLOSED','NOT_ENTERED') or never_entered, + 'actual uncertain native entry/wait/FD prevents protected continuation') + if purpose == 'RETENTION': + need(attempt.terminal_written and all(attempt.required.values()), + 'all owning finalizers and original attempt terminal before retention') + return True + + +def finish_joined_attempts(bound,wrapper,queue,root_results,primary): + state = _JOINED_RUN + if state is None: + return + registry = state['registry'] + # Each actual owning component runs its own required finally paths before + # any source seal. C2 never supplies a blanket all-writers Boolean. + rows = registry.snapshot()['attempts'] + for row in rows: + if bound is not None: + bound.finish_case(row['label'],primary) + for module in (wrapper,queue): + module.finalize_completed_source(primary) + for row in registry.snapshot()['attempts']: + attempt = registry.attempt(row['label']) + if not attempt.required['strict']: + need(not IO_UNKNOWN[0], 'unknown C2 strict IO cannot close source') + registry.required_writer_closed(attempt,'strict') + if not attempt.required['serialized-DATA']: + # Only actual returned supervised cleanup or source-owned proved + # never-entered state can establish this delegated writer lifetime. + resources = attempt.resources + need(not attempt.uncertain and all(r['state'] in ('CLOSED','NOT_ENTERED') for r in resources), + 'serialized DATA writer lifetime unresolved') + registry.required_writer_closed(attempt,'serialized-DATA') + status = 'PASS' if primary is None and attempt.label in state['validated_labels'] else 'STOP' + if attempt.error is not None and type(attempt.error) in (KeyboardInterrupt,SystemExit): + status = 'INTERRUPTED' + if attempt.status is None: + registry.finish_attempt(attempt,status,primary) + + +def actual_context_ports(active_module,ctx): + """Fixed safe dispatch consistency; loaded source authentication is external.""" + cls = type(ctx) + need(type(cls) is type, 'ordinary exact private context class') + mro = type.__getattribute__(cls,'__mro__') + need(len(mro) == 2 and mro[0] is cls and mro[1] is object, 'direct private context class') + namespace = type.__getattribute__(cls,'__dict__') + keys = tuple(namespace) + need(all(type(k) is str for k in keys), 'exact context class keys') + image = {k:namespace[k] for k in keys} + methods = ('initialize','refresh_opening','current_binding','begin','native_lease_for_controller', + 'check','release_for_exec','adopt_handoff','publish_reviewed_close','release') + need(set(image) == {'__module__','__doc__','__slots__','__new__'} | set(methods) and + type(image.get('__slots__')) is tuple and image['__slots__'] == () and + type(image['__new__']) is staticmethod and type(image['__new__'].__func__) is FunctionType and + image['__new__'].__func__.__globals__ is active_module.__dict__, 'fixed empty-slotted A2 context layout') + need(all(type(image[name]) is FunctionType and image[name].__globals__ is active_module.__dict__ + for name in methods), 'source-private actual context methods') + def call(name,*args): + current = type.__getattribute__(cls,'__dict__');current_keys = tuple(current) + need(all(type(k) is str for k in current_keys) and set(current_keys) == set(image) and + all(current[k] is image[k] for k in current_keys), 'no context method/special-hook substitution') + now = type.__getattribute__(cls,'__mro__') + need(len(now) == 2 and now[0] is cls and now[1] is object, 'unchanged context ancestry') + return image[name](ctx,*args) # Actual A2 rec() still enforces private identity/role. + return call + + +def run_composed(actual_C, actual_A, supervisor, wrapper, queue, envelope, ctx, whole_body_begin_ns, plan_pin, admission_pin, *, joined=None): + global _JOINED_RUN + started = None # Local diagnostic; never replaces genuine wholeouter START. + lease, queue_lock, keeper = None, None, None + release_owner = None + barrier = ExecutionBarrier() + evidence, initial, facade, plan, initial_packet = None, None, None, None, None + final_custody, root_results, packet_envelope = None, None, None + pins, before, safe_state = None, None, None + clock, queue_span = CaseBudget(), [None, None] + resource_scope_observation = None + bound_consumer, joined_retention = None, None + result, primary, queue_lock_pending = {'status': 'STOP'}, None, False + try: + need(type(actual_C) is ModuleType and actual_C.__dict__ is globals(), 'actual complete selected controller module') + need(all(type(m) is ModuleType for m in (actual_A,supervisor,wrapper,queue,envelope)), 'actual authenticated selected modules') + ctx_call = actual_context_ports(actual_A,ctx) + release_owner = lambda:ctx_call('release') # Fixed actual A2 method, retained before fallible getter. + need(type(_ENVIRONMENT_ASSOCIATION) is dict and _ENVIRONMENT_ASSOCIATION['phase'] == 'OPEN', + 'genuine authenticated parent/profile association owner before science') + started = time.monotonic() + need(type(whole_body_begin_ns) is int and 0 <= whole_body_begin_ns <= time.monotonic_ns(), + 'genuine outer START ns source binding required') + exact_pin(plan_pin); exact_pin(admission_pin) + args = argparse.Namespace(plan=Path(plan_pin['path']),plan_bytes=plan_pin['bytes'],plan_sha256=plan_pin['sha256'], + admission=Path(admission_pin['path']),admission_bytes=admission_pin['bytes'], + admission_sha256=admission_pin['sha256'],source_sha256=None) + need(_JOINED is not None and joined is _JOINED['token'], 'fixed complete joined source binding absent') + for module,name,value,code in _JOINED['image']: + need(module.__dict__[name] is value and getattr(value,'__code__',None) is code, 'joined fixed source function changed') + lease = ctx_call('native_lease_for_controller',actual_C) # A2 native guards, SAME lease, no second acquire. + binding = ctx_call('current_binding') + request = binding['request'] + need(type(request['body_reservation_ns']) is int and 0 < request['body_reservation_ns'] <= 180000000000, + 'complete current outer reservation<=180s, not two independent180s grants') + successor_guard(lease) # Own actual acquire precedes exact history, no inherited lease. + barrier.prepare(lease) # Persistent incomplete-parent marker precedes preflight. + original_start_pin = binding['start']['pre_entry_provenance']['original_start_pin'] + original_start,original_start_observation = read_json(Path(original_start_pin['path']),65536,original_start_pin['mode'],original_start_pin) + need(original_start['schema'] == 'fresh-owner-meter-incomplete-v1' and + type(original_start['start_monotonic_ns']) is int and + original_start['start_monotonic_ns'] == whole_body_begin_ns, + 'genuine original manual START differs; ACTIVE local anchor is not wholeouter start') + # Complete-case180 is retained. One actual enclosing180s command, + # both complete cases, all setup/finalization/tails require a new full bill. + launch = clean_launch() + need(args.plan.parent == ROOT / 'control' and args.admission.parent == ROOT / 'control', + 'plan/admission must be actual frozen round control paths') + plan, plan_pin = read_json(args.plan, 2097152, 0o444, + {'bytes': args.plan_bytes, 'sha256': args.plan_sha256}) + need(plan['schema'] == 'fresh-composed-controller-plan-v1' and plan['queue_name'] == NAME and + plan['root'] == str(ROOT) and plan['operating_TCB_sha256'] == TCB_SHA and + plan['case_clock_premises_sha256'] == CLOCK_PREMISES_SHA, 'exact parent plan differs') + approval, approval_pin = read_json(args.admission, 1048576, 0o444, + {'bytes': args.admission_bytes, 'sha256': args.admission_sha256}) + need(approval['schema'] == 'fresh-composed-controller-admission-v1' and + approval['grants_execution'] is True and approval['plan_sha256'] == plan_pin['sha256'] and + approval['controller_source_sha256'] == plan['controller_source']['sha256'] and + approval['operating_TCB_sha256'] == TCB_SHA and + approval['case_clock_premises_sha256'] == CLOCK_PREMISES_SHA and + approval['closed_registered_writer_scope_admitted'] is True and + approval['no_admin_replacement_or_alias_or_interposition'] is True and + type(approval['complete_case_seconds']) is int and approval['complete_case_seconds'] == 180 and + approval['selected_packet_sha256'] == plan['selected_packet_pin']['sha256'] and + approval['whole_body_bill_sha256'] == plan['whole_body_bill_pin']['sha256'] and + approval['complete_work_review_sha256'] == plan['complete_work_review_pin']['sha256'] and + approval['resource_and_funding_scope_admitted'] is True, + 'separate actual command/profile/funding/closed-world admission absent') + need(original_start['source_sha256'] == plan['outer_meter_source_sha256'], 'actual enclosing meter source binding differs') + args.source_sha256 = plan['controller_source']['sha256'] + IO.read(Path(__file__).absolute(),2097152,0o444,plan['controller_source']) + profile,profile_pin = read_json(Path(plan['derived_role_profile_pin']['path']),1048576,0o444,plan['derived_role_profile_pin']) + need(approval['derived_role_profile_sha256'] == profile_pin['sha256'] and + profile['controller_source_sha256'] == args.source_sha256 and + profile['selected_packet_sha256'] == plan['selected_packet_pin']['sha256'] and + profile['actual_loaded_image_proof'] is False, 'fresh derived C/source/closure role profile absent') + bill = complete_bill(plan,approval,request) + whole_deadline_ns = whole_body_begin_ns + request['body_reservation_ns'] + layout = _JOINED['layout_module'].LayoutSelection(Path(_JOINED['retention']['source_root']),Path(_JOINED['retention']['admin_root']),tuple(_JOINED['retention']['labels'])) + registry = _JOINED['registry_module'].AttemptRegistry(layout,ctx) + issuer = _JOINED['issuer'] + issuer.prepare(supervisor,plan['source_pins']) + issuer.parent_authority.bind_actual_owner(actual_C,actual_A,ctx,lease,registry,_JOINED['guardian'],issuer) + issuer.bind_connected(actual_C,actual_A,ctx,lease,layout,registry,_JOINED['guardian'],_JOINED['retention']) + registry.bind_guardian(_JOINED['guardian'],issuer.guardian_writer_closure) + for module in (supervisor,wrapper,queue): + module.configure_completed_source(layout,registry,_JOINED['guardian']) + queue.bind_full_receiver(full_receiver()) + _JOINED_RUN = dict(layout=layout,registry=registry,issuer=issuer,guardian=_JOINED['guardian'], + whole_begin_ns=whole_body_begin_ns,whole_deadline_ns=whole_deadline_ns,queue_native_ns=[None,None],queue_exited=False, + validated_labels=[],last_observation=None) + joined_budget_checkpoint(bill['remaining_before_queue_ns'], + bill['controller_final_ns']+bill['outer_post_controller_ns']) + need(time.monotonic_ns()+bill['remaining_before_queue_ns'] <= whole_deadline_ns, + 'wholeouter preparation/startup and remaining complete work do not fit') + ctx_call('check',bill['remaining_before_queue_ns'],0) + tcb, tcb_pin = read_json(ROOT / 'control/INDEPENDENT-DATA-OPERATING-TCB-SELECTION-v1.json', 65536, 0o444) + need(tcb_pin['sha256'] == TCB_SHA and tcb['actual_loaded_image_proof'] is False, 'role-bound operating TCB selection changed') + clock_scope, clock_pin = read_json(ROOT / 'control/INDEPENDENT-DATA-CASE-CLOCK-PREMISES-v1.json', + 65536, 0o444, plan['case_clock_premises_pin']) + need(clock_pin['sha256'] == CLOCK_PREMISES_SHA and clock_scope['grants_execution'] is False and + clock_scope['existing_operating_TCB_selection']['sha256'] == TCB_SHA, + 'additive exact clock role premises changed') + for catalog in plan['required_absent_catalogs']: + need(not os.path.lexists(catalog), 'present locale catalog needs separate source review') + evidence = layout.admin_role('C2') + need(not evidence.exists(), 'owning parent evidence already attempted') + for path in plan['fresh_absent_paths']: + need(not os.path.lexists(path), 'declared once-only path already exists') + # Source root is created only by first actual attempt reservation. + evidence.mkdir(mode=0o700,parents=True) + IO.write(evidence / 'GLOBAL-LEASE.json', lease.verify()) + IO.write(evidence / 'LAUNCH.json', {'launch': launch, 'plan': plan_pin, 'external_admission': approval_pin, + 'source_selection_is_conditional_not_native_proof': True}) + actual_stage = stage_check(plan['full_stage_pins']) + need(plan['stage_sha256'] == actual_stage['manifest']['sha256'], 'full bill normal-stage binding') + config, config_pin = read_json(Path(plan['queue_path']), 1048576, 0o444, plan['queue_pin']) + policy, policy_pin = read_json(Path(plan['policy_path']), 65536, 0o444, plan['policy_pin']) + need(config['queue'] == NAME and [x['job'] for x in config['cases']] == ['normal', 'optimized'] and + [x['label'] for x in config['cases']] == [NAME+'N',NAME+'O'] and + all(x == full_receiver().case_for(mode,plan['full_stage_pins'][mode]['sha256']) + for x,mode in zip(config['cases'],('normal','optimized'))) and + policy == {'queue': NAME, 'root_seconds': 180, + 'root_address_space_bytes': 1073741824, 'root_rss_sum_bytes': 1073741824}, 'exact two-root queue/policy differs') + inputs, spec = {}, {} # No serialized-prefix DATA substitutes for full science. + IO.read(Path(full_receiver().__file__),2097152,0o444,plan['full_receiver_pin']) + pins = {} + for path,row in ELIGIBILITY[0].PINS.items(): + add_expectation(pins,path,row) # All exact history remains protected through final custody. + add_expectation(pins,str(ELIGIBILITY_PATH),dict(ELIGIBILITY_PIN,mode=0o444)) + for row in binding['start']['pre_entry_provenance'].values(): + if type(row) is dict and set(row) == {'path','bytes','sha256','mode'}: + add_expectation(pins,row['path'],row) + add_expectation(pins,original_start_observation['path'],original_start_observation) + for source in (plan['source_pins'],): + for path, row in source.items(): + add_expectation(pins, path, row) + for relative, row in actual_stage['files'].items(): + add_expectation(pins, str(STAGE / relative), row) + add_expectation(pins, str(STAGE / 'STAGE.json'), actual_stage['manifest']) + add_expectation(pins, str(args.plan), plan_pin) + add_expectation(pins, str(args.admission), approval_pin) + before = snapshot_domain(pins) + IO.write(evidence / 'PREFLIGHT-CUSTODY.json', {'files': before, 'writers': writer_probe(before), 'stage': actual_stage}) + IO.read(Path(envelope.__file__),2097152,0o444,plan['envelope_pin']) + initial_packet, wrapper_bytes = envelope.snapshot(PACKET, PACKET_SHA, 'run_queue4_subreaper.py') + for module,key,names in ((wrapper,'wrapper_pin',('source_packet',)), + (supervisor,'supervisor_pin',('bind_active_run_root','launch_contract','packet_unchanged')), + (queue,'queue_source_pin',('main','validate')), + (envelope,'envelope_pin',('snapshot',))): + need(all(type(module.__dict__.get(name)) is FunctionType and + module.__dict__[name].__globals__ is module.__dict__ for name in names), + 'actual selected component functions, no copied method attachment') + IO.read(Path(module.__file__),2097152,0o444,plan[key]) + required_sources = {str(Path(__file__).absolute()),str(Path(actual_A.__file__)),str(Path(supervisor.__file__)), + str(Path(wrapper.__file__)),str(Path(queue.__file__)),str(Path(envelope.__file__)),str(supervisor.RUNNER_PATH), + str(ELIGIBILITY_PATH),plan['funding_source_pin']['path']} + for module in (_JOINED['layout_module'],_JOINED['registry_module'],issuer, + issuer.parent_authority,issuer.postrun_hook,issuer.fork_borrower, + issuer.actual_consumer,issuer.native_io): + required_sources.add(str(Path(module.__file__).absolute())) + retention_root = Path(_JOINED['retention']['config_template']['tools_root']) + for leaf in ('archive.py','oracle.py','error_custody.py','plain_boundary.py','reuse_v2.py'): + required_sources.add(str(retention_root / leaf)) + required_sources.add(str(Path(full_receiver().__file__))) + required_sources.add(str(JOINED_ROOT / 'implementation/source/bounded_relay.py')) + required_sources.add(str(JOINED_ROOT / 'implementation/source/run_guarded_v3.py')) + required_sources.add(str(JOINED_ROOT / 'implementation/source/candidate_entry.py')) + required_sources.add(str(Path(_ENVIRONMENT_ASSOCIATION['module'].__file__))) + need(set(plan['selected_sources']) == required_sources and + plan['funding_source_pin']['sha256'] == actual_A.FUNDING_SHA and + approval['active_source_sha256'] == plan['selected_sources'][str(Path(actual_A.__file__))]['sha256'] and + approval['funding_source_sha256'] == plan['funding_source_pin']['sha256'], + 'complete selected actual source-role closure differs; no source-plan hash cycle') + packet_envelope = wrapper.source_packet(actual_C,plan['selected_packet_pin'],plan['selected_sources']) + supervisor.launch_contract() + queue_lock_pending = True + queue_lock = supervisor.parent_lock(ROOT) + queue_lock_pending = False + initial = ctx_call('current_binding') # DATA correlation; actual owner remains private ctx. + need(canonical(initial) == canonical(binding), 'same actual own pending START/head and reservation') + bound_consumer = supervisor.bind_active_run_root(actual_A,actual_C,ctx, + whole_body_begin_ns=whole_body_begin_ns,case_contracts=[{'case':{k:case[k] for k in + ('stage','job','label','stage_sha256')},'validation_allowance_ns':bill['cases'][case['job']]['validation_ns'], + 'body_closing_allowance_ns':bill['cases'][case['job']]['closing_ns']} for case in config['cases']], + layout=layout,registry=registry,guardian=_JOINED['guardian']) + subreaper, keeper = supervisor.install_subreaper(ROOT) + IO.write(evidence / 'PARENT-SUBREAPER.json', subreaper) + need(queue.ROOT == ROOT and queue.subprocess is subprocess, 'original generic queue initial globals differ') + outer_label = supervisor.nested_label(request['label']) + supervision = layout.source + began_queue = time.monotonic() + remaining = sum(sum(row.values()) for row in bill['cases'].values())+bill['controller_final_ns']+bill['outer_post_controller_ns'] + need(time.monotonic_ns()+remaining <= whole_deadline_ns, 'complete two-case work+validation+cleanup+final/tail no longer fits') + ctx_call('check',remaining,0) + deadline = (whole_deadline_ns-bill['outer_post_controller_ns']-bill['controller_final_ns'])/1000000000 + root_results = ActualRootResults(bound_consumer.run_root,clock,bill['cases']) + proxy = wrapper.RootProxy(supervisor,bound_consumer,root_results.run_root,ROOT,config['cases'],supervision,policy,deadline, + layout=layout,registry=registry,guardian=_JOINED['guardian']) + facade = StrictQueueFacade(queue, proxy, lease, supervisor, pins, before, inputs, spec, + plan['full_receiver_pin'], evidence, clock) + try: + native_queue_begin = _JOINED['guardian'].queue_begin() + _JOINED_RUN['queue_native_ns'][0] = native_queue_begin['end_monotonic_ns'] + queue_span[0] = time.monotonic() + try: + queue.main(Path(plan['queue_path']),supervision,supervisor.RUNNER_PATH,facade, + layout=layout,registry=registry,guardian=_JOINED['guardian']) + except BaseException as error: + remember(error) + retain_queue_failure(error,queue) + raise + finally: + _JOINED_RUN['queue_exited'] = True + try: + queue_span[1] = time.monotonic() + native_queue_end = _JOINED['guardian'].queue_end() + _JOINED_RUN['queue_native_ns'][1] = native_queue_end['end_monotonic_ns'] + except BaseException as end_error: + remember(end_error) + # The unmatched endpoint stays None. No zero/clamp or + # completed-outside interval is invented after G loss. + raise + finally: + try: + clock.close() + except BaseException as secondary: + remember(secondary) + need(facade.validated == ['normal', 'optimized'] and proxy.next == 2 and not supervisor.children_now(), + 'actual serial complete full-positive/refusal cleanup order absent') + facade.case_metrics.append(clock.original_metric(config['cases'][-1])) + need(len(facade.case_metrics) == 2, 'both actual original complete-case metrics required') + result = {'schema': 'exact-owned-full-candidate-parent-v1', + 'status': 'OWNED_FULL_CANDIDATE_AND_ORIGINAL_REFUSAL_OBSERVED', + 'actual_stage_sha256': plan['stage_sha256'], + 'full_stage_pins': plan['full_stage_pins'], + 'assertion_on_full_and_optimized_refusal_terminal_observed': True, + 'original_full_scientific_images_unchanged': True, + 'original_embedded_full_control_calls_retained_in_unchanged_images': True, + 'source_campaign_52_helpers_100_commands_executed_here': False, + 'fresh_independent_baseline_transfer_and_comparison_completed_here': False, + 'global_lease_acquired_here': True, + 'runtime_profile_qualification_issued_here': False, + 'execution_permission_created': False, 'financial_close_issued': False, + 'full52_qualified': False, 'full99_qualified': False, 'fullscience': False, 'gain': False, + 'all_costs_settled': False, 'final_parent_exit_and_no_quarantine_required': True, + 'no_universal_whole_parent_hard_timeout_claim': True} + except BaseException as error: + primary = remember(error) + finally: + # All original-domain reads and known accounting stay BEFORE lease.close. + # An uncertain failed Root has no reconstructed domain/capability here. + if queue_lock_pending: + IO_UNKNOWN[0] = True + try: + clock.close() + except BaseException as error: + primary = remember(error) + # Inherited postcustody on success AND known-safe failure, held-FD. + # Separate failures retained; IO ambiguity prohibits all further reads. + custody = {'status': 'UNVERIFIED', 'checks': {}} + try: + safe_state = safe_custody_state(root_results, supervisor, lease) + except BaseException as error: + primary = remember(error) + if safe_state is not None: + if envelope is not None and initial_packet is not None and not IO_UNKNOWN[0]: + try: + after_packet, unused = envelope.snapshot(PACKET, PACKET_SHA, 'run_queue4_subreaper.py') + need(after_packet == initial_packet, 'before/after unchanged packet custody differs') + custody['checks']['envelope'] = after_packet + except BaseException as error: + primary = remember(error) + if supervisor is not None and packet_envelope is not None and not IO_UNKNOWN[0]: + try: + supervisor.packet_unchanged(PACKET, packet_envelope) + custody['checks']['wrapper_packet_unchanged'] = True + except BaseException as error: + primary = remember(error) + if pins is not None and before is not None and not IO_UNKNOWN[0]: + try: + custody['files'] = snapshot_domain(pins) + need(custody['files'] == before, 'final original/source domain custody differs') + custody['writers'] = writer_probe(before) + custody['global_lease'] = lease.verify() + custody['checks']['source_input_config_policy'] = True + except BaseException as error: + primary = remember(error) + if (all(custody['checks'].get(key) is not None for key in + ('envelope', 'wrapper_packet_unchanged', 'source_input_config_policy')) and + not IO_UNKNOWN[0]): + custody['status'] = 'FINAL_CUSTODY_OBSERVED' + final_custody = custody + unsafe_root = safe_state is None + if unsafe_root: + result['final_custody_unverified_external_teardown_required'] = True + if final_custody is None: + result['status'] = 'STOP' + if primary is None: + primary = remember(AdapterStop('final inherited custody unverified')) + # Preserve original dynamic queue390/outside30 scopes alongside whole180. + # This is a local timing guard, never a financial residual or full tail. + try: + sample = time.monotonic() # Genuine local guard observation only. + need(type(sample) is float and math.isfinite(sample), 'actual resource guard endpoint unavailable') + if started is not None: + need(type(started) is float and math.isfinite(started) and sample >= started, + 'actual controller local timing origin differs') + if queue_span[0] is not None and queue_span[1] is not None: + need(all(type(v) is float and math.isfinite(v) for v in queue_span) and + started <= queue_span[0] <= queue_span[1] <= sample, + 'actual ordered queue timing endpoints differ') + queue_seconds = queue_span[1]-queue_span[0] + outside_seconds = (sample-started)-queue_seconds + need(outside_seconds >= 0, 'nonqueue interval unknown; no zero clamp') + resource_scope_observation = {'scope':'controller_local_start_through_guard_sample', + 'start':started,'queue_span':list(queue_span),'sample':sample, + 'queue_seconds':queue_seconds,'outside_seconds':outside_seconds, + 'complete_outer_body':False,'financial_charge':False} + if queue_seconds > 390 or outside_seconds > 30: + primary = remember(AdapterStop('separate queue/outside scope crossed; costs retained')) + elif queue_span[0] is None and queue_span[1] is None: + # Queue was never entered: all known local elapsed is outside. + # None remains None; no zero queue duration/endpoint is invented. + outside_seconds = sample-started + resource_scope_observation = {'scope':'early_failure_before_queue_entry', + 'start':started,'queue_span':list(queue_span),'sample':sample, + 'queue_seconds':None,'outside_seconds':outside_seconds, + 'complete_outer_body':False,'financial_charge':False} + if outside_seconds > 30: + primary = remember(AdapterStop('separate queue/outside scope crossed; costs retained')) + else: + raise AdapterStop('actual queue timing endpoint unknown; no duration invented') + else: + need(FIRST[0] is not None, 'controller local timing origin unavailable') + if queue_span[0] is not None and queue_span[1] is not None: + if time.monotonic_ns()+bill['outer_post_controller_ns'] > whole_deadline_ns: + primary = remember(AdapterStop('wholeouter controller+reserved tail scope crossed; actual costs retained')) + except BaseException as error: + primary = remember(error) # Actual first error survives guard/clock failures. + if FIRST[0] is not None: + primary = FIRST[0] + result['status'] = 'STOP' + if initial is not None and evidence is not None and lease is not None and not IO_UNKNOWN[0]: + try: + observed_ns = time.monotonic_ns() + need(observed_ns >= whole_body_begin_ns, 'genuine partial controller observation endpoint') + known = {'schema':'fresh-composed-controller-observation-v1','status':result['status'], + 'current_binding':initial,'actual_body_begin_ns':whole_body_begin_ns, + 'observed_ns':observed_ns,'partial_elapsed_ns':observed_ns-whole_body_begin_ns, + 'clock_scope':'genuine_outer_START_through_this_sample_before_final_records_seal_release_exit', + 'whole_outer_body_complete':False,'financial_receipt_created':False,'all_costs_settled':False, + 'unsafe_root_cleanup':unsafe_root,'final_original_custody':final_custody, + 'custody_attempts':custody,'actual_cleanup_safety':safe_state,'queue_span':queue_span, + 'resource_scope_observation':resource_scope_observation, + 'complete_case_metrics':None if facade is None else facade.case_metrics, + 'actual_returned_root_records':None if root_results is None else root_results.results, + 'actual_root_entries':None if root_results is None else root_results.entered, + 'root_metadata_is_observation_not_live_ownership_authority':True, + 'errors':error_data(),'held_global_lease_at_observation':lease.verify(), + 'original_domain_reads_end_before_global_release':True,'execution_permission':False} + IO.write(evidence/'ACCOUNTING.json',known) + IO.write(evidence/'PARENT.json',dict(result,errors=error_data(), + schema='fresh-composed-controller-observation-v1',whole_outer_body_complete=False, + known_accounting=False,financial_receipt_created=False,all_costs_settled=False, + final_custody_completed=final_custody is not None,unsafe_root_cleanup=unsafe_root)) + except BaseException as error: + primary = remember(error) + if queue_lock is not None: + try: + queue_lock.close() # Actual retained parent-queue owner, one attempt. + except BaseException as error: + primary = remember(error) + IO_UNKNOWN[0] = True + # The parent association owns its actual observations/descriptors. + # Retire it exactly once before attempt closure or retention seal. + try: + close_environment_association() + except BaseException as error: + primary = remember(error) + # Required original finally/STOP/reconcile work precedes irreversible + # source seal. A known closed scientific STOP still takes retention once. + if _JOINED_RUN is not None: + try: + finish_joined_attempts(bound_consumer,wrapper,queue,root_results,primary) + need(not IO_UNKNOWN[0] and safe_state is not None, + 'unknown writer/FD lifecycle forbids protected retention reads') + joined_budget_checkpoint(bill['outer_post_controller_ns']+bill['controller_final_release_ns']) + joined_retention = _JOINED_RUN['issuer'].completed_boundary(evidence) + result['retention'] = joined_retention + joined_budget_checkpoint(bill['outer_post_controller_ns']+bill['controller_final_release_ns']) + except BaseException as error: + primary = remember(error) + if FIRST[0] is not None: + primary = FIRST[0] + if primary is not None or IO_UNKNOWN[0]: + if barrier.phase in ('PREPARING', 'PREPARED', 'SEALED_SUCCESS'): + barrier.quarantine() + elif barrier.phase == 'PREPARED': + try: + need(joined_retention is not None and joined_retention['status'] == 'PARENT_FULL_READBACK_COMPLETE', 'actual full retention before seal_success') + _JOINED_RUN['issuer'].parent_authority.require_release_ready() + joined_budget_checkpoint(bill['outer_post_controller_ns']+bill['controller_final_release_ns']) + barrier.seal_success() + except BaseException as error: + primary = remember(error) + barrier.quarantine() + try: + need(release_owner is not None, 'private release method unavailable; external actual teardown required') + if _JOINED_RUN is not None: + joined_budget_checkpoint(bill['outer_post_controller_ns']) + if _JOINED_RUN is not None: + _JOINED_RUN['issuer'].require_owner_disposal_ready() + release_owner() # Original actual A2 once-only release point. + if _JOINED_RUN is not None: + joined_budget_checkpoint(bill['outer_post_controller_ns']) + _JOINED_RUN['guardian'].role_closed(os.getpid()) + except BaseException as error: + primary = remember(error) + # Metadata-only activation after close uncertainty; no original reads. + barrier.quarantine() + if _JOINED_RUN is not None: + try: + _JOINED_RUN['guardian'].retire('C2_RELEASE_OR_NATIVE_LIFETIME_UNRESOLVED') + except BaseException as retire_error: + remember(retire_error) + # No original-domain/source reads after actual A2 release. Retained records + # are partial observations only. Real enclosing meter/native completion and + # a separate actual CLOSER/review are required; no financial CLOSE is minted. + return 1 if primary is not None else 0 + + diff --git a/research/h25-parent-waiting-entry/implementation/source/bounded_relay.py b/research/h25-parent-waiting-entry/implementation/source/bounded_relay.py new file mode 100644 index 0000000000..6a52b22183 --- /dev/null +++ b/research/h25-parent-waiting-entry/implementation/source/bounded_relay.py @@ -0,0 +1,322 @@ +# Modified 2026-11-07: Clear1nsight, with OpenAI Codex and ChatGPT Pro assistance. See NOTICE.md. +"""Fair bounded pipe-to-file relay, selected by the authenticated parent loader. + +Only read endpoints are nonblocking. Child stdio writers keep blocking semantics. +Every descriptor has a pre-registered linear owner; uncertain close is never +replayed. EOF is a stream observation, never proof of native writer retirement. +This module is source only until the original separate execution admission. +""" +import hashlib +import os +from pathlib import Path +import select +import stat +import time + +CAP = 2 * 1024 * 1024 +CHUNK = 65536 + + +def need(value, message): + if not value: + raise RuntimeError(message) + + +class RegistryOwner: + """Adapt genuine parent registry FD ownership without creating another owner.""" + def __init__(self, registry, attempt): + self.registry, self.attempt = registry, attempt + self.custody=registry.synchronous_writer(attempt,'relay-raw-custody',attempt.layout.supervision_root/'root.stdout.raw') + self.custody['kind'],self.custody['object']='relay-owner',self + def bind(self,relay): + self.custody['object']=relay # Retain actual relay and raw errors until parent exit. + def retired(self,known): + self.custody['state']='CLOSED' if known else 'UNKNOWN' + def pending(self, role, path=None): + row = self.registry.fd_pending(self.attempt, role) + row['kind'], row['path'] = 'relay-fd', path + return row + def acquired(self, row, fd): + previous=row['state'] + row['object'],row['state']=fd,'OWNED' # Actual native return before validator. + need(previous=='PENDING' and type(fd) is int and fd>=0,'known actual registered relay descriptor') + def failed(self, row, error): + self.registry.fd_unknown(row, error) + def close(self, row): + self.registry.fd_close(row) + def remember(self, error): + self.registry.capture_error(self.attempt, error) + + +class LocalOwner: + """Runner-local raw owners; their terminal projection remains DATA to parent.""" + def __init__(self, state, remember): + self.state, self.remember_error = state, remember + def pending(self, role, path=None): + need(len(self.state['fds']) < 64 and self.state['overflow'] is None and + not any(r['state'] == 'UNKNOWN' for r in self.state['fds']), + 'runner descriptor custody unavailable') + row = {'role':role, 'path':path, 'object':None, 'state':'PENDING', + 'primary':None, 'secondary':None, 'close_attempted':False} + self.state['fds'].append(row) + return row + def bind(self,relay): + self.state['relay']=relay + def retired(self,known): + pass # Actual descriptor rows remain in the runner's strong state. + def acquired(self, row, fd): + previous=row['state'] + row['object'],row['state']=fd,'OWNED' # Actual native return before validator. + need(previous=='PENDING' and type(fd) is int and fd>=0,'one actual runner descriptor return') + def failed(self, row, error): + row['primary'], row['state'] = error, 'UNKNOWN' + self.remember(error) + def close(self, row): + need(row['state'] == 'OWNED' and type(row['object']) is int, + 'one known runner descriptor close') + fd, row['object'], row['state'], row['close_attempted'] = row['object'], None, 'CLOSING', True + try: + os.close(fd) + except BaseException as error: + row['secondary'], row['state'] = error, 'UNKNOWN' + self.remember(error) + raise + row['state'] = 'CLOSED' + def remember(self, error): + self.remember_error(error) + + +class BoundedRelay: + def __init__(self, paths, owner, role): + need(type(paths) is tuple and len(paths) == 2 and + all(type(p) is type(Path('/')) and p.is_absolute() for p in paths), + 'two exact absolute capture paths') + self.owner, self.role, self.rows, self.turn = owner, role, [], 0 + self.primary, self.traceback, self.secondary = None, None, [None] * 16 + self.retired, self.setup_complete = False, False + self.owner.bind(self) + # Allocate stream records BEFORE any native file/pipe operation. + for index, path in enumerate(paths): + self.rows.append({'path':path, 'capture':None, 'reader':None, 'writer':None, + 'pipe_return':None, 'identity':None, 'retained':0, 'observed':0, + 'discarded':0, 'overflow':False, 'eof':False, 'write_uncertain':False, + 'final_bytes':None, 'sha256':hashlib.sha256(), 'index':index}) + def remember(self, error): + if self.primary is None: + self.primary = error + self.traceback = BaseException.__dict__['__traceback__'].__get__(error, BaseException) + elif error is not self.primary: + for index, old in enumerate(self.secondary): + if old is error: + break + if old is None: + self.secondary[index] = error + break + else: + pass # Saturation remains non-successful through the first raw error. + try: + self.owner.remember(error) + except BaseException as secondary: + for index,old in enumerate(self.secondary): + if old is secondary: + break + if old is None: + self.secondary[index]=secondary + break + def open(self, *, capture_fds=None): + need(capture_fds is None or (type(capture_fds) is tuple and capture_fds == (1, 2)), + 'only actual inherited standard captures may be adopted by the entry') + need(not self.setup_complete and not self.retired and self.primary is None, + 'one relay setup') + try: + for row in self.rows: + ticket = self.owner.pending(self.role + '-capture-' + str(row['index']), row['path']) + row['capture'] = ticket + try: + if capture_fds is None: + fd = os.open(row['path'], os.O_WRONLY | os.O_CREAT | os.O_EXCL | + os.O_NOFOLLOW | os.O_CLOEXEC, 0o600) + else: + fd = os.dup(capture_fds[row['index']]) + except BaseException as error: + ticket['primary'] = error + self.owner.failed(ticket, error) + raise + self.owner.acquired(ticket, fd) # Actual handle before fchmod/fstat. + if capture_fds is None: + os.fchmod(fd, 0o600) + info = os.fstat(fd) + need(stat.S_ISREG(info.st_mode) and stat.S_IMODE(info.st_mode) == 0o600 and + info.st_uid == os.getuid() and info.st_nlink == 1 and info.st_size == 0, + 'exclusive owned regular0600 empty capture') + current = row['path'].lstat() + need((info.st_dev, info.st_ino) == (current.st_dev, current.st_ino), + 'actual exclusive capture inode') + row['identity'] = (info.st_dev, info.st_ino) + row['reader'] = self.owner.pending(self.role + '-pipe-read-' + str(row['index'])) + row['writer'] = self.owner.pending(self.role + '-pipe-write-' + str(row['index'])) + try: + pair = os.pipe2(os.O_CLOEXEC) + except BaseException as error: + row['reader']['primary'] = row['writer']['primary'] = error + self.owner.failed(row['reader'], error) + self.owner.failed(row['writer'], error) + raise + row['pipe_return'] = pair # Retain actual pair before any validation. + row['reader']['object'],row['reader']['state']=pair[0],'OWNED' + row['writer']['object'],row['writer']['state']=pair[1],'OWNED' + need(type(pair) is tuple and len(pair)==2 and + all(type(fd) is int and fd>=0 for fd in pair),'actual returned pipe pair') + os.set_blocking(pair[0], False) # Never change the writer's O_NONBLOCK. + need(not os.get_blocking(pair[0]) and os.get_blocking(pair[1]), + 'nonblocking relay reader and blocking child writer') + self.setup_complete = True + return self + except BaseException as error: + self.remember(error) + raise + def writers(self): + need(self.setup_complete and not self.retired and self.primary is None, + 'complete owned relay before launch') + return tuple(row['writer']['object'] for row in self.rows) + def close_writers(self): + first = None + for row in self.rows: + ticket = row['writer'] + if ticket is not None and ticket['state'] == 'OWNED': + try: + self.owner.close(ticket) + except BaseException as error: + self.remember(error) + first = error if first is None else first + if first is not None: + raise first + def overflowed(self): + return any(row['overflow'] for row in self.rows) + def eof_complete(self): + return all(row['eof'] for row in self.rows) + def _write_prefix(self, row, block): + room = CAP - row['retained'] + prefix = block[:room] + position = 0 + while position < len(prefix): + try: + count = os.write(row['capture']['object'], prefix[position:]) + except BaseException: + row['write_uncertain'] = True + raise + need(type(count) is int and 0 < count <= len(prefix) - position, + 'relay partial-write progress and returned count') + row['sha256'].update(prefix[position:position + count]) + position += count + row['retained'] += count + row['discarded'] += len(block) - len(prefix) + if len(block) > len(prefix): + row['overflow'] = True # Exactly CAP bytes alone never signals overflow. + def pump(self, timeout=0.0): + need(self.setup_complete and not self.retired and self.primary is None, + 'relay draining requires known resources') + need(type(timeout) in (int, float) and 0 <= timeout <= 0.05, + 'bounded fair relay wait') + active = [row for row in self.rows if row['reader']['state'] == 'OWNED'] + if not active: + return + try: + ready, _, _ = select.select([row['reader']['object'] for row in active], [], [], timeout) + # One bounded read per ready stream per call; alternate first stream. + ordered = self.rows[self.turn:] + self.rows[:self.turn] + self.turn = (self.turn + 1) % len(self.rows) + for row in ordered: + ticket = row['reader'] + if ticket['state'] != 'OWNED' or ticket['object'] not in ready: + continue + # At the boundary read one extra byte to distinguish overflow. + amount = CHUNK if row['overflow'] else min(CHUNK, max(1, CAP - row['retained'] + 1)) + try: + block = os.read(ticket['object'], amount) + except BlockingIOError: + continue + if not block: + self.owner.close(ticket) + row['eof'] = True + continue + row['observed'] += len(block) + self._write_prefix(row, block) + except BaseException as error: + self.remember(error) + raise + def drain_until(self, deadline): + # Caller must first retire real writers. EOF alone does not retire them. + while not self.eof_complete() and self.primary is None and time.monotonic() < deadline: + self.pump(min(0.01, max(0.0, deadline - time.monotonic()))) + return self.eof_complete() + def retire(self): + """One bounded close pass. No numeric descriptor is retried after failure.""" + need(not self.retired, 'one irreversible relay retirement') + self.retired = True + first = None + for row in self.rows: + for name in ('writer', 'reader', 'capture'): + ticket = row[name] + if ticket is None or ticket['state'] != 'OWNED': + continue + if name == 'capture': + try: + info = os.fstat(ticket['object']) + row['final_bytes'] = info.st_size + need(stat.S_ISREG(info.st_mode) and stat.S_IMODE(info.st_mode) == 0o600 and + info.st_uid == os.getuid() and info.st_nlink == 1 and + (info.st_dev, info.st_ino) == row['identity'] and info.st_size <= CAP, + 'physical capture bound and original owned inode') + named=row['path'].lstat() + need((named.st_dev,named.st_ino,named.st_mode,named.st_uid,named.st_nlink,named.st_size)== + (info.st_dev,info.st_ino,info.st_mode,info.st_uid,info.st_nlink,info.st_size), + 'capture path still names the original relay-only inode') + need(info.st_size == row['retained'] and not row['write_uncertain'], + 'complete known relay write prefix') + os.fsync(ticket['object']) + except BaseException as error: + self.remember(error) + first = error if first is None else first + try: + self.owner.close(ticket) + except BaseException as error: + self.remember(error) + first = error if first is None else first + resources=[row[name] for row in self.rows for name in ('capture','reader','writer') if row[name] is not None] + self.owner.retired(all(row['state'] in ('CLOSED','NOT_ENTERED') for row in resources)) + if first is not None: + raise first + def snapshot(self): + resources = [row[name] for row in self.rows for name in ('capture','reader','writer') + if row[name] is not None] + return {'schema':'joined-bounded-relay-v1', 'cap_bytes_each':CAP, + 'nonblocking_readers_only':True, 'fair_read_quantum_bytes':CHUNK, + 'setup_complete':self.setup_complete, 'retired':self.retired, + 'all_descriptors_known_closed':self.retired and len(resources) == 6 and + all(ticket['state'] == 'CLOSED' for ticket in resources), + 'eof_complete':self.eof_complete(), 'overflow':self.overflowed(), + 'raw_error_present':self.primary is not None, + 'streams':[{'path':str(row['path']), 'bytes':row['retained'], + 'observed_bytes':row['observed'], 'discarded_bytes':row['discarded'], + 'overflow':row['overflow'], 'eof':row['eof'], 'final_bytes':row['final_bytes'], + 'write_uncertain':row['write_uncertain'], 'sha256':row['sha256'].hexdigest()} + for row in self.rows], + 'writer_lifetime_proof':False} + + +def compiler_file_limits(inherited, infinity=-1): + """The existing guardian/archive H=512MiB, preserving lower hard refusal. + + This explicitly reconciles the enclosing2MiB stream soft limit with the + unchanged cold child16MiB prerequisite and original58MiB witness. Only the + relay supplies the2MiB physical stream bound. H is not a complete-tree fit. + """ + cap = 536870912 + need(type(inherited) is tuple and len(inherited) == 2 and + all(type(v) is int and (v >= 0 or v == infinity) for v in inherited), + 'exact inherited FSIZE pair') + soft, hard = inherited + need(hard == infinity or (soft != infinity and soft <= hard), 'ordered inherited FSIZE') + need(hard == infinity or hard >= cap, 'original guardian H hard prerequisite; no owner hard-limit increase') + return cap, cap diff --git a/research/h25-parent-waiting-entry/implementation/source/candidate_entry.py b/research/h25-parent-waiting-entry/implementation/source/candidate_entry.py new file mode 100644 index 0000000000..702ebd2800 --- /dev/null +++ b/research/h25-parent-waiting-entry/implementation/source/candidate_entry.py @@ -0,0 +1,466 @@ +# Modified 2026-11-07: Clear1nsight, with OpenAI Codex and ChatGPT Pro assistance. See NOTICE.md. +#!/usr/bin/env python3 +"""Candidate waiting entry below the unchanged common runner algorithms. + +Source-only until separately admitted. The parent owns qualification and release; +no Context, lease, guardian or parent association is recreated after exec. +LocalOwner is reused verbatim from the existing bounded relay; the bounded WAIT +reader is reused from the recovered common runner. See SOURCE-LINEAGE.json. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import resource +import signal +import stat +import subprocess +import sys +import time +from types import ModuleType + +FLAGS = ('-S','-s','-P','-B') +ENV = {'PATH':'/usr/bin:/bin','PYTHONHASHSEED':'0','LANG':'C.UTF-8', + 'LC_ALL':'C.UTF-8','TZ':'UTC','PYTHONDONTWRITEBYTECODE':'1'} +READ_ROOT = Path('/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/h25-data-handling-20261028') +ERROR_DESTINATION = None +STATE = {'fds':[], 'overflow':None, 'errors':[], 'modules':[], 'first':None, 'traceback':None} + +def need(value,message): + if not value: + raise RuntimeError(message) + +def digest(raw): + return hashlib.sha256(raw).hexdigest() + +def remember(error): + if STATE['first'] is None: + STATE['first'],STATE['traceback']=error,BaseException.__dict__['__traceback__'].__get__(error,BaseException) + if not any(item is error for item in STATE['errors']): + if len(STATE['errors']) < 16: STATE['errors'].append(error) + else: STATE['overflow']=error + +class LocalOwner: + """Runner-local raw owners; their terminal projection remains DATA to parent.""" + def __init__(self, state, remember): + self.state, self.remember_error = state, remember + def pending(self, role, path=None): + need(len(self.state['fds']) < 64 and self.state['overflow'] is None and + not any(r['state'] == 'UNKNOWN' for r in self.state['fds']), + 'runner descriptor custody unavailable') + row = {'role':role, 'path':path, 'object':None, 'state':'PENDING', + 'primary':None, 'secondary':None, 'close_attempted':False} + self.state['fds'].append(row) + return row + def bind(self,relay): + self.state['relay']=relay + def retired(self,known): + pass # Actual descriptor rows remain in the runner's strong state. + def acquired(self, row, fd): + previous=row['state'] + row['object'],row['state']=fd,'OWNED' # Actual native return before validator. + need(previous=='PENDING' and type(fd) is int and fd>=0,'one actual runner descriptor return') + def failed(self, row, error): + row['primary'], row['state'] = error, 'UNKNOWN' + self.remember(error) + def close(self, row): + need(row['state'] == 'OWNED' and type(row['object']) is int, + 'one known runner descriptor close') + fd, row['object'], row['state'], row['close_attempted'] = row['object'], None, 'CLOSING', True + try: + os.close(fd) + except BaseException as error: + row['secondary'], row['state'] = error, 'UNKNOWN' + self.remember(error) + raise + row['state'] = 'CLOSED' + def remember(self, error): + self.remember_error(error) + +def read_waiting_configuration(path, expected_sha): + """Read parent-created DATA, never restore its capability or release a child.""" + path = Path(path) + if (not path.is_absolute() or path.resolve(strict=True) != path or + type(expected_sha) is not str or len(expected_sha) != 64 or + any(c not in '0123456789abcdef' for c in expected_sha)): + raise ValueError('Exact canonical waiting configuration and digest required') + identity = lambda q: (q.st_dev,q.st_ino,q.st_mode,q.st_uid,q.st_nlink,q.st_size,q.st_mtime_ns,q.st_ctime_ns) + before = path.lstat() + if (not stat.S_ISREG(before.st_mode) or stat.S_IMODE(before.st_mode) != 0o444 or + before.st_uid != os.getuid() or before.st_nlink != 1 or not 0 < before.st_size <= 16384): + raise ValueError('Owned immutable bounded waiting configuration required') + fd = None + primary = secondary = None + raw = None + try: + fd = os.open(path,os.O_RDONLY|os.O_NOFOLLOW|os.O_NONBLOCK|os.O_CLOEXEC) + if identity(os.fstat(fd)) != identity(before): + raise ValueError('Waiting configuration opened identity') + blocks, count = [], 0 + while True: + block = os.read(fd,min(65536,before.st_size+1-count)) + if not block: + break + blocks.append(block); count += len(block) + if count > before.st_size: + raise ValueError('Waiting configuration extra byte') + raw = b''.join(blocks) + if (len(raw) != before.st_size or digest(raw) != expected_sha or + identity(os.fstat(fd)) != identity(before) or identity(path.lstat()) != identity(before)): + raise ValueError('Waiting configuration exact stable readback') + except BaseException as error: + primary = error + finally: + if fd is not None: + owned, fd = fd, None + try: + os.close(owned) + except BaseException as error: + secondary = error + if primary is not None: + if secondary is not None: + raise primary from secondary + raise primary + if secondary is not None: + raise secondary + def pairs(items): + result = {} + for key,value in items: + if key in result: + raise ValueError('Duplicate waiting configuration key') + result[key] = value + return result + def no_number(value): + raise ValueError('Waiting configuration forbids floating/nonfinite numbers') + value = json.loads(raw.decode('ascii'),object_pairs_hook=pairs,parse_float=no_number,parse_constant=no_number) + if type(value) is not dict or value.get('schema') != 'h25-waiting-entry-config-v1': + raise ValueError('Exact waiting configuration schema') + return value + + +OWNER = LocalOwner(STATE, remember) + +def opened(path,flags,role,mode=0o600): + row=OWNER.pending(role,path) + try: + fd=os.open(path,flags|os.O_NOFOLLOW|os.O_CLOEXEC,mode) + except BaseException as error: + OWNER.failed(row,error) + raise + OWNER.acquired(row,fd) + return row + +def identity(st): + return (st.st_dev,st.st_ino,st.st_mode,st.st_uid,st.st_nlink,st.st_size,st.st_mtime_ns,st.st_ctime_ns) + +def close_preserving(row,first): + if row is not None and row['state']=='OWNED': + try: OWNER.close(row) + except BaseException as error: + remember(error) + if first is None: first=error + return first + +def read_stable(path,cap,expected=None,mode=None): + path=Path(path);before=path.lstat() + need(path.is_absolute() and path.resolve(strict=True)==path and stat.S_ISREG(before.st_mode) + and before.st_uid in (0,os.getuid()) and before.st_nlink==1 and 0<=before.st_size<=cap + and (mode is None or stat.S_IMODE(before.st_mode)==mode),'bounded canonical selected file') + row=None;first=None;raw=None + try: + row=opened(path,os.O_RDONLY|os.O_NONBLOCK,'entry-read') + need(identity(os.fstat(row['object']))==identity(before),'opened selected inode') + parts=[];count=0 + while True: + block=os.read(row['object'],min(65536,cap+1-count)) + if not block: break + parts.append(block);count+=len(block) + need(count<=cap,'complete bounded file read') + raw=b''.join(parts) + need(identity(os.fstat(row['object']))==identity(path.lstat())==identity(before), + 'stable complete descriptor and path read') + if expected is not None: + need(len(raw)==expected['bytes'] and digest(raw)==expected['sha256'],'exact selected bytes') + except BaseException as error: + first=error;remember(error) + finally: first=close_preserving(row,first) + if first is not None: raise first + return raw + +def json_read(path,cap=16384,expected=None,mode=0o444): + raw=read_stable(path,cap,expected,mode) + def pairs(items): + result={} + for key,value in items: + need(key not in result,'duplicate record key');result[key]=value + return result + def number(unused): raise ValueError('record floats/nonfinite forbidden') + value=json.loads(raw.decode('ascii'),object_pairs_hook=pairs,parse_float=number,parse_constant=number) + need(type(value) is dict,'exact record object') + return value,raw + +def immutable_write(path,value): + raw=(json.dumps(value,sort_keys=True,separators=(',',':'),allow_nan=False)+'\n').encode('ascii') + need(len(raw)<=16384,'entry record bound') + row=None;first=None + try: + row=opened(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL,'entry-record') + view=memoryview(raw) + while view: + count=os.write(row['object'],view);need(type(count) is int and count>0,'record write progress');view=view[count:] + os.fchmod(row['object'],0o444);os.fsync(row['object']) + except BaseException as error: + first=error;remember(error) + finally: first=close_preserving(row,first) + if first is not None: raise first + directory=None + try: + directory=opened(Path(path).parent,os.O_RDONLY|os.O_DIRECTORY,'entry-record-directory') + os.fsync(directory['object']) + except BaseException as error: + first=error;remember(error) + finally: first=close_preserving(directory,first) + if first is not None: raise first + return {'path':str(path),'bytes':len(raw),'sha256':digest(raw)} + +def process_row(pid): + row=opened(Path('/proc')/str(pid)/'stat',os.O_RDONLY,'entry-proc-read');first=None;raw=None + try: + raw=os.read(row['object'],8193);need(len(raw)<=8192 and b') ' in raw,'bounded actual generation') + except BaseException as error: first=error;remember(error) + finally: first=close_preserving(row,first) + if first is not None: raise first + fields=raw[raw.rfind(b') ')+2:].split() + return {'pid':pid,'ppid':int(fields[1]),'start_ticks':int(fields[19]),'state':fields[0].decode('ascii')} + +def key(row): return [row['pid'],row['start_ticks']] + +def load_source(pin): + need(type(pin) is dict and set(pin)=={'path','bytes','sha256','mode'} and pin['mode']==0o444, + 'selected source module pin') + raw=read_stable(Path(pin['path']),262144,pin,0o444) + module=ModuleType('_entry_'+Path(pin['path']).stem);module.__file__=pin['path'] + STATE['modules'].append(module) + exec(compile(raw,pin['path'],'exec'),module.__dict__,module.__dict__) + return module + +def inherited_holders(folder): + """Snapshot only stdio and the possible GNU-time usage alias; reject others.""" + info=(folder/'usage.json').stat();usage_key=(info.st_dev,info.st_ino) + rows=[];directory_key=(Path('/proc/self/fd').stat().st_dev,Path('/proc/self/fd').stat().st_ino) + iterator=os.scandir('/proc/self/fd');first=None;scan_holders=0 + try: + names=set() + for item in iterator: + if not item.name.isdecimal(): continue + fd=int(item.name);names.add(fd) + need(len(names)<=16,'finite exact inherited descriptor table') + # Inspect while scandir still owns its FD. Exhausting it first + # would close that very descriptor before its fstat. + st=os.fstat(fd) + if stat.S_ISDIR(st.st_mode) and (st.st_dev,st.st_ino)==directory_key: + scan_holders+=1;continue + if fd==0: + null=os.stat('/dev/null');need(stat.S_ISCHR(st.st_mode) and st.st_rdev==null.st_rdev,'admitted inherited stdin') + elif fd in (1,2): + path=folder/('stdout.txt' if fd==1 else 'stderr.txt');named=path.lstat() + need(stat.S_ISREG(st.st_mode) and identity(st)==identity(named) and st.st_size==0 + and stat.S_IMODE(st.st_mode)==0o600,'actual empty inherited common capture') + else: + need(stat.S_ISREG(st.st_mode) and (st.st_dev,st.st_ino)==usage_key, + 'only outer GNU-time usage alias may also survive exec') + ticket=OWNER.pending('entry-inherited-'+str(fd));OWNER.acquired(ticket,fd) + rows.append(ticket) + need(scan_holders==1 and {0,1,2}.issubset({r['object'] for r in rows}),'one known fd-census iterator') + except BaseException as error: first=error;remember(error) + finally: + try: iterator.close() + except BaseException as error: + remember(error);first=error if first is None else first + if first is not None: raise first + return rows + +def native_argv(profile,timed,stage,artifact,usage,config): + read_stable(Path(config['native_source_path']),262144,{'bytes':Path(config['native_source_path']).stat().st_size, + 'sha256':profile['source_sha256']},0o444) + for kind in ('entry','time'): + read_stable(Path(profile[kind+'_path']),16777216,{'bytes':profile[kind+'_bytes'],'sha256':profile[kind+'_sha256']}) + info=artifact.lstat() + need(artifact.resolve(strict=True)==artifact and stat.S_ISDIR(info.st_mode) and stat.S_IMODE(info.st_mode)==0o700 + and info.st_uid==os.getuid() and not list(artifact.iterdir()),'owned empty native artifact parent') + return [profile['entry_path'],'--entry-image',profile['entry_path'],profile['entry_sha256'],str(profile['entry_bytes']), + '--time-image',profile['time_path'],profile['time_sha256'],str(profile['time_bytes']), + '--read-root',str(READ_ROOT),'--artifact-parent',str(artifact),str(info.st_dev),str(info.st_ino), + '--science-leaf','science','--usage',str(timed[4]),str(usage[0]),str(usage[1]),'--',*timed] + +def main(): + global ERROR_DESTINATION + parser=argparse.ArgumentParser();parser.add_argument('--output',required=True);parser.add_argument('--lanes',required=True) + parser.add_argument('--waiting-config',required=True);parser.add_argument('--waiting-sha256',required=True);args=parser.parse_args() + need(dict(os.environ)==ENV and sys.flags.no_site==sys.flags.no_user_site==sys.flags.dont_write_bytecode==1 + and sys.flags.safe_path and not sys.flags.isolated and not sys.flags.ignore_environment + and not sys.flags.hash_randomization and sys.executable=='/usr/bin/python3.12','original clean entry launch') + config=read_waiting_configuration(args.waiting_config,args.waiting_sha256) + case=Path(config['completed_layout']['case_container']);folder=case/'runner';stage=Path(config['stage_path']) + need(config['outer_output']==args.output==config['completed_layout']['science_root'] and args.lanes=='candidate' + and Path(args.waiting_config)==case/'supervision/WAIT.json','exact source-selected waiting paths') + ERROR_DESTINATION=case/'supervision/ENTRY-ERROR.json' + own=process_row(os.getpid());timer=process_row(own['ppid']);root=process_row(timer['ppid']);parent=process_row(root['ppid']) + need(key(parent)==config['parent'] and sys.flags.optimize==(1 if config['job']=='optimized' else 0),'actual parent and original interpreter mode') + own_raw=read_stable(Path(__file__),262144,{'bytes':config['entry_bytes'],'sha256':config['entry_sha256']},0o444) + aliases=inherited_holders(folder) + arrival={'schema':'h25-entry-arrived-v1','case_id':config['case_id'],'waiting_sha256':args.waiting_sha256, + 'entry':key(own),'timer':key(timer),'runner':key(root),'parent':key(parent),'entry_sha256':digest(own_raw)} + arrival_pin=immutable_write(case/'supervision/ARRIVED.json',arrival) + os.kill(os.getpid(),signal.SIGSTOP) + # File presence never releases this entry: only return from the actual stop, + # followed by the parent's exact known-closed seal and intent, permits exec. + need(time.monotonic_ns()=65536: + raise RuntimeError('runner native wait unresolved; no retry') + state['wait_state']='UNRESOLVED';state['wait_calls']+=1 + try: + actual=os.waitpid(process.pid,os.WNOHANG) + state['raw_wait']=actual # Actual tuple BEFORE comparison/decoder. + if type(actual) is not tuple or len(actual)!=2 or any(type(v) is not int for v in actual): + raise RuntimeError('runner native wait tuple') + if actual==(0,0): + state['wait_state']='SAFE_NONTERMINAL' + return None + if actual[0]!=process.pid: + raise RuntimeError('runner waited actual child differs') + state['wait_state']='CONSUMED' + code=os.waitstatus_to_exitcode(actual[1]) + if type(code) is not int: + raise RuntimeError('runner wait decoder') + process.returncode=code + state['wait_known']=True;state['wait_state']='COMMITTED' + return code + except BaseException as error: + state['wait_error']=error + state['wait_state']='UNRESOLVED' + _remember_runner(error) + raise + +def _wait_child(process,relay=None,deadline=None): + if deadline is None: + deadline=time.monotonic()+2.0 + while True: + code=_poll_child(process) + if code is not None: + return code + if time.monotonic()>=deadline: + raise RuntimeError('runner reserved native cleanup wait exhausted') + if relay is not None and relay.primary is None: + relay.pump(0.01) + else: + time.sleep(0.01) + +if __name__=='__main__': + try: code=main() + except BaseException as error: + remember(error) + try: + frames=[];tb=STATE['traceback'] + while tb is not None and len(frames)<16: + frames.append({'source':tb.tb_frame.f_code.co_filename,'line':tb.tb_lineno});tb=tb.tb_next + if ERROR_DESTINATION is not None: + immutable_write(ERROR_DESTINATION,{'schema':'h25-entry-envelope-error-v1','error_type':'opaque-caught-exception','frames':frames}) + except BaseException as secondary: remember(secondary) + code=125 # Envelope failure can never masquerade as the original exit-1 refusal. + raise SystemExit(code) diff --git a/research/h25-parent-waiting-entry/implementation/source/composed_queue.py b/research/h25-parent-waiting-entry/implementation/source/composed_queue.py new file mode 100644 index 0000000000..aec28e09ac --- /dev/null +++ b/research/h25-parent-waiting-entry/implementation/source/composed_queue.py @@ -0,0 +1,312 @@ +# Modified 2026-11-07: Clear1nsight, with OpenAI Codex and ChatGPT Pro assistance. See NOTICE.md. +"""Parent-owned serial queue derivative for the fresh composed route. + +Actual runner receipts and retained logs are checked before the next case. +The explicit trusted transport retains native process authority. Nested metrics +are diagnostics inside one enclosing body, never additive ledger records. +No scientific module is imported here. No automatic retry. +""" +import hashlib +import json +import os +import resource +from pathlib import Path +import subprocess +import sys +import time + +ROOT = Path('/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/h25-data-handling-20261028') + + +STAGE_BASE = Path('/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/caller-proof-completion-20261107T0155Z/implementation/bindings/stages') +CONFIG_BASE = Path('/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/caller-proof-completion-20261107T0155Z/implementation/bindings/control') +# This is a trusted parent launch contract, not Python self-authentication or -I. +# -P suppresses unsafe path insertion; -S/-s prevent site and user-site loading. +# Unlike -I, this preserves the explicitly whitelisted fixed hash seed. +LAUNCH_FLAGS = ('-S', '-s', '-P', '-B') +LAUNCH_ENV = {'PATH': '/usr/bin:/bin', 'PYTHONHASHSEED': '0', + 'LANG': 'C.UTF-8', 'LC_ALL': 'C.UTF-8', 'TZ': 'UTC', + 'PYTHONDONTWRITEBYTECODE': '1'} + + +def require_trusted_launch(): + if not (sys.flags.no_site == 1 and sys.flags.no_user_site == 1 and + sys.flags.safe_path and sys.flags.dont_write_bytecode == 1 and + sys.flags.ignore_environment == 0 and sys.flags.isolated == 0 and + sys.flags.hash_randomization == 0): + raise ValueError('Explicit no-site/safe-path parent launch required') + if dict(os.environ) != LAUNCH_ENV: + raise ValueError('Exact clean parent environment required') + if sys.executable != '/usr/bin/python3.12': + raise ValueError('Absolute admitted interpreter required') + if tuple(sys.path) != ('/usr/lib/python312.zip', '/usr/lib/python3.12', + '/usr/lib/python3.12/lib-dynload'): + raise ValueError('Unadmitted ordered initial Python search path') + return {'contract': 'trusted-clean-nosite-safe-path-fixedseed-v1', + 'no_site': sys.flags.no_site, 'no_user_site': sys.flags.no_user_site, + 'safe_path': bool(sys.flags.safe_path), + 'ignore_environment': sys.flags.ignore_environment, + 'isolated': sys.flags.isolated, 'hash_seed_environment': '0', + 'hash_randomization': sys.flags.hash_randomization, + 'initial_sys_path': list(sys.path), 'environment': dict(os.environ), + 'trust_boundary': 'Authenticated parent launcher, OS, interpreter and system stdlib before this module; no Python self-authentication claim'} + + +def need(value, message): + if not value: + raise ValueError(message) + + + +_COMPLETED = None +_FULL_RECEIVER = None + + +def bind_full_receiver(module): + global _FULL_RECEIVER + need(_FULL_RECEIVER is None and module is not None, 'one authenticated actual full receiver') + _FULL_RECEIVER = module + return True + + +def configure_completed_source(layout, registry, guardian): + global _COMPLETED + need(_COMPLETED is None and registry.layout is layout and guardian is not None, + 'one actual complete-source binding before producers') + _COMPLETED = (layout, registry, guardian) + return True + +def completed_source(): + need(_COMPLETED is not None, 'actual complete-source binding required') + return _COMPLETED + +def digest(path): + h = hashlib.sha256() + count = 0 + with path.open('rb') as stream: + for block in iter(lambda: stream.read(65536), b''): + h.update(block) + count += len(block) + return h.hexdigest(), count + + +def _write_admin(path,value,registry): + raw=(json.dumps(value,indent=2,sort_keys=True)+'\n').encode('ascii') + if len(raw)>4194304: + raise ValueError('bounded queue admin metadata') + fd,primary,secondary,traceback=None,None,None,None + try: + fd=os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW|os.O_CLOEXEC,0o600) + position=0 + while position0,'queue admin complete write') + position+=count + os.fsync(fd) + except BaseException as error: + primary=error + traceback=BaseException.__dict__['__traceback__'].__get__(error,BaseException) + registry.remember(error) + finally: + if fd is not None: + closing_fd,fd=fd,None + try: + os.close(closing_fd) + except BaseException as error: + secondary=error + registry.quarantine(error) + if primary is not None: + raise BaseException.with_traceback(primary,traceback) + if secondary is not None: + raise secondary + + +def record_time(path): + row = json.loads(path.read_bytes()) + return row.get('runner_wall_seconds', row['wall_seconds']) + + +def validate(case, nested_root, runner_path): + stage = STAGE_BASE / case['stage'] + stage_hash, _ = digest(stage / 'STAGE.json') + need(stage_hash == case['stage_sha256'], 'Reviewed stage changed') + declared = json.loads((stage / 'STAGE.json').read_bytes()) + layout,registry,guardian = completed_source() + attempt = registry.attempt(case['label']) + registry.assert_open(attempt) + folder = attempt.layout.runner_root + receipt = json.loads((folder / 'receipt.json').read_bytes()) + common='integration/candidate_entry.py' in declared['files'] + need(not common or case['job']=='normal','positive queue validator cannot accept optimized STOP') + start = json.loads((folder / 'START.json').read_bytes()) + for key, value in start.items(): + need(receipt.get(key) == value, 'START differs from receipt: ' + key) + need(receipt['stage_sha256'] == stage_hash, 'Receipt stage differs') + need(receipt['runner_sha256'] == declared['runner_sha256'] == digest(runner_path)[0], 'Runner identity differs') + need(receipt['parent_launch'] == require_trusted_launch(), 'Parent launch provenance differs') + if not common: + need(receipt['funding_intent_sha256'] == digest(attempt.layout.intent_path)[0] and + receipt['outer_label'] == nested_root.name and receipt['nested_is_not_registry_charge'] is True, + 'Exact enclosing ACTIVE intent DATA provenance differs') + need(_FULL_RECEIVER is not None and receipt['command'] == + _FULL_RECEIVER.command_for(stage,declared,case['job'],_FULL_RECEIVER.job_for(case['job']),attempt.layout.science_root), + 'Exact adopted full Root/provider/scientific command differs') + else: + entry=json.loads((folder/'ENTRY.json').read_bytes()) + need(entry['inner_command']==_FULL_RECEIVER.command_for(stage,declared,case['job'], + _FULL_RECEIVER.job_for(case['job']),attempt.layout.science_root), + 'common entry retains the exact original inner scientific command') + need(receipt['fractions_sha256'] == digest(Path('/usr/lib/python3.12/fractions.py'))[0], 'Actual Fraction source differs') + need(receipt['label'] == case['label'] and receipt['job'] == case['job'], 'Receipt case differs') + need(receipt['status'] == 'PASS' and receipt['exit'] == (1 if case['job'] == 'optimized' else 0) and + receipt['termination'] is None, 'Actual runner terminal disposition differs') + need(receipt['source_bytes_and_modes_unchanged'] is True and receipt['retained_log_bytes_stable'] is True, 'Custody or logs changed') + need(receipt['log_read_chunk_bytes'] == 65536, 'Bounded log reader differs') + for stream in ('stdout', 'stderr'): + observed, count = digest(folder / (stream + '.txt')) + need(observed == receipt[stream + '_sha256'], 'Raw log digest differs') + need(count == receipt[stream + '_bytes'] == receipt[stream + '_final_bytes'], 'Raw log byte count differs') + need(count <= 2097152, 'Ordinary raw log cap exceeded') + need((receipt['stderr_bytes'] == 0) if case['job'] == 'normal' else + (receipt['stderr_bytes'] > 0), 'Original full/refusal stderr disposition differs') + need(receipt['runner_wall_seconds'] >= receipt['wall_seconds'] >= 0, 'Runner time scope differs') + usage = receipt['usage'] + usage_fields_available = (type(usage) is dict and + all(key in usage and type(usage[key]) in (int,float) + for key in ('user_seconds','system_seconds','kernel_max_rss_kib'))) + science_status = ('FULL_NETWORK_COMPLETE_PASS' if case['job'] == 'normal' else + 'ORIGINAL_OPTIMIZED_FULL_ENTRY_REFUSAL_OBSERVED') + return {'label': case['label'], 'job': case['job'], 'stage': case['stage'], + 'gate': 'PASS_RETAINED_RECEIPT', 'science_status': science_status, + 'runner_wall_seconds': receipt['runner_wall_seconds'], 'child_wall_seconds': receipt['wall_seconds'], + 'cpu_seconds': (usage['user_seconds'] + usage['system_seconds']) if usage_fields_available else None, + 'usage_fields_available': usage_fields_available, + 'runner_cpu_seconds_before_own_receipt': receipt['runner_user_seconds'] + receipt['runner_system_seconds'], + 'kernel_max_rss_kib': usage['kernel_max_rss_kib'] if usage_fields_available else None, + 'sampled_process_group_rss_bytes': receipt['sampled_process_group_rss_bytes']} + + +def main(config_path, nested_root, runner_path, transport, *, layout=None, registry=None, guardian=None): + if _COMPLETED is None: + configure_completed_source(layout,registry,guardian) + layout,registry,guardian = completed_source() + require_trusted_launch() + begin = time.monotonic() + usage_start = (resource.getrusage(resource.RUSAGE_SELF), resource.getrusage(resource.RUSAGE_CHILDREN)) + own_raw = Path(__file__).read_bytes() + name = 'unadmitted' + raw = None + rows, failure = [], None + first_error = None + actual_attempt = None + try: + need(type(config_path) is type(ROOT) and type(nested_root) is type(ROOT) and + type(runner_path) is type(ROOT), 'Exact concrete queue paths required') + need(config_path.resolve(strict=True) == config_path, 'Canonical frozen queue config required') + need(config_path.is_relative_to(CONFIG_BASE), 'Queue config must be new-round control source') + raw = config_path.read_bytes() + spec = json.loads(raw) + proposed = spec['queue'] + need(type(proposed) is str and proposed.isalnum(), 'Simple unique queue identity required') + evidence = layout.admin_role('queue') / proposed + need(not evidence.exists(), 'Queue already attempted; no automatic retry') + need(not (layout.admin_role('queue') / (proposed+'-QUEUE.json')).exists(), 'Queue observation already exists') + name = proposed + layout.admin_role('queue').mkdir(mode=0o700,exist_ok=True) + evidence.mkdir(mode=0o700) + for case in spec['cases']: + actual_attempt = registry.reserve_actual_attempt(case['label']) + for key in ('stage','job','label'): + need(type(case[key]) is str and case[key] and + all(c.isalnum() or c in '-_' for c in case[key]), 'Unsafe queue case identity') + need(digest(STAGE_BASE / case['stage'] / 'STAGE.json')[0] == case['stage_sha256'], + 'Admitted stage differs before queue') + command = ['/usr/bin/python3.12', *LAUNCH_FLAGS, str(runner_path), case['stage'], case['job'], case['label']] + case_begin = time.monotonic() + case_usage = (resource.getrusage(resource.RUSAGE_SELF), resource.getrusage(resource.RUSAGE_CHILDREN)) + result = transport.run(command, cwd=ROOT, env=dict(LAUNCH_ENV), capture_output=True, timeout=190) + registry.write_bytes(actual_attempt,'queue-stdout',actual_attempt.layout.queue_root / (case['label'] + '.stdout'),result.stdout) + registry.write_bytes(actual_attempt,'queue-stderr',actual_attempt.layout.queue_root / (case['label'] + '.stderr'),result.stderr) + need(result.returncode == (1 if case['job']=='optimized' else 0) and not result.stderr, + 'actual common runner terminal code differs: '+case['label']) + row = transport.validate(case) + row.update(transport.primary(case)) + rows.append(row) + registry.write_json(actual_attempt,'queue-gate',actual_attempt.layout.queue_root / (case['label'] + '.gate.json'),row) + registry.required_writer_closed(actual_attempt,'queue') + actual_attempt = None + print(json.dumps(row, sort_keys=True), flush=True) + need(config_path.read_bytes() == raw and Path(__file__).read_bytes() == own_raw, 'Queue config or consumer changed') + except BaseException as error: + first_error = error # Direct actual object before helper or projection. + try: + registry.remember(error) + except BaseException: + pass + failure = {'type':'opaque-caught-exception','message':'projection_unavailable'} + finally: + finalizer_errors = [None] * 8 + if actual_attempt is not None and actual_attempt.status is None: + try: + registry.write_json(actual_attempt,'queue-terminal',actual_attempt.layout.queue_root / 'QUEUE-STOP.json', + {'schema':'h25-actual-queue-case-stop-v1','status':'INTERRUPTED' if type(first_error) in (KeyboardInterrupt,SystemExit) else 'STOP', + 'error_type':None if first_error is None else 'opaque-caught-exception', + 'canonical_runner_receipt_created':False}) + registry.required_writer_closed(actual_attempt,'queue') + except BaseException as error: + finalizer_errors[0] = error + usage_end, elapsed = None,None + try: + usage_end = (resource.getrusage(resource.RUSAGE_SELF), resource.getrusage(resource.RUSAGE_CHILDREN)) + except BaseException as error: + finalizer_errors[1] = error + try: + elapsed = time.monotonic() - begin + except BaseException as error: + finalizer_errors[2] = error + for error in finalizer_errors: + if error is not None: + if first_error is None: + first_error = error + try: + registry.remember(error) + except BaseException: + pass + try: + result = {'status':'STOP' if first_error is not None else 'PASS_REVIEWED_QUEUE', + 'queue':name,'controls':rows,'failure':failure, + 'nested_metrics_not_additive_charges':True,'financial_receipt_created':False, + 'complete_queue_seconds_before_own_receipt':elapsed, + 'parent_self_cpu_seconds_before_own_receipt':None if usage_end is None else (usage_end[0].ru_utime+usage_end[0].ru_stime)-(usage_start[0].ru_utime+usage_start[0].ru_stime), + 'all_child_cpu_seconds_before_own_receipt':None if usage_end is None else (usage_end[1].ru_utime+usage_end[1].ru_stime)-(usage_start[1].ru_utime+usage_start[1].ru_stime), + 'complete_cpu_seconds_before_own_receipt':None if usage_end is None else sum((b.ru_utime+b.ru_stime)-(a.ru_utime+a.ru_stime) for a,b in zip(usage_start,usage_end)), + 'queue_own_receipt_tail_excluded':True,'all_raw_outputs_retained':first_error is None, + 'config_sha256':None if raw is None else hashlib.sha256(raw).hexdigest(), + 'consumer_sha256':hashlib.sha256(own_raw).hexdigest()} + destination = layout.admin_role('queue') / (name+'-QUEUE.json') + _write_admin(destination,result,registry) + except BaseException as error: + finalizer_errors[3] = error + if first_error is None: + first_error = error + try: + registry.remember(error) + except BaseException: + pass + if first_error is not None: + raise first_error + + +def finalize_completed_source(error=None): + layout,registry,guardian = completed_source() + for item in registry.snapshot()['attempts']: + attempt = registry.attempt(item['label']) + if attempt.status is not None or attempt.required['queue'] is True: + continue + registry.prepare_finalizer_dirs(attempt) + if error is not None: + registry.capture_error(attempt,error) + registry.write_json(attempt,'queue-finalizer',attempt.layout.queue_root/'QUEUE-FINALIZER.json',{ + 'schema':'h25-queue-finalizer-stop-v1','label':attempt.label,'status':'STOP', + 'canonical_runner_receipt_created':False,'raw_original_error_held':attempt.error is not None}) + registry.required_writer_closed(attempt,'queue') diff --git a/research/h25-parent-waiting-entry/implementation/source/fresh_supervisor.py b/research/h25-parent-waiting-entry/implementation/source/fresh_supervisor.py new file mode 100644 index 0000000000..f80ceec9f1 --- /dev/null +++ b/research/h25-parent-waiting-entry/implementation/source/fresh_supervisor.py @@ -0,0 +1,2160 @@ +# Modified 2026-11-07: Clear1nsight, with OpenAI Codex and ChatGPT Pro assistance. See NOTICE.md. +"""Parent-only bounded process supervision; imports no candidate implementation. + +The runtime caller must establish the trusted clean launcher before calling us. +This source was prepared without loading ctypes or running any control. The +closed single-threaded child domain is an explicit premise, not a hostile-fork +sandbox. Numeric process IDs are never used as signal destinations. +""" +import fcntl +import hashlib +import json +import os +from pathlib import Path +import resource +import signal +import stat +import subprocess +import sys +import time +from types import ModuleType, FunctionType, MethodType, GetSetDescriptorType + +ROOT = Path('/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/h25-data-handling-20261028') + +STAGE_BASE = Path('/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/caller-proof-completion-20261107T0155Z/implementation/bindings/stages') +CONFIG_BASE = Path('/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/caller-proof-completion-20261107T0155Z/implementation/bindings/control') +NESTED_BASE = ROOT / 'runtime/fresh-metered-round-v1/nested-runs' +RUNNER_PATH = Path('/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/caller-proof-completion-20261107T0155Z/implementation/source/fresh_runner.py') +_BOUND_CONTEXTS = {} + +FLAGS = ('-S', '-s', '-P', '-B') +ENV = {'PATH': '/usr/bin:/bin', 'PYTHONHASHSEED': '0', 'LANG': 'C.UTF-8', + 'LC_ALL': 'C.UTF-8', 'TZ': 'UTC', 'PYTHONDONTWRITEBYTECODE': '1'} +RUNNER_SHA = '682f530cd83a3a8c01c14d21f6321177a6472e795c1ca423aad238dffad458f9' +QUEUE_SHA = '3dc44e957b2aaa4807ec0735ae6ac77b58563bf9db00db4f5495077544e8305c' +TCB_SHA = '610492b3fc06baa0560175edc3ba27057de00d00b8fd3d58dbe55e5a371c042a' +LIBC = '/usr/lib/x86_64-linux-gnu/libc.so.6' +NATIVE_PINS = { + LIBC: '3a15d66867d83762c7f2f1e37359cb8f6c5743edb369c65285cb0b1c4f7498bf', + '/usr/lib/python3.12/lib-dynload/_ctypes.cpython-312-x86_64-linux-gnu.so': 'aad3e24f186e6c0a1c7efa8f16004f951f527db86f6451d30118657384a456c1', + '/usr/lib/x86_64-linux-gnu/libffi.so.8.1.4': '00f593fe192f2851b8ce23b25cec2488d769beb5a8f63e8c9e563071e1075153', + '/usr/lib/python3.12/ctypes/__init__.py': '0782592567ad71097198a3afe985ac3e2ea0b9b5e75452402c9460c89a86318a', + '/usr/lib/python3.12/ctypes/_endian.py': 'c5d692bdce10dfee242752620061bab684633bc72445a3def484961ef1bdbf3a', +} +CHUNK = 65536 +LOG_CAP = 2 * 1024 * 1024 +META_CAP = 256 * 1024 +CLEANUP_SECONDS = 2.0 + + +def need(condition, message): + if not condition: + raise RuntimeError(message) + + +def root_address_space_limits(inherited, requested_bytes, infinity=-1): + """Preserve the enclosing hard cap and every lower inherited Root bound. + + requested_bytes remains the original admitted upper bound. C2's selected + lower hard limit cannot legally be raised by its unprivileged child. + """ + need(type(requested_bytes) is int and 0 < requested_bytes <= 1024 ** 3, + 'original admitted Root AS upper bound') + need(type(inherited) is tuple and len(inherited) == 2 and + all(type(value) is int and (value >= 0 or value == infinity) for value in inherited), + 'exact inherited Root AS limits') + soft, hard = inherited + need(hard == infinity or (soft != infinity and soft <= hard), 'ordered inherited Root AS limits') + hard = requested_bytes if hard == infinity else min(hard, requested_bytes) + soft = hard if soft == infinity else min(soft, hard) + return soft, hard + + + +_COMPLETED = None + +_JOINED = None +_JOINED_STATE = 'UNENTERED' +_QUERY_JOINED = None +_SUPERVISOR_IO = {'rows':[],'unknown':False} +SOURCE_BASE = Path(__file__).absolute().parent + + +def configure_joined_runtime(relay_module, relay_pin, native_entry_profile_template, *, association, full_receiver, full_receiver_pin, query_receiver=None, query_receiver_pin=None, query_profile=None, common_runner_pin=None, waiting_entry_pin=None): + """Actual authenticated private modules/profile, before any producer exists. + + These checks corroborate the parent's selection. Runtime image/kernel/object + compatibility is supplied by that genuine boundary, never a DATA boolean. + """ + global _JOINED,_JOINED_STATE,_QUERY_JOINED,_COMMON,RUNNER_PATH,RUNNER_SHA + need(_JOINED_STATE=='UNENTERED' and not _SUPERVISOR_IO['unknown'],'one monotone joined source binding entry') + _JOINED_STATE='ENTERED' + need(_JOINED is None and type(relay_module) is ModuleType and type(full_receiver) is ModuleType, + 'one genuine joined module/profile binding') + for module,pin,leaf in ((relay_module,relay_pin,'bounded_relay.py'), + (full_receiver,full_receiver_pin,'full_result_receiver.py')): + need(type(pin) is dict and set(pin)=={'path','bytes','sha256','mode'} and + pin['path']==str(SOURCE_BASE/leaf) and pin['mode']==0o444 and + type(pin['bytes']) is int and 0 0, 'Metadata write made no progress') + view = view[written:] + os.fsync(fd) + finally: + os.close(fd) + + +def proc(pid): + try: + with open('/proc/' + str(pid) + '/stat', 'rb') as stream: + raw = stream.read(8193) + need(len(raw) <= 8192, 'Unexpected process-stat size') + end = raw.rfind(b') ') + need(end >= 0, 'Malformed process stat') + fields = raw[end + 2:].split() + return {'pid': int(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')} + except (FileNotFoundError, ProcessLookupError, PermissionError): + return None + + +def census(): + found = {} + with os.scandir('/proc') as entries: + for entry in entries: + if entry.name.isdecimal(): + row = proc(int(entry.name)) + if row is not None: + found[row['pid']] = row + return found + + +def generation(row): + return row['pid'], row['start_ticks'] + + +def children_now(): + return [row for row in census().values() if row['ppid'] == os.getpid()] + + +def install_subreaper(root): + """Called only by the future parent, before any controlled root exists.""" + launch_contract() + need(not children_now(), 'Parent must own no preexisting child processes') + tcb, tcb_row = read_json(root / 'control/NATIVE-INITIAL-TCB-v1.json') + need(tcb_row['sha256'] == TCB_SHA, 'Accepted initial TCB changed') + need(any(row['path'] == LIBC and row['sha256'] == NATIVE_PINS[LIBC] + for row in tcb['files']), 'Pinned libc absent from accepted TCB') + evidence = {path: stable_file(path, 16 * 1024 * 1024) for path in NATIVE_PINS} + need(all(evidence[path]['sha256'] == expected for path, expected in NATIVE_PINS.items()), + 'Subreaper native/stdlib source supplement changed') + # This import and native call have NOT been performed during source authoring. + need(Path('/usr/lib/x86_64-linux-gnu/libffi.so.8').resolve() == + Path('/usr/lib/x86_64-linux-gnu/libffi.so.8.1.4'), 'Foreign libffi SONAME resolution') + import ctypes + need(sys.modules['_ctypes'].__file__ == + '/usr/lib/python3.12/lib-dynload/_ctypes.cpython-312-x86_64-linux-gnu.so', 'Foreign _ctypes owner') + need(ctypes.__file__ == '/usr/lib/python3.12/ctypes/__init__.py', 'Foreign ctypes owner') + library = ctypes.CDLL(LIBC, use_errno=True) + call = library.prctl + call.argtypes = [ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong] + call.restype = ctypes.c_int + prior, actual = ctypes.c_int(), ctypes.c_int() + need(call(37, ctypes.addressof(prior), 0, 0, 0) == 0, 'PR_GET_CHILD_SUBREAPER failed') + need(call(36, 1, 0, 0, 0) == 0, 'PR_SET_CHILD_SUBREAPER failed') + need(call(37, ctypes.addressof(actual), 0, 0, 0) == 0 and actual.value == 1, + 'Same-process subreaper readback failed') + for path, expected in NATIVE_PINS.items(): + need(stable_file(path, 16 * 1024 * 1024)['sha256'] == expected, 'TCB bytes changed across load') + # Retain the CDLL and typed function in the owning parent for its whole queue. + return {'pid': os.getpid(), 'prior': prior.value, 'actual': actual.value, + 'tcb_sha256': TCB_SHA, 'native_source_evidence': evidence, + 'trust': 'Trusted OS/loader/initial system stdlib; file pins do not authenticate native memory'}, (library, call) + + + + + +def parent_lock(root): + lock = (root / 'runtime/parent-queue.lock').open('a') + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BaseException: + lock.close() + raise + return lock + + +class ExecutionDeadline(RuntimeError): + pass + + +def deadline_handler(signum, frame): + raise ExecutionDeadline('Outer execution deadline reached, including Popen/preexec') + + +class DeadlineOwner: + """One absolute SIGALRM owner, retained through caller validation. + + A nested query may only shorten an existing deadline. Pop restores its + remaining absolute interval; neither a query nor cleanup starts a new case. + """ + def __init__(self, absolute_end_ns): + need(type(absolute_end_ns) is int and absolute_end_ns > time.monotonic_ns(), + 'future fixed whole-case deadline') + self.end_ns, self.stack, self.started, self.finished = absolute_end_ns, [], False, False + self.old_handler = None + self.poisoned = False + def _expired(self, signum, frame): + self.poisoned = True + left = self.end_ns-time.monotonic_ns() + signal.setitimer(signal.ITIMER_REAL,max(.000001,left/1e9)) + raise ExecutionDeadline('Working deadline expired; only reserved retirement remains') + def _arm(self): + end = min([self.end_ns] + [row[1] for row in self.stack]) + left = end - time.monotonic_ns() + if left <= 0: + self._expired(signal.SIGALRM,None) + signal.setitimer(signal.ITIMER_REAL, max(.000001, left / 1e9)) + def start(self): + need(not self.started and not self.finished and signal.getitimer(signal.ITIMER_REAL) == (0.0,0.0), + 'sole monotone timer owner') + self.old_handler = signal.getsignal(signal.SIGALRM) + self.started = True + signal.signal(signal.SIGALRM, self._expired) + self._arm() + def push(self, end_ns): + need(self.started and not self.finished and not self.poisoned and type(end_ns) is int and + time.monotonic_ns() < end_ns <= self.end_ns, 'bounded nested absolute deadline') + token = object() + self.stack.append((token, end_ns)) + self._arm() + return token + def pop(self, token): + need(self.started and not self.finished and self.stack and self.stack[-1][0] is token, + 'same LIFO deadline token') + self.stack.pop() + self._arm() + def checkpoint(self): + need(self.started and not self.finished and not self.poisoned and time.monotonic_ns() < + min([self.end_ns] + [row[1] for row in self.stack]), 'absolute active deadline') + def finish(self): + need(self.started and not self.finished, 'one timer retirement') + self.finished = True # Never retry an uncertain timer/handler operation. + first, tb = None, None + try: + signal.setitimer(signal.ITIMER_REAL, 0) + except BaseException as error: + first, tb = error, BaseException.__dict__['__traceback__'].__get__(error,BaseException) + try: + signal.signal(signal.SIGALRM, self.old_handler) + except BaseException as error: + if first is None: + first, tb = error, BaseException.__dict__['__traceback__'].__get__(error,BaseException) + if first is not None: + raise BaseException.with_traceback(first,tb) + + +def pop_deadline_preserving(owner, token, primary, remember): + """Retain a timer-unwind failure after an already captured working error.""" + try: + owner.pop(token) + except BaseException as error: + remember(error) + if primary is None: + raise + + +def direct_children_exact(all_rows): + # The kernel child list prevents an unreadable direct child from vanishing + # merely because a /proc census could not decode its stat file. + path = Path('/proc/self/task') / str(os.getpid()) / 'children' + with path.open('rb') as stream: + raw = stream.read(16385) + need(len(raw) <= 16384, 'bounded direct-child identity census') + pids = [int(word) for word in raw.split()] + need(len(pids) <= 128 and len(set(pids)) == len(pids), 'finite distinct direct children') + rows = [] + for pid in pids: + current = proc(pid) + need(current is not None and current['ppid'] == os.getpid(), + 'direct child generation remains observable') + all_rows[pid] = current + rows.append(current) + return rows + + +class ProtectedRoot: + """Actual waiting R/time/entry generations held by the enclosing domain. + + The caller constructs this only after genuine Popen/registry/guardian birth. + Query owners borrow the exclusion set, never these pidfds or the EX owner. + """ + def __init__(self, registry, attempt, domain, process, entry, arrival_pin, waiting_pin): + need(domain.registry is registry and domain.attempt is attempt and + domain.root == (process.pid, proc(process.pid)['start_ticks']), + 'same actual registered R generation') + self.registry, self.attempt, self.domain, self.process = registry, attempt, domain, process + rows = census() + root = rows.get(process.pid) + timer = rows.get(entry['ppid']) + need(root is not None and timer is not None and timer['ppid'] == root['pid'] and + entry['ppid'] == timer['pid'] and generation(rows.get(entry['pid'], {})) == generation(entry), + 'actual common R -> GNU time -> waiting entry chain') + self.keys = tuple(generation(row) for row in (root,timer,entry)) + need(len(set(self.keys)) == 3, 'three distinct held generations') + self.entry_key, self.runner_key = self.keys[-1], self.keys[0] + self.arrival_pin, self.waiting_pin = dict(arrival_pin), dict(waiting_pin) + self.release_entered, self.released = False, False + for row in (root,timer,entry): + domain.add(row) + need(generation(row) in domain.fds, 'known pidfd for each protected generation') + self.verify() + def verify(self, query=None): + need(not self.release_entered, 'protected exclusion exists only before one release') + rows = census() + for index,key in enumerate(self.keys): + row = proc(key[0]) + need(row is not None and generation(row) == key and row['state'] != 'Z' and + key in self.domain.fds and self.domain.fd_tokens[key]['state'] == 'OWNED', + 'live protected generation and actual known pidfd') + rows[key[0]] = row + need(row['ppid'] == (os.getpid() if index == 0 else self.keys[index-1][0]), + 'unchanged protected parent chain') + entry = rows[self.entry_key[0]] + need(entry['state'] in ('T','t') and + sorted(p.name for p in (Path('/proc')/str(entry['pid'])/'task').iterdir()) == [str(entry['pid'])], + 'genuine stopped single-task waiting entry') + pids = {key[0] for key in self.keys} + need(all(generation(row) in self.keys for row in rows.values() if row['ppid'] in pids), + 'no unregistered protected descendant or pre-release scientific birth') + allowed = set(self.keys) + if query is not None: + need(query.protected is self, 'actual query-domain exclusion owner') + allowed.update(query.rows) + need(all(generation(row) in allowed for row in direct_children_exact(rows)), + 'unknown direct child/orphan is uncertainty, never an excluded query') + return [rows[key[0]] for key in self.keys] + def release(self, intent_pin, writer, seal_pin, seal_writer): + # Check an actual registry resource, not a supplied True or JSON token. + need(any(item is writer for item in self.attempt.resources) and + writer['attempt'] is self.attempt and writer['kind'] == 'writer-permit' and + writer['role'] == 'intent' and writer['path'] == self.attempt.layout.intent_path and + writer['state'] == 'CLOSED' and writer['primary'] is None and + self.attempt.required['intent'] is True and not self.attempt.uncertain, + 'actual completed immutable intent writer and known registry closure') + need(type(intent_pin) is dict and intent_pin.get('path') == str(self.attempt.layout.intent_path) and + type(intent_pin.get('bytes')) is int and 0 < intent_pin['bytes'] <= 16384, + 'actual independently read-back intent pin') + need(any(r is seal_writer for r in self.attempt.resources) and seal_writer['state']=='CLOSED' + and seal_writer['primary'] is None and seal_writer['path']==self.attempt.layout.supervision_root/'RELEASE.json', + 'actual known-closed release-seal writer') + for path,pin in ((self.attempt.layout.intent_path,intent_pin), + (self.attempt.layout.supervision_root/'RELEASE.json',seal_pin)): + observed=stable_file(path,16384) + need(observed['bytes']==pin['bytes'] and observed['sha256']==pin['sha256'], + 'final exact immutable intent and release readback') + self.verify() + self.release_entered = True # No second signal after an uncertain native return. + try: + signal.pidfd_send_signal(self.domain.fds[self.entry_key], signal.SIGCONT, None, 0) + except BaseException as error: + self.registry.capture_error(self.attempt,error) + self.registry.mark_uncertain(self.attempt,'waiting-entry release result uncertain') + raise + self.released = True + + +class OwnedDomain: + """Only our new children and their observed descendants enter this domain.""" + def __init__(self, registry, attempt, protected=None): + self.protected = protected + self.registry,self.attempt,self.fd_tokens = registry,attempt,{} + self.raw_first,self.raw_secondary = None,[None]*16 + if protected is None: + need(not direct_children_exact(census()), 'Owned child domain was not initially empty') + else: + protected.verify() + self.rows, self.fds, self.groups, self.reaped = {}, {}, set(), [] + self.root = None + self.parent_group = os.getpgrp() + self.parent_session = os.getsid(0) + + def add(self, row): + key = generation(row) + if key in self.rows: + if row['pgid'] != self.parent_group: + self.groups.add((row['pgid'], row['sid'])) + return + need(len(self.rows) < 128, 'Owned process observation limit exceeded') + need(row['pid'] != os.getpid(), 'Parent cannot enter its own child domain') + ticket = self.registry.fd_pending(self.attempt,'owned-generation-pidfd') + try: + fd = os.pidfd_open(row['pid'], 0) + except ProcessLookupError: + self.registry.fd_not_entered(ticket) + return + except BaseException as error: + self.raw_first = error if self.raw_first is None else self.raw_first + self.registry.fd_unknown(ticket,error) + raise + self.registry.fd_acquired(ticket,fd) + ticket['native_generation'] = list(key) + self.fd_tokens[key] = ticket # Actual returned holder before fallible observation. + current = proc(row['pid']) + if current is None or generation(current) != key: + self.fd_tokens.pop(key) + self.registry.fd_close(ticket) + return + self.rows[key], self.fds[key] = dict(current), fd + # During interrupted Popen a child can briefly precede setsid. Its + # individual pidfd is owned; the queue parent group never is. + if current['pgid'] != self.parent_group: + self.groups.add((current['pgid'], current['sid'])) + + def observe(self): + all_rows = census() + known = {pid for pid, start in self.rows if pid in all_rows and + all_rows[pid]['start_ticks'] == start} + for pid in known: + self.add(all_rows[pid]) + changed = True + while changed: + changed = False + for pid, row in all_rows.items(): + if pid not in known and (row['ppid'] in known or + (self.protected is None and row['ppid'] == os.getpid())): + self.add(row) + if generation(row) in self.rows: + known.add(pid) + changed = True + if self.protected is not None: + self.protected.verify(self) + return all_rows, [all_rows[pid] for pid in known] + + def kill_owned(self): + self.observe() + for key, fd in self.fds.items(): + current = proc(key[0]) + if current is not None and generation(current) == key and current['state'] != 'Z': + try: + signal.pidfd_send_signal(fd, signal.SIGKILL, None, 0) + except ProcessLookupError: + pass + + def _cleanup_body(self, process, absolute_deadline=None): + start = time.monotonic() + seen_after_root = [] + completed = False + while True: + _, current = self.observe() + if process is not None and process.returncode is not None: + seen_after_root.extend(generation(row) for row in current if row['pid'] != process.pid) + self.kill_owned() + if process is not None: + self.registry.poll_root(process) + for key in list(self.rows): + row = proc(key[0]) + if row is None or generation(row) != key or row['ppid'] != os.getpid(): + continue + if process is not None and row['pid'] == process.pid: + continue + try: + pid, status = os.waitpid(row['pid'], os.WNOHANG) + except ChildProcessError: + continue + if pid: + self.reaped.append({'pid': pid, 'start_ticks': key[1], 'wait_status': status}) + all_rows, current = self.observe() + occupied = [row for row in all_rows.values() if (row['pgid'], row['sid']) in self.groups] + direct = direct_children_exact(all_rows) + extras = [row for row in direct if self.protected is None or generation(row) not in self.protected.keys] + if not current and not occupied and not extras: + completed = True + break + if time.monotonic() - start >= CLEANUP_SECONDS or (absolute_deadline is not None and time.monotonic()>=absolute_deadline): + break + time.sleep(0.01) + final_rows = census() + remaining = [row for row in final_rows.values() if + generation(row) in self.rows or (row['pgid'], row['sid']) in self.groups or + (row['ppid'] == os.getpid() and + (self.protected is None or generation(row) not in self.protected.keys))] + return {'complete': completed and not remaining, + 'owned_generations': list(self.rows.values()), + 'groups': [{'pgid': g, 'sid': s} for g, s in sorted(self.groups)], + 'reaped_adopted': self.reaped, + 'observed_after_root_exit': [list(key) for key in sorted(set(seen_after_root))], + 'remaining': remaining, 'cleanup_seconds': time.monotonic() - start, + 'cleanup_tail_limit_seconds': CLEANUP_SECONDS, + 'group_empty_proved': completed and not remaining, + 'signal_method': 'SIGKILL via generation-checked pidfd only; never killpg'} + + def close_known_fds(self): + first = None + for index,key in enumerate(tuple(self.fd_tokens)): + ticket = self.fd_tokens.pop(key) # Retire owner before close, never replay a number. + self.fds.pop(key,None) + if ticket['state'] != 'OWNED': + continue + try: + self.registry.fd_close(ticket) + except BaseException as error: + if first is None: + first = error + if index < len(self.raw_secondary): + self.raw_secondary[index] = error + if first is not None: + raise first + def cleanup(self, process, absolute_deadline=None): + result,primary,traceback = None,None,None + try: + result = self._cleanup_body(process,absolute_deadline) + except BaseException as error: + primary = error + traceback = BaseException.__dict__['__traceback__'].__get__(error,BaseException) + self.raw_first = error if self.raw_first is None else self.raw_first + self.registry.capture_error(self.attempt,error) + finally: + try: + self.close_known_fds() + except BaseException as error: + if primary is None: + primary = error + traceback = BaseException.__dict__['__traceback__'].__get__(error,BaseException) + self.registry.capture_error(self.attempt,error) + if primary is not None: + raise BaseException.with_traceback(primary,traceback) + return result + + + + + + + + + + + +def nested_plain(value, depth=0): + if depth > 16: + raise ValueError('nested intent depth') + kind = type(value) + if kind is dict: + if len(value) > 64: + raise ValueError('nested intent object cap') + for key,item in value.items(): + if type(key) is not str or len(key) > 128: + raise ValueError('nested intent exact string key') + nested_plain(item,depth+1) + elif kind is list: + if len(value) > 128: + raise ValueError('nested intent list cap') + for item in value: + nested_plain(item,depth+1) + elif kind is str: + if len(value) > 2048: + raise ValueError('nested intent string cap') + elif kind is int: + if not 0 <= value <= 9223372036854775807: + raise ValueError('nested intent integer bound') + elif value is not None and kind is not bool: + raise ValueError('nested intent exact builtin DATA') + + +def nested_label(value): + if (type(value) is not str or not 1 <= len(value) <= 64 or + any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_' for c in value)): + raise ValueError('nested simple label') + return value + + + +def validate_completed_layout(value): + fields = {'source_root','case_container','runner_root','artifact_parent','science_root','external_root','intent_path','attempt_identity'} + if type(value) is not dict or set(value) != fields or any(type(value[k]) is not str for k in fields): + raise ValueError('exact complete prospective layout DATA') + source = Path('/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/caller-proof-completion-20261107T0155Z/runtime/completed-source/IndependentPrefixDATAComposedV1') + case = source / value['case_container'].split('/')[-1] + if case.name not in ('IndependentPrefixDATAComposedV1N','IndependentPrefixDATAComposedV1O'): + raise ValueError('fixed completed source label') + expected = {'source_root':str(source),'case_container':str(case),'runner_root':str(case/'runner'), + 'artifact_parent':str(case/'runner/artifact'),'science_root':str(case/'runner/artifact/science'),'external_root':str(case/'serialized-DATA'), + 'intent_path':str(case/'intent/INTENT.json'),'attempt_identity':value['attempt_identity']} + if value != expected or not 0 < len(value['attempt_identity']) <= 256: + raise ValueError('complete prospective path inverse') + return value + +def validate_nested_intent(value): + nested_plain(value) + keys = {'schema','round_id','outer_label','stage','job','label','stage_sha256','runner_sha256', + 'parent_pid','parent_start_ticks','whole_body_begin_ns','whole_body_deadline_ns', + 'body_reservation_ns','nested_allowance_ns','validation_allowance_ns','cleanup_allowance_ns', + 'active_binding','native_capability','execution_permission','completed_layout', + 'relay_pin','full_receiver_pin','native_entry_profile','association_record','common_rendezvous'} + if type(value) is not dict or set(value) != keys: + raise ValueError('exact nested intent schema') + if (value['schema'] != 'fresh-active-nested-runner-intent-v3' or + value['round_id'] != 'fresh-metered-round-v1' or + value['native_capability'] is not False or value['execution_permission'] is not False): + raise ValueError('nested intent is DATA only') + for key in ('outer_label','stage','job','label'): + nested_label(value[key]) + for key in ('stage_sha256','runner_sha256'): + sha = value[key] + if type(sha) is not str or len(sha) != 64 or any(c not in '0123456789abcdef' for c in sha): + raise ValueError('nested source digest') + for key in ('parent_pid','parent_start_ticks','whole_body_begin_ns','whole_body_deadline_ns', + 'body_reservation_ns','nested_allowance_ns','validation_allowance_ns','cleanup_allowance_ns'): + if type(value[key]) is not int or value[key] < 0: + raise ValueError('nested exact nonnegative integer') + if (value['parent_pid'] == 0 or not 0 < value['body_reservation_ns'] <= 180000000000 or + not 0 < value['nested_allowance_ns'] <= 180000000000 or + value['validation_allowance_ns'] <= 0 or value['cleanup_allowance_ns'] < 2000000000 or + value['whole_body_deadline_ns']-value['whole_body_begin_ns'] != value['body_reservation_ns'] or + value['nested_allowance_ns']+value['validation_allowance_ns']+value['cleanup_allowance_ns'] > value['body_reservation_ns']): + raise ValueError('nested whole-body necessary allowance') + binding = value['active_binding'] + if (type(binding) is not dict or binding.get('schema') != 'fresh-active-current-binding-v1' or + set(binding) != {'schema','request','start','start_pin','head_pin','baseline_registry_pin', + 'native_capability','execution_permission'} or + binding['native_capability'] is not False or binding['execution_permission'] is not False): + raise ValueError('exact source-private current binding observation') + request, start = binding['request'], binding['start'] + if (type(request) is not dict or type(start) is not dict or + request.get('label') != value['outer_label'] or start.get('label') != value['outer_label'] or + type(request.get('body_reservation_ns')) is not int or + request['body_reservation_ns'] != value['body_reservation_ns'] or + start.get('command_sha256') != request.get('command_sha256') or + start.get('body_reservation_ns') != request['body_reservation_ns']): + raise ValueError('nested current reservation DATA correlation') + rendezvous = value['common_rendezvous'] + need(type(rendezvous) is dict and set(rendezvous) == {'entry','runner','arrival_sha256','waiting_sha256'} and + all(type(rendezvous[k]) is list and len(rendezvous[k]) == 2 and + all(type(v) is int and v > 0 for v in rendezvous[k]) for k in ('entry','runner')) and + all(type(rendezvous[k]) is str and len(rendezvous[k]) == 64 and + all(c in '0123456789abcdef' for c in rendezvous[k]) for k in ('arrival_sha256','waiting_sha256')), + 'exact generation-bound waiting rendezvous correlation DATA') + validate_completed_layout(value['completed_layout']) + if Path(value['completed_layout']['case_container']).name != value['label']: + raise ValueError('intent case identity inverse') + return value + + +def seconds_ceiling_ns(value): + need(type(value) in (int,float) and value > 0, 'positive native timing value') + numerator,denominator = value.as_integer_ratio() if type(value) is float else (value,1) + return (numerator*1000000000+denominator-1)//denominator + + +def same_data(actual, expected): + need(type(actual) is type(expected), 'exact source declaration type') + if type(expected) is dict: + need(all(type(k) is str for k in actual) and set(actual) == set(expected), 'exact source declaration keys') + for key in expected: + same_data(actual[key],expected[key]) + elif type(expected) is list: + need(len(actual) == len(expected), 'exact source declaration list') + for first,second in zip(actual,expected): + same_data(first,second) + else: + need(type(expected) in (str,int,bool,type(None)) and actual == expected, 'exact source declaration value') + + +def bounded_stop_reason(value): + # Reject foreign containers/keys before iteration, hashing or JSON callbacks. + pending, nodes, text = [(value,0)],0,0 + while pending: + item,depth = pending.pop(); nodes += 1 + need(nodes <= 512 and depth <= 16, 'bounded STOP reason tree') + kind = type(item) + if kind is dict: + need(len(item) <= 64 and all(type(k) is str and len(k) <= 128 for k in item), + 'exact bounded STOP reason keys') + text += sum(len(k) for k in item) + pending.extend((v,depth+1) for v in item.values()) + elif kind is list: + need(len(item) <= 128, 'bounded STOP reason list') + pending.extend((v,depth+1) for v in item) + elif kind is str: + need(len(item) <= 2048, 'bounded STOP reason string'); text += len(item) + elif kind is int: + need(0 <= item <= 9223372036854775807, 'bounded STOP reason integer') + else: + need(item is None or kind is bool, 'exact builtin STOP reason DATA') + need(text <= 16384 and len(pending) <= 512, 'bounded STOP reason bytes/nodes') + return value + + +class PropertyQueryCustody: + """One registry container retaining the existing relay's linear FD owners. + + Grouping does not erase FD lifetimes: every native return, once-only close, + raw primary and secondary remains in this actual container until the seal. + """ + def __init__(self, registry, attempt, relay_module): + self.registry, self.attempt = registry, attempt + self.state = {'fds': [], 'overflow': None, 'relay': None} + self.first, self.secondary = None, [None] * 32 + self.ticket = registry._resource(attempt, 'property-query-custody', 'property-query-custody') + self.ticket['object'], self.ticket['state'] = self, 'OWNED' + self.owner = relay_module.LocalOwner(self.state, self.remember) + self.identities = {} + + def remember(self, error): + if self.first is None: + self.first = error + elif error is not self.first: + for index, previous in enumerate(self.secondary): + if previous is error: + break + if previous is None: + self.secondary[index] = error + break + else: + if self.state['overflow'] is None: + self.state['overflow'] = error + self.registry.capture_error(self.attempt, error) + + def open(self, role, path, flags, *, mode=0o600, expected=None, directory=False, null=False): + ticket = self.owner.pending(role, path) + try: + fd = os.open(path, flags | os.O_CLOEXEC | os.O_NOFOLLOW, mode) + except BaseException as error: + ticket['primary'] = error + self.owner.failed(ticket, error) + raise + self.owner.acquired(ticket, fd) + try: + info = os.fstat(fd) + if directory: + need(stat.S_ISDIR(info.st_mode), 'held actual query cwd directory') + elif null: + need(stat.S_ISCHR(info.st_mode) and info.st_rdev == os.makedev(1, 3), 'genuine query /dev/null') + else: + need(stat.S_ISREG(info.st_mode), 'regular query evidence/program descriptor') + if expected is not None: + need(info.st_size == expected['bytes'] and stat.S_IMODE(info.st_mode) == expected['mode'], + 'selected actual query image size/mode') + h, count = hashlib.sha256(), 0 + while count < info.st_size: + block = os.read(fd, min(CHUNK, info.st_size - count)) + need(bool(block), 'complete selected query image read') + count += len(block); h.update(block) + need(h.hexdigest() == expected['sha256'] and identity(info) == identity(os.fstat(fd)), + 'selected actual query image byte identity') + os.lseek(fd, 0, os.SEEK_SET) + elif flags & os.O_CREAT: + need(info.st_uid == os.getuid() and stat.S_IMODE(info.st_mode) == 0o600 and + info.st_nlink == 1 and info.st_size == 0, 'exclusive empty owned query evidence') + self.identities[str(path)] = identity(info) + return ticket + except BaseException as error: + ticket['primary'] = error + self.remember(error) + raise + + def write(self, ticket, raw): + need(type(raw) is bytes and ticket['state'] == 'OWNED', 'known query write owner') + try: + offset = 0 + while offset < len(raw): + count = os.write(ticket['object'], memoryview(raw)[offset:offset + CHUNK]) + need(type(count) is int and 0 < count <= min(CHUNK, len(raw) - offset), 'query write progress') + offset += count + os.fsync(ticket['object']) + os.lseek(ticket['object'], 0, os.SEEK_SET) + except BaseException as error: + ticket['primary'] = error + self.remember(error) + raise + + def close(self, ticket): + try: + self.owner.close(ticket) + except BaseException as error: + self.remember(error) + raise + + def close_all(self): + first = None + for ticket in self.state['fds']: + if ticket['state'] == 'OWNED': + try: + self.close(ticket) + except BaseException as error: + first = error if first is None else first + if first is not None: + raise first + + def readback(self, path, cap, expected_identity=None): + ticket = self.open('query-independent-readback', path, os.O_RDONLY) + first, raw, pin = None, None, None + try: + fd = ticket['object']; info = os.fstat(fd) + need(info.st_size <= cap and stat.S_IMODE(info.st_mode) == 0o600 and info.st_nlink == 1 and + info.st_uid == os.getuid(), 'bounded retained query readback object') + if expected_identity is not None: + need(identity(info)[:3] == tuple(expected_identity[:3]), 'same exclusive query evidence inode/mode') + blocks, count, h = [], 0, hashlib.sha256() + while count <= cap: + block = os.read(fd, min(CHUNK, cap + 1 - count)) + if not block: + break + count += len(block); need(count <= cap, 'query readback cap+1 refusal') + blocks.append(block); h.update(block) + need(count == info.st_size and identity(info) == identity(os.fstat(fd)) == identity(path.lstat()), + 'complete stable actual query readback') + raw = b''.join(blocks) + pin = {'path': str(path), 'bytes': count, 'sha256': h.hexdigest(), 'identity': list(identity(info))} + except BaseException as error: + first = error + ticket['primary'] = error + self.remember(error) + finally: + try: + self.close(ticket) + except BaseException as error: + first = error if first is None else first + if first is not None: + raise first + return pin, raw + + def snapshot(self): + rows = self.state['fds'] + return {'all_closed': all(r['state'] in ('CLOSED', 'NOT_ENTERED') for r in rows), + 'raw_error_present': self.first is not None or self.state['overflow'] is not None, + 'descriptors': [{'role': r['role'], 'path': None if r['path'] is None else str(r['path']), + 'state': r['state'], 'close_attempted': r['close_attempted'], + 'primary_present': r['primary'] is not None, 'secondary_present': r['secondary'] is not None} + for r in rows]} + + +def owns_property_query_runner(bound, association): + """Actual private instance lineage; no callable or DATA compatibility adapter.""" + for state in _BOUND_CONTEXTS.values(): + if state.get('bound_consumer') is not bound or state.get('association') is not association: + continue + method = getattr(bound, 'run_property_query') + fn, code = state['property_query_method'] + need(type(method) is MethodType and method.__self__ is bound and method.__func__ is fn and + fn.__code__ is code and fn.__globals__ is globals() and + type.__getattribute__(type(bound), '__dict__').get('run_property_query') is fn and + state['owner_pid'] == os.getpid() and state['context'] is not None and + state['failed'] is False, 'actual unchanged query runner/context lineage') + return True + return False + + +def bind_active_run_root(active_module, kernel_module, active_context, *, whole_body_begin_ns, case_contracts, layout=None, registry=None, guardian=None): + """Trusted fixed bootstrap supplies ACTUAL selected modules/context, never JSON. + + Module/MethodType consistency does not authenticate a fabricated module. + The enclosing real meter must supply its genuine pre-preparation START ns. + This component neither creates another GlobalLease nor calls its acquire. + """ + need(type(active_module) is ModuleType and type(kernel_module) is ModuleType, 'actual authenticated A/C kernel modules') + if _COMPLETED is None: + configure_completed_source(layout,registry,guardian) + else: + need((layout is None or layout is _COMPLETED[0]) and (registry is None or registry is _COMPLETED[1]), 'same completed source binding') + layout,registry,guardian = completed_source() + A,C,ctx = active_module,kernel_module,active_context + ag = ModuleType.__getattribute__(A,'__dict__') + cg = ModuleType.__getattribute__(C,'__dict__') + + def class_image(cls, methods, *, slotted=False): + # Fixed type operations bypass foreign metaclass/instance attribute hooks. + need(type(cls) is type, 'ordinary exact kernel/context class') + mro = type.__getattribute__(cls,'__mro__') + need(len(mro) == 2 and mro[0] is cls and mro[1] is object, 'direct object class only') + namespace = type.__getattribute__(cls,'__dict__') + keys = tuple(namespace) + need(all(type(k) is str for k in keys), 'exact class attribute keys') + image = {k:namespace[k] for k in keys} + if slotted: + need(type(image.get('__slots__')) is tuple and image.get('__slots__') == (), + 'source-private empty-slotted context') + allowed = {'__module__','__doc__','__slots__','__new__'} | set(methods) + need(set(image) == allowed and type(image['__new__']) is staticmethod and + type(image['__new__'].__func__) is FunctionType and + image['__new__'].__func__.__globals__ is ag, 'fixed context class layout') + else: + need(set(image) == {'__module__','__doc__','__dict__','__weakref__'} | set(methods), + 'fixed kernel class layout without special hooks') + for name in ('__dict__','__weakref__'): + descriptor = image[name] + need(type(descriptor) is GetSetDescriptorType and descriptor.__objclass__ is cls and + descriptor.__name__ == name, 'original native instance dictionary descriptor') + globals_expected = ag if slotted else cg + need(all(type(image[name]) is FunctionType and image[name].__globals__ is globals_expected + for name in methods), 'actual source-bound class functions') + return image + + ContextType = type(ctx) + context_methods = ('initialize','refresh_opening','current_binding','begin','native_lease_for_controller', + 'check','release_for_exec','adopt_handoff','publish_reviewed_close','release') + context_image = class_image(ContextType,context_methods,slotted=True) + check = MethodType(context_image['check'],ctx) + current_binding = MethodType(context_image['current_binding'],ctx) + get_lease = MethodType(context_image['native_lease_for_controller'],ctx) + key = id(ctx) + need(key not in _BOUND_CONTEXTS, 'one consumer binding per actual ACTIVE context; no retry binding') + state = {'context':ctx,'phase':'BINDING_ENTERED','failed':False,'first':None,'outer_identity':None,'members':set(),'used':set(),'finished':set(),'supplemented':set()} + state.update(queries={}, query_counts={}, owner_pid=os.getpid(), pending_intents={}, + waiting={}, protected=None, run_context=None, deadlines={}, primary={}) + _BOUND_CONTEXTS[key] = state # Private state precedes fallible native verification. + io,IOType,LeaseType = cg['IO'],cg['OwnedIO'],cg['GlobalLease'] + io_image = class_image(IOType,('__init__','acquire','close','read','names','write')) + lease_image = class_image(LeaseType,('__init__','acquire','verify','close')) + need(type(io) is IOType, 'same actual original IO singleton') + + def unchanged_class(cls,image): + need(type(cls) is type, 'unchanged ordinary metaclass') + namespace = type.__getattribute__(cls,'__dict__') + keys = tuple(namespace) + need(all(type(k) is str for k in keys) and set(keys) == set(image) and + all(namespace[k] is image[k] for k in keys), 'no class method/descriptor/special-hook substitution') + mro = type.__getattribute__(cls,'__mro__') + need(len(mro) == 2 and mro[0] is cls and mro[1] is object, 'unchanged direct class ancestry') + + def plain_instance(value,cls,image,fields): + need(type(value) is cls, 'same exact native instance type') + unchanged_class(cls,image) + values = image['__dict__'].__get__(value,cls) + need(type(values) is dict and all(type(k) is str for k in values) and set(values) == fields, + 'no instance method/special-hook shadows') + + def dispatch_integrity(held=None): + need(cg.get('IO') is io and cg.get('OwnedIO') is IOType and cg.get('GlobalLease') is LeaseType, + 'unchanged actual kernel singleton/classes') + unchanged_class(ContextType,context_image) + plain_instance(io,IOType,io_image,{'slots'}) + unchanged_class(LeaseType,lease_image) + if held is not None: + plain_instance(held,LeaseType,lease_image,{'fd','phase','birth','lock_info'}) + + dispatch_integrity() + # The authenticated bootstrap must supply the pristine private ACTIVE lease + # at FIRST getter entry: A verifies it before returning it. This is not a + # pre-getter instance-shadow test or a consumer-created/restored capability. + lease = get_lease(C) + dispatch_integrity(lease) + + def io_call(name,*args,**kwargs): + dispatch_integrity(lease) + return io_image[name](io,*args,**kwargs) # Original unbound dispatch. + initial = current_binding() + nested_plain(initial); initial = json.loads(json.dumps(initial)) + need(type(initial) is dict and initial.get('schema') == 'fresh-active-current-binding-v1' and + initial.get('native_capability') is False and initial.get('execution_permission') is False, + 'current binding observation, not owner restoration') + outer = nested_label(initial['request']['label']) + reservation = initial['request']['body_reservation_ns'] + need(type(reservation) is int and 0 < reservation <= 180000000000 and + type(whole_body_begin_ns) is int and 0 <= whole_body_begin_ns <= time.monotonic_ns(), + 'actual enclosing meter START/reservation; provenance is caller source obligation') + whole_deadline_ns = whole_body_begin_ns + reservation + nested_plain(case_contracts) + need(type(case_contracts) is list and 0 < len(case_contracts) <= 128, 'fixed finite nested case declarations') + declared = {} + for item in case_contracts: + need(type(item) is dict and set(item) == {'case','validation_allowance_ns','body_closing_allowance_ns'}, + 'exact nested case/validation/closing declaration') + row = item['case'] + need(type(row) is dict and set(row) == {'stage','job','label','stage_sha256'}, 'exact frozen nested case keys') + for field in ('stage','job','label'): + nested_label(row[field]) + sha = row['stage_sha256'] + need(type(sha) is str and len(sha) == 64 and all(c in '0123456789abcdef' for c in sha), 'exact immutable stage digest') + need(type(item['validation_allowance_ns']) is int and item['validation_allowance_ns'] > 0 and + type(item['body_closing_allowance_ns']) is int and item['body_closing_allowance_ns'] >= 0 and + row['label'] not in declared, 'explicit nonzero validation and unique nested identity') + declared[row['label']] = json.loads(json.dumps(item)) + outer_dir = layout.source + + def verify_native(cleanup=False): + dispatch_integrity(lease) # BEFORE A's nested instance self-dispatch. + need(C.IO_UNKNOWN[0] is False, 'no uncertain native acquisition') + held = get_lease(C,registry,'CLEANUP') if cleanup is True else get_lease(C) + need(lease is held, 'same actual source-private native lease') + dispatch_integrity(lease) + return lease_image['verify'](lease) + + def refresh(nested_ns,cleanup_ns): + need(not state['failed'] and _BOUND_CONTEXTS[key] is state and state['context'] is ctx, 'live sole bound consumer') + dispatch_integrity(lease) + verify_native() + observation = check(nested_ns,cleanup_ns) + same_data(current_binding(),initial) + now = time.monotonic_ns() + need(now >= whole_body_begin_ns and now-whole_body_begin_ns+nested_ns+cleanup_ns <= reservation, + 'complete enclosing body necessary allowance, not local-anchor substitution') + return observation + + def sync_dir(path): + slot,primary = io_call('acquire',path,os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC),None + try: + os.fsync(slot[0]) + except BaseException as error: + primary=error + C.remember(error) + finally: + if slot[1] == 'OWNED': + try: + io_call('close',slot) + except BaseException as error: + secondary=error + C.remember(error) + if primary is None: + primary=error + if primary is not None: + raise primary + + def private_directory(path): + info = path.lstat() + need(path.resolve(strict=True) == path and stat.S_ISDIR(info.st_mode) and + info.st_uid == os.getuid() and stat.S_IMODE(info.st_mode) == 0o700, 'canonical owned nested directory0700') + return info.st_dev,info.st_ino,info.st_mode,info.st_uid + + def write_intent(path,value): + pin = io_call('write',path,value,cap=16384) + slot,primary = io_call('acquire',path,os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC),None + try: + need(tuple(pin['identity']) == C.identity(os.fstat(slot[0])) == C.identity(path.lstat()), 'same owned intent beforefreeze') + os.fchmod(slot[0],0o444); os.fsync(slot[0]) + except BaseException as error: + primary=error + C.remember(error) + finally: + if slot[1] == 'OWNED': + try: + io_call('close',slot) + except BaseException as error: + secondary=error + C.remember(error) + if primary is None: + primary=error + if primary is not None: + raise primary + row,raw = io_call('read',path,16384,0o444,{'bytes':pin['bytes'],'sha256':pin['sha256']},True) + sync_dir(path.parent) + return row + + def prepare(root,case,evidence,seconds,shared_deadline): + need(type(root) is type(ROOT) and type(evidence) is type(ROOT), 'exact concrete root/evidence Path') + need(root == ROOT, 'fixed successor root; no ROOT overwrite') + need(type(case) is dict and all(type(k) is str for k in case), 'builtin source case keys') + selected = {k:case[k] for k in ('stage','job','label','stage_sha256')} + label = nested_label(selected['label']); need(label in declared, 'case in immutable declaration') + same_data(selected,declared[label]['case']) + need(label not in state['used'] and label not in state['finished'] and not state['failed'], 'no nested retry or reused label') + state['used'].add(label); state['phase'] = 'NESTED_PREPARATION_ENTERED' + need(type(seconds) in (int,float) and 0 < seconds <= 190, 'Unadmitted root deadline') + root_ns = seconds_ceiling_ns(seconds) + validation = declared[label]['validation_allowance_ns'] + cleanup = 2000000000 + declared[label]['body_closing_allowance_ns'] + refresh(root_ns+validation,cleanup) + need(seconds_ceiling_ns(shared_deadline) <= whole_deadline_ns, 'caller shareddeadline cannot exceed actual enclosing body') + attempt = registry.attempt(label) + registry.assert_open(attempt,launch=True) + row = attempt.layout + need(evidence == row.supervision_root, 'exact private prospective supervision destination') + if state['outer_identity'] is None: + state['outer_identity'] = private_directory(outer_dir) + state['members'] = set(registry.snapshot()['attempts'][i]['label'] for i in range(len(registry.snapshot()['attempts']))) + need(private_directory(outer_dir) == state['outer_identity'] and + set(io_call('names',outer_dir,512)) == state['members'], 'complete actual attempt top-level census') + parent = proc(os.getpid()) + need(parent is not None, 'actual owning parent generation') + intent = dict(selected,schema='fresh-active-nested-runner-intent-v2',round_id='fresh-metered-round-v1', + outer_label=outer,runner_sha256=RUNNER_SHA,parent_pid=parent['pid'],parent_start_ticks=parent['start_ticks'], + whole_body_begin_ns=whole_body_begin_ns,whole_body_deadline_ns=whole_deadline_ns, + body_reservation_ns=reservation,nested_allowance_ns=root_ns,validation_allowance_ns=validation, + cleanup_allowance_ns=cleanup,active_binding=initial,native_capability=False,execution_permission=False,completed_layout=row.intent_fields(attempt.identity)) + need(_JOINED is not None and _COMMON is not None,'actual selected common runner and entry') + state['pending_intents'][label]=intent + wait_path=row.supervision_root/'WAIT.json' + config={'schema':'h25-waiting-entry-config-v1','case_id':label,'job':case['job'], + 'stage_path':str(STAGE_BASE/case['stage']),'stage_sha256':case['stage_sha256'], + 'runner_path':str(RUNNER_PATH),'runner_sha256':RUNNER_SHA, + 'entry_sha256':_COMMON[1]['sha256'],'entry_bytes':_COMMON[1]['bytes'], + 'outer_output':str(row.science_root),'completed_layout':row.intent_fields(attempt.identity), + 'parent':[parent['pid'],parent['start_ticks']], + 'working_deadline_ns':min(time.monotonic_ns()+root_ns,seconds_ceiling_ns(shared_deadline)-validation-cleanup), + 'cleanup_deadline_ns':min(time.monotonic_ns()+root_ns+2000000000,seconds_ceiling_ns(shared_deadline)-validation), + 'native_source_path':str(SOURCE_BASE.parent/'native/science_view_entry.c')} + need(config['working_deadline_ns']>time.monotonic_ns(),'remaining fixed working interval') + waiting_writer=registry.synchronous_writer(attempt,'pending-launch',wait_path) + try: + wait_pin=write_intent(wait_path,config) + except BaseException as error: + waiting_writer['primary']=error + waiting_writer['state']='UNKNOWN' + registry.capture_error(attempt,error) + raise + waiting_writer['state']='CLOSED' + state['waiting'][label]=(config,wait_pin,waiting_writer) + return wait_path,wait_pin + + def qualify_waiting_candidate(case,domain,process,relay): + """Only the genuine bound parent, after actual registered R arrival.""" + label=case['label'];attempt=registry.attempt(label) + row=attempt.layout + need(state['run_context'] is not None and state['run_context']['process'] is process + and state['run_context']['domain'] is domain and state['owner_pid']==os.getpid(), + 'actual held run and source-private parent closure') + config,wait_pin,waiting_writer=state['waiting'][label] + arrival_path=attempt.layout.supervision_root/'ARRIVED.json' + while True: + state['deadlines'][label].checkpoint() + relay.pump(.01) + unused,rows=domain.observe() + need(not relay.overflowed(),'waiting outer relay cap') + waiting_rss=sum(row['rss_bytes'] for row in rows) + state['run_context']['peak_rss_bytes']=max(state['run_context'].get('peak_rss_bytes',0),waiting_rss) + need(waiting_rss<=state['run_context']['rss_bytes'], + 'whole waiting owned-forest RSS bound') + need(registry.poll_root(process) is None,'common runner died before arrival') + if not arrival_path.exists(): continue + arrival,arrival_pin=read_json(arrival_path,16384) + need(type(arrival) is dict and type(arrival.get('entry')) is list + and len(arrival['entry'])==2 and all(type(v) is int and v>0 for v in arrival['entry']), + 'bounded exact arrival generation') + entry=proc(arrival['entry'][0]) + if entry is not None and generation(entry)==tuple(arrival['entry']) and entry['state'] not in ('T','t'): + continue # Known-closed arrival publication precedes the actual stop. + need(entry is not None and generation(entry)==tuple(arrival['entry']), + 'same live entry generation') + timer=proc(entry['ppid']);root_row=proc(process.pid);parent=proc(os.getpid()) + need(timer is not None and root_row is not None and parent is not None,'actual arrival chain') + expected={'schema':'h25-entry-arrived-v1','case_id':label,'waiting_sha256':wait_pin['sha256'], + 'entry':list(generation(entry)),'timer':list(generation(timer)), + 'runner':list(generation(root_row)),'parent':list(generation(parent)), + 'entry_sha256':_COMMON[1]['sha256']} + same_data(arrival,expected) + need((json.dumps(arrival,sort_keys=True,separators=(',',':'),allow_nan=False)+'\n').encode('ascii')== + stable_file(arrival_path,16384,True)[1],'canonical complete arrival record') + expected_command=['/usr/bin/python3.12',*FLAGS,*(['-O'] if case['job']=='optimized' else []), + str(STAGE_BASE/case['stage']/'integration/candidate_entry.py'), + '--output',str(attempt.layout.science_root),'--lanes','candidate', + '--waiting-config',str(attempt.layout.supervision_root/'WAIT.json'), + '--waiting-sha256',wait_pin['sha256']] + command_path=Path('/proc')/str(entry['pid'])/'cmdline' + with command_path.open('rb') as stream: actual_command=stream.read(16385) + need(len(actual_command)<=16384 and actual_command==b'\0'.join(v.encode() for v in expected_command)+b'\0', + 'actual stopped entry argv, not only its record') + protected=ProtectedRoot(registry,attempt,domain,process,entry,arrival_pin,wait_pin) + state['protected']=protected;state['phase']='C_WAITING_FOR_ASSOCIATION' + break + intent=state['pending_intents'][label] + intent['schema']='fresh-active-nested-runner-intent-v3' + intent['common_rendezvous']={'entry':list(protected.entry_key),'runner':list(protected.runner_key), + 'arrival_sha256':arrival_pin['sha256'],'waiting_sha256':wait_pin['sha256']} + # All current image observations and genuine property work occur after R launch. + for kind in ('entry','time'): + profile=_JOINED[2] + observed=stable_file(Path(profile[kind+'_path']),16777216) + need(observed['bytes']==profile[kind+'_bytes'] and observed['sha256']==profile[kind+'_sha256'], + 'current selected native image within the primary interval') + association,cls,ports,parent_pid=_JOINED[5:] + need(os.getpid()==parent_pid and type(association) is cls,'same genuine parent association process') + for name,(method,fn,code) in ports.items(): + current=getattr(association,name) + need(type(current) is MethodType and current.__self__ is association and current.__func__ is fn and + fn.__code__ is code and type.__getattribute__(cls,'__dict__').get(name) is fn, + 'unchanged actual association method/code owner') + ports['observe'][0](label) # Genuine first observation after actual reserve; bind_launch independently reobserves. + token=ports['bind_launch'][0](label) + record=ports['launch_record'][0](token) + need(type(record) is dict and record.get('case_id')==label and record.get('parent_pid')==parent_pid and + type(record.get('association_sha256')) is str,'actual case association handoff correlation') + raw_record=(json.dumps(record,sort_keys=True,separators=(',',':'),allow_nan=False)+'\n').encode('ascii') + need(len(raw_record)<=8192,'bounded actual association launch record') + unsigned=dict(record);unsigned.pop('association_sha256') + observed_digest=hashlib.sha256((json.dumps(unsigned,sort_keys=True,separators=(',',':'),allow_nan=False)+'\n').encode('ascii')).hexdigest() + need(observed_digest==record['association_sha256'],'actual parent launch record canonical digest') + actual_profile=dict(_JOINED[2],association_sha256=record['association_sha256']) + intent.update(relay_pin=dict(_JOINED[1]),native_entry_profile=actual_profile, + full_receiver_pin=dict(_JOINED[4]),association_record=record) + validate_nested_intent(intent) + intent_path = row.intent_path + intent_writer=registry.synchronous_writer(attempt,'intent',intent_path) + try: + intent_pin=write_intent(intent_path,intent) + except BaseException as error: + intent_writer['primary']=error # Actual first before helper. + intent_writer['state']='CLOSED' if C.IO_UNKNOWN[0] is False and all(slot[1] in ('FREE','CLOSED') for slot in io.slots) else 'UNKNOWN' + registry.capture_error(attempt,error) + raise + else: + intent_writer['state']='CLOSED' + registry.required_writer_closed(attempt,'intent') + protected.verify() + release_path=attempt.layout.supervision_root/'RELEASE.json' + release={'schema':'h25-entry-release-v1','waiting_sha256':wait_pin['sha256'], + 'arrival_sha256':arrival_pin['sha256'],'entry':list(protected.entry_key), + 'runner':list(protected.runner_key),'intent_pin':{'path':str(intent_path), + 'bytes':intent_pin['bytes'],'sha256':intent_pin['sha256']}} + release_writer=registry.synchronous_writer(attempt,'pending-launch',release_path) + try: release_pin=write_intent(release_path,release) + except BaseException as error: + release_writer['primary']=error;release_writer['state']='UNKNOWN' + registry.capture_error(attempt,error);raise + release_writer['state']='CLOSED' + protected.release(intent_pin,intent_writer,release_pin,release_writer) + state['protected']=None;state['phase']='ROOT_RUNNING' + state['run_context']['intent_pin']=intent_pin + state['run_context']['arrival_pin']=arrival_pin + state['run_context']['release_pin']=release_pin + return protected + + def reconcile_missing_receipt(root,label,evidence,began,cause,cleanup): + verify_native(cleanup=True) + # Missing canonical runner receipt remains missing. Only separate DATA is retained. + folder = layout.case(nested_label(label)).runner_root + if (folder / 'receipt.json').exists(): + return None + observation = {'schema':'fresh-nested-missing-receipt-observation-v1','label':label, + 'status':'STOP','cause':cause,'cleanup':cleanup,'canonical_runner_receipt_absent':True, + 'runner_completion_claimed':False,'financial_receipt_created':False, + 'nested_elapsed_seconds_diagnostic':time.monotonic()-began, + 'covered_only_by_genuine_enclosing_body':True,'execution_permission':False} + write_new(evidence/'NESTED-MISSING-RECEIPT.json',observation) + return observation + + def stop_supplement(root,label,reason): + need(type(root) is type(ROOT), 'exact concrete supplement root Path') + label = nested_label(label) # Exact str BEFORE hash/membership. + need(root == ROOT and registry.attempt(label).status is None, 'same actually entered private attempt') + need(label not in state['supplemented'], 'one actual stop supplement') + state['supplemented'].add(label) + reason = bounded_stop_reason(reason) + verify_native(cleanup=True) + attempt = registry.attempt(label) + registry.assert_open(attempt) + evidence = attempt.layout.supervision_root + write_new(evidence/'NESTED-SUPERVISION-STOP.json',{ + 'schema':'fresh-nested-supervision-stop-observation-v1','label':label,'reason':reason, + 'financial_receipt_created':False,'cost_accounted_only_by_actual_enclosing_body':True, + 'execution_permission':False}) + + def query_port(name, *args): + need(_QUERY_JOINED is not None, 'actual joined property receiver/profile required') + module, pin, profile, ports = _QUERY_JOINED + fn, code = ports[name] + need(module.__dict__.get(name) is fn and fn.__code__ is code and + fn.__globals__ is module.__dict__ and module.__dict__.get('__file__') == pin['path'], + 'unchanged genuine property receiver source port') + return fn(*args) + + def query_scratch(custody, path, created): + need(private_directory(path) == created, 'same original administrative query directory') + names = sorted(os.listdir(path)) + need(len(names) <= 32 and all(type(n) is str and n not in ('.', '..') and '/' not in n for n in names), + 'bounded exact query temporary subtree') + files, total = [], 0 + for name in names: + target = path / name + info = target.lstat() + need(stat.S_ISREG(info.st_mode) and info.st_uid == os.getuid() and info.st_nlink == 1 and + info.st_size <= 1048576, 'retained ordinary query temporary file') + total += info.st_size + need(total <= 1048576, 'aggregate administrative query temporary retention') + # Keep the actual files in this same retained source union. No copy, + # unlink or alpha-renaming changes the original non-temporary argv. + ticket = custody.open('query-temporary-readback', target, os.O_RDONLY) + first, h, count = None, hashlib.sha256(), 0 + try: + while count < info.st_size: + block = os.read(ticket['object'], min(CHUNK, info.st_size - count)) + need(bool(block), 'whole query temporary file readback') + count += len(block); h.update(block) + need(identity(info) == identity(os.fstat(ticket['object'])) == identity(target.lstat()), + 'stable actual query temporary file') + except BaseException as error: + first = error + custody.remember(error) + finally: + try: + custody.close(ticket) + except BaseException as error: + first = error if first is None else first + if first is not None: + raise first + files.append({'path': str(target), 'bytes': count, 'sha256': h.hexdigest(), + 'identity': list(identity(info))}) + need(private_directory(path) == created and sorted(os.listdir(path)) == names, + 'complete stable administrative query file census') + return {'path': str(path), 'created_identity': list(created), 'final_identity': list(private_directory(path)), + 'files': files, 'finalized': True, 'writer_retired': True} + + def run_property_query(case_id, request): + """Same genuine owner/lease/registry/guardian as science; distinct receiver.""" + need(type(case_id) is str and case_id in declared and + declared[case_id]['case']['job'] == 'normal' and case_id in state['used'] and + state['phase'] == 'C_WAITING_FOR_ASSOCIATION' and state['protected'] is not None and not state['failed'], + 'only actual reserved case preparation may request properties') + attempt = registry.attempt(case_id) + registry.assert_open(attempt, launch=True) + association, cls, ports, parent_pid = _JOINED[5:] + need(owns_property_query_runner(bound, association) and parent_pid == os.getpid(), + 'same authenticated association, context and parent') + profile = _QUERY_JOINED[2] + stem, program_pin, request_sha = query_port('validate_request', request, case_id, + attempt.layout.supervision_root, profile) + query_key = (case_id, request['family_id'], request['query_id']) + need(query_key not in state['queries'], 'no property query retry or duplicate') + ordinal = state['query_counts'].get(case_id, 0) + 1 + need(ordinal <= 17, 'source-derived fixed property-query count') + state['query_counts'][case_id] = ordinal + query_row = {'request': request, 'phase': 'RESERVED', 'first': None, + 'ordinal': ordinal, 'result': None} + state['queries'][query_key] = query_row # Before any query native operation. + began_ns = time.monotonic_ns() + deadline = None + relay_module = _JOINED[0] + custody = PropertyQueryCustody(registry, attempt, relay_module) + ticket = registry.birth(attempt, 'actual-property-query-observer') + scratch_ticket = registry._resource(attempt, 'property-query-administrative-writer', 'query-scratch-writer') + scratch_ticket['object'], scratch_ticket['state'] = query_row, 'OWNED' + process, domain, relay = None, None, None + spawn_entered, guardian_registered, guardian_retired = False, False, False + guardian_birth_pending = False + first, cleanup, captured, scratch = None, None, None, None + limits, peak_rss = None, 0 + scratch_create_entered = False + temporary = Path(request['temporary_directory']) + payloads, readback_pins, native_fds, diagnostic_pins = {}, {}, {}, {} + root = attempt.layout.supervision_root + paths = {name: root / (stem + '.' + suffix) for name, suffix in + (('request', 'request.bin'), ('snapshot', 'snapshot.bin'), ('stdout', 'stdout.raw'), + ('stderr', 'stderr.raw'), ('terminal', 'native-terminal.json'), ('journal', 'native-errors.bin'))} + old_handler, alarm_owned, query_deadline_token = None, False, None + try: + refresh(12000000000, 2000000000) + verify_native() + deadline = min(began_ns / 1e9 + 12, whole_deadline_ns / 1e9 - CLEANUP_SECONDS, + guardian.whole_deadline_ns / 1e9 - CLEANUP_SECONDS) + need(deadline > time.monotonic(), 'actual existing query working/cleanup budget') + old_handler = signal.getsignal(signal.SIGALRM) + need(state['deadlines'][case_id].started, 'actual enclosing deadline remains owned') + launch_contract() + native_request = query_port('encode_request', request, ordinal) + # Original registry directory constructor reserves the known inode; + # the scratch-writer container remains OWNED through child death. + scratch_create_entered = True + registry._create_owned_case_dir(attempt, temporary) + created = private_directory(temporary) + query_row['scratch_created_identity'] = created + write_ticket = custody.open('query-request-write', paths['request'], + os.O_RDWR | os.O_CREAT | os.O_EXCL) + custody.write(write_ticket, native_request) + custody.close(write_ticket) + native_fds['request'] = custody.open('query-request-read', paths['request'], os.O_RDONLY) + for name in ('snapshot', 'stdout', 'stderr', 'terminal', 'journal'): + native_fds[name] = custody.open('query-native-' + name, paths[name], + os.O_RDWR | os.O_CREAT | os.O_EXCL) + custody.write(native_fds['journal'], b'\0' * 4096) + native_fds['exec'] = custody.open('query-held-program', Path(request['program']), os.O_RDONLY, + expected=program_pin) + native_fds['cwd'] = custody.open('query-held-original-cwd', Path(request['cwd']), + os.O_RDONLY | os.O_DIRECTORY, directory=True) + native_fds['stdin'] = custody.open('query-held-dev-null', Path('/dev/null'), os.O_RDONLY, null=True) + argv = [profile['observer_pin']['path']] + ordered = ('request', 'snapshot', 'stdout', 'stderr', 'terminal', 'journal', 'exec', 'cwd', 'stdin') + for name in ordered: + argv.extend(['--' + name + '-fd', str(native_fds[name]['object'])]) + passed = tuple(native_fds[name]['object'] for name in ordered) + need(len(set(passed)) == 9 and all(fd >= 3 for fd in passed) and 198 not in passed, + 'nine distinct exact observer FDs; no guardian capability inheritance') + observed = stable_file(Path(profile['observer_pin']['path']), 16777216) + need(observed['bytes'] == profile['observer_pin']['bytes'] and + observed['sha256'] == profile['observer_pin']['sha256'], 'current selected observer image bytes') + registry.write_json(attempt, 'property-query-request', root / (stem + '.request.json'), { + 'schema': 'actual-property-query-reservation-v1', 'case_id': case_id, + 'attempt_identity': attempt.identity, 'query_ordinal': ordinal, + 'request': request, 'request_sha256': request_sha, + 'native_request_sha256': hashlib.sha256(native_request).hexdigest(), + 'observer_pin': profile['observer_pin'], 'observer_source_pin': profile['observer_source_pin'], + 'program_pin': program_pin, 'observer_argv': argv, + 'existing_whole_body_begin_ns': whole_body_begin_ns, + 'existing_whole_deadline_ns': whole_deadline_ns, + 'query_working_deadline_ns': int(deadline * 1e9), 'new_allowance_ns': 0}) + query_row['request_retained'] = True + relay = relay_module.BoundedRelay((root / (stem + '.observer.stdout'), + root / (stem + '.observer.stderr')), custody.owner, 'property-query-observer') + relay.open(); out, err = relay.writers() + domain = OwnedDomain(registry, attempt, protected=state['protected']) + limits = root_address_space_limits(resource.getrlimit(resource.RLIMIT_AS), 268435456, resource.RLIM_INFINITY) + fsize = relay_module.compiler_file_limits(resource.getrlimit(resource.RLIMIT_FSIZE), resource.RLIM_INFINITY) + setter, as_kind, file_kind = resource.setrlimit, resource.RLIMIT_AS, resource.RLIMIT_FSIZE + def child_limits(): + setter(as_kind, limits) + setter(file_kind, fsize) + query_deadline_token=state['deadlines'][case_id].push(int(deadline*1e9)) + alarm_owned=True + try: + guardian_birth_pending = True # Actual request may enter before a failed ACK. + guardian.spawn_pending('PropertyQuery', profile['observer_source_pin']['sha256']) + registry.birth_entered(ticket); spawn_entered = True + launch_error, launch_traceback = None, None + try: + process = registry.spawn_root(argv, cwd=request['cwd'], env=dict(ENV), + stdin=native_fds['stdin']['object'], stdout=out, stderr=err, pass_fds=passed, + close_fds=True, start_new_session=True, preexec_fn=child_limits) + registry.born(ticket, process) + except BaseException as error: + launch_error = error + launch_traceback = BaseException.__dict__['__traceback__'].__get__(error, BaseException) + custody.remember(error) + finally: + try: + relay.close_writers() + except BaseException as error: + custody.remember(error) + if launch_error is None: + launch_error = error + launch_traceback = BaseException.__dict__['__traceback__'].__get__(error, BaseException) + if launch_error is not None: + raise BaseException.with_traceback(launch_error, launch_traceback) + captured = proc(process.pid) + need(captured is not None and captured['pgid'] == captured['sid'] == process.pid, + 'actual property observer new-session generation') + domain.root = generation(captured); domain.add(captured) + registry.started_root(process, captured) + guardian.child_known('PropertyQuery', process.pid, profile['observer_source_pin']['sha256'], + pidfd=domain.fds[generation(captured)]) + guardian_registered = True; guardian_birth_pending = False + query_row['phase'] = 'OBSERVER_BORN' + while True: + relay.pump(.01) + outer=state['run_context'];outer['relay'].pump(0) + protected_rows=state['protected'].verify(domain) + need(not outer['relay'].overflowed(), 'waiting root relay remains bounded during query') + unused, current = domain.observe() + concurrent_rss=sum(r['rss_bytes'] for r in protected_rows+current) + outer['peak_rss_bytes']=max(outer.get('peak_rss_bytes',0),concurrent_rss) + need(concurrent_rss<=outer['rss_bytes'], + 'concurrent protected root and query forest RSS bound') + peak_rss = max(peak_rss, sum(row['rss_bytes'] for row in current)) + need(peak_rss <= 1073741824, 'existing actual owned-domain sampled RSS upper bound') + need(not relay.overflowed(), 'observer diagnostic first extra byte observed') + if registry.poll_root(process) is not None: + break + except BaseException as error: + first=error;query_row['first']=error + custody.remember(error) # Before fallible timer unwind. + raise + finally: + pop_deadline_preserving(state['deadlines'][case_id],query_deadline_token,first,custody.remember) + except BaseException as error: + first = error; query_row['first'] = error + custody.remember(error) + if ticket['state'] == 'PENDING': + registry.birth_failed(ticket, error, known_not_entered=not spawn_entered) + finally: + # Every secondary cleanup failure is immediately a query failure. + # A readable prefix never permits another query/scientific launch. + if alarm_owned: + try: + owner=state['deadlines'][case_id] + if query_deadline_token is not None and owner.stack and owner.stack[-1][0] is query_deadline_token: + owner.pop(query_deadline_token) + except BaseException as error: + first=error if first is None else first;custody.remember(error) + try: + cleanup = domain.cleanup(process,min(deadline+CLEANUP_SECONDS,whole_deadline_ns/1e9)) if domain is not None else { + 'complete': not spawn_entered, 'group_empty_proved': not spawn_entered, + 'remaining': [] if not spawn_entered else 'UNKNOWN', + 'observed_after_root_exit': [], 'reaped_adopted': []} + need(cleanup['complete'] and cleanup['group_empty_proved'] and cleanup['remaining'] == [], + 'actual complete query domain retirement') + if process is not None: + registry.waited(ticket, process.returncode) + registry.holder_closed(ticket) + need(guardian_registered, 'known guardian query birth before retirement') + guardian.child_closed('PropertyQuery', process.pid) + guardian_retired = True + except BaseException as error: + first = error if first is None else first + custody.remember(error) + registry.mark_uncertain(attempt, 'property query process/guardian retirement uncertain') + if guardian_birth_pending: + registry.mark_uncertain(attempt, 'property query guardian birth pending or acknowledgement uncertain') + if relay is not None: + try: + relay.close_writers() + if relay.setup_complete and relay.primary is None: + relay.drain_until(min(time.monotonic() + CLEANUP_SECONDS, whole_deadline_ns / 1e9)) + except BaseException as error: + first = error if first is None else first + custody.remember(error) + finally: + try: + if not relay.retired: relay.retire() + except BaseException as error: + first = error if first is None else first + custody.remember(error) + try: + custody.close_all() + except BaseException as error: + first = error if first is None else first + known_retirement = (cleanup is not None and cleanup['complete'] and + cleanup['group_empty_proved'] and cleanup['remaining'] == []) + if known_retirement and 'scratch_created_identity' in query_row and custody.snapshot()['all_closed']: + try: + scratch = query_scratch(custody, temporary, query_row['scratch_created_identity']) + scratch_ticket['state'] = 'CLOSED' + except BaseException as error: + first = error if first is None else first + custody.remember(error) + elif not scratch_create_entered: + scratch_ticket['state'] = 'NOT_ENTERED' + if first is None: + try: + need(process is not None and process.returncode == 0, 'actual observer success wait') + caps = {'snapshot': 2752520, 'stdout': 1048576, 'stderr': 1048576, + 'terminal': 16384, 'journal': 4096} + for name, cap in caps.items(): + pin, raw = custody.readback(paths[name], cap, custody.identities[str(paths[name])]) + readback_pins[name], payloads[name] = pin, raw + for name in ('stdout', 'stderr'): + diagnostic = root / (stem + '.observer.' + name) + pin, raw = custody.readback(diagnostic, LOG_CAP) + diagnostic_pins[name] = pin + need(raw == b'', 'selected native observer has no success diagnostic output') + context = {'case_id': case_id, 'attempt_identity': attempt.identity, + 'request_sha256': request_sha, 'native_request_sha256': hashlib.sha256(native_request).hexdigest(), + 'source_tuple_sha256': profile['source_tuple_sha256'], 'profile_sha256': profile['profile_sha256'], + 'observer_pin': profile['observer_pin'], 'observer_source_pin': profile['observer_source_pin'], + 'program_pin': program_pin, 'observer_process': captured, + 'observer_wait': process.returncode, 'guardian_registered': guardian_registered, + 'guardian_retired': guardian_retired, 'domain': cleanup, 'relay': relay.snapshot(), + 'custody': custody.snapshot(), 'scratch': scratch, 'readback_pins': readback_pins, + 'diagnostic_pins': diagnostic_pins, + 'elapsed_ns': time.monotonic_ns() - began_ns} + result = query_port('validate_terminal', request, ordinal, context, payloads) + query_row['result'] = result; query_row['phase'] = 'QUALIFIED' + except BaseException as error: + first = error; query_row['first'] = error + custody.remember(error) + if first is not None: + query_row['phase'] = 'FAILED_OR_UNCERTAIN_RETIRED' + if scratch_ticket['state'] == 'OWNED': + scratch_ticket['state'] = 'UNKNOWN' + if not custody.snapshot()['all_closed']: + registry.mark_uncertain(attempt, 'property query descriptors unavailable or unknown after one close') + custody.ticket['state'] = 'CLOSED' if custody.snapshot()['all_closed'] else 'UNKNOWN' + registry.write_json(attempt, 'property-query-terminal', root / (stem + '.parent-terminal.json'), { + 'schema': 'actual-property-query-parent-terminal-v1', 'case_id': case_id, + 'attempt_identity': attempt.identity, 'query_ordinal': ordinal, 'request_sha256': request_sha, + 'prelaunch_request': None if query_row.get('request_retained') else request, + 'status': 'QUERY_BYTES_QUALIFIED' if first is None else 'SETUP_QUERY_FAILED', + 'spawn_entered': spawn_entered, 'observer_wait': None if process is None else process.returncode, + 'guardian_registered': guardian_registered, 'guardian_retired': guardian_retired, + 'guardian_birth_pending': guardian_birth_pending, + 'domain': cleanup, 'custody': custody.snapshot(), 'readback_pins': readback_pins, + 'diagnostic_pins': diagnostic_pins, + 'installed_observer_as_limits': None if limits is None else list(limits), + 'sampled_owned_domain_peak_rss': peak_rss, 'native_working_seconds': 10, + 'native_cleanup_tail_seconds': 2, 'parent_cleanup_tail_seconds': 2, + 'scratch': scratch, 'actual_elapsed_ns': time.monotonic_ns() - began_ns, + 'raw_primary_retained': first is not None, 'scientific_negative_issued': False, + 'new_allowance_ns': 0}) + if first is not None: + raise BaseException.with_traceback(attempt.error, attempt.traceback) + refresh(0, 2000000000) + return query_row['result'] + + def run_root(root, case, evidence, seconds, shared_deadline, as_bytes=201326592, + rss_bytes=201326592): + """Actual joined Root, followed by bounded relay and genuine domain retirement.""" + wait_path,wait_pin = prepare(root,case,evidence,seconds,shared_deadline) + launch_contract() + need(_JOINED is not None,'actual joined runtime source association') + relay_module,relay_pin,native_profile,full_receiver,full_receiver_pin = _JOINED[:5] + need(stable_file(RUNNER_PATH,META_CAP)['sha256']==RUNNER_SHA,'Actual root runner changed') + need(time.monotonic()+CLEANUP_SECONDSshared_deadline: + failure=failure or {'type':'SharedDeadline','message':'Shared cap crossed; cleanup charged'} + closure_path=attempt.layout.runner_root/'WRITER-CLOSURE.json' + local_closed=False + closure=None + if process is None and not spawn_entered: + local_closed=outer_relay['all_descriptors_known_closed'] + elif closure_path.exists() and native_domain_closed: + closure,closure_pin=read_runner_closure(closure_path) + local_closed=closure['local_holders_closed'] + if local_closed and native_domain_closed and outer_relay['all_descriptors_known_closed']: + for holder in holders: + if holder['state']=='OWNED': + registry.native_holder_closed(holder) + for role in ('runner','native-usage','native-child','native-entry','native-setup', + 'relay-capture','relay-read','relay-writer','pending-launch'): + registry.required_writer_closed(attempt,role) + else: + registry.mark_uncertain(attempt,'joined local closure absent; no EOF/direct-exit substitution') + reconciled=reconcile_missing_receipt(root,case['label'],evidence,began, + failure or {'type':'MissingRootReceipt','message':'Root exited without receipt'},cleanup) + if reconciled is not None: + failure=failure or {'type':'MissingRootReceipt','message':'Missing canonical receipt retained; no retry'} + logs={} + for name in ('root.stdout.raw','root.stderr.raw'): + try: + logs[name]=stable_file(evidence/name,LOG_CAP) + except BaseException as error: + registry.capture_error(attempt,error) + failure=failure or {'type':'opaque-log-exception','message':'projection_unavailable'} + logs[name]={'path':str(evidence/name),'complete_hash':None,'stable':False} + result={'schema':'h25-parent-root-supervision-v1','label':case['label'], + 'status':'STOP' if failure else 'ROOT_COMPLETED_AND_OWNED_DOMAIN_EMPTY','failure':failure, + 'spawn_entered':spawn_entered,'spawn_returned':process is not None,'captured_root':captured, + 'returncode':None if process is None else process.returncode,'cleanup':cleanup,'outer_logs':logs, + 'outer_relay':outer_relay,'runner_local_closure':closure, + 'sampled_owned_rss_bytes':max(peak,(state['run_context'] or {}).get('peak_rss_bytes',0)), + 'execution_and_cleanup_seconds':time.monotonic()-began,'root_receipt_reconciled':reconciled is not None, + 'G_cgroup_writer_lifetime_proof_still_required':True,'no_hostile_fork_or_concurrent_children_claim':True} + write_new(evidence/'SUPERVISION.json',result) + registry.required_writer_closed(attempt,'reconcile') + registry.required_writer_closed(attempt,'supervision') + return result + + sentinel = object() + class BoundConsumers: + __slots__ = () + def __new__(cls,key_value): + need(key_value is sentinel, 'private bound native consumer only') + return object.__new__(cls) + def run_property_query(self, case_id, request): + need(self is bound, 'actual source-private property-query consumer') + try: + frame = sys._getframe(1) + try: + association = _JOINED[5] + need(frame.f_globals is _JOINED[7]['observe'][1].__globals__ and + frame.f_locals.get('self') is association, + 'property request originates in the actual source-owned association') + finally: + del frame + return run_property_query(case_id, request) + except BaseException as error: + if state['first'] is None: + state['first'] = error + state['failed'], state['phase'] = True, 'PROPERTY_QUERY_FAILED_NO_RETRY' + attempt = registry.attempt(case_id) + registry.capture_error(attempt, error) + raise BaseException.with_traceback(attempt.error, attempt.traceback) + def run_root(self,root,case,evidence,seconds,shared_deadline,as_bytes=201326592,rss_bytes=201326592): + need(self is bound, 'actual bound source consumer') + try: + result = run_root(root,case,evidence,seconds,shared_deadline,as_bytes,rss_bytes) + if result['status'] == 'STOP': + state['failed'] = True; state['phase'] = 'NESTED_STOP_NO_RETRY' + else: + need(private_directory(outer_dir) == state['outer_identity'] and + set(io_call('names',outer_dir,512)) == state['members'], 'complete nested top-level census') + state['phase'] = 'NESTED_RETURNED' + result['fresh_round_outer_label'] = outer + result['nested_is_not_registry_charge'] = True + return result + except BaseException as error: + if state['first'] is None: + state['first'] = error # Direct raw reference before any helper/state projection. + attempt = registry.attempt(case['label']) + registry.capture_error(attempt,error) + state['failed'] = True; state['phase'] = 'FAILED_NO_RETRY' + raise BaseException.with_traceback(attempt.error,attempt.traceback) + def finish_primary(self,label): + need(self is bound and label in state['primary'] and state['phase']=='NESTED_RETURNED', + 'actual returned case before its retained validation endpoint') + begin,before_self,before_children=state['primary'].pop(label) + after_self=resource.getrusage(resource.RUSAGE_SELF) + after_children=resource.getrusage(resource.RUSAGE_CHILDREN) + end=time.monotonic_ns() + owner=state['deadlines'][label];owner.checkpoint();owner.finish() + return {'parent_command_wall_seconds_through_validation':(end-begin)/1e9, + 'parent_command_cpu_seconds_with_runner_children_validation': + (after_self.ru_utime+after_self.ru_stime-before_self.ru_utime-before_self.ru_stime)+ + (after_children.ru_utime+after_children.ru_stime-before_children.ru_utime-before_children.ru_stime), + 'primary_begin_monotonic_ns':begin,'primary_end_monotonic_ns':end} + def finish_case(self,label,error=None): + need(self is bound,'same actual bound source finalizer') + owner=state['deadlines'].get(label) + if owner is not None and owner.started and not owner.finished: + try: owner.finish() + except BaseException as failure: + registry.capture_error(registry.attempt(label),failure) + if error is None: error=failure + attempt = registry.attempt(nested_label(label)) + registry.assert_open(attempt) + registry.retire_unentered(attempt) + verify_native(cleanup=True) + registry.prepare_finalizer_dirs(attempt) + if error is not None: + registry.capture_error(attempt,error) + if label in state['finished']: + return + state['finished'].add(label) # Irreversible: prepare refuses this case thereafter. + if label not in state['used']: + write_new(attempt.layout.supervision_root/'SUPERVISOR-NOT-ENTERED.json',{ + 'schema':'h25-supervisor-not-entered-observation-v1','label':label, + 'status':'STOP','native_launch_entered':False,'canonical_runner_receipt_created':False}) + for role in ('intent','runner','native-usage','native-child','native-entry','native-setup', + 'relay-capture','relay-read','relay-writer','pending-launch','supervision','reconcile'): + if attempt.required[role] is False: + registry.required_writer_closed(attempt,role) + return + # Required originals are invoked only if their owning path has not completed. + if attempt.required['reconcile'] is False: + process_rows = [r for r in attempt.resources if r['kind']=='process' and r['role']=='actual-root-runner'] + known = all(r['state'] in ('CLOSED','NOT_ENTERED') for r in process_rows) + cleanup = {'complete':known,'remaining':[] if known else 'UNKNOWN_NATIVE_ENTRY'} + observation = reconcile_missing_receipt(ROOT,label,attempt.layout.supervision_root,time.monotonic(), + {'type':'OwningCaseFinalizer','message':'Actual failed preparation/producer finally'},cleanup) + registry.required_writer_closed(attempt,'reconcile') + if attempt.required['supervision'] is False: + write_new(attempt.layout.supervision_root/'SUPERVISOR-FINALIZER.json',{ + 'schema':'h25-supervisor-finalizer-observation-v1','label':label,'status':'STOP', + 'canonical_runner_receipt_created':False,'original_run_root_result_present':(attempt.layout.supervision_root/'SUPERVISION.json').exists()}) + registry.required_writer_closed(attempt,'supervision') + process_rows = [r for r in attempt.resources if r['kind']=='process' and r['role']=='actual-root-runner'] + for resource in attempt.resources: + if resource['kind'] in ('process','native-holder') and resource['state']=='PENDING' and not resource['entry_entered'] and not any(r['entry_entered'] for r in process_rows): + resource['state']='NOT_ENTERED' + resource['wait_known']=resource['aliases_closed']=True + no_launch = not process_rows or all(r['state']=='NOT_ENTERED' for r in process_rows) + if no_launch: + # Retire a genuinely unentered relay owner too; known returned FDs + # are closed once, and unknown endpoints remain unknown. + for resource in attempt.resources: + if resource['kind']=='relay-owner' and resource['state']=='OWNED': + actual_relay=resource['object'] + if not actual_relay.retired: + actual_relay.retire() + for role in ('intent','runner','native-usage','native-child','native-entry','native-setup', + 'relay-capture','relay-read','relay-writer','pending-launch'): + if attempt.required[role] is False: + registry.required_writer_closed(attempt,role) + else: + if attempt.required['intent'] is False: + registry.mark_uncertain(attempt,'intent writer incomplete after native entry') + def stop_supplement(self,root,label,reason): + need(self is bound, 'actual bound source consumer') + state['failed'] = True; state['phase'] = 'STOP_SUPPLEMENT_ENTERED_NO_RETRY' + try: + result = stop_supplement(root,label,reason) + except BaseException as error: + if state['first'] is None: + state['first'] = error + state['phase'] = 'STOP_SUPPLEMENT_FAILED_NO_RETRY' + raise # Preserve this actual exception and the privately retained first. + state['phase'] = 'STOP_SUPPLEMENT_RETAINED_NO_RETRY' + return result + bound = BoundConsumers(sentinel) + state['bound_consumer'], state['association'] = bound, _JOINED[5] + state['property_query_method'] = (BoundConsumers.__dict__['run_property_query'], + BoundConsumers.__dict__['run_property_query'].__code__) + _JOINED[7]['bind_property_query_runner'][0](bound) + state['phase'] = 'BOUND_TO_ACTUAL_ACTIVE_OWNER' + return bound + + +def packet_unchanged(directory, manifest): + for name, expected in manifest['files'].items(): + row = stable_file(directory / name, META_CAP) + need(row['sha256'] == expected['sha256'] and row['bytes'] == expected['bytes'], + 'Parent source packet changed: ' + name) + need(not (directory / name).stat().st_mode & 0o222, 'Parent source packet became writable') + return True diff --git a/research/h25-parent-waiting-entry/implementation/source/full_result_receiver.py b/research/h25-parent-waiting-entry/implementation/source/full_result_receiver.py new file mode 100644 index 0000000000..29304eb6ce --- /dev/null +++ b/research/h25-parent-waiting-entry/implementation/source/full_result_receiver.py @@ -0,0 +1,373 @@ +# Modified 2026-11-07: Clear1nsight, with OpenAI Codex and ChatGPT Pro assistance. See NOTICE.md. +"""Exact adopted full-source command projection and terminal parent receiver. + +This module never imports a scientific image, issues execution permission or +changes its input domain. The authenticated parent loads it as source. The +normal image's original SC4 entry qualifies live disposition after its finally; +the parent additionally requires actual exit/wait, relay EOF and all writer +closure. A full receipt written before a later exception cannot pass here. +""" +from pathlib import Path + +W = Path('/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453') +R = W / 'outputs/caller-proof-completion-20261107T0155Z' +ROOT = W / 'outputs/h25-data-handling-20261028' +STAGE_BASE = R / 'implementation/bindings/stages' +ADOPTED = W / 'outputs/s03-frozen-source-selection-20261104T1210Z/implementation' +NAME = 'IndependentPrefixDATAComposedV1' +FLAGS = ('-S', '-s', '-P', '-B') +ROOT_SHA = 'f5a2d33f2b4d3651f214156a0e7094c2bb516ce2d5ab7698d18c11f98f35dee0' +PROVIDER_SHA = '9cbb7368f89e71d1e6cc46db5dc77efed3e03ed2a801c98c88fe316e4d9f3ef2' +BASELINE_SHA = '9bbafe3f53febec7a984751b9e06741e06df34e2e6fa7c328c805b9eea700bd7' +SELECTIONS = { + 'normal': ('joined-full-candidate-v1', '1a0dd86bffc5cd4d', + '4804814035aea33eeb1a26ca51ddf82555423e8d275636d6a274f43541aa5977', + 'fa9f473320e9df3a2328bd8388f12eca4e7fc3eeed9289f7fdbf2eeb32a7452f', + 'full:candidate', False), + 'optimized': ('joined-full-candidate-refusal-v1', 'b1497bfaaf2cedca', + 'da49427ab8cce9d552f4dc64d6031adb60ed52c006ebcd1627ed409e9c632cc4', + '92b507a2667b0d0085f63fb35176167806272934fef8149da691043411c81db0', + 'optimized-refusal:candidate', True), +} +ADOPTION_PATH = W / 'outputs/s03-adoption-proof-review-20261104T1255Z/review/FINAL-ACTUAL-SOURCE-ADOPTION-ACCEPTANCE-v1.json' +ADOPTION_SHA = '99b856e02dd05a0fe576a052c976f8ee98de5db71b4dcddf44ab32532c4d62b2' +CATALOG_SHA = '97af356321e9dabe465c70f6a475e6b957735152d293359e9713cf01c7733d96' +MANIFEST_SHA = 'e4e4f461794b4a8e09291a421ae4765446ff4c25431728df7609999e2ef4fed3' +COMMANDS_SHA = '5872d8d79247356e2ac8c9a41fc1de875f292426dfd2d2174145c14561ffc942' +REFUSAL = b'RuntimeError: SC4 fixed assertion-on fresh candidate full invocation required\n' + + +def need(value, reason): + if value is not True: + raise ValueError(reason) + + +def job_for(mode): + need(type(mode) is str and mode in SELECTIONS, 'exact complete full job') + row = SELECTIONS[mode] + return {'optimized': row[5], 'lanes': 'candidate', 'finite_only': False, + 'bootstrap': {'provider': 'integration/probe_binding_v3.py', + 'driver': 'integration/scientific_driver.py'}, + 'full_caller_role': row[4]} + + +def case_for(mode, stage_sha256): + row = SELECTIONS[mode] + return {'stage': row[0], 'job': mode, 'label': NAME + ('N' if mode == 'normal' else 'O'), + 'stage_sha256': stage_sha256} + + +def command_for(stage, declared, job_name, job, science_root): + """Only the adopted full Root/provider/image command with a new owned output. + + The sole command/path inverse changes are the new immutable stage mount and + genuinely owned retained output. Defaults, lane, anchor, flags and original + native/source bootstrap remain explicit. Optimized full is refusal only. + """ + need(type(stage) is type(STAGE_BASE) and type(science_root) is type(STAGE_BASE), + 'concrete full command paths') + need(type(job_name) is str and job_name in SELECTIONS and job == job_for(job_name), + 'exact adopted full job with original assertion semantics') + row = SELECTIONS[job_name] + need(stage == STAGE_BASE / row[0], 'exact full stage inverse') + files = declared['files'] + for relative, expected in (('integration/full_driver.py', ROOT_SHA), + ('integration/probe_binding_v3.py', PROVIDER_SHA), + ('integration/scientific_driver.py', row[3])): + need(type(files[relative]) is dict and files[relative]['sha256'] == expected and + files[relative]['mode'] == 0o444, 'adopted original Root/provider/scientific source') + source = R / 'runtime/completed-source' / NAME + label = NAME + ('N' if job_name == 'normal' else 'O') + need(science_root == source / label / 'runner/artifact/science', + 'full science stays in the complete actual attempted source union') + return ['/usr/bin/python3.12', *(['-O'] if row[5] else []), *FLAGS, + str(stage / 'integration/full_driver.py'), '--root-sha256', ROOT_SHA, + '--provider', str(stage / 'integration/probe_binding_v3.py'), PROVIDER_SHA, + '--driver', str(stage / 'integration/scientific_driver.py'), row[3], + '--integration', str(stage / 'integration'), '--', '--lanes', 'candidate', + '--output', str(science_root), '--anchor', str(stage / 'baseline/anchor.json')] + + +def common_entry_command(case, stage, layout, waiting_sha): + return ['/usr/bin/python3.12', *FLAGS, *(['-O'] if case['job']=='optimized' else []), + str(stage/'integration/candidate_entry.py'),'--output',str(layout.science_root), + '--lanes','candidate','--waiting-config',str(layout.supervision_root/'WAIT.json'), + '--waiting-sha256',waiting_sha] + + +def common_entry_binding(kernel,case,layout,declared,receipt): + """Bind both the original common R command and actual inner native command.""" + wait,wait_pin=kernel.read_json(layout.supervision_root/'WAIT.json',16384,0o444) + arrival,arrival_pin=kernel.read_json(layout.supervision_root/'ARRIVED.json',16384,0o444) + seal,seal_pin=kernel.read_json(layout.supervision_root/'RELEASE.json',16384,0o444) + intent,intent_pin=kernel.read_json(layout.intent_path,16384,0o444,seal['intent_pin']) + entry,entry_pin=kernel.read_json(layout.runner_root/'ENTRY.json',16384,0o444) + stage=STAGE_BASE/case['stage'] + kernel.need(wait['case_id']==case['label'] and wait['stage_sha256']==case['stage_sha256'] + and wait['runner_sha256']==receipt['runner_sha256'] and wait['job']==case['job'] + and receipt['command']==common_entry_command(case,stage,layout,wait_pin['sha256']), + 'actual common runner candidate-entry command') + kernel.need(intent['schema']=='fresh-active-nested-runner-intent-v3' + and intent['common_rendezvous']=={'entry':arrival['entry'],'runner':arrival['runner'], + 'arrival_sha256':arrival_pin['sha256'],'waiting_sha256':wait_pin['sha256']} + and seal['schema']=='h25-entry-release-v1' and seal['entry']==arrival['entry'] + and seal['runner']==arrival['runner'] and seal['waiting_sha256']==wait_pin['sha256'] + and seal['arrival_sha256']==arrival_pin['sha256'],'exact retained release/arrival/intent inverse') + inner=command_for(stage,declared,case['job'],job_for(case['job']),layout.science_root) + kernel.need(entry['schema']=='h25-common-entry-result-v1' and entry['case_id']==case['label'] + and entry['inner_command']==inner and type(entry['inner_exit']) is int + and entry['inner_exit']==(1 if case['job']=='optimized' else 0) + and entry['failure'] is None and entry['waiting_sha256']==wait_pin['sha256'] + and entry['arrival_sha256']==arrival_pin['sha256'] and entry['release_sha256']==seal_pin['sha256'] + and entry['intent_pin']==seal['intent_pin'] and entry['outer_usage_aliases_retired'] is True, + 'actual complete entry disposition and retained one-use binding') + profile=intent['native_entry_profile'];artifact=layout.artifact_parent.stat() + usage_path=layout.runner_root/'native-usage.json';usage=usage_path.stat() + timed=[profile['time_path'],'-f','{"user_seconds":%U,"system_seconds":%S,"kernel_max_rss_kib":%M,"exit":%x}', + '-o',str(usage_path),'--',*inner] + native=[profile['entry_path'],'--entry-image',profile['entry_path'],profile['entry_sha256'],str(profile['entry_bytes']), + '--time-image',profile['time_path'],profile['time_sha256'],str(profile['time_bytes']), + '--read-root',str(ROOT),'--artifact-parent',str(layout.artifact_parent),str(artifact.st_dev),str(artifact.st_ino), + '--science-leaf','science','--usage',str(usage_path),str(usage.st_dev),str(usage.st_ino),'--',*timed] + kernel.need(entry['native_command']==native,'actual inner native/time/source command inverse') + return entry + + +def stage_check(kernel, stage_pins): + """Verify exact full payload inverses; only JOBS and enclosing bindings differ.""" + kernel.exact(stage_pins, ('normal', 'optimized')) + catalog, catalog_pin = kernel.read_json(ADOPTED / 'SOURCE-SELECTIONS-v1.json', 1048576, 0o444) + manifest, manifest_pin = kernel.read_json(ADOPTED / 'SELECTED-SOURCE-MANIFEST-v1.json', 1048576, 0o444) + adoption, adoption_pin = kernel.read_json(ADOPTION_PATH, 1048576, 0o444) + commands, commands_pin = kernel.read_json(ADOPTED / 'COMMANDS-v1.json', 1048576, 0o444) + kernel.need(catalog_pin['sha256'] == CATALOG_SHA and manifest_pin['sha256'] == MANIFEST_SHA and + adoption_pin['sha256'] == ADOPTION_SHA and commands_pin['sha256'] == COMMANDS_SHA and + adoption['source_adopted'] is True and adoption['S03_08_completed'] is True and + adoption['selected_manifest']['sha256'] == MANIFEST_SHA, + 'exact actual adopted S03 source authority, no rejected historical catalog') + kernel.need(catalog['full_callers']['baseline']['overlay']['integration/scientific_driver.py']['sha256'] == BASELINE_SHA, + 'independent adopted full baseline image retained') + rows, retained = {}, {} + # S10.02 is a separately owned fresh-baseline route. Retain its actual + # accepted source/command boundary; the historical anchor alone never + # completes the later current baseline-transfer/comparison requirement. + baseline_command = baseline_source_route(commands) + for baseline_pin in catalog['full_callers']['baseline']['overlay'].values(): + row, unused = kernel.IO.read(Path(baseline_pin['path']),baseline_pin['bytes'],0o444,baseline_pin) + rows[row['path']] = row + for mode, selected in SELECTIONS.items(): + stage = STAGE_BASE / selected[0] + declared, actual = kernel.read_json(stage / 'STAGE.json', 1048576, 0o444, stage_pins[mode]) + recipe_path = ADOPTED / 'stages' / selected[1] / 'STAGE.json' + recipe, recipe_pin = kernel.read_json(recipe_path, 1048576, 0o444) + kernel.need(recipe_pin['sha256'] == selected[2], 'exact accepted full stage recipe') + original = recipe['files'] + common='integration/candidate_entry.py' in declared['files'] + expected_members=set(original)|({'integration/candidate_entry.py'} if common else set()) + kernel.need(set(declared['files']) == expected_members and + all(declared['files'][name] == pin for name, pin in original.items() if name != 'JOBS.json'), + 'every original full source/control/oracle byte and mode unchanged') + jobs, jobs_pin = kernel.read_json(stage / 'JOBS.json', 65536, 0o444) + selected_job=job_for(mode) + if common: + selected_job={k:v for k,v in selected_job.items() if k!='bootstrap'} + selected_job['entry']='integration/candidate_entry.py' + entry_source=Path(__file__).absolute().parent/'candidate_entry.py' + entry_source_pin,unused=kernel.IO.read(entry_source,262144,0o444,materialize=False) + kernel.need(declared['files']['integration/candidate_entry.py']=={'sha256':entry_source_pin['sha256'],'mode':0o444}, + 'actual enrolled waiting-entry source byte inverse') + rows[str(entry_source)]=entry_source_pin + kernel.need(jobs == {mode: selected_job} and + declared['files']['JOBS.json'] == {'sha256': jobs_pin['sha256'], 'mode': 0o444}, + 'sole JOBS change has an exact complete-command inverse') + for relative, expected in declared['files'].items(): + kernel.need(type(relative) is str and not Path(relative).is_absolute() and + '..' not in Path(relative).parts, 'exact relative full source member') + path = stage / relative + pin, unused = kernel.IO.read(path, 67108864, expected['mode'], materialize=False) + kernel.need(pin['sha256'] == expected['sha256'], 'unchanged full payload member') + rows[str(path)] = pin + # Compare the reached command with the original accepted command DATA. + original_commands = [row for row in commands['commands'] if row['role'] == selected[4]] + kernel.need(len(original_commands) == 1, 'one adopted original command for full role') + command = original_commands[0] + old_stage = ROOT / 'stages' / ('s03-r6-' + selected[1]) + old_output = ROOT / 'runtime/runs' / ('s03-r6-' + selected[1] + ('-O' if selected[5] else '')) / 'science' + projected = [str(stage) + value[len(str(old_stage)):] if value == str(old_stage) or value.startswith(str(old_stage) + '/') + else str(R / 'runtime/completed-source' / NAME / (NAME + ('N' if mode == 'normal' else 'O')) / 'runner/artifact/science') + if value == str(old_output) else value for value in command['argv']] + expected = command_for(stage, declared, mode, job_for(mode), + R / 'runtime/completed-source' / NAME / (NAME + ('N' if mode == 'normal' else 'O')) / 'runner/artifact/science') + kernel.need(projected == expected and command['cwd'] == str(ROOT) and + command['optimize'] == int(selected[5]) and command['execution_authorized'] is False, + 'exact original command/path/mode inverse') + rows[str(stage / 'STAGE.json')] = actual + rows[str(recipe_path)] = recipe_pin + retained[mode] = {'manifest': actual, 'recipe': recipe_pin, 'declared': declared} + for pin in (catalog_pin, manifest_pin, adoption_pin, commands_pin): + rows[pin['path']] = pin + return {'manifest': retained['normal']['manifest'], 'files': rows, 'stages': retained, + 'separate_fresh_baseline_source_route': baseline_command, + 'fresh_baseline_execution_or_comparison_completed': False} + + +def baseline_source_route(commands): + """The retained original S10.02 full baseline invocation, never a grant. + + Its actual fresh result and typed transfer belong to the separately guarded + original baseline/comparison activities. No prior receipt or anchor is + accepted as a current baseline by this complete candidate source route. + """ + rows = [row for row in commands['commands'] if row['role'] == 'full:baseline'] + need(len(rows) == 1 and rows[0]['optimize'] == 0 and + rows[0]['cwd'] == str(ROOT) and rows[0]['execution_authorized'] is False and + BASELINE_SHA in rows[0]['argv'] and '--finite-only' not in rows[0]['argv'], + 'actual accepted independent full baseline source command') + return rows[0] + + +def _artifact(kernel, path, expected_sha, expected_bytes=None): + # Full scientific files include a 58MB witness. OwnedIO streams in 64KiB + # chunks without materialization; the complete command/validation bill pays + # for all bytes. The existing original budget bounds the operation. + size = path.lstat().st_size + kernel.need(type(size) is int and size >= 0, 'original scientific file size') + pin, unused = kernel.IO.read(path, size) + kernel.need(pin['sha256'] == expected_sha and + (expected_bytes is None or pin['bytes'] == expected_bytes), + 'exact original full scientific bytes') + return pin + + +def _relay(kernel, observation, paths): + kernel.exact(observation, ('schema','cap_bytes_each','nonblocking_readers_only', + 'fair_read_quantum_bytes','setup_complete','retired', + 'all_descriptors_known_closed','eof_complete','overflow', + 'raw_error_present','streams','writer_lifetime_proof')) + kernel.need(observation['schema'] == 'joined-bounded-relay-v1' and + type(observation['cap_bytes_each']) is int and observation['cap_bytes_each'] == 2097152 and + observation['nonblocking_readers_only'] is True and + type(observation['fair_read_quantum_bytes']) is int and observation['fair_read_quantum_bytes'] == 65536 and + observation['setup_complete'] is True and observation['retired'] is True and + observation['all_descriptors_known_closed'] is True and + observation['eof_complete'] is True and observation['overflow'] is False and + observation['raw_error_present'] is False and observation['writer_lifetime_proof'] is False and + type(observation['streams']) is list and len(observation['streams']) == 2, + 'actual bounded fair relay completed; EOF is not lifetime authority') + pins = [] + for stream,path in zip(observation['streams'],paths): + kernel.exact(stream, ('path','bytes','observed_bytes','discarded_bytes','overflow','eof', + 'final_bytes','write_uncertain','sha256')) + pin, unused = kernel.IO.read(path, 2097152, 0o600) + kernel.need(stream['path'] == str(path) and type(stream['bytes']) is int and + type(stream['observed_bytes']) is int and type(stream['final_bytes']) is int and + pin['bytes'] == stream['bytes'] == stream['observed_bytes'] == stream['final_bytes'] and + type(stream['discarded_bytes']) is int and stream['discarded_bytes'] == 0 and + stream['overflow'] is False and stream['write_uncertain'] is False and + stream['eof'] is True and pin['sha256'] == stream['sha256'], + 'complete exact-limit/EOF/partial-write raw relay custody') + pins.append(pin) + return pins + + +def validate_terminal(kernel, case, layout, runner_receipt, supervision): + """Validate only after real process cleanup; retain every raw original error. + + This is observational validation, not financial CLOSE, S10.03 acceptance, + installed-image qualification, a compatibility flag or an execution grant. + """ + mode = case['job'] + kernel.need(type(mode) is str and mode in SELECTIONS and + case == case_for(mode, case['stage_sha256']), 'exact full case inverse') + selected = SELECTIONS[mode] + stage = STAGE_BASE / selected[0] + declared, stage_pin = kernel.read_json(stage / 'STAGE.json', 1048576, 0o444) + common='integration/candidate_entry.py' in declared['files'] + if common: common_entry_binding(kernel,case,layout,declared,runner_receipt) + kernel.need(stage_pin['sha256'] == case['stage_sha256'] and + (common or runner_receipt['command'] == command_for(stage, declared, mode, job_for(mode), layout.science_root)), + 'actual full terminal command/source differs') + cleanup = supervision['cleanup'] + kernel.need(type(supervision['returncode']) is int and supervision['returncode'] == (1 if common and selected[5] else 0) and + supervision['failure'] is None and + cleanup['complete'] is True and cleanup['group_empty_proved'] is True and + cleanup['remaining'] == [] and cleanup['observed_after_root_exit'] == [] and + cleanup['reaped_adopted'] == [], 'genuine post-root terminal cleanup required') + kernel.need(runner_receipt['status'] == ('STOP' if common and selected[5] else 'PASS') and + type(runner_receipt['exit']) is int and runner_receipt['exit'] == (1 if selected[5] else 0) and + runner_receipt['termination'] is None and + runner_receipt['source_bytes_and_modes_unchanged'] is True and + runner_receipt['retained_log_bytes_stable'] is True, + 'later failure or uncertain native terminal state defeats earlier science receipt') + closure, closure_pin = kernel.read_json(layout.runner_root / 'WRITER-CLOSURE.json', 65536, 0o444 if common else 0o600) + kernel.exact(closure, ('schema','launch_entered','launch_returned','wait_known','stdio_aliases_closed', + 'process_group_empty','usage_inode_retired','local_holders_closed', + 'domain_reconciliation_required','relay','error_type')) + kernel.need(closure['schema'] == 'h25-runner-native-writer-closure-v2' and + closure['launch_entered'] is True and closure['launch_returned'] is True and + closure['wait_known'] is True and closure['stdio_aliases_closed'] is True and + closure['process_group_empty'] is (False if common else True) and closure['usage_inode_retired'] is True and + closure['local_holders_closed'] is True and closure['domain_reconciliation_required'] is True and + closure['relay']['all_descriptors_known_closed'] is True and + closure['relay']['eof_complete'] is True and closure['relay']['overflow'] is False and + closure['relay']['raw_error_present'] is False and + closure['error_type'] is None, 'genuine all-holder closure after original cleanup') + _relay(kernel, closure['relay'], [layout.runner_root / 'stdout.txt',layout.runner_root / 'stderr.txt']) + _relay(kernel, supervision['outer_relay'], + [layout.supervision_root / 'root.stdout.raw',layout.supervision_root / 'root.stderr.raw']) + raw_logs = {} + for stream in ('stdout', 'stderr'): + pin, raw = kernel.IO.read(layout.runner_root / (stream + '.txt'), 2097152, 0o600, + materialize=selected[5] and stream == 'stderr') + kernel.need(pin['sha256'] == runner_receipt[stream + '_sha256'] and + pin['bytes'] == runner_receipt[stream + '_bytes'] == runner_receipt[stream + '_final_bytes'], + 'actual retained complete original stream differs') + raw_logs[stream] = pin + if selected[5] and stream == 'stderr': + kernel.need(type(raw) is bytes and raw.startswith(b'Traceback (most recent call last):\n') and + raw.endswith(REFUSAL) and b'_epoch_sc4_full_entry' in raw and + b'STOP evidence write failed:' not in raw, + 'original optimized full-entry refusal and raw traceback required') + if selected[5]: + kernel.need(not (layout.science_root / 'receipt.json').exists() and + not (layout.science_root / 'STOP.json').exists() and raw_logs['stdout']['bytes'] == 0, + 'optimized full entry remains original refusal, never positive science') + return {'schema': 'full-caller-terminal-observation-v1', 'role': selected[4], + 'status': 'ORIGINAL_OPTIMIZED_FULL_ENTRY_REFUSAL_OBSERVED', + 'raw_logs': raw_logs, 'writer_closure': closure_pin, + 'whole_outer_complete': False, 'original_retention_and_known_owner_release_still_required': True, + 'execution_permission': False, 'financial_close_issued': False} + kernel.need(raw_logs['stderr']['bytes'] == 0 and not (layout.science_root / 'STOP.json').exists(), + 'full positive retains every original error and STOP refusal') + receipt, receipt_pin = kernel.read_json(layout.science_root / 'receipt.json', 4194304) + anchor, anchor_pin = kernel.read_json(stage / 'baseline/anchor.json', 65536, 0o444) + kernel.need(receipt['status'] == 'FULL_NETWORK_COMPLETE_PASS' and receipt['mode'] == 'candidate' and + receipt['lanes'] == 'candidate' and receipt['driver_sha256'] == selected[3] and + receipt['data_handling']['full_caller_run'] is True and receipt['data_handling']['arm'] == 'candidate' and + receipt['science'] == anchor['science'] and + receipt['reference_driver_sha256'] == anchor['driver_sha256'] and + receipt['source_pin_sha256'] == anchor['source_pin_sha256'], + 'complete original scientific/full-image/anchor disposition required') + science, files = anchor['science'], {} + for relative, expected in ( + ('runtime-root/certificates/complex-network.json', science['full_cli_certificate_sha256']), + ('original-stdout.txt', science['full_cli_stdout_sha256']), + ('full-return.lossless.json', science['full_return_lossless_sha256'])): + files[relative] = _artifact(kernel, layout.science_root / relative, expected) + side = science['side'] + for name, key, count in (('result.json', 'result_sha256', 'result'), + ('witness.json', 'exact_witness_sha256', 'witness'), + ('rank-trace.json', 'rank_trace_sha256', 'rank_trace')): + relative = 'side-observations/' + name + files[relative] = _artifact(kernel, layout.science_root / relative, side[key], side['serialized_bytes'][count]) + complement, complement_pin = kernel.read_json(layout.science_root / 'complement-transcript.json', 65536) + kernel.need(complement == science['ordered_complements'], 'exact ordered complement observations') + kernel.need(kernel.IO.read(layout.science_root / 'receipt.json', 4194304)[0] == receipt_pin, + 'full receipt changed across terminal scientific verification') + return {'schema': 'full-caller-terminal-observation-v1', 'role': selected[4], + 'status': 'ORIGINAL_FULL_CANDIDATE_TERMINAL_OBSERVED', 'receipt': receipt_pin, + 'anchor': anchor_pin, 'scientific_files': files, 'complement': complement_pin, + 'raw_logs': raw_logs, 'writer_closure': closure_pin, + 'original_live_SC4_disposition_required_before_zero_exit': True, + 'whole_outer_complete': False, 'original_retention_and_known_owner_release_still_required': True, + 'execution_permission': False, 'financial_close_issued': False} diff --git a/research/h25-parent-waiting-entry/implementation/source/run_guarded_v3.py b/research/h25-parent-waiting-entry/implementation/source/run_guarded_v3.py new file mode 100644 index 0000000000..685f7c7833 --- /dev/null +++ b/research/h25-parent-waiting-entry/implementation/source/run_guarded_v3.py @@ -0,0 +1,410 @@ +# Modified 2026-11-07: Clear1nsight, with OpenAI Codex and ChatGPT Pro assistance. See NOTICE.md. +#!/usr/bin/env python3 +"""Parent-only immutable-stage runner; explicit clean no-site launch, fixed hash seed.""" +import argparse +import fcntl +import hashlib +import json +import os +from pathlib import Path +import platform +import resource +import signal +import stat +import subprocess +import sys +import time + +HERE = Path('/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/caller-proof-completion-20261107T0155Z/implementation/bindings') +# Reviewed path substitution. This remains the complete registered attempt union. +SOURCE_ROOT = Path('/home/d3lerium/.codex/.chatgpt-projects/g-p-6ad5817fd84881918865926b6fd51453/outputs/caller-proof-completion-20261107T0155Z/runtime/completed-source/IndependentPrefixDATAComposedV1') +TIMEOUT = 180 +RSS_CAP = 1024 ** 3 +OUTPUT_CAP = 2 * 1024 ** 2 +TOTAL_CAP = 2400 +LOG_CHUNK_BYTES = 64 * 1024 +USAGE_METADATA_CAP = 16 * 1024 + +# This is a trusted parent launch contract, not Python self-authentication or -I. +# -P suppresses unsafe path insertion; -S/-s prevent site and user-site loading. +# Unlike -I, this preserves the explicitly whitelisted fixed hash seed. +LAUNCH_FLAGS = ('-S', '-s', '-P', '-B') +LAUNCH_ENV = {'PATH': '/usr/bin:/bin', 'PYTHONHASHSEED': '0', + 'LANG': 'C.UTF-8', 'LC_ALL': 'C.UTF-8', 'TZ': 'UTC', + 'PYTHONDONTWRITEBYTECODE': '1'} + + +def require_trusted_launch(): + if not (sys.flags.no_site == 1 and sys.flags.no_user_site == 1 and + sys.flags.safe_path and sys.flags.dont_write_bytecode == 1 and + sys.flags.ignore_environment == 0 and sys.flags.isolated == 0 and + sys.flags.hash_randomization == 0): + raise ValueError('Explicit no-site/safe-path parent launch required') + if dict(os.environ) != LAUNCH_ENV: + raise ValueError('Exact clean parent environment required') + if sys.executable != '/usr/bin/python3.12': + raise ValueError('Absolute admitted interpreter required') + if tuple(sys.path) != ('/usr/lib/python312.zip', '/usr/lib/python3.12', + '/usr/lib/python3.12/lib-dynload'): + raise ValueError('Unadmitted ordered initial Python search path') + return {'contract': 'trusted-clean-nosite-safe-path-fixedseed-v1', + 'no_site': sys.flags.no_site, 'no_user_site': sys.flags.no_user_site, + 'safe_path': bool(sys.flags.safe_path), + 'ignore_environment': sys.flags.ignore_environment, + 'isolated': sys.flags.isolated, 'hash_seed_environment': '0', + 'hash_randomization': sys.flags.hash_randomization, + 'initial_sys_path': list(sys.path), 'environment': dict(os.environ), + 'trust_boundary': 'Authenticated parent launcher, OS, interpreter and system stdlib before this module; no Python self-authentication claim'} + + +def digest(raw): + return hashlib.sha256(raw).hexdigest() + + +def inventory(stage): + rows = {} + for path in sorted(stage.rglob('*')): + if path.is_symlink(): + raise ValueError('Symlink in immutable stage') + if path.is_file() and path.name != 'STAGE.json': + rows[str(path.relative_to(stage))] = { + 'sha256': digest(path.read_bytes()), + 'mode': path.stat().st_mode & 0o777, + } + return rows + + +def group_rss(group): + total = 0 + for path in Path('/proc').iterdir(): + if not path.name.isdigit(): + continue + try: + raw = (path / 'stat').read_text() + fields = raw[raw.rfind(')') + 2:].split() + if int(fields[2]) == group: + total += int(fields[21]) * os.sysconf('SC_PAGE_SIZE') + except (FileNotFoundError, ProcessLookupError, PermissionError): + pass + return total + + +def log_identity(value): + """Exclude atime: our own read may change it.""" + return (value.st_dev, value.st_ino, value.st_mode, value.st_size, + value.st_mtime_ns, value.st_ctime_ns) + + +def stream_log(path): + """Hash a finite snapshot in bounded memory, failing closed on file drift. + + A stable record covers every byte of the retained file. An unstable record + describes only the bytes actually hashed and cannot support a PASS. Reading + at most the initial length also prevents a growing file prolonging hashing. + """ + path_before = path.stat(follow_symlinks=False) + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + with os.fdopen(fd, 'rb', buffering=0) as stream: + before = os.fstat(stream.fileno()) + if not stat.S_ISREG(before.st_mode): + raise ValueError('Retained log must be a regular file') + hasher = hashlib.sha256() + count = 0 + while count < before.st_size: + block = stream.read(min(LOG_CHUNK_BYTES, before.st_size - count)) + if not block: + break + hasher.update(block) + count += len(block) + after = os.fstat(stream.fileno()) + path_after = path.stat(follow_symlinks=False) + stable = (log_identity(path_before) == log_identity(before) == + log_identity(after) == log_identity(path_after) and + count == before.st_size) + return {'sha256': hasher.hexdigest(), 'bytes': count, + 'snapshot_bytes': before.st_size, 'final_bytes': path_after.st_size, + 'stable': stable} + + +def finalize_logs(folder, stop): + """Check sizes before any log read, stream complete stable evidence, recheck.""" + paths = [folder / 'stdout.txt', folder / 'stderr.txt'] + before = [path.stat(follow_symlinks=False) for path in paths] + cap_seen = 'process_monitor' if stop == 'output_cap' else None + if max(value.st_size for value in before) > OUTPUT_CAP: + stop = stop or 'output_cap' + cap_seen = cap_seen or 'before_stream_hash' + records = [stream_log(path) for path in paths] + final = [path.stat(follow_symlinks=False) for path in paths] + if max(value.st_size for value in final) > OUTPUT_CAP: + stop = stop or 'output_cap' + cap_seen = cap_seen or 'after_stream_hash' + for initial, record, ending in zip(before, records, final): + record['final_bytes'] = ending.st_size + record['stable'] = (record['stable'] and + log_identity(initial) == log_identity(ending) and + record['bytes'] == ending.st_size) + if not all(record['stable'] for record in records): + stop = stop or 'output_changed_during_hash' + return records[0], records[1], stop, cap_seen + + +def read_usage(path): + """The time tool's small diagnostic must not reintroduce an unbounded read.""" + if not path.exists(): + return None, False + size = path.stat().st_size + if size > USAGE_METADATA_CAP: + return {'raw_omitted': True, 'bytes': size}, True + with path.open('rb') as stream: + raw = stream.read(USAGE_METADATA_CAP + 1) + if len(raw) > USAGE_METADATA_CAP or path.stat().st_size > USAGE_METADATA_CAP: + return {'raw_omitted': True, 'bytes': path.stat().st_size}, True + try: + return json.loads(raw), False + except (json.JSONDecodeError, UnicodeDecodeError): + return {'raw': raw.decode('utf-8', errors='replace')}, False + + +def read_waiting_configuration(path, expected_sha): + """Read parent-created DATA, never restore its capability or release a child.""" + path = Path(path) + if (not path.is_absolute() or path.resolve(strict=True) != path or + type(expected_sha) is not str or len(expected_sha) != 64 or + any(c not in '0123456789abcdef' for c in expected_sha)): + raise ValueError('Exact canonical waiting configuration and digest required') + identity = lambda q: (q.st_dev,q.st_ino,q.st_mode,q.st_uid,q.st_nlink,q.st_size,q.st_mtime_ns,q.st_ctime_ns) + before = path.lstat() + if (not stat.S_ISREG(before.st_mode) or stat.S_IMODE(before.st_mode) != 0o444 or + before.st_uid != os.getuid() or before.st_nlink != 1 or not 0 < before.st_size <= 16384): + raise ValueError('Owned immutable bounded waiting configuration required') + fd = None + primary = secondary = None + raw = None + try: + fd = os.open(path,os.O_RDONLY|os.O_NOFOLLOW|os.O_NONBLOCK|os.O_CLOEXEC) + if identity(os.fstat(fd)) != identity(before): + raise ValueError('Waiting configuration opened identity') + blocks, count = [], 0 + while True: + block = os.read(fd,min(65536,before.st_size+1-count)) + if not block: + break + blocks.append(block); count += len(block) + if count > before.st_size: + raise ValueError('Waiting configuration extra byte') + raw = b''.join(blocks) + if (len(raw) != before.st_size or digest(raw) != expected_sha or + identity(os.fstat(fd)) != identity(before) or identity(path.lstat()) != identity(before)): + raise ValueError('Waiting configuration exact stable readback') + except BaseException as error: + primary = error + finally: + if fd is not None: + owned, fd = fd, None + try: + os.close(owned) + except BaseException as error: + secondary = error + if primary is not None: + if secondary is not None: + raise primary from secondary + raise primary + if secondary is not None: + raise secondary + def pairs(items): + result = {} + for key,value in items: + if key in result: + raise ValueError('Duplicate waiting configuration key') + result[key] = value + return result + def no_number(value): + raise ValueError('Waiting configuration forbids floating/nonfinite numbers') + value = json.loads(raw.decode('ascii'),object_pairs_hook=pairs,parse_float=no_number,parse_constant=no_number) + if type(value) is not dict or value.get('schema') != 'h25-waiting-entry-config-v1': + raise ValueError('Exact waiting configuration schema') + return value + + +def main(): + launch = require_trusted_launch() + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('stage') + parser.add_argument('job') + parser.add_argument('label') + parser.add_argument('--waiting-config') + parser.add_argument('--waiting-sha256') + args = parser.parse_args() + for value in (args.stage, args.job, args.label): + if not value or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_' for c in value): + raise ValueError('Simple immutable stage/job/run names required') + runner_start = time.monotonic() + runner_usage_start = resource.getrusage(resource.RUSAGE_SELF) + (HERE / 'runtime').mkdir(exist_ok=True) + # A single parent owns this round; never wait behind another scientific run. + with (HERE / 'runtime/science.lock').open('a') as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + stage = HERE / 'stages' / args.stage + stage_raw = (stage / 'STAGE.json').read_bytes() + declared = json.loads(stage_raw) + before = inventory(stage) + if before != declared['files']: + raise ValueError('Stage bytes/modes differ from declared closure') + jobs = json.loads((stage / 'JOBS.json').read_bytes()) + job = jobs[args.job] + phase_raw = (HERE / 'control/EXECUTION-PHASE.json').read_bytes() + phase = json.loads(phase_raw) + cap = phase['aggregate_cap_seconds'] + if type(cap) is not int or cap not in (600, TOTAL_CAP): + raise ValueError('Unrecognized parent budget phase') + candidate_entry = job.get('entry') == 'integration/candidate_entry.py' + waiting = None + if candidate_entry: + if not args.waiting_config or not args.waiting_sha256: + raise ValueError('Candidate waiting configuration required') + waiting = read_waiting_configuration(args.waiting_config,args.waiting_sha256) + expected_case = SOURCE_ROOT / args.label + expected_layout = waiting.get('completed_layout') + if (waiting.get('case_id') != args.label or waiting.get('job') != args.job or + waiting.get('stage_path') != str(stage) or waiting.get('stage_sha256') != digest(stage_raw) or + waiting.get('runner_path') != str(Path(__file__).resolve()) or + waiting.get('runner_sha256') != declared['runner_sha256'] or + waiting.get('entry_sha256') != declared['files']['integration/candidate_entry.py']['sha256'] or + waiting.get('outer_output') != str(expected_case/'runner/artifact/science') or + type(expected_layout) is not dict or expected_layout.get('case_container') != str(expected_case) or + expected_layout.get('runner_root') != str(expected_case/'runner') or + Path(args.waiting_config) != expected_case/'supervision/WAIT.json'): + raise ValueError('Exact registered candidate waiting inverse') + elif args.waiting_config is not None or args.waiting_sha256 is not None: + raise ValueError('Waiting configuration belongs only to the candidate entry') + runs = SOURCE_ROOT + runs.mkdir(exist_ok=True) + spent = 0.0 + for run in runs.iterdir(): + if not run.is_dir(): + continue + # The current case is genuinely reserved before birth. Its exact + # WAIT binding permits only this one pre-launch absence. + if candidate_entry and run == SOURCE_ROOT/args.label: + if (run/'runner').exists() or (run/'runner').is_symlink(): + raise ValueError('Current registered runner must still be absent') + continue + receipt_path = run / 'runner/receipt.json' + if not receipt_path.exists(): + raise ValueError('Unclosed prior attempt: preserve and reconcile before another run') + prior = json.loads(receipt_path.read_bytes()) + spent += prior.get('runner_wall_seconds', prior['wall_seconds']) + if spent >= cap: + raise ValueError('Aggregate budget consumed') + if 'entry' in job: + entry = job['entry'] + if (type(entry) is not str or entry not in ('integration/predecessor_entry.py','integration/candidate_entry.py') or + 'bootstrap' in job or entry not in declared['files'] or + (stage / entry).is_symlink() or + (stage / entry).resolve() != stage.resolve() / entry): + raise ValueError('Entry must be the declared canonical predecessor file without bootstrap') + folder = runs / args.label / 'runner' + folder.mkdir() + runner_before = Path(__file__).read_bytes() + if digest(runner_before) != declared['runner_sha256']: + raise ValueError('Actual runner differs from frozen runner source') + fraction_path = Path('/usr/lib/python3.12/fractions.py') + fractions_before = fraction_path.read_bytes() + env = dict(LAUNCH_ENV) + command = ['/usr/bin/python3.12', *LAUNCH_FLAGS] + if job.get('optimized', False): + command.append('-O') + if 'entry' in job: + command.append(str(stage / entry)) + else: + command.append(str(stage / 'integration/full_driver.py')) + if 'bootstrap' in job: + bootstrap = job['bootstrap'] + if type(bootstrap) is not dict or set(bootstrap) != {'provider', 'driver'}: + raise ValueError('Exact bootstrap map required') + for relative in bootstrap.values(): + if (type(relative) is not str or relative not in declared['files'] or + Path(relative).is_absolute() or '..' in Path(relative).parts or + Path(relative).parent != Path('integration')): + raise ValueError('Bootstrap source must be a declared integration file') + command.extend(['--root-sha256', declared['files']['integration/full_driver.py']['sha256'], + '--provider', str(stage / bootstrap['provider']), + declared['files'][bootstrap['provider']]['sha256'], + '--driver', str(stage / bootstrap['driver']), + declared['files'][bootstrap['driver']]['sha256'], + '--integration', str(stage / 'integration'), '--']) + command.extend(['--output', str(folder / 'artifact/science'), '--lanes', job['lanes']]) + if candidate_entry: + if job.get('finite_only',False) or job.get('lanes') != 'candidate': + raise ValueError('Complete candidate entry cannot select finite science') + command.extend(['--waiting-config',args.waiting_config,'--waiting-sha256',args.waiting_sha256]) + if job.get('finite_only', False): + command.append('--finite-only') + usage = folder / 'usage.json' + timed = ['/usr/bin/time', '-f', '{"user_seconds":%U,"system_seconds":%S,"kernel_max_rss_kib":%M,"exit":%x}', '-o', str(usage), '--', *command] + started = {'command': command, 'parent_launch': launch, 'stage_sha256': digest(stage_raw), + 'runner_sha256': digest(runner_before), 'fractions_sha256': digest(fractions_before), + 'budget_phase_sha256': digest(phase_raw), 'spent_before_seconds': spent, + 'phase_cap_seconds': cap, 'job': args.job, 'label': args.label} + (folder / 'START.json').write_text(json.dumps(started, indent=2, sort_keys=True) + '\n') + start = time.monotonic() + stop = None + peak = 0 + with (folder / 'stdout.txt').open('wb') as out, (folder / 'stderr.txt').open('wb') as err: + process = subprocess.Popen(timed, cwd=stage, env=env, stdout=out, stderr=err, start_new_session=True) + try: + while process.poll() is None: + peak = max(peak, group_rss(process.pid)) + if peak > RSS_CAP: + stop = 'sampled_group_rss_cap' + elif time.monotonic() - runner_start > min(TIMEOUT, cap - spent): + stop = 'wall_or_aggregate_cap' + elif max((folder / 'stdout.txt').stat().st_size, (folder / 'stderr.txt').stat().st_size) > OUTPUT_CAP: + stop = 'output_cap' + if stop: + os.killpg(process.pid, signal.SIGKILL) + break + time.sleep(0.05) + code = process.wait() + finally: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + elapsed = time.monotonic() - start + stdout, stderr, stop, cap_seen = finalize_logs(folder, stop) + measurement, oversized_usage = read_usage(usage) + if oversized_usage: + stop = stop or 'usage_metadata_cap' + unchanged = (inventory(stage) == before and (stage / 'STAGE.json').read_bytes() == stage_raw and + Path(__file__).read_bytes() == runner_before and fraction_path.read_bytes() == fractions_before) + runner_elapsed = time.monotonic() - runner_start + runner_usage_end = resource.getrusage(resource.RUSAGE_SELF) + if runner_elapsed > min(TIMEOUT, cap - spent): + stop = stop or 'wall_or_aggregate_cap' + if runner_usage_end.ru_maxrss * 1024 > RSS_CAP: + stop = stop or 'runner_rss_cap' + receipt = dict(started, exit=code, wall_seconds=elapsed, usage=measurement, + termination=stop, sampled_process_group_rss_bytes=peak, + source_bytes_and_modes_unchanged=unchanged, + stdout_sha256=stdout['sha256'], stdout_bytes=stdout['bytes'], + stderr_sha256=stderr['sha256'], stderr_bytes=stderr['bytes'], + stdout_final_bytes=stdout['final_bytes'], stderr_final_bytes=stderr['final_bytes'], + retained_log_bytes_stable=stdout['stable'] and stderr['stable'], + output_cap_observed_at=cap_seen, log_read_chunk_bytes=LOG_CHUNK_BYTES, + runner_wall_seconds=runner_elapsed, + runner_user_seconds=runner_usage_end.ru_utime - runner_usage_start.ru_utime, + runner_system_seconds=runner_usage_end.ru_stime - runner_usage_start.ru_stime, + runner_lifetime_max_rss_kib=runner_usage_end.ru_maxrss, + python=sys.version, platform=platform.platform(), + status='PASS' if code == 0 and stop is None and stderr['bytes'] == 0 and unchanged else 'STOP') + (folder / 'receipt.json').write_text(json.dumps(receipt, indent=2, sort_keys=True) + '\n') + print(json.dumps(receipt, sort_keys=True), flush=True) + if receipt['status'] != 'PASS': + raise SystemExit(1) + + +if __name__ == '__main__': + main() diff --git a/research/h25-parent-waiting-entry/review/PRO-REVIEW-DISPOSITION.md b/research/h25-parent-waiting-entry/review/PRO-REVIEW-DISPOSITION.md new file mode 100644 index 0000000000..82c23ad2bf --- /dev/null +++ b/research/h25-parent-waiting-entry/review/PRO-REVIEW-DISPOSITION.md @@ -0,0 +1,9 @@ +# Bounded source review disposition + +ChatGPT Pro, verified mode 5 of 5, reviewed initial commit c99f97f652d39c2eedd1bffa3fb3aabaa29d3b93 in the existing consultation. Its completed answer identified first-error custody loss when DeadlineOwner.pop raises during query/root unwind. The working-body exception had not yet reached the enclosing capture. + +The corrected source records the raw primary before timer unwind. pop_deadline_preserving records a pop failure after it and rethrows that failure only when no earlier primary exists. controls-v8 executes the actual production inner try/except/finally nodes for both run_property_query and run_root, replacing only the working body by an injected original error. Actual DeadlineOwner.pop expires with inert clock/signal ports. Both cases retain and raise the identical original OSError, followed by the ExecutionDeadline secondary. This test passed locally; it is not a native caller or independent source qualification. + +Pro found no premature-release counterexample in the spans it inspected and no envelope exit 125 as original refusal exit 1 acceptance. It supported the intended query ownership separation but explicitly did not give a complete birth/race/retirement proof. It did not complete relay, all loader/bootstrap authentication, external-dependency or whole-assembly review. The correction itself was locally assessed and tested after that answer; it was not sent for a second Pro review. + +The original full caller, actual source assembly, environment, funding and execution gates remain open. The scope is a reviewable source archive and bounded controls, with no scientific or original-activity credit. diff --git a/research/h25-parent-waiting-entry/validation/test_unwind.py b/research/h25-parent-waiting-entry/validation/test_unwind.py new file mode 100644 index 0000000000..c6a5a3b550 --- /dev/null +++ b/research/h25-parent-waiting-entry/validation/test_unwind.py @@ -0,0 +1,21 @@ +import ast,copy,importlib.util,types,unittest +from pathlib import Path +p=Path(__file__).resolve().parents[1]/'implementation/source/fresh_supervisor.py' +spec=importlib.util.spec_from_file_location('subject',p);S=importlib.util.module_from_spec(spec);spec.loader.exec_module(S) +class Collision(unittest.TestCase): + def test_real_query_and_root_unwind_collision(self): + tree=ast.parse(p.read_bytes());binding=next(n for n in tree.body if isinstance(n,ast.FunctionDef) and n.name=='bind_active_run_root') + for name in ('run_property_query','run_root'): + with self.subTest(caller=name): + fn=next(n for n in binding.body if isinstance(n,ast.FunctionDef) and n.name==name) + node=next(n for n in ast.walk(fn) if isinstance(n,ast.Try) and n.finalbody and any(isinstance(x,ast.Call) and isinstance(x.func,ast.Name) and x.func.id=='pop_deadline_preserving' for st in n.finalbody for x in ast.walk(st))) + primary=OSError('body failed');seen=[];token=object();clock=types.SimpleNamespace(monotonic_ns=lambda:0);oldtime,oldsignal=S.time,S.signal + S.time=clock;S.signal=types.SimpleNamespace(SIGALRM=14,ITIMER_REAL=0,setitimer=lambda *a:None) + try: + owner=S.DeadlineOwner(100);owner.started=True;owner.stack=[(token,80)];clock.monotonic_ns=lambda:200 + ns=dict(vars(S));ns.update(primary=primary,first=None,first_error=None,query_row={},custody=types.SimpleNamespace(remember=seen.append),registry=types.SimpleNamespace(capture_error=lambda a,e:seen.append(e)),attempt=object(),state={'deadlines':{'case':owner}},case_id='case',query_deadline_token=token,root_deadline_token=token,deadline_owner=owner) + changed=copy.deepcopy(node);changed.body=[ast.Raise(exc=ast.Name(id='primary',ctx=ast.Load()),cause=None)] + with self.assertRaises(OSError) as caught:exec(compile(ast.fix_missing_locations(ast.Module(body=[changed],type_ignores=[])),str(p),'exec'),ns) + self.assertIs(caught.exception,primary);self.assertIs(seen[0],primary);self.assertIsInstance(seen[1],S.ExecutionDeadline);self.assertEqual(len(seen),2) + finally:S.time,S.signal=oldtime,oldsignal +if __name__=='__main__':unittest.main(verbosity=2) diff --git a/research/h25-parent-waiting-entry/validation/test_waiting_boundary.py b/research/h25-parent-waiting-entry/validation/test_waiting_boundary.py new file mode 100644 index 0000000000..ed1df3bca1 --- /dev/null +++ b/research/h25-parent-waiting-entry/validation/test_waiting_boundary.py @@ -0,0 +1,222 @@ +"""Standalone changed-boundary fixtures, not original caller/native admission. + +The new production modules and private qualification body execute unchanged. +Context/association/schema/funding ports here are explicitly inert fixtures. +Real owned R -> GNU-time -> waiting-entry generations and a query subtree use +actual pidfds. No original scientific driver, compiler, native view entry or +property observer runs. The terminal child is the installed /usr/bin/false. +""" +import ast +import ctypes +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import resource +import signal +import subprocess +import sys +import tempfile +import time +import types +import unittest +from contextlib import contextmanager + +@contextmanager +def retained_directory(*args,**kwargs): + yield tempfile.mkdtemp(*args,**kwargs) + +D=Path(__file__).resolve().parents[1] +SOURCE=D/'implementation/source' +ENV={'PATH':'/usr/bin:/bin','PYTHONHASHSEED':'0','LANG':'C.UTF-8','LC_ALL':'C.UTF-8','TZ':'UTC','PYTHONDONTWRITEBYTECODE':'1'} +FLAGS=['-S','-s','-P','-B'] + +def module(name,path): + spec=importlib.util.spec_from_file_location(name,path);value=importlib.util.module_from_spec(spec);spec.loader.exec_module(value);return value +S=module('fixture_subject_supervisor',SOURCE/'fresh_supervisor.py') +B=module('fixture_subject_relay',SOURCE/'bounded_relay.py') + +def sha(raw): return hashlib.sha256(raw).hexdigest() +def pin(path): + raw=Path(path).read_bytes();return {'path':str(path),'bytes':len(raw),'sha256':sha(raw),'mode':0o444} +def frozen(path,value): + path.parent.mkdir(parents=True,exist_ok=True);path.write_text(json.dumps(value,sort_keys=True)+'\n');path.chmod(0o444);return pin(path) + +def private_function(name,env): + tree=ast.parse((SOURCE/'fresh_supervisor.py').read_text());owner=next(n for n in tree.body if isinstance(n,ast.FunctionDef) and n.name=='bind_active_run_root') + node=next(n for n in owner.body if isinstance(n,ast.FunctionDef) and n.name==name) + ns=dict(vars(S));ns.update(env);exec(compile(ast.fix_missing_locations(ast.Module(body=[node],type_ignores=[])),str(SOURCE/'fresh_supervisor.py'),'exec'),ns);return ns[name] + +class Registry: + def __init__(self,attempt): self.a=attempt;self.errors=[] + def attempt(self,label): assert label==self.a.label;return self.a + def capture_error(self,a,error): + if a.error is None:a.error=error + self.errors.append(error) + def mark_uncertain(self,a,message):a.uncertain.append(message) + def synchronous_writer(self,a,role,path): + r={'attempt':a,'kind':'writer-permit','role':role,'path':path,'state':'OWNED','primary':None};a.resources.append(r);return r + def required_writer_closed(self,a,role):assert a.required[role] is False;a.required[role]=True + def fd_pending(self,a,role): + r={'attempt':a,'kind':'fd','role':role,'object':None,'state':'PENDING'};a.resources.append(r);return r + def fd_acquired(self,r,fd):r.update(object=fd,state='OWNED') + def fd_not_entered(self,r):r['state']='NOT_ENTERED' + def fd_unknown(self,r,error):r.update(state='UNKNOWN',primary=error);self.errors.append(error) + def fd_close(self,r): + fd=r['object'];r.update(object=None,state='CLOSING') + try:os.close(fd) + except BaseException as error:r.update(state='UNKNOWN',secondary=error);raise + r['state']='CLOSED' + def poll_root(self,p):return p.poll() + +class FixtureIO: + def __init__(self,fail_path=None):self.fail_path=fail_path;self.primary=OSError('deliberate retained readback failure');self.events=[];self.slots=[] + def call(self,operation,path,*args,**kw): + self.events.append((operation,str(path) if isinstance(path,Path) else 'fd')) + if operation=='write': + raw=(json.dumps(args[0],sort_keys=True,separators=(',',':'))+'\n').encode();fd=os.open(path,os.O_CREAT|os.O_EXCL|os.O_WRONLY,0o600) + try: + view=memoryview(raw) + while view:n=os.write(fd,view);view=view[n:] + os.fsync(fd) + finally:os.close(fd) + return {'path':str(path),'bytes':len(raw),'sha256':sha(raw),'identity':S.identity(path.stat())} + if operation=='acquire': + slot=[os.open(path,args[0]),'OWNED'];self.slots.append(slot);return slot + if operation=='close': + slot=path;fd=slot[0];slot[:]=[None,'CLOSING'];os.close(fd);slot[1]='CLOSED';return + if operation=='read': + if path==self.fail_path:raise self.primary + raw=path.read_bytes();return {'path':str(path),'bytes':len(raw),'sha256':sha(raw),'identity':S.identity(path.stat())},raw + raise AssertionError(operation) + +class Boundary(unittest.TestCase): + @classmethod + def setUpClass(cls): + # Process-local fixture subreaper only, in the guarded test process. + libc=ctypes.CDLL(None,use_errno=True) + if libc.prctl(36,1,0,0,0)!=0:raise OSError(ctypes.get_errno(),'fixture subreaper') + cls.libc=libc + def exercise(self,failed_record=None): + with retained_directory(prefix='connected-',dir=D/'validation/tmp') as temporary: + root=Path(temporary);os.chmod(root,0o700);stage=root/'stages/fixture';stage.mkdir(parents=True) + entry=stage/'integration/candidate_entry.py';entry.parent.mkdir();entry.write_bytes((SOURCE/'candidate_entry.py').read_bytes());entry.chmod(0o444) + cases=root/'cases';cases.mkdir();case=cases/'FixtureN';case.mkdir(mode=0o700) + supervision=case/'supervision';supervision.mkdir(mode=0o700);(case/'intent').mkdir(mode=0o700) + layout=types.SimpleNamespace(case_root=case,supervision_root=supervision,runner_root=case/'runner',science_root=case/'runner/artifact/science',intent_path=case/'intent/INTENT.json') + attempt=types.SimpleNamespace(label='FixtureN',layout=layout,resources=[],required={'intent':False},uncertain=[],error=None) + reg=Registry(attempt);outer=B.BoundedRelay((supervision/'root.stdout.raw',supervision/'root.stderr.raw'),B.RegistryOwner(reg,attempt),'fixture-root') + # Only these two stage files form this inert, explicitly non-scientific fixture. + job={'normal':{'entry':'integration/candidate_entry.py','optimized':False,'lanes':'candidate','finite_only':False}} + frozen(stage/'JOBS.json',job) + declared={'runner_sha256':sha((SOURCE/'run_guarded_v3.py').read_bytes()),'files':{str(p.relative_to(stage)):{'sha256':sha(p.read_bytes()),'mode':0o444} for p in (entry,stage/'JOBS.json')}} + stage_pin=frozen(stage/'STAGE.json',declared);frozen(root/'control/EXECUTION-PHASE.json',{'aggregate_cap_seconds':600});(root/'runtime').mkdir() + native_source=root/'fixture-native-source.c';native_source.write_text('/* inert fixture, never compiled */\n');native_source.chmod(0o444) + receiver=root/'full_result_receiver.py';marker=case/'post-release-marker' + receiver.write_text('from pathlib import Path\ndef job_for(mode): return {"fixture":mode}\ndef command_for(*args):\n Path('+repr(str(marker))+').write_text("post-release reached")\n return ["/usr/bin/false"]\n');receiver.chmod(0o444) + # The host tools are owned by uid65534, which is deliberately outside + # the production source/image owner contract. Keep that contract; + # make byte-identical fixture-owned copies rather than weaken it. + bin_dir=root/'fixture-bin';bin_dir.mkdir() + for leaf in ('false','time'): + q=bin_dir/leaf;q.write_bytes((Path('/usr/bin')/leaf).read_bytes());q.chmod(0o755) + profile={} + for kind,path in [('entry',bin_dir/'false'),('time',bin_dir/'time')]: + p=pin(path);profile.update({kind+'_path':p['path'],kind+'_bytes':p['bytes'],kind+'_sha256':p['sha256']}) + profile.update(schema='joined-native-entry-profile-v1',source_sha256=sha(native_source.read_bytes())) + parent=S.proc(os.getpid());end=time.monotonic_ns()+8_000_000_000 + config={'schema':'h25-waiting-entry-config-v1','case_id':'FixtureN','job':'normal','stage_path':str(stage),'stage_sha256':stage_pin['sha256'], + 'runner_path':str(SOURCE/'run_guarded_v3.py'),'runner_sha256':declared['runner_sha256'],'entry_sha256':pin(entry)['sha256'],'entry_bytes':entry.stat().st_size, + 'outer_output':str(layout.science_root),'completed_layout':{'case_container':str(case),'runner_root':str(case/'runner'),'science_root':str(layout.science_root)}, + 'parent':[parent['pid'],parent['start_ticks']],'working_deadline_ns':end-2_000_000_000,'cleanup_deadline_ns':end-1_000_000_000,'native_source_path':str(native_source)} + io=FixtureIO(supervision/failed_record if failed_record=='RELEASE.json' else layout.intent_path if failed_record else None) + kernel=types.SimpleNamespace(identity=S.identity,remember=lambda e:reg.capture_error(attempt,e),IO_UNKNOWN=[False]) + write_intent=private_function('write_intent',{'io_call':io.call,'sync_dir':lambda p:None,'C':kernel}) + # The directory fsync is performed by the production sync_dir closure. + sync_dir=private_function('sync_dir',{'io_call':io.call,'C':kernel});write_intent=private_function('write_intent',{'io_call':io.call,'sync_dir':sync_dir,'C':kernel}) + wait_pin=write_intent(supervision/'WAIT.json',config) + domain=S.OwnedDomain(reg,attempt);outer.open();out,err=outer.writers();process=None;deadline=S.DeadlineOwner(end) + state={'owner_pid':os.getpid(),'run_context':None,'waiting':{'FixtureN':(config,wait_pin,None)},'pending_intents':{'FixtureN':{'schema':'fresh-active-nested-runner-intent-v2','label':'FixtureN','parent_pid':parent['pid'],'parent_start_ticks':parent['start_ticks'],'completed_layout':config['completed_layout']}},'deadlines':{'FixtureN':deadline},'protected':None,'phase':'ROOT_LAUNCH'} + observed={};query_processes=[] + class Association: + def observe(self,label): + protected=state['protected'];protected.verify();entry_before=S.proc(protected.entry_key[0]);selftest.assertIn(entry_before['state'],('T','t')) + qdomain=S.OwnedDomain(reg,attempt,protected=protected) + child_ready=case/'query-child.json' + program='import subprocess,time,pathlib; p=subprocess.Popen(["/usr/bin/python3.12","-c","import time;time.sleep(2)"]);pathlib.Path('+repr(str(child_ready))+').write_text(str(p.pid));time.sleep(2)' + q=subprocess.Popen(['/usr/bin/python3.12',*FLAGS,'-c',program],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True,env=ENV) + query_processes.append(q);row=S.proc(q.pid);qdomain.root=S.generation(row);qdomain.add(row) + until=time.monotonic()+1 + while not child_ready.exists() and time.monotonic()