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
aien-sovereign-core-mv / crates / aien-runtime / tests / provisional_prep_test.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Headstart M3 (#537): provisional engineering preparation and the final |
| 17 | //! commit fence (crate::provisional). Compiled only with |
| 18 | //! `--features provisional-prep`; without it this binary holds no tests. |
| 19 | //! |
| 20 | //! The M2 scheduler and the M1/M2 harness store are real (spark-harness, |
| 21 | //! shipped workflow and eval definitions). The World commit is the real |
| 22 | //! approved-proposal path; tests that need it to commit run fully only in a |
| 23 | //! linked build (cfg compose_linked) and check the stub refusal otherwise. |
| 24 | //! Timing lines start with `M3-TIMING` (run with `--nocapture`). |
| 25 | #![cfg(feature = "provisional-prep")] |
| 26 | |
| 27 | #[path = "support/home_guard.rs"] |
| 28 | mod home_guard; |
| 29 | |
| 30 | use aien_omega_compose::hex; |
| 31 | use aien_runtime::approved::{ |
| 32 | ApprovedComposeReport, ApprovedProposal, ApprovedRefusal, ProposerHook, |
| 33 | }; |
| 34 | use aien_runtime::approved_auth::{desk_key_path, AuthorizeBinding, DeskKey}; |
| 35 | use aien_runtime::control::{ControlCommand, ControlResponse, DeskProof}; |
| 36 | use aien_runtime::effects::MintRequest; |
| 37 | use aien_runtime::provisional::{ |
| 38 | classify_approved, classify_authorize, deferred_journal_path, DeliverError, Delivered, |
| 39 | FenceError, FenceKey, PrepAdapter, PrepError, PrepOperation, DEFERRED_CAPACITY, |
| 40 | DEFERRED_MAX_BYTES, |
| 41 | }; |
| 42 | use aien_runtime::{ComposeBridge, ComposeProposer}; |
| 43 | use serde_json::{json, Value}; |
| 44 | use sha2::{Digest, Sha256}; |
| 45 | use spark_harness::completion::CompletionSubmission; |
| 46 | use spark_harness::execution::TaskState; |
| 47 | use spark_harness::readiness::{InterfaceSubmission, OperationClass, ProofClaim, ReadinessLevel}; |
| 48 | use spark_harness::scheduler::{ |
| 49 | Clock, CommitResult, Effects, Event, EventKind, Outcome, ProvisionalConfig, ResourceLimits, |
| 50 | ResourceRequest, SchedError, |
| 51 | }; |
| 52 | use spark_harness::{HarnessEngine, WorkflowState}; |
| 53 | use std::collections::BTreeMap; |
| 54 | use std::path::{Path, PathBuf}; |
| 55 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 56 | use std::sync::{mpsc, Arc}; |
| 57 | use std::time::{Duration, Instant}; |
| 58 | |
| 59 | const COMMIT: &str = "1111111111111111111111111111111111111111"; |
| 60 | const PATH: &str = "NOTES.md"; |
| 61 | const CONTENT: &str = "approved after the producers were final\n"; |
| 62 | const GOAL: &str = "Write NOTES.md: one line about the parser interface"; |
| 63 | |
| 64 | // ---------- harness store and scheduler ---------- |
| 65 | |
| 66 | fn fixed_receipt_clock() -> u64 { |
| 67 | 1_760_000_000 |
| 68 | } |
| 69 | |
| 70 | fn cfg(enabled: bool, max_concurrency: u32) -> ProvisionalConfig { |
| 71 | ProvisionalConfig { |
| 72 | enabled, |
| 73 | queue_capacity: 8, |
| 74 | limits: ResourceLimits { |
| 75 | cpu_slots: 8, |
| 76 | memory_bytes: 1 << 30, |
| 77 | max_concurrency, |
| 78 | }, |
| 79 | lease_ttl: 1_000_000, |
| 80 | dedup_window: 64, |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | fn clock(t: &Arc<AtomicU64>) -> Clock { |
| 85 | let t = Arc::clone(t); |
| 86 | Box::new(move || t.load(Ordering::SeqCst)) |
| 87 | } |
| 88 | |
| 89 | fn copy_definitions(dir: &Path) { |
| 90 | let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("../spark-harness"); |
| 91 | std::fs::create_dir_all(dir.join("schemas")).unwrap(); |
| 92 | for f in ["workflows.json", "evals.json"] { |
| 93 | std::fs::copy(src.join(f), dir.join(f)).unwrap(); |
| 94 | } |
| 95 | for e in std::fs::read_dir(src.join("schemas")).unwrap() { |
| 96 | let e = e.unwrap(); |
| 97 | std::fs::copy(e.path(), dir.join("schemas").join(e.file_name())).unwrap(); |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | fn artifact(task: &str) -> Value { |
| 102 | json!({ |
| 103 | "bug": format!("Parser rejects valid token sequence in {task}"), |
| 104 | "reproduction_steps": ["Run parser test"], |
| 105 | "failure_evidence": "thread panicked at line 42", |
| 106 | "regression_test": "tests::test_parser", |
| 107 | "diff_summary": "Fixed token parser logic", |
| 108 | "retest_evidence": "All tests passing cleanly" |
| 109 | }) |
| 110 | } |
| 111 | |
| 112 | /// One adapter, its harness store, a compose home and a workspace, all in |
| 113 | /// one temp dir: `<tmp>/harness`, `<tmp>/compose`, `<tmp>/ws`. |
| 114 | struct H { |
| 115 | tmp: tempfile::TempDir, |
| 116 | engine: HarnessEngine, |
| 117 | ticks: Arc<AtomicU64>, |
| 118 | adapter: Arc<PrepAdapter>, |
| 119 | n: u64, |
| 120 | } |
| 121 | |
| 122 | impl H { |
| 123 | fn new(c: ProvisionalConfig) -> Self { |
| 124 | Self::build(c, false) |
| 125 | } |
| 126 | |
| 127 | fn journaled(c: ProvisionalConfig) -> Self { |
| 128 | Self::build(c, true) |
| 129 | } |
| 130 | |
| 131 | fn build(c: ProvisionalConfig, journaled: bool) -> Self { |
| 132 | let tmp = tempfile::tempdir().unwrap(); |
| 133 | let hd = tmp.path().join("harness"); |
| 134 | copy_definitions(&hd); |
| 135 | std::fs::create_dir_all(tmp.path().join("ws")).unwrap(); |
| 136 | let mut engine = HarnessEngine::load(&hd).expect("shipped definitions load"); |
| 137 | engine.completion_clock = fixed_receipt_clock; |
| 138 | let ticks = Arc::new(AtomicU64::new(0)); |
| 139 | let adapter = if journaled { |
| 140 | let (a, revoked) = PrepAdapter::open( |
| 141 | c, |
| 142 | &engine.completion_store, |
| 143 | &tmp.path().join("journal.jsonl"), |
| 144 | clock(&ticks), |
| 145 | ) |
| 146 | .unwrap(); |
| 147 | assert!(revoked.is_empty()); |
| 148 | a |
| 149 | } else { |
| 150 | PrepAdapter::new(c, &engine.completion_store, clock(&ticks)).unwrap() |
| 151 | }; |
| 152 | H { |
| 153 | tmp, |
| 154 | engine, |
| 155 | ticks, |
| 156 | adapter: Arc::new(adapter), |
| 157 | n: 0, |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | /// A daemon restart: drop the adapter, replay its journal, audit. |
| 162 | fn restart(&mut self, c: ProvisionalConfig) -> Vec<String> { |
| 163 | let placeholder = |
| 164 | PrepAdapter::new(c.clone(), &self.engine.completion_store, clock(&self.ticks)).unwrap(); |
| 165 | drop(std::mem::replace(&mut self.adapter, Arc::new(placeholder))); |
| 166 | self.ticks.store(0, Ordering::SeqCst); |
| 167 | let (a, revoked) = PrepAdapter::open( |
| 168 | c, |
| 169 | &self.engine.completion_store, |
| 170 | &self.tmp.path().join("journal.jsonl"), |
| 171 | clock(&self.ticks), |
| 172 | ) |
| 173 | .unwrap(); |
| 174 | self.adapter = Arc::new(a); |
| 175 | revoked |
| 176 | } |
| 177 | |
| 178 | fn ws(&self) -> PathBuf { |
| 179 | self.tmp.path().join("ws") |
| 180 | } |
| 181 | |
| 182 | fn deliver(&mut self, kind: EventKind) -> Result<Delivered, DeliverError> { |
| 183 | self.n += 1; |
| 184 | self.ticks.fetch_add(10, Ordering::SeqCst); |
| 185 | let r = self.adapter.deliver(Event { |
| 186 | id: format!("ev-{}", self.n), |
| 187 | kind, |
| 188 | }); |
| 189 | self.adapter.inspect(|s| s.check_invariants()).unwrap(); |
| 190 | r |
| 191 | } |
| 192 | |
| 193 | /// An event no commit holds back: applied, or refused by M2. |
| 194 | fn send(&mut self, kind: EventKind) -> Result<Outcome, SchedError> { |
| 195 | match self.deliver(kind) { |
| 196 | Ok(Delivered::Applied(o)) => Ok(o), |
| 197 | Err(DeliverError::Scheduler(e)) => Err(e), |
| 198 | other => panic!("not applied or refused by M2: {other:?}"), |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | fn ok(&mut self, kind: EventKind) -> Effects { |
| 203 | match self.send(kind.clone()) { |
| 204 | Ok(Outcome::Applied(fx)) => fx, |
| 205 | other => panic!("{kind:?} not applied: {other:?}"), |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | fn gen(&self, task: &str) -> u64 { |
| 210 | self.adapter.generation(task).unwrap() |
| 211 | } |
| 212 | |
| 213 | fn state(&self, task: &str) -> TaskState { |
| 214 | self.adapter.state(task).unwrap() |
| 215 | } |
| 216 | |
| 217 | fn register(&mut self, task: &str, producers: &[&str]) -> Effects { |
| 218 | self.ok(EventKind::RegisterTask { |
| 219 | task: task.into(), |
| 220 | resources: ResourceRequest { |
| 221 | cpu_slots: 1, |
| 222 | memory_bytes: 1 << 20, |
| 223 | }, |
| 224 | producers: producers.iter().map(|p| p.to_string()).collect(), |
| 225 | }) |
| 226 | } |
| 227 | |
| 228 | fn mint_interface(&self, task: &str, version: u32) -> ProofClaim { |
| 229 | self.engine |
| 230 | .publish_interface(&InterfaceSubmission { |
| 231 | task_id: task.into(), |
| 232 | generation: self.gen(task), |
| 233 | source_commit: COMMIT.into(), |
| 234 | interface: json!({ "task": task, "api_version": version }), |
| 235 | }) |
| 236 | .unwrap() |
| 237 | .claim() |
| 238 | } |
| 239 | |
| 240 | fn publish(&mut self, task: &str, version: u32) -> (ProofClaim, Effects) { |
| 241 | let claim = self.mint_interface(task, version); |
| 242 | let generation = self.gen(task); |
| 243 | let fx = self.ok(EventKind::InterfacePublished { |
| 244 | task: task.into(), |
| 245 | generation, |
| 246 | claim: claim.clone(), |
| 247 | }); |
| 248 | (claim, fx) |
| 249 | } |
| 250 | |
| 251 | fn mint_completion(&self, task: &str) -> ProofClaim { |
| 252 | let mut wf = WorkflowState { |
| 253 | id: format!("wf-{task}"), |
| 254 | workflow_type: "engineering_fix".into(), |
| 255 | current_state: "review".into(), |
| 256 | history: Vec::new(), |
| 257 | created_at: "2026-10-15T00:00:00Z".into(), |
| 258 | }; |
| 259 | let rec = self |
| 260 | .engine |
| 261 | .complete_verified_workflow( |
| 262 | &mut wf, |
| 263 | &CompletionSubmission { |
| 264 | task_id: task.into(), |
| 265 | generation: self.gen(task), |
| 266 | source_commit: COMMIT.into(), |
| 267 | artifact: artifact(task), |
| 268 | }, |
| 269 | ) |
| 270 | .unwrap(); |
| 271 | ProofClaim { |
| 272 | receipt_id: rec.receipt_id, |
| 273 | commit: rec.source_commit, |
| 274 | digest: rec.artifact_digest, |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | fn work_done(&mut self, task: &str) { |
| 279 | let generation = self.gen(task); |
| 280 | self.ok(EventKind::WorkDone { |
| 281 | task: task.into(), |
| 282 | generation, |
| 283 | result_digest: format!("result-of-{task}"), |
| 284 | }); |
| 285 | } |
| 286 | |
| 287 | fn finalize(&mut self, task: &str) { |
| 288 | let generation = self.gen(task); |
| 289 | self.ok(EventKind::Finalize { |
| 290 | task: task.into(), |
| 291 | generation, |
| 292 | }); |
| 293 | } |
| 294 | |
| 295 | fn complete(&mut self, task: &str) -> ProofClaim { |
| 296 | let claim = self.mint_completion(task); |
| 297 | let generation = self.gen(task); |
| 298 | self.ok(EventKind::CompletionVerified { |
| 299 | task: task.into(), |
| 300 | generation, |
| 301 | claim: claim.clone(), |
| 302 | }); |
| 303 | claim |
| 304 | } |
| 305 | |
| 306 | /// Work done, finalize, M1 completion: the task is final and committable. |
| 307 | fn finish(&mut self, task: &str) { |
| 308 | self.work_done(task); |
| 309 | self.finalize(task); |
| 310 | self.complete(task); |
| 311 | assert_eq!(self.state(task), TaskState::Committable); |
| 312 | } |
| 313 | |
| 314 | fn prepare( |
| 315 | &self, |
| 316 | task: &str, |
| 317 | ) -> Result<aien_runtime::provisional::PreparationResult, PrepError> { |
| 318 | self.adapter.prepare(task, self.gen(task), GOAL, &self.ws()) |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | // ---------- compose home and approvals ---------- |
| 323 | |
| 324 | fn model_never_called() -> ComposeProposer { |
| 325 | Arc::new(|_: &str, _: Duration| panic!("the model proposer ran on the approved path")) |
| 326 | } |
| 327 | |
| 328 | fn sha(b: &[u8]) -> String { |
| 329 | hex(&Sha256::digest(b)) |
| 330 | } |
| 331 | |
| 332 | fn interplane_sha(path: &str, content: &str) -> String { |
| 333 | let s = format!( |
| 334 | "{{\"content\":{},\"path\":{}}}", |
| 335 | serde_json::to_string(content).unwrap(), |
| 336 | serde_json::to_string(path).unwrap() |
| 337 | ); |
| 338 | sha(s.as_bytes()) |
| 339 | } |
| 340 | |
| 341 | struct Compose { |
| 342 | bridge: Arc<ComposeBridge>, |
| 343 | hook: ProposerHook, |
| 344 | ws: String, |
| 345 | } |
| 346 | |
| 347 | impl Compose { |
| 348 | fn new(h: &H) -> Self { |
| 349 | DeskKey::create(&desk_key_path(&h.tmp.path().join("compose"))).unwrap(); |
| 350 | Self::reopen(h) |
| 351 | } |
| 352 | |
| 353 | /// A fresh bridge on the same compose home and desk key (a daemon restart). |
| 354 | fn reopen(h: &H) -> Self { |
| 355 | let bridge = Arc::new(ComposeBridge::new( |
| 356 | h.tmp.path().join("compose"), |
| 357 | model_never_called(), |
| 358 | "test:model-never-called", |
| 359 | )); |
| 360 | let hook = ProposerHook::new(bridge.clone()); |
| 361 | Compose { |
| 362 | bridge, |
| 363 | hook, |
| 364 | ws: h.ws().display().to_string(), |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | /// An approval sealed with this home's desk key. |
| 369 | fn approval(&self, request: &str) -> ApprovedProposal { |
| 370 | let mut p = ApprovedProposal { |
| 371 | request_id: request.into(), |
| 372 | trace_id: format!("trace-{request}"), |
| 373 | approval_id: format!("appr-{request}"), |
| 374 | approver: "interplane-host".into(), |
| 375 | path: PATH.into(), |
| 376 | content: CONTENT.into(), |
| 377 | approved_proposal_sha256: interplane_sha(PATH, CONTENT), |
| 378 | content_sha256: sha(CONTENT.as_bytes()), |
| 379 | approval_mac: String::new(), |
| 380 | requirements: Some(String::new()), |
| 381 | requirements_mac: String::new(), |
| 382 | requirements_base: None, |
| 383 | }; |
| 384 | DeskKey::load(&desk_key_path(self.bridge.dir())) |
| 385 | .unwrap() |
| 386 | .seal(&mut p, Path::new(&self.ws)); |
| 387 | p |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | type Submit = Result<ApprovedComposeReport, Box<ApprovedRefusal>>; |
| 392 | |
| 393 | /// The canonical path's answer for a valid approval: COMMITTED when linked, |
| 394 | /// the stub refusal otherwise. Returns the report when linked. |
| 395 | fn committed_or_stub(r: Submit) -> Option<ApprovedComposeReport> { |
| 396 | if !aien_omega_compose::LINKED { |
| 397 | let e = r.expect_err("stub build must refuse"); |
| 398 | assert!( |
| 399 | e.refused_by == "REPLAY_REFUSED" || e.name == "ComposeError", |
| 400 | "{e}" |
| 401 | ); |
| 402 | return None; |
| 403 | } |
| 404 | let r = r.unwrap_or_else(|e| panic!("want COMMITTED, got {e}")); |
| 405 | assert_eq!(r.state, "COMMITTED"); |
| 406 | let t = r.task.as_ref().expect("a compose run"); |
| 407 | assert!(t.committed && t.cx_promotion != 0, "{t:?}"); |
| 408 | Some(r) |
| 409 | } |
| 410 | |
| 411 | /// Every file under `dir` with its sha256, for "nothing was written" checks. |
| 412 | fn tree(dir: &Path) -> BTreeMap<PathBuf, String> { |
| 413 | let mut out = BTreeMap::new(); |
| 414 | let mut stack = vec![dir.to_path_buf()]; |
| 415 | while let Some(d) = stack.pop() { |
| 416 | let Ok(rd) = std::fs::read_dir(&d) else { |
| 417 | continue; |
| 418 | }; |
| 419 | for e in rd.flatten() { |
| 420 | let p = e.path(); |
| 421 | if p.is_dir() { |
| 422 | stack.push(p); |
| 423 | } else { |
| 424 | out.insert(p.clone(), sha(&std::fs::read(&p).unwrap_or_default())); |
| 425 | } |
| 426 | } |
| 427 | } |
| 428 | out |
| 429 | } |
| 430 | |
| 431 | /// Classifier for `fenced_for_tests`: the call committed. |
| 432 | fn committed<T>(_: &T) -> CommitResult { |
| 433 | CommitResult::Committed { |
| 434 | detail: "test".into(), |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | fn fence_err<T: std::fmt::Debug>(r: Result<T, FenceError>) -> FenceError { |
| 439 | match r { |
| 440 | Err(e) => e, |
| 441 | Ok(v) => panic!("the fence let a call through: {v:?}"), |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | // ---------- tests ---------- |
| 446 | |
| 447 | #[test] |
| 448 | fn the_one_whitelisted_operation_is_read_only_analysis() { |
| 449 | let op = PrepOperation::ComposePlanPreview; |
| 450 | assert_eq!(op.class(), OperationClass::ReadOnlyAnalysis); |
| 451 | for c in OperationClass::ALL { |
| 452 | if c != OperationClass::ReadOnlyAnalysis { |
| 453 | assert_ne!(op.class(), c); |
| 454 | } |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | struct Timing { |
| 459 | critical_ms: f64, |
| 460 | overlap_ms: f64, |
| 461 | prep_ms: f64, |
| 462 | prep_started_before_producer_final: bool, |
| 463 | } |
| 464 | |
| 465 | const PRODUCER_WORK: Duration = Duration::from_millis(60); |
| 466 | const PREP_LOAD: Duration = Duration::from_millis(40); |
| 467 | |
| 468 | fn ms(d: Duration) -> f64 { |
| 469 | d.as_secs_f64() * 1000.0 |
| 470 | } |
| 471 | |
| 472 | /// Producer A (60 ms of simulated work on another thread) and consumer B, |
| 473 | /// whose preparation is the real whitelisted operation plus 40 ms of |
| 474 | /// simulated preparation load (the test hook, outside the adapter mutex). |
| 475 | /// Ends with B's fenced World commit through the approved path. |
| 476 | fn two_stage(enabled: bool) -> Timing { |
| 477 | let mut h = H::new(cfg(enabled, 4)); |
| 478 | let c = Compose::new(&h); |
| 479 | h.adapter |
| 480 | .set_prep_hook(Some(Arc::new(|_: &str| std::thread::sleep(PREP_LOAD)))); |
| 481 | h.register("a", &[]); |
| 482 | h.register("b", &["a"]); |
| 483 | h.publish("a", 1); |
| 484 | let t0 = Instant::now(); |
| 485 | let producer = std::thread::spawn(move || { |
| 486 | std::thread::sleep(PRODUCER_WORK); |
| 487 | Instant::now() |
| 488 | }); |
| 489 | let mut prep = None; |
| 490 | if enabled { |
| 491 | assert_eq!(h.state("b"), TaskState::Provisional); |
| 492 | let s = Instant::now(); |
| 493 | let r = h.prepare("b").expect("early preparation"); |
| 494 | assert!(r.is_provisional(), "bound to an interface, not a final"); |
| 495 | prep = Some((s, Instant::now())); |
| 496 | } else { |
| 497 | assert_eq!(h.state("b"), TaskState::Blocked); |
| 498 | assert!(matches!( |
| 499 | h.prepare("b"), |
| 500 | Err(PrepError::Scheduler(SchedError::WrongState { .. })) |
| 501 | )); |
| 502 | } |
| 503 | let producer_end = producer.join().unwrap(); |
| 504 | h.finish("a"); |
| 505 | if !enabled { |
| 506 | assert_eq!(h.state("b"), TaskState::Provisional); |
| 507 | let s = Instant::now(); |
| 508 | let r = h.prepare("b").expect("sequential preparation"); |
| 509 | assert!(!r.is_provisional()); |
| 510 | prep = Some((s, Instant::now())); |
| 511 | } |
| 512 | h.finish("b"); |
| 513 | let _home = home_guard::home_slot(); |
| 514 | let g = h.gen("b"); |
| 515 | let out = h |
| 516 | .adapter |
| 517 | .submit_approved("b", g, &c.hook, &c.approval("req-two"), &c.ws) |
| 518 | .expect("fence passes"); |
| 519 | committed_or_stub(out.outcome); |
| 520 | let end = Instant::now(); |
| 521 | let (ps, pe) = prep.unwrap(); |
| 522 | let overlap = pe.min(producer_end).saturating_duration_since(ps.max(t0)); |
| 523 | Timing { |
| 524 | critical_ms: ms(end - t0), |
| 525 | overlap_ms: ms(overlap), |
| 526 | prep_ms: ms(pe - ps), |
| 527 | prep_started_before_producer_final: ps < producer_end, |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | #[test] |
| 532 | fn two_stage_overlap_measured_against_the_sequential_fallback() { |
| 533 | let on = two_stage(true); |
| 534 | let off = two_stage(false); |
| 535 | for (name, t) in [("enabled", &on), ("disabled", &off)] { |
| 536 | eprintln!( |
| 537 | "M3-TIMING two_stage {name}: critical_path_ms={:.2} prep_ms={:.2} overlap_ms={:.2} producer_work_ms={} prep_load_ms={} linked={}", |
| 538 | t.critical_ms, |
| 539 | t.prep_ms, |
| 540 | t.overlap_ms, |
| 541 | PRODUCER_WORK.as_millis(), |
| 542 | PREP_LOAD.as_millis(), |
| 543 | aien_omega_compose::LINKED |
| 544 | ); |
| 545 | } |
| 546 | assert!(on.prep_started_before_producer_final && on.overlap_ms > 0.0); |
| 547 | assert!(!off.prep_started_before_producer_final); |
| 548 | assert_eq!(off.overlap_ms, 0.0, "disabled means no early start"); |
| 549 | } |
| 550 | |
| 551 | #[test] |
| 552 | fn three_stage_chain_prepares_two_consumers_while_the_root_runs() { |
| 553 | let _home = home_guard::home_slot(); |
| 554 | let mut h = H::new(cfg(true, 4)); |
| 555 | let c = Compose::new(&h); |
| 556 | h.register("a", &[]); |
| 557 | h.register("b", &["a"]); |
| 558 | h.register("c", &["b"]); |
| 559 | let (ia, _) = h.publish("a", 1); |
| 560 | assert_eq!(h.state("b"), TaskState::Provisional); |
| 561 | let (ib, _) = h.publish("b", 1); |
| 562 | assert_eq!(h.state("c"), TaskState::Provisional); |
| 563 | let t0 = Instant::now(); |
| 564 | let rb = h.prepare("b").unwrap(); |
| 565 | let rc = h.prepare("c").unwrap(); |
| 566 | eprintln!( |
| 567 | "M3-TIMING three_stage: two preparations while the root is not final took {:.3} ms", |
| 568 | ms(t0.elapsed()) |
| 569 | ); |
| 570 | assert_eq!(h.state("a"), TaskState::Provisional, "root still running"); |
| 571 | // Each result is bound to its producer's interface receipt. |
| 572 | let b0 = &rb.bindings()[0]; |
| 573 | assert_eq!( |
| 574 | (b0.producer_task.as_str(), b0.receipt_id.as_str()), |
| 575 | ("a", ia.receipt_id.as_str()) |
| 576 | ); |
| 577 | assert_eq!( |
| 578 | (b0.source_commit.as_str(), b0.artifact_digest.as_str()), |
| 579 | (COMMIT, ia.digest.as_str()) |
| 580 | ); |
| 581 | assert_eq!(b0.producer_generation, 1); |
| 582 | assert_eq!(b0.level, ReadinessLevel::InterfaceVerified); |
| 583 | assert_eq!(rc.bindings()[0].receipt_id, ib.receipt_id); |
| 584 | assert_eq!(rc.operation(), PrepOperation::ComposePlanPreview); |
| 585 | assert_eq!(rc.class(), OperationClass::ReadOnlyAnalysis); |
| 586 | assert_eq!(rc.plan_sha256().len(), 64); |
| 587 | // The fence refuses C until the whole chain is final. |
| 588 | let gc = h.gen("c"); |
| 589 | let p = c.approval("req-three"); |
| 590 | assert!(matches!( |
| 591 | fence_err(h.adapter.submit_approved("c", gc, &c.hook, &p, &c.ws)), |
| 592 | FenceError::NotCommittable { .. } |
| 593 | )); |
| 594 | h.finish("a"); |
| 595 | h.finish("b"); |
| 596 | h.work_done("c"); |
| 597 | h.finalize("c"); |
| 598 | // Committable but without its own M1 completion: still refused. |
| 599 | assert!(matches!( |
| 600 | fence_err(h.adapter.submit_approved("c", gc, &c.hook, &p, &c.ws)), |
| 601 | FenceError::NoCompletion(_) |
| 602 | )); |
| 603 | h.complete("c"); |
| 604 | let out = h |
| 605 | .adapter |
| 606 | .submit_approved("c", gc, &c.hook, &p, &c.ws) |
| 607 | .expect("fence passes once A, B and C are final"); |
| 608 | assert_eq!(out.proof.producers.len(), 1); |
| 609 | assert_eq!(out.proof.producers[0].level, ReadinessLevel::FinalVerified); |
| 610 | assert_eq!(out.proof.completion.level, ReadinessLevel::FinalVerified); |
| 611 | committed_or_stub(out.outcome); |
| 612 | } |
| 613 | |
| 614 | #[test] |
| 615 | fn failed_producer_discards_the_dependent_result() { |
| 616 | let mut h = H::new(cfg(true, 4)); |
| 617 | h.register("a", &[]); |
| 618 | h.register("b", &["a"]); |
| 619 | h.publish("a", 1); |
| 620 | h.prepare("b").unwrap(); |
| 621 | assert!(h.adapter.prepared("b").is_some()); |
| 622 | h.ok(EventKind::ProducerFailed { |
| 623 | task: "a".into(), |
| 624 | generation: 1, |
| 625 | reason: "tests failed".into(), |
| 626 | }); |
| 627 | assert_eq!((h.state("b"), h.gen("b")), (TaskState::Blocked, 2)); |
| 628 | assert!(h.adapter.prepared("b").is_none(), "result discarded"); |
| 629 | assert!(matches!( |
| 630 | h.adapter.prepare("b", 1, GOAL, &h.ws()), |
| 631 | Err(PrepError::StaleGeneration { .. }) |
| 632 | )); |
| 633 | assert!(matches!( |
| 634 | fence_err(h.adapter.fenced_for_tests("b", 1, |_| (), committed)), |
| 635 | FenceError::StaleGeneration { .. } |
| 636 | )); |
| 637 | } |
| 638 | |
| 639 | #[test] |
| 640 | fn completed_producer_upgrades_the_binding_to_final() { |
| 641 | let mut h = H::new(cfg(true, 4)); |
| 642 | h.register("a", &[]); |
| 643 | h.register("b", &["a"]); |
| 644 | h.publish("a", 1); |
| 645 | assert!(h.prepare("b").unwrap().is_provisional()); |
| 646 | h.finish("a"); |
| 647 | let r = h.prepare("b").unwrap(); |
| 648 | assert!(!r.is_provisional()); |
| 649 | assert_eq!(r.bindings()[0].level, ReadinessLevel::FinalVerified); |
| 650 | } |
| 651 | |
| 652 | #[test] |
| 653 | fn changed_interface_revokes_and_rebinds_to_the_new_receipt() { |
| 654 | let mut h = H::new(cfg(true, 4)); |
| 655 | h.register("a", &[]); |
| 656 | h.register("b", &["a"]); |
| 657 | let (v1, _) = h.publish("a", 1); |
| 658 | assert_eq!( |
| 659 | h.prepare("b").unwrap().bindings()[0].receipt_id, |
| 660 | v1.receipt_id |
| 661 | ); |
| 662 | let (v2, fx) = h.publish("a", 2); |
| 663 | assert_ne!(v1.receipt_id, v2.receipt_id); |
| 664 | assert!(fx.revoked.contains(&"b".to_string())); |
| 665 | assert!(h.adapter.prepared("b").is_none()); |
| 666 | assert_eq!((h.state("b"), h.gen("b")), (TaskState::Provisional, 2)); |
| 667 | let r = h.prepare("b").unwrap(); |
| 668 | assert_eq!( |
| 669 | (r.generation(), r.bindings()[0].receipt_id.as_str()), |
| 670 | (2, v2.receipt_id.as_str()) |
| 671 | ); |
| 672 | } |
| 673 | |
| 674 | #[test] |
| 675 | fn new_producer_generation_makes_old_generations_stale() { |
| 676 | let mut h = H::new(cfg(true, 4)); |
| 677 | h.register("a", &[]); |
| 678 | h.register("b", &["a"]); |
| 679 | h.publish("a", 1); |
| 680 | h.prepare("b").unwrap(); |
| 681 | h.ok(EventKind::NewGeneration { |
| 682 | task: "a".into(), |
| 683 | generation: 2, |
| 684 | }); |
| 685 | assert!(h.adapter.prepared("b").is_none()); |
| 686 | assert_eq!(h.gen("b"), 2); |
| 687 | for g in [1, 3] { |
| 688 | assert!(matches!( |
| 689 | h.adapter.prepare("b", g, GOAL, &h.ws()), |
| 690 | Err(PrepError::StaleGeneration { .. }) |
| 691 | )); |
| 692 | } |
| 693 | } |
| 694 | |
| 695 | #[test] |
| 696 | fn cancellation_discards_results_and_refuses_preparation() { |
| 697 | let mut h = H::new(cfg(true, 4)); |
| 698 | h.register("a", &[]); |
| 699 | h.register("b", &["a"]); |
| 700 | h.publish("a", 1); |
| 701 | h.prepare("b").unwrap(); |
| 702 | h.ok(EventKind::Cancel { |
| 703 | task: "a".into(), |
| 704 | generation: 1, |
| 705 | }); |
| 706 | assert_eq!(h.state("b"), TaskState::Aborted); |
| 707 | assert!(h.adapter.prepared("b").is_none()); |
| 708 | assert!(matches!( |
| 709 | h.prepare("b"), |
| 710 | Err(PrepError::Scheduler(SchedError::WrongState { .. })) |
| 711 | )); |
| 712 | } |
| 713 | |
| 714 | #[test] |
| 715 | fn duplicate_event_is_a_noop_and_keeps_the_result() { |
| 716 | let mut h = H::new(cfg(true, 4)); |
| 717 | h.register("a", &[]); |
| 718 | h.register("b", &["a"]); |
| 719 | let claim = h.mint_interface("a", 1); |
| 720 | let ev = Event { |
| 721 | id: "publish-a".into(), |
| 722 | kind: EventKind::InterfacePublished { |
| 723 | task: "a".into(), |
| 724 | generation: 1, |
| 725 | claim, |
| 726 | }, |
| 727 | }; |
| 728 | assert!(matches!( |
| 729 | h.adapter.deliver(ev.clone()), |
| 730 | Ok(Delivered::Applied(Outcome::Applied(_))) |
| 731 | )); |
| 732 | let r = h.prepare("b").unwrap(); |
| 733 | assert_eq!( |
| 734 | h.adapter.deliver(ev).unwrap(), |
| 735 | Delivered::Applied(Outcome::Duplicate) |
| 736 | ); |
| 737 | assert_eq!(h.adapter.prepared("b"), Some(r)); |
| 738 | assert_eq!(h.gen("b"), 1); |
| 739 | } |
| 740 | |
| 741 | #[test] |
| 742 | fn invalid_receipts_are_refused_by_the_event_gate_and_the_fence() { |
| 743 | let mut h = H::new(cfg(true, 4)); |
| 744 | h.register("a", &[]); |
| 745 | h.register("b", &["a"]); |
| 746 | // A claim naming no stored receipt never reaches the scheduler. |
| 747 | let forged = ProofClaim { |
| 748 | receipt_id: "ab".repeat(32), |
| 749 | commit: COMMIT.into(), |
| 750 | digest: "cd".repeat(32), |
| 751 | }; |
| 752 | assert!(matches!( |
| 753 | h.send(EventKind::InterfacePublished { |
| 754 | task: "a".into(), |
| 755 | generation: 1, |
| 756 | claim: forged, |
| 757 | }), |
| 758 | Err(SchedError::Proof { .. }) |
| 759 | )); |
| 760 | assert_eq!(h.state("b"), TaskState::Blocked); |
| 761 | h.publish("a", 1); |
| 762 | h.finish("a"); |
| 763 | h.finish("b"); |
| 764 | // Tamper with B's own M1 receipt in the store after it was accepted. |
| 765 | let rid = h |
| 766 | .adapter |
| 767 | .inspect(|s| s.task("b").unwrap().completion.clone().unwrap().receipt_id); |
| 768 | let file = h |
| 769 | .engine |
| 770 | .completion_store |
| 771 | .join(aien_proof::evidence::RECEIPT_DIR) |
| 772 | .join(format!("{rid}.json")); |
| 773 | let original = std::fs::read(&file).unwrap(); |
| 774 | let text = String::from_utf8(original.clone()).unwrap(); |
| 775 | std::fs::write(&file, text.replacen("spark-harness", "spark-harnesz", 1)).unwrap(); |
| 776 | let mut ran = false; |
| 777 | assert!(matches!( |
| 778 | fence_err( |
| 779 | h.adapter |
| 780 | .fenced_for_tests("b", 1, |_| ran = true, committed) |
| 781 | ), |
| 782 | FenceError::CompletionInvalid { .. } |
| 783 | )); |
| 784 | assert!(!ran); |
| 785 | std::fs::write(&file, &original).unwrap(); |
| 786 | // Tamper with the producer's receipt instead: M2 may_finalize refuses. |
| 787 | let ra = h |
| 788 | .adapter |
| 789 | .inspect(|s| s.task("a").unwrap().completion.clone().unwrap().receipt_id); |
| 790 | let fa = file.with_file_name(format!("{ra}.json")); |
| 791 | let oa = std::fs::read(&fa).unwrap(); |
| 792 | std::fs::write( |
| 793 | &fa, |
| 794 | String::from_utf8(oa.clone()) |
| 795 | .unwrap() |
| 796 | .replacen("spark-harness", "spark-harnesz", 1), |
| 797 | ) |
| 798 | .unwrap(); |
| 799 | assert!(matches!( |
| 800 | fence_err( |
| 801 | h.adapter |
| 802 | .fenced_for_tests("b", 1, |_| ran = true, committed) |
| 803 | ), |
| 804 | FenceError::Scheduler(SchedError::Proof { .. }) |
| 805 | )); |
| 806 | assert!(!ran); |
| 807 | std::fs::write(&fa, &oa).unwrap(); |
| 808 | h.adapter |
| 809 | .fenced_for_tests("b", 1, |_| ran = true, committed) |
| 810 | .unwrap(); |
| 811 | assert!(ran); |
| 812 | } |
| 813 | |
| 814 | #[test] |
| 815 | fn early_fence_alone_commits_nothing_and_writes_nothing() { |
| 816 | let _home = home_guard::home_slot(); |
| 817 | let mut h = H::new(cfg(true, 4)); |
| 818 | let c = Compose::new(&h); |
| 819 | let mut ws_file = std::fs::File::create(h.ws().join("parser.md")).unwrap(); |
| 820 | std::io::Write::write_all(&mut ws_file, b"# Parser\n").unwrap(); |
| 821 | h.register("a", &[]); |
| 822 | h.register("b", &["a"]); |
| 823 | h.publish("a", 1); |
| 824 | let p = c.approval("req-early"); |
| 825 | let compose_dir = c.bridge.dir().to_path_buf(); |
| 826 | let before = (tree(&h.ws()), tree(&compose_dir)); |
| 827 | // The early gate passes and preparation runs ... |
| 828 | let r = h.prepare("b").unwrap(); |
| 829 | assert!(r.is_provisional()); |
| 830 | // ... but no commit or grant path is reachable from it. |
| 831 | let g = h.gen("b"); |
| 832 | { |
| 833 | assert!(matches!( |
| 834 | fence_err(h.adapter.submit_approved("b", g, &c.hook, &p, &c.ws)), |
| 835 | FenceError::NotCommittable { |
| 836 | state: TaskState::Provisional, |
| 837 | .. |
| 838 | } |
| 839 | )); |
| 840 | let req = MintRequest { |
| 841 | cx_promotion: 1, |
| 842 | proposal_sha256: sha(b"x"), |
| 843 | workspace: c.ws.clone(), |
| 844 | approver: "drake".into(), |
| 845 | constraints: vec![], |
| 846 | }; |
| 847 | assert!(matches!( |
| 848 | fence_err(h.adapter.authorize("b", g, &c.bridge, &req, None, None)), |
| 849 | FenceError::NotCommittable { |
| 850 | state: TaskState::Provisional, |
| 851 | .. |
| 852 | } |
| 853 | )); |
| 854 | } |
| 855 | h.work_done("b"); |
| 856 | assert!(matches!( |
| 857 | fence_err( |
| 858 | h.adapter |
| 859 | .submit_approved("b", h.gen("b"), &c.hook, &p, &c.ws) |
| 860 | ), |
| 861 | FenceError::NotCommittable { |
| 862 | state: TaskState::AwaitingFinalProof, |
| 863 | .. |
| 864 | } |
| 865 | )); |
| 866 | assert_eq!( |
| 867 | (tree(&h.ws()), tree(&compose_dir)), |
| 868 | before, |
| 869 | "preparation and refused fences wrote nothing" |
| 870 | ); |
| 871 | assert!(!h.ws().join(PATH).exists()); |
| 872 | // The same approval commits once the chain is final: the fence refused it. |
| 873 | h.finish("a"); |
| 874 | h.finalize("b"); |
| 875 | h.complete("b"); |
| 876 | let out = h |
| 877 | .adapter |
| 878 | .submit_approved("b", h.gen("b"), &c.hook, &p, &c.ws) |
| 879 | .unwrap(); |
| 880 | committed_or_stub(out.outcome); |
| 881 | assert!( |
| 882 | !h.ws().join(PATH).exists(), |
| 883 | "a World commit is not an effect" |
| 884 | ); |
| 885 | } |
| 886 | |
| 887 | #[test] |
| 888 | fn unauthorized_effects_are_still_refused_by_the_canonical_path() { |
| 889 | let _home = home_guard::home_slot(); |
| 890 | let mut h = H::new(cfg(true, 4)); |
| 891 | let c = Compose::new(&h); |
| 892 | h.register("a", &[]); |
| 893 | h.register("b", &["a"]); |
| 894 | h.publish("a", 1); |
| 895 | h.finish("a"); |
| 896 | h.finish("b"); |
| 897 | // The fence passes; the desk MAC does not. |
| 898 | let mut p = c.approval("req-forged"); |
| 899 | p.approver = "drake".into(); |
| 900 | let out = h |
| 901 | .adapter |
| 902 | .submit_approved("b", 1, &c.hook, &p, &c.ws) |
| 903 | .expect("fence passes"); |
| 904 | let e = out.outcome.expect_err("unauthenticated approval"); |
| 905 | assert_eq!( |
| 906 | (e.refused_by.as_str(), e.name.as_str()), |
| 907 | ("PROPOSAL_REFUSED", "Unauthenticated") |
| 908 | ); |
| 909 | // Refused before any replay claim: nothing durable, the task aborts. |
| 910 | assert!(matches!(out.result, CommitResult::Failed { .. })); |
| 911 | assert_eq!(h.state("b"), TaskState::Aborted); |
| 912 | assert!(!h.ws().join(PATH).exists()); |
| 913 | // ComposeAuthorize through the fence, no desk proof and no compose |
| 914 | // commit: refused by the existing authorize rules. |
| 915 | h.register("d", &["a"]); |
| 916 | h.finish("d"); |
| 917 | let req = MintRequest { |
| 918 | cx_promotion: 1, |
| 919 | proposal_sha256: sha(b"never committed"), |
| 920 | workspace: c.ws.clone(), |
| 921 | approver: "drake".into(), |
| 922 | constraints: vec![], |
| 923 | }; |
| 924 | let out = h |
| 925 | .adapter |
| 926 | .authorize("d", 1, &c.bridge, &req, None, None) |
| 927 | .expect("fence passes"); |
| 928 | match out.outcome { |
| 929 | ControlResponse::Error(e) => { |
| 930 | if aien_omega_compose::LINKED { |
| 931 | assert!(e.contains("DeskMacRequired"), "{e}"); |
| 932 | } |
| 933 | } |
| 934 | other => panic!("authorize must refuse: {other:?}"), |
| 935 | } |
| 936 | } |
| 937 | |
| 938 | #[test] |
| 939 | fn duplicate_commit_is_refused_and_a_restart_does_not_run_it_again() { |
| 940 | let _home = home_guard::home_slot(); |
| 941 | let c0 = cfg(true, 4); |
| 942 | let mut h = H::journaled(c0.clone()); |
| 943 | let c = Compose::new(&h); |
| 944 | h.register("a", &[]); |
| 945 | h.register("b", &["a"]); |
| 946 | h.publish("a", 1); |
| 947 | h.prepare("b").unwrap(); |
| 948 | h.finish("a"); |
| 949 | h.finish("b"); |
| 950 | let p = c.approval("req-dup"); |
| 951 | let first = h |
| 952 | .adapter |
| 953 | .submit_approved("b", 1, &c.hook, &p, &c.ws) |
| 954 | .unwrap(); |
| 955 | // The stub refuses the replay claim itself (no claim was made, nothing |
| 956 | // ran): recorded as failed, the task aborts. |
| 957 | let want = if aien_omega_compose::LINKED { |
| 958 | assert!(matches!(first.result, CommitResult::Committed { .. })); |
| 959 | TaskState::Committed |
| 960 | } else { |
| 961 | match &first.result { |
| 962 | CommitResult::Failed { reason } => assert!( |
| 963 | reason.starts_with("REPLAY_REFUSED Journal: ") |
| 964 | && reason.ends_with("is not linked (stub build)"), |
| 965 | "{reason}" |
| 966 | ), |
| 967 | other => panic!("want Failed, got {other:?}"), |
| 968 | } |
| 969 | TaskState::Aborted |
| 970 | }; |
| 971 | assert!(first.record_error.is_none()); |
| 972 | let report = committed_or_stub(first.outcome); |
| 973 | assert_eq!(h.state("b"), want); |
| 974 | // Same process, same task generation: refused before the hook runs. |
| 975 | assert!(matches!( |
| 976 | fence_err(h.adapter.submit_approved("b", 1, &c.hook, &p, &c.ws)), |
| 977 | FenceError::AlreadySubmitted { .. } |
| 978 | )); |
| 979 | // Restart: the journal replays the outcome, the audit passes, no result |
| 980 | // survives. |
| 981 | let revoked = h.restart(c0); |
| 982 | c.bridge.close(); |
| 983 | drop(c); |
| 984 | let c = Compose::reopen(&h); |
| 985 | assert!(revoked.is_empty(), "{revoked:?}"); |
| 986 | assert_eq!(h.state("b"), want); |
| 987 | assert!(h.adapter.prepared("b").is_none()); |
| 988 | // The new process has no in-memory record of the call, but the journaled |
| 989 | // outcome refuses a second run before the hook. |
| 990 | match fence_err(h.adapter.submit_approved("b", 1, &c.hook, &p, &c.ws)) { |
| 991 | FenceError::NotCommittable { state, .. } => assert_eq!(state, want), |
| 992 | other => panic!("want NotCommittable, got {other}"), |
| 993 | } |
| 994 | // Under the fence, the durable replay ledger still answers an exact retry |
| 995 | // without a second compose run. |
| 996 | let again = c.hook.submit(&p, &c.ws); |
| 997 | if let Some(first) = report { |
| 998 | let r = again.expect("an exact retry gets the original result"); |
| 999 | assert_eq!(r.state, "ALREADY_COMMITTED"); |
| 1000 | assert!(r.task.is_none(), "nothing ran again"); |
| 1001 | assert_eq!(r.replay_claim, first.replay_claim); |
| 1002 | assert_eq!(r.grant_links, first.grant_links); |
| 1003 | } else { |
| 1004 | let e = again.expect_err("stub build must refuse the retry"); |
| 1005 | assert_eq!( |
| 1006 | (e.refused_by.as_str(), e.name.as_str(), e.replay_claim), |
| 1007 | ("REPLAY_REFUSED", "Journal", None), |
| 1008 | "{e}" |
| 1009 | ); |
| 1010 | } |
| 1011 | } |
| 1012 | |
| 1013 | #[test] |
| 1014 | fn restart_with_a_provisional_task_drops_the_result_and_prepares_again() { |
| 1015 | let c0 = cfg(true, 4); |
| 1016 | let mut h = H::journaled(c0.clone()); |
| 1017 | h.register("a", &[]); |
| 1018 | h.register("b", &["a"]); |
| 1019 | h.publish("a", 1); |
| 1020 | let r = h.prepare("b").unwrap(); |
| 1021 | let revoked = h.restart(c0); |
| 1022 | assert!(revoked.is_empty()); |
| 1023 | assert_eq!(h.state("b"), TaskState::Provisional); |
| 1024 | assert!( |
| 1025 | h.adapter.prepared("b").is_none(), |
| 1026 | "results are never journaled" |
| 1027 | ); |
| 1028 | let again = h.prepare("b").unwrap(); |
| 1029 | assert_eq!(again.plan_sha256(), r.plan_sha256()); |
| 1030 | // A producer receipt removed from the store while the daemon was down: |
| 1031 | // the audit revokes the consumer at replay. |
| 1032 | let c1 = cfg(true, 4); |
| 1033 | let rid = h |
| 1034 | .adapter |
| 1035 | .inspect(|s| s.task("a").unwrap().interface.clone().unwrap().receipt_id); |
| 1036 | std::fs::remove_file( |
| 1037 | h.engine |
| 1038 | .completion_store |
| 1039 | .join(aien_proof::evidence::RECEIPT_DIR) |
| 1040 | .join(format!("{rid}.json")), |
| 1041 | ) |
| 1042 | .unwrap(); |
| 1043 | let revoked = h.restart(c1); |
| 1044 | assert!(revoked.contains(&"a".to_string()), "{revoked:?}"); |
| 1045 | assert_eq!(h.state("b"), TaskState::Blocked); |
| 1046 | } |
| 1047 | |
| 1048 | /// M6 (#538 task 1): a task's own M1 receipt that is malformed (not a |
| 1049 | /// receipt at all) or deleted after M2 accepted it is refused at the final |
| 1050 | /// fence, and the effect never runs. The tampered case is covered by |
| 1051 | /// `invalid_receipts_are_refused_by_the_event_gate_and_the_fence`. |
| 1052 | #[test] |
| 1053 | fn a_malformed_or_missing_own_receipt_is_refused_at_the_fence() { |
| 1054 | let mut h = H::new(cfg(true, 4)); |
| 1055 | h.register("a", &[]); |
| 1056 | h.register("b", &["a"]); |
| 1057 | h.publish("a", 1); |
| 1058 | h.finish("a"); |
| 1059 | h.finish("b"); |
| 1060 | let rid = h |
| 1061 | .adapter |
| 1062 | .inspect(|s| s.task("b").unwrap().completion.clone().unwrap().receipt_id); |
| 1063 | let file = h |
| 1064 | .engine |
| 1065 | .completion_store |
| 1066 | .join(aien_proof::evidence::RECEIPT_DIR) |
| 1067 | .join(format!("{rid}.json")); |
| 1068 | let original = std::fs::read(&file).unwrap(); |
| 1069 | let mut ran = false; |
| 1070 | for (case, bytes) in [ |
| 1071 | ("truncated", Some(original[..original.len() / 2].to_vec())), |
| 1072 | ("not json", Some(b"\x00\xffnot a receipt".to_vec())), |
| 1073 | ("empty", Some(Vec::new())), |
| 1074 | ("deleted", None), |
| 1075 | ] { |
| 1076 | match bytes { |
| 1077 | Some(b) => std::fs::write(&file, b).unwrap(), |
| 1078 | None => std::fs::remove_file(&file).unwrap(), |
| 1079 | } |
| 1080 | let e = fence_err( |
| 1081 | h.adapter |
| 1082 | .fenced_for_tests("b", 1, |_| ran = true, committed), |
| 1083 | ); |
| 1084 | assert!( |
| 1085 | matches!(e, FenceError::CompletionInvalid { .. }), |
| 1086 | "{case}: {e:?}" |
| 1087 | ); |
| 1088 | assert!(!ran, "{case}: the effect ran"); |
| 1089 | assert_eq!(h.state("b"), TaskState::Committable, "{case}"); |
| 1090 | } |
| 1091 | std::fs::write(&file, &original).unwrap(); |
| 1092 | h.adapter |
| 1093 | .fenced_for_tests("b", 1, |_| ran = true, committed) |
| 1094 | .unwrap(); |
| 1095 | assert!(ran); |
| 1096 | assert_eq!(h.state("b"), TaskState::Committed); |
| 1097 | } |
| 1098 | |
| 1099 | /// M6 (#538 task 1): a restart while a task is unfinished never treats it as |
| 1100 | /// committed. Provisional or work-done tasks replay short of `Committable` |
| 1101 | /// and the fence refuses them (`NotCommittable`). A finalized task whose M1 |
| 1102 | /// completion was minted but never delivered to M2 replays without a |
| 1103 | /// completion (M2 reaches `Committable` at `Finalize`, see |
| 1104 | /// spark_harness::scheduler), so the fence refuses it (`NoCompletion`). |
| 1105 | /// Nothing runs until the real completion is delivered after the restart. |
| 1106 | #[test] |
| 1107 | fn a_restart_with_an_unfinished_task_is_never_treated_as_committed() { |
| 1108 | let c = cfg(true, 4); |
| 1109 | let mut h = H::journaled(c.clone()); |
| 1110 | h.register("a", &[]); |
| 1111 | h.register("b", &["a"]); |
| 1112 | h.register("d", &["a"]); |
| 1113 | h.publish("a", 1); |
| 1114 | // b: provisional work done while its producer is not final. |
| 1115 | h.work_done("b"); |
| 1116 | // d: provisional, nothing done. |
| 1117 | let mut ran = false; |
| 1118 | let not_final = |s: TaskState| { |
| 1119 | !matches!( |
| 1120 | s, |
| 1121 | TaskState::Committable | TaskState::Committing | TaskState::Committed |
| 1122 | ) |
| 1123 | }; |
| 1124 | let refused = |h: &H, t: &str, ran: &mut bool| { |
| 1125 | let e = fence_err( |
| 1126 | h.adapter |
| 1127 | .fenced_for_tests(t, h.gen(t), |_| *ran = true, committed), |
| 1128 | ); |
| 1129 | assert!(matches!(e, FenceError::NotCommittable { .. }), "{t}: {e:?}"); |
| 1130 | }; |
| 1131 | h.restart(c.clone()); |
| 1132 | for t in ["b", "d"] { |
| 1133 | assert!(not_final(h.state(t)), "{t}: {:?}", h.state(t)); |
| 1134 | refused(&h, t, &mut ran); |
| 1135 | } |
| 1136 | // a becomes final; b finalizes and its completion is minted in M1, but the |
| 1137 | // daemon goes down before CompletionVerified reaches M2. |
| 1138 | h.finish("a"); |
| 1139 | h.finalize("b"); |
| 1140 | let minted = h.mint_completion("b"); |
| 1141 | h.restart(c.clone()); |
| 1142 | assert_eq!(h.state("b"), TaskState::Committable); |
| 1143 | assert!( |
| 1144 | h.adapter |
| 1145 | .inspect(|s| s.task("b").unwrap().completion.clone()) |
| 1146 | .is_none(), |
| 1147 | "a receipt M2 never accepted is not a completion" |
| 1148 | ); |
| 1149 | let e = fence_err( |
| 1150 | h.adapter |
| 1151 | .fenced_for_tests("b", h.gen("b"), |_| ran = true, committed), |
| 1152 | ); |
| 1153 | assert!( |
| 1154 | matches!(e, FenceError::NoCompletion(ref t) if t == "b"), |
| 1155 | "{e:?}" |
| 1156 | ); |
| 1157 | assert!(!ran, "an unfinished task ran its effect"); |
| 1158 | assert_eq!(h.state("b"), TaskState::Committable); |
| 1159 | // Only the real completion, delivered after the restart, makes it final. |
| 1160 | let generation = h.gen("b"); |
| 1161 | h.ok(EventKind::CompletionVerified { |
| 1162 | task: "b".into(), |
| 1163 | generation, |
| 1164 | claim: minted, |
| 1165 | }); |
| 1166 | assert_eq!(h.state("b"), TaskState::Committable); |
| 1167 | h.adapter |
| 1168 | .fenced_for_tests("b", generation, |_| ran = true, committed) |
| 1169 | .unwrap(); |
| 1170 | assert!(ran); |
| 1171 | assert_eq!(h.state("b"), TaskState::Committed); |
| 1172 | assert!(not_final(h.state("d"))); |
| 1173 | } |
| 1174 | |
| 1175 | #[test] |
| 1176 | fn revocation_during_preparation_discards_the_result() { |
| 1177 | let mut h = H::new(cfg(true, 4)); |
| 1178 | h.register("a", &[]); |
| 1179 | h.register("b", &["a"]); |
| 1180 | h.publish("a", 1); |
| 1181 | let adapter = Arc::clone(&h.adapter); |
| 1182 | h.adapter.set_prep_hook(Some(Arc::new(move |_: &str| { |
| 1183 | adapter |
| 1184 | .deliver(Event { |
| 1185 | id: "fail-a-mid-prep".into(), |
| 1186 | kind: EventKind::ProducerFailed { |
| 1187 | task: "a".into(), |
| 1188 | generation: 1, |
| 1189 | reason: "failed while b prepared".into(), |
| 1190 | }, |
| 1191 | }) |
| 1192 | .unwrap(); |
| 1193 | }))); |
| 1194 | assert!(matches!(h.prepare("b"), Err(PrepError::Revoked { .. }))); |
| 1195 | assert!(h.adapter.prepared("b").is_none()); |
| 1196 | assert_eq!(h.state("b"), TaskState::Blocked); |
| 1197 | } |
| 1198 | |
| 1199 | #[test] |
| 1200 | fn an_interface_change_during_preparation_refuses_the_old_generation() { |
| 1201 | let mut h = H::new(cfg(true, 4)); |
| 1202 | h.register("a", &[]); |
| 1203 | h.register("b", &["a"]); |
| 1204 | h.publish("a", 1); |
| 1205 | let store_dir = h.tmp.path().join("harness"); |
| 1206 | let adapter = Arc::clone(&h.adapter); |
| 1207 | // While b's operation runs, a publishes a new interface (store write, |
| 1208 | // then the M2 event). |
| 1209 | h.adapter.set_prep_hook(Some(Arc::new(move |_: &str| { |
| 1210 | let mut e = HarnessEngine::load(&store_dir).unwrap(); |
| 1211 | e.completion_clock = fixed_receipt_clock; |
| 1212 | let v2 = e |
| 1213 | .publish_interface(&InterfaceSubmission { |
| 1214 | task_id: "a".into(), |
| 1215 | generation: 1, |
| 1216 | source_commit: COMMIT.into(), |
| 1217 | interface: json!({ "task": "a", "api_version": 2 }), |
| 1218 | }) |
| 1219 | .unwrap() |
| 1220 | .claim(); |
| 1221 | adapter |
| 1222 | .deliver(Event { |
| 1223 | id: "republish-a-mid-prep".into(), |
| 1224 | kind: EventKind::InterfacePublished { |
| 1225 | task: "a".into(), |
| 1226 | generation: 1, |
| 1227 | claim: v2, |
| 1228 | }, |
| 1229 | }) |
| 1230 | .unwrap(); |
| 1231 | }))); |
| 1232 | // b is revoked and dispatched again at generation 2 before the operation |
| 1233 | // ends, so M2 would admit it again: only the generation recheck refuses |
| 1234 | // the result made against the old interface. |
| 1235 | assert!(matches!(h.prepare("b"), Err(PrepError::Revoked { .. }))); |
| 1236 | assert_eq!((h.state("b"), h.gen("b")), (TaskState::Provisional, 2)); |
| 1237 | assert!(h.adapter.prepared("b").is_none()); |
| 1238 | h.adapter.set_prep_hook(None); |
| 1239 | assert_eq!(h.prepare("b").unwrap().generation(), 2); |
| 1240 | } |
| 1241 | |
| 1242 | #[test] |
| 1243 | fn a_producer_receipt_that_stops_verifying_during_preparation_refuses_the_result() { |
| 1244 | let mut h = H::new(cfg(true, 4)); |
| 1245 | h.register("a", &[]); |
| 1246 | h.register("b", &["a"]); |
| 1247 | let (v1, _) = h.publish("a", 1); |
| 1248 | let gen_b = h.gen("b"); |
| 1249 | let file = h |
| 1250 | .engine |
| 1251 | .completion_store |
| 1252 | .join(aien_proof::evidence::RECEIPT_DIR) |
| 1253 | .join(format!("{}.json", v1.receipt_id)); |
| 1254 | let original = std::fs::read(&file).unwrap(); |
| 1255 | let (f2, o2) = (file.clone(), original.clone()); |
| 1256 | // No event: the producer's receipt is altered in the store while b's |
| 1257 | // operation runs, so only the post-operation M2 check can see it. |
| 1258 | h.adapter.set_prep_hook(Some(Arc::new(move |_: &str| { |
| 1259 | let text = String::from_utf8(o2.clone()).unwrap(); |
| 1260 | std::fs::write(&f2, text.replacen("spark-harness", "spark-harnesz", 1)).unwrap(); |
| 1261 | }))); |
| 1262 | assert!(matches!(h.prepare("b"), Err(PrepError::Revoked { .. }))); |
| 1263 | assert_eq!((h.state("b"), h.gen("b")), (TaskState::Provisional, gen_b)); |
| 1264 | assert!(h.adapter.prepared("b").is_none()); |
| 1265 | h.adapter.set_prep_hook(None); |
| 1266 | std::fs::write(&file, &original).unwrap(); |
| 1267 | h.prepare("b").unwrap(); |
| 1268 | } |
| 1269 | |
| 1270 | #[test] |
| 1271 | fn a_producer_completing_during_preparation_is_recorded_as_final() { |
| 1272 | let mut h = H::new(cfg(true, 4)); |
| 1273 | h.register("a", &[]); |
| 1274 | h.register("b", &["a"]); |
| 1275 | h.publish("a", 1); |
| 1276 | h.work_done("a"); |
| 1277 | h.finalize("a"); |
| 1278 | let claim = h.mint_completion("a"); |
| 1279 | let gen_b = h.gen("b"); |
| 1280 | let adapter = Arc::clone(&h.adapter); |
| 1281 | h.adapter.set_prep_hook(Some(Arc::new(move |_: &str| { |
| 1282 | adapter |
| 1283 | .deliver(Event { |
| 1284 | id: "complete-a-mid-prep".into(), |
| 1285 | kind: EventKind::CompletionVerified { |
| 1286 | task: "a".into(), |
| 1287 | generation: 1, |
| 1288 | claim: claim.clone(), |
| 1289 | }, |
| 1290 | }) |
| 1291 | .unwrap(); |
| 1292 | }))); |
| 1293 | // Admitted on the interface, the producer went final while the |
| 1294 | // operation ran. Nothing was revoked, so the consumer keeps its |
| 1295 | // generation, and the stored result carries the readiness re-checked |
| 1296 | // after the operation (final), never the admission-time one. |
| 1297 | let r = h.prepare("b").unwrap(); |
| 1298 | assert_eq!((h.state("b"), h.gen("b")), (TaskState::Provisional, gen_b)); |
| 1299 | assert!(!r.is_provisional()); |
| 1300 | assert_eq!(r.bindings()[0].level, ReadinessLevel::FinalVerified); |
| 1301 | let stored = h.adapter.prepared("b").unwrap(); |
| 1302 | assert_eq!(stored.bindings()[0].level, ReadinessLevel::FinalVerified); |
| 1303 | } |
| 1304 | |
| 1305 | #[test] |
| 1306 | fn one_preparation_per_task_at_a_time() { |
| 1307 | let mut h = H::new(cfg(true, 4)); |
| 1308 | h.register("a", &[]); |
| 1309 | h.register("b", &["a"]); |
| 1310 | h.publish("a", 1); |
| 1311 | let (entered_tx, entered_rx) = mpsc::channel::<()>(); |
| 1312 | let (release_tx, release_rx) = mpsc::channel::<()>(); |
| 1313 | let release_rx = std::sync::Mutex::new(release_rx); |
| 1314 | let calls = AtomicU64::new(0); |
| 1315 | // Only the first call parks; a second admitted call would run straight |
| 1316 | // through and fail the Busy assertion below instead of deadlocking. |
| 1317 | h.adapter.set_prep_hook(Some(Arc::new(move |_: &str| { |
| 1318 | if calls.fetch_add(1, Ordering::SeqCst) == 0 { |
| 1319 | entered_tx.send(()).unwrap(); |
| 1320 | let _ = release_rx |
| 1321 | .lock() |
| 1322 | .unwrap() |
| 1323 | .recv_timeout(Duration::from_secs(10)); |
| 1324 | } |
| 1325 | }))); |
| 1326 | let (a2, ws) = (Arc::clone(&h.adapter), h.ws()); |
| 1327 | let first = std::thread::spawn(move || a2.prepare("b", 1, GOAL, &ws).map(|_| ())); |
| 1328 | entered_rx.recv().unwrap(); |
| 1329 | assert!(matches!(h.prepare("b"), Err(PrepError::Busy(_)))); |
| 1330 | release_tx.send(()).unwrap(); |
| 1331 | first.join().unwrap().unwrap(); |
| 1332 | h.adapter.set_prep_hook(None); |
| 1333 | h.prepare("b").unwrap(); |
| 1334 | } |
| 1335 | |
| 1336 | #[test] |
| 1337 | fn concurrency_is_bounded_by_the_m2_permits() { |
| 1338 | let mut h = H::new(cfg(true, 1)); |
| 1339 | h.register("a", &[]); |
| 1340 | h.register("b", &["a"]); |
| 1341 | h.register("c", &["a"]); |
| 1342 | h.publish("a", 1); |
| 1343 | // A holds the only permit: neither consumer may prepare yet. |
| 1344 | assert_eq!(h.adapter.permits_in_use().running, 1); |
| 1345 | for t in ["b", "c"] { |
| 1346 | assert_eq!(h.state(t), TaskState::Blocked); |
| 1347 | assert!(h.prepare(t).is_err()); |
| 1348 | } |
| 1349 | h.work_done("a"); |
| 1350 | // One consumer at a time, in task-id order. |
| 1351 | assert_eq!( |
| 1352 | (h.state("b"), h.state("c")), |
| 1353 | (TaskState::Provisional, TaskState::Blocked) |
| 1354 | ); |
| 1355 | h.prepare("b").unwrap(); |
| 1356 | assert!(h.prepare("c").is_err()); |
| 1357 | h.work_done("b"); |
| 1358 | assert_eq!(h.state("c"), TaskState::Provisional); |
| 1359 | h.prepare("c").unwrap(); |
| 1360 | assert!(h.adapter.permits_in_use().running <= 1); |
| 1361 | } |
| 1362 | |
| 1363 | #[test] |
| 1364 | fn the_commit_decision_freezes_the_inputs_without_holding_any_lock() { |
| 1365 | let mut h = H::new(cfg(true, 4)); |
| 1366 | h.register("a", &[]); |
| 1367 | h.register("b", &["a"]); |
| 1368 | h.publish("a", 1); |
| 1369 | h.finish("a"); |
| 1370 | h.finish("b"); |
| 1371 | // An unrelated task with a live lease, heartbeating during the call. |
| 1372 | h.register("x", &[]); |
| 1373 | assert_eq!(h.state("x"), TaskState::Provisional); |
| 1374 | let adapter = Arc::clone(&h.adapter); |
| 1375 | let store_dir = h.tmp.path().join("harness"); |
| 1376 | let wait = Duration::from_secs(10); |
| 1377 | let fenced = h.adapter.fenced_for_tests( |
| 1378 | "b", |
| 1379 | 1, |
| 1380 | |_| { |
| 1381 | let during = adapter.state("b"); |
| 1382 | // Each probe runs on its own thread and must finish while the |
| 1383 | // call is still running: neither the adapter mutex nor a store |
| 1384 | // lock is held. |
| 1385 | let (tx, rx) = mpsc::channel(); |
| 1386 | let a2 = Arc::clone(&adapter); |
| 1387 | let t = tx.clone(); |
| 1388 | std::thread::spawn(move || { |
| 1389 | let r = a2.deliver(Event { |
| 1390 | id: "revoke-a-during-commit".into(), |
| 1391 | kind: EventKind::Revoke { |
| 1392 | task: "a".into(), |
| 1393 | generation: 1, |
| 1394 | reason: "interface withdrawn".into(), |
| 1395 | }, |
| 1396 | }); |
| 1397 | t.send(format!("revoke {r:?}")).unwrap(); |
| 1398 | }); |
| 1399 | let revoke = rx.recv_timeout(wait).expect("revoke blocked by the call"); |
| 1400 | let a3 = Arc::clone(&adapter); |
| 1401 | let t = tx.clone(); |
| 1402 | std::thread::spawn(move || { |
| 1403 | let r = a3.deliver(Event { |
| 1404 | id: "beat-x-during-commit".into(), |
| 1405 | kind: EventKind::Heartbeat { |
| 1406 | task: "x".into(), |
| 1407 | generation: 1, |
| 1408 | beat: 1, |
| 1409 | }, |
| 1410 | }); |
| 1411 | t.send(format!("beat {r:?}")).unwrap(); |
| 1412 | }); |
| 1413 | let beat = rx |
| 1414 | .recv_timeout(wait) |
| 1415 | .expect("heartbeat blocked by the call"); |
| 1416 | std::thread::spawn(move || { |
| 1417 | let mut e = HarnessEngine::load(&store_dir).unwrap(); |
| 1418 | e.completion_clock = fixed_receipt_clock; |
| 1419 | let r = e.publish_interface(&InterfaceSubmission { |
| 1420 | task_id: "a".into(), |
| 1421 | generation: 1, |
| 1422 | source_commit: COMMIT.into(), |
| 1423 | interface: json!({ "task": "a", "api_version": 9 }), |
| 1424 | }); |
| 1425 | tx.send(format!("store {:?}", r.map(|_| ()))).unwrap(); |
| 1426 | }); |
| 1427 | let store = rx |
| 1428 | .recv_timeout(wait) |
| 1429 | .expect("store writer blocked by the call"); |
| 1430 | // A second fence for the same task generation while the first |
| 1431 | // call runs: refused as already submitted, and it never runs. |
| 1432 | let a4 = Arc::clone(&adapter); |
| 1433 | let (tx2, rx2) = mpsc::channel(); |
| 1434 | std::thread::spawn(move || { |
| 1435 | let r = a4.fenced_for_tests("b", 1, |_| (), committed); |
| 1436 | tx2.send(format!("{:?}", r.map(|_| "ran"))).unwrap(); |
| 1437 | }); |
| 1438 | let second = rx2 |
| 1439 | .recv_timeout(wait) |
| 1440 | .expect("second fence blocked by the call"); |
| 1441 | (during, revoke, beat, store, second) |
| 1442 | }, |
| 1443 | committed, |
| 1444 | ); |
| 1445 | let out = fenced.expect("fence passes"); |
| 1446 | let (during, revoke, beat, store, second) = out.outcome; |
| 1447 | assert!(second.starts_with("Err(AlreadySubmitted"), "{second}"); |
| 1448 | assert_eq!(during, Some(TaskState::Committing)); |
| 1449 | assert!( |
| 1450 | revoke.starts_with("revoke Ok(Deferred") && revoke.contains("committing: \"b\""), |
| 1451 | "an upstream revoke must be held back while committing: {revoke}" |
| 1452 | ); |
| 1453 | assert!(beat.contains("Ok(Applied(Applied"), "{beat}"); |
| 1454 | assert_eq!(store, "store Ok(())"); |
| 1455 | assert_eq!(out.result, committed(&())); |
| 1456 | assert!(out.record_error.is_none()); |
| 1457 | assert_eq!((h.state("b"), h.gen("b")), (TaskState::Committed, 1)); |
| 1458 | // After the outcome the held-back revoke applied, and stopped at the |
| 1459 | // committed task. |
| 1460 | assert_eq!(out.redelivered.len(), 1); |
| 1461 | assert_eq!(out.redelivered[0].id, "revoke-a-during-commit"); |
| 1462 | assert!( |
| 1463 | matches!(out.redelivered[0].result, Ok(Outcome::Applied(_))), |
| 1464 | "{:?}", |
| 1465 | out.redelivered[0].result |
| 1466 | ); |
| 1467 | assert_eq!(h.adapter.deferred_len(), 0); |
| 1468 | assert_eq!((h.state("b"), h.gen("b")), (TaskState::Committed, 1)); |
| 1469 | assert!(matches!( |
| 1470 | fence_err(h.adapter.fenced_for_tests("b", 1, |_| (), committed)), |
| 1471 | FenceError::AlreadySubmitted { .. } |
| 1472 | )); |
| 1473 | } |
| 1474 | |
| 1475 | #[test] |
| 1476 | fn a_panicking_commit_is_uncertain_and_never_runs_again() { |
| 1477 | let mut h = H::new(cfg(true, 4)); |
| 1478 | h.register("a", &[]); |
| 1479 | h.register("b", &["a"]); |
| 1480 | h.register("c", &["b"]); |
| 1481 | h.publish("a", 1); |
| 1482 | h.publish("b", 1); |
| 1483 | h.finish("a"); |
| 1484 | h.finish("b"); |
| 1485 | assert_eq!(h.state("c"), TaskState::Provisional); |
| 1486 | let adapter = Arc::clone(&h.adapter); |
| 1487 | let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 1488 | adapter.fenced_for_tests("b", 1, |_| panic!("commit blew up"), committed) |
| 1489 | })); |
| 1490 | assert!(r.is_err(), "the panic is resumed"); |
| 1491 | assert_eq!(h.state("b"), TaskState::CommitUncertain); |
| 1492 | assert_eq!(h.state("c"), TaskState::Blocked, "consumers revoked"); |
| 1493 | let mut ran = false; |
| 1494 | assert!(matches!( |
| 1495 | fence_err( |
| 1496 | h.adapter |
| 1497 | .fenced_for_tests("b", 1, |_| ran = true, committed) |
| 1498 | ), |
| 1499 | FenceError::AlreadySubmitted { .. } |
| 1500 | )); |
| 1501 | assert!(!ran); |
| 1502 | } |
| 1503 | |
| 1504 | #[test] |
| 1505 | fn a_failed_commit_aborts_the_task_and_a_new_generation_may_commit() { |
| 1506 | let mut h = H::new(cfg(true, 4)); |
| 1507 | h.register("a", &[]); |
| 1508 | h.register("b", &["a"]); |
| 1509 | h.publish("a", 1); |
| 1510 | h.finish("a"); |
| 1511 | h.finish("b"); |
| 1512 | let failed = |_: &()| CommitResult::Failed { |
| 1513 | reason: "refused before any write".into(), |
| 1514 | }; |
| 1515 | let out = h.adapter.fenced_for_tests("b", 1, |_| (), failed).unwrap(); |
| 1516 | assert!(matches!(out.result, CommitResult::Failed { .. })); |
| 1517 | assert_eq!(h.state("b"), TaskState::Aborted); |
| 1518 | h.ok(EventKind::Retry { |
| 1519 | task: "b".into(), |
| 1520 | generation: 1, |
| 1521 | }); |
| 1522 | assert_eq!(h.gen("b"), 2); |
| 1523 | h.finish("b"); |
| 1524 | let out = h |
| 1525 | .adapter |
| 1526 | .fenced_for_tests("b", 2, |_| (), committed) |
| 1527 | .unwrap(); |
| 1528 | assert!(out.record_error.is_none()); |
| 1529 | assert_eq!(h.state("b"), TaskState::Committed); |
| 1530 | } |
| 1531 | |
| 1532 | #[test] |
| 1533 | fn outcomes_are_classified_conservatively() { |
| 1534 | let refusal = |name: &str, claim: Option<u64>| { |
| 1535 | let e = ApprovedRefusal { |
| 1536 | refused_by: "REPLAY_REFUSED".into(), |
| 1537 | name: name.into(), |
| 1538 | detail: "d".into(), |
| 1539 | request_id: "r".into(), |
| 1540 | trace_id: "t".into(), |
| 1541 | approval_id: "a".into(), |
| 1542 | replay_claim: claim, |
| 1543 | }; |
| 1544 | classify_approved(&Err(Box::new(e))) |
| 1545 | }; |
| 1546 | assert!(matches!( |
| 1547 | refusal("Unauthenticated", None), |
| 1548 | CommitResult::Failed { .. } |
| 1549 | )); |
| 1550 | assert!(matches!( |
| 1551 | refusal("NotCommitted", Some(3)), |
| 1552 | CommitResult::Failed { .. } |
| 1553 | )); |
| 1554 | assert!(matches!( |
| 1555 | refusal("ComposeError", Some(3)), |
| 1556 | CommitResult::Uncertain { .. } |
| 1557 | )); |
| 1558 | assert!(matches!( |
| 1559 | refusal("Mismatch", Some(3)), |
| 1560 | CommitResult::Uncertain { .. } |
| 1561 | )); |
| 1562 | assert!(matches!( |
| 1563 | refusal("GrantNotWritten", Some(3)), |
| 1564 | CommitResult::Uncertain { .. } |
| 1565 | )); |
| 1566 | let e = |s: &str| classify_authorize(&ControlResponse::Error(s.into())); |
| 1567 | assert!(matches!( |
| 1568 | e("EFFECT_REFUSED DeskMacRequired: none"), |
| 1569 | CommitResult::Failed { .. } |
| 1570 | )); |
| 1571 | assert!(matches!( |
| 1572 | e("effect record: re-read 7: io"), |
| 1573 | CommitResult::Uncertain { .. } |
| 1574 | )); |
| 1575 | assert!(matches!( |
| 1576 | classify_authorize(&ControlResponse::ComposeNoted( |
| 1577 | aien_runtime::control::ComposeNoteReport { |
| 1578 | machine_id: "m".into(), |
| 1579 | id: 7, |
| 1580 | kind: "authorization".into(), |
| 1581 | digest: "d".into(), |
| 1582 | text_sha256: "s".into(), |
| 1583 | links: vec![], |
| 1584 | } |
| 1585 | )), |
| 1586 | CommitResult::Committed { .. } |
| 1587 | )); |
| 1588 | } |
| 1589 | |
| 1590 | #[test] |
| 1591 | fn disabled_flag_is_the_default_and_sequential() { |
| 1592 | assert!(!ProvisionalConfig::default().enabled); |
| 1593 | let mut h = H::new(cfg(false, 4)); |
| 1594 | assert!(!h.adapter.enabled()); |
| 1595 | h.register("a", &[]); |
| 1596 | h.register("b", &["a"]); |
| 1597 | h.publish("a", 1); |
| 1598 | assert_eq!(h.state("b"), TaskState::Blocked); |
| 1599 | assert!(h.prepare("b").is_err()); |
| 1600 | h.finish("a"); |
| 1601 | let r = h.prepare("b").unwrap(); |
| 1602 | assert!(!r.is_provisional()); |
| 1603 | } |
| 1604 | |
| 1605 | // ---------- through the daemon socket ---------- |
| 1606 | |
| 1607 | async fn daemon( |
| 1608 | socket: &Path, |
| 1609 | bridge: Arc<ComposeBridge>, |
| 1610 | adapter: Arc<PrepAdapter>, |
| 1611 | ) -> ( |
| 1612 | aien_runtime::client::AienRuntimeClient, |
| 1613 | tokio::task::JoinHandle<Result<(), String>>, |
| 1614 | ) { |
| 1615 | let cfg = aien_scheduler::SchedulerConfig { |
| 1616 | max_batch_size: 8, |
| 1617 | max_batch_tokens: 1024, |
| 1618 | prefill_chunk_size: 64, |
| 1619 | watermark_blocks: 4, |
| 1620 | chunk_prefill: true, |
| 1621 | max_prefill_tokens: 1024, |
| 1622 | }; |
| 1623 | let spine = aien_runtime::spine::AienRuntimeSpine::new( |
| 1624 | 64, |
| 1625 | cfg, |
| 1626 | aien_kv_cache::create_shared_kv_manager(256, 16), |
| 1627 | ); |
| 1628 | let server = aien_runtime::server::AienRuntimeServer::new(spine, socket) |
| 1629 | .with_compose_bridge(bridge) |
| 1630 | .with_prep_adapter(adapter); |
| 1631 | let handle = tokio::spawn(async move { |
| 1632 | server |
| 1633 | .run(aien_inference_abi::MockInferenceBackend::new(1)) |
| 1634 | .await |
| 1635 | }); |
| 1636 | let client = aien_runtime::client::AienRuntimeClient::new(socket); |
| 1637 | for _ in 0..250 { |
| 1638 | if client.is_alive().await { |
| 1639 | return (client, handle); |
| 1640 | } |
| 1641 | if handle.is_finished() { |
| 1642 | panic!("daemon stopped: {:?}", handle.await); |
| 1643 | } |
| 1644 | tokio::time::sleep(Duration::from_millis(20)).await; |
| 1645 | } |
| 1646 | panic!("daemon did not come up"); |
| 1647 | } |
| 1648 | |
| 1649 | fn fence_refused(r: &ControlResponse, name: &str) -> bool { |
| 1650 | matches!(r, ControlResponse::Error(e) if e.starts_with(&format!("FENCE_REFUSED {name}"))) |
| 1651 | } |
| 1652 | |
| 1653 | /// The original `ComposeApprovedProposal` answer: a result or a refusal from |
| 1654 | /// the canonical path, never a fence error. |
| 1655 | fn canonical_approved(r: &ControlResponse) -> bool { |
| 1656 | matches!( |
| 1657 | r, |
| 1658 | ControlResponse::ComposeApprovedResult(_) | ControlResponse::ComposeApprovedRefused(_) |
| 1659 | ) |
| 1660 | } |
| 1661 | |
| 1662 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 1663 | async fn the_daemon_fences_bound_requests_and_runs_unbound_ones_unchanged() { |
| 1664 | let _home = home_guard::home_slot(); |
| 1665 | let mut h = H::new(cfg(true, 4)); |
| 1666 | let c = Compose::new(&h); |
| 1667 | let socket = h.tmp.path().join("d.sock"); |
| 1668 | let (client, server) = daemon(&socket, c.bridge.clone(), h.adapter.clone()).await; |
| 1669 | let send = |cmd: ControlCommand| { |
| 1670 | let client = &client; |
| 1671 | async move { client.send_command(cmd).await.unwrap() } |
| 1672 | }; |
| 1673 | let approved = |p: &ApprovedProposal| ControlCommand::ComposeApprovedProposal { |
| 1674 | proposal: p.clone(), |
| 1675 | workspace: c.ws.clone(), |
| 1676 | }; |
| 1677 | let authorize = |digest: &str| ControlCommand::ComposeAuthorize { |
| 1678 | cx_promotion: 1, |
| 1679 | proposal_sha256: digest.into(), |
| 1680 | workspace: c.ws.clone(), |
| 1681 | approver: "drake".into(), |
| 1682 | constraints: vec![], |
| 1683 | desk_proof: None, |
| 1684 | objective_id: None, |
| 1685 | }; |
| 1686 | |
| 1687 | // Early overlap: B prepares while its producer A is only interface |
| 1688 | // verified. |
| 1689 | h.register("a", &[]); |
| 1690 | h.register("b", &["a"]); |
| 1691 | h.publish("a", 1); |
| 1692 | assert!(h.prepare("b").unwrap().is_provisional()); |
| 1693 | let bound = c.approval("req-bound"); |
| 1694 | let free = c.approval("req-free"); |
| 1695 | let commit_key = FenceKey::Approval(bound.approval_id.clone()); |
| 1696 | let grant_key = FenceKey::Proposal(sha(b"bound grant")); |
| 1697 | h.adapter.bind_approval(commit_key.clone(), "b", 1).unwrap(); |
| 1698 | h.adapter.bind_approval(grant_key.clone(), "b", 1).unwrap(); |
| 1699 | assert!(h |
| 1700 | .adapter |
| 1701 | .binding(&FenceKey::Approval(free.approval_id.clone())) |
| 1702 | .is_none()); |
| 1703 | |
| 1704 | // Bound, while B is provisional: the fence refuses both kinds and |
| 1705 | // nothing runs. |
| 1706 | let compose_dir = c.bridge.dir().to_path_buf(); |
| 1707 | let before = (tree(&h.ws()), tree(&compose_dir)); |
| 1708 | let r = send(approved(&bound)).await; |
| 1709 | assert!(fence_refused(&r, "NotCommittable"), "{r:?}"); |
| 1710 | let r = send(authorize(&sha(b"bound grant"))).await; |
| 1711 | assert!(fence_refused(&r, "NotCommittable"), "{r:?}"); |
| 1712 | assert_eq!( |
| 1713 | (tree(&h.ws()), tree(&compose_dir)), |
| 1714 | before, |
| 1715 | "a fenced request wrote nothing" |
| 1716 | ); |
| 1717 | assert_eq!(h.state("b"), TaskState::Provisional); |
| 1718 | |
| 1719 | // Unbound: the original calls run, whatever the M2 state. |
| 1720 | let r = send(authorize(&sha(b"never committed"))).await; |
| 1721 | match &r { |
| 1722 | ControlResponse::Error(e) if aien_omega_compose::LINKED => { |
| 1723 | assert!(e.starts_with("EFFECT_REFUSED DeskMacRequired"), "{e}") |
| 1724 | } |
| 1725 | ControlResponse::Error(e) => assert!( |
| 1726 | e.starts_with("compose home ") && e.ends_with("is not linked (stub build)"), |
| 1727 | "{e}" |
| 1728 | ), |
| 1729 | other => panic!("the canonical authorize must refuse: {other:?}"), |
| 1730 | } |
| 1731 | let r = send(approved(&free)).await; |
| 1732 | assert!(canonical_approved(&r), "{r:?}"); |
| 1733 | assert_eq!( |
| 1734 | h.state("b"), |
| 1735 | TaskState::Provisional, |
| 1736 | "unbound runs touch no task" |
| 1737 | ); |
| 1738 | |
| 1739 | // Once A and B are final the bound approval passes the fence and the |
| 1740 | // canonical path decides: the World commit and its own grant, in one |
| 1741 | // fenced call. |
| 1742 | h.finish("a"); |
| 1743 | h.finish("b"); |
| 1744 | let r = send(approved(&bound)).await; |
| 1745 | assert!(canonical_approved(&r), "{r:?}"); |
| 1746 | let report = match &r { |
| 1747 | ControlResponse::ComposeApprovedResult(rep) if aien_omega_compose::LINKED => { |
| 1748 | assert_eq!(rep.state, "COMMITTED"); |
| 1749 | Some(rep.clone()) |
| 1750 | } |
| 1751 | // The stub refuses the replay claim itself: nothing durable. |
| 1752 | ControlResponse::ComposeApprovedRefused(_) if !aien_omega_compose::LINKED => None, |
| 1753 | other => panic!("unexpected answer: {other:?}"), |
| 1754 | }; |
| 1755 | let Some(report) = report else { |
| 1756 | // The refusal is classified `Failed`: B is aborted and keeps both |
| 1757 | // bindings, so a resend is fenced and never reaches the canonical |
| 1758 | // path unfenced. |
| 1759 | assert_eq!(h.state("b"), TaskState::Aborted); |
| 1760 | assert_eq!(h.adapter.binding(&commit_key), Some(("b".into(), 1))); |
| 1761 | assert_eq!(h.adapter.binding(&grant_key), Some(("b".into(), 1))); |
| 1762 | let r = send(approved(&bound)).await; |
| 1763 | assert!(fence_refused(&r, "AlreadySubmitted"), "{r:?}"); |
| 1764 | let r = send(authorize(&sha(b"bound grant"))).await; |
| 1765 | assert!(fence_refused(&r, "AlreadySubmitted"), "{r:?}"); |
| 1766 | assert_eq!(h.state("b"), TaskState::Aborted); |
| 1767 | let _ = client.send_command(ControlCommand::Shutdown).await; |
| 1768 | let _ = tokio::time::timeout(Duration::from_secs(5), server).await; |
| 1769 | return; |
| 1770 | }; |
| 1771 | // B committed, so M2 dropped both of its bindings. |
| 1772 | assert!(h.adapter.binding(&commit_key).is_none()); |
| 1773 | assert!(h.adapter.binding(&grant_key).is_none()); |
| 1774 | assert_eq!(h.adapter.inspect(|s| s.approvals_len()), 0); |
| 1775 | assert_eq!(h.state("b"), TaskState::Committed); |
| 1776 | assert!(report.approved_grant.is_some(), "{report:?}"); |
| 1777 | // An exact retry goes to the canonical path, whose replay ledger |
| 1778 | // answers it without a second run. |
| 1779 | let r = send(approved(&bound)).await; |
| 1780 | match &r { |
| 1781 | ControlResponse::ComposeApprovedResult(rep) => { |
| 1782 | assert_eq!(rep.state, "ALREADY_COMMITTED"); |
| 1783 | assert!(rep.task.is_none(), "nothing ran again"); |
| 1784 | } |
| 1785 | other => panic!("want ALREADY_COMMITTED, got {other:?}"), |
| 1786 | } |
| 1787 | // No later grant stage exists for this flow. M2 refuses to bind one to |
| 1788 | // the ended task, and the canonical mint refuses a desk-signed grant |
| 1789 | // against the approved commit: the approved path writes no |
| 1790 | // `compose_commit` record (compose/bridge.rs `run_task_inner`), which |
| 1791 | // `ComposeAuthorize` requires (effects.rs). |
| 1792 | let digest = report.compose_proposal_sha256.clone(); |
| 1793 | let cx = report.grant_links[0]; |
| 1794 | let late = h |
| 1795 | .adapter |
| 1796 | .bind_approval(FenceKey::Proposal(digest.clone()), "b", 1); |
| 1797 | assert!( |
| 1798 | matches!(late, Err(SchedError::WrongState { .. })), |
| 1799 | "{late:?}" |
| 1800 | ); |
| 1801 | let key = DeskKey::load(&desk_key_path(c.bridge.dir())).unwrap(); |
| 1802 | let nonce = format!("m3-grant-{cx}"); |
| 1803 | let mac = key.sign_authorize(&AuthorizeBinding { |
| 1804 | cx_promotion: cx, |
| 1805 | proposal_sha256: digest.clone(), |
| 1806 | path: PATH.into(), |
| 1807 | content_sha256: sha(CONTENT.as_bytes()), |
| 1808 | workspace: c.ws.clone(), |
| 1809 | approver: "drake".into(), |
| 1810 | constraints: vec![], |
| 1811 | nonce: nonce.clone(), |
| 1812 | desk_key_id: key.id().into(), |
| 1813 | }); |
| 1814 | let r = send(ControlCommand::ComposeAuthorize { |
| 1815 | cx_promotion: cx, |
| 1816 | proposal_sha256: digest, |
| 1817 | workspace: c.ws.clone(), |
| 1818 | approver: "drake".into(), |
| 1819 | constraints: vec![], |
| 1820 | desk_proof: Some(DeskProof { nonce, mac }), |
| 1821 | objective_id: None, |
| 1822 | }) |
| 1823 | .await; |
| 1824 | match &r { |
| 1825 | ControlResponse::Error(e) => { |
| 1826 | assert!(e.starts_with("EFFECT_REFUSED NotAuthorized"), "{e}") |
| 1827 | } |
| 1828 | other => panic!("want the canonical NotAuthorized refusal, got {other:?}"), |
| 1829 | } |
| 1830 | assert_eq!(h.state("b"), TaskState::Committed); |
| 1831 | // In process the generation is spent. |
| 1832 | assert!(matches!( |
| 1833 | fence_err(h.adapter.submit_approved("b", 1, &c.hook, &bound, &c.ws)), |
| 1834 | FenceError::AlreadySubmitted { .. } |
| 1835 | )); |
| 1836 | |
| 1837 | let _ = client.send_command(ControlCommand::Shutdown).await; |
| 1838 | let _ = tokio::time::timeout(Duration::from_secs(5), server).await; |
| 1839 | } |
| 1840 | |
| 1841 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 1842 | async fn an_aborted_task_keeps_its_bound_requests_fenced_until_retried_and_bound_again() { |
| 1843 | let _home = home_guard::home_slot(); |
| 1844 | let mut h = H::new(cfg(true, 4)); |
| 1845 | let c = Compose::new(&h); |
| 1846 | let socket = h.tmp.path().join("d.sock"); |
| 1847 | let (client, server) = daemon(&socket, c.bridge.clone(), h.adapter.clone()).await; |
| 1848 | let send = |cmd: ControlCommand| { |
| 1849 | let client = &client; |
| 1850 | async move { client.send_command(cmd).await.unwrap() } |
| 1851 | }; |
| 1852 | let authorize = |digest: &str| ControlCommand::ComposeAuthorize { |
| 1853 | cx_promotion: 1, |
| 1854 | proposal_sha256: digest.into(), |
| 1855 | workspace: c.ws.clone(), |
| 1856 | approver: "drake".into(), |
| 1857 | constraints: vec![], |
| 1858 | desk_proof: None, |
| 1859 | objective_id: None, |
| 1860 | }; |
| 1861 | // The canonical call's own refusal (no desk MAC, or the stub), never a |
| 1862 | // fence error: what an unfenced run answers. |
| 1863 | let canonical = |r: &ControlResponse| matches!(r, ControlResponse::Error(e) if !e.starts_with("FENCE_REFUSED")); |
| 1864 | let r = send(authorize(&sha(b"never bound"))).await; |
| 1865 | assert!(canonical(&r), "control, unbound: {r:?}"); |
| 1866 | |
| 1867 | // (a) Cancel, producer failure and lease expiry: the binding stays and |
| 1868 | // the request is refused. |
| 1869 | type Abort = fn(&mut H, &str); |
| 1870 | let aborts: [(&str, Abort); 3] = [ |
| 1871 | ("cancel", |h, t| { |
| 1872 | let generation = h.gen(t); |
| 1873 | h.ok(EventKind::Cancel { |
| 1874 | task: t.into(), |
| 1875 | generation, |
| 1876 | }); |
| 1877 | }), |
| 1878 | ("producer failed", |h, t| { |
| 1879 | let generation = h.gen(t); |
| 1880 | h.ok(EventKind::ProducerFailed { |
| 1881 | task: t.into(), |
| 1882 | generation, |
| 1883 | reason: "test".into(), |
| 1884 | }); |
| 1885 | }), |
| 1886 | ("lease expired", |h, t| { |
| 1887 | // The producer finishes first, so only b's provisional lease |
| 1888 | // runs out (a running producer's expiry would revoke b instead). |
| 1889 | h.finish(&t.replacen('b', "a", 1)); |
| 1890 | h.ticks.fetch_add(2_000_000, Ordering::SeqCst); |
| 1891 | h.ok(EventKind::Tick); |
| 1892 | }), |
| 1893 | ]; |
| 1894 | for (i, (how, abort)) in aborts.into_iter().enumerate() { |
| 1895 | let (a, b) = (format!("a{i}"), format!("b{i}")); |
| 1896 | h.register(&a, &[]); |
| 1897 | h.register(&b, &[a.as_str()]); |
| 1898 | h.publish(&a, 1); |
| 1899 | assert_eq!(h.state(&b), TaskState::Provisional, "{how}"); |
| 1900 | let digest = sha(how.as_bytes()); |
| 1901 | h.adapter |
| 1902 | .bind_approval(FenceKey::Proposal(digest.clone()), &b, 1) |
| 1903 | .unwrap(); |
| 1904 | abort(&mut h, &b); |
| 1905 | assert_eq!(h.state(&b), TaskState::Aborted, "{how}"); |
| 1906 | let r = send(authorize(&digest)).await; |
| 1907 | assert!(fence_refused(&r, "NotCommittable"), "{how}: {r:?}"); |
| 1908 | } |
| 1909 | |
| 1910 | // (b) A committable task is cancelled, retried and committable again: |
| 1911 | // the old binding refuses until the request is bound at the new |
| 1912 | // generation, and then the request runs through the fence. |
| 1913 | h.register("p", &[]); |
| 1914 | h.register("q", &["p"]); |
| 1915 | h.publish("p", 1); |
| 1916 | h.finish("p"); |
| 1917 | h.finish("q"); |
| 1918 | let digest = sha(b"retried grant"); |
| 1919 | let key = FenceKey::Proposal(digest.clone()); |
| 1920 | h.adapter.bind_approval(key.clone(), "q", 1).unwrap(); |
| 1921 | h.ok(EventKind::Cancel { |
| 1922 | task: "q".into(), |
| 1923 | generation: 1, |
| 1924 | }); |
| 1925 | let r = send(authorize(&digest)).await; |
| 1926 | assert!(fence_refused(&r, "NotCommittable"), "{r:?}"); |
| 1927 | h.ok(EventKind::Retry { |
| 1928 | task: "q".into(), |
| 1929 | generation: 1, |
| 1930 | }); |
| 1931 | h.finish("q"); |
| 1932 | assert_eq!(h.gen("q"), 2); |
| 1933 | let r = send(authorize(&digest)).await; |
| 1934 | assert!(fence_refused(&r, "StaleGeneration"), "{r:?}"); |
| 1935 | assert_eq!(h.state("q"), TaskState::Committable); |
| 1936 | h.adapter.bind_approval(key.clone(), "q", 2).unwrap(); |
| 1937 | let r = send(authorize(&digest)).await; |
| 1938 | assert!(canonical(&r), "bound again, it runs fenced: {r:?}"); |
| 1939 | if aien_omega_compose::LINKED { |
| 1940 | // The canonical refusal (no desk MAC) is a failed commit: q is |
| 1941 | // aborted, keeps the binding, and a resend stays fenced. |
| 1942 | assert_eq!(h.state("q"), TaskState::Aborted); |
| 1943 | assert_eq!(h.adapter.binding(&key), Some(("q".into(), 2))); |
| 1944 | let r = send(authorize(&digest)).await; |
| 1945 | assert!(fence_refused(&r, "AlreadySubmitted"), "{r:?}"); |
| 1946 | } else { |
| 1947 | // The stub answer is not an EFFECT_REFUSED: uncertain, terminal. |
| 1948 | assert_eq!(h.state("q"), TaskState::CommitUncertain); |
| 1949 | assert!(h.adapter.binding(&key).is_none()); |
| 1950 | } |
| 1951 | |
| 1952 | let _ = client.send_command(ControlCommand::Shutdown).await; |
| 1953 | let _ = tokio::time::timeout(Duration::from_secs(5), server).await; |
| 1954 | } |
| 1955 | |
| 1956 | // The model proposal of the `RunComposeTask` flow, as in |
| 1957 | // provenance_link_test.rs. |
| 1958 | const RUN_GOAL: &str = "write the note"; |
| 1959 | const RUN_PROPOSAL: &str = "filename: NOTES.md\nkeep every change inside the workspace\n"; |
| 1960 | const RUN_CONTENT: &str = "keep every change inside the workspace\n"; |
| 1961 | |
| 1962 | fn model_proposer() -> ComposeProposer { |
| 1963 | Arc::new(|_: &str, _: Duration| { |
| 1964 | Ok(aien_runtime::compose::Generation { |
| 1965 | text: RUN_PROPOSAL.to_string(), |
| 1966 | tokens: 3, |
| 1967 | finish_reason: Some("eos".into()), |
| 1968 | token_ids: Some(vec![11, 12, 13]), |
| 1969 | prompt_tokens: Some(5), |
| 1970 | prompt_ids_sha256: Some(aien_runtime::compose::token_ids_sha256(&[1, 2, 3, 4, 5])), |
| 1971 | decoding: Some(aien_inference_abi::DecodeObservation { |
| 1972 | greedy_tokens: 3, |
| 1973 | ..Default::default() |
| 1974 | }), |
| 1975 | ops: Some(aien_inference_abi::OpEvidence { |
| 1976 | backend: "reference-cpu".into(), |
| 1977 | native_fallbacks: 0, |
| 1978 | reference_runs: 0, |
| 1979 | report: "OP_REPORT native=[] reference=[] native_fallbacks=[] reference_runs=[]" |
| 1980 | .into(), |
| 1981 | gpu_executions: None, |
| 1982 | }), |
| 1983 | }) |
| 1984 | }) |
| 1985 | } |
| 1986 | |
| 1987 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 1988 | async fn a_bound_grant_after_an_unfenced_compose_run_mints_through_the_fence() { |
| 1989 | let _home = home_guard::home_slot(); |
| 1990 | let mut h = H::new(cfg(true, 4)); |
| 1991 | let home = h.tmp.path().join("compose"); |
| 1992 | DeskKey::create(&desk_key_path(&home)).unwrap(); |
| 1993 | let bridge = Arc::new(ComposeBridge::new( |
| 1994 | home.clone(), |
| 1995 | model_proposer(), |
| 1996 | "test:m3-model", |
| 1997 | )); |
| 1998 | let ws = std::fs::canonicalize(h.ws()).unwrap().display().to_string(); |
| 1999 | let socket = h.tmp.path().join("g.sock"); |
| 2000 | let (client, server) = daemon(&socket, bridge.clone(), h.adapter.clone()).await; |
| 2001 | let send = |cmd: ControlCommand| { |
| 2002 | let client = &client; |
| 2003 | async move { client.send_command(cmd).await.unwrap() } |
| 2004 | }; |
| 2005 | h.register("a", &[]); |
| 2006 | h.register("b", &["a"]); |
| 2007 | h.publish("a", 1); |
| 2008 | let digest = sha(RUN_PROPOSAL.as_bytes()); |
| 2009 | let key = FenceKey::Proposal(digest.clone()); |
| 2010 | h.adapter.bind_approval(key.clone(), "b", 1).unwrap(); |
| 2011 | |
| 2012 | // The model run has no binding kind: it runs unfenced, whatever B's |
| 2013 | // state, and records the compose commit the grant needs. |
| 2014 | let r = send(ControlCommand::RunComposeTask { |
| 2015 | context: None, |
| 2016 | goal: RUN_GOAL.into(), |
| 2017 | workspace: ws.clone(), |
| 2018 | }) |
| 2019 | .await; |
| 2020 | let cx = match &r { |
| 2021 | ControlResponse::ComposeTaskResult(rep) if aien_omega_compose::LINKED => { |
| 2022 | let v = serde_json::to_value(&**rep).unwrap(); |
| 2023 | assert_eq!(v["committed"], true, "{v}"); |
| 2024 | assert!(v["compose_commit"].as_u64().is_some(), "{v}"); |
| 2025 | v["cx_promotion"].as_u64().unwrap() |
| 2026 | } |
| 2027 | ControlResponse::Error(e) if !aien_omega_compose::LINKED => { |
| 2028 | assert!(e.ends_with("is not linked (stub build)"), "{e}"); |
| 2029 | 1 |
| 2030 | } |
| 2031 | other => panic!("unexpected run answer: {other:?}"), |
| 2032 | }; |
| 2033 | assert_eq!(h.state("b"), TaskState::Provisional); |
| 2034 | let desk = DeskKey::load(&desk_key_path(&home)).unwrap(); |
| 2035 | let grant = |nonce: &str| { |
| 2036 | let mac = desk.sign_authorize(&AuthorizeBinding { |
| 2037 | cx_promotion: cx, |
| 2038 | proposal_sha256: digest.clone(), |
| 2039 | path: PATH.into(), |
| 2040 | content_sha256: sha(RUN_CONTENT.as_bytes()), |
| 2041 | workspace: ws.clone(), |
| 2042 | approver: "drake".into(), |
| 2043 | constraints: vec![], |
| 2044 | nonce: nonce.into(), |
| 2045 | desk_key_id: desk.id().into(), |
| 2046 | }); |
| 2047 | ControlCommand::ComposeAuthorize { |
| 2048 | cx_promotion: cx, |
| 2049 | proposal_sha256: digest.clone(), |
| 2050 | workspace: ws.clone(), |
| 2051 | approver: "drake".into(), |
| 2052 | constraints: vec![], |
| 2053 | desk_proof: Some(DeskProof { |
| 2054 | nonce: nonce.into(), |
| 2055 | mac, |
| 2056 | }), |
| 2057 | objective_id: None, |
| 2058 | } |
| 2059 | }; |
| 2060 | |
| 2061 | // Bound, while B is provisional: the grant is the fenced call and is |
| 2062 | // refused; nothing is written. |
| 2063 | let before = (tree(Path::new(&ws)), tree(&home)); |
| 2064 | let r = send(grant("m3-run-early")).await; |
| 2065 | assert!(fence_refused(&r, "NotCommittable"), "{r:?}"); |
| 2066 | assert_eq!( |
| 2067 | (tree(Path::new(&ws)), tree(&home)), |
| 2068 | before, |
| 2069 | "a fenced grant wrote nothing" |
| 2070 | ); |
| 2071 | |
| 2072 | // Final: the grant passes the fence and the canonical mint decides. |
| 2073 | h.finish("a"); |
| 2074 | h.finish("b"); |
| 2075 | let r = send(grant("m3-run-final")).await; |
| 2076 | if aien_omega_compose::LINKED { |
| 2077 | match &r { |
| 2078 | ControlResponse::ComposeNoted(_) => {} |
| 2079 | other => panic!("want the grant minted, got {other:?}"), |
| 2080 | } |
| 2081 | assert_eq!(h.state("b"), TaskState::Committed); |
| 2082 | } else { |
| 2083 | match &r { |
| 2084 | ControlResponse::Error(e) => assert!( |
| 2085 | e.starts_with("compose home ") && e.ends_with("is not linked (stub build)"), |
| 2086 | "{e}" |
| 2087 | ), |
| 2088 | other => panic!("the stub authorize must refuse: {other:?}"), |
| 2089 | } |
| 2090 | // Not an `EFFECT_REFUSED`: classified uncertain (fail closed). |
| 2091 | assert_eq!(h.state("b"), TaskState::CommitUncertain); |
| 2092 | } |
| 2093 | // B ended: the binding is dropped and the retry is the original call. |
| 2094 | assert!(h.adapter.binding(&key).is_none()); |
| 2095 | let r = send(grant("m3-run-final")).await; |
| 2096 | match &r { |
| 2097 | ControlResponse::Error(e) if aien_omega_compose::LINKED => { |
| 2098 | assert!(e.starts_with("EFFECT_REFUSED "), "{e}") |
| 2099 | } |
| 2100 | ControlResponse::Error(e) => assert!(e.ends_with("is not linked (stub build)"), "{e}"), |
| 2101 | other => panic!("a second grant must be refused: {other:?}"), |
| 2102 | } |
| 2103 | |
| 2104 | let _ = client.send_command(ControlCommand::Shutdown).await; |
| 2105 | let _ = tokio::time::timeout(Duration::from_secs(5), server).await; |
| 2106 | } |
| 2107 | |
| 2108 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 2109 | async fn a_binding_survives_a_daemon_restart_and_the_request_stays_fenced() { |
| 2110 | let _home = home_guard::home_slot(); |
| 2111 | let c0 = cfg(true, 4); |
| 2112 | let mut h = H::journaled(c0.clone()); |
| 2113 | let c = Compose::new(&h); |
| 2114 | h.register("a", &[]); |
| 2115 | h.register("b", &["a"]); |
| 2116 | h.publish("a", 1); |
| 2117 | let bound = c.approval("req-bound-restart"); |
| 2118 | let free = c.approval("req-free-restart"); |
| 2119 | let key = FenceKey::Approval(bound.approval_id.clone()); |
| 2120 | h.adapter.bind_approval(key.clone(), "b", 1).unwrap(); |
| 2121 | // The daemon restarts: a new adapter replays the journal. |
| 2122 | let revoked = h.restart(c0); |
| 2123 | assert!(revoked.is_empty(), "{revoked:?}"); |
| 2124 | assert_eq!(h.adapter.binding(&key), Some(("b".to_string(), 1))); |
| 2125 | let socket = h.tmp.path().join("r.sock"); |
| 2126 | let (client, server) = daemon(&socket, c.bridge.clone(), h.adapter.clone()).await; |
| 2127 | let compose_dir = c.bridge.dir().to_path_buf(); |
| 2128 | let before = (tree(&h.ws()), tree(&compose_dir)); |
| 2129 | let r = client |
| 2130 | .send_command(ControlCommand::ComposeApprovedProposal { |
| 2131 | proposal: bound.clone(), |
| 2132 | workspace: c.ws.clone(), |
| 2133 | }) |
| 2134 | .await |
| 2135 | .unwrap(); |
| 2136 | assert!(fence_refused(&r, "NotCommittable"), "{r:?}"); |
| 2137 | assert_eq!( |
| 2138 | (tree(&h.ws()), tree(&compose_dir)), |
| 2139 | before, |
| 2140 | "the restarted daemon still fenced the bound request" |
| 2141 | ); |
| 2142 | // Control: an unbound approval runs the original call after the restart. |
| 2143 | let r = client |
| 2144 | .send_command(ControlCommand::ComposeApprovedProposal { |
| 2145 | proposal: free, |
| 2146 | workspace: c.ws.clone(), |
| 2147 | }) |
| 2148 | .await |
| 2149 | .unwrap(); |
| 2150 | assert!(canonical_approved(&r), "{r:?}"); |
| 2151 | let _ = client.send_command(ControlCommand::Shutdown).await; |
| 2152 | let _ = tokio::time::timeout(Duration::from_secs(5), server).await; |
| 2153 | } |
| 2154 | |
| 2155 | #[test] |
| 2156 | fn a_restart_during_a_commit_is_uncertain_and_never_runs_it_again() { |
| 2157 | let mut h = H::journaled(cfg(true, 4)); |
| 2158 | h.register("a", &[]); |
| 2159 | h.register("b", &["a"]); |
| 2160 | h.register("c", &["b"]); |
| 2161 | h.publish("a", 1); |
| 2162 | h.publish("b", 1); |
| 2163 | h.finish("a"); |
| 2164 | h.finish("b"); |
| 2165 | assert_eq!(h.state("c"), TaskState::Provisional); |
| 2166 | let journal = h.tmp.path().join("journal.jsonl"); |
| 2167 | let copy = h.tmp.path().join("journal-mid-commit.jsonl"); |
| 2168 | let store = h.engine.completion_store.clone(); |
| 2169 | let ticks = Arc::clone(&h.ticks); |
| 2170 | // The daemon dies while the commit runs: its journal at that moment is |
| 2171 | // opened by a new process. |
| 2172 | let out = h |
| 2173 | .adapter |
| 2174 | .fenced_for_tests( |
| 2175 | "b", |
| 2176 | 1, |
| 2177 | |_| { |
| 2178 | std::fs::copy(&journal, ©).unwrap(); |
| 2179 | // The audit's own revocations: settling the interrupted |
| 2180 | // commit is not one of them (its consumers are revoked by |
| 2181 | // the settled outcome itself, checked below). |
| 2182 | let (a, _audit) = |
| 2183 | PrepAdapter::open(cfg(true, 4), &store, ©, clock(&ticks)).unwrap(); |
| 2184 | let mut ran = false; |
| 2185 | let again = a.fenced_for_tests("b", 1, |_| ran = true, committed).err(); |
| 2186 | (a.state("b"), a.generation("c"), again, ran) |
| 2187 | }, |
| 2188 | committed, |
| 2189 | ) |
| 2190 | .unwrap(); |
| 2191 | let (state, gen_c, again, ran) = out.outcome; |
| 2192 | assert_eq!(state, Some(TaskState::CommitUncertain)); |
| 2193 | assert_eq!(gen_c, Some(2), "the consumer was revoked"); |
| 2194 | assert!( |
| 2195 | matches!( |
| 2196 | again, |
| 2197 | Some(FenceError::NotCommittable { |
| 2198 | state: TaskState::CommitUncertain, |
| 2199 | .. |
| 2200 | }) |
| 2201 | ), |
| 2202 | "{again:?}" |
| 2203 | ); |
| 2204 | assert!(!ran, "the restarted process ran nothing"); |
| 2205 | // The process that did not die records its outcome as usual. |
| 2206 | assert_eq!(h.state("b"), TaskState::Committed); |
| 2207 | } |
| 2208 | |
| 2209 | #[test] |
| 2210 | fn a_revoke_during_a_commit_is_applied_after_the_outcome() { |
| 2211 | let mut h = H::new(cfg(true, 4)); |
| 2212 | h.register("a", &[]); |
| 2213 | h.register("b", &["a"]); |
| 2214 | h.register("d", &["a"]); |
| 2215 | h.publish("a", 1); |
| 2216 | h.finish("a"); |
| 2217 | h.finish("b"); |
| 2218 | assert_eq!(h.state("d"), TaskState::Provisional); |
| 2219 | h.prepare("d").unwrap(); |
| 2220 | let adapter = Arc::clone(&h.adapter); |
| 2221 | let revoke = |id: &str, reason: &str| Event { |
| 2222 | id: id.into(), |
| 2223 | kind: EventKind::Revoke { |
| 2224 | task: "a".into(), |
| 2225 | generation: 1, |
| 2226 | reason: reason.into(), |
| 2227 | }, |
| 2228 | }; |
| 2229 | let out = h |
| 2230 | .adapter |
| 2231 | .fenced_for_tests( |
| 2232 | "b", |
| 2233 | 1, |
| 2234 | |_| { |
| 2235 | let first = adapter.deliver(revoke("revoke-a", "withdrawn")); |
| 2236 | let again = adapter.deliver(revoke("revoke-a", "withdrawn")); |
| 2237 | let conflict = adapter.deliver(revoke("revoke-a", "other reason")); |
| 2238 | let d = ( |
| 2239 | adapter.state("d"), |
| 2240 | adapter.generation("d"), |
| 2241 | adapter.prepared("d").is_some(), |
| 2242 | ); |
| 2243 | (first, again, conflict, d, adapter.deferred_len()) |
| 2244 | }, |
| 2245 | committed, |
| 2246 | ) |
| 2247 | .unwrap(); |
| 2248 | let (first, again, conflict, d, queued) = out.outcome; |
| 2249 | let deferred = Delivered::Deferred { |
| 2250 | committing: "b".into(), |
| 2251 | queued: 1, |
| 2252 | }; |
| 2253 | assert_eq!(first.unwrap(), deferred); |
| 2254 | assert_eq!(again.unwrap(), deferred, "a redelivery is not queued twice"); |
| 2255 | assert!( |
| 2256 | matches!( |
| 2257 | conflict, |
| 2258 | Err(DeliverError::Scheduler(SchedError::EventIdConflict(_))) |
| 2259 | ), |
| 2260 | "{conflict:?}" |
| 2261 | ); |
| 2262 | assert_eq!( |
| 2263 | d, |
| 2264 | (Some(TaskState::Provisional), Some(1), true), |
| 2265 | "nothing applied while b commits" |
| 2266 | ); |
| 2267 | assert_eq!(queued, 1); |
| 2268 | // After the outcome: the revoke applied and invalidated the other |
| 2269 | // consumer; the committed task is not reached. |
| 2270 | assert_eq!(out.redelivered.len(), 1); |
| 2271 | assert_eq!(out.redelivered[0].id, "revoke-a"); |
| 2272 | match &out.redelivered[0].result { |
| 2273 | Ok(Outcome::Applied(fx)) => assert!(fx.revoked.contains(&"d".to_string()), "{fx:?}"), |
| 2274 | other => panic!("want the revoke applied, got {other:?}"), |
| 2275 | } |
| 2276 | assert_eq!(h.adapter.deferred_len(), 0); |
| 2277 | assert_eq!(h.gen("d"), 2); |
| 2278 | assert!( |
| 2279 | h.adapter.prepared("d").is_none(), |
| 2280 | "the result was discarded" |
| 2281 | ); |
| 2282 | assert_eq!((h.state("b"), h.gen("b")), (TaskState::Committed, 1)); |
| 2283 | } |
| 2284 | |
| 2285 | #[test] |
| 2286 | fn an_event_held_by_another_running_commit_stays_queued() { |
| 2287 | let mut h = H::new(cfg(true, 8)); |
| 2288 | // Two independent chains: a -> b and x -> y. |
| 2289 | for (p, c) in [("a", "b"), ("x", "y")] { |
| 2290 | h.register(p, &[]); |
| 2291 | h.register(c, &[p]); |
| 2292 | h.publish(p, 1); |
| 2293 | h.finish(p); |
| 2294 | h.finish(c); |
| 2295 | } |
| 2296 | let adapter = Arc::clone(&h.adapter); |
| 2297 | let out = h |
| 2298 | .adapter |
| 2299 | .fenced_for_tests( |
| 2300 | "y", |
| 2301 | 1, |
| 2302 | |_| { |
| 2303 | // Held back by y's commit. |
| 2304 | let held = adapter.deliver(Event { |
| 2305 | id: "revoke-x".into(), |
| 2306 | kind: EventKind::Revoke { |
| 2307 | task: "x".into(), |
| 2308 | generation: 1, |
| 2309 | reason: "withdrawn".into(), |
| 2310 | }, |
| 2311 | }); |
| 2312 | // b's whole commit runs and ends while y still commits: its |
| 2313 | // drain must keep the event y still refuses. |
| 2314 | let b = adapter |
| 2315 | .fenced_for_tests("b", 1, |_| (), committed) |
| 2316 | .map(|f| f.redelivered.len()); |
| 2317 | (held, b, adapter.deferred_len(), adapter.generation("x")) |
| 2318 | }, |
| 2319 | committed, |
| 2320 | ) |
| 2321 | .unwrap(); |
| 2322 | let (held, b, queued, gen_x) = out.outcome; |
| 2323 | assert!( |
| 2324 | matches!(held, Ok(Delivered::Deferred { ref committing, .. }) if committing == "y"), |
| 2325 | "{held:?}" |
| 2326 | ); |
| 2327 | assert_eq!(b.unwrap(), 0, "nothing was reported by b's drain"); |
| 2328 | assert_eq!((queued, gen_x), (1, Some(1)), "still queued, not applied"); |
| 2329 | // y's outcome delivers it. |
| 2330 | assert_eq!(out.redelivered.len(), 1); |
| 2331 | assert_eq!(out.redelivered[0].id, "revoke-x"); |
| 2332 | assert!(matches!(out.redelivered[0].result, Ok(Outcome::Applied(_)))); |
| 2333 | assert_eq!(h.adapter.deferred_len(), 0); |
| 2334 | assert_eq!( |
| 2335 | (h.state("b"), h.state("y")), |
| 2336 | (TaskState::Committed, TaskState::Committed) |
| 2337 | ); |
| 2338 | } |
| 2339 | |
| 2340 | #[test] |
| 2341 | fn the_deferred_queue_is_bounded_and_fails_closed() { |
| 2342 | let mut h = H::new(cfg(true, 4)); |
| 2343 | h.register("a", &[]); |
| 2344 | h.register("b", &["a"]); |
| 2345 | h.publish("a", 1); |
| 2346 | h.finish("a"); |
| 2347 | h.finish("b"); |
| 2348 | let adapter = Arc::clone(&h.adapter); |
| 2349 | let out = h |
| 2350 | .adapter |
| 2351 | .fenced_for_tests( |
| 2352 | "b", |
| 2353 | 1, |
| 2354 | |_| { |
| 2355 | let mut answers = Vec::new(); |
| 2356 | for i in 0..=DEFERRED_CAPACITY { |
| 2357 | answers.push(adapter.deliver(Event { |
| 2358 | id: format!("revoke-{i}"), |
| 2359 | kind: EventKind::Revoke { |
| 2360 | task: "a".into(), |
| 2361 | generation: 1, |
| 2362 | reason: format!("withdrawn {i}"), |
| 2363 | }, |
| 2364 | })); |
| 2365 | } |
| 2366 | answers |
| 2367 | }, |
| 2368 | committed, |
| 2369 | ) |
| 2370 | .unwrap(); |
| 2371 | for (i, a) in out.outcome[..DEFERRED_CAPACITY].iter().enumerate() { |
| 2372 | match a { |
| 2373 | Ok(Delivered::Deferred { queued, .. }) => assert_eq!(*queued, i + 1), |
| 2374 | other => panic!("event {i}: want Deferred, got {other:?}"), |
| 2375 | } |
| 2376 | } |
| 2377 | match &out.outcome[DEFERRED_CAPACITY] { |
| 2378 | Err(DeliverError::DeferredFull { |
| 2379 | committing, |
| 2380 | capacity, |
| 2381 | }) => assert_eq!((committing.as_str(), *capacity), ("b", DEFERRED_CAPACITY)), |
| 2382 | other => panic!("want DeferredFull, got {other:?}"), |
| 2383 | } |
| 2384 | // Every queued event is delivered again and reported, oldest first; the |
| 2385 | // refused one was never queued. |
| 2386 | let ids: Vec<String> = out.redelivered.iter().map(|r| r.id.clone()).collect(); |
| 2387 | let want: Vec<String> = (0..DEFERRED_CAPACITY) |
| 2388 | .map(|i| format!("revoke-{i}")) |
| 2389 | .collect(); |
| 2390 | assert_eq!(ids, want); |
| 2391 | assert!(matches!(out.redelivered[0].result, Ok(Outcome::Applied(_)))); |
| 2392 | // The first revoke moved a to generation 2, so the rest are refused as |
| 2393 | // stale. Refused redeliveries are kept (never dropped) until discarded. |
| 2394 | assert!(out.redelivered[1..] |
| 2395 | .iter() |
| 2396 | .all(|r| matches!(r.result, Err(SchedError::StaleGeneration { .. })))); |
| 2397 | assert_eq!(h.adapter.deferred_len(), DEFERRED_CAPACITY - 1); |
| 2398 | assert_eq!(h.state("b"), TaskState::Committed); |
| 2399 | } |
| 2400 | |
| 2401 | #[test] |
| 2402 | fn the_fence_events_are_refused_by_deliver() { |
| 2403 | let mut h = H::new(cfg(true, 4)); |
| 2404 | h.register("a", &[]); |
| 2405 | h.register("b", &["a"]); |
| 2406 | h.publish("a", 1); |
| 2407 | h.finish("a"); |
| 2408 | h.finish("b"); |
| 2409 | let claim = h |
| 2410 | .adapter |
| 2411 | .inspect(|s| s.task("b").unwrap().completion.clone().unwrap()); |
| 2412 | let kinds = [ |
| 2413 | ( |
| 2414 | "begin_commit", |
| 2415 | EventKind::BeginCommit { |
| 2416 | task: "b".into(), |
| 2417 | generation: 1, |
| 2418 | completion: claim, |
| 2419 | producers: BTreeMap::new(), |
| 2420 | }, |
| 2421 | ), |
| 2422 | ( |
| 2423 | "commit_outcome", |
| 2424 | EventKind::CommitOutcome { |
| 2425 | task: "b".into(), |
| 2426 | generation: 1, |
| 2427 | outcome: committed(&()), |
| 2428 | }, |
| 2429 | ), |
| 2430 | ( |
| 2431 | "bind_approval", |
| 2432 | EventKind::BindApproval { |
| 2433 | key: "approval:x".into(), |
| 2434 | task: "b".into(), |
| 2435 | generation: 1, |
| 2436 | }, |
| 2437 | ), |
| 2438 | ]; |
| 2439 | for (name, kind) in kinds { |
| 2440 | match h.deliver(kind) { |
| 2441 | Err(DeliverError::FenceOnly(k)) => assert_eq!(k, name), |
| 2442 | other => panic!("{name}: want FenceOnly, got {other:?}"), |
| 2443 | } |
| 2444 | } |
| 2445 | assert_eq!(h.state("b"), TaskState::Committable); |
| 2446 | assert!(h.adapter.binding(&FenceKey::Approval("x".into())).is_none()); |
| 2447 | // Control: an ordinary event is delivered. |
| 2448 | assert!(matches!( |
| 2449 | h.deliver(EventKind::Tick), |
| 2450 | Ok(Delivered::Applied(_)) |
| 2451 | )); |
| 2452 | } |
| 2453 | |
| 2454 | #[test] |
| 2455 | fn begin_commit_holds_the_store_writers_out() { |
| 2456 | let mut h = H::new(cfg(true, 4)); |
| 2457 | h.register("a", &[]); |
| 2458 | h.register("b", &["a"]); |
| 2459 | h.publish("a", 1); |
| 2460 | h.finish("a"); |
| 2461 | h.finish("b"); |
| 2462 | let store_dir = h.tmp.path().join("harness"); |
| 2463 | // A writer for a task M2 does not know: it takes the same store lock |
| 2464 | // but changes nothing the fence verifies. |
| 2465 | let writer = move |version: u32| { |
| 2466 | let (tx, rx) = mpsc::channel(); |
| 2467 | let dir = store_dir.clone(); |
| 2468 | std::thread::spawn(move || { |
| 2469 | let mut e = HarnessEngine::load(&dir).unwrap(); |
| 2470 | e.completion_clock = fixed_receipt_clock; |
| 2471 | let r = e.publish_interface(&InterfaceSubmission { |
| 2472 | task_id: "outside".into(), |
| 2473 | generation: 1, |
| 2474 | source_commit: COMMIT.into(), |
| 2475 | interface: json!({ "task": "outside", "api_version": version }), |
| 2476 | }); |
| 2477 | tx.send(r.map(|_| ()).map_err(|e| e.to_string())).unwrap(); |
| 2478 | }); |
| 2479 | rx |
| 2480 | }; |
| 2481 | // Control: with no fence running, the writer finishes at once. |
| 2482 | writer(7) |
| 2483 | .recv_timeout(Duration::from_secs(10)) |
| 2484 | .expect("writer runs") |
| 2485 | .unwrap(); |
| 2486 | let (entered_tx, entered_rx) = mpsc::channel::<()>(); |
| 2487 | let (release_tx, release_rx) = mpsc::channel::<()>(); |
| 2488 | let release_rx = std::sync::Mutex::new(release_rx); |
| 2489 | let entered_tx = std::sync::Mutex::new(entered_tx); |
| 2490 | h.adapter.set_begin_hook(Some(Arc::new(move |_: &str| { |
| 2491 | entered_tx.lock().unwrap().send(()).unwrap(); |
| 2492 | let _ = release_rx |
| 2493 | .lock() |
| 2494 | .unwrap() |
| 2495 | .recv_timeout(Duration::from_secs(10)); |
| 2496 | }))); |
| 2497 | let a2 = Arc::clone(&h.adapter); |
| 2498 | let fence = std::thread::spawn(move || { |
| 2499 | a2.fenced_for_tests("b", 1, |_| (), committed) |
| 2500 | .map(|f| f.result) |
| 2501 | .map_err(|e| e.to_string()) |
| 2502 | }); |
| 2503 | entered_rx |
| 2504 | .recv_timeout(Duration::from_secs(10)) |
| 2505 | .expect("the fence reached its hook"); |
| 2506 | // Inside begin_commit, between the checks and the journaled transition: |
| 2507 | // a store writer must wait. |
| 2508 | let rx = writer(8); |
| 2509 | assert!( |
| 2510 | matches!( |
| 2511 | rx.recv_timeout(Duration::from_millis(300)), |
| 2512 | Err(mpsc::RecvTimeoutError::Timeout) |
| 2513 | ), |
| 2514 | "a store writer ran inside begin_commit" |
| 2515 | ); |
| 2516 | release_tx.send(()).unwrap(); |
| 2517 | rx.recv_timeout(Duration::from_secs(10)) |
| 2518 | .expect("the writer runs once the fence releases its locks") |
| 2519 | .unwrap(); |
| 2520 | assert_eq!(fence.join().unwrap().unwrap(), committed(&())); |
| 2521 | h.adapter.set_begin_hook(None); |
| 2522 | } |
| 2523 | |
| 2524 | // ---------- the journaled deferred queue ---------- |
| 2525 | |
| 2526 | fn revoke_a(id: &str) -> Event { |
| 2527 | Event { |
| 2528 | id: id.into(), |
| 2529 | kind: EventKind::Revoke { |
| 2530 | task: "a".into(), |
| 2531 | generation: 1, |
| 2532 | reason: "withdrawn".into(), |
| 2533 | }, |
| 2534 | } |
| 2535 | } |
| 2536 | |
| 2537 | #[test] |
| 2538 | fn a_revoke_deferred_by_a_commit_that_crashed_is_applied_on_open() { |
| 2539 | let mut h = H::journaled(cfg(true, 4)); |
| 2540 | h.register("a", &[]); |
| 2541 | h.register("b", &["a"]); |
| 2542 | h.register("d", &["a"]); |
| 2543 | h.publish("a", 1); |
| 2544 | h.finish("a"); |
| 2545 | h.finish("b"); |
| 2546 | assert_eq!(h.state("d"), TaskState::Provisional); |
| 2547 | let journal = h.tmp.path().join("journal.jsonl"); |
| 2548 | let sidecar = deferred_journal_path(&journal); |
| 2549 | let copy = h.tmp.path().join("journal-crash.jsonl"); |
| 2550 | let bare = h.tmp.path().join("journal-crash-no-sidecar.jsonl"); |
| 2551 | let store = h.engine.completion_store.clone(); |
| 2552 | let ticks = Arc::clone(&h.ticks); |
| 2553 | let adapter = Arc::clone(&h.adapter); |
| 2554 | let out = h |
| 2555 | .adapter |
| 2556 | .fenced_for_tests( |
| 2557 | "b", |
| 2558 | 1, |
| 2559 | |_| { |
| 2560 | let deferred = adapter.deliver(revoke_a("revoke-a")); |
| 2561 | // The daemon dies here, before the drain: the journal and |
| 2562 | // its sidecar as they are now. |
| 2563 | std::fs::copy(&journal, ©).unwrap(); |
| 2564 | std::fs::copy(&sidecar, deferred_journal_path(©)).unwrap(); |
| 2565 | std::fs::copy(&journal, &bare).unwrap(); |
| 2566 | let (a, _audit) = |
| 2567 | PrepAdapter::open(cfg(true, 4), &store, ©, clock(&ticks)).unwrap(); |
| 2568 | let replayed = a.take_replayed_deferred(); |
| 2569 | let again = a.take_replayed_deferred().len(); |
| 2570 | let reopened = ( |
| 2571 | a.state("b"), |
| 2572 | a.generation("d"), |
| 2573 | a.deferred_len(), |
| 2574 | std::fs::read_to_string(deferred_journal_path(©)).unwrap(), |
| 2575 | ); |
| 2576 | // Negative control: the same crash without the sidecar |
| 2577 | // loses the revoke. |
| 2578 | let (n, _audit) = |
| 2579 | PrepAdapter::open(cfg(true, 4), &store, &bare, clock(&ticks)).unwrap(); |
| 2580 | let control = (n.generation("d"), n.take_replayed_deferred().len()); |
| 2581 | (deferred, replayed, again, reopened, control) |
| 2582 | }, |
| 2583 | committed, |
| 2584 | ) |
| 2585 | .unwrap(); |
| 2586 | let (deferred, replayed, again, reopened, control) = out.outcome; |
| 2587 | assert!( |
| 2588 | matches!(deferred, Ok(Delivered::Deferred { ref committing, .. }) if committing == "b"), |
| 2589 | "{deferred:?}" |
| 2590 | ); |
| 2591 | // Reopened: the interrupted commit settled first, then the revoke. |
| 2592 | assert_eq!(replayed.len(), 1); |
| 2593 | assert_eq!(replayed[0].id, "revoke-a"); |
| 2594 | match &replayed[0].result { |
| 2595 | Ok(Outcome::Applied(fx)) => assert!(fx.revoked.contains(&"d".to_string()), "{fx:?}"), |
| 2596 | other => panic!("want the revoke applied, got {other:?}"), |
| 2597 | } |
| 2598 | assert_eq!(again, 0, "taken once"); |
| 2599 | assert_eq!( |
| 2600 | reopened, |
| 2601 | (Some(TaskState::CommitUncertain), Some(2), 0, String::new()) |
| 2602 | ); |
| 2603 | assert_eq!(control, (Some(1), 0)); |
| 2604 | // The process that did not die drained it as usual and emptied the |
| 2605 | // sidecar. |
| 2606 | assert_eq!(out.redelivered.len(), 1); |
| 2607 | assert!(out.deferred_error.is_none()); |
| 2608 | assert_eq!(h.gen("d"), 2); |
| 2609 | assert_eq!(std::fs::read_to_string(&sidecar).unwrap(), ""); |
| 2610 | // A second open of the drained journal replays nothing. |
| 2611 | drop(adapter); |
| 2612 | let n = h.restart(cfg(true, 4)); |
| 2613 | assert!(n.is_empty(), "{n:?}"); |
| 2614 | assert!(h.adapter.take_replayed_deferred().is_empty()); |
| 2615 | assert_eq!(h.gen("d"), 2); |
| 2616 | } |
| 2617 | |
| 2618 | #[test] |
| 2619 | fn a_bad_deferred_sidecar_fails_the_open() { |
| 2620 | let h = H::journaled(cfg(true, 4)); |
| 2621 | let copy = h.tmp.path().join("journal-copy.jsonl"); |
| 2622 | std::fs::copy(h.tmp.path().join("journal.jsonl"), ©).unwrap(); |
| 2623 | let side = deferred_journal_path(©); |
| 2624 | let store = h.engine.completion_store.clone(); |
| 2625 | let ticks = Arc::clone(&h.ticks); |
| 2626 | let open = || PrepAdapter::open(cfg(true, 4), &store, ©, clock(&ticks)); |
| 2627 | let lines = |events: Vec<Event>| -> String { |
| 2628 | events |
| 2629 | .iter() |
| 2630 | .map(|e| serde_json::to_string(e).unwrap() + "\n") |
| 2631 | .collect() |
| 2632 | }; |
| 2633 | let revokes = |
| 2634 | |n: usize| -> Vec<Event> { (0..n).map(|i| revoke_a(&format!("revoke-{i}"))).collect() }; |
| 2635 | let bind = Event { |
| 2636 | id: "bind-x".into(), |
| 2637 | kind: EventKind::BindApproval { |
| 2638 | key: "approval:x".into(), |
| 2639 | task: "a".into(), |
| 2640 | generation: 1, |
| 2641 | }, |
| 2642 | }; |
| 2643 | let reason = "r".repeat(DEFERRED_MAX_BYTES as usize / DEFERRED_CAPACITY + 1); |
| 2644 | let large: Vec<Event> = (0..DEFERRED_CAPACITY) |
| 2645 | .map(|i| Event { |
| 2646 | id: format!("large-{i}"), |
| 2647 | kind: EventKind::Revoke { |
| 2648 | task: "a".into(), |
| 2649 | generation: 1, |
| 2650 | reason: reason.clone(), |
| 2651 | }, |
| 2652 | }) |
| 2653 | .collect(); |
| 2654 | for (what, text) in [ |
| 2655 | ("not json", "not json\n".to_string()), |
| 2656 | ("over the cap", lines(revokes(DEFERRED_CAPACITY + 1))), |
| 2657 | ("fence-only", lines(vec![bind])), |
| 2658 | // Well-formed and under the event cap, but over the byte cap. |
| 2659 | ("too large", lines(large)), |
| 2660 | ] { |
| 2661 | std::fs::write(&side, text).unwrap(); |
| 2662 | match open() { |
| 2663 | Err(SchedError::Journal(e)) => assert!(e.contains("deferred"), "{what}: {e}"), |
| 2664 | Err(e) => panic!("{what}: want a journal error, got {e}"), |
| 2665 | Ok(_) => panic!("{what}: the open must fail"), |
| 2666 | } |
| 2667 | } |
| 2668 | // Control: exactly the cap opens and every event is delivered. Each is |
| 2669 | // refused here (no task is registered), reported, and kept queued and |
| 2670 | // journaled until it is discarded. |
| 2671 | let full = lines(revokes(DEFERRED_CAPACITY)); |
| 2672 | std::fs::write(&side, &full).unwrap(); |
| 2673 | let (a, _) = open().unwrap(); |
| 2674 | let replayed = a.take_replayed_deferred(); |
| 2675 | assert_eq!(replayed.len(), DEFERRED_CAPACITY); |
| 2676 | assert!(replayed |
| 2677 | .iter() |
| 2678 | .all(|r| matches!(r.result, Err(SchedError::UnknownTask(_))))); |
| 2679 | assert_eq!(a.deferred_len(), DEFERRED_CAPACITY); |
| 2680 | assert_eq!(std::fs::read_to_string(&side).unwrap(), full); |
| 2681 | for i in 0..DEFERRED_CAPACITY { |
| 2682 | let id = format!("revoke-{i}"); |
| 2683 | let ev = a.discard_deferred(&id).unwrap().expect("queued"); |
| 2684 | assert_eq!(ev.id, id); |
| 2685 | } |
| 2686 | assert_eq!(a.deferred_len(), 0); |
| 2687 | assert_eq!(std::fs::read_to_string(&side).unwrap(), ""); |
| 2688 | } |
| 2689 | |
| 2690 | #[test] |
| 2691 | fn a_deferred_event_that_cannot_be_journaled_is_refused() { |
| 2692 | let mut h = H::journaled(cfg(true, 4)); |
| 2693 | h.register("a", &[]); |
| 2694 | h.register("b", &["a"]); |
| 2695 | h.publish("a", 1); |
| 2696 | h.finish("a"); |
| 2697 | h.finish("b"); |
| 2698 | let side = deferred_journal_path(&h.tmp.path().join("journal.jsonl")); |
| 2699 | // A non-empty directory where the sidecar goes: the rename fails. |
| 2700 | std::fs::create_dir_all(side.join("block")).unwrap(); |
| 2701 | let adapter = Arc::clone(&h.adapter); |
| 2702 | let out = h |
| 2703 | .adapter |
| 2704 | .fenced_for_tests( |
| 2705 | "b", |
| 2706 | 1, |
| 2707 | |_| { |
| 2708 | ( |
| 2709 | adapter.deliver(revoke_a("revoke-a")), |
| 2710 | adapter.deferred_len(), |
| 2711 | ) |
| 2712 | }, |
| 2713 | committed, |
| 2714 | ) |
| 2715 | .unwrap(); |
| 2716 | let (r, queued) = out.outcome; |
| 2717 | assert!(matches!(r, Err(DeliverError::DeferredJournal(_))), "{r:?}"); |
| 2718 | assert_eq!(queued, 0, "nothing was queued"); |
| 2719 | assert!(out.redelivered.is_empty()); |
| 2720 | assert_eq!(h.gen("a"), 1, "and nothing applied"); |
| 2721 | // Control: with the sidecar writable the same event applies. |
| 2722 | std::fs::remove_dir_all(&side).unwrap(); |
| 2723 | assert!(matches!( |
| 2724 | h.adapter.deliver(revoke_a("revoke-a")), |
| 2725 | Ok(Delivered::Applied(_)) |
| 2726 | )); |
| 2727 | assert_eq!(h.gen("a"), 2); |
| 2728 | } |
| 2729 | |
| 2730 | #[test] |
| 2731 | fn a_failed_sidecar_rewrite_after_the_drain_is_reported() { |
| 2732 | let mut h = H::journaled(cfg(true, 4)); |
| 2733 | h.register("a", &[]); |
| 2734 | h.register("b", &["a"]); |
| 2735 | h.register("d", &["a"]); |
| 2736 | h.publish("a", 1); |
| 2737 | h.finish("a"); |
| 2738 | h.finish("b"); |
| 2739 | let side = deferred_journal_path(&h.tmp.path().join("journal.jsonl")); |
| 2740 | let adapter = Arc::clone(&h.adapter); |
| 2741 | let out = h |
| 2742 | .adapter |
| 2743 | .fenced_for_tests( |
| 2744 | "b", |
| 2745 | 1, |
| 2746 | |_| { |
| 2747 | let r = adapter.deliver(revoke_a("revoke-a")); |
| 2748 | // The sidecar becomes unwritable before the drain. |
| 2749 | std::fs::remove_file(&side).unwrap(); |
| 2750 | std::fs::create_dir_all(side.join("block")).unwrap(); |
| 2751 | r |
| 2752 | }, |
| 2753 | committed, |
| 2754 | ) |
| 2755 | .unwrap(); |
| 2756 | assert!(matches!(out.outcome, Ok(Delivered::Deferred { .. }))); |
| 2757 | // The revoke still applied; the failed rewrite is reported. |
| 2758 | assert_eq!(out.redelivered.len(), 1); |
| 2759 | assert!(matches!(out.redelivered[0].result, Ok(Outcome::Applied(_)))); |
| 2760 | assert_eq!(h.gen("d"), 2); |
| 2761 | let e = out.deferred_error.expect("the rewrite failure is reported"); |
| 2762 | assert!(e.contains("deferred"), "{e}"); |
| 2763 | } |
| 2764 | |
| 2765 | #[test] |
| 2766 | fn an_open_whose_sidecar_cannot_be_rewritten_fails() { |
| 2767 | let mut h = H::journaled(cfg(true, 4)); |
| 2768 | // a is registered, so the deferred revoke applies on open and the |
| 2769 | // sidecar must be rewritten without it. |
| 2770 | h.register("a", &[]); |
| 2771 | let dir = h.tmp.path().join("ro"); |
| 2772 | std::fs::create_dir_all(&dir).unwrap(); |
| 2773 | let copy = dir.join("j.jsonl"); |
| 2774 | std::fs::copy(h.tmp.path().join("journal.jsonl"), ©).unwrap(); |
| 2775 | let side = deferred_journal_path(©); |
| 2776 | std::fs::write( |
| 2777 | &side, |
| 2778 | serde_json::to_string(&revoke_a("revoke-a")).unwrap() + "\n", |
| 2779 | ) |
| 2780 | .unwrap(); |
| 2781 | let store = h.engine.completion_store.clone(); |
| 2782 | let ticks = Arc::clone(&h.ticks); |
| 2783 | let open = || PrepAdapter::open(cfg(true, 4), &store, ©, clock(&ticks)); |
| 2784 | // A directory where the rewrite's temp file goes: the journal opens and |
| 2785 | // locks as usual, only the sidecar rewrite fails. |
| 2786 | let blocker = dir.join(format!(".j.jsonl.deferred.tmp-{}", std::process::id())); |
| 2787 | std::fs::create_dir_all(blocker.join("x")).unwrap(); |
| 2788 | match open() { |
| 2789 | Err(SchedError::Journal(e)) => assert!(e.contains("j.jsonl.deferred"), "{e}"), |
| 2790 | Err(e) => panic!("want the sidecar rewrite error, got {e}"), |
| 2791 | Ok(_) => panic!("the open must fail when the sidecar cannot be rewritten"), |
| 2792 | } |
| 2793 | // Control: without the blocker, the same open succeeds. The failed |
| 2794 | // open had journaled the revoke before its rewrite failed, so a is at |
| 2795 | // generation 2 once, and the redelivered copy is refused as stale and |
| 2796 | // kept (never dropped) until it is discarded. |
| 2797 | std::fs::remove_dir_all(&blocker).unwrap(); |
| 2798 | let (a, _) = open().unwrap(); |
| 2799 | assert_eq!(a.generation("a"), Some(2)); |
| 2800 | let replayed = a.take_replayed_deferred(); |
| 2801 | assert_eq!(replayed.len(), 1); |
| 2802 | assert!( |
| 2803 | matches!(replayed[0].result, Err(SchedError::StaleGeneration { .. })), |
| 2804 | "{:?}", |
| 2805 | replayed[0].result |
| 2806 | ); |
| 2807 | assert_eq!(a.deferred_len(), 1); |
| 2808 | assert!(a.discard_deferred("revoke-a").unwrap().is_some()); |
| 2809 | assert_eq!(std::fs::read_to_string(&side).unwrap(), ""); |
| 2810 | } |
| 2811 | |
| 2812 | #[test] |
| 2813 | fn a_refused_redelivery_stays_queued_until_discarded() { |
| 2814 | let mut h = H::journaled(cfg(true, 4)); |
| 2815 | h.register("a", &[]); |
| 2816 | h.register("b", &["a"]); |
| 2817 | h.publish("a", 1); |
| 2818 | h.finish("a"); |
| 2819 | h.finish("b"); |
| 2820 | let side = deferred_journal_path(&h.tmp.path().join("journal.jsonl")); |
| 2821 | // A cancel of b while b commits is refused with CommitInProgress and |
| 2822 | // deferred. |
| 2823 | let cancel_b = Event { |
| 2824 | id: "cancel-b".into(), |
| 2825 | kind: EventKind::Cancel { |
| 2826 | task: "b".into(), |
| 2827 | generation: 1, |
| 2828 | }, |
| 2829 | }; |
| 2830 | let line = serde_json::to_string(&cancel_b).unwrap() + "\n"; |
| 2831 | let adapter = Arc::clone(&h.adapter); |
| 2832 | let ev = cancel_b.clone(); |
| 2833 | let out = h |
| 2834 | .adapter |
| 2835 | .fenced_for_tests("b", 1, |_| adapter.deliver(ev), committed) |
| 2836 | .unwrap(); |
| 2837 | assert!( |
| 2838 | matches!(out.outcome, Ok(Delivered::Deferred { ref committing, .. }) if committing == "b"), |
| 2839 | "{:?}", |
| 2840 | out.outcome |
| 2841 | ); |
| 2842 | // Redelivered after the commit: b is committed, so the cancel is |
| 2843 | // refused (a committed task cannot abort). It is reported and kept, in memory and in the sidecar. |
| 2844 | assert_eq!(h.state("b"), TaskState::Committed); |
| 2845 | assert_eq!(out.redelivered.len(), 1); |
| 2846 | assert!( |
| 2847 | matches!(out.redelivered[0].result, Err(SchedError::Transition(_))), |
| 2848 | "{:?}", |
| 2849 | out.redelivered[0].result |
| 2850 | ); |
| 2851 | assert!(out.deferred_error.is_none()); |
| 2852 | let queued: Vec<String> = h |
| 2853 | .adapter |
| 2854 | .deferred_events() |
| 2855 | .into_iter() |
| 2856 | .map(|e| e.id) |
| 2857 | .collect(); |
| 2858 | assert_eq!(queued, vec!["cancel-b".to_string()]); |
| 2859 | assert_eq!(std::fs::read_to_string(&side).unwrap(), line); |
| 2860 | // A restart replays it again: refused again, still kept. |
| 2861 | drop(adapter); |
| 2862 | h.restart(cfg(true, 4)); |
| 2863 | let replayed = h.adapter.take_replayed_deferred(); |
| 2864 | assert_eq!(replayed.len(), 1); |
| 2865 | assert_eq!(replayed[0].id, "cancel-b"); |
| 2866 | assert!( |
| 2867 | matches!(replayed[0].result, Err(SchedError::Transition(_))), |
| 2868 | "{:?}", |
| 2869 | replayed[0].result |
| 2870 | ); |
| 2871 | assert_eq!(h.adapter.deferred_len(), 1); |
| 2872 | assert_eq!(std::fs::read_to_string(&side).unwrap(), line); |
| 2873 | // Only an explicit discard removes it, and the removal is journaled. |
| 2874 | assert!(h.adapter.discard_deferred("unknown").unwrap().is_none()); |
| 2875 | assert_eq!(h.adapter.deferred_len(), 1); |
| 2876 | let gone = h.adapter.discard_deferred("cancel-b").unwrap(); |
| 2877 | assert_eq!(gone.map(|e| e.id), Some("cancel-b".to_string())); |
| 2878 | assert_eq!(h.adapter.deferred_len(), 0); |
| 2879 | assert_eq!(std::fs::read_to_string(&side).unwrap(), ""); |
| 2880 | assert!(h.adapter.discard_deferred("cancel-b").unwrap().is_none()); |
| 2881 | h.restart(cfg(true, 4)); |
| 2882 | assert!(h.adapter.take_replayed_deferred().is_empty()); |
| 2883 | } |
| 2884 | |
| 2885 | #[test] |
| 2886 | fn a_discard_that_cannot_be_journaled_keeps_the_event() { |
| 2887 | let h = H::journaled(cfg(true, 4)); |
| 2888 | let copy = h.tmp.path().join("journal-copy.jsonl"); |
| 2889 | std::fs::copy(h.tmp.path().join("journal.jsonl"), ©).unwrap(); |
| 2890 | let side = deferred_journal_path(©); |
| 2891 | let line = serde_json::to_string(&revoke_a("revoke-a")).unwrap() + "\n"; |
| 2892 | std::fs::write(&side, &line).unwrap(); |
| 2893 | let store = h.engine.completion_store.clone(); |
| 2894 | let (a, _) = PrepAdapter::open(cfg(true, 4), &store, ©, clock(&h.ticks)).unwrap(); |
| 2895 | // No task a: refused and kept. |
| 2896 | assert_eq!(a.deferred_len(), 1); |
| 2897 | std::fs::remove_file(&side).unwrap(); |
| 2898 | std::fs::create_dir_all(side.join("block")).unwrap(); |
| 2899 | assert!(matches!( |
| 2900 | a.discard_deferred("revoke-a"), |
| 2901 | Err(DeliverError::DeferredJournal(_)) |
| 2902 | )); |
| 2903 | assert_eq!(a.deferred_len(), 1, "the failed discard keeps the event"); |
| 2904 | // Control: writable again, the discard succeeds. |
| 2905 | std::fs::remove_dir_all(&side).unwrap(); |
| 2906 | assert!(a.discard_deferred("revoke-a").unwrap().is_some()); |
| 2907 | assert_eq!(a.deferred_len(), 0); |
| 2908 | assert_eq!(std::fs::read_to_string(&side).unwrap(), ""); |
| 2909 | } |
| 2910 | |
| 2911 | #[test] |
| 2912 | fn a_second_adapter_on_the_same_journal_is_refused() { |
| 2913 | let mut h = H::journaled(cfg(true, 4)); |
| 2914 | h.register("a", &[]); |
| 2915 | let journal = h.tmp.path().join("journal.jsonl"); |
| 2916 | let side = deferred_journal_path(&journal); |
| 2917 | let line = serde_json::to_string(&revoke_a("revoke-x")).unwrap() + "\n"; |
| 2918 | std::fs::write(&side, &line).unwrap(); |
| 2919 | let store = h.engine.completion_store.clone(); |
| 2920 | let ticks = Arc::clone(&h.ticks); |
| 2921 | let open = |p: &Path| PrepAdapter::open(cfg(true, 4), &store, p, clock(&ticks)); |
| 2922 | let held = |what: &str, r: Result<(PrepAdapter, Vec<String>), SchedError>| match r { |
| 2923 | Err(SchedError::Journal(e)) => { |
| 2924 | assert!(e.contains("held by another process"), "{what}: {e}") |
| 2925 | } |
| 2926 | Err(e) => panic!("{what}: want the journal lock error, got {e}"), |
| 2927 | Ok(_) => panic!("{what}: a second adapter on one journal must be refused"), |
| 2928 | }; |
| 2929 | // The same path, a symlink to the file, a path through a symlinked |
| 2930 | // directory and a path with a `..` step all name the one journal. |
| 2931 | let link = h.tmp.path().join("link.jsonl"); |
| 2932 | std::os::unix::fs::symlink(&journal, &link).unwrap(); |
| 2933 | let dir_link = h.tmp.path().join("dirlink"); |
| 2934 | std::os::unix::fs::symlink(h.tmp.path(), &dir_link).unwrap(); |
| 2935 | std::fs::create_dir_all(h.tmp.path().join("sub")).unwrap(); |
| 2936 | held("same path", open(&journal)); |
| 2937 | held("file symlink", open(&link)); |
| 2938 | held("dir symlink", open(&dir_link.join("journal.jsonl"))); |
| 2939 | held("dot-dot", open(&h.tmp.path().join("sub/../journal.jsonl"))); |
| 2940 | // None of the refused opens read or rewrote the first adapter's |
| 2941 | // sidecar, and the first adapter still works. |
| 2942 | assert_eq!(std::fs::read_to_string(&side).unwrap(), line); |
| 2943 | assert_eq!(h.gen("a"), 1); |
| 2944 | // Negative control: a different journal in the same directory opens, |
| 2945 | // with its own sidecar. |
| 2946 | let other = h.tmp.path().join("journal.log"); |
| 2947 | assert_ne!(deferred_journal_path(&other), side); |
| 2948 | let (o, _) = open(&other).unwrap(); |
| 2949 | assert_eq!(o.deferred_len(), 0); |
| 2950 | drop(o); |
| 2951 | // Once the first adapter is gone the symlinked path opens the journal, |
| 2952 | // and that adapter alone delivers the sidecar it now owns. |
| 2953 | drop(h.adapter); |
| 2954 | let (b, _) = open(&link).unwrap(); |
| 2955 | let replayed = b.take_replayed_deferred(); |
| 2956 | assert_eq!(replayed.len(), 1); |
| 2957 | assert_eq!(replayed[0].id, "revoke-x"); |
| 2958 | assert!(matches!(replayed[0].result, Ok(Outcome::Applied(_)))); |
| 2959 | assert_eq!(b.generation("a"), Some(2)); |
| 2960 | assert_eq!(std::fs::read_to_string(&side).unwrap(), ""); |
| 2961 | } |
| 2962 | |
| 2963 | #[test] |
| 2964 | fn a_journal_named_like_a_sidecar_is_refused() { |
| 2965 | let h = H::journaled(cfg(true, 4)); |
| 2966 | let tmp = &h.tmp; |
| 2967 | let store = h.engine.completion_store.clone(); |
| 2968 | let ticks = Arc::clone(&h.ticks); |
| 2969 | let bad = tmp.path().join("x.deferred"); |
| 2970 | match PrepAdapter::open(cfg(true, 4), &store, &bad, clock(&ticks)) { |
| 2971 | Err(SchedError::Journal(e)) => assert!(e.contains(".deferred"), "{e}"), |
| 2972 | Err(e) => panic!("want a journal error, got {e}"), |
| 2973 | Ok(_) => panic!("a journal ending in .deferred must be refused"), |
| 2974 | } |
| 2975 | assert!(!bad.exists(), "nothing was created"); |
| 2976 | // Negative control: the same directory, a plain name. |
| 2977 | let good = tmp.path().join("x.jsonl"); |
| 2978 | assert!(PrepAdapter::open(cfg(true, 4), &store, &good, clock(&ticks)).is_ok()); |
| 2979 | assert_eq!( |
| 2980 | deferred_journal_path(&good), |
| 2981 | tmp.path().join("x.jsonl.deferred") |
| 2982 | ); |
| 2983 | } |