aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
GitHub aien-dev/aien-sovereign-core-mv#727 (code only)
Fetch it
curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/0ff2f51e361c58b6.bundle -o 0ff2f51e361c58b6.bundle git fetch 0ff2f51e361c58b6.bundle refs/pull/727/head
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
727
84a1c6a33e7fdb7ab0dede2c2024ba4176744985
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":727,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/727","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:51Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.crumb b/.crumb index ca888b85..14fa897c 100644 --- a/.crumb +++ b/.crumb @@ -65,43 +65,43 @@ "children": [ { "digest": "e5a81587d398cafcc737337c51428c09697768967eea61386a6ab34f7f871903", - "last_commit": "20877670", + "last_commit": "e8cc3aa0", "name": "crates/aien-allen", "purpose": "ALLEN identity gate: resolve-only subject check, host pin record, deployment record (ADR 0035). " }, { "digest": "a6f60499665540ddd49ad3122d016232b15d9cc878cb68febb725cd711dfbb6d", - "last_commit": "20877670", + "last_commit": "e8cc3aa0", "name": "crates/aien-allen-memory", "purpose": "ALLEN scoped memory store: scopes enforced at recall, inspect/correct/export, key-destroying for" }, { "digest": "3b65ec8698bac001b1d2aef39c1fce13a3475280186147af40a319212ed76d42", - "last_commit": "20877670", + "last_commit": "e8cc3aa0", "name": "crates/aien-allen-profile", "purpose": "ALLEN persona profile v1: versioned, user-editable profile bound to the engaged ALLEN identity; " }, { "digest": "73b7b51a60981ac052f28b05a50071fb6846e6c3f7331d28786d220733f204c7", - "last_commit": "20877670", + "last_commit": "e8cc3aa0", "name": "crates/aien-cli", "purpose": "" }, { "digest": "246e54412a28d811dc38af14bb943890fbafd85f55864c2468a04e6ea698062e", - "last_commit": "20877670", + "last_commit": "e8cc3aa0", "name": "crates/aien-scheduler/src/bin", "purpose": "" }, { "digest": "34d1c3a8c38c4f75d9eca8e73f6d15418f2ffc3d129f99813d7adf9e80902659", - "last_commit": "20877670", + "last_commit": "e8cc3aa0", "name": "crates/spark-cockpit-rs", "purpose": "" }, { "digest": "20f3120e6d2067007c8e67dfd13a821a83f5a382e7e11a0eec22f2d9b6380971", - "last_commit": "20877670", + "last_commit": "e8cc3aa0", "name": "scripts", "purpose": "" }, @@ -112,21 +112,21 @@ "purpose": "" }, { - "digest": "598dc3bd4d60f47f79ccb3b42d5966be1ba921fdbb24f347ef6c998463a4da3a", - "last_commit": "20877670", + "digest": "e5e7271b10298838894bed570db8e039af89dc3063640b6da5d84d420534c7f6", + "last_commit": "af308364", "name": "tools/aien-local-ci", "purpose": "Local CI sandbox exec contract (C8), aien-run user/caches install, Forgejo trigger hook, health " } ], - "children_root": "sha256:0d89f72950a8f4e92fd5b1f360e7092d0b0fb9c28ff362b954b98c44cc053be4", - "compiled_at": "2026-10-24T04:21:21Z", + "children_root": "sha256:42dea8f42ecd7470f90f838092ee89e7e916ddc3005223c7b4589e17361dcfa9", + "compiled_at": "2026-10-24T04:35:35Z", "compiler": "crumb-compile/1", - "digest": "sha256:3b49c0a02cd350da72ac4576403a4ef924c11a4f4e238f165ac9b09806c979af", - "evidence_files": 1578, - "evidence_root": "sha256:301c3ce7bca14655fc023095434f2d2942ebdfa9b30d5757d88343925d633a4d", - "files": 5898, - "generated_at_commit": "358b7c2e23adb910f23fe4a1ed58981a9c401f72", - "source_tree": "sha256:303a5f99ad9ca6d260b8ad3d74a0d9e59dac0a49757e52c6185e4219fa6814a7" + "digest": "sha256:f6c552b27a1eb8e6de2dd377582bb730c4e9f1605b45932a8ff2f8b41d277527", + "evidence_files": 1579, + "evidence_root": "sha256:d4a2620df9ff37a1470c6cb1cec12d1e00a6768eda5fa324e27c93e12d3b1cf0", + "files": 5904, + "generated_at_commit": "af30836418a663ea06cdcf3a037e337fb2d8c5aa", + "source_tree": "sha256:be06effe7dffa27e18ca6bae8487511690fe1b7a386e11f99af05bb6b567fa85" } }, "history": [], diff --git a/crates/aien-runtime/tests/prefill_e2e2.gate b/crates/aien-runtime/tests/prefill_e2e2.gate index 5d95c034..1ba21854 100644 --- a/crates/aien-runtime/tests/prefill_e2e2.gate +++ b/crates/aien-runtime/tests/prefill_e2e2.gate @@ -3,7 +3,6 @@ # prefix; only the new positions are computed. Same chain as the first forge # line for PE2E2-A: fmt check, clippy, then the ignored real-checkpoint test # (TinyLlama-1.1B on the host CPU, release mode). GB10 is not needed. -# cache: never because the checkpoint directory is not an input we hash. gate: PREFILL-E2E-2 manifest_version: 1 owner: aien-sovereign-core @@ -14,6 +13,12 @@ inputs: - Cargo.lock - crates/ - tools/ + # Read outside crates/ (aien-audit-inputs, L335): the C1 acceptance file at + # run time, two campaign files compiled in by include_str!, and omega.lock + # through a build script. + - docs/campaigns/c1/ + - docs/campaigns/next-phase-1/ + - omega.lock run: exec: crates/aien-runtime/tests/prefill_e2e2_run.sh args: ["main"] @@ -24,4 +29,6 @@ expects: timeout: 120m checks: - clean_tree_after -cache: never +outside_inputs: + - ~/models/TinyLlama-1.1B-Chat-v1.0/ +cache: inputs_complete diff --git a/crates/aien-runtime/tests/prefill_e2e2_m1.gate b/crates/aien-runtime/tests/prefill_e2e2_m1.gate index 5cefbb97..b8f5143f 100644 --- a/crates/aien-runtime/tests/prefill_e2e2_m1.gate +++ b/crates/aien-runtime/tests/prefill_e2e2_m1.gate @@ -1,4 +1,6 @@ # crates/aien-runtime/tests/prefill_e2e2_m1.gate +# inputs: the crates cargo compiles for aien-runtime and its tests (cargo metadata, L335), every member manifest and the +# target listings cargo reads to load the workspace; outside_inputs: the checkpoint. Audited with aien-audit-inputs. # PREFILL-E2E-2 mutant m1 (the append replays the whole earlier context). Same as the forge mutant leg for m1: # apply prefill_e2e2_mutants/mutant_m1.patch, run the ignored test, restore the # tree. PASS means the mutant was killed: the test failed and printed @@ -11,15 +13,50 @@ requires: inputs: - Cargo.toml - Cargo.lock - - crates/aien-runtime/ + # Read outside crates/ (aien-audit-inputs, L335): the C1 acceptance file at + # run time and omega.lock through a build script. + - docs/campaigns/c1/ + - omega.lock + - crates/aien-abi-conformance/ + - crates/aien-abi-core/ + - crates/aien-allen/ + - crates/aien-allen-memory/ + - crates/aien-allen-profile/ + - crates/aien-inference-abi/ + - crates/aien-kv-cache/ + - crates/aien-kv-store/ + - crates/aien-localhttp/ + - crates/aien-omega-bf16/ + - crates/aien-omega-compose/ + - crates/aien-omega-dattn/ + - crates/aien-omega-dgraph/ + - crates/aien-omega-fp8/ + - crates/aien-omega-gpu/ + - crates/aien-omega-moe/ + - crates/aien-omega-pf/ + - crates/aien-omega-router/ - crates/aien-platform/ - crates/aien-platform-linux/ - - crates/aien-kv-cache/ + - crates/aien-runtime/ - crates/aien-scheduler/ - - crates/aien-abi-core/ - - crates/aien-inference-abi/ - crates/aien-security/ + - crates/aien-trace/ - crates/cortex-rs/ + - crates/*/Cargo.toml + - tools/*/Cargo.toml +listed: + - crates/* + - crates/*/src + - crates/*/src/bin + - crates/*/tests + - crates/*/examples + - crates/*/benches + - tools/* + - tools/*/src + - tools/*/src/bin + - tools/*/tests + - tools/*/examples + - tools/*/benches run: exec: crates/aien-runtime/tests/prefill_e2e2_run.sh args: ["mutant", "m1", "RECOMPUTE_ALL_VIOLATION"] @@ -30,4 +67,6 @@ expects: timeout: 60m checks: - clean_tree_after -cache: never +outside_inputs: + - ~/models/TinyLlama-1.1B-Chat-v1.0/ +cache: inputs_complete diff --git a/crates/aien-runtime/tests/prefill_e2e2_m2.gate b/crates/aien-runtime/tests/prefill_e2e2_m2.gate index fa3c213d..2cd31637 100644 --- a/crates/aien-runtime/tests/prefill_e2e2_m2.gate +++ b/crates/aien-runtime/tests/prefill_e2e2_m2.gate @@ -1,4 +1,6 @@ # crates/aien-runtime/tests/prefill_e2e2_m2.gate +# inputs: the crates cargo compiles for aien-runtime and its tests (cargo metadata, L335), every member manifest and the +# target listings cargo reads to load the workspace; outside_inputs: the checkpoint. Audited with aien-audit-inputs. # PREFILL-E2E-2 mutant m2 (a short continuation chunk restarts RoPE at position 0). Same as the forge mutant leg for m2: # apply prefill_e2e2_mutants/mutant_m2.patch, run the ignored test, restore the # tree. PASS means the mutant was killed: the test failed and printed @@ -11,15 +13,50 @@ requires: inputs: - Cargo.toml - Cargo.lock - - crates/aien-runtime/ + # Read outside crates/ (aien-audit-inputs, L335): the C1 acceptance file at + # run time and omega.lock through a build script. + - docs/campaigns/c1/ + - omega.lock + - crates/aien-abi-conformance/ + - crates/aien-abi-core/ + - crates/aien-allen/ + - crates/aien-allen-memory/ + - crates/aien-allen-profile/ + - crates/aien-inference-abi/ + - crates/aien-kv-cache/ + - crates/aien-kv-store/ + - crates/aien-localhttp/ + - crates/aien-omega-bf16/ + - crates/aien-omega-compose/ + - crates/aien-omega-dattn/ + - crates/aien-omega-dgraph/ + - crates/aien-omega-fp8/ + - crates/aien-omega-gpu/ + - crates/aien-omega-moe/ + - crates/aien-omega-pf/ + - crates/aien-omega-router/ - crates/aien-platform/ - crates/aien-platform-linux/ - - crates/aien-kv-cache/ + - crates/aien-runtime/ - crates/aien-scheduler/ - - crates/aien-abi-core/ - - crates/aien-inference-abi/ - crates/aien-security/ + - crates/aien-trace/ - crates/cortex-rs/ + - crates/*/Cargo.toml + - tools/*/Cargo.toml +listed: + - crates/* + - crates/*/src + - crates/*/src/bin + - crates/*/tests + - crates/*/examples + - crates/*/benches + - tools/* + - tools/*/src + - tools/*/src/bin + - tools/*/tests + - tools/*/examples + - tools/*/benches run: exec: crates/aien-runtime/tests/prefill_e2e2_run.sh args: ["mutant", "m2", "KV_PARITY_VIOLATION"] @@ -30,4 +67,6 @@ expects: timeout: 60m checks: - clean_tree_after -cache: never +outside_inputs: + - ~/models/TinyLlama-1.1B-Chat-v1.0/ +cache: inputs_complete diff --git a/crates/aien-runtime/tests/prefill_e2e2_m3.gate b/crates/aien-runtime/tests/prefill_e2e2_m3.gate index 8583ac07..ed93be23 100644 --- a/crates/aien-runtime/tests/prefill_e2e2_m3.gate +++ b/crates/aien-runtime/tests/prefill_e2e2_m3.gate @@ -1,4 +1,6 @@ # crates/aien-runtime/tests/prefill_e2e2_m3.gate +# inputs: the crates cargo compiles for aien-runtime and its tests (cargo metadata, L335), every member manifest and the +# target listings cargo reads to load the workspace; outside_inputs: the checkpoint. Audited with aien-audit-inputs. # PREFILL-E2E-2 mutant m3 (copy-on-write copies the shared tail then wipes the old block). Same as the forge mutant leg for m3: # apply prefill_e2e2_mutants/mutant_m3.patch, run the ignored test, restore the # tree. PASS means the mutant was killed: the test failed and printed @@ -11,15 +13,50 @@ requires: inputs: - Cargo.toml - Cargo.lock - - crates/aien-runtime/ + # Read outside crates/ (aien-audit-inputs, L335): the C1 acceptance file at + # run time and omega.lock through a build script. + - docs/campaigns/c1/ + - omega.lock + - crates/aien-abi-conformance/ + - crates/aien-abi-core/ + - crates/aien-allen/ + - crates/aien-allen-memory/ + - crates/aien-allen-profile/ + - crates/aien-inference-abi/ + - crates/aien-kv-cache/ + - crates/aien-kv-store/ + - crates/aien-localhttp/ + - crates/aien-omega-bf16/ + - crates/aien-omega-compose/ + - crates/aien-omega-dattn/ + - crates/aien-omega-dgraph/ + - crates/aien-omega-fp8/ + - crates/aien-omega-gpu/ + - crates/aien-omega-moe/ + - crates/aien-omega-pf/ + - crates/aien-omega-router/ - crates/aien-platform/ - crates/aien-platform-linux/ - - crates/aien-kv-cache/ + - crates/aien-runtime/ - crates/aien-scheduler/ - - crates/aien-abi-core/ - - crates/aien-inference-abi/ - crates/aien-security/ + - crates/aien-trace/ - crates/cortex-rs/ + - crates/*/Cargo.toml + - tools/*/Cargo.toml +listed: + - crates/* + - crates/*/src + - crates/*/src/bin + - crates/*/tests + - crates/*/examples + - crates/*/benches + - tools/* + - tools/*/src + - tools/*/src/bin + - tools/*/tests + - tools/*/examples + - tools/*/benches run: exec: crates/aien-runtime/tests/prefill_e2e2_run.sh args: ["mutant", "m3", "OLD_BLOCKS_REWRITTEN_VIOLATION"] @@ -30,4 +67,6 @@ expects: timeout: 60m checks: - clean_tree_after -cache: never +outside_inputs: + - ~/models/TinyLlama-1.1B-Chat-v1.0/ +cache: inputs_complete diff --git a/crates/aien-runtime/tests/prefill_e2e2_m4.gate b/crates/aien-runtime/tests/prefill_e2e2_m4.gate index d540db91..14db7303 100644 --- a/crates/aien-runtime/tests/prefill_e2e2_m4.gate +++ b/crates/aien-runtime/tests/prefill_e2e2_m4.gate @@ -1,4 +1,6 @@ # crates/aien-runtime/tests/prefill_e2e2_m4.gate +# inputs: the crates cargo compiles for aien-runtime and its tests (cargo metadata, L335), every member manifest and the +# target listings cargo reads to load the workspace; outside_inputs: the checkpoint. Audited with aien-audit-inputs. # PREFILL-E2E-2 mutant m4 (the dense prefix rebuilt from the pool reads the wrong layer). Same as the forge mutant leg for m4: # apply prefill_e2e2_mutants/mutant_m4.patch, run the ignored test, restore the # tree. PASS means the mutant was killed: the test failed and printed @@ -11,15 +13,50 @@ requires: inputs: - Cargo.toml - Cargo.lock - - crates/aien-runtime/ + # Read outside crates/ (aien-audit-inputs, L335): the C1 acceptance file at + # run time and omega.lock through a build script. + - docs/campaigns/c1/ + - omega.lock + - crates/aien-abi-conformance/ + - crates/aien-abi-core/ + - crates/aien-allen/ + - crates/aien-allen-memory/ + - crates/aien-allen-profile/ + - crates/aien-inference-abi/ + - crates/aien-kv-cache/ + - crates/aien-kv-store/ + - crates/aien-localhttp/ + - crates/aien-omega-bf16/ + - crates/aien-omega-compose/ + - crates/aien-omega-dattn/ + - crates/aien-omega-dgraph/ + - crates/aien-omega-fp8/ + - crates/aien-omega-gpu/ + - crates/aien-omega-moe/ + - crates/aien-omega-pf/ + - crates/aien-omega-router/ - crates/aien-platform/ - crates/aien-platform-linux/ - - crates/aien-kv-cache/ + - crates/aien-runtime/ - crates/aien-scheduler/ - - crates/aien-abi-core/ - - crates/aien-inference-abi/ - crates/aien-security/ + - crates/aien-trace/ - crates/cortex-rs/ + - crates/*/Cargo.toml + - tools/*/Cargo.toml +listed: + - crates/* + - crates/*/src + - crates/*/src/bin + - crates/*/tests + - crates/*/examples + - crates/*/benches + - tools/* + - tools/*/src + - tools/*/src/bin + - tools/*/tests + - tools/*/examples + - tools/*/benches run: exec: crates/aien-runtime/tests/prefill_e2e2_run.sh args: ["mutant", "m4", "KV_PARITY_VIOLATION"] @@ -30,4 +67,6 @@ expects: timeout: 60m checks: - clean_tree_after -cache: never +outside_inputs: + - ~/models/TinyLlama-1.1B-Chat-v1.0/ +cache: inputs_complete diff --git a/crates/aien-runtime/tests/prefill_e2e2_m5.gate b/crates/aien-runtime/tests/prefill_e2e2_m5.gate index 658dbafa..53a96042 100644 --- a/crates/aien-runtime/tests/prefill_e2e2_m5.gate +++ b/crates/aien-runtime/tests/prefill_e2e2_m5.gate @@ -1,4 +1,6 @@ # crates/aien-runtime/tests/prefill_e2e2_m5.gate +# inputs: the crates cargo compiles for aien-runtime and its tests (cargo metadata, L335), every member manifest and the +# target listings cargo reads to load the workspace; outside_inputs: the checkpoint. Audited with aien-audit-inputs. # PREFILL-E2E-2 mutant m5 (copy-on-write skipped entirely). Same as the forge mutant leg for m5: # apply prefill_e2e2_mutants/mutant_m5.patch, run the ignored test, restore the # tree. PASS means the mutant was killed: the test failed and printed @@ -11,15 +13,50 @@ requires: inputs: - Cargo.toml - Cargo.lock - - crates/aien-runtime/ + # Read outside crates/ (aien-audit-inputs, L335): the C1 acceptance file at + # run time and omega.lock through a build script. + - docs/campaigns/c1/ + - omega.lock + - crates/aien-abi-conformance/ + - crates/aien-abi-core/ + - crates/aien-allen/ + - crates/aien-allen-memory/ + - crates/aien-allen-profile/ + - crates/aien-inference-abi/ + - crates/aien-kv-cache/ + - crates/aien-kv-store/ + - crates/aien-localhttp/ + - crates/aien-omega-bf16/ + - crates/aien-omega-compose/ + - crates/aien-omega-dattn/ + - crates/aien-omega-dgraph/ + - crates/aien-omega-fp8/ + - crates/aien-omega-gpu/ + - crates/aien-omega-moe/ + - crates/aien-omega-pf/ + - crates/aien-omega-router/ - crates/aien-platform/ - crates/aien-platform-linux/ - - crates/aien-kv-cache/ + - crates/aien-runtime/ - crates/aien-scheduler/ - - crates/aien-abi-core/ - - crates/aien-inference-abi/ - crates/aien-security/ + - crates/aien-trace/ - crates/cortex-rs/ + - crates/*/Cargo.toml + - tools/*/Cargo.toml +listed: + - crates/* + - crates/*/src + - crates/*/src/bin + - crates/*/tests + - crates/*/examples + - crates/*/benches + - tools/* + - tools/*/src + - tools/*/src/bin + - tools/*/tests + - tools/*/examples + - tools/*/benches run: exec: crates/aien-runtime/tests/prefill_e2e2_run.sh args: ["mutant", "m5", "COW_VIOLATION"] @@ -30,4 +67,6 @@ expects: timeout: 60m checks: - clean_tree_after -cache: never +outside_inputs: + - ~/models/TinyLlama-1.1B-Chat-v1.0/ +cache: inputs_complete diff --git a/crates/aien-runtime/tests/prefill_e2e2_m6.gate b/crates/aien-runtime/tests/prefill_e2e2_m6.gate index deab317f..960126e5 100644 --- a/crates/aien-runtime/tests/prefill_e2e2_m6.gate +++ b/crates/aien-runtime/tests/prefill_e2e2_m6.gate @@ -1,4 +1,6 @@ # crates/aien-runtime/tests/prefill_e2e2_m6.gate +# inputs: the crates cargo compiles for aien-runtime and its tests (cargo metadata, L335), every member manifest and the +# target listings cargo reads to load the workspace; outside_inputs: the checkpoint. Audited with aien-audit-inputs. # PREFILL-E2E-2 mutant m6 (the pool is 3 blocks short, a test-file change). Same as the forge mutant leg for m6: # apply prefill_e2e2_mutants/mutant_m6.patch, run the ignored test, restore the # tree. PASS means the mutant was killed: the test failed and printed @@ -11,15 +13,50 @@ requires: inputs: - Cargo.toml - Cargo.lock - - crates/aien-runtime/ + # Read outside crates/ (aien-audit-inputs, L335): the C1 acceptance file at + # run time and omega.lock through a build script. + - docs/campaigns/c1/ + - omega.lock + - crates/aien-abi-conformance/ + - crates/aien-abi-core/ + - crates/aien-allen/ + - crates/aien-allen-memory/ + - crates/aien-allen-profile/ + - crates/aien-inference-abi/ + - crates/aien-kv-cache/ + - crates/aien-kv-store/ + - crates/aien-localhttp/ + - crates/aien-omega-bf16/ + - crates/aien-omega-compose/ + - crates/aien-omega-dattn/ + - crates/aien-omega-dgraph/ + - crates/aien-omega-fp8/ + - crates/aien-omega-gpu/ + - crates/aien-omega-moe/ + - crates/aien-omega-pf/ + - crates/aien-omega-router/ - crates/aien-platform/ - crates/aien-platform-linux/ - - crates/aien-kv-cache/ + - crates/aien-runtime/ - crates/aien-scheduler/ - - crates/aien-abi-core/ - - crates/aien-inference-abi/ - crates/aien-security/ + - crates/aien-trace/ - crates/cortex-rs/ + - crates/*/Cargo.toml + - tools/*/Cargo.toml +listed: + - crates/* + - crates/*/src + - crates/*/src/bin + - crates/*/tests + - crates/*/examples + - crates/*/benches + - tools/* + - tools/*/src + - tools/*/src/bin + - tools/*/tests + - tools/*/examples + - tools/*/benches run: exec: crates/aien-runtime/tests/prefill_e2e2_run.sh args: ["mutant", "m6", "POOL_EXHAUSTION_VIOLATION"] @@ -30,4 +67,6 @@ expects: timeout: 60m checks: - clean_tree_after -cache: never +outside_inputs: + - ~/models/TinyLlama-1.1B-Chat-v1.0/ +cache: inputs_complete diff --git a/crates/aien-runtime/tests/prefill_e2e2_m7.gate b/crates/aien-runtime/tests/prefill_e2e2_m7.gate index d588aca0..715ad1f2 100644 --- a/crates/aien-runtime/tests/prefill_e2e2_m7.gate +++ b/crates/aien-runtime/tests/prefill_e2e2_m7.gate @@ -1,4 +1,6 @@ # crates/aien-runtime/tests/prefill_e2e2_m7.gate +# inputs: the crates cargo compiles for aien-runtime and its tests (cargo metadata, L335), every member manifest and the +# target listings cargo reads to load the workspace; outside_inputs: the checkpoint. Audited with aien-audit-inputs. # PREFILL-E2E-2 mutant m7 (a shared single-token tail is not copied). Same as the forge mutant leg for m7: # apply prefill_e2e2_mutants/mutant_m7.patch, run the ignored test, restore the # tree. PASS means the mutant was killed: the test failed and printed @@ -11,15 +13,50 @@ requires: inputs: - Cargo.toml - Cargo.lock - - crates/aien-runtime/ + # Read outside crates/ (aien-audit-inputs, L335): the C1 acceptance file at + # run time and omega.lock through a build script. + - docs/campaigns/c1/ + - omega.lock + - crates/aien-abi-conformance/ + - crates/aien-abi-core/ + - crates/aien-allen/ + - crates/aien-allen-memory/ + - crates/aien-allen-profile/ + - crates/aien-inference-abi/ + - crates/aien-kv-cache/ + - crates/aien-kv-store/ + - crates/aien-localhttp/ + - crates/aien-omega-bf16/ + - crates/aien-omega-compose/ + - crates/aien-omega-dattn/ + - crates/aien-omega-dgraph/ + - crates/aien-omega-fp8/ + - crates/aien-omega-gpu/ + - crates/aien-omega-moe/ + - crates/aien-omega-pf/ + - crates/aien-omega-router/ - crates/aien-platform/ - crates/aien-platform-linux/ - - crates/aien-kv-cache/ + - crates/aien-runtime/ - crates/aien-scheduler/ - - crates/aien-abi-core/ - - crates/aien-inference-abi/ - crates/aien-security/ + - crates/aien-trace/ - crates/cortex-rs/ + - crates/*/Cargo.toml + - tools/*/Cargo.toml +listed: + - crates/* + - crates/*/src + - crates/*/src/bin + - crates/*/tests + - crates/*/examples + - crates/*/benches + - tools/* + - tools/*/src + - tools/*/src/bin + - tools/*/tests + - tools/*/examples + - tools/*/benches run: exec: crates/aien-runtime/tests/prefill_e2e2_run.sh args: ["mutant", "m7", "BRANCH_ISOLATION_VIOLATION"] @@ -30,4 +67,6 @@ expects: timeout: 60m checks: - clean_tree_after -cache: never +outside_inputs: + - ~/models/TinyLlama-1.1B-Chat-v1.0/ +cache: inputs_complete diff --git a/crates/aien-runtime/tests/prefill_e2e2_m8.gate b/crates/aien-runtime/tests/prefill_e2e2_m8.gate index 27939c82..a42b5c33 100644 --- a/crates/aien-runtime/tests/prefill_e2e2_m8.gate +++ b/crates/aien-runtime/tests/prefill_e2e2_m8.gate @@ -1,4 +1,6 @@ # crates/aien-runtime/tests/prefill_e2e2_m8.gate +# inputs: the crates cargo compiles for aien-runtime and its tests (cargo metadata, L335), every member manifest and the +# target listings cargo reads to load the workspace; outside_inputs: the checkpoint. Audited with aien-audit-inputs. # PREFILL-E2E-2 mutant m8 (free_sequence leaks partially filled blocks). Same as the forge mutant leg for m8: # apply prefill_e2e2_mutants/mutant_m8.patch, run the ignored test, restore the # tree. PASS means the mutant was killed: the test failed and printed @@ -11,15 +13,50 @@ requires: inputs: - Cargo.toml - Cargo.lock - - crates/aien-runtime/ + # Read outside crates/ (aien-audit-inputs, L335): the C1 acceptance file at + # run time and omega.lock through a build script. + - docs/campaigns/c1/ + - omega.lock + - crates/aien-abi-conformance/ + - crates/aien-abi-core/ + - crates/aien-allen/ + - crates/aien-allen-memory/ + - crates/aien-allen-profile/ + - crates/aien-inference-abi/ + - crates/aien-kv-cache/ + - crates/aien-kv-store/ + - crates/aien-localhttp/ + - crates/aien-omega-bf16/ + - crates/aien-omega-compose/ + - crates/aien-omega-dattn/ + - crates/aien-omega-dgraph/ + - crates/aien-omega-fp8/ + - crates/aien-omega-gpu/ + - crates/aien-omega-moe/ + - crates/aien-omega-pf/ + - crates/aien-omega-router/ - crates/aien-platform/ - crates/aien-platform-linux/ - - crates/aien-kv-cache/ + - crates/aien-runtime/ - crates/aien-scheduler/ - - crates/aien-abi-core/ - - crates/aien-inference-abi/ - crates/aien-security/ + - crates/aien-trace/ - crates/cortex-rs/ + - crates/*/Cargo.toml + - tools/*/Cargo.toml +listed: + - crates/* + - crates/*/src + - crates/*/src/bin + - crates/*/tests + - crates/*/examples + - crates/*/benches + - tools/* + - tools/*/src + - tools/*/src/bin + - tools/*/tests + - tools/*/examples + - tools/*/benches run: exec: crates/aien-runtime/tests/prefill_e2e2_run.sh args: ["mutant", "m8", "RECLAIM_VIOLATION"] @@ -30,4 +67,6 @@ expects: timeout: 60m checks: - clean_tree_after -cache: never +outside_inputs: + - ~/models/TinyLlama-1.1B-Chat-v1.0/ +cache: inputs_complete diff --git a/tests/gates/crumb.gate b/tests/gates/crumb.gate index ef2310cb..4eec4225 100644 --- a/tests/gates/crumb.gate +++ b/tests/gates/crumb.gate @@ -1,4 +1,5 @@ # tests/gates/crumb.gate +# target_lock: none because aien-audit-inputs traced no cargo or rustc in this gate (L335, 2026-10-21). # Mirrors hosted: no hosted crumb job in this repository; crumb verify . is the always-run structural check # cache: never because crumbs live in many directories and inputs are literal paths; the check is sub-second. gate: CRUMB-VERIFY @@ -20,3 +21,4 @@ timeout: 5m exactness: EXACT cache_scope: portable cache: never +target_lock: none diff --git a/tests/gates/sc-anti-slop.gate b/tests/gates/sc-anti-slop.gate index 541a3c4a..e34f9caa 100644 --- a/tests/gates/sc-anti-slop.gate +++ b/tests/gates/sc-anti-slop.gate @@ -1,4 +1,6 @@ # tests/gates/sc-anti-slop.gate +# target_lock: none because aien-audit-inputs traced no cargo or rustc in this gate (L335, 2026-10-21). +# cache: inputs_complete because aien-audit-inputs found every file this gate reads declared (L335). # Mirrors hosted: ci.yml verify 'Enforce Sovereign Voice and Anti-Slop Invariant' over crates/ docs/ README.md (always-run) gate: SC-ANTI-SLOP manifest_version: 2 @@ -20,3 +22,5 @@ expects: timeout: 2m exactness: EXACT cache_scope: portable +target_lock: none +cache: inputs_complete diff --git a/tests/gates/sc-crb1.gate b/tests/gates/sc-crb1.gate index 552b2df5..be576c18 100644 --- a/tests/gates/sc-crb1.gate +++ b/tests/gates/sc-crb1.gate @@ -1,6 +1,7 @@ # tests/gates/sc-crb1.gate # Mirrors hosted: crumb-visible-conformance.yml: crumbs visible_conformance with the aien-protocols corpus at b50c00d (hosted 26 s) -# cache: never because the vector corpus is a pinned sibling checkout outside this repository. +# cache: inputs_complete: the corpus is a sibling pinned by sha in tests/gates/run.sh (an input); aien-audit-inputs (L335) found every +# other read declared (the crate, every member manifest and the target listings cargo reads to load the workspace). gate: SC-CRB1 manifest_version: 2 owner: aien-sovereign-core @@ -10,6 +11,21 @@ inputs: - crates/crumbs/ - Cargo.lock - tests/gates/ + - crates/*/Cargo.toml + - tools/*/Cargo.toml +listed: + - crates/* + - crates/*/src + - crates/*/src/bin + - crates/*/tests + - crates/*/examples + - crates/*/benches + - tools/* + - tools/*/src + - tools/*/src/bin + - tools/*/tests + - tools/*/examples + - tools/*/benches run: exec: tests/gates/run.sh args: ["crb1"] @@ -19,4 +35,4 @@ expects: timeout: 15m exactness: EXACT cache_scope: machine -cache: never +cache: inputs_complete diff --git a/tests/gates/sc-pins-selftest.gate b/tests/gates/sc-pins-selftest.gate index d8f03774..a3c6a2eb 100644 --- a/tests/gates/sc-pins-selftest.gate +++ b/tests/gates/sc-pins-selftest.gate @@ -1,4 +1,6 @@ # tests/gates/sc-pins-selftest.gate +# target_lock: none because aien-audit-inputs traced no cargo or rustc in this gate (L335, 2026-10-21). +# cache: inputs_complete because aien-audit-inputs found every file this gate reads declared (L335). # Mirrors hosted: ci.yml verify 'bash scripts/test-pins.sh' gate: SC-PINS-SELFTEST manifest_version: 2 @@ -19,3 +21,5 @@ expects: timeout: 10m exactness: EXACT cache_scope: machine +target_lock: none +cache: inputs_complete diff --git a/tests/gates/sc-preflight-guard.gate b/tests/gates/sc-preflight-guard.gate index 4cd97709..0633b0a1 100644 --- a/tests/gates/sc-preflight-guard.gate +++ b/tests/gates/sc-preflight-guard.gate @@ -1,4 +1,6 @@ # tests/gates/sc-preflight-guard.gate +# target_lock: none because aien-audit-inputs traced no cargo or rustc in this gate (L335, 2026-10-21). +# cache: inputs_complete because aien-audit-inputs found every file this gate reads declared (L335). # Mirrors hosted: ci.yml verify 'bash scripts/test-preflight-branch-guard.sh' gate: SC-PREFLIGHT-GUARD manifest_version: 2 @@ -17,3 +19,5 @@ expects: timeout: 10m exactness: EXACT cache_scope: machine +target_lock: none +cache: inputs_complete diff --git a/tests/gates/sc-release-dry-run.gate b/tests/gates/sc-release-dry-run.gate index 5c9b082c..787affe7 100644 --- a/tests/gates/sc-release-dry-run.gate +++ b/tests/gates/sc-release-dry-run.gate @@ -1,4 +1,5 @@ # tests/gates/sc-release-dry-run.gate +# target_lock: none because aien-audit-inputs traced no cargo or rustc in this gate (L335, 2026-10-21). # Mirrors hosted: release-dry-run.yml (pull_request): test-dry-run-workflow, test-release-gate-wiring, test-release-signing-workflow, tree gate report (observation only, as hosted continue-on-error), test-release-real-tree (hosted 8 s) gate: SC-RELEASE-DRY-RUN manifest_version: 2 @@ -19,3 +20,4 @@ expects: timeout: 15m exactness: EXACT cache_scope: machine +target_lock: none diff --git a/tests/gates/sc-release-gate-negatives.gate b/tests/gates/sc-release-gate-negatives.gate index 8ba67a2d..3ef558da 100644 --- a/tests/gates/sc-release-gate-negatives.gate +++ b/tests/gates/sc-release-gate-negatives.gate @@ -1,4 +1,5 @@ # tests/gates/sc-release-gate-negatives.gate +# target_lock: none because aien-audit-inputs traced no cargo or rustc in this gate (L335, 2026-10-21). # Mirrors hosted: ci.yml verify: test-install-release, test-offline-signing, test-public-key-integration, check-release-trust-config, test-release-checks gate: SC-RELEASE-GATE-NEGATIVES manifest_version: 2 @@ -19,3 +20,4 @@ expects: timeout: 15m exactness: EXACT cache_scope: machine +target_lock: none diff --git a/tests/gates/sc-scoring-v5.gate b/tests/gates/sc-scoring-v5.gate index 351f227a..b253e04f 100644 --- a/tests/gates/sc-scoring-v5.gate +++ b/tests/gates/sc-scoring-v5.gate @@ -1,4 +1,6 @@ # tests/gates/sc-scoring-v5.gate +# target_lock: none because aien-audit-inputs traced no cargo or rustc in this gate (L335, 2026-10-21). +# cache: inputs_complete because aien-audit-inputs found every file this gate reads declared (L335). # Mirrors hosted: ci.yml verify 'bash docs/campaigns/scoring/test-scoring-v5.sh' gate: SC-SCORING-V5 manifest_version: 2 @@ -7,6 +9,7 @@ requires: - portable inputs: - docs/campaigns/scoring/ + - docs/campaigns/next-phase-2/ - tests/gates/ run: exec: tests/gates/run.sh @@ -17,3 +20,5 @@ expects: timeout: 5m exactness: EXACT cache_scope: portable +target_lock: none +cache: inputs_complete diff --git a/tests/gates/sc-trn1.gate b/tests/gates/sc-trn1.gate index b1ec90b0..4ffad0d0 100644 --- a/tests/gates/sc-trn1.gate +++ b/tests/gates/sc-trn1.gate @@ -1,6 +1,7 @@ # tests/gates/sc-trn1.gate # Mirrors hosted: hardening.yml trn1: aien-replay trn1_conformance with the aien-protocols corpus at 353b7d4 + run_mutants.sh trn1 (hosted 50 s) -# cache: never because the vector corpus is a pinned sibling checkout outside this repository. +# cache: inputs_complete: the corpus is a sibling pinned by sha in tests/gates/run.sh (an input); crates/aien-replay is its own +# cargo workspace, and aien-audit-inputs (L335) found it reads only the crates listed below. gate: SC-TRN1 manifest_version: 2 owner: aien-sovereign-core @@ -8,6 +9,9 @@ requires: - host inputs: - crates/aien-replay/ + - crates/aien-platform/ + - crates/aien-platform-linux/ + - crates/aien-kv-cache/ - Cargo.lock - tests/gates/ run: @@ -19,4 +23,4 @@ expects: timeout: 15m exactness: EXACT cache_scope: machine -cache: never +cache: inputs_complete diff --git a/tests/gates/sc-zero-disk-plaintext.gate b/tests/gates/sc-zero-disk-plaintext.gate index 8f572a65..76a66de6 100644 --- a/tests/gates/sc-zero-disk-plaintext.gate +++ b/tests/gates/sc-zero-disk-plaintext.gate @@ -1,4 +1,5 @@ # tests/gates/sc-zero-disk-plaintext.gate (file name avoids "secret": scripts/agent-preflight.sh flags any *secret* file within depth 3) +# target_lock: none because aien-audit-inputs traced no cargo or rustc in this gate (L335, 2026-10-21). # Mirrors hosted: ci.yml verify 'Enforce Zero Disk Secrets Invariant' (always-run) gate: SC-ZERO-DISK-SECRETS manifest_version: 2 @@ -17,3 +18,4 @@ expects: timeout: 2m exactness: EXACT cache_scope: portable +target_lock: none diff --git a/tools/aien-local-ci/.crumb b/tools/aien-local-ci/.crumb index 647214d4..18ffc55d 100644 --- a/tools/aien-local-ci/.crumb +++ b/tools/aien-local-ci/.crumb @@ -3,14 +3,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-24T04:15:31Z", + "compiled_at": "2026-10-24T04:35:35Z", "compiler": "crumb-compile/1", - "digest": "sha256:598dc3bd4d60f47f79ccb3b42d5966be1ba921fdbb24f347ef6c998463a4da3a", - "evidence_files": 0, - "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 21, - "generated_at_commit": "208776701cc8996b0d6badce6ae5e2bd26aace74", - "source_tree": "sha256:00335311d2bf0073d3b163450c23f53327cf9d9ed4d3ab2e1cecb995255fa355" + "digest": "sha256:e5e7271b10298838894bed570db8e039af89dc3063640b6da5d84d420534c7f6", + "evidence_files": 1, + "evidence_root": "sha256:df8becc2ad8de903c2cae60e1066a9a5239db46f374af2a30ba923b3aea98658", + "files": 23, + "generated_at_commit": "af30836418a663ea06cdcf3a037e337fb2d8c5aa", + "source_tree": "sha256:b2cb1909074a16f5fa806632d1b58a81ad727e69ff9a18d090c5e3db681b5f4e" } }, "layer": "infra", diff --git a/tools/aien-local-ci/evidence/L337-pipeline-polling-2026-10-21.md b/tools/aien-local-ci/evidence/L337-pipeline-polling-2026-10-21.md new file mode 100644 index 00000000..b0d74ad8 --- /dev/null +++ b/tools/aien-local-ci/evidence/L337-pipeline-polling-2026-10-21.md @@ -0,0 +1,18 @@ +# L337: pipeline polling and GitHub calls (2026-10-21) + +Findings G3-ci-judge-3..7 from the efficiency review (L325). Before numbers: gh guard ledger, window 22:26Z-01:09Z +(9,735 s, 11,605 calls), pipeline journal 2026-10-20, receipts under the state dir. calc ids are aien-calc receipts. + +| finding | before | after | receipt | +|---|---|---|---| +| G3-4 settled bundles re-checked every round | publish round on 710 real bundles (sandbox copy, trusted clones read-only, local bare receipts): 15.2, 18.1, 18.4 s | 0.53 s steady (3 more rounds 0.52-0.54 s); first round after a key/binary/bundle change still does the full pass (3.6 s) | 32.5x faster (calc:c1f89414e591c94865598eef37c616819862cdf9c7bb898f4c431a0108617a0b); live: no publish lines in the 02:15Z round | +| G3-5 GitHub asked before the free behind-main check | pulls/N reads 650 in 9,735 s = 5,769/day (calc:3e21153baa4b70be7377af196238a0080cae143eaaa40ebf6833e3c7d4fc6c0d); 86.8 % of merge attempts ended "behind" (calc:2630bb78ddd10972fcbe48e608f62144f45ff63e40e498208c77e0acabe9efca) | live round 02:11Z-02:16Z: 5 pulls/N reads (was about 20 per round); behind PRs cost 0 requests | gh guard ledger | +| G3-6 repo slug asked every tick | 355 reads in the window, 11 per round = 3,168/day (calc:c0d04c3a552bcaa80b92b3673c0368b8c8743dad581e1d6a9c37526d0d885422) | 0 in the 02:11Z round; 11 per 24 h | ledger | +| G3-7 PR lists polled again and again | pipeline: 2 full list reads per repo per round; worker: 2 calls per repo per poll, 1,343 in the window = 11,919/day (calc:99a652d11df0c1acad0939a869e3b2549450760996657377c72231d919220da7) | pipeline lists are now If-None-Match (live: conditional calls in the ledger, 22 cached answers); worker code written and unit-tested, takes effect when the judge binary is rebuilt and the poll worker restarts between heads (NOT restarted: a head is being judged) | see note below | +| G3-3 same gate re-run on same head | all receipts: 13.8 % of gate seconds are repeats (record said 14.1 %); 2026-10-20 alone 9.1 %, of which 49 % had byte-identical stderr | NOT MEASURABLE yet: no completed receipt since 2026-10-20 20:32Z, so nothing exists after L319's harness fix (23:52Z); retry files `*.try-*` stopped on 2026-10-19 10:15Z | `repeat-gates.sh 2026-10-21T00:00` re-measures after the next completed runs | + +## Notes and limits +- 304 cost: GitHub's documentation says a 304 does not count against the primary limit (docs.github.com, best practices: "Making a conditional request does not count against your primary rate limit if a 304 response is returned"). My live probes agree but are noisy because other callers spend in bursts: 30 conditional requests (30 x 304) moved the counter by 30 in a window where idle drift was 12 per 10 s; 30 plain requests moved it by 189. Treat as consistent with free, not as a proof. +- The sandbox publish timings use the real 710 bundles and real keys and the real aien-test binary, with git fetch on the trusted clones turned off and a local bare repository as the receipts remote. Nothing was pushed. +- Tests: pipeline_test.sh 77 checks pass; 14 checks added, 11 of the first batch fail on the old script (run against `git show origin/main:tools/aien-local-ci/pipeline.sh`), the ETag checks fail on it too. Rust: worker unit test `an_unchanged_list_is_asked_with_its_etag_and_answered_from_memory` (fake gh, 304, changed list, 404) passes; it has no old-code red run because it calls the new function; the old behaviour (unconditional) is asserted by the last step. Clippy clean. +- Found on the way (not mine): renda-harness reads `commits/SHA/statuses` about 2,700 times an hour and drained the shared allowance to 482 at 01:40Z (all reads refused until 02:05Z). Ledger L348 carries the proposed fix. diff --git a/tools/aien-local-ci/repeat-gates.sh b/tools/aien-local-ci/repeat-gates.sh new file mode 100755 index 00000000..da46e6c3 --- /dev/null +++ b/tools/aien-local-ci/repeat-gates.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# repeat-gates.sh [SINCE_UTC] [STATE]: how much gate time went into running the same gate on the same head again. +# Reads every receipt under $STATE/evidence (core.commit, core.gate, core.stderr_sha256, volatile.duration_ms and +# started_utc). The first run of each (head, gate) is the work; every later run is a repeat. "equal" repeats gave +# byte-identical stderr, so they were pure waste; the rest changed (a flake, a retry after a harness fault, or a real change). +# Prints: day, total gate seconds, repeat seconds and share, equal-stderr repeat seconds. SINCE_UTC (default all) keeps +# only receipts that started at or after it, e.g. 2026-10-21T00:00 to check the rounds after a harness fix (L337, G3-ci-judge-3). +set -euo pipefail +SINCE=${1:-} +STATE=${2:-${AIEN_STATE:-$HOME/.local/state/aien-local-ci}} +find "$STATE/evidence" -name '*.json' -print0 | xargs -0 jq -r \ + '[.core.commit, .core.gate, (.core.stderr_sha256 // ""), (.volatile.duration_ms // 0), (.volatile.started_utc // "")] | @tsv' \ + | sort -t$'\t' -k1,1 -k2,2 -k5,5 \ + | awk -F'\t' -v since="$SINCE" ' + { k = $1 "\t" $2; take = (since == "" || $5 >= since) + if (take) { tot += $4 } + if (k == pk && take) { rep += $4; n++; if ($3 == ps) { eq += $4 } } + pk = k; ps = $3 } + END { if (tot == 0) { print "no receipts in the window"; exit } + printf "total_s=%.0f repeat_s=%.0f (%.1f%%) repeat_runs=%d equal_stderr_s=%.0f\n", tot/1000, rep/1000, 100*rep/tot, n, eq/1000 }' diff --git a/tools/aien-test/Cargo.toml b/tools/aien-test/Cargo.toml index 32dcd53f..39de8f82 100644 --- a/tools/aien-test/Cargo.toml +++ b/tools/aien-test/Cargo.toml @@ -18,6 +18,10 @@ sha2 = "0.10" name = "aien-test" path = "src/main.rs" +[[bin]] +name = "aien-audit-inputs" +path = "src/bin/aien-audit-inputs.rs" + [lib] name = "aien_test" path = "src/lib.rs" diff --git a/tools/aien-test/docs/LOCAL_VERIFICATION.md b/tools/aien-test/docs/LOCAL_VERIFICATION.md index b51f5b9c..e582759f 100644 --- a/tools/aien-test/docs/LOCAL_VERIFICATION.md +++ b/tools/aien-test/docs/LOCAL_VERIFICATION.md @@ -251,13 +251,42 @@ The one rule: worker records each sibling made (`name` = its `dir`) and each operator pin (`name` = `pin:<source>`) with its commit in the receipt's `pins`, which is part of the cache key. The worker's evidence directory is per - head (`evidence/<repo>/<sha>/`), so a result is reused only when the same - commit runs again with every sibling at the same commit; a sibling that - moved runs every gate fresh. A declared sibling that cannot be made turns - the cache off for the head (`no_cache`). Results are never reused across - commits in the worker: gates read files they do not declare as `inputs` - (SC-TEST reads the root `README.md` and `COVENANT.md`), so a key built - from declared inputs alone could hand a commit another commit's PASS. + head (`evidence/<repo>/<sha>/`); results cross heads only through the + shared store `<state>/gate-cache/<repo>/` (judge once, Drake 2026-10-20), + and only as far as the gate allows (`cache::cross_head`): + - **Never across heads:** `cache: never`, gb10/nvrm (chip state), + bare_metal/analog, `requires: operator`, `cache_scope: hardware`, + APPROXIMATE/ADVISORY. These keep the per-head cache only. + - **Whole tree identical:** every other gate, by default. Gates read files + they do not declare (SC-TEST reads the root `README.md` and + `COVENANT.md`), so declared inputs alone could hand a commit another + commit's PASS. Two heads with the same tree id (a squash merge of an + up-to-date PR, a re-push, a duplicate PR) share every such result. + - **Declared inputs identical:** a gate whose manifest says + `cache: inputs_complete`, the author's promise that `inputs` name every + file the gate reads. Any head with the same key reuses it. + A promise is checked, not trusted: `aien-audit-inputs GATE_FILE` runs the + gate once under `strace -f -y -Y` (cold target dir, private TMPDIR) and + lists every file it opened that the manifest does not cover; RESULT FAIL + means the promise is false. Three manifest keys say what `inputs` alone + cannot (L335): `outside_inputs` (files outside the repository, `~/` or + absolute, hashed into the key: the PREFILL-E2E-2 checkpoint), `listed` + (directories whose entry names, not bytes, join the key: cargo lists + `tests/`, `src/bin/`, `examples/` of every workspace member to load the + workspace) and `*` patterns in `inputs` and `listed` + (`crates/*/Cargo.toml`). `target_lock: none` lets a gate that never + starts cargo (the audit refuses it if it does) skip the head's target-dir + lock instead of queueing behind every cargo gate. + The key adds the repository build files (`runner::IMPLIED_BUILD_FILES`: + Cargo.toml, Cargo.lock, rust-toolchain(.toml), .cargo/config(.toml), + native-artifacts.lock, mojoproject.toml) and the judge's own sha256 + (`machine.judge_sha256`), so an entry dies with a new judge or exec + helper. A FAIL is reused as FAIL. The reuse receipt says + `volatile.cache.reused_from` and `reused_from_commit`; the bundle entry + is `cached` with `resolution.resolved_from` and `resolved_from_commit`. + One flock per entry (`locks/<entry>.lock`) makes a second judge of the + same key wait and reuse instead of running it again. A declared sibling + that cannot be made turns the cache off for the head (`no_cache`). `wt.sh remove` takes the whole run directory away (checkout and siblings) and prunes every mirror's worktree list. An older `wt.sh` that still makes @@ -381,7 +410,8 @@ Forgejo). Merging a pull request on GitHub does not wake it. `--jobs host=N,qemu=M` and `--no-cache` apply to the runs the worker starts, as they do for `aien-test test`. `--no-cache` runs every selected gate again -(a head reuses only its own earlier results, see "Sibling checkouts"). `--jobs host=1` +(results come from this head or, through the shared store, from another head +with the same key, see "Sibling checkouts"). `--jobs host=1` runs one host gate at a time: omega's gates share one checkout's `build/` and pin clones, and on main 771af52 ten of them failed from parallel races ("Text file busy" on `build/omegatool`, concurrent clones of @@ -389,6 +419,26 @@ and pin clones, and on main 771af52 ten of them failed from parallel races `aien-local-ci once omega <sha> --operator --jobs host=1` until the gates or a per-repository pool setting make them safe in parallel. +### Batches: shared gates once and first (judge once, 2026-10-20) + +`aien-test worker --batch REPO SHA SHA...` judges several heads of one +repository together, and the loop does the same for the heads it finds of +one repository, `--batch-heads N` at a time (default 6). The heads run side +by side; each gate that will really run takes a slot of one budget the batch +shares, `--batch-host N` host slots (default half the CPUs), and every gb10 +gate takes the batch's single gb10 slot before `/tmp/aien-gb10.lock`, so GPU +gates stay one at a time and heads never spend their bounded GPU wait on each +other. A gate that other heads of the batch also select (same manifest, same +blob ids for its inputs and the repository build files, read from git before +checkout: `worker::batch_first`) is picked first in its head and served first +from the budget, so the shared gates run before the per-head ones. Two heads +that reach the same key meet at that key's lock: the second waits, then +reuses. The ordering is only a hint; the cache key alone decides reuse. A +head is judged by one worker at a time (`<state>/locks/head/<repo>.<sha>.lock`, +non-blocking: a second judge of the same head is refused), and checkouts, +pins, siblings and worktree removal are done one head at a time. +`--jobs host=1` still limits each head's own pool (omega). + ## verify-bundle and the vacuous PASS `aien-test verify-bundle` (the GitHub thin gate's command) prints and exits @@ -435,10 +485,11 @@ manifest at COMMIT (`MANIFEST_MISMATCH`); then the plan judge. Every rejection is a `Problem` or `Evidence note` line and leaves READY out of reach; no path defaults to PASS. Crumb status comes from `crumb verify .` in a temporary detached worktree at COMMIT, removed afterwards. Queue time is the sum of -`pool_wait_ms`, GPU lock wait the sum of `gpu_wait.waited_ms` (gb10 gates: +`pool_wait_ms`, `batch_wait_ms` (waiting for a slot of the `worker --batch` +budget) and `target_wait_ms` (waiting for the target dir another gate holds), GPU lock wait the sum of `gpu_wait.waited_ms` (gb10 gates: how long each waited in the kernel queue of `/tmp/aien-gb10.lock`, see below), test time the sum of `duration_ms` over the executed -receipts, total time the bundle's `finished_utc - started_utc`; build time +receipts less those two waits (both fall inside `duration_ms`), total time the bundle's `finished_utc - started_utc`; build time is not measured yet. `READY` requires: evidence VERIFIED, final verdict PASS, crumb CURRENT, no diff --git a/tools/aien-test/src/audit.rs b/tools/aien-test/src/audit.rs new file mode 100644 index 00000000..9a525b63 --- /dev/null +++ b/tools/aien-test/src/audit.rs @@ -0,0 +1,655 @@ +//! Input audit (L335): does a gate read only what its manifest declares? +//! +//! A gate that says `cache: inputs_complete` lends its result to every head +//! whose declared inputs are byte-identical (`cache::cross_head`). If the gate +//! reads a file it does not declare, a head that changed only that file gets +//! another head's verdict: a false PASS. This module checks the promise +//! against a real run: `aien-audit-inputs` runs the gate once under +//! `strace -f -y -Y` (every file opened, with the path the kernel resolved and +//! the program that opened it) and lists each opened file the manifest does +//! not cover. +//! +//! What counts as covered: +//! - inside the repository: a declared input (file, directory or `*` pattern), +//! a build file every key carries ([`runner::IMPLIED_BUILD_FILES`]), the +//! manifest itself and `run.exec`; +//! - outside it: an `outside_inputs` entry, or the toolchain and system +//! (`/usr`, `/lib`, `/etc`, `/proc`, `/sys`, `/dev`, `/run`, `~/.rustup`, +//! `~/.cargo`). The toolchain is pinned by `rust-toolchain.toml` and the +//! registry sources by `Cargo.lock`, both in every key; a system library +//! upgrade is not (a limit of this audit, stated in the report). +//! +//! Not judged as reads (each reported with a count, never silently): +//! - `git` opening anything (the commit, its config and objects) and `tar` +//! opening the tree (the copy step). What the +//! copy's consumers read is mapped back (next item). A script that branches +//! on git output is not caught here; read the script. +//! - files under the private `TMPDIR` the audit gives the run: a path +//! `TMPDIR/<dir>/REL` whose `REL` exists in the repository is judged as the +//! repository file `REL` (the PREFILL mutants build a copy of the tree); +//! anything else there is the run's own scratch. +//! - the cargo target dir, `.git/`, `/tmp`, and opens for writing only. +//! +//! An audit only sees what one run read: run it with a cold target dir, or +//! cargo skips reading the sources of crates it considers fresh. +use crate::manifest::Manifest; +use crate::runner; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; + +/// One successful open (or exec) from an strace log. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Opened { + /// The program's name as the kernel reports it (15 characters at most). + pub comm: String, + /// The path the kernel resolved (the `-y` decoration), absolute. + pub path: String, + /// Opened only for writing (`O_WRONLY`): not a read. + pub write_only: bool, + /// Opened as a directory (`O_DIRECTORY`): a listing of its names. + pub dir: bool, + /// Opened with `O_TRUNC`: the run replaced the file, so a later read of + /// it reads the run's own output. + pub truncates: bool, +} + +/// Parse `strace -f -qq -Y -y -e trace=open,openat,openat2,execve +/// -e status=successful` output. Lines that are not a successful open or +/// exec of a named file are skipped. +pub fn parse_strace(text: &str) -> Vec<Opened> { + let mut out = Vec::new(); + for line in text.lines() { + let Some(lt) = line.find('<') else { continue }; + let Some(gt) = line[lt..].find("> ") else { + continue; + }; + let comm = line[lt + 1..lt + gt].to_string(); + let call = &line[lt + gt + 2..]; + if call.starts_with("execve(") { + // execve("/abs/path", ...) = 0: the program file itself is read. + if let Some(p) = quoted(call) { + if p.starts_with('/') && call.trim_end().ends_with("= 0") { + out.push(Opened { + comm, + path: p, + write_only: false, + dir: false, + truncates: false, + }); + } + } + continue; + } + if !(call.starts_with("openat(") + || call.starts_with("open(") + || call.starts_with("openat2(")) + { + continue; + } + // ... ) = 3</resolved/path> + let Some(eq) = call.rfind(") = ") else { + continue; + }; + let ret = &call[eq + 4..]; + let (Some(a), Some(b)) = (ret.find('<'), ret.rfind('>')) else { + continue; + }; + if b <= a + 1 { + continue; + } + let path = ret[a + 1..b].to_string(); + // A pipe or socket (`pipe:[123]`) is not a file. + if !path.starts_with('/') { + continue; + } + let write_only = call[..eq].contains("O_WRONLY"); + let dir = call[..eq].contains("O_DIRECTORY"); + let truncates = call[..eq].contains("O_TRUNC"); + out.push(Opened { + comm, + path, + write_only, + dir, + truncates, + }); + } + out +} + +/// The first double-quoted string of a syscall line (no escapes expected in +/// the paths we judge; a path with `"` is skipped). +fn quoted(call: &str) -> Option<String> { + let a = call.find('"')?; + let b = call[a + 1..].find('"')?; + Some(call[a + 1..a + 1 + b].to_string()) +} + +/// Where the audited run lived. +#[derive(Debug, Clone)] +pub struct Places { + /// The repository root (canonical). + pub root: PathBuf, + /// The repository-relative path of the manifest. + pub manifest_rel: String, + /// The cargo target dir of the run (canonical). + pub target_dir: PathBuf, + /// The private `TMPDIR` given to the run (canonical). + pub tmpdir: PathBuf, + /// The judge's home, for `~/` entries and `~/.rustup`, `~/.cargo`. + pub home: PathBuf, + /// The files git tracks at HEAD (repo-relative). A repository path that is + /// neither one of them nor a directory holding one was made by the run + /// (build outputs in the tree, say `build/`), so it is not an input. None: + /// every path is judged. + pub tracked: Option<BTreeSet<String>>, + /// Sibling checkouts the judge provides (`../<repo>`, canonical). Their + /// commits are in every key as pins, so reading them is covered. + pub siblings: Vec<PathBuf>, +} + +/// The audit's findings. +#[derive(Debug, Default, Clone)] +pub struct Report { + /// Repository files read but not declared (repo-relative), with a reader. + pub undeclared: BTreeMap<String, String>, + /// Files outside the repository read but not declared, with a reader. + pub undeclared_outside: BTreeMap<String, String>, + /// Counts of opens not judged as reads, by reason. + pub ignored: BTreeMap<&'static str, usize>, + /// Declared repository files the run did read (for the record). + pub covered: BTreeSet<String>, + /// The run started cargo, rustc, clippy or rustdoc. + pub uses_cargo: bool, +} + +impl Report { + /// The promise holds: nothing undeclared, and a `target_lock: none` gate + /// never started cargo. + pub fn ok(&self, m: &Manifest) -> bool { + self.undeclared.is_empty() + && self.undeclared_outside.is_empty() + && (m.target_lock || !self.uses_cargo) + } +} + +const SYSTEM: [&str; 9] = [ + "/usr/", "/lib/", "/lib64/", "/bin/", "/sbin/", "/etc/", "/proc/", "/sys/", "/dev/", +]; +const CARGO_PROGRAMS: [&str; 6] = [ + "cargo", + "rustc", + "clippy-driver", + "cargo-clippy", + "rustdoc", + "cargo-fmt", +]; + +/// Is the repository path `rel` covered by the manifest's declarations? +pub fn covered(m: &Manifest, manifest_rel: &str, rel: &str) -> bool { + let rel = rel.trim_end_matches('/'); + if rel == manifest_rel || rel == m.exec || runner::IMPLIED_BUILD_FILES.contains(&rel) { + return true; + } + m.inputs.iter().any(|i| input_covers(i, rel)) +} + +/// A directory listing is covered when a `listed` entry names that very +/// directory (component by component, `*` allowed): its names are in the key. +fn listed_covers(m: &Manifest, rel: &str) -> bool { + let rp: Vec<&str> = rel.split('/').collect(); + m.listed.iter().any(|l| { + let lp: Vec<&str> = l.trim_end_matches('/').split('/').collect(); + lp.len() == rp.len() + && lp + .iter() + .zip(&rp) + .all(|(a, b)| runner::wildcard_match(a, b)) + }) +} + +/// One declared input against one path: equal, inside a declared directory, +/// or matched component by component by a `*` pattern (whose last component +/// may itself be a directory the path is inside). +fn input_covers(input: &str, rel: &str) -> bool { + let i = input.trim().trim_start_matches("./").trim_end_matches('/'); + if i.is_empty() || i == "." { + return true; + } + let ip: Vec<&str> = i.split('/').collect(); + let rp: Vec<&str> = rel.split('/').collect(); + if rp.len() < ip.len() { + return false; + } + ip.iter() + .zip(&rp) + .all(|(a, b)| runner::wildcard_match(a, b)) +} + +/// Judge every open of an audited run. +pub fn judge(m: &Manifest, places: &Places, opened: &[Opened]) -> Report { + let mut r = Report::default(); + let root = places.root.to_string_lossy().into_owned() + "/"; + let target = places.target_dir.to_string_lossy().into_owned() + "/"; + let tmpdir = places.tmpdir.to_string_lossy().into_owned() + "/"; + let home = places.home.to_string_lossy().into_owned(); + let toolchain = [ + format!("{home}/.rustup/"), + format!("{home}/.cargo/"), + "/var/lib/aien-run/rustup/".into(), + "/var/lib/aien-run/cargo/".into(), + ]; + let outside: Vec<String> = m + .outside_inputs + .iter() + .map(|o| { + let o = o.trim_end_matches('/'); + match o.strip_prefix("~/") { + Some(rest) => format!("{home}/{rest}"), + None => o.to_string(), + } + }) + .collect(); + // Files the run truncated (a log it writes, then greps): reads after that + // see its own output, not an input. + let mut made: BTreeSet<&str> = BTreeSet::new(); + for o in opened { + if CARGO_PROGRAMS.contains(&o.comm.as_str()) { + r.uses_cargo = true; + } + if o.truncates { + made.insert(o.path.as_str()); + } + if o.write_only { + bump(&mut r, "opened for writing only"); + continue; + } + // git reads its own records wherever they live (a worktree's common + // dir, a mirror, ~/.gitconfig): the commit, not a gate input. + if o.comm == "git" || o.comm.starts_with("git-") { + bump(&mut r, "git (commit metadata, config, objects)"); + continue; + } + // rm opens directories to delete what is inside them, never to read. + if o.comm == "rm" { + bump(&mut r, "rm (deleting, not reading)"); + continue; + } + // Any program reading a git directory (cargo lists a path package's + // files through the git index; gix reads the excludes) reads the tree's + // own record of itself, which the declared files already pin. + if o.path.contains("/.git/") || o.path.ends_with("/.git") { + bump(&mut r, "git metadata (.git)"); + continue; + } + let p = o.path.as_str(); + let p_dir = format!("{}/", p.trim_end_matches('/')); + if p_dir.starts_with(&target) { + bump(&mut r, "cargo target dir (outputs)"); + continue; + } + // A file of the private TMPDIR whose tail names a repository file is + // that file (a copy of the tree); the rest is the run's scratch. + if let Some(t) = p.strip_prefix(&tmpdir) { + let tail = t.split_once('/').map(|x| x.1).unwrap_or(""); + if o.comm == "tar" { + // tar -x making the copy: it writes, it does not read. + bump(&mut r, "tar writing the copy"); + } else if !tail.is_empty() + && places.root.join(tail).exists() + && !tail.starts_with(".git") + { + judge_repo(m, places, tail, o, &mut r); + } else { + bump(&mut r, "private TMPDIR scratch"); + } + continue; + } + if places + .siblings + .iter() + .any(|s| p_dir.starts_with(&format!("{}/", s.display()))) + { + bump(&mut r, "sibling checkout (its commit is a pin in the key)"); + continue; + } + if p_dir.starts_with(&root) || p_dir == root { + let rel = p_dir[root.len().min(p_dir.len())..] + .trim_end_matches('/') + .to_string(); + if rel.is_empty() { + bump(&mut r, "the repository root directory itself"); + } else if rel == ".git" || rel.starts_with(".git/") { + bump(&mut r, "git metadata (.git)"); + } else if o.comm == "tar" { + bump(&mut r, "tar reading the tree (the copy step)"); + } else { + judge_repo(m, places, &rel, o, &mut r); + } + continue; + } + // Only outside the tree and its TMPDIR copy: a copied repository file + // is written by tar first and is still that repository file. + if made.contains(p) { + bump(&mut r, "made earlier by the run (truncated, then read)"); + continue; + } + if outside + .iter() + .any(|d| p == d || p.starts_with(&format!("{d}/"))) + { + bump(&mut r, "declared outside_inputs"); + continue; + } + if toolchain.iter().any(|t| p_dir.starts_with(t.as_str())) { + bump( + &mut r, + "toolchain and registry (rust-toolchain.toml, Cargo.lock)", + ); + continue; + } + // cargo reads git's user config for git dependencies and fetches; + // with every dependency locked by Cargo.lock it does not change a build. + if p == format!("{home}/.gitconfig") || p == format!("{home}/.gitignore_global") { + bump( + &mut r, + "~/.gitconfig, ~/.gitignore_global (git user config)", + ); + continue; + } + if SYSTEM.iter().any(|s| p_dir.starts_with(s)) || p == "/" { + bump(&mut r, "system (not in the key: a limit)"); + continue; + } + if p.starts_with("/tmp/") || p.starts_with("/run/") || p.starts_with("/var/tmp/") { + bump(&mut r, "/tmp, /run (locks and scratch)"); + continue; + } + r.undeclared_outside + .entry(p.to_string()) + .or_insert_with(|| o.comm.clone()); + } + r +} + +fn bump(r: &mut Report, why: &'static str) { + *r.ignored.entry(why).or_insert(0) += 1; +} + +fn judge_repo(m: &Manifest, places: &Places, rel: &str, o: &Opened, r: &mut Report) { + let comm = o.comm.as_str(); + if let Some(t) = &places.tracked { + let dir = format!("{rel}/"); + let in_tree = t.contains(rel) + || t.range(dir.clone()..) + .next() + .is_some_and(|f| f.starts_with(&dir)); + if !in_tree { + bump(r, "not in the tree at HEAD (made by the run)"); + return; + } + } + if covered(m, &places.manifest_rel, rel) || (o.dir && listed_covers(m, rel)) { + r.covered.insert(rel.to_string()); + } else { + r.undeclared + .entry(rel.to_string()) + .or_insert_with(|| comm.to_string()); + } +} + +/// The report as text, one finding per line; `ok` decides the last line. +pub fn render(m: &Manifest, r: &Report) -> String { + let mut s = String::new(); + s.push_str(&format!( + "AUDIT {} covered_repo_files={} uses_cargo={}\n", + m.gate, + r.covered.len(), + r.uses_cargo + )); + for (why, n) in &r.ignored { + s.push_str(&format!("IGNORED {n} {why}\n")); + } + for (p, who) in &r.undeclared { + s.push_str(&format!("UNDECLARED {p} (read by {who})\n")); + } + for (p, who) in &r.undeclared_outside { + s.push_str(&format!("UNDECLARED_OUTSIDE {p} (read by {who})\n")); + } + if !m.target_lock && r.uses_cargo { + s.push_str("TARGET_LOCK_BROKEN target_lock: none but the run started cargo or rustc\n"); + } + s.push_str(if r.ok(m) { + "RESULT PASS inputs complete\n" + } else { + "RESULT FAIL inputs incomplete\n" + }); + s +} + +/// Canonical form of `p`, or `p` itself when it does not exist yet. +pub fn canon(p: &Path) -> PathBuf { + std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::manifest; + + fn gate(extra: &str) -> Manifest { + let text = format!( + "gate: G\nmanifest_version: 1\nowner: t\nrequires:\n - host\ninputs:\n - crates/a/\n - crates/*/Cargo.toml\n{extra}run:\n exec: tests/run.sh\nexpects:\n exit: 0\n verdict: PASS\ntimeout: 1m\ncache: inputs_complete\n" + ); + manifest::parse(text.as_bytes()).unwrap() + } + + fn places(root: &Path) -> Places { + Places { + root: root.to_path_buf(), + manifest_rel: "tests/g.gate".into(), + target_dir: root.join("target"), + tmpdir: PathBuf::from("/audit/tmp"), + home: PathBuf::from("/home/op"), + tracked: None, + siblings: Vec::new(), + } + } + + fn line(comm: &str, path: &str) -> String { + format!("7<{comm}> openat(AT_FDCWD</r>, \"x\", O_RDONLY|O_CLOEXEC) = 3<{path}>\n") + } + + #[test] + fn parses_opens_execs_and_writes() { + let t = "12<sh> openat(AT_FDCWD</r>, \"a\", O_RDONLY) = 3</r/a>\n\ + 12<sh> openat(AT_FDCWD</r>, \"o\", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 4</r/o>\n\ + 13<sh> execve(\"/usr/bin/cargo\", [\"cargo\"], 0xffff /* 3 vars */) = 0\n\ + 13<cargo> +++ exited with 0 +++\n"; + let o = parse_strace(t); + assert_eq!(o.len(), 3); + assert_eq!( + o[0], + Opened { + comm: "sh".into(), + path: "/r/a".into(), + write_only: false, + dir: false, + truncates: false + } + ); + assert!(o[1].write_only); + assert!(o[1].truncates); + assert_eq!(o[2].path, "/usr/bin/cargo"); + } + + #[test] + fn a_dropped_input_is_caught_and_a_declared_one_is_not() { + let dir = tempdir(); + let root = dir.as_path(); + for f in [ + "crates/a/src/lib.rs", + "crates/b/src/lib.rs", + "crates/b/Cargo.toml", + ] { + std::fs::create_dir_all(root.join(f).parent().unwrap()).unwrap(); + std::fs::write(root.join(f), "x").unwrap(); + } + let r = root.display(); + let trace = line("rustc", &format!("{r}/crates/a/src/lib.rs")) + + &line("rustc", &format!("{r}/crates/b/src/lib.rs")) + + &line("cargo", &format!("{r}/crates/b/Cargo.toml")) + + &line("rustc", &format!("{r}/target/release/deps/liba.rlib")) + + &line("rustc", "/usr/lib/libc.so.6"); + let opened = parse_strace(&trace); + // crates/b/ is read but only its Cargo.toml is declared: FAIL. + let m = gate(""); + let rep = judge(&m, &places(root), &opened); + assert_eq!( + rep.undeclared.keys().collect::<Vec<_>>(), + vec!["crates/b/src/lib.rs"] + ); + assert!(!rep.ok(&m)); + // Declare it: PASS. + let m2 = gate(" - crates/b/\n"); + let rep2 = judge(&m2, &places(root), &opened); + assert!(rep2.ok(&m2), "{}", render(&m2, &rep2)); + assert!( + rep2.covered.contains("crates/b/Cargo.toml"), + "the * pattern covers it" + ); + } + + #[test] + fn outside_reads_need_outside_inputs() { + let dir = tempdir(); + let opened = parse_strace(&line( + "prefill_e2e2-4", + "/home/op/models/T/model.safetensors", + )); + let m = gate(""); + assert_eq!( + judge(&m, &places(&dir), &opened).undeclared_outside.len(), + 1 + ); + let m2 = gate("outside_inputs:\n - ~/models/T/\n"); + let rep = judge(&m2, &places(&dir), &opened); + assert!(rep.ok(&m2), "{}", render(&m2, &rep)); + } + + #[test] + fn a_file_the_run_truncated_is_its_output_but_a_read_before_is_an_input() { + let dir = tempdir(); + let log = "/home/op/logs/run.log"; + let write = format!( + "7<sh> openat(AT_FDCWD</r>, \"x\", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3<{log}>\n" + ); + // Written, then grepped: its own output. + let after = parse_strace(&(write.clone() + &line("grep", log))); + let m = gate(""); + let rep = judge(&m, &places(&dir), &after); + assert!(rep.ok(&m), "{}", render(&m, &rep)); + // Read before the run replaced it: the old bytes were an input. + let before = parse_strace(&(line("grep", log) + &write)); + assert_eq!( + judge(&m, &places(&dir), &before).undeclared_outside.len(), + 1 + ); + // The TMPDIR copy of a repository file is written by tar, then read: + // still that repository file. + std::fs::create_dir_all(dir.join("crates/z")).unwrap(); + std::fs::write(dir.join("crates/z/lib.rs"), "x").unwrap(); + let copy = "/audit/tmp/tmp.Ab12/crates/z/lib.rs"; + let t = format!( + "7<tar> openat(AT_FDCWD</r>, \"x\", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3<{copy}>\n" + ) + &line("rustc", copy); + let rep = judge(&m, &places(&dir), &parse_strace(&t)); + assert_eq!( + rep.undeclared.keys().collect::<Vec<_>>(), + vec!["crates/z/lib.rs"] + ); + } + + #[test] + fn a_copy_in_the_private_tmpdir_is_judged_as_the_repository_file() { + let dir = tempdir(); + std::fs::create_dir_all(dir.join("crates/z")).unwrap(); + std::fs::write(dir.join("crates/z/lib.rs"), "x").unwrap(); + let trace = line("tar", &format!("{}/crates/z/lib.rs", dir.display())) + + &line("rustc", "/audit/tmp/tmp.Ab12/crates/z/lib.rs") + + &line("rustc", "/audit/tmp/tmp.Ab12/scratch.o"); + let rep = judge(&gate(""), &places(&dir), &parse_strace(&trace)); + assert_eq!( + rep.undeclared.keys().collect::<Vec<_>>(), + vec!["crates/z/lib.rs"] + ); + assert_eq!(rep.ignored.get("private TMPDIR scratch"), Some(&1)); + } + + #[test] + fn target_lock_none_with_cargo_fails() { + let dir = tempdir(); + let m = gate("target_lock: none\n"); + let opened = parse_strace("9<sh> execve(\"/usr/bin/cargo\", [\"cargo\"], 0x1 /* 1 vars */) = 0\n9<cargo> openat(AT_FDCWD</r>, \"/etc/x\", O_RDONLY) = 3</etc/x>\n"); + let rep = judge(&m, &places(&dir), &opened); + assert!(rep.uses_cargo && !rep.ok(&m)); + assert!(render(&m, &rep).contains("TARGET_LOCK_BROKEN")); + } + + #[test] + fn files_the_run_made_in_the_tree_are_not_inputs() { + let dir = tempdir(); + let mut p = places(&dir); + p.tracked = Some(["src/x.c".to_string()].into_iter().collect()); + let r = dir.display(); + let trace = line("cc", &format!("{r}/src/x.c")) + + &line("ld", &format!("{r}/build/x.o")) + + &line("make", &format!("{r}/src")); + let rep = judge(&gate(""), &p, &parse_strace(&trace)); + // src/x.c and the src listing are tracked and undeclared; build/x.o is the run's own. + assert_eq!( + rep.undeclared.keys().collect::<Vec<_>>(), + vec!["src", "src/x.c"] + ); + assert_eq!( + rep.ignored.get("not in the tree at HEAD (made by the run)"), + Some(&1) + ); + } + + #[test] + fn a_listing_is_covered_by_listed_and_only_by_it() { + let dir = tempdir(); + std::fs::create_dir_all(dir.join("crates/b/tests")).unwrap(); + std::fs::write(dir.join("crates/b/tests/t.rs"), "x").unwrap(); + let t = format!( + "9<cargo> openat(AT_FDCWD</r>, \"x\", O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_DIRECTORY) = 3<{}/crates/b/tests>\n", + dir.display() + ); + let opened = parse_strace(&t); + assert!(opened[0].dir); + let rep = judge(&gate(""), &places(&dir), &opened); + assert_eq!( + rep.undeclared.keys().collect::<Vec<_>>(), + vec!["crates/b/tests"] + ); + let m = gate("listed:\n - crates/*/tests\n"); + assert!(judge(&m, &places(&dir), &opened).ok(&m)); + // A file read inside a listed directory is not covered by the listing. + let f = format!( + "9<rustc> openat(AT_FDCWD</r>, \"x\", O_RDONLY) = 3<{}/crates/b/tests/t.rs>\n", + dir.display() + ); + assert!(!judge(&m, &places(&dir), &parse_strace(&f)).ok(&m)); + } + + fn tempdir() -> PathBuf { + let d = std::env::temp_dir().join(format!( + "aien-audit-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + canon(&d) + } +} diff --git a/tools/aien-test/src/bin/aien-audit-inputs.rs b/tools/aien-test/src/bin/aien-audit-inputs.rs new file mode 100644 index 00000000..871bd058 --- /dev/null +++ b/tools/aien-test/src/bin/aien-audit-inputs.rs @@ -0,0 +1,169 @@ +//! aien-audit-inputs: run one gate under strace and list every file it read +//! that its manifest does not declare (see `aien_test::audit`). +//! +//! ```text +//! aien-audit-inputs [--root DIR] --target-dir DIR --work DIR GATE_FILE +//! aien-audit-inputs [--root DIR] --target-dir DIR --work DIR --trace FILE GATE_FILE +//! ``` +//! The first form runs `run.exec` with the manifest's args from the +//! repository root, with `CARGO_TARGET_DIR=--target-dir` (use a cold one) and +//! `TMPDIR=<work>/tmp`, and keeps the trace in `<work>/strace.txt`. The second +//! judges a trace made earlier with the same layout. Exit 0: inputs complete; +//! 1: something read is not declared; 2: usage or setup error. +use aien_test::audit::{self, Places}; +use aien_test::manifest; +use std::path::PathBuf; +use std::process::{exit, Command}; + +fn main() { + let mut root = PathBuf::from("."); + let (mut target, mut work, mut trace, mut gate): ( + Option<PathBuf>, + Option<PathBuf>, + Option<PathBuf>, + Option<PathBuf>, + ) = (None, None, None, None); + let mut siblings: Vec<PathBuf> = Vec::new(); + let mut as_rel: Option<String> = None; + let mut it = std::env::args().skip(1); + while let Some(a) = it.next() { + let mut val = || { + it.next() + .map(PathBuf::from) + .unwrap_or_else(|| usage(&format!("{a} needs a value"))) + }; + match a.as_str() { + "--root" => root = val(), + "--target-dir" => target = Some(val()), + "--work" => work = Some(val()), + "--trace" => trace = Some(val()), + "--sibling" => siblings.push(audit::canon(&val())), + "--manifest-rel" => as_rel = Some(val().to_string_lossy().into_owned()), + s if s.starts_with('-') => usage(&format!("unknown flag {s}")), + _ => gate = Some(PathBuf::from(&a)), + } + } + let (Some(target), Some(work), Some(gate)) = (target, work, gate) else { + usage("missing --target-dir, --work or GATE_FILE") + }; + let root = audit::canon(&root); + let gate_path = if gate.is_absolute() { + gate.clone() + } else { + root.join(&gate) + }; + let bytes = std::fs::read(&gate_path) + .unwrap_or_else(|e| fail(&format!("cannot read {}: {e}", gate_path.display()))); + let m = manifest::parse(&bytes).unwrap_or_else(|e| fail(&format!("bad manifest: {e:?}"))); + // `--manifest-rel REL`: judge an earlier trace with a manifest kept + // elsewhere (a later edit of the same gate), named as the repository path REL. + let manifest_rel = match &as_rel { + Some(r) => r.clone(), + None => audit::canon(&gate_path) + .strip_prefix(&root) + .map(|p| p.to_string_lossy().into_owned()) + .unwrap_or_else(|_| fail("the gate file is not inside --root")), + }; + // The tree at HEAD: what is not in it was made by the run. A dirty tree + // is judged anyway (its own files count as made by the run), with a warning. + let ls = Command::new("git") + .args(["ls-files", "-z"]) + .current_dir(&root) + .output() + .unwrap_or_else(|e| fail(&format!("git ls-files: {e}"))); + let tracked: std::collections::BTreeSet<String> = String::from_utf8_lossy(&ls.stdout) + .split('\0') + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect(); + let dirty = Command::new("git") + .args(["status", "--porcelain"]) + .current_dir(&root) + .output() + .map(|o| !o.stdout.is_empty()) + .unwrap_or(true); + if dirty { + println!("WARNING the tree has uncommitted changes; audit a clean checkout for the record"); + } + let tmpdir = work.join("tmp"); + std::fs::create_dir_all(&tmpdir) + .unwrap_or_else(|e| fail(&format!("cannot make {}: {e}", tmpdir.display()))); + std::fs::create_dir_all(&target) + .unwrap_or_else(|e| fail(&format!("cannot make {}: {e}", target.display()))); + let trace_path = match trace { + Some(t) => t, + None => { + let t = work.join("strace.txt"); + let status = Command::new("strace") + .args([ + "-f", + "-qq", + "-Y", + "-y", + "-e", + "trace=open,openat,openat2,execve", + "-e", + "status=successful", + "-o", + ]) + .arg(&t) + .arg(root.join(&m.exec)) + .args(&m.args) + .current_dir(&root) + .env("TMPDIR", &tmpdir) + .env("CARGO_TARGET_DIR", &target) + .status() + .unwrap_or_else(|e| fail(&format!("cannot start strace: {e}"))); + println!( + "GATE_EXIT {}", + status + .code() + .map(|c| c.to_string()) + .unwrap_or_else(|| "signal".into()) + ); + t + } + }; + let text = std::fs::read_to_string(&trace_path) + .unwrap_or_else(|e| fail(&format!("cannot read {}: {e}", trace_path.display()))); + let places = Places { + root, + manifest_rel, + target_dir: audit::canon(&target), + tmpdir: audit::canon(&tmpdir), + home: std::env::var_os("HOME") + .map(PathBuf::from) + .unwrap_or_default(), + tracked: Some(tracked), + siblings, + }; + let report = audit::judge(&m, &places, &audit::parse_strace(&text)); + let out = audit::render(&m, &report); + let _ = std::fs::write(work.join(format!("audit-{}.txt", m.gate)), &out); + // Every repository file the run read, declared or not: the closure to + // narrow `inputs` to. + let reads: Vec<&str> = report + .covered + .iter() + .map(String::as_str) + .chain(report.undeclared.keys().map(String::as_str)) + .collect(); + let mut reads = reads; + reads.sort(); + let _ = std::fs::write( + work.join(format!("reads-{}.txt", m.gate)), + reads.join("\n") + "\n", + ); + print!("{out}"); + exit(if report.ok(&m) { 0 } else { 1 }); +} + +fn usage(msg: &str) -> ! { + eprintln!("aien-audit-inputs: {msg}\nusage: aien-audit-inputs [--root DIR] --target-dir DIR --work DIR [--trace FILE] [--sibling DIR]... [--manifest-rel REL] GATE_FILE"); + exit(2) +} + +fn fail(msg: &str) -> ! { + eprintln!("aien-audit-inputs: {msg}"); + exit(2) +} diff --git a/tools/aien-test/src/block_first.rs b/tools/aien-test/src/block_first.rs new file mode 100644 index 00000000..72f58715 --- /dev/null +++ b/tools/aien-test/src/block_first.rs @@ -0,0 +1,273 @@ +//! Desk blocks go first (L309, 2026-10-20). +//! +//! The PR desk (Renda) carries many PRs in one "desk block" PR and records it +//! in `<state>/renda-block-<repo>.json`: +//! `{"open": {"sha": HEAD, "carried": [PR..], "heads": {"PR": SHA}, ..}, ..}`. +//! One judge run on the block head stands for every carried PR, so while a +//! block is open the worker judges its head before any other head of that +//! repository and does not judge a carried PR's own head by itself. +//! +//! A state file older than `MAX_AGE` is ignored, so a desk that stopped +//! cannot keep PRs from being judged forever. An explicit trigger file is an +//! operator's order and is never skipped. + +use std::collections::{BTreeSet, HashSet, VecDeque}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::time::{Duration, SystemTime}; + +/// A queued head: repository key, commit, and the trigger file to remove +/// once it has been served. +pub type Head = (String, String, Option<PathBuf>); + +/// Longest a block state file is believed without being rewritten. +pub const MAX_AGE: Duration = Duration::from_secs(24 * 3600); + +/// One open desk block. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Block { + pub repo: String, + pub head: String, + /// Heads of the PRs the block carries. + pub carried: BTreeSet<String>, +} + +/// Parse one `renda-block-<repo>.json`; None when no block is open or the +/// text is not what the desk writes. +pub fn parse(repo: &str, text: &str) -> Option<Block> { + let v: serde_json::Value = serde_json::from_str(text).ok()?; + let open = v.get("open")?; + let head = open.get("sha")?.as_str()?.to_ascii_lowercase(); + if !crate::worker::valid_sha(&head) { + return None; + } + let numbers: BTreeSet<u64> = open + .get("carried") + .and_then(|c| c.as_array()) + .map(|a| a.iter().filter_map(|n| n.as_u64()).collect()) + .unwrap_or_default(); + let heads = open.get("heads").and_then(|h| h.as_object()); + let carried = numbers + .iter() + .filter_map(|n| heads?.get(&n.to_string())?.as_str()) + .map(str::to_ascii_lowercase) + .filter(|s| crate::worker::valid_sha(s)) + .collect(); + Some(Block { + repo: repo.to_string(), + head, + carried, + }) +} + +/// The open blocks of `repos`, read from `state_root`. A file not rewritten +/// within `MAX_AGE` of `now` is ignored. +pub fn open_blocks(state_root: &Path, repos: &[String], now: SystemTime) -> Vec<Block> { + let mut out = Vec::new(); + for repo in repos { + if !crate::worker::valid_repo_key(repo) { + continue; + } + let path = state_root.join(format!("renda-block-{repo}.json")); + let fresh = fs::metadata(&path) + .and_then(|m| m.modified()) + .ok() + .and_then(|t| now.duration_since(t).ok().or(Some(Duration::ZERO))) + .is_some_and(|age| age <= MAX_AGE); + if !fresh { + continue; + } + if let Some(b) = fs::read_to_string(&path).ok().and_then(|t| parse(repo, &t)) { + out.push(b); + } + } + out +} + +/// The next head to judge. A block head not yet `tried` and without a bundle +/// comes first (taken from the queue when it is there, otherwise made, with +/// its trigger file when one exists). Otherwise the front of the queue, except +/// that a head with no trigger file which a block carries is dropped. +pub fn next_head( + queue: &mut VecDeque<Head>, + blocks: &[Block], + trigger_dir: &Path, + bundled: &dyn Fn(&str, &str) -> bool, + tried: &mut HashSet<(String, String)>, +) -> Option<Head> { + for b in blocks { + let key = (b.repo.clone(), b.head.clone()); + if tried.contains(&key) || bundled(&b.repo, &b.head) { + continue; + } + tried.insert(key); + if let Some(i) = queue + .iter() + .position(|(r, s, _)| *r == b.repo && *s == b.head) + { + return queue.remove(i); + } + let trigger = trigger_dir.join(format!("{}.{}", b.repo, b.head)); + return Some(( + b.repo.clone(), + b.head.clone(), + trigger.exists().then_some(trigger), + )); + } + while let Some((repo, sha, trigger)) = queue.pop_front() { + if !tried.insert((repo.clone(), sha.clone())) { + // Served already this round; a leftover trigger file goes with it. + if let Some(f) = trigger { + let _ = fs::remove_file(f); + } + continue; + } + let carried = trigger.is_none() + && blocks + .iter() + .any(|b| b.repo == repo && b.carried.contains(&sha)); + if carried { + tried.remove(&(repo, sha)); + continue; + } + return Some((repo, sha, trigger)); + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sha(c: char) -> String { + c.to_string().repeat(40) + } + + fn state(name: &str, text: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("block-first-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(d.join("trigger")).unwrap(); + fs::write(d.join("renda-block-r.json"), text).unwrap(); + d + } + + fn block_text(head: &str) -> String { + format!( + r#"{{"open": {{"pr": 9, "sha": "{head}", "carried": [1, 2], + "heads": {{"1": "{}", "2": "{}", "3": "{}"}}}}, "size": 12}}"#, + sha('1'), + sha('2'), + sha('3') + ) + } + + fn drain( + q: Vec<Head>, + blocks: &[Block], + dir: &Path, + bundled: &dyn Fn(&str, &str) -> bool, + ) -> Vec<String> { + let mut q: VecDeque<Head> = q.into(); + let mut tried = HashSet::new(); + let mut out = Vec::new(); + while let Some((_, s, _)) = next_head(&mut q, blocks, dir, bundled, &mut tried) { + out.push(s); + } + out + } + + fn head(c: char) -> Head { + ("r".to_string(), sha(c), None) + } + + #[test] + fn block_head_goes_first_and_carried_heads_are_skipped() { + let d = state("order", &block_text(&sha('b'))); + let blocks = open_blocks(&d, &["r".to_string()], SystemTime::now()); + assert_eq!(blocks.len(), 1); + assert_eq!(blocks[0].carried.len(), 2); + // queue sorted by sha as GitHub polling leaves it: 1, 2, 3, b + let q = vec![head('1'), head('2'), head('3'), head('b')]; + let got = drain(q, &blocks, &d.join("trigger"), &|_, _| false); + assert_eq!(got, vec![sha('b'), sha('3')]); + } + + #[test] + fn block_head_missing_from_the_queue_is_made_first() { + let d = state("missing", &block_text(&sha('b'))); + let blocks = open_blocks(&d, &["r".to_string()], SystemTime::now()); + let got = drain(vec![head('3')], &blocks, &d.join("trigger"), &|_, _| false); + assert_eq!(got, vec![sha('b'), sha('3')]); + } + + #[test] + fn judged_block_head_is_not_queued_again_and_carried_stay_skipped() { + let d = state("done", &block_text(&sha('b'))); + let blocks = open_blocks(&d, &["r".to_string()], SystemTime::now()); + let b = sha('b'); + let got = drain( + vec![head('1'), head('3')], + &blocks, + &d.join("trigger"), + &|_, s| s == b, + ); + assert_eq!(got, vec![sha('3')]); + } + + #[test] + fn a_trigger_file_for_a_carried_head_is_still_served() { + let d = state("trigger", &block_text(&sha('b'))); + let blocks = open_blocks(&d, &["r".to_string()], SystemTime::now()); + let t = d.join("trigger").join(format!("r.{}", sha('1'))); + fs::write(&t, "").unwrap(); + let q = vec![("r".to_string(), sha('1'), Some(t))]; + let got = drain(q, &blocks, &d.join("trigger"), &|_, _| false); + assert_eq!(got, vec![sha('b'), sha('1')]); + } + + #[test] + fn block_head_trigger_file_made_mid_round_travels_with_the_head() { + let d = state("mid", &block_text(&sha('b'))); + let blocks = open_blocks(&d, &["r".to_string()], SystemTime::now()); + let t = d.join("trigger").join(format!("r.{}", sha('b'))); + fs::write(&t, "").unwrap(); + let mut q: VecDeque<Head> = VecDeque::new(); + let mut tried = HashSet::new(); + let got = next_head( + &mut q, + &blocks, + &d.join("trigger"), + &|_, _| false, + &mut tried, + ); + assert_eq!(got, Some(("r".to_string(), sha('b'), Some(t)))); + } + + #[test] + fn no_open_block_leaves_the_order_alone() { + let d = state("none", r#"{"open": null, "size": 12}"#); + let blocks = open_blocks(&d, &["r".to_string()], SystemTime::now()); + assert!(blocks.is_empty()); + let got = drain( + vec![head('1'), head('b')], + &blocks, + &d.join("trigger"), + &|_, _| false, + ); + assert_eq!(got, vec![sha('1'), sha('b')]); + } + + #[test] + fn a_stale_state_file_and_other_repos_are_ignored() { + let d = state("stale", &block_text(&sha('b'))); + let later = SystemTime::now() + MAX_AGE + Duration::from_secs(60); + assert!(open_blocks(&d, &["r".to_string()], later).is_empty()); + assert!(open_blocks(&d, &["other".to_string()], SystemTime::now()).is_empty()); + } + + #[test] + fn unreadable_state_is_no_block() { + assert_eq!(parse("r", "not json"), None); + assert_eq!(parse("r", r#"{"open": {"sha": "short"}}"#), None); + } +} diff --git a/tools/aien-test/src/cache.rs b/tools/aien-test/src/cache.rs index 6a2e00cb..272c6233 100644 --- a/tools/aien-test/src/cache.rs +++ b/tools/aien-test/src/cache.rs @@ -468,6 +468,230 @@ pub fn explain_chain( out } +// ---- across heads ------------------------------------------------------ +// +// The key above has no commit in it, but the worker gives every head its own +// evidence store (`evidence/<repo>/<sha>`), so a result made for one head was +// never found by another. The shared store below closes that gap without a +// second cache: a fresh receipt that `usable` accepts is copied, with its log +// blobs and the dependency receipts its key rests on, into +// `<state>/gate-cache/<repo>/` (itself a `Store`) under a pointer +// `keys/<key>`. A head that misses in its own store imports that closure into +// its own store and then takes the ordinary hit path: the reuse receipt says +// `reused_from` (the source digest) and `reused_from_commit` (the source +// head), the bundle entry is `cached` with the same two facts. Nothing is +// reused that `lookup` would not reuse inside one head. +// +// Only a gate whose result is a function of its key may cross heads; see +// [`cross_head`]. A gate whose author has not promised complete inputs +// (`cache: inputs_complete`) crosses heads only between byte-identical trees: +// SC-TEST reads the root README.md and lists only crates/, tools/, scripts/ +// (tests/local_ci.rs, the U gate). The judge binary and the exec helper are part of the +// machine object (`runner::identity`), so an entry never outlives either. + +/// Why a gate's result stays inside the head it was made for. A gate that +/// gets one of these still uses the per-head cache exactly as before. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Local { + /// `cache: never`: the author's rule. + CacheNever, + /// gb10 or nvrm: the result depends on chip state (clocks, memory left, + /// other holders of the GPU), which no input file describes. + ChipState, + /// bare_metal or aarch64-only boot gates: the machine is the input. + BareMetal, + /// `requires: operator`: a person ran a step the manifest cannot see. + Operator, + /// `cache_scope: hardware`: the author says the result belongs to one + /// piece of hardware (timing and chip gates use it). + HardwareScope, + /// `exactness: APPROXIMATE` or `ADVISORY`: the result is not exact, so + /// equal inputs do not promise an equal result (timing, sampling). + NotExact, +} + +impl Local { + pub fn text(self) -> &'static str { + match self { + Local::CacheNever => "the manifest says cache: never", + Local::ChipState => "a GPU gate: its result depends on chip state no input describes", + Local::BareMetal => "a bare-metal gate: the machine itself is the input", + Local::Operator => "an operator step: a person did something the inputs cannot show", + Local::HardwareScope => { + "cache_scope: hardware, the result belongs to one piece of hardware" + } + Local::NotExact => { + "not EXACT or BOUNDED, so equal inputs do not promise an equal result" + } + } + } +} + +/// How far a gate's result may travel to other heads with the same key. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Reach { + /// `cache: inputs_complete` and real inputs: any head whose declared + /// inputs (and the rest of the key) are identical. + Inputs, + /// Any other cacheable gate: only a head whose whole tree is identical + /// (a squash merge of an up-to-date PR, a re-push, a duplicate PR). Its + /// manifest promises no more, so the whole tree is its input. + Tree, +} + +/// May this gate's result be reused by another head with the same key, and +/// how far? The first reason it may not wins (fail closed). +pub fn cross_head(m: &crate::manifest::Manifest) -> Result<Reach, Local> { + use crate::manifest::{CacheScope, Exactness}; + let req = |r: &str| m.requires.iter().any(|x| x == r); + if !m.cache_allowed { + return Err(Local::CacheNever); + } + if req("gb10") || req("nvrm") { + return Err(Local::ChipState); + } + if req("bare_metal") || req("analog_eligible") { + return Err(Local::BareMetal); + } + if req("operator") { + return Err(Local::Operator); + } + if m.cache_scope == CacheScope::Hardware { + return Err(Local::HardwareScope); + } + if !matches!(m.exactness, Exactness::Exact | Exactness::Bounded) { + return Err(Local::NotExact); + } + let whole = |i: &str| { + let t = i.trim().trim_start_matches("./").trim_end_matches('/'); + t.is_empty() || t == "." || t.split('/').next().is_some_and(|c| c.contains('*')) + }; + // No promise, no inputs, or the whole tree as an input: the key cannot + // tell two trees apart, so the tree id must. + if !m.inputs_complete || m.inputs.is_empty() || m.inputs.iter().any(|i| whole(i)) { + return Ok(Reach::Tree); + } + Ok(Reach::Inputs) +} + +/// The name of a shared entry: the key alone for [`Reach::Inputs`], the key +/// and the tree id for [`Reach::Tree`]. +pub fn slot(key: &str, reach: Reach, tree: &str) -> String { + match reach { + Reach::Inputs => key.to_string(), + Reach::Tree => format!("{key}-{tree}"), + } +} + +/// The cross-head store of one repository: `<dir>/<digest>.json`, +/// `<dir>/blobs/`, `<dir>/keys/<key>` (one line: the receipt digest) and +/// `<dir>/locks/<key>.lock`. +#[derive(Debug, Clone)] +pub struct Shared { + dir: std::path::PathBuf, +} + +/// Held while one head decides about a key and, on a miss, runs the gate and +/// publishes the result, so a second judge of the same key waits and reuses +/// instead of running it again. +pub struct KeyLock { + _lock: crate::resources::TargetLock, +} + +impl Shared { + pub fn new(dir: &Path) -> Shared { + Shared { + dir: dir.to_path_buf(), + } + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + fn store(&self) -> Store { + Store::new(&self.dir) + } + + fn pointer(&self, slot: &str) -> std::path::PathBuf { + self.dir.join("keys").join(slot) + } + + pub fn lock(&self, slot: &str) -> std::io::Result<KeyLock> { + let path = self.dir.join("locks").join(format!("{slot}.lock")); + Ok(KeyLock { + _lock: crate::resources::lock_target_dir(&path)?, + }) + } + + /// The source receipt the pointer for `key` names, if the store holds it + /// intact and it really carries that key. + pub fn source(&self, slot: &str, key: &str) -> Option<Stored> { + let digest = std::fs::read_to_string(self.pointer(slot)).ok()?; + let src = self.store().get_receipt(digest.trim())?; + (src.value["volatile"]["cache"]["key"] == key).then_some(src) + } + + /// Copy `digest` and everything its key rests on from `from` to `to`: + /// the receipt, its log blobs, every dependency receipt it names and, for + /// a dependency that was itself reused, the receipt it was reused from. + fn copy_closure(from: &Store, to: &Store, digest: &str) -> Result<(), String> { + let mut todo = vec![digest.to_string()]; + let mut seen = std::collections::BTreeSet::new(); + while let Some(d) = todo.pop() { + if !seen.insert(d.clone()) { + continue; + } + let r = from + .get_receipt(&d) + .ok_or_else(|| format!("receipt {} is missing or damaged", short(&d)))?; + for member in ["stdout_sha256", "stderr_sha256"] { + if let Some(sha) = r.value["core"][member].as_str() { + if let Some(bytes) = from.read_blob(sha) { + to.put_blob(&bytes).map_err(|e| e.to_string())?; + } + } + } + to.put_receipt(&r.value).map_err(|e| e.to_string())?; + if let Some(deps) = r.value["core"]["dependencies"].as_array() { + todo.extend( + deps.iter() + .filter_map(|x| x["receipt"].as_str().map(str::to_string)), + ); + } + if let Some(src) = r.value["volatile"]["cache"]["reused_from"].as_str() { + todo.push(src.to_string()); + } + } + Ok(()) + } + + /// Bring the shared source of `key` into a head's own store. Ok(None) + /// when there is none; the head's own `lookup` then decides as always. + pub fn import(&self, slot: &str, key: &str, head: &Store) -> Result<Option<String>, String> { + let Some(src) = self.source(slot, key) else { + return Ok(None); + }; + Self::copy_closure(&self.store(), head, &src.digest)?; + Ok(Some(src.digest)) + } + + /// Publish the fresh receipt `digest` of a head's store for `key`. The + /// caller has checked it with `usable`; the pointer is written last, by + /// rename, so a reader sees either no entry or a whole one. + pub fn publish(&self, slot: &str, digest: &str, head: &Store) -> Result<(), String> { + Self::copy_closure(head, &self.store(), digest)?; + let keys = self.dir.join("keys"); + std::fs::create_dir_all(&keys) + .map_err(|e| format!("cannot create {}: {e}", keys.display()))?; + let tmp = keys.join(format!(".tmp-{slot}-{}", std::process::id())); + std::fs::write(&tmp, format!("{digest}\n")) + .map_err(|e| format!("cannot write key pointer: {e}"))?; + std::fs::rename(&tmp, self.pointer(slot)) + .map_err(|e| format!("cannot publish key pointer: {e}")) + } +} + #[cfg(test)] mod tests { use super::*; @@ -569,7 +793,7 @@ mod tests { fn reused_from(o: &Outcome) -> Option<&str> { match &o.cache { - CacheNote::Reused { from } => Some(from), + CacheNote::Reused { from, .. } => Some(from), _ => None, } } diff --git a/tools/aien-test/src/cli.rs b/tools/aien-test/src/cli.rs index 40109550..40c52130 100644 --- a/tools/aien-test/src/cli.rs +++ b/tools/aien-test/src/cli.rs @@ -25,7 +25,7 @@ //! aien-test plan [--base REF] [--repo NAME] [--operator] [--allow-dirty] //! aien-test status [--state-dir DIR] //! aien-test verify COMMIT [--repo NAME] [--base REF] [--state-dir DIR] [--release] -//! aien-test worker [--once REPO SHA] [--poll SECS] [--repos LIST] [--github] [--iterations N] +//! aien-test worker [--once REPO SHA | --batch REPO SHA...] [--batch-host N] [--batch-heads N] [--poll SECS] [--repos LIST] [--github] [--iterations N] //! [--state-dir DIR] [--key FILE] [--clones DIR] [--wt-root DIR] [--wt-tool FILE] [--siblings FILE] [--sandbox user|none --dev-unsandboxed] //! ``` //! @@ -44,10 +44,10 @@ pub const USAGE: &str = "usage: aien-test plan [--base REF] [--repo NAME] [--operator] [--allow-dirty] aien-test status [--state-dir DIR] aien-test verify COMMIT [--repo NAME] [--base REF] [--state-dir DIR] [--release] - aien-test worker [--once REPO SHA] [--poll SECS] [--repos A,B] [--github] [--iterations N] + aien-test worker [--once REPO SHA | --batch REPO SHA...] [--batch-host N] [--batch-heads N] [--poll SECS] [--repos A,B] [--github] [--iterations N] [--state-dir DIR] [--key FILE] [--clones DIR] [--wt-root DIR] [--wt-tool FILE] [--siblings FILE] [--sandbox user|none --dev-unsandboxed] flags: --evidence-dir DIR --allow-dirty --no-cache --release --jobs host=N,qemu=M --gpu-wait 0|DURATION --wait-gpu - --sandbox none|user --base REF --operator"; + --sandbox none|user --base REF --operator --shared-cache DIR (run)"; /// Which gates `test` runs. #[derive(Debug, Clone, PartialEq, Eq)] @@ -96,6 +96,9 @@ pub struct Cli { /// `identity` only: the compiler identity string (default empty: nothing /// here builds yet). pub compiler_identity: String, + /// `--shared-cache DIR` (run only): the cross-head store the worker keeps + /// in `<state>/gate-cache/<repo>`, for one gate judged by hand. + pub shared_cache: Option<PathBuf>, /// `identity` only: `--flag F`, repeatable, order kept. pub flags: Vec<String>, /// `identity` only: needed for `cache_scope: hardware`. @@ -128,6 +131,12 @@ pub struct Cli { pub siblings: Option<PathBuf>, /// worker: `--once REPO SHA`. pub once: Option<(String, String)>, + /// worker: `--batch REPO SHA SHA...` (judge these heads together). + pub batch: Option<(String, Vec<String>)>, + /// worker: `--batch-host N` (host slots a batch shares). + pub batch_host: Option<usize>, + /// worker: `--batch-heads N` (heads per batch in the loop). + pub batch_heads: Option<usize>, /// worker: `--poll SECS` (default 30). pub poll: Option<u64>, /// worker: `--repos A,B`. @@ -162,7 +171,10 @@ fn parse_selection(s: &str) -> Result<Selection, String> { const COMMANDS: [&str; 9] = [ "run", "test", "why", "list", "identity", "plan", "status", "verify", "worker", ]; -const WORKER_FLAGS: [&str; 13] = [ +const WORKER_FLAGS: [&str; 16] = [ + "--batch", + "--batch-host", + "--batch-heads", "--dev-unsandboxed", "--key", "--clones", @@ -211,10 +223,14 @@ pub fn parse_args(argv: &[String]) -> Result<Cli, String> { let mut wt_tool: Option<PathBuf> = None; let mut siblings: Option<PathBuf> = None; let mut once: Option<(String, String)> = None; + let mut batch: Option<(String, Vec<String>)> = None; + let mut batch_host: Option<usize> = None; + let mut batch_heads: Option<usize> = None; let mut poll: Option<u64> = None; let mut repos: Vec<String> = Vec::new(); let mut github = false; let mut iterations: Option<u64> = None; + let mut shared_cache: Option<PathBuf> = None; let mut worker_flags: Vec<&str> = Vec::new(); let mut i = 1; let value = |i: &mut usize, a: &str| -> Result<String, String> { @@ -230,6 +246,8 @@ pub fn parse_args(argv: &[String]) -> Result<Cli, String> { break; } else if a == "--evidence-dir" { evidence_dir = Some(PathBuf::from(value(&mut i, a)?)); + } else if a == "--shared-cache" { + shared_cache = Some(PathBuf::from(value(&mut i, a)?)); } else if a == "--jobs" { jobs = parse_jobs(&value(&mut i, a)?)?; } else if a == "--compiler-identity" || a == "--flag" || a == "--hardware-identity" { @@ -292,6 +310,38 @@ pub fn parse_args(argv: &[String]) -> Result<Cli, String> { return Err("--once needs REPO and a 40-hex SHA".to_string()); } once = Some((r, s.to_ascii_lowercase())); + } else if a == "--batch" { + worker_flags.push("--batch"); + let r = value(&mut i, a)?; + let mut shas = Vec::new(); + while argv.get(i + 1).is_some_and(|s| !s.starts_with("--")) { + let s = value(&mut i, a)?; + if s.len() != 40 || !s.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(format!("--batch needs REPO and 40-hex SHAs, not {s:?}")); + } + shas.push(s.to_ascii_lowercase()); + } + if shas.is_empty() { + return Err("--batch needs REPO and at least one 40-hex SHA".to_string()); + } + batch = Some((r, shas)); + } else if a == "--batch-host" || a == "--batch-heads" { + worker_flags.push(if a == "--batch-host" { + "--batch-host" + } else { + "--batch-heads" + }); + let v = value(&mut i, a)?; + let n = v + .parse::<usize>() + .ok() + .filter(|n| *n > 0) + .ok_or_else(|| format!("{a} needs a positive number, not {v:?}"))?; + if a == "--batch-host" { + batch_host = Some(n); + } else { + batch_heads = Some(n); + } } else if a == "--poll" { worker_flags.push("--poll"); let v = value(&mut i, a)?; @@ -357,6 +407,9 @@ pub fn parse_args(argv: &[String]) -> Result<Cli, String> { if repo.is_some() && !["plan", "verify", "worker"].contains(&name) { return Err("--repo only applies to plan, verify and worker".to_string()); } + if shared_cache.is_some() && name != "run" { + return Err("--shared-cache only applies to run".to_string()); + } if state_dir.is_some() && !["status", "verify", "worker"].contains(&name) { return Err("--state-dir only applies to status, verify and worker".to_string()); } @@ -415,10 +468,14 @@ pub fn parse_args(argv: &[String]) -> Result<Cli, String> { wt_tool, siblings, once, + batch, + batch_host, + batch_heads, poll, repos, github, iterations, + shared_cache, }) } diff --git a/tools/aien-test/src/evidence.rs b/tools/aien-test/src/evidence.rs index 2a71ed58..e2e51715 100644 --- a/tools/aien-test/src/evidence.rs +++ b/tools/aien-test/src/evidence.rs @@ -252,6 +252,39 @@ impl Store { } Ok((digest, path)) } + + /// The bytes of blob `sha`, only if they still hash to `sha`. + pub fn read_blob(&self, sha: &str) -> Option<Vec<u8>> { + if !self.blob_exists(sha) { + return None; + } + let bytes = fs::read(self.dir.join("blobs").join(format!("{sha}.log"))).ok()?; + (sha256_hex(&bytes) == sha).then_some(bytes) + } + + /// The one receipt `<digest>.json`, with the same checks `Index::load` + /// makes (bytes hash to the name, JSON, receipt schema). None otherwise. + pub fn get_receipt(&self, digest: &str) -> Option<Stored> { + if !is_sha256_hex(digest) { + return None; + } + let path = self.dir.join(format!("{digest}.json")); + let bytes = fs::read(&path).ok()?; + let body = bytes.strip_suffix(b"\n").unwrap_or(&bytes); + if sha256_hex(body) != digest { + return None; + } + let value: Value = serde_json::from_slice(body).ok()?; + if value["schema"] != SCHEMA { + return None; + } + let modified = fs::metadata(&path).and_then(|m| m.modified()).ok(); + Some(Stored { + digest: digest.to_string(), + value, + modified, + }) + } } /// A receipt read back from a store. `digest` comes from the file name and diff --git a/tools/aien-test/src/judge_once_tests.rs b/tools/aien-test/src/judge_once_tests.rs new file mode 100644 index 00000000..3525df85 --- /dev/null +++ b/tools/aien-test/src/judge_once_tests.rs @@ -0,0 +1,503 @@ +//! Judge once (Drake 2026-10-20): the cross-head store, its key, the rules +//! for what may leave a head, and the batch budget. Red/green: each reuse +//! test also shows the miss one byte away. + +use crate::cache::{self, Local, Reach, Shared}; +use crate::evidence::{Index, Store}; +use crate::manifest; +use crate::resources::{Budget, GpuConfig, Hardware}; +use crate::runner::{self, CacheNote, Options, Outcome}; +use crate::testutil::{git, init_repo, write_file, TempDir}; +use crate::verdict::Verdict; +use serde_json::Value; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +const PASS: &str = "#!/bin/sh\necho x >> \"$1\"\necho \"AIEN-OBS n 3\"\necho PASS\n"; +const FAIL: &str = "#!/bin/sh\necho x >> \"$1\"\necho \"AIEN-OBS n 3\"\nexit 1\n"; + +fn gate(counter: &Path, version: u8, extra: &str) -> String { + format!( + "gate: J-A\nmanifest_version: {version}\nowner: t\nrequires:\n - host\ninputs:\n - data/\nrun:\n exec: tools/run.sh\n args: [\"{}\"]\nexpects:\n exit: 0\n observe: [\"n == 3\"]\n verdict: PASS\ntimeout: 20s\n{extra}", + counter.display() + ) +} + +/// One repository whose commits stand for different heads; each head gets +/// its own evidence store, as the worker gives it, and all share one +/// cross-head store. +struct Fx { + repo: TempDir, + ev: TempDir, + scratch: TempDir, +} + +impl Fx { + fn new(script: &str, version: u8, extra: &str) -> Fx { + let scratch = TempDir::new("jo-scratch"); + let text = gate(&scratch.path().join("a.count"), version, extra); + let repo = init_repo( + "jo-repo", + &[ + ("tools/run.sh", script, true), + ("tests/a.gate", text.as_str(), false), + ("data/in.txt", "one\n", false), + ("README", "hello\n", false), + ], + ); + Fx { + repo, + ev: TempDir::new("jo-ev"), + scratch, + } + } + fn runs(&self) -> usize { + fs::read_to_string(self.scratch.path().join("a.count")).map_or(0, |s| s.lines().count()) + } + fn head(&self) -> String { + runner::head(self.repo.path()).unwrap() + } + fn shared_dir(&self) -> PathBuf { + self.ev.path().join("gate-cache") + } + /// The options the worker would give the head now checked out. + fn opts(&self) -> Options { + let mut o = Options::new(self.ev.path().join("evidence").join(self.head())); + o.kill_grace = Duration::from_millis(300); + o.hardware = Hardware { + gb10_present: false, + qemu_available: false, + }; + o.gpu = GpuConfig::rooted_at(self.scratch.path()); + o.shared_cache = Some(Shared::new(&self.shared_dir())); + o + } + fn run(&self) -> Outcome { + runner::run_gate( + self.repo.path(), + &self.repo.path().join("tests/a.gate"), + &self.opts(), + ) + .unwrap() + } + fn commit(&self, rel: &str, content: &str) -> String { + write_file(self.repo.path(), rel, content, false); + git(self.repo.path(), &["add", "-A"]); + git(self.repo.path(), &["commit", "-q", "-m", rel]); + self.head() + } + /// A new commit with the very same tree (a re-push, a squash merge of an + /// up-to-date PR). + fn same_tree_commit(&self) -> String { + git( + self.repo.path(), + &["commit", "-q", "--allow-empty", "-m", "same tree"], + ); + self.head() + } + fn receipt(o: &Outcome) -> Value { + serde_json::from_slice(&fs::read(o.receipt_path.as_ref().unwrap()).unwrap()).unwrap() + } +} + +fn reused(o: &Outcome) -> Option<(&str, &str)> { + match &o.cache { + CacheNote::Reused { from, commit } => Some((from, commit)), + _ => None, + } +} + +fn parsed(text: &str) -> manifest::Manifest { + manifest::parse(text.as_bytes()).unwrap_or_else(|e| panic!("{e:?}\n{text}")) +} + +// ---- what may leave a head ---------------------------------------------- + +#[test] +fn cross_head_rules_name_what_stays_in_its_head_and_why() { + let c = Path::new("/tmp/c"); + let v2 = |extra: &str| parsed(&gate(c, 2, extra)); + assert_eq!(cache::cross_head(&v2("")), Ok(Reach::Tree)); + assert_eq!( + cache::cross_head(&v2("cache: inputs_complete\n")), + Ok(Reach::Inputs) + ); + assert_eq!( + cache::cross_head(&v2("cache: never\n")), + Err(Local::CacheNever) + ); + assert_eq!( + cache::cross_head(&v2("cache: inputs_complete\ncache_scope: hardware\n")), + Err(Local::HardwareScope) + ); + assert_eq!( + cache::cross_head(&v2("cache: inputs_complete\nexactness: APPROXIMATE\n")), + Err(Local::NotExact) + ); + let swap = + |from: &str, to: &str| parsed(&gate(c, 2, "cache: inputs_complete\n").replace(from, to)); + assert_eq!( + cache::cross_head(&swap(" - host\n", " - gb10\n")), + Err(Local::ChipState) + ); + assert_eq!( + cache::cross_head(&swap(" - host\n", " - host\n - operator\n")), + Err(Local::Operator) + ); + // A promise without real inputs is no promise: the tree decides. + assert_eq!( + cache::cross_head(&swap("inputs:\n - data/\n", "")), + Ok(Reach::Tree) + ); + assert_eq!(cache::slot("k", Reach::Inputs, "t"), "k"); + assert_eq!(cache::slot("k", Reach::Tree, "t"), "k-t"); +} + +// ---- the key --------------------------------------------------------------- + +#[test] +fn key_flips_on_any_declared_input_or_build_file_byte_and_not_on_others() { + let fx = Fx::new(PASS, 1, ""); + let m = parsed(&fs::read_to_string(fx.repo.path().join("tests/a.gate")).unwrap()); + let digest = || runner::build_inputs_digest(fx.repo.path(), None, &m); + let d0 = digest(); + fx.commit("README", "changed\n"); + assert_eq!(digest(), d0, "an undeclared file is not in the key"); + fx.commit("data/in.txt", "onf\n"); + let d1 = digest(); + assert_ne!(d1, d0, "one declared byte flips the key"); + fx.commit("Cargo.lock", "# lock\n"); + let d2 = digest(); + assert_ne!(d2, d1, "a repository build file joins every key"); + fx.commit("rust-toolchain.toml", "[toolchain]\n"); + assert_ne!(digest(), d2, "so does the toolchain pin"); +} + +#[test] +fn the_judge_binary_is_part_of_the_machine_and_so_of_the_key() { + let fx = Fx::new(PASS, 1, ""); + let m = parsed(&fs::read_to_string(fx.repo.path().join("tests/a.gate")).unwrap()); + let hw = Hardware { + gb10_present: false, + qemu_available: false, + }; + let path = fx.repo.path().join("tests/a.gate"); + let id = runner::identity( + fx.repo.path(), + &path, + &m, + &hw, + crate::sandbox::Sandbox::None, + ) + .unwrap(); + let sha = runner::judge_sha256().expect("the test binary can be read"); + assert_eq!(id.machine["judge_sha256"], sha.as_str()); + let o = fx.run(); + assert_eq!( + Fx::receipt(&o)["core"]["machine"]["judge_sha256"], + sha.as_str() + ); +} + +// ---- reuse across heads, red/green ------------------------------------------- + +#[test] +fn a_complete_inputs_result_is_reused_by_another_head_and_not_one_byte_away() { + let fx = Fx::new(PASS, 1, "cache: inputs_complete\n"); + let h1 = fx.head(); + let first = fx.run(); + assert_eq!((first.verdict, fx.runs()), (Verdict::Pass, 1)); + assert_eq!(reused(&first), None); + + // Another head: only an undeclared file differs. Reused, not run. + let h2 = fx.commit("README", "other head\n"); + let second = fx.run(); + assert_eq!((second.verdict, fx.runs()), (Verdict::Pass, 1)); + let src = first.receipt_digest.clone().unwrap(); + assert_eq!(reused(&second), Some((src.as_str(), h1.as_str()))); + let r = Fx::receipt(&second); + assert_eq!(r["core"]["commit"], h2.as_str()); + assert_eq!(r["volatile"]["cache"]["reused"], true); + assert_eq!(r["volatile"]["cache"]["reused_from"], src.as_str()); + assert_eq!(r["volatile"]["cache"]["reused_from_commit"], h1.as_str()); + // The source receipt and its logs came along into this head's own store. + let store = Store::new(&fx.opts().evidence_dir); + let index = Index::load(&store); + let copied = index.get(&src).expect("source receipt imported"); + assert!(store.blob_exists(copied.value["core"]["stdout_sha256"].as_str().unwrap())); + + // One declared byte different: the gate runs again. + fx.commit("data/in.txt", "onf\n"); + let third = fx.run(); + assert_eq!((third.verdict, fx.runs()), (Verdict::Pass, 2)); + assert_eq!(reused(&third), None); + match &third.cache { + CacheNote::Miss(why) => assert!(why.contains("across heads"), "{why}"), + other => panic!("{other:?}"), + } +} + +#[test] +fn without_the_promise_only_an_identical_tree_reuses() { + // The gate reads nothing undeclared here, but its manifest does not say + // so: an undeclared change (README) must run it again (SC-TEST reads the + // root README.md), the same tree under a new commit reuses it. + let fx = Fx::new(PASS, 1, ""); + fx.run(); + assert_eq!(fx.runs(), 1); + fx.commit("README", "other head\n"); + let second = fx.run(); + assert_eq!((fx.runs(), reused(&second)), (2, None)); + let h2 = fx.head(); + fx.same_tree_commit(); + let third = fx.run(); + assert_eq!(fx.runs(), 2); + assert_eq!(reused(&third).map(|r| r.1), Some(h2.as_str())); +} + +#[test] +fn a_fail_crosses_heads_as_a_fail_never_as_a_pass() { + let fx = Fx::new(FAIL, 1, "cache: inputs_complete\n"); + let first = fx.run(); + assert_eq!(first.verdict, Verdict::Fail); + fx.commit("README", "other head\n"); + let second = fx.run(); + assert_eq!((second.verdict, fx.runs()), (Verdict::Fail, 1)); + assert!(reused(&second).is_some()); +} + +#[test] +fn a_gate_that_stays_in_its_head_is_never_shared_even_on_the_same_tree() { + let fx = Fx::new(PASS, 2, "exactness: APPROXIMATE\n"); + fx.run(); + fx.same_tree_commit(); + let second = fx.run(); + assert_eq!((fx.runs(), reused(&second)), (2, None)); + assert!(!fx.shared_dir().join("keys").exists()); +} + +#[test] +fn a_damaged_shared_receipt_is_a_miss_never_a_hit() { + let fx = Fx::new(PASS, 1, "cache: inputs_complete\n"); + let first = fx.run(); + let src = first.receipt_digest.unwrap(); + let path = fx.shared_dir().join(format!("{src}.json")); + let mut perm = fs::metadata(&path).unwrap().permissions(); + #[allow(clippy::permissions_set_readonly_false)] + perm.set_readonly(false); + fs::set_permissions(&path, perm).unwrap(); + let text = fs::read_to_string(&path).unwrap().replace("PASS", "FAIL"); + fs::write(&path, text).unwrap(); + fx.commit("README", "other head\n"); + let second = fx.run(); + assert_eq!( + (second.verdict, fx.runs(), reused(&second)), + (Verdict::Pass, 2, None) + ); +} + +#[test] +fn two_heads_racing_for_one_key_run_it_once() { + // Two clones at different commits with the same declared inputs, judged + // at the same moment: the key lock makes the second wait and reuse. + let fx = Fx::new( + "#!/bin/sh\necho x >> \"$1\"\nsleep 1\necho \"AIEN-OBS n 3\"\necho PASS\n", + 1, + "cache: inputs_complete\n", + ); + let other = TempDir::new("jo-clone"); + let dst = other.path().join("r"); + git( + other.path(), + &[ + "clone", + "-q", + fx.repo.path().to_str().unwrap(), + dst.to_str().unwrap(), + ], + ); + write_file(&dst, "README", "other head\n", false); + git(&dst, &["add", "-A"]); + git(&dst, &["commit", "-q", "-m", "other"]); + let opts_b = { + let mut o = fx.opts(); + o.evidence_dir = fx.ev.path().join("evidence").join("b"); + o + }; + let (a, b) = std::thread::scope(|s| { + let a = s.spawn(|| fx.run()); + let b = s.spawn(|| runner::run_gate(&dst, &dst.join("tests/a.gate"), &opts_b).unwrap()); + (a.join().unwrap(), b.join().unwrap()) + }); + assert_eq!(fx.runs(), 1, "one run for both heads"); + assert_eq!( + [reused(&a).is_some(), reused(&b).is_some()] + .iter() + .filter(|x| **x) + .count(), + 1 + ); + assert_eq!((a.verdict, b.verdict), (Verdict::Pass, Verdict::Pass)); +} + +// ---- the batch budget ---------------------------------------------------------- + +#[test] +fn the_batch_budget_serves_shared_gates_before_the_others() { + let budget = Arc::new(Budget::new(1)); + let held = budget.acquire(false); + let order = Arc::new(std::sync::Mutex::new(Vec::new())); + let started = Arc::new(AtomicUsize::new(0)); + std::thread::scope(|s| { + let plain = { + let (b, o, st) = (budget.clone(), order.clone(), started.clone()); + s.spawn(move || { + st.fetch_add(1, Ordering::SeqCst); + let _p = b.acquire(false); + o.lock().unwrap().push("unique"); + }) + }; + while started.load(Ordering::SeqCst) < 1 { + std::thread::yield_now(); + } + std::thread::sleep(Duration::from_millis(50)); + let shared = { + let (b, o) = (budget.clone(), order.clone()); + s.spawn(move || { + let _p = b.acquire(true); + o.lock().unwrap().push("shared"); + }) + }; + std::thread::sleep(Duration::from_millis(50)); + drop(held); + plain.join().unwrap(); + shared.join().unwrap(); + }); + assert_eq!(*order.lock().unwrap(), vec!["shared", "unique"]); +} + +// ---- declared inputs outside the tree and by pattern (L335) ---------------- + +/// A model checkpoint is not in the repository; `outside_inputs` puts its +/// bytes in the key. Unchanged checkpoint: another head reuses. One byte of +/// the checkpoint changed: the gate runs again. +#[test] +fn an_outside_input_is_in_the_key_and_one_changed_byte_runs_the_gate_again() { + let ckpt = TempDir::new("jo-ckpt"); + fs::write(ckpt.path().join("model.safetensors"), "weights-1").unwrap(); + let extra = format!( + "outside_inputs:\n - {}/\ncache: inputs_complete\n", + ckpt.path().display() + ); + let fx = Fx::new(PASS, 1, &extra); + let first = fx.run(); + assert_eq!((first.verdict, fx.runs()), (Verdict::Pass, 1)); + fx.commit("README", "other head\n"); + let second = fx.run(); + assert_eq!( + fx.runs(), + 1, + "same checkpoint, same declared inputs: reused" + ); + assert!(reused(&second).is_some()); + // Same length, other bytes (the memo is keyed on size, mtime and inode, + // so a rewrite is seen). + std::thread::sleep(Duration::from_millis(20)); + fs::write(ckpt.path().join("model.safetensors"), "weights-2").unwrap(); + fx.commit("README", "third head\n"); + let third = fx.run(); + assert_eq!((third.verdict, fx.runs()), (Verdict::Pass, 2)); + assert_eq!(reused(&third), None); +} + +#[test] +fn an_outside_input_that_is_missing_is_a_null_row_not_a_match() { + let gone = TempDir::new("jo-gone"); + let text = |p: &str| { + parsed(&gate( + Path::new("/c"), + 1, + &format!("outside_inputs:\n - {p}/x\n"), + )) + }; + let fx = Fx::new(PASS, 1, ""); + let d_missing = runner::build_inputs_digest( + fx.repo.path(), + None, + &text(&gone.path().display().to_string()), + ); + fs::write(gone.path().join("x"), "").unwrap(); + let d_empty = runner::build_inputs_digest( + fx.repo.path(), + None, + &text(&gone.path().display().to_string()), + ); + assert_ne!( + d_missing, d_empty, + "a missing file and an empty file are different keys" + ); + // A manifest without outside_inputs keeps the digest it always had. + let plain = parsed(&gate(Path::new("/c"), 1, "")); + let before = runner::build_inputs_digest(fx.repo.path(), None, &plain); + assert_eq!( + before, + runner::build_inputs_digest(fx.repo.path(), None, &plain) + ); +} + +#[test] +fn outside_inputs_must_be_home_or_absolute_paths_without_dotdot() { + for bad in ["models/x", "~/../etc", "/a/../b", "~/", "/"] { + let t = gate(Path::new("/c"), 1, &format!("outside_inputs:\n - {bad}\n")); + assert!( + manifest::parse(t.as_bytes()).is_err(), + "{bad} must be refused" + ); + } + let t = gate(Path::new("/c"), 1, "outside_inputs:\n - ~/models/T/\n"); + assert_eq!(parsed(&t).outside_inputs, vec!["~/models/T/".to_string()]); +} + +/// `crates/*/Cargo.toml`: every member manifest is in the key (cargo reads +/// them all to load the workspace), their sources are not. +#[test] +fn a_star_pattern_input_covers_each_match_and_nothing_else() { + let fx = Fx::new(PASS, 1, ""); + fx.commit("crates/b/Cargo.toml", "[package]\n"); + fx.commit("crates/b/src/lib.rs", "x\n"); + let m = + parsed(&gate(Path::new("/c"), 1, "").replace(" - data/\n", " - crates/*/Cargo.toml\n")); + let digest = || runner::build_inputs_digest(fx.repo.path(), None, &m); + let d0 = digest(); + fx.commit("crates/b/src/lib.rs", "y\n"); + assert_eq!(digest(), d0, "a source file the pattern does not name"); + fx.commit("crates/b/Cargo.toml", "[package]\nname = \"b\"\n"); + let d1 = digest(); + assert_ne!(d1, d0, "a matched member manifest"); + fx.commit("crates/c/Cargo.toml", "[package]\n"); + assert_ne!(digest(), d1, "a new member manifest"); + // A pattern at the top is the whole tree for the cross-head rule. + let top = parsed( + &gate(Path::new("/c"), 1, "cache: inputs_complete\n") + .replace(" - data/\n", " - */Cargo.toml\n"), + ); + assert_eq!(cache::cross_head(&top), Ok(Reach::Tree)); +} + +/// `listed`: a file added to a listed directory flips the key; a changed +/// byte inside it does not (its contents are not declared by the listing). +#[test] +fn a_listed_directory_puts_its_names_in_the_key_not_its_bytes() { + let fx = Fx::new(PASS, 1, ""); + fx.commit("crates/b/tests/one.rs", "x\n"); + let m = parsed(&gate(Path::new("/c"), 1, "listed:\n - crates/*/tests\n")); + let digest = || runner::build_inputs_digest(fx.repo.path(), None, &m); + let d0 = digest(); + fx.commit("crates/b/tests/one.rs", "y\n"); + assert_eq!(digest(), d0, "same names"); + fx.commit("crates/b/tests/two.rs", "z\n"); + assert_ne!(digest(), d0, "a new test target"); +} diff --git a/tools/aien-test/src/lib.rs b/tools/aien-test/src/lib.rs index 9fa41de0..91aac72c 100644 --- a/tools/aien-test/src/lib.rs +++ b/tools/aien-test/src/lib.rs @@ -51,6 +51,8 @@ //! `CHECK_ID` and the `OBJECT` it hashed (and the ids of the gates it rests //! on). +pub mod audit; +pub mod block_first; pub mod bundle; pub mod cache; pub mod cli; @@ -71,3 +73,6 @@ pub mod worker; #[cfg(test)] pub mod testutil; + +#[cfg(test)] +mod judge_once_tests; diff --git a/tools/aien-test/src/main.rs b/tools/aien-test/src/main.rs index 1cd0fa7d..130e30a9 100644 --- a/tools/aien-test/src/main.rs +++ b/tools/aien-test/src/main.rs @@ -139,8 +139,8 @@ fn repo_root_or_report(cwd: &Path) -> Result<PathBuf, i32> { /// fresh run. fn print_cache(note: &CacheNote) { match note { - CacheNote::Reused { from } => { - println!("REUSED {from}"); + CacheNote::Reused { from, commit } => { + println!("REUSED {from} (made at commit {commit})"); println!( "CACHE reused: an earlier run of exactly this experiment already has this result, so it was not run again (use --no-cache to force a fresh run)" ); @@ -163,10 +163,14 @@ fn cmd_run(cli: &Cli, gate: &str, cwd: &Path) -> i32 { Ok(r) => r, Err(code) => return code, }; - let opts = match options(cli, &root) { + let mut opts = match options(cli, &root) { Ok(o) => o, Err(code) => return code, }; + opts.shared_cache = cli + .shared_cache + .as_deref() + .map(aien_test::cache::Shared::new); match runner::run_gate(&root, &manifest_path, &opts) { Ok(o) => { if o.verdict == Verdict::NotRun && !o.reason.is_empty() { @@ -585,19 +589,49 @@ fn cmd_worker(cli: &Cli) -> i32 { } cfg.no_cache = cli.no_cache; cfg.hardware_identity = cli.hardware_identity.clone().unwrap_or_default(); - if let Some((repo, sha)) = &cli.once { - // The same exclusive right the loop takes: a poller may be judging it. - let _claim = match worker::claim_head(&cfg.state, repo, sha) { - Ok(Some(c)) => c, - Ok(None) => { - println!("AIEN_TEST: {}", worker::held_note(&cfg.state, repo, sha)); - return EXIT_HELD; - } - Err(e) => { - println!("AIEN_TEST: FAIL {e}"); - return 1; + cfg.batch_host = cli.batch_host; + if let Some(n) = cli.batch_heads { + cfg.batch_heads = n; + } + if let Some((repo, shas)) = &cli.batch { + // One line per head, then the worst exit code: 0 only if every head + // passed. + let t0 = std::time::Instant::now(); + let mut code = 0; + for (sha, r) in worker::run_batch(&cfg, repo, shas) { + match r { + Ok(s) => { + for (g, st, v) in &s.gates { + println!("GATE {sha} {g} {st} {}", v.as_str()); + } + println!( + "HEAD {repo} {sha} {} {} bundle {} publication {}", + s.verdict.as_str(), + s.reason, + s.bundle_path.display(), + s.publication + ); + code = code.max(s.verdict.exit_code()); + } + Err(e) => { + println!("HEAD {repo} {sha} ERROR {e}"); + code = code.max(1); + } } - }; + } + println!( + "BATCH {repo} heads={} wall_ms={}", + shas.len(), + t0.elapsed().as_millis() + ); + return code; + } + if let Some((repo, sha)) = &cli.once { + // run_once owns the head lock; report a holder without taking it twice. + if let Some(pid) = worker::head_holder(&cfg.state, repo, sha) { + println!("AIEN_TEST: SKIP already being judged by pid {pid}"); + return EXIT_HELD; + } return match worker::run_once(&cfg, repo, sha) { Ok(s) => { for n in &s.notes { @@ -615,6 +649,10 @@ fn cmd_worker(cli: &Cli) -> i32 { } s.verdict.exit_code() } + Err(e) if e.contains("already being judged") => { + println!("AIEN_TEST: {e}"); + EXIT_HELD + } Err(e) => { println!("AIEN_TEST: FAIL {e}"); 1 diff --git a/tools/aien-test/src/manifest.rs b/tools/aien-test/src/manifest.rs index 57402914..2450125a 100644 --- a/tools/aien-test/src/manifest.rs +++ b/tools/aien-test/src/manifest.rs @@ -169,6 +169,25 @@ pub struct Manifest { pub mutants: Vec<String>, pub checks: Vec<String>, pub cache_allowed: bool, + /// `cache: inputs_complete`: the author promises `inputs` name every file + /// the gate reads, so a result may be reused by another head whose + /// declared inputs are byte-identical (`cache::cross_head`). Without it a + /// result crosses heads only when the whole tree is identical. + pub inputs_complete: bool, + /// `outside_inputs`: files or directories outside the repository the gate + /// reads (a model checkpoint under `~/models`, say). Each entry is `~/` + /// (the judge's home) or an absolute path; the bytes of every file under + /// it join the declared-inputs digest, so a changed checkpoint is a miss. + pub outside_inputs: Vec<String>, + /// `listed`: directories (repo-relative, `*` patterns allowed) whose entry + /// NAMES join the key, not their contents. cargo lists `tests/`, `src/bin/`, + /// `examples/` of every workspace member to find targets, so a file added + /// there changes what it loads even when no byte it compiles changed. + pub listed: Vec<String>, + /// `target_lock: none`: the gate never builds or runs anything from a cargo + /// target dir (a grep, a find, `crumb verify`), so it runs without waiting + /// for the head's target-dir lock. Default true (the lock is taken). + pub target_lock: bool, /// `manifest_version` (1 or 2). The fields below are v2 and hold their /// documented defaults for a v1 manifest. pub version: u8, @@ -239,6 +258,16 @@ fn valid_rel_path(s: &str) -> bool { !s.is_empty() && !s.starts_with('/') && !s.contains('\0') && !s.split('/').any(|c| c == "..") } +/// An `outside_inputs` entry: `~/REST` (the judge's home) or `/REST`, with +/// something after the prefix and no `..` component. +fn valid_outside_path(s: &str) -> bool { + let rest = match (s.strip_prefix("~/"), s.strip_prefix('/')) { + (Some(r), _) | (None, Some(r)) => r, + _ => return false, + }; + !rest.trim_matches('/').is_empty() && !s.contains('\0') && !rest.split('/').any(|c| c == "..") +} + fn parse_val(s: &str, line: usize) -> Result<Val, ManifestError> { if s.starts_with('"') { let mut it = serde_json::Deserializer::from_str(s).into_iter::<String>(); @@ -717,7 +746,10 @@ pub fn parse(bytes: &[u8]) -> Result<Manifest, ManifestError> { } let entries = parse_entries(text)?; - const KNOWN: [&str; 19] = [ + const KNOWN: [&str; 22] = [ + "listed", + "outside_inputs", + "target_lock", "gate", "manifest_version", "owner", @@ -820,6 +852,41 @@ pub fn parse(bytes: &[u8]) -> Result<Manifest, ManifestError> { } } + let outside_inputs = match get("outside_inputs") { + Some(e) => list(e)?, + None => Vec::new(), + }; + for o in &outside_inputs { + if !valid_outside_path(o) { + return Err(ManifestError(format!( + "outside_inputs path must start with ~/ or / and have no ..: {o:?}" + ))); + } + } + let listed = match get("listed") { + Some(e) => list(e)?, + None => Vec::new(), + }; + for l in &listed { + if !valid_rel_path(l) { + return Err(ManifestError(format!( + "listed path must be repo-relative: {l:?}" + ))); + } + } + let target_lock = match get("target_lock") { + None => true, + Some(e) => match scalar(e)?.as_str() { + "dir" => true, + "none" => false, + other => { + return Err(ManifestError(format!( + "target_lock must be dir or none, got {other:?}" + ))) + } + }, + }; + let build = match get("build") { None => None, Some(e) => { @@ -901,14 +968,15 @@ pub fn parse(bytes: &[u8]) -> Result<Manifest, ManifestError> { return Err(ManifestError(format!("unknown check {c:?}"))); } } - let cache_allowed = match get("cache") { - None => true, + let (cache_allowed, inputs_complete) = match get("cache") { + None => (true, false), Some(e) => match scalar(e)?.as_str() { - "allow" => true, - "never" => false, + "allow" => (true, false), + "inputs_complete" => (true, true), + "never" => (false, false), other => { return Err(ManifestError(format!( - "cache must be allow or never, got {other:?}" + "cache must be allow, inputs_complete or never, got {other:?}" ))) } }, @@ -933,6 +1001,10 @@ pub fn parse(bytes: &[u8]) -> Result<Manifest, ManifestError> { mutants, checks, cache_allowed, + inputs_complete, + outside_inputs, + listed, + target_lock, version, exactness, tolerance, @@ -1160,6 +1232,10 @@ mod tests { mutants: vec![], checks: vec![], cache_allowed: true, + inputs_complete: false, + outside_inputs: Vec::new(), + listed: Vec::new(), + target_lock: true, version: 1, exactness: Exactness::Exact, tolerance: None, diff --git a/tools/aien-test/src/resources.rs b/tools/aien-test/src/resources.rs index e9fc4e73..6fd5581a 100644 --- a/tools/aien-test/src/resources.rs +++ b/tools/aien-test/src/resources.rs @@ -533,6 +533,97 @@ impl Drop for TargetLock { } } +/// The same exclusive lock without waiting: None when someone else holds it. +pub fn try_lock(path: &Path) -> io::Result<Option<TargetLock>> { + let file = open_lock(path)?; + Ok(flock_exclusive(&file, false)?.then(|| TargetLock { + file: Some(file), + path: path.to_path_buf(), + })) +} + +/// A counting semaphore shared by every head of one batch (`worker +/// --batch`), with one rule `Semaphore` lacks: while a priority waiter (a +/// gate other heads of the batch share) is queued, no plain waiter gets a +/// slot, so the shared gates of the whole batch run first and the per-head +/// ones after. Taken after the in-process pool slot and before the target-dir +/// lock (order (1b) in the module comment); a holder never waits for a pool +/// slot or a cache entry lock. +pub struct Budget { + size: usize, + state: Mutex<(usize, usize)>, + cv: Condvar, +} + +/// One slot of a `Budget`, given back when dropped. +pub struct BudgetPermit<'a> { + budget: &'a Budget, +} + +impl Budget { + pub fn new(size: usize) -> Budget { + let size = size.max(1); + Budget { + size, + state: Mutex::new((size, 0)), + cv: Condvar::new(), + } + } + + pub fn size(&self) -> usize { + self.size + } + + /// Wait for a slot. `priority`: this gate is shared with other heads. + pub fn acquire(&self, priority: bool) -> BudgetPermit<'_> { + let mut st = lock(&self.state); + if priority { + st.1 += 1; + } + while st.0 == 0 || (!priority && st.1 > 0) { + st = self.cv.wait(st).unwrap_or_else(|e| e.into_inner()); + } + st.0 -= 1; + if priority { + st.1 -= 1; + } + drop(st); + // A plain waiter blocked only by the priority count may go now. + self.cv.notify_all(); + BudgetPermit { budget: self } + } +} + +impl Drop for BudgetPermit<'_> { + fn drop(&mut self) { + lock(&self.budget.state).0 += 1; + self.budget.cv.notify_all(); + } +} + +/// What the heads of one batch share: the host budget (default half the +/// CPUs) and one gb10 slot, so two heads' GPU gates queue here, one at a +/// time, instead of spending their bounded wait for `/tmp/aien-gb10.lock` on +/// each other. +pub struct BatchShare { + pub host: Budget, + pub gb10: Budget, +} + +impl BatchShare { + pub fn new(host: usize) -> BatchShare { + BatchShare { + host: Budget::new(host), + gb10: Budget::new(1), + } + } + + /// The default host budget: half the CPUs, at least one. + pub fn default_host() -> usize { + std::thread::available_parallelism().map_or(1, |n| (n.get() / 2).max(1)) + } +} + /// Take the target-dir lock at `path` (see `target_lock_path`), waiting for /// the holder to finish. The file is created if absent and never deleted. pub fn lock_target_dir(path: &Path) -> io::Result<TargetLock> { diff --git a/tools/aien-test/src/runner.rs b/tools/aien-test/src/runner.rs index 796de254..fb5bfb42 100644 --- a/tools/aien-test/src/runner.rs +++ b/tools/aien-test/src/runner.rs @@ -91,6 +91,16 @@ pub struct Options { /// `requires: operator` gate runs instead of staying OPERATOR_STEP_PENDING /// (ADR 0033 Decision 2). Never set by the automatic loop. pub operator: bool, + /// The cross-head store (`cache::Shared`, `<state>/gate-cache/<repo>`). + /// None keeps the cache inside `evidence_dir`, as before. The worker sets + /// it; a lone `run` does not. + pub shared_cache: Option<cache::Shared>, + /// The budget every head of one `worker --batch` shares (host slots, one + /// gb10 slot). None outside a batch: only this run's own pools apply. + pub batch: Option<std::sync::Arc<crate::resources::BatchShare>>, + /// Gates other heads of the batch also select: picked before the others + /// and ahead of them for the batch budget (shared first, unique after). + pub first: BTreeSet<String>, } impl Options { @@ -112,6 +122,9 @@ impl Options { release: false, pins: json!([]), operator: false, + shared_cache: None, + batch: None, + first: BTreeSet::new(), } } } @@ -147,8 +160,9 @@ pub struct Outcome { #[derive(Debug, Clone, PartialEq, Eq)] pub enum CacheNote { /// The result was reused, not rerun. Holds the digest of the fresh - /// receipt it was taken from. - Reused { from: String }, + /// receipt it was taken from and the commit that receipt was made for + /// (another head when it came through the cross-head store). + Reused { from: String, commit: String }, /// The cache was consulted and had nothing usable; the gate ran. Miss(String), /// The cache was not consulted; the gate ran (or was refused). Holds why. @@ -200,6 +214,18 @@ pub fn head(root: &Path) -> Result<String, String> { } } +/// The tree id of HEAD: equal for two commits whose every file is identical. +pub fn head_tree(root: &Path) -> Result<String, String> { + let s = git_out(root, &["rev-parse", "HEAD^{tree}"])? + .trim() + .to_string(); + if s.len() == 40 && s.bytes().all(|c| c.is_ascii_hexdigit()) { + Ok(s) + } else { + Err(format!("HEAD^{{tree}} is not a 40-hex id: {s:?}")) + } +} + fn porcelain(root: &Path) -> Result<String, String> { git_out(root, &["status", "--porcelain"]) } @@ -333,6 +359,34 @@ pub fn locate_gate(cwd: &Path, name: &str) -> Result<PathBuf, String> { } fn collect_files(root: &Path, rel: &str, out: &mut BTreeSet<String>) { + // A component with `*` (`crates/*/Cargo.toml`) stands for every entry of + // its directory whose name matches; `*` matches any run of characters. + let parts: Vec<&str> = rel.trim_end_matches('/').split('/').collect(); + if let Some(i) = parts.iter().position(|c| c.contains('*')) { + let base = parts[..i].join("/"); + let rest = parts[i + 1..].join("/"); + let mut names: Vec<String> = fs::read_dir(root.join(&base)) + .map(|rd| { + rd.flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|n| n != ".git" && wildcard_match(parts[i], n)) + .collect() + }) + .unwrap_or_default(); + names.sort(); + for n in names { + let mut child = if base.is_empty() { + n + } else { + format!("{base}/{n}") + }; + if !rest.is_empty() { + child = format!("{child}/{rest}"); + } + collect_files(root, &child, out); + } + return; + } let path = root.join(rel.trim_end_matches('/')); let md = match fs::symlink_metadata(&path) { Ok(m) => m, @@ -357,6 +411,129 @@ fn collect_files(root: &Path, rel: &str, out: &mut BTreeSet<String>) { } } +/// The existing directories a `listed` entry names (`*` per component). +fn expand_dirs(root: &Path, pat: &str, out: &mut BTreeSet<String>) { + let mut cur: Vec<String> = vec![String::new()]; + for c in pat.trim_end_matches('/').split('/') { + let mut next = Vec::new(); + for base in &cur { + let join = |n: &str| { + if base.is_empty() { + n.to_string() + } else { + format!("{base}/{n}") + } + }; + if c.contains('*') { + if let Ok(rd) = fs::read_dir(root.join(base)) { + for e in rd.flatten() { + let n = e.file_name().to_string_lossy().into_owned(); + if n != ".git" && wildcard_match(c, &n) && e.path().is_dir() { + next.push(join(&n)); + } + } + } + } else if root.join(join(c)).is_dir() { + next.push(join(c)); + } + } + cur = next; + } + out.extend(cur.into_iter().filter(|d| !d.is_empty())); +} + +/// `pat` against `name`, where `*` matches any run of characters (none too). +pub(crate) fn wildcard_match(pat: &str, name: &str) -> bool { + let pieces: Vec<&str> = pat.split('*').collect(); + if pieces.len() == 1 { + return pat == name; + } + let (first, last) = (pieces[0], pieces[pieces.len() - 1]); + if !name.starts_with(first) || name.len() < first.len() + last.len() || !name.ends_with(last) { + return false; + } + let mut rest = &name[first.len()..name.len() - last.len()]; + for p in &pieces[1..pieces.len() - 1] { + match rest.find(p) { + Some(at) => rest = &rest[at + p.len()..], + None => return false, + } + } + true +} + +/// `~/REST` against the judge's `HOME`; an absolute path as it is. +pub(crate) fn outside_path(entry: &str) -> PathBuf { + match entry.strip_prefix("~/") { + Some(rest) => std::env::var_os("HOME") + .map(PathBuf::from) + .unwrap_or_default() + .join(rest), + None => PathBuf::from(entry), + } +} + +/// `(name, sha256)` of every file under one `outside_inputs` entry, named by +/// the entry as written (`~/models/X/model.safetensors`), so the key does not +/// depend on whose home it is. A missing entry is one row with a null digest. +/// Digests are remembered per (path, size, mtime, inode) for the life of the +/// process: a checkpoint of gigabytes is read once per judge, not per gate. +fn outside_rows(entry: &str) -> Vec<(String, Option<String>)> { + use std::os::unix::fs::MetadataExt; + type Memo = BTreeMap<(PathBuf, u64, i64, i64, u64), String>; + static MEMO: std::sync::OnceLock<Mutex<Memo>> = std::sync::OnceLock::new(); + let shown = entry.trim_end_matches('/').to_string(); + let base = outside_path(&shown); + let mut walk = vec![(base.clone(), shown.clone())]; + let mut rows = Vec::new(); + while let Some((p, name)) = walk.pop() { + match fs::metadata(&p) { + Ok(md) if md.is_dir() => { + if let Ok(rd) = fs::read_dir(&p) { + for e in rd.flatten() { + let n = e.file_name().to_string_lossy().into_owned(); + walk.push((e.path(), format!("{name}/{n}"))); + } + } + } + Ok(md) if md.is_file() => { + let k = (p.clone(), md.len(), md.mtime(), md.mtime_nsec(), md.ino()); + let memo = MEMO.get_or_init(|| Mutex::new(BTreeMap::new())); + let hit = memo.lock().ok().and_then(|m| m.get(&k).cloned()); + let digest = hit.or_else(|| { + let d = sha256_file(&p)?; + if let Ok(mut m) = memo.lock() { + m.insert(k, d.clone()); + } + Some(d) + }); + rows.push((name, digest)); + } + _ => rows.push((name, None)), + } + } + rows.sort(); + rows +} + +/// sha256 of a file, streamed (a checkpoint does not fit the 16 KiB budget +/// of anything else here, and need not sit in memory). +fn sha256_file(p: &Path) -> Option<String> { + use sha2::{Digest, Sha256}; + use std::io::Read; + let mut f = fs::File::open(p).ok()?; + let mut h = Sha256::new(); + let mut buf = vec![0u8; 1 << 20]; + loop { + let n = f.read(&mut buf).ok()?; + if n == 0 { + break; + } + h.update(&buf[..n]); + } + Some(format!("{:x}", h.finalize())) +} + /// Where `run.exec` is, for a run without the sandbox (the runner's PATH). /// See [`exec_path_for`]. pub fn exec_path(root: &Path, exec: &str) -> Option<PathBuf> { @@ -398,7 +575,8 @@ fn exec_path_in(root: &Path, exec: &str, path: Option<std::ffi::OsString>) -> Op } /// sha256 over the canonical list of (path, file sha256) for the explicit -/// `inputs` plus the D3 convention-implied inputs of `tests/<dir>/<name>.gate`. +/// `inputs`, the D3 convention-implied inputs of `tests/<dir>/<name>.gate` and +/// the repository build files in [`IMPLIED_BUILD_FILES`] that exist. /// A listed path that does not exist is recorded with a null digest. Compiler /// identity is not included yet because nothing here builds. pub fn build_inputs_digest(root: &Path, manifest_rel: Option<&Path>, m: &Manifest) -> String { @@ -406,6 +584,11 @@ pub fn build_inputs_digest(root: &Path, manifest_rel: Option<&Path>, m: &Manifes for i in &m.inputs { collect_files(root, i, &mut paths); } + for f in IMPLIED_BUILD_FILES { + if root.join(f).is_file() { + paths.insert(f.to_string()); + } + } if let Some(rel) = manifest_rel { let dir = rel.parent().unwrap_or(Path::new("")); let stem = rel @@ -447,9 +630,74 @@ pub fn build_inputs_digest(root: &Path, manifest_rel: Option<&Path>, m: &Manifes json!({ "path": p, "sha256": digest }) }) .collect(); - canonical_digest(&json!({ "inputs": entries })).unwrap_or_default() + // Outside inputs and listings join under their own members, so a + // manifest without them keeps the digest it always had. + let mut obj = json!({ "inputs": entries }); + if !m.outside_inputs.is_empty() { + let outside: Vec<Value> = m + .outside_inputs + .iter() + .flat_map(|o| outside_rows(o)) + .map(|(p, d)| json!({ "path": p, "sha256": d })) + .collect(); + obj["outside_inputs"] = json!(outside); + } + if !m.listed.is_empty() { + let mut dirs: BTreeSet<String> = BTreeSet::new(); + for l in &m.listed { + expand_dirs(root, l, &mut dirs); + } + let rows: Vec<Value> = dirs + .iter() + .map(|d| { + let mut names: Vec<String> = fs::read_dir(root.join(d)) + .map(|rd| { + rd.flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|n| n != ".git") + .collect() + }) + .unwrap_or_default(); + names.sort(); + json!({ "dir": d, "names": names }) + }) + .collect(); + obj["listed"] = json!(rows); + } + canonical_digest(&obj).unwrap_or_default() } +/// sha256 of the running aien-test binary, read once. None when the binary +/// cannot be read (then no result made under None matches one made under a +/// readable binary). +pub fn judge_sha256() -> Option<String> { + static SHA: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new(); + SHA.get_or_init(|| { + std::env::current_exe() + .and_then(fs::read) + .ok() + .map(|b| sha256_hex(&b)) + }) + .clone() +} + +/// Repository build files that change what any gate builds or runs even when +/// its manifest does not list them (the workspace manifest and lock, the +/// toolchain pin, cargo's config). Each one that exists joins every gate's +/// `build_inputs_digest`: a gate like SC-INQUISITOR builds with cargo and +/// lists no Cargo.toml. Adding a file to the key can only turn a hit into a +/// miss, never the other way. +pub const IMPLIED_BUILD_FILES: [&str; 8] = [ + "Cargo.toml", + "Cargo.lock", + "rust-toolchain", + "rust-toolchain.toml", + ".cargo/config", + ".cargo/config.toml", + "native-artifacts.lock", + "mojoproject.toml", +]; + pub(crate) fn machine(hw: &Hardware) -> Value { let kernel = fs::read_to_string("/proc/sys/kernel/osrelease") .map(|s| s.trim().to_string()) @@ -536,6 +784,10 @@ pub(crate) fn identity( machine["sandbox_helper_sha256"] = json!(fs::read(sandbox::EXEC_HELPER).ok().map(|b| sha256_hex(&b))); } + // The judge that derives the verdict is part of the machine too: a result + // made by another build of aien-test is never reused, inside one head or + // across heads (a new rule in the verdict, a new receipt member). + machine["judge_sha256"] = json!(judge_sha256()); let machine_digest = canonical_digest(&machine)?; Ok(Identity { binary_sha, @@ -630,11 +882,20 @@ fn execute_gate(job: &Job<'_>, permit: Option<Permit<'_>>) -> Result<Outcome, Ru let dependencies: Vec<(String, String)> = dependency_rows(&facts.deps).into_iter().collect(); // Receipts are read when a lookup may happen, and to follow a reused // dependency back to the receipt it stands for. - let index = if mode == cache::Mode::Allow || !dependencies.is_empty() { + let mut index = if mode == cache::Mode::Allow || !dependencies.is_empty() { Index::load(&store) } else { Index::default() }; + // The cross-head store, only for a gate whose result may leave this head + // (`cache::cross_head`); every other gate keeps its cache inside this + // head. The reach decides the entry name: the key, or the key and the + // tree id when the manifest does not promise complete inputs. + let reach = cache::cross_head(m).ok(); + let shared: Option<(&cache::Shared, cache::Reach)> = match (opts.shared_cache.as_ref(), reach) { + (Some(sh), Some(r)) => Some((sh, r)), + _ => None, + }; let experiment = cache::Experiment { manifest_digest: m.digest.clone(), binary_sha256: id.binary_sha.clone(), @@ -655,8 +916,47 @@ fn execute_gate(job: &Job<'_>, permit: Option<Permit<'_>>) -> Result<Outcome, Ru // Reuse only when the gate would really have run: a refusal, a blocked // verdict or a dependency that is not PASS is reported as it is, never // hidden behind an old result. + // Held from the shared lookup until this head's result is published, so + // another judge of the same key waits for it instead of running it too. + let mut key_lock: Option<cache::KeyLock> = None; + let mut shared_note: Option<String> = None; + let mut shared_slot: Option<String> = None; if mode == cache::Mode::Allow && !evidence_inside && verdict::pre_run(m, &facts).is_none() { - match cache::lookup(&index, &store, &cache_key, &captured_env()) { + let env = captured_env(); + let local_hit = matches!( + cache::lookup(&index, &store, &cache_key, &env), + cache::Lookup::Hit(_) + ); + if let (false, Some((sh, reach))) = (local_hit, shared) { + // The shared store is an extra: if the tree id or the entry lock + // cannot be had, this head decides alone, as before. + let named = head_tree(root) + .map(|tree| cache::slot(&cache_key, reach, &tree)) + .and_then(|name| match sh.lock(&name) { + Ok(l) => Ok((name, l)), + Err(e) => Err(format!("cannot lock the entry: {e}")), + }); + match named { + Err(e) => shared_note = Some(format!("the cross-head store was not used ({e})")), + Ok((name, l)) => { + key_lock = Some(l); + match sh.import(&name, &cache_key, &store) { + Ok(Some(_)) => index = Index::load(&store), + Ok(None) => { + shared_note = Some(match reach { + cache::Reach::Inputs => "no other head has this key yet".to_string(), + cache::Reach::Tree => "no other head with this exact tree has this key yet (the manifest does not say cache: inputs_complete)".to_string(), + }) + } + Err(e) => { + shared_note = Some(format!("the cross-head entry could not be read ({e})")) + } + } + shared_slot = Some(name); + } + } + } + match cache::lookup(&index, &store, &cache_key, &env) { cache::Lookup::Hit(src) => { let reused_verdict = src .verdict() @@ -671,6 +971,10 @@ fn execute_gate(job: &Job<'_>, permit: Option<Permit<'_>>) -> Result<Outcome, Ru "cache": cache::cache_member(&cache_key, Some(&src.digest), mode), "timeout_exceeded": false, }); + let mut volatile = volatile; + // Which head the result was made for: this one, or another + // head whose result came through the cross-head store. + volatile["cache"]["reused_from_commit"] = json!(src.commit()); let receipt = build_receipt(cache::reused_core(src, &commit), volatile); let (digest, path) = store.put_receipt(&receipt).map_err(fatal)?; drop(permit); @@ -681,13 +985,36 @@ fn execute_gate(job: &Job<'_>, permit: Option<Permit<'_>>) -> Result<Outcome, Ru receipt_digest: Some(digest), cache: CacheNote::Reused { from: src.digest.clone(), + commit: src.commit().to_string(), }, }); } - cache::Lookup::Miss(miss) => note = CacheNote::Miss(miss.text()), + cache::Lookup::Miss(miss) => { + note = CacheNote::Miss(match &shared_note { + Some(s) => format!("{}; across heads: {s}", miss.text()), + None => miss.text(), + }) + } } } + // In a batch, a host gate that will really run takes one slot of the + // batch budget (shared gates ahead of the rest), and a gb10 gate takes + // the batch's one gb10 slot, so heads of the batch never compete for + // `/tmp/aien-gb10.lock` and spend their bounded wait on each other. A + // reused result above never got here, so it costs no slot. + // Both waits below are timed and go into the receipt on their own + // (`batch_wait_ms`, `target_wait_ms`): `duration_ms` starts at `t0`, so + // without them a gate queued behind another head reads as a slow gate. + let runs = verdict::pre_run(m, &facts).is_none(); + let t_batch = Instant::now(); + let _batch_slot = match (&opts.batch, m.pool(), runs) { + (Some(b), "host", true) => Some(b.host.acquire(opts.first.contains(&m.gate))), + (Some(b), "gb10", true) => Some(b.gb10.acquire(true)), + _ => None, + }; + let batch_wait_ms = t_batch.elapsed().as_millis() as u64; + let t_target = Instant::now(); // A gate that will run holds its target dir for the whole run (build and // run), so no other gate builds in it or relinks a binary this one is // executing (sc fix/521). Every gate, not only those whose manifest @@ -700,18 +1027,24 @@ fn execute_gate(job: &Job<'_>, permit: Option<Permit<'_>>) -> Result<Outcome, Ru // A gb10 gate is never killed on timeout (ADR 0028 Decision 6), so one // that hangs holds the target dir until it exits; the receipt's // `timeout_exceeded` is the only sign. - let target_lock: Option<resources::TargetLock> = if verdict::pre_run(m, &facts).is_none() { - let dir = opts - .cargo_target_dir - .clone() - .unwrap_or_else(|| resolve(root).join("target")); - let path = resources::target_lock_path(&opts.target_lock_dir, &dir); - Some(resources::lock_target_dir(&path).map_err(|e| { - RunError::Fatal(format!("cannot lock target dir {}: {e}", path.display())) - })?) - } else { - None - }; + // `target_lock: none` (a grep, a find, `crumb verify`) skips it: such a gate + // queued behind the head's cargo gates for up to the head's whole wall + // (L335, finding G3-ci-judge-2); `aien-test audit-inputs` refuses the + // promise when the traced run starts cargo or rustc. + let target_lock: Option<resources::TargetLock> = + if m.target_lock && verdict::pre_run(m, &facts).is_none() { + let dir = opts + .cargo_target_dir + .clone() + .unwrap_or_else(|| resolve(root).join("target")); + let path = resources::target_lock_path(&opts.target_lock_dir, &dir); + Some(resources::lock_target_dir(&path).map_err(|e| { + RunError::Fatal(format!("cannot lock target dir {}: {e}", path.display())) + })?) + } else { + None + }; + let target_wait_ms = t_target.elapsed().as_millis() as u64; // A gb10 gate takes the GPU locks only when nothing else already stops it, // waiting for a held lock as `opts.gpu.wait` says. A refusal (quiet flag, @@ -874,6 +1207,8 @@ fn execute_gate(job: &Job<'_>, permit: Option<Permit<'_>>) -> Result<Outcome, Ru "duration_ms": t0.elapsed().as_millis() as u64, "pool": m.pool(), "pool_wait_ms": job.pool_wait_ms, + "batch_wait_ms": batch_wait_ms, + "target_wait_ms": target_wait_ms, "runner": { "name": "aien-test", "version": env!("CARGO_PKG_VERSION"), "impl": "rust" }, "cache": cache::cache_member(&cache_key, None, mode), "timeout_exceeded": timeout_exceeded, @@ -882,6 +1217,22 @@ fn execute_gate(job: &Job<'_>, permit: Option<Permit<'_>>) -> Result<Outcome, Ru let receipt = build_receipt(Value::Object(core), volatile); let (digest, path) = store.put_receipt(&receipt).map_err(fatal)?; + // Offer the result to other heads only if `lookup` would reuse it here + // (PASS or FAIL, clean tree, in time, key recomputes, logs present): a + // failed publication costs the next head a run, never a wrong verdict. + if let (Some((sh, _)), Some(name), Some(_held)) = + (shared, shared_slot.as_ref(), key_lock.as_ref()) + { + let idx = Index::load(&store); + if let Some(r) = idx.get(&digest) { + if cache::usable(r, &cache_key, &idx, &store, &captured_env()).is_ok() { + if let Err(e) = sh.publish(name, &digest, &store) { + eprintln!("aien-test: {} not shared with other heads: {e}", m.gate); + } + } + } + } + drop(key_lock); Ok(Outcome { verdict: derived.verdict, reason: derived.reason, @@ -1007,7 +1358,16 @@ impl GraphRun<'_> { /// work). Called with the scheduler lock held. fn pick(&self, st: &mut Sched) -> Option<Pick<'_>> { let mut chosen = None; - for &i in &st.ready { + // Gates other heads of a batch share go first (`Options::first`). + let shared = |i: &usize| self.opts.first.contains(&self.graph.node(*i).id); + let order: Vec<usize> = st + .ready + .iter() + .filter(|i| shared(i)) + .chain(st.ready.iter().filter(|i| !shared(i))) + .copied() + .collect(); + for i in order { let deps = self.dep_facts(&st.results, i); if !deps.iter().all(|d| d.verdict == Some(Verdict::Pass)) { chosen = Some(Pick { @@ -2122,6 +2482,68 @@ mod tests { assert!(lock.exists(), "lock {} never taken", lock.display()); } + /// The gate that waits for the target dir the other holds says so in its + /// receipt (`target_wait_ms`), so the wait never reads as test time; a + /// run outside a batch takes no batch slot (`batch_wait_ms` 0). + #[test] + fn a_target_dir_wait_is_recorded_apart_from_the_run() { + let fx = gfx(&[ + ("G-A", "", "host", slow("G-A")), + ("G-B", "", "host", slow("G-B")), + ]); + let mut opts = fx.opts(); + opts.target_lock_dir = fx.scratch.path().join("locks"); + let c = fx.campaign(&opts); + assert_eq!(c.exit_code(), 0); + let second = fx.log()[2].trim_start_matches("start-").to_string(); + let v = |id: &str| { + read_json(outcome(&c, id).receipt_path.as_ref().unwrap())["volatile"].clone() + }; + let (late, early) = if second == "G-A" { + (v("G-A"), v("G-B")) + } else { + (v("G-B"), v("G-A")) + }; + let waited = late["target_wait_ms"].as_u64().unwrap(); + assert!( + waited >= 150, + "second gate waited {waited} ms for the target dir" + ); + assert!(late["duration_ms"].as_u64().unwrap() >= waited); + assert!(early["target_wait_ms"].as_u64().unwrap() < 150); + assert_eq!(late["batch_wait_ms"], json!(0)); + } + + /// `target_lock: none` (L335, G3-ci-judge-2): two such gates of one head + /// run side by side instead of queueing on the target dir. + #[test] + fn target_lock_none_gates_do_not_queue_on_the_target_dir() { + let fx = gfx_with( + &[ + ("G-A", "", "host", slow("G-A")), + ("G-B", "", "host", slow("G-B")), + ], + "target_lock: none\n", + &[], + ); + let mut opts = fx.opts(); + opts.target_lock_dir = fx.scratch.path().join("locks"); + let c = fx.campaign(&opts); + assert_eq!(c.exit_code(), 0); + let log = fx.log(); + assert!( + log[0].starts_with("start-") && log[1].starts_with("start-"), + "both started before either ended: {log:?}" + ); + for id in ["G-A", "G-B"] { + let v = read_json(outcome(&c, id).receipt_path.as_ref().unwrap())["volatile"].clone(); + assert!( + v["target_wait_ms"].as_u64().unwrap() < 150, + "{id} waited: {v}" + ); + } + } + /// A gate may call cargo without naming `Cargo.toml` among its inputs /// (SC-INQUISITOR builds spark-inquisitor that way), so the rule is not /// "cargo gates": every gate given a `CARGO_TARGET_DIR` holds it. diff --git a/tools/aien-test/src/verify.rs b/tools/aien-test/src/verify.rs index b6805977..9c820eda 100644 --- a/tools/aien-test/src/verify.rs +++ b/tools/aien-test/src/verify.rs @@ -682,8 +682,12 @@ pub fn run(root: &Path, ask: &Ask) -> Report { _ => "NOT_RUN".to_string(), }; lines.push(format!("Final verdict: {final_verdict}")); - let queue = sum_u64(&found.index, &run_digests, "/pool_wait_ms"); - let test = sum_u64(&found.index, &run_digests, "/duration_ms"); + // A gate's batch-slot and target-dir waits fall inside its `duration_ms`; + // they are queue time, not test time. + let held = sum_u64(&found.index, &run_digests, "/batch_wait_ms").unwrap_or(0) + + sum_u64(&found.index, &run_digests, "/target_wait_ms").unwrap_or(0); + let queue = sum_u64(&found.index, &run_digests, "/pool_wait_ms").map(|q| q + held); + let test = sum_u64(&found.index, &run_digests, "/duration_ms").map(|t| t.saturating_sub(held)); let gpu_wait = sum_u64(&found.index, &run_digests, "/gpu_wait/waited_ms"); let total = bundle.as_ref().and_then(|b| { let s = utc_secs(b["started_utc"].as_str()?)?; diff --git a/tools/aien-test/src/worker.rs b/tools/aien-test/src/worker.rs index 873b7866..9c8349cb 100644 --- a/tools/aien-test/src/worker.rs +++ b/tools/aien-test/src/worker.rs @@ -51,7 +51,7 @@ use crate::sandbox::Sandbox; use crate::verdict::Verdict; use crate::verify; use serde_json::{json, Value}; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::fs; use std::io::Write; use std::os::unix::fs::MetadataExt; @@ -143,6 +143,12 @@ impl StateDir { self.root.join("evidence").join(repo).join(sha) } + /// `<state>/gate-cache/<repo>`: the cross-head store (`cache::Shared`) + /// every head of one repository reads and publishes to. + pub fn gate_cache(&self, repo: &str) -> PathBuf { + self.root.join("gate-cache").join(repo) + } + /// `<state>/locks/target`: the per-target-dir lock files /// (`resources::target_lock_path`). Every holder of a cargo target dir, /// a gate run by this worker or the worker's own priming of @@ -208,7 +214,12 @@ impl StateDir { "phase": phase, }); let _ = fs::create_dir_all(&self.root); - let tmp = self.root.join("worker.heartbeat.tmp"); + // One temp name per thread: heads of a batch beat at the same time. + let tmp = self.root.join(format!( + "worker.heartbeat.tmp.{}.{:?}", + std::process::id(), + std::thread::current().id() + )); if fs::write(&tmp, serde_json::to_string(&v).unwrap_or_default()).is_ok() { let _ = fs::rename(&tmp, self.heartbeat()); } @@ -269,6 +280,12 @@ pub struct Config { /// How a gb10 gate waits for a held GPU lock (`--gpu-wait`, `--wait-gpu`; /// default the bounded `resources::DEFAULT_GPU_WAIT`). pub gpu_wait: GpuWait, + /// `--batch-host N`: host slots the heads of one batch share (None: half + /// the CPUs, `resources::BatchShare::default_host`). + pub batch_host: Option<usize>, + /// `--batch-heads N`: how many heads of one repository the loop checks + /// out and judges together (default 6; 1 judges one head at a time). + pub batch_heads: usize, } impl Config { @@ -295,6 +312,8 @@ impl Config { jobs: JobsSpec::default(), no_cache: false, gpu_wait: GpuWait::Bounded(DEFAULT_GPU_WAIT), + batch_host: None, + batch_heads: 6, } } @@ -839,6 +858,23 @@ fn crumb(cfg: &Config, wt: &Path, args: &[&str], notes: &mut Vec<String>) { /// Verify one head end to end. Never panics on GitHub trouble. pub fn run_once(cfg: &Config, repo: &str, sha: &str) -> Result<Summary, String> { + run_once_in(cfg, repo, sha, None) +} + +/// What one head of a batch gets from `run_batch`: the shared budget and the +/// gates other heads of the batch also select. +pub type Share = ( + std::sync::Arc<crate::resources::BatchShare>, + BTreeSet<String>, +); + +/// `run_once` as one head of a batch (`share`), or alone (None). +pub fn run_once_in( + cfg: &Config, + repo: &str, + sha: &str, + share: Option<&Share>, +) -> Result<Summary, String> { // Refusals first: nothing is fetched, checked out or run before these. if !valid_repo_key(repo) { return Err(format!("refusing repository name {repo:?}")); @@ -863,21 +899,64 @@ pub fn run_once(cfg: &Config, repo: &str, sha: &str) -> Result<Summary, String> let sibs = siblings_for(cfg, repo)?; let pins = pins_for(cfg, repo)?; let mut notes: Vec<String> = Vec::new(); + // One judge per head at a time, across processes (the batch, `--once`, + // the loop): a second one would rewrite the same bundle and evidence. + let head_lock = cfg.state.head_lock(repo, sha); + // Tried for up to two seconds: a child another thread forks holds a copy + // of the descriptor until it execs, so a lock just released can look held + // for a moment; a real second judge holds it for the whole run. + let deadline = std::time::Instant::now() + Duration::from_secs(2); + let _head = loop { + match crate::resources::try_lock(&head_lock) { + Ok(Some(l)) => break l, + Ok(None) if std::time::Instant::now() < deadline => { + std::thread::sleep(Duration::from_millis(50)) + } + Ok(None) => { + return Err(format!( + "{repo} {sha} is already being judged by another worker" + )) + } + Err(e) => { + return Err(format!( + "cannot take the head lock {}: {e}", + head_lock.display() + )) + } + } + }; cfg.state.beat(repo, sha, "checkout"); + // Heads of one batch share the clones and mirrors: checkouts, pins and + // sibling worktrees are made one head at a time (git's own locks refuse + // concurrent `worktree add` on one repository). + let prep = lock_prep(); let co = checkout(cfg, repo, sha, &mut notes)?; ensure_pins(&cfg.clones, &pins, &sibs, &mut notes); let (made, pin_values) = provision_siblings(cfg, repo, sha, &co, &sibs, &pins, &mut notes); + drop(prep); let (clone, wt) = (co.clone.clone(), co.wt.clone()); // A wt.sh worktree belongs to aien-run; the operator's git opens it only // after `check_worktree_link` (see `process::trust_worktree`). let trust = (cfg.sandbox == Sandbox::User).then(|| process::trust_worktree(&wt)); // Every sibling's commit is in `opts.pins` (`core.pins` and `cache.key`), - // and the evidence directory is this head's own (`evidence/<repo>/<sha>`), - // so a result is reused only for this same commit with every sibling at - // the same commit. A declared sibling that could not be made turns the - // cache off for the whole head. + // and the evidence directory is this head's own (`evidence/<repo>/<sha>`): + // a result from another head arrives only through the shared store, for a + // gate `cache::cross_head` lets out, with every sibling at the same commit. + // A declared sibling that could not be made turns the cache off for the + // whole head. let fresh = made.len() < sibs.len(); - let result = run_in_worktree(cfg, repo, sha, &co, fresh, pin_values, &mut notes); + let result = run_in_worktree( + cfg, + repo, + sha, + &co, + HeadCache { + fresh, + pins: pin_values, + share, + }, + &mut notes, + ); crumb( cfg, &wt, @@ -892,6 +971,7 @@ pub fn run_once(cfg: &Config, repo: &str, sha: &str) -> Result<Summary, String> &mut notes, ); drop(trust); + let prep = lock_prep(); if cfg.sandbox == Sandbox::User { if let Some(tool) = &cfg.wt_tool { let tool = tool.display().to_string(); @@ -902,21 +982,31 @@ pub fn run_once(cfg: &Config, repo: &str, sha: &str) -> Result<Summary, String> } else { remove_checkout(&co, &made); } + drop(prep); cfg.state.beat(repo, sha, "idle"); let mut summary = result?; summary.notes.append(&mut notes); Ok(summary) } +/// What the cache of one head rests on: `fresh` (a declared sibling could not +/// be made, so nothing is reused), the sibling and operator `pins`, and the +/// batch it belongs to, if any. +struct HeadCache<'a> { + fresh: bool, + pins: Value, + share: Option<&'a Share>, +} + fn run_in_worktree( cfg: &Config, repo: &str, sha: &str, co: &Checkout, - fresh: bool, - pins: Value, + hc: HeadCache<'_>, notes: &mut Vec<String>, ) -> Result<Summary, String> { + let HeadCache { fresh, pins, share } = hc; let (clone, wt) = (co.clone.as_path(), co.wt.as_path()); let started = now_secs(); crumb( @@ -961,6 +1051,13 @@ fn run_in_worktree( if fresh || cfg.no_cache { opts.no_cache = true; } + // A result whose key another head of this repository already has is + // reused from there (`cache::Shared`); the bundle entry names that head. + opts.shared_cache = Some(crate::cache::Shared::new(&cfg.state.gate_cache(repo))); + if let Some((budget, first)) = share { + opts.batch = Some(budget.clone()); + opts.first = first.clone(); + } let mut known: BTreeMap<String, Known> = BTreeMap::new(); let mut notes_cache: BTreeMap<String, CacheNote> = BTreeMap::new(); if plan.blocked.is_none() && !plan.entries.is_empty() { @@ -1016,10 +1113,14 @@ fn run_in_worktree( let (status, verdict, extra): (&str, String, Value) = match (e.section, k, notes_cache.get(&e.gate)) { (Section::Blocked, _, _) => ("blocked", bundle_verdict(eff), json!({})), - (_, Some(k), Some(CacheNote::Reused { from })) if k.receipt.is_some() => ( + (_, Some(k), Some(CacheNote::Reused { from, commit })) if k.receipt.is_some() => ( "cached", bundle_verdict(eff), - json!({ "resolution": { "resolved_from": from, "receipt": k.receipt } }), + json!({ "resolution": { + "resolved_from": from, + "resolved_from_commit": commit, + "receipt": k.receipt, + } }), ), (_, Some(k), _) if k.receipt.is_some() => { ("run", bundle_verdict(eff), json!({ "receipt": k.receipt })) @@ -1408,6 +1509,77 @@ pub fn triggers(state: &StateDir) -> Vec<(String, String, PathBuf)> { out } +/// What the last answer to one GitHub list request said, kept with its ETag so the next poll can ask +/// "has it changed?" (a 304 reply costs nothing against the hourly allowance; L337, G3-ci-judge-7). +#[derive(Default)] +pub struct GithubHeadCache { + entries: std::collections::HashMap<String, (String, Vec<String>)>, +} + +/// One list request as a conditional GET. `pick` turns a 200 body into head shas. A 304 returns the shas of +/// the answer the ETag belongs to; any other status is an error carrying gh's message. +fn conditional_heads( + gh: &str, + path: &str, + pick: fn(&Value) -> Vec<String>, + cache: &mut GithubHeadCache, +) -> Result<Vec<String>, String> { + let mut cmd = Command::new(gh); + cmd.args(["api", "-i"]); + if let Some((etag, _)) = cache.entries.get(path) { + cmd.args(["-H", &format!("If-None-Match: {etag}")]); + } + cmd.arg(path); + let out = process::output_gated(&mut cmd).map_err(|e| format!("cannot run {gh}: {e}"))?; + let text = String::from_utf8_lossy(&out.stdout).into_owned(); + let (head, body) = text + .split_once("\r\n\r\n") + .or_else(|| text.split_once("\n\n")) + .unwrap_or((text.as_str(), "")); + let status = head + .lines() + .next() + .and_then(|l| l.split_whitespace().nth(1)) + .unwrap_or(""); + if status == "304" { + if let Some((_, shas)) = cache.entries.get(path) { + return Ok(shas.clone()); + } + } + if status != "200" || !out.status.success() { + cache.entries.remove(path); + let err = String::from_utf8_lossy(&out.stderr).trim().to_string(); + return Err(if err.is_empty() { + head.lines().next().unwrap_or("no answer").to_string() + } else { + err + }); + } + let value: Value = + serde_json::from_str(body).map_err(|e| format!("unreadable answer for {path}: {e}"))?; + let shas: Vec<String> = pick(&value) + .into_iter() + .map(|s| s.trim().to_ascii_lowercase()) + .filter(|s| valid_sha(s)) + .collect(); + let etag = head + .lines() + .find_map(|l| { + l.split_once(':') + .filter(|(k, _)| k.eq_ignore_ascii_case("etag")) + }) + .map(|(_, v)| v.trim().to_string()); + match etag { + Some(etag) if !etag.is_empty() => { + cache.entries.insert(path.to_string(), (etag, shas.clone())); + } + _ => { + cache.entries.remove(path); + } + } + Ok(shas) +} + /// `triggers`, limited to the repositories in `repos` (a poller started with /// `--repos`). An empty list takes every trigger. Files of other repositories /// are left where they are: they belong to the poller that lists them. @@ -1501,44 +1673,168 @@ pub fn held_note(state: &StateDir, repo: &str, sha: &str) -> String { } } -/// Open PR heads and the main head of `repo` from GitHub (bounded: one call -/// per list). Errors are returned, never fatal to the loop. -pub fn github_heads(gh: &str, repository: &str) -> Result<Vec<String>, String> { +fn pull_heads(v: &Value) -> Vec<String> { + v.as_array() + .map(|a| { + a.iter() + .filter_map(|p| p["head"]["sha"].as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default() +} + +fn main_head(v: &Value) -> Vec<String> { + v["sha"].as_str().map(str::to_string).into_iter().collect() +} + +/// Open PR heads and the main head of `repo` from GitHub (bounded: one conditional call per list). Errors are +/// returned, never fatal to the loop. Unchanged lists answer 304 and cost no allowance. +pub fn github_heads_cached( + gh: &str, + repository: &str, + cache: &mut GithubHeadCache, +) -> Result<Vec<String>, String> { let or = owner_repo(repository).ok_or("bad repository name")?; - let mut shas = Vec::new(); - for args in [ - vec![ - "api", - &format!("repos/{or}/pulls?state=open&per_page=50"), - "--jq", - ".[].head.sha", - ], - vec!["api", &format!("repos/{or}/commits/main"), "--jq", ".sha"], - ] { - let mut cmd = Command::new(gh); - cmd.args(&args); - let out = process::output_gated(&mut cmd).map_err(|e| format!("cannot run {gh}: {e}"))?; - if !out.status.success() { - return Err(String::from_utf8_lossy(&out.stderr).trim().to_string()); - } - for l in String::from_utf8_lossy(&out.stdout).lines() { - let l = l.trim().to_ascii_lowercase(); - if valid_sha(&l) { - shas.push(l); - } - } - } + let mut shas = conditional_heads( + gh, + &format!("repos/{or}/pulls?state=open&per_page=50"), + pull_heads, + cache, + )?; + shas.extend(conditional_heads( + gh, + &format!("repos/{or}/commits/main"), + main_head, + cache, + )?); shas.sort(); shas.dedup(); Ok(shas) } +/// `github_heads_cached` with no memory of earlier polls. +pub fn github_heads(gh: &str, repository: &str) -> Result<Vec<String>, String> { + github_heads_cached(gh, repository, &mut GithubHeadCache::default()) +} + /// The loop: flush the outbox, serve trigger files, poll GitHub when asked, /// sleep. `iterations` bounds the rounds (None: forever). Returns the number /// of heads served. +/// Checkouts, pins, sibling worktrees and worktree removal touch the shared +/// clones and mirrors; heads of one batch do them one at a time. +fn lock_prep() -> std::sync::MutexGuard<'static, ()> { + static PREP: std::sync::Mutex<()> = std::sync::Mutex::new(()); + PREP.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// For each head, the gates whose experiment another head of the batch is +/// likely to share, read from git objects before anything is checked out: a +/// gate whose manifest blob, declared inputs and repository build files have +/// the same blob ids at two heads (and, for a gate without `cache: +/// inputs_complete`, the same tree). Only an ordering hint: whether a result +/// is really reused is decided by the cache key, never by this. +pub fn batch_first(clone: &Path, shas: &[String]) -> BTreeMap<String, BTreeSet<String>> { + let mut prints: BTreeMap<String, Vec<(String, String)>> = BTreeMap::new(); + for sha in shas { + let tree = git(clone, &["rev-parse", &format!("{sha}^{{tree}}")]).unwrap_or_default(); + let files = git(clone, &["ls-tree", "-r", "--name-only", sha]).unwrap_or_default(); + let mut mine = Vec::new(); + for path in files.lines().filter(|p| p.ends_with(".gate")) { + let Ok(bytes) = git(clone, &["show", &format!("{sha}:{path}")]) else { + continue; + }; + let Ok(m) = crate::manifest::parse(bytes.as_bytes()) else { + continue; + }; + let Ok(reach) = crate::cache::cross_head(&m) else { + continue; + }; + let mut args: Vec<String> = + vec!["ls-tree".into(), "-r".into(), sha.clone(), "--".into()]; + args.extend(m.inputs.iter().cloned()); + args.extend(runner::IMPLIED_BUILD_FILES.iter().map(|s| s.to_string())); + let argv: Vec<&str> = args.iter().map(String::as_str).collect(); + let listing = git(clone, &argv).unwrap_or_default(); + let scope = match reach { + crate::cache::Reach::Inputs => String::new(), + crate::cache::Reach::Tree => tree.trim().to_string(), + }; + let print = sha256_hex(format!("{}\n{scope}\n{listing}", m.digest).as_bytes()); + mine.push((m.gate.clone(), print)); + } + prints.insert(sha.clone(), mine); + } + let mut count: BTreeMap<&str, usize> = BTreeMap::new(); + for p in prints.values().flatten() { + *count.entry(p.1.as_str()).or_default() += 1; + } + prints + .iter() + .map(|(sha, v)| { + let first = v + .iter() + .filter(|(_, p)| count.get(p.as_str()).copied().unwrap_or(0) > 1) + .map(|(g, _)| g.clone()) + .collect(); + (sha.clone(), first) + }) + .collect() +} + +/// Judge several heads of one repository together (Drake 2026-10-20: "do all +/// the similar ones first and then you go to the ones that are unique"). The +/// heads run side by side; their host gates share one budget of +/// `cfg.batch_host` slots (default half the CPUs) in which gates another head +/// also selects go first, and their gb10 gates take one batch slot, one at a +/// time, before `/tmp/aien-gb10.lock`. A gate with a key another head is +/// running waits on that key's lock and then reuses the result. Results come +/// back in the order of `shas`. +pub fn run_batch( + cfg: &Config, + repo: &str, + shas: &[String], +) -> Vec<(String, Result<Summary, String>)> { + let mut seen = BTreeSet::new(); + let shas: Vec<String> = shas + .iter() + .filter(|s| seen.insert((*s).clone())) + .cloned() + .collect(); + let budget = std::sync::Arc::new(crate::resources::BatchShare::new( + cfg.batch_host + .unwrap_or_else(crate::resources::BatchShare::default_host), + )); + let first = if valid_repo_key(repo) { + batch_first(&cfg.clones.join(repo), &shas) + } else { + BTreeMap::new() + }; + let shares: Vec<Share> = shas + .iter() + .map(|s| (budget.clone(), first.get(s).cloned().unwrap_or_default())) + .collect(); + std::thread::scope(|scope| { + let handles: Vec<_> = shas + .iter() + .zip(&shares) + .map(|(sha, share)| scope.spawn(move || run_once_in(cfg, repo, sha, Some(share)))) + .collect(); + shas.iter() + .zip(handles) + .map(|(sha, h)| { + let r = h + .join() + .unwrap_or_else(|_| Err(format!("internal error while judging {sha}"))); + (sha.clone(), r) + }) + .collect() + }) +} + pub fn run_loop(cfg: &Config, iterations: Option<u64>) -> usize { let mut served = 0; let mut round = 0u64; + let mut head_cache = GithubHeadCache::default(); loop { round += 1; cfg.state.beat("-", "-", "poll"); @@ -1561,7 +1857,7 @@ pub fn run_loop(cfg: &Config, iterations: Option<u64>) -> usize { if cfg.github { for repo in &cfg.repos { let repository = plan::repository_name(&cfg.clones.join(repo), None); - match github_heads(&cfg.gh, &repository) { + match github_heads_cached(&cfg.gh, &repository, &mut head_cache) { Ok(shas) => { for s in shas { if !cfg.state.bundle_path(repo, &s).exists() { @@ -1573,54 +1869,74 @@ pub fn run_loop(cfg: &Config, iterations: Option<u64>) -> usize { } } } - for (repo, sha, trigger) in heads { - // One process judges a head at a time: the worktree is shared. - let _claim = match claim_head(&cfg.state, &repo, &sha) { - Ok(Some(c)) => c, - Ok(None) => { - println!("HEAD {repo} {sha} {}", held_note(&cfg.state, &repo, &sha)); - continue; - } - Err(e) => { - println!("HEAD {repo} {sha} ERROR {e}"); - continue; - } - }; - // The holder we waited behind may have served this head already. - let served_meanwhile = match &trigger { - Some(f) => !f.exists(), - None => cfg.state.bundle_path(&repo, &sha).exists(), - }; - if served_meanwhile { - println!("HEAD {repo} {sha} SKIP already judged by another process"); - continue; - } - match run_once(cfg, &repo, &sha) { - Ok(s) => { - println!( - "HEAD {repo} {sha} {} {} bundle {} publication {}", - s.verdict.as_str(), - s.reason, - s.bundle_path.display(), - s.publication - ); - served += 1; + // L307/L309 integration: take the block-first queue once per round, + // then preserve that order within each repository's batches. + let mut queue: std::collections::VecDeque<(String, String, Option<PathBuf>)> = heads.into(); + let mut tried = std::collections::HashSet::new(); + let blocks = if cfg.github { + crate::block_first::open_blocks(&cfg.state.root, &cfg.repos, SystemTime::now()) + } else { + Vec::new() + }; + let mut by_repo: BTreeMap<String, Vec<(String, Option<PathBuf>)>> = BTreeMap::new(); + while let Some((repo, sha, trigger)) = crate::block_first::next_head( + &mut queue, + &blocks, + &cfg.state.trigger_dir(), + &|r, s| cfg.state.bundle_path(r, s).exists(), + &mut tried, + ) { + by_repo.entry(repo).or_default().push((sha, trigger)); + } + for (repo, list) in by_repo { + let shas: Vec<String> = list.iter().map(|(s, _)| s.clone()).collect(); + // At most `cfg.batch_heads` heads are checked out at once. + let results: Vec<(String, Result<Summary, String>)> = shas + .chunks(cfg.batch_heads.max(1)) + .flat_map(|c| { + if c.len() > 1 { + run_batch(cfg, &repo, c) + } else { + c.iter() + .map(|s| (s.clone(), run_once(cfg, &repo, s))) + .collect() + } + }) + .collect(); + for ((sha, result), (_, trigger)) in results.into_iter().zip(list) { + let mut keep_trigger = false; + match result { + Ok(s) => { + println!( + "HEAD {repo} {sha} {} {} bundle {} publication {}", + s.verdict.as_str(), + s.reason, + s.bundle_path.display(), + s.publication + ); + served += 1; + } + Err(e) => { + println!("HEAD {repo} {sha} ERROR {e}"); + if e.contains("already being judged") { + keep_trigger = true; + } + let _ = cfg.state.journal_append(&json!({ + "utc": utc_string(now_secs()), + "repo": repo, + "sha": sha, + "verdict": "NOT_RUN", + "reason": format!("WORKER_ERROR:{e}"), + "publication": "none", + })); + } } - Err(e) => { - println!("HEAD {repo} {sha} ERROR {e}"); - let _ = cfg.state.journal_append(&json!({ - "utc": utc_string(now_secs()), - "repo": repo, - "sha": sha, - "verdict": "NOT_RUN", - "reason": format!("WORKER_ERROR:{e}"), - "publication": "none", - })); + if !keep_trigger { + if let Some(f) = trigger { + let _ = fs::remove_file(f); + } } } - if let Some(f) = trigger { - let _ = fs::remove_file(f); - } } if iterations.is_some_and(|n| round >= n) { break; @@ -1664,6 +1980,90 @@ mod tests { assert_ne!(pr_a, pr_b); assert_ne!(pr_a, main_a); } + /// A fake `gh` that answers `gh api -i [-H If-None-Match: E] PATH` from files: `<key>.body` and `<key>.etag` + /// (key = the path with every non-alphanumeric byte as `_`), and logs every call to `log`. + fn fake_gh(dir: &Path) -> PathBuf { + let script = dir.join("gh"); + fs::write( + &script, + r#"#!/bin/bash +d=$(dirname "$0") +echo "$*" >> "$d/log" +path="${@: -1}" +key=$(printf '%s' "$path" | tr -c 'A-Za-z0-9' '_') +if [ ! -f "$d/$key.body" ]; then printf 'HTTP/2.0 404 Not Found\r\n\r\n{}'; echo "gh: Not Found (HTTP 404)" >&2; exit 1; fi +etag=$(cat "$d/$key.etag") +if [[ " $* " == *"If-None-Match: $etag "* ]]; then printf 'HTTP/2.0 304 Not Modified\r\nEtag: %s\r\n\r\n' "$etag"; echo "gh: HTTP 304" >&2; exit 1; fi +printf 'HTTP/2.0 200 OK\r\nEtag: %s\r\nContent-Type: application/json\r\n\r\n' "$etag"; cat "$d/$key.body" +"#, + ) + .unwrap(); + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap(); + script + } + + fn fake_answer(dir: &Path, path: &str, etag: &str, body: &str) { + let key: String = path + .chars() + .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }) + .collect(); + fs::write(dir.join(format!("{key}.etag")), etag).unwrap(); + fs::write(dir.join(format!("{key}.body")), body).unwrap(); + } + + #[test] + fn an_unchanged_list_is_asked_with_its_etag_and_answered_from_memory() { + let dir = std::env::temp_dir().join(format!("l337-heads-{}", std::process::id())); + fs::create_dir_all(&dir).unwrap(); + let gh = fake_gh(&dir); + let gh = gh.to_str().unwrap(); + let (p1, p2, m1) = ("1".repeat(40), "2".repeat(40), "3".repeat(40)); + let pulls = "repos/aien-dev/demo/pulls?state=open&per_page=50"; + let main = "repos/aien-dev/demo/commits/main"; + fake_answer( + &dir, + pulls, + "W/\"a\"", + &format!(r#"[{{"head":{{"sha":"{p2}"}}}},{{"head":{{"sha":"{p1}"}}}}]"#), + ); + fake_answer(&dir, main, "\"m\"", &format!(r#"{{"sha":"{m1}"}}"#)); + let mut cache = GithubHeadCache::default(); + let first = github_heads_cached(gh, "github.com/aien-dev/demo", &mut cache).unwrap(); + assert_eq!(first, vec![p1.clone(), p2.clone(), m1.clone()]); + let second = github_heads_cached(gh, "github.com/aien-dev/demo", &mut cache).unwrap(); + assert_eq!(second, first, "a 304 gives back the earlier answer"); + let log = fs::read_to_string(dir.join("log")).unwrap(); + let lines: Vec<&str> = log.lines().collect(); + assert_eq!(lines.len(), 4, "two calls per poll: {log}"); + assert!( + !lines[0].contains("If-None-Match") && !lines[1].contains("If-None-Match"), + "first poll is unconditional: {log}" + ); + assert!( + lines[2].contains("If-None-Match: W/\"a\"") + && lines[3].contains("If-None-Match: \"m\""), + "second poll sends the etags: {log}" + ); + // The list changes: the new etag brings the new answer. + let p3 = "4".repeat(40); + fake_answer( + &dir, + pulls, + "W/\"b\"", + &format!(r#"[{{"head":{{"sha":"{p3}"}}}}]"#), + ); + let third = github_heads_cached(gh, "github.com/aien-dev/demo", &mut cache).unwrap(); + assert_eq!(third, vec![m1, p3], "sorted, new list replaces the old"); + // A repository GitHub does not know is an error, and forgets nothing it should not. + let err = github_heads_cached(gh, "github.com/aien-dev/missing", &mut cache).unwrap_err(); + assert!(err.contains("404"), "{err}"); + // With no memory (the old behaviour) every poll is unconditional. + let _ = github_heads(gh, "github.com/aien-dev/demo").unwrap(); + let log = fs::read_to_string(dir.join("log")).unwrap(); + assert!(!log.lines().last().unwrap().contains("If-None-Match")); + let _ = fs::remove_dir_all(&dir); + } #[test] fn pin_list_selects_the_repository_and_refuses_bad_lines() { diff --git a/tools/aien-test/tests/local_ci.rs b/tools/aien-test/tests/local_ci.rs index d4ca7d87..b6650387 100644 --- a/tools/aien-test/tests/local_ci.rs +++ b/tools/aien-test/tests/local_ci.rs @@ -1575,6 +1575,96 @@ fn worker_operator_run_of_a_config_change_is_ready_and_posts_success() { ); } +/// A new commit of `branch` with the very same tree (a re-push, a squash +/// merge of an up-to-date PR). +fn same_tree_commit_on(w: &World, branch: &str) -> String { + git(&w.origin, &["checkout", "-q", branch]); + git( + &w.origin, + &["commit", "-q", "--allow-empty", "-m", "same tree"], + ); + let sha = git(&w.origin, &["rev-parse", "HEAD"]); + git(&w.origin, &["checkout", "-q", "main"]); + git(&w.clone, &["fetch", "-q", "--all"]); + sha +} + +fn bundle_check(s: &worker::Summary, id: &str) -> serde_json::Value { + let b: serde_json::Value = serde_json::from_slice(&fs::read(&s.bundle_path).unwrap()).unwrap(); + b["checks"] + .as_array() + .unwrap() + .iter() + .find(|c| c["gate"] == id) + .cloned() + .unwrap_or_else(|| panic!("no check {id} in {b}")) +} + +/// Judge once (Drake 2026-10-20): a second head with the same tree reuses +/// the first head's result through the shared store, the signed bundle says +/// which receipt and which head it came from, and verify still says READY. +#[test] +fn another_head_reuses_through_the_shared_store_and_the_bundle_says_so() { + let w = world(); + let cfg = w.config(); + let r1 = worker::run_once(&cfg, REPO, &w.head).expect("worker r1"); + assert_eq!(gate_status(&r1, "A"), ("run".to_string(), Verdict::Pass)); + let receipt = bundle_check(&r1, "A")["receipt"] + .as_str() + .unwrap() + .to_string(); + + let head2 = same_tree_commit_on(&w, "topic"); + let r2 = worker::run_once(&cfg, REPO, &head2).expect("worker r2"); + assert_eq!(gate_status(&r2, "A"), ("cached".to_string(), Verdict::Pass)); + let c = bundle_check(&r2, "A"); + assert_eq!(c["resolution"]["resolved_from"], receipt.as_str()); + assert_eq!(c["resolution"]["resolved_from_commit"], w.head.as_str()); + assert!(r2.ready, "{:?}", r2.notes); + assert_eq!(r2.verdict, Verdict::Pass, "{}", r2.reason); + + // A head one declared byte away runs A again. + let head3 = commit_on(&w, "topic", &[("a/a.txt", "a3\n")], "change a"); + let r3 = worker::run_once(&cfg, REPO, &head3).expect("worker r3"); + assert_eq!(gate_status(&r3, "A"), ("run".to_string(), Verdict::Pass)); +} + +/// A batch of two heads with one tree runs each shared gate once: one head +/// runs it, the other reuses it, and both bundles are READY. +#[test] +fn a_batch_runs_a_shared_gate_once_for_all_its_heads() { + let w = world(); + let mut cfg = w.config(); + cfg.batch_host = Some(2); + let head2 = same_tree_commit_on(&w, "topic"); + let out = worker::run_batch(&cfg, REPO, &[w.head.clone(), head2.clone()]); + assert_eq!(out.len(), 2); + let mut statuses = Vec::new(); + for (sha, r) in &out { + let s = r.as_ref().unwrap_or_else(|e| panic!("{sha}: {e}")); + assert!(s.ready, "{sha}: {:?}", s.notes); + assert_eq!(s.verdict, Verdict::Pass, "{sha}: {}", s.reason); + statuses.push(gate_status(s, "A").0); + } + statuses.sort(); + assert_eq!(statuses, vec!["cached".to_string(), "run".to_string()]); +} + +/// One judge per head: a second judge of a head that is being judged is +/// refused at once, before any checkout. +#[test] +fn a_head_being_judged_is_refused_to_a_second_judge() { + let w = world(); + let cfg = w.config(); + let held = worker::claim_head(&w.state, REPO, &w.head) + .unwrap() + .expect("free"); + let e = worker::run_once(&cfg, REPO, &w.head).expect_err("refused"); + assert!(e.contains("already being judged"), "{e}"); + drop(held); + assert!(worker::run_once(&cfg, REPO, &w.head).is_ok()); +} + #[test] fn loop_leaves_triggers_of_other_repos_alone() { // One trigger file is visible to every poller; a poller started with