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#589 (code only)
Apply it
git checkout -b patch-00d6096f83903b53 bdd58a2b8fc873deecc06871809817801ac8b1e2 curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/00d6096f83903b53.patch | git am
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
589
77cca63424ee6a1a43de396ddf1d9e22bcc9a06d
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":589,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/589","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:35Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.crumb b/.crumb index 08ee53fc..f1d77dbe 100644 --- a/.crumb +++ b/.crumb @@ -65,68 +65,68 @@ "children": [ { "digest": "4e7f370019e67f6c71565d1544530851eb1b3b1bed61c2712f4ac7d9614a89bf", - "last_commit": "6bbe2ec", + "last_commit": "6bbe2ec2", "name": "crates/aien-allen", "purpose": "ALLEN identity gate: resolve-only subject check, host pin record, deployment record (ADR 0035). " }, { "digest": "40a231c50dba92af7de2527ab33879c5d1eaaa6e7ea5d6a5ebaa9d60c7542075", - "last_commit": "b9b52f9", + "last_commit": "b9b52f9c", "name": "crates/aien-allen-memory", "purpose": "ALLEN scoped memory store: scopes enforced at recall, inspect/correct/export, key-destroying for" }, { "digest": "44dc482b8c9db8919a68ec69b019cd77967232a6ec8b1910c0dfe3cd4d71f141", - "last_commit": "b9b52f9", + "last_commit": "b9b52f9c", "name": "crates/aien-allen-profile", "purpose": "ALLEN persona profile v1: versioned, user-editable profile bound to the engaged ALLEN identity; " }, { "digest": "f5571bcc0bb95b44dd8bf8f0b47ded3bcb1e1ee76c81b4ff5edb87ac237d66d8", - "last_commit": "f8eea42", + "last_commit": "f8eea420", "name": "crates/aien-cli", "purpose": "" }, { "digest": "25fd9f8afbea19702750f8ddba2ef4aeafc5bc4515aa695340a5af6931989c03", - "last_commit": "8cca802", + "last_commit": "8cca8020", "name": "crates/aien-scheduler/src/bin", "purpose": "" }, { "digest": "a0a981f6168d15e43a6b036c3aa82d44547aadfc3b6c62139a5a3afab0644514", - "last_commit": "8cca802", + "last_commit": "8cca8020", "name": "crates/spark-cockpit-rs", "purpose": "" }, { "digest": "f38ccede5d794040581cf48d409424c923d705a2fc206140b52691ef7fb186ef", - "last_commit": "deff6f7", + "last_commit": "deff6f7a", "name": "scripts", "purpose": "" }, { "digest": "75e439cb2ae120e1807af894b70b6454971028f5527f56451f9d6558f503c88b", - "last_commit": "fa73e77", + "last_commit": "fa73e778", "name": "skills", "purpose": "" }, { "digest": "b95ea9baa15ce7ddc69a3ef4dc25cdcccba52ec1f5fd99e19f0f24af9181a306", - "last_commit": "247e092", + "last_commit": "247e0927", "name": "tools/aien-local-ci", "purpose": "Local CI sandbox exec contract (C8), aien-run user/caches install, Forgejo trigger hook, health " } ], "children_root": "sha256:7d8cf5937a13dd896fe511aee80a0873f4917a0a5eb07cbe0fe3690c0c878cbb", - "compiled_at": "2026-10-16T10:56:35Z", + "compiled_at": "2026-10-16T15:26:31Z", "compiler": "crumb-compile/1", - "digest": "sha256:465b497c444698ff5ff701c52b5835526c9e7bf1bdb5bf9b3805e3753d369dd8", + "digest": "sha256:5c3262fb97f4051b7780f820f039da497a16ac9d1cf8d077e593d3b2e786ba89", "evidence_files": 1578, "evidence_root": "sha256:135e27a1a0704c4a8371cd2c1eb555f2b5beec61c212949b029a5457418a7160", "files": 5889, - "generated_at_commit": "a78ee68ab9a1285a7d4e8a983a7738ff2e1b7d4a", - "source_tree": "sha256:d2f1c2a7c6e804ba394685c392e84936afceeee5c6bf795bc5f3903b9113d8e2" + "generated_at_commit": "228809d2f65ded6e8bbc011bc817209d82255bb5", + "source_tree": "sha256:7bdcd0cf99ffd24054c17de9287bf4506d8059c855d566eab42a2280024ec2a2" } }, "history": [], diff --git a/crates/aien-inference-abi/src/lib.rs b/crates/aien-inference-abi/src/lib.rs index b6e9ff89..f9c52894 100644 --- a/crates/aien-inference-abi/src/lib.rs +++ b/crates/aien-inference-abi/src/lib.rs @@ -39,7 +39,7 @@ pub mod weights; /// bump orphans every stored chunk instead of serving K/V computed the old way. /// Guarded by `arith_epoch_pinned_bytes` in `aien-runtime`: a numeric change fails /// that test until this constant is bumped and the pin refreshed. -pub const KV_ARITH_EPOCH: u32 = 1; +pub const KV_ARITH_EPOCH: u32 = 2; pub use aien_abi_core::*; pub use aien_kv_cache::*; diff --git a/crates/aien-inference-abi/src/transformer_backend.rs b/crates/aien-inference-abi/src/transformer_backend.rs index e36e46ff..cdcfc493 100644 --- a/crates/aien-inference-abi/src/transformer_backend.rs +++ b/crates/aien-inference-abi/src/transformer_backend.rs @@ -9,7 +9,8 @@ use crate::{ DecodeOutput, FinishReason, ModelConfig, SamplingParams, ScheduledBatch, StepMetrics, }; use aien_kv_cache::{ - create_shared_kv_manager_with_pool, AienKvManager, KvDType, KvPoolConfig, SharedKvManager, + create_shared_kv_manager_with_pool, round_to_dtype_in_place, AienKvManager, KvDType, + KvPoolConfig, SharedKvManager, }; use async_trait::async_trait; use std::collections::HashMap; @@ -163,6 +164,10 @@ pub struct NativeTransformerBackend { pub sequences: HashMap<u64, SequenceState>, pub tensor_backend: Arc<dyn TensorBackend>, pub kv_manager: Option<SharedKvManager>, + /// Element type K/V are rounded to at birth when no physical pool is attached + /// (a pool's own dtype wins; see `storage_dtype`). `Fp32` = no rounding. A dense + /// control backend sets this to the pool dtype it is the reference for. + pub kv_dtype: KvDType, /// Per-request sampling params used by decode (PREFILL-E2E C6). Recorded /// from the prefill request (`execute_step`) and from the fork hook /// (`fork_sequence_with_sampling`; a plain `fork_sequence` child inherits @@ -214,6 +219,7 @@ impl NativeTransformerBackend { tensor_backend: Arc::new(ReferenceCpuBackend::new()), kv_manager: None, pending_prefill_token: HashMap::new(), + kv_dtype: KvDType::Fp32, } } @@ -230,6 +236,7 @@ impl NativeTransformerBackend { tensor_backend, kv_manager: None, pending_prefill_token: HashMap::new(), + kv_dtype: KvDType::Fp32, } } @@ -278,6 +285,7 @@ impl NativeTransformerBackend { tensor_backend: Arc::new(ReferenceCpuBackend::new()), kv_manager: Some(kv_mgr), pending_prefill_token: HashMap::new(), + kv_dtype: KvDType::Fp32, }) } @@ -305,6 +313,7 @@ impl NativeTransformerBackend { tensor_backend, kv_manager: Some(kv_mgr), pending_prefill_token: HashMap::new(), + kv_dtype: KvDType::Fp32, }) } @@ -322,6 +331,7 @@ impl NativeTransformerBackend { tensor_backend, kv_manager: Some(kv_manager), pending_prefill_token: HashMap::new(), + kv_dtype: KvDType::Fp32, } } @@ -346,12 +356,14 @@ impl NativeTransformerBackend { } let num_layers = self.weights.config.num_layers; + let kv_dtype = self.storage_dtype(); let seq = self .sequences .entry(seq_id) .or_insert_with(|| SequenceState { tokens: Vec::new(), layers: vec![LayerKvCache::default(); num_layers], + kv_dtype, }); let last_hidden = Self::prefill_prompt_layer_by_layer_paged( @@ -379,12 +391,14 @@ impl NativeTransformerBackend { } let num_layers = self.weights.config.num_layers; + let kv_dtype = self.storage_dtype(); let seq = self .sequences .entry(handle.0) .or_insert_with(|| SequenceState { tokens: Vec::new(), layers: vec![LayerKvCache::default(); num_layers], + kv_dtype, }); Self::prefill_prompt_layer_by_layer_paged( @@ -432,6 +446,7 @@ impl NativeTransformerBackend { SequenceState { tokens: parent_seq.tokens.clone(), layers: Vec::new(), + kv_dtype: parent_seq.kv_dtype, } } else { parent_seq.clone() @@ -1083,6 +1098,17 @@ impl NativeTransformerBackend { ) } + /// Element type every new sequence's K/V are rounded to the moment they are + /// produced: the attached pool's dtype (what `write_token_kv` stores), else + /// `kv_dtype`. One rounding point keeps dense cache, pool and attention on the + /// same bits (PREFILL-E2E-2). + pub fn storage_dtype(&self) -> KvDType { + self.kv_manager + .as_ref() + .and_then(|m| m.read().tensor_pool().map(|p| p.config().dtype)) + .unwrap_or(self.kv_dtype) + } + /// Forward pass executing one token forward pass through the transformer with optional paged COW KV. /// /// Panics when the paged KV pool cannot supply the block this token needs @@ -1207,6 +1233,10 @@ impl NativeTransformerBackend { num_kv_heads, &rope, ); + // Round once, at birth: pool write, dense cache and attention all see + // the same bits (PREFILL-E2E-2). + round_to_dtype_in_place(seq_state.kv_dtype, &mut k); + round_to_dtype_in_place(seq_state.kv_dtype, &mut v); if let (Some((block_id, slot)), Some(mgr)) = (block_slot, kv_manager) { { @@ -1382,6 +1412,7 @@ impl NativeTransformerBackend { // token t sits at absolute position `offset + t`: that position drives RoPE, // the paged block/slot, and the causal attention length. let offset = seq_state.tokens.len(); + let kv_dtype = seq_state.kv_dtype; if n == 1 && offset == 0 { // The token is recorded only after the forward pass succeeded, so a // loud KV failure leaves `seq_state` untouched. @@ -1573,10 +1604,14 @@ impl NativeTransformerBackend { for t in 0..n { let q_t = &mut q_batch[t * q_dim..(t + 1) * q_dim]; let k_t = &mut k_batch[t * kv_dim..(t + 1) * kv_dim]; - let v_t = &v_batch[t * kv_dim..(t + 1) * kv_dim]; + let v_t = &mut v_batch[t * kv_dim..(t + 1) * kv_dim]; let pos = offset + t; backend.apply_rope(q_t, k_t, pos, head_dim, num_heads, num_kv_heads, &rope); + // Round once, at birth, so this chunk's in-flight K/V and the earlier + // chunks gathered back from the pool carry the same bits (PREFILL-E2E-2). + round_to_dtype_in_place(kv_dtype, k_t); + round_to_dtype_in_place(kv_dtype, v_t); if let (Some((block_id, slot)), Some(mgr)) = (paged_slots[t], kv_manager) { // Slots exist only when a physical pool is attached, so this @@ -1927,8 +1962,14 @@ impl NativeTransformerBackend { ); } - // c. RoPE across all D sequences at their respective positions - for (i, &(_seq_id, _tok, pos)) in valid_reqs.iter().enumerate() { + // c. RoPE across all D sequences at their respective positions, then + // round K/V once at birth (PREFILL-E2E-2). + for (i, &(seq_id, _tok, pos)) in valid_reqs.iter().enumerate() { + let kv_dtype = self + .sequences + .get(&seq_id) + .map(|s| s.kv_dtype) + .unwrap_or_else(|| self.storage_dtype()); layer_w.apply_qk_norm_on( self.tensor_backend.as_ref(), &mut q_batch[i * q_dim..(i + 1) * q_dim], @@ -1945,6 +1986,8 @@ impl NativeTransformerBackend { num_kv_heads, &rope, ); + round_to_dtype_in_place(kv_dtype, &mut k_batch[i * kv_dim..(i + 1) * kv_dim]); + round_to_dtype_in_place(kv_dtype, &mut v_batch[i * kv_dim..(i + 1) * kv_dim]); } // d. Write K & V into KV cache @@ -2291,12 +2334,14 @@ impl AienInferenceBackend for NativeTransformerBackend { if let Some(&pending) = self.pending_prefill_token.get(&parent_id) { parent_tokens.push(pending); } + let kv_dtype = self.storage_dtype(); self.sequences.insert( child_id, SequenceState { tokens: parent_tokens, // Paged mode: K/V lives in the shared pool, never in per-sequence layers. layers: Vec::new(), + kv_dtype, }, ); // PREFILL-E2E C6: a plain fork inherits the parent's sampling params @@ -2407,12 +2452,14 @@ impl AienInferenceBackend for NativeTransformerBackend { "restore_sequence {seq_id} refused: sequence already has backend state" )); } + let kv_dtype = self.storage_dtype(); self.sequences.insert( seq_id, SequenceState { tokens: tokens.to_vec(), // Paged mode: K/V lives in the shared pool, never in per-sequence layers. layers: Vec::new(), + kv_dtype, }, ); Ok(()) @@ -2477,12 +2524,14 @@ impl AienInferenceBackend for NativeTransformerBackend { } } + let kv_dtype = self.storage_dtype(); let seq = self .sequences .entry(req.request_id) .or_insert_with(|| SequenceState { tokens: Vec::new(), layers: vec![LayerKvCache::default(); num_layers], + kv_dtype, }); let last_hidden = Self::prefill_prompt_layer_by_layer_paged( @@ -2593,6 +2642,7 @@ mod tests { let mut seq_state = SequenceState { tokens: vec![1], layers: vec![LayerKvCache::default(); config.num_layers], + kv_dtype: KvDType::Fp32, }; let hidden = backend.forward_token(1, 0, &mut seq_state); diff --git a/crates/aien-inference-abi/src/weights.rs b/crates/aien-inference-abi/src/weights.rs index 19afdc43..5835ac02 100644 --- a/crates/aien-inference-abi/src/weights.rs +++ b/crates/aien-inference-abi/src/weights.rs @@ -6,6 +6,7 @@ use crate::tensor::{ scaled_dot_product_attention_single, swiglu, }; use crate::ModelConfig; +use aien_kv_cache::KvDType; use serde_json::Value; #[derive(Debug, Clone, Default)] @@ -20,6 +21,10 @@ pub struct LayerKvCache { pub struct SequenceState { pub tokens: Vec<u32>, pub layers: Vec<LayerKvCache>, + /// Element type K/V are rounded to the moment they are produced, before any + /// reader (dense cache, pool write, attention) sees them. The pool's dtype when + /// a physical pool is attached, else the backend's `kv_dtype` (default `Fp32`). + pub kv_dtype: KvDType, } #[derive(Debug, Clone)] @@ -442,6 +447,7 @@ impl TransformerWeights { let mut seq_state = SequenceState { tokens: Vec::with_capacity(n), layers: vec![LayerKvCache::default(); self.config.num_layers], + kv_dtype: KvDType::Fp32, }; for (pos, &token_id) in tokens.iter().enumerate() { @@ -626,6 +632,7 @@ impl TransformerWeights { let mut seq_state = SequenceState { tokens: Vec::with_capacity(prompt_tokens.len() + num_steps), layers: vec![LayerKvCache::default(); self.config.num_layers], + kv_dtype: KvDType::Fp32, }; let mut last_hidden = Vec::new(); diff --git a/crates/aien-inference-abi/tests/qwen3_forward_parity.rs b/crates/aien-inference-abi/tests/qwen3_forward_parity.rs index 44f6cd74..620427c1 100644 --- a/crates/aien-inference-abi/tests/qwen3_forward_parity.rs +++ b/crates/aien-inference-abi/tests/qwen3_forward_parity.rs @@ -109,6 +109,7 @@ fn qwen3_tiny_token_by_token_logits_match_transformers() { let mut state = SequenceState { tokens: Vec::new(), layers: vec![Default::default(); weights.config.num_layers], + kv_dtype: Default::default(), }; let mut last = Vec::new(); for (pos, id) in r.ids.iter().enumerate() { diff --git a/crates/aien-inference-abi/tests/qwen3_untied_head.rs b/crates/aien-inference-abi/tests/qwen3_untied_head.rs index 53911594..cb0adf83 100644 --- a/crates/aien-inference-abi/tests/qwen3_untied_head.rs +++ b/crates/aien-inference-abi/tests/qwen3_untied_head.rs @@ -92,6 +92,7 @@ fn last_logits(w: &TransformerWeights, ids: &[u32]) -> Vec<f32> { let mut state = SequenceState { tokens: Vec::new(), layers: vec![Default::default(); w.config.num_layers], + kv_dtype: Default::default(), }; let mut last = Vec::new(); for (pos, id) in ids.iter().enumerate() { diff --git a/crates/aien-kv-cache/src/lib.rs b/crates/aien-kv-cache/src/lib.rs index 63f60027..2609b64a 100644 --- a/crates/aien-kv-cache/src/lib.rs +++ b/crates/aien-kv-cache/src/lib.rs @@ -55,6 +55,36 @@ pub enum KvDType { Fp32, } +impl Default for KvDType { + /// Full precision: no rounding anywhere (the pre-sc#464 behaviour). + fn default() -> Self { + KvDType::Fp32 + } +} + +/// Rounds `values` in place to what a pool of `dtype` would store, so a K/V vector +/// has the same bits whether a reader takes it from the dense per-sequence cache or +/// gathers it back from the pool (PREFILL-E2E-2: a prompt prefilled in chunks must +/// be bit-identical to the same prompt prefilled in one shot). Called once, where +/// the vector is produced; `write_token_kv` applies the same rounding on the pool +/// side, so the pool write is a no-op re-rounding. `Fp32` leaves the values alone. +/// Element types this crate cannot store on the host path are a loud error, as in +/// `write_token_kv`. +pub fn round_to_dtype_in_place(dtype: KvDType, values: &mut [f32]) { + match dtype { + KvDType::Fp32 => {} + KvDType::Bf16 => { + for x in values.iter_mut() { + *x = bf16_bits_to_f32(f32_to_bf16_bits(*x)); + } + } + other => panic!( + "Unsupported KvDType for round_to_dtype_in_place: {:?}", + other + ), + } +} + impl KvDType { pub fn bytes_per_element(&self) -> f32 { match self { diff --git a/crates/aien-runtime/tests/compute_config_binding_test.rs b/crates/aien-runtime/tests/compute_config_binding_test.rs index 24cb7a3c..07868e7c 100644 --- a/crates/aien-runtime/tests/compute_config_binding_test.rs +++ b/crates/aien-runtime/tests/compute_config_binding_test.rs @@ -298,8 +298,8 @@ fn conversion_refuses_values_that_do_not_fit_the_wire_width() { // --- arith_epoch_pinned_bytes ------------------------------------------------ /// The epoch the pin below was taken at, and the SHA-256 of the K/V bytes. -const PINNED_EPOCH: u32 = 1; -const PINNED_KV_SHA256: &str = "9b29d964da18f2fb47584bdf7b42932996bfc05d53e6071c7af89a9ce5a80fa2"; +const PINNED_EPOCH: u32 = 2; +const PINNED_KV_SHA256: &str = "48340604c2513464fde46789d95b2473e87fdb057201822ff207b5e1acf4872c"; fn pin_model() -> ModelConfig { ModelConfig { diff --git a/crates/aien-runtime/tests/kv_park_restore_test.rs b/crates/aien-runtime/tests/kv_park_restore_test.rs index e6ae4162..fbd6cded 100644 --- a/crates/aien-runtime/tests/kv_park_restore_test.rs +++ b/crates/aien-runtime/tests/kv_park_restore_test.rs @@ -1011,13 +1011,27 @@ async fn restore_retry_window_prefills_without_lookup_after_two_failures() { /// ADR 2.4 / METRICS `kv_park_indeterminate_total`: a publication whose /// directory sync failed after the rename is served but counted indeterminate. +/// +/// Dispatch stays paused until both park jobs are submitted. The faulted first +/// job puts the fake store into `Degraded`, and a store in that state refuses +/// new submissions (`DeviceUnavailable`); with a running worker the second +/// submission raced that terminal and lost about one time in six (one job +/// counted, two failures), so the race is removed rather than tolerated. #[tokio::test] async fn indeterminate_park_publication_is_counted() { - let mut r = rig(); + let mut r = rig_with(0, true); r.fake.script(JobScript::fault(Fault::RenameOkDirsyncFail)); - park_turn(&mut r, &prompt14(), 3).await; + let seq = r.spine.submit_request(request(&prompt14(), 3)); + step(&mut r).await; + paint(&r, seq); + step_until(&mut r, "turn finished with both parks submitted", |r| { + finished(r, seq) && status(r).parking_jobs == 2 + }) + .await; + r.worker.resume_dispatch(); + step_until(&mut r, "parks terminal", |r| status(r).parking_jobs == 0).await; let s = status(&r).stats; - assert_eq!(s.park_jobs_total, 2); + assert_eq!(s.park_jobs_total, 2, "{s:?}"); assert_eq!(s.park_indeterminate_total, 1, "{s:?}"); // The object is published and served, its durability unknown (the fake // reports it on a failed terminal and the store goes Degraded). diff --git a/crates/aien-runtime/tests/prefill_e2e2.rs b/crates/aien-runtime/tests/prefill_e2e2.rs index b4f45a4a..47a69d56 100644 --- a/crates/aien-runtime/tests/prefill_e2e2.rs +++ b/crates/aien-runtime/tests/prefill_e2e2.rs @@ -75,7 +75,7 @@ use aien_inference_abi::{ TensorBackend, TinyLlamaTokenizer, TransformerWeights, }; use aien_kv_cache::SharedKvManager; -use aien_runtime::shared_kv::{build_shared_kv_runtime, SharedKvSizing}; +use aien_runtime::shared_kv::{build_shared_kv_runtime, SharedKvSizing, SHARED_KV_DTYPE}; use aien_scheduler::SchedulerConfig; use parking_lot::Mutex; use sha2::{Digest, Sha256}; @@ -1141,6 +1141,9 @@ async fn run_stages(env: &Env<'_>, ev: &mut Evidence) -> Result<(), String> { // 217-token control is the witness control. let t_control = Instant::now(); let mut control = NativeTransformerBackend::new(env.weights.clone()); + // The control is dense (no pool) but is the reference for a pool of + // SHARED_KV_DTYPE, so it rounds K/V at birth exactly as the paged backend does. + control.kv_dtype = SHARED_KV_DTYPE; if control.kv_manager.is_some() { return Err("control must be unpaged".to_string()); } diff --git a/crates/aien-runtime/tests/prefill_e2e2_mutants/mutant_m1.patch b/crates/aien-runtime/tests/prefill_e2e2_mutants/mutant_m1.patch index edb65721..7b5b0e46 100644 --- a/crates/aien-runtime/tests/prefill_e2e2_mutants/mutant_m1.patch +++ b/crates/aien-runtime/tests/prefill_e2e2_mutants/mutant_m1.patch @@ -1,9 +1,9 @@ diff --git a/crates/aien-inference-abi/src/transformer_backend.rs b/crates/aien-inference-abi/src/transformer_backend.rs -index 0ea923d..68a0920 100644 +index cdcfc49..dea36bb 100644 --- a/crates/aien-inference-abi/src/transformer_backend.rs +++ b/crates/aien-inference-abi/src/transformer_backend.rs -@@ -1675,10 +1675,15 @@ impl AienInferenceBackend for NativeTransformerBackend { - layers: vec![LayerKvCache::default(); num_layers], +@@ -2534,10 +2534,15 @@ impl AienInferenceBackend for NativeTransformerBackend { + kv_dtype, }); + // MUTANT m1 (PE2E2-A): replay the whole earlier context with every prefill request diff --git a/crates/aien-runtime/tests/prefill_e2e2_mutants/mutant_m2.patch b/crates/aien-runtime/tests/prefill_e2e2_mutants/mutant_m2.patch index d7bb7ac2..25ac30f1 100644 --- a/crates/aien-runtime/tests/prefill_e2e2_mutants/mutant_m2.patch +++ b/crates/aien-runtime/tests/prefill_e2e2_mutants/mutant_m2.patch @@ -1,14 +1,14 @@ diff --git a/crates/aien-inference-abi/src/transformer_backend.rs b/crates/aien-inference-abi/src/transformer_backend.rs -index 0ea923d..9e4a50f 100644 +index cdcfc49..d298e62 100644 --- a/crates/aien-inference-abi/src/transformer_backend.rs +++ b/crates/aien-inference-abi/src/transformer_backend.rs -@@ -963,7 +963,8 @@ impl NativeTransformerBackend { +@@ -1606,7 +1606,8 @@ impl NativeTransformerBackend { let k_t = &mut k_batch[t * kv_dim..(t + 1) * kv_dim]; - let v_t = &v_batch[t * kv_dim..(t + 1) * kv_dim]; + let v_t = &mut v_batch[t * kv_dim..(t + 1) * kv_dim]; - let pos = offset + t; + // MUTANT m2 (PE2E2-A): a short continuation chunk restarts RoPE at position 0 + let pos = if offset > 0 && n < 64 { t } else { offset + t }; - backend.apply_rope(q_t, k_t, pos, head_dim, num_heads, num_kv_heads, theta); - - if let (Some((block_id, slot)), Some(mgr)) = (paged_slots[t], kv_manager) { + backend.apply_rope(q_t, k_t, pos, head_dim, num_heads, num_kv_heads, &rope); + // Round once, at birth, so this chunk's in-flight K/V and the earlier + // chunks gathered back from the pool carry the same bits (PREFILL-E2E-2). diff --git a/crates/aien-runtime/tests/prefill_e2e2_mutants/mutant_m3.patch b/crates/aien-runtime/tests/prefill_e2e2_mutants/mutant_m3.patch index bf829980..8b0f24f4 100644 --- a/crates/aien-runtime/tests/prefill_e2e2_mutants/mutant_m3.patch +++ b/crates/aien-runtime/tests/prefill_e2e2_mutants/mutant_m3.patch @@ -1,9 +1,9 @@ diff --git a/crates/aien-kv-cache/src/lib.rs b/crates/aien-kv-cache/src/lib.rs -index cd73fc7..2d35217 100644 +index 87df391..b357c5d 100644 --- a/crates/aien-kv-cache/src/lib.rs +++ b/crates/aien-kv-cache/src/lib.rs -@@ -1193,6 +1193,8 @@ impl<B: aien_platform::UnifiedBuffer> AienKvManager<B> { - let new_blk = self.allocate_block()?; +@@ -1473,6 +1473,8 @@ impl<B: aien_platform::UnifiedBuffer> AienKvManager<B> { + self.cow_faults += 1; if let Some(pool) = &mut self.tensor_pool { pool.copy_block(last_blk_id, new_blk); + // MUTANT m3 (PE2E2-A): copy-on-write wipes the old shared tail block after the copy diff --git a/crates/aien-runtime/tests/prefill_e2e2_mutants/mutant_m5.patch b/crates/aien-runtime/tests/prefill_e2e2_mutants/mutant_m5.patch index 11f2350e..92e32543 100644 --- a/crates/aien-runtime/tests/prefill_e2e2_mutants/mutant_m5.patch +++ b/crates/aien-runtime/tests/prefill_e2e2_mutants/mutant_m5.patch @@ -1,8 +1,8 @@ diff --git a/crates/aien-kv-cache/src/lib.rs b/crates/aien-kv-cache/src/lib.rs -index cd73fc7..006b801 100644 +index 87df391..54c455c 100644 --- a/crates/aien-kv-cache/src/lib.rs +++ b/crates/aien-kv-cache/src/lib.rs -@@ -1187,7 +1187,8 @@ impl<B: aien_platform::UnifiedBuffer> AienKvManager<B> { +@@ -1465,7 +1465,8 @@ impl<B: aien_platform::UnifiedBuffer> AienKvManager<B> { let last_blk_id = table.block_ids[last_blk_idx]; let blk = &self.blocks[last_blk_id]; @@ -10,5 +10,5 @@ index cd73fc7..006b801 100644 + // MUTANT m5 (PE2E2-A): a shared partial tail is appended to in place, no copy-on-write + if false && blk.is_shared { if blk.num_tokens < self.block_size { - self.cow_faults += 1; - let new_blk = self.allocate_block()?; + // Counted only once the copy has a block: a copy-on-write refused for + // an empty pool is not a fault that happened (L6-KV). diff --git a/crates/aien-runtime/tests/prefill_e2e2_mutants/mutant_m7.patch b/crates/aien-runtime/tests/prefill_e2e2_mutants/mutant_m7.patch index da6dc960..5f60ceec 100644 --- a/crates/aien-runtime/tests/prefill_e2e2_mutants/mutant_m7.patch +++ b/crates/aien-runtime/tests/prefill_e2e2_mutants/mutant_m7.patch @@ -1,8 +1,8 @@ diff --git a/crates/aien-kv-cache/src/lib.rs b/crates/aien-kv-cache/src/lib.rs -index cd73fc7..b7a13d0 100644 +index 87df391..ee21dcd 100644 --- a/crates/aien-kv-cache/src/lib.rs +++ b/crates/aien-kv-cache/src/lib.rs -@@ -1187,7 +1187,8 @@ impl<B: aien_platform::UnifiedBuffer> AienKvManager<B> { +@@ -1465,7 +1465,8 @@ impl<B: aien_platform::UnifiedBuffer> AienKvManager<B> { let last_blk_id = table.block_ids[last_blk_idx]; let blk = &self.blocks[last_blk_id]; @@ -10,5 +10,5 @@ index cd73fc7..b7a13d0 100644 + // MUTANT m7 (PE2E2-A): a shared tail with a single token is appended to in place + if blk.is_shared && blk.num_tokens > 1 { if blk.num_tokens < self.block_size { - self.cow_faults += 1; - let new_blk = self.allocate_block()?; + // Counted only once the copy has a block: a copy-on-write refused for + // an empty pool is not a fault that happened (L6-KV). diff --git a/crates/aien-runtime/tests/shared_kv_runtime_test.rs b/crates/aien-runtime/tests/shared_kv_runtime_test.rs index 8edb952f..61fab9b0 100644 --- a/crates/aien-runtime/tests/shared_kv_runtime_test.rs +++ b/crates/aien-runtime/tests/shared_kv_runtime_test.rs @@ -36,9 +36,12 @@ use aien_scheduler::SchedulerConfig; const TOL: f32 = 1e-6; -/// The unpaged backend keeps f32 K/V; the spine pool stores `SHARED_KV_DTYPE`. The pool value -/// must equal the unpaged value rounded to the pool dtype, exactly (bf16 round-to-nearest-even), -/// so a pool that stored something other than the rounded f32 still fails this check. +/// The spine pool stores `SHARED_KV_DTYPE`, and since the birth-rounding fix (KV_ARITH_EPOCH 2) +/// every backend rounds K/V to its storage dtype the moment they are produced, so attention sees +/// the same bits the pool keeps. The control below therefore runs with `kv_dtype = SHARED_KV_DTYPE` +/// and must match the pool value exactly (bf16 round-to-nearest-even); `pool_rounded` is then the +/// identity on the control value and only guards against a pool that stored something other than +/// the rounded f32. fn pool_rounded(x: f32) -> f32 { match SHARED_KV_DTYPE { KvDType::Bf16 => bf16_bits_to_f32(f32_to_bf16_bits(x)), @@ -160,7 +163,10 @@ async fn shared_kv_root_prefill_lands_in_spine_pool_and_matches_unpaged_backend( assert!(!spine.swarm_manager.is_root_prefill_pending(swarm_id)); // Control: an unpaged backend (no KV manager) with the same weights. + // Same storage dtype as the pool: both sides round at birth, so the hidden states that feed + // later layers agree bit for bit (an f32 control diverges from layer 1 on, see #589). let mut control = NativeTransformerBackend::new_reference(weights); + control.kv_dtype = SHARED_KV_DTYPE; let control_id = 9_000_001u64; control .prefill_sequence(control_id, &prompt) diff --git a/tools/aien-test/docs/LOCAL_VERIFICATION.md b/tools/aien-test/docs/LOCAL_VERIFICATION.md index 790900cb..e955a369 100644 --- a/tools/aien-test/docs/LOCAL_VERIFICATION.md +++ b/tools/aien-test/docs/LOCAL_VERIFICATION.md @@ -118,6 +118,22 @@ rule (`Config.allow_unsandboxed`, default false). Under `--sandbox user` the worker passes `CARGO_TARGET_DIR=/var/lib/aien-run/target/<repo>/main` for a head already on the base line and `.../pr` for any other head (A2). +The gates of one head share that target dir, so the runner holds it for one +gate at a time: every gate that runs takes an exclusive `flock` on +`<state>/locks/target/<sanitised target dir>.lock` (the `CARGO_TARGET_DIR` it +is given, or else the worktree's own `target/`) for its whole run, build and +execution, and releases it when its process has exited. Every gate, not only +those whose manifest names cargo inputs: SC-INQUISITOR builds with cargo and +lists no `Cargo.toml`, and the runner cannot see inside a script. The lock is +the worker's, never the gate's. Without it two gates built in one target dir +at once and one relinked a test binary the other was executing (sc fix/521: +SC-AGENT-PREFLIGHT under SC-TEST, `current_exe: NotFound`, a false FAIL). +Gates given different target dirs still run at the same time. The fixed lock +order of one gate is: pool slot, target-dir lock, `/tmp/aien-gb10.lock`, +aien-proof `slots/gpu.lock`; the worker's target priming takes only the +target-dir lock. Known limit: a gb10 gate is never killed on timeout, so a +hung one holds the target dir until it exits on its own. + Under `--sandbox user` every checkout is made with INFRA's worktree tool (`--wt-tool`, default `<clones>/aien-sovereign-core/tools/aien-local-ci/wt.sh`; without it the worker refuses to run). `wt.sh sync` refreshes the bare mirror diff --git a/tools/aien-test/src/resources.rs b/tools/aien-test/src/resources.rs index fe55128e..407c6aad 100644 --- a/tools/aien-test/src/resources.rs +++ b/tools/aien-test/src/resources.rs @@ -8,9 +8,17 @@ //! //! Deadlock rule: whenever more than one resource is taken, they are taken in //! one fixed order. Pools are ordered by `Pool`'s derived `Ord` (gb10, then -//! qemu, then host). For a gb10 job the order is: the in-process gb10 slot, -//! then `/tmp/aien-gb10.lock`, then aien-proof's `slots/gpu.lock` when the -//! aien-proof board directory exists. +//! qemu, then host). The full order for one gate is: (1) the in-process pool +//! slot, (2) the target-dir lock (`lock_target_dir`, every gate that runs, +//! on its `CARGO_TARGET_DIR` or else the worktree's `target/`), (3) +//! `/tmp/aien-gb10.lock`, (4) aien-proof's `slots/gpu.lock` when the +//! aien-proof board directory exists. A holder of (2) already has its slot +//! and never waits for one, so a gate blocked on (2) with a slot in hand +//! cannot close a cycle; the worker's target priming takes (2) alone and +//! never (3) or (4). Known limit: a gb10 gate is never killed on timeout, +//! so a hung one holds (2) and (3) until it exits on its own; every other +//! gate of that target dir waits behind it (the receipt says +//! `timeout_exceeded`). //! //! GPU job protocol (CR-028, CR-029, CR-033, CR-052, CR-053): refuse at once //! (never wait, never steal) if the quiet flag file exists or an `est_load` @@ -405,6 +413,68 @@ impl Drop for GpuGuard { } } +/// The default directory of the target-dir lock files for a bare `run` +/// without a worker state dir (the worker uses `<state>/locks/target`). +pub const DEFAULT_TARGET_LOCK_DIR: &str = "/tmp/aien-test-target-locks"; + +/// The lock file for one cargo target dir: `<lock_dir>/<sanitised>.lock`, +/// where every character of the target dir path outside `[A-Za-z0-9._-]` +/// becomes `_`. The path is taken as given (no canonicalising), so every +/// holder that names the same target dir names the same lock file. Not +/// inside the target dir itself: under the user sandbox that belongs to +/// `aien-run`, and the lock is the worker's. +pub fn target_lock_path(lock_dir: &Path, target_dir: &Path) -> PathBuf { + let name: String = target_dir + .display() + .to_string() + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') { + c + } else { + '_' + } + }) + .collect(); + lock_dir.join(format!("{name}.lock")) +} + +/// Exclusive hold of one cargo target dir (`flock(LOCK_EX)`, waited for). +/// Held by the runner for a whole cargo gate, build and run, so two gates of +/// one head never build in, or relink a binary under, the same target dir +/// at once (sc fix/521: SC-AGENT-PREFLIGHT relinked a test binary while +/// SC-TEST was executing it). Dropping it closes the descriptor under the +/// spawn gate, like `GpuGuard`. +#[derive(Debug)] +pub struct TargetLock { + file: Option<File>, + path: PathBuf, +} + +impl TargetLock { + pub fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TargetLock { + fn drop(&mut self) { + let _gate = crate::process::spawn_gate(); + self.file.take(); + } +} + +/// 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> { + let file = open_lock(path)?; + flock_exclusive(&file, true)?; + Ok(TargetLock { + file: Some(file), + path: path.to_path_buf(), + }) +} + fn open_lock(path: &Path) -> io::Result<File> { if let Some(parent) = path.parent() { if !parent.as_os_str().is_empty() { @@ -516,6 +586,46 @@ mod tests { }); } + #[test] + fn target_lock_path_is_one_file_per_target_dir_under_the_lock_dir() { + let p = target_lock_path( + Path::new("/state/locks/target"), + Path::new("/var/lib/aien-run/target/aien-sovereign-core/pr"), + ); + assert_eq!( + p, + PathBuf::from( + "/state/locks/target/_var_lib_aien-run_target_aien-sovereign-core_pr.lock" + ) + ); + let main = target_lock_path(Path::new("/l"), Path::new("/t/main")); + let pr = target_lock_path(Path::new("/l"), Path::new("/t/pr")); + assert_ne!(main, pr, "main and pr are different target dirs"); + } + + /// Two holders in one process (two `open`s, two file descriptions) and + /// so two threads of the runner exclude each other; the second waits + /// until the first is dropped. + #[test] + fn target_lock_is_exclusive_and_waited_for() { + let dir = TempDir::new("tlock"); + let path = target_lock_path(dir.path(), Path::new("/t/pr")); + let held = lock_target_dir(&path).unwrap(); + assert!(held.path().exists()); + let (tx, rx) = mpsc::channel(); + thread::scope(|s| { + s.spawn(|| { + let _second = lock_target_dir(&path).unwrap(); + tx.send(()).unwrap(); + }); + thread::sleep(Duration::from_millis(200)); + assert!(rx.try_recv().is_err(), "the second holder must wait"); + drop(held); + rx.recv_timeout(Duration::from_secs(20)) + .expect("the waiter takes the lock after the release"); + }); + } + #[test] fn gb10_pool_is_serialized() { let p = Pools::new(PoolSizes { host: 4, qemu: 2 }); diff --git a/tools/aien-test/src/runner.rs b/tools/aien-test/src/runner.rs index 1258b401..0cf0703b 100644 --- a/tools/aien-test/src/runner.rs +++ b/tools/aien-test/src/runner.rs @@ -27,7 +27,7 @@ use crate::graph::Graph; use crate::manifest::{self, Manifest}; use crate::process::{self, RunSpec}; use crate::resources::{ - acquire_gpu, lock, GpuConfig, GpuGuard, Hardware, Permit, Pool, PoolSizes, Pools, + self, acquire_gpu, lock, GpuConfig, GpuGuard, Hardware, Permit, Pool, PoolSizes, Pools, }; use crate::sandbox::{self, Sandbox}; use crate::verdict::{self, campaign_verdict, derive, parse_observations, DepFact, Facts, Verdict}; @@ -60,6 +60,11 @@ pub struct Options { /// `CARGO_TARGET_DIR` as the runner itself was given it; passed through /// the sandbox as the only environment pair. pub cargo_target_dir: Option<PathBuf>, + /// Where the per-target-dir lock files live (`resources::target_lock_path`). + /// Every gate that runs holds the lock of its target dir (`cargo_target_dir` + /// or the worktree's `target/`) for its whole run, so two gates never + /// build in one target dir at once. The worker sets `<state>/locks/target`. + pub target_lock_dir: PathBuf, /// `--release`: qualification mode. No cache reuse and the tree must be /// clean even with `--allow-dirty`. pub release: bool, @@ -83,6 +88,7 @@ impl Options { gpu: GpuConfig::detect(), sandbox: Sandbox::None, cargo_target_dir: None, + target_lock_dir: PathBuf::from(crate::resources::DEFAULT_TARGET_LOCK_DIR), release: false, pins: json!([]), } @@ -660,6 +666,31 @@ fn execute_gate(job: &Job<'_>, permit: Option<Permit<'_>>) -> Result<Outcome, Ru } } + // 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 + // names cargo inputs: SC-INQUISITOR builds with cargo and lists no + // Cargo.toml, and the runner cannot see inside a script. The dir is the + // `CARGO_TARGET_DIR` the gate is given, or else the worktree's own + // `target/`, which cargo uses by default. Taken after the pool slot and + // before the GPU locks: the fixed order in `resources`. Waited for, + // never refused: the holder is another gate or the worker's priming. + // 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 + }; + // A gb10 gate takes the GPU locks only when nothing else already stops it. // A refusal (quiet flag, est_load, a held lock) becomes the gate's reason. let gpu: Option<GpuGuard> = if m.pool() == "gb10" && verdict::pre_run(m, &facts).is_none() { @@ -717,6 +748,7 @@ fn execute_gate(job: &Job<'_>, permit: Option<Permit<'_>>) -> Result<Outcome, Ru } // The job is over: close the lock descriptors at once. drop(gpu); + drop(target_lock); after = porcelain(root).map_err(RunError::Fatal)?; let head_after = head(root).unwrap_or_default(); facts.tree_changed_after = after != before; @@ -1689,6 +1721,15 @@ mod tests { /// A repository with one gate (tests/<id>.gate) and script /// (tools/<id>.sh) per entry; `@S@` in a script is the scratch directory. fn gfx(gates: &[GateSpec]) -> Gfx { + gfx_with(gates, "", &[]) + } + + /// `inputs` block of a gate that declares it builds in the target dir. + const CARGO_INPUTS: &str = "inputs:\n - Cargo.lock\n"; + + /// `gfx` with `extra` appended to every manifest and `files` added to + /// the repository (a `Cargo.lock` for the cargo gates). + fn gfx_with(gates: &[GateSpec], extra: &str, more: &[(&str, &str)]) -> Gfx { let scratch = TempDir::new("gscratch"); let s = scratch.path().to_str().unwrap().to_string(); let mut files: Vec<(String, String, bool)> = Vec::new(); @@ -1696,10 +1737,13 @@ mod tests { files.push((format!("tools/{id}.sh"), script.replace("@S@", &s), true)); files.push(( format!("tests/{id}.gate"), - graph_gate_text(id, deps, requires), + format!("{}{extra}", graph_gate_text(id, deps, requires)), false, )); } + for (p, c) in more { + files.push((p.to_string(), c.to_string(), false)); + } let refs: Vec<(&str, &str, bool)> = files .iter() .map(|(p, c, x)| (p.as_str(), c.as_str(), *x)) @@ -1843,14 +1887,130 @@ mod tests { assert_eq!(c.exit_code(), 3); } + /// `log` holds `start-X, end-X` pairs with no interleaving. + fn assert_serial(log: &[String], what: &str) { + assert_eq!(log.len() % 2, 0, "{what}: {log:?}"); + for pair in log.chunks(2) { + let id = pair[0].strip_prefix("start-").unwrap_or("?"); + assert_eq!(pair[1], format!("end-{id}"), "{what} overlapped: {log:?}"); + } + } + + /// Without a `CARGO_TARGET_DIR` the gates of one run still share the + /// worktree's own `target/`, so they are serialised on that path. + #[test] + fn gates_without_a_target_dir_serialise_on_the_worktree_target() { + 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 log = fx.log(); + assert_eq!(log.len(), 4, "{log:?}"); + assert_serial(&log, "gates sharing the worktree target"); + let lock = crate::resources::target_lock_path( + &opts.target_lock_dir, + &resolve(fx.repo.path()).join("target"), + ); + assert!(lock.exists(), "lock {} never taken", lock.display()); + } + + /// 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. #[test] - fn independent_gates_run_at_the_same_time_when_the_pool_allows() { + fn every_gate_given_a_target_dir_is_serialised() { + let cargo_user = |id: &str| { + format!( + "#!/bin/sh\necho start-{id} >> \"@S@/log\"\n\"${{CARGO:-cargo}}\" --version >/dev/null\nsleep 0.2\necho end-{id} >> \"@S@/log\"\n" + ) + }; + let fx = gfx(&[ + ("G-A", "", "host", cargo_user("G-A")), + ("G-B", "", "host", cargo_user("G-B")), + ]); + let mut opts = fx.opts(); + opts.cargo_target_dir = Some(fx.scratch.path().join("target")); + 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_eq!(log.len(), 4, "{log:?}"); + assert_serial(&log, "undeclared cargo users"); + } + + /// Two cargo gates of one head share `CARGO_TARGET_DIR`. Run at the same + /// time, one relinks a test binary the other is executing (sc fix/521: + /// SC-AGENT-PREFLIGHT relinked `aien_inference_abi-*` under SC-TEST, which + /// then failed with `current_exe: NotFound`). The runner must hold the + /// target dir for one cargo gate at a time, whatever the pool allows. + #[test] + fn cargo_gates_sharing_a_target_dir_never_overlap() { + let fx = gfx_with( + &[ + ("C-A", "", "host", slow("C-A")), + ("C-B", "", "host", slow("C-B")), + ], + CARGO_INPUTS, + &[("Cargo.lock", "# lock\n")], + ); + let mut opts = fx.opts(); + opts.cargo_target_dir = Some(fx.scratch.path().join("target")); + 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_eq!(log.len(), 4, "{log:?}"); + let first = log[0].trim_start_matches("start-").to_string(); + let second = if first == "C-A" { "C-B" } else { "C-A" }; + assert_eq!( + log, + vec![ + format!("start-{first}"), + format!("end-{first}"), + format!("start-{second}"), + format!("end-{second}"), + ], + "the two cargo gates overlapped in one target dir" + ); + let lock = crate::resources::target_lock_path( + &opts.target_lock_dir, + &fx.scratch.path().join("target"), + ); + assert!( + lock.exists(), + "the lock file {} was never taken", + lock.display() + ); + } + + /// The lock is per target dir: gates given different target dirs still + /// run at the same time. + #[test] + fn gates_with_different_target_dirs_run_at_the_same_time() { let fx = gfx(&[ ("G-A", "", "host", rendezvous("a", "b")), ("G-B", "", "host", rendezvous("b", "a")), ]); - let c = fx.campaign(&fx.opts()); - assert_eq!(c.exit_code(), 0); + let mut opts = fx.opts(); + opts.target_lock_dir = fx.scratch.path().join("locks"); + let g = fx.graph(); + let (a, b) = (g.index_of("G-A").unwrap(), g.index_of("G-B").unwrap()); + thread::scope(|s| { + for (i, dir) in [(a, "ta"), (b, "tb")] { + let mut o = Options { + cargo_target_dir: Some(fx.scratch.path().join(dir)), + ..fx.opts() + }; + o.target_lock_dir = opts.target_lock_dir.clone(); + let sel: BTreeSet<usize> = [i].into_iter().collect(); + let (g, root) = (&g, fx.repo.path()); + s.spawn(move || run_graph(root, g, &sel, &o).unwrap()); + } + }); assert!(fx.scratch.path().join("saw-a").exists(), "A never saw B"); assert!(fx.scratch.path().join("saw-b").exists(), "B never saw A"); } diff --git a/tools/aien-test/src/worker.rs b/tools/aien-test/src/worker.rs index 4736e9dd..39288d3c 100644 --- a/tools/aien-test/src/worker.rs +++ b/tools/aien-test/src/worker.rs @@ -126,6 +126,14 @@ impl StateDir { self.root.join("evidence").join(repo).join(sha) } + /// `<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 + /// `target/<repo>/pr`, takes its lock from here. + pub fn target_lock_dir(&self) -> PathBuf { + self.root.join("locks").join("target") + } + pub fn bundle_path(&self, repo: &str, sha: &str) -> PathBuf { self.root .join("bundles") @@ -912,6 +920,7 @@ fn run_in_worktree( let mut opts = Options::new(evidence_dir.clone()); opts.sandbox = cfg.sandbox; opts.cargo_target_dir = target_dir_for(cfg, repo, on_main); + opts.target_lock_dir = cfg.state.target_lock_dir(); opts.pool_sizes = opts.pool_sizes.with(cfg.jobs); opts.pins = pins; if fresh || cfg.no_cache {