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-cli / tests / recovery_matrix_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 | //! Real-process recovery matrix for the ordinary compose -> grant -> execute -> ack |
| 17 | //! path (arch#162). Every case starts the real `aien daemon` and the real |
| 18 | //! `aien compose ...` CLI as OS processes, each with its OWN fresh |
| 19 | //! AIEN_RUNTIME_STATE_DIR, AIEN_COMPOSE_DIR (the desk key lives under it), |
| 20 | //! AIEN_PROVENANCE_DIR, socket and workspace. Crashes are SIGKILL (kill -9) of |
| 21 | //! the real process at a named fault-hold point of `aien compose execute` |
| 22 | //! (before_intent, after_intent, after_write), then SIGKILL of the daemon, |
| 23 | //! then a restart over the same state. Nothing is a clean shutdown or abort(). |
| 24 | //! |
| 25 | //! How the grant is obtained: a real SmolLM2-1.7B proposal on the CPU reference |
| 26 | //! backend (`aien compose propose`, one committed one-file change per case), then |
| 27 | //! the ordinary `aien compose authorize`, so the daemon mints the grant from its |
| 28 | //! own compose-commit record. That model daemon is SIGKILLed; the case then runs |
| 29 | //! on a model-less daemon over the same state. Two modes: the default (the desk |
| 30 | //! is required, sc#328: desk key in the case compose dir, every authorize |
| 31 | //! carries a desk MAC under a fresh nonce) and AIEN_MATRIX_MAC=0, the legacy |
| 32 | //! OS-user-only authorize, which is only reachable through the dev opt-out |
| 33 | //! (AIEN_COMPOSE_AUTHORIZE_REQUIRES_DESK=0 with AIEN_DEV_FALLBACK=1), so such a |
| 34 | //! run is a dev run and never qualification evidence. Receipts record the |
| 35 | //! daemon's "Authorize MAC: on" or "Authorize MAC: OFF, DEV OPT-OUT" line. AIEN_PROPOSER_MODEL overrides the |
| 36 | //! SmolLM2 directory. Rows M1 and M2 are about the MAC and always run with it on. |
| 37 | //! |
| 38 | //! Needs a compose-linked CPU build of `aien-cli` with the `fault-hold` feature |
| 39 | //! (never a GPU build). Build once, then run (single documented command): |
| 40 | //! |
| 41 | //! ```text |
| 42 | //! AIEN_OMEGA_COMPOSE_DIR=<omega checkout at omega.lock> AIEN_PHYSICS_DIR=<physics> \ |
| 43 | //! AIEN_AIENOS_LOCK_REPO=<aienos clone holding aienos.lock> CARGO_TARGET_DIR=<dir> \ |
| 44 | //! cargo build --release -p aien-cli --features aien-cli/fault-hold |
| 45 | //! AIEN_BIN=<dir>/release/aien-cli cargo test -p aien-cli --test recovery_matrix_test \ |
| 46 | //! -- --ignored --test-threads=1 --nocapture |
| 47 | //! ``` |
| 48 | //! |
| 49 | //! Every case prints one line `MATRIX_RECEIPT {json}` (commit, binary sha256, |
| 50 | //! backend line, model sha256, case id, outcome) and, when AIEN_MATRIX_RECEIPTS |
| 51 | //! names a file, appends it there. The daemon must report the CPU reference |
| 52 | //! backend or the case stops (no GPU use here). |
| 53 | #[path = "../../aien-allen/tests/support/mod.rs"] |
| 54 | mod support; |
| 55 | |
| 56 | use aien_allen::binding::pin_path; |
| 57 | use aien_runtime::approved_auth::{desk_key_path, AuthorizeBinding, DeskKey}; |
| 58 | use aien_runtime::client::AienRuntimeClient; |
| 59 | use aien_runtime::control::ChatTurn; |
| 60 | use serde_json::{json, Value}; |
| 61 | use sha2::{Digest, Sha256}; |
| 62 | use std::os::unix::fs::MetadataExt; |
| 63 | use std::os::unix::process::{CommandExt, ExitStatusExt}; |
| 64 | use std::path::{Path, PathBuf}; |
| 65 | use std::process::{Child, Command, Stdio}; |
| 66 | use std::time::Duration; |
| 67 | |
| 68 | const AUTHORIZE_DESK_ENV: &str = "AIEN_COMPOSE_AUTHORIZE_REQUIRES_DESK"; |
| 69 | |
| 70 | /// A committed proposal the real model made: the S3 report file and what it names. |
| 71 | #[derive(Clone)] |
| 72 | struct Prop { |
| 73 | report: PathBuf, |
| 74 | path: String, |
| 75 | content_sha256: String, |
| 76 | cx_promotion: u64, |
| 77 | proposal_sha256: String, |
| 78 | } |
| 79 | |
| 80 | fn sha(b: &[u8]) -> String { |
| 81 | aien_omega_compose::hex(&Sha256::digest(b)) |
| 82 | } |
| 83 | |
| 84 | fn s(p: &Path) -> String { |
| 85 | p.display().to_string() |
| 86 | } |
| 87 | |
| 88 | #[derive(Debug)] |
| 89 | struct Down { |
| 90 | code: Option<i32>, |
| 91 | signal: Option<i32>, |
| 92 | log: String, |
| 93 | } |
| 94 | |
| 95 | struct Out { |
| 96 | code: i32, |
| 97 | json: Value, |
| 98 | stdout: String, |
| 99 | stderr: String, |
| 100 | } |
| 101 | |
| 102 | impl Out { |
| 103 | fn all(&self) -> String { |
| 104 | format!("{} {}", self.stdout, self.stderr) |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | struct Rig { |
| 109 | case: &'static str, |
| 110 | _tmp: tempfile::TempDir, |
| 111 | root: PathBuf, |
| 112 | bin: PathBuf, |
| 113 | daemon: Option<Child>, |
| 114 | nd: u32, |
| 115 | env: Vec<(String, String)>, |
| 116 | rt: tokio::runtime::Runtime, |
| 117 | backend: String, |
| 118 | model: String, |
| 119 | detail: String, |
| 120 | mac: bool, |
| 121 | mac_line: String, |
| 122 | props: Vec<Prop>, |
| 123 | } |
| 124 | |
| 125 | impl Rig { |
| 126 | fn new(case: &'static str) -> Rig { |
| 127 | Rig::with_mac(case, std::env::var("AIEN_MATRIX_MAC").as_deref() != Ok("0")) |
| 128 | } |
| 129 | |
| 130 | /// `mac` forces the authorize-MAC mode (rows that are about the MAC itself). |
| 131 | fn with_mac(case: &'static str, mac: bool) -> Rig { |
| 132 | let bin = PathBuf::from(std::env::var("AIEN_BIN").unwrap_or_else(|_| { |
| 133 | panic!("AIEN_BIN must name the compose-linked CPU aien-cli (see the file header)") |
| 134 | })); |
| 135 | // A short path: unix socket paths are limited to 108 bytes. |
| 136 | let tmp = tempfile::Builder::new() |
| 137 | .prefix("rm-") |
| 138 | .tempdir_in("/tmp") |
| 139 | .unwrap(); |
| 140 | let root = std::fs::canonicalize(tmp.path()).unwrap(); |
| 141 | for d in ["ws", "state", "home", "prov"] { |
| 142 | std::fs::create_dir_all(root.join(d)).unwrap(); |
| 143 | } |
| 144 | DeskKey::create(&desk_key_path(&root.join("compose"))).unwrap(); |
| 145 | let mut r = Rig { |
| 146 | case, |
| 147 | _tmp: tmp, |
| 148 | root, |
| 149 | bin, |
| 150 | daemon: None, |
| 151 | nd: 0, |
| 152 | env: Vec::new(), |
| 153 | rt: tokio::runtime::Builder::new_current_thread() |
| 154 | .enable_all() |
| 155 | .build() |
| 156 | .unwrap(), |
| 157 | backend: "not started".into(), |
| 158 | model: "none".into(), |
| 159 | detail: String::new(), |
| 160 | mac, |
| 161 | mac_line: String::new(), |
| 162 | props: Vec::new(), |
| 163 | }; |
| 164 | if mac { |
| 165 | r.env.push((AUTHORIZE_DESK_ENV.into(), "1".into())); |
| 166 | } else { |
| 167 | // sc#328: the legacy path is the visible dev opt-out, never strict. |
| 168 | r.env.push((AUTHORIZE_DESK_ENV.into(), "0".into())); |
| 169 | r.env.push(("AIEN_DEV_FALLBACK".into(), "1".into())); |
| 170 | } |
| 171 | r |
| 172 | } |
| 173 | |
| 174 | fn sock(&self) -> PathBuf { |
| 175 | self.root.join("s") |
| 176 | } |
| 177 | fn compose(&self) -> PathBuf { |
| 178 | self.root.join("compose") |
| 179 | } |
| 180 | fn ws(&self) -> PathBuf { |
| 181 | self.root.join("ws") |
| 182 | } |
| 183 | |
| 184 | fn cmd_env(&self, c: &mut Command) { |
| 185 | c.current_dir(&self.root) |
| 186 | .env("HOME", self.root.join("home")) |
| 187 | .env("NO_COLOR", "1") |
| 188 | .env("AIEN_RUNTIME_SOCK", self.sock()) |
| 189 | .env("AIEN_RUNTIME_STATE_DIR", self.root.join("state")) |
| 190 | .env("AIEN_COMPOSE_DIR", self.compose()) |
| 191 | .env("AIEN_PROVENANCE_DIR", self.root.join("prov")) |
| 192 | .env("AIEN_REQUIRE_CHECKPOINT", "0"); |
| 193 | for k in [ |
| 194 | "AIEN_OMEGA_DIR", |
| 195 | "AIEN_OMEGA_GPU_LIB", |
| 196 | "AIEN_REQUIRE_BLACKWELL", |
| 197 | "AIEN_GPU_BACKEND", |
| 198 | "AIEN_MODEL_PATH", |
| 199 | "AIEN_TOKENIZER_PATH", |
| 200 | "AIEN_MODEL_DIR", |
| 201 | "AIEN_ALLEN_SUBJECT", |
| 202 | "AIEN_ALLEN_ADOPT", |
| 203 | "AIEN_FAULT_HOLD", |
| 204 | "AIEN_FAULT_HOLD_FILE", |
| 205 | AUTHORIZE_DESK_ENV, |
| 206 | ] { |
| 207 | c.env_remove(k); |
| 208 | } |
| 209 | for (k, v) in &self.env { |
| 210 | c.env(k, v); |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | fn down_of(&mut self, mut child: Child, log: &Path) -> Down { |
| 215 | let st = child.wait().unwrap(); |
| 216 | self.daemon = None; |
| 217 | Down { |
| 218 | code: st.code(), |
| 219 | signal: st.signal(), |
| 220 | log: std::fs::read_to_string(log).unwrap_or_default(), |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | fn start(&mut self) -> Result<(), Down> { |
| 225 | self.start_with(&[]) |
| 226 | } |
| 227 | |
| 228 | /// Start the daemon; `once` is added to this start only. Err when the |
| 229 | /// process exits before it is serving (a refusal). |
| 230 | fn start_with(&mut self, once: &[(&str, &str)]) -> Result<(), Down> { |
| 231 | assert!(self.daemon.is_none(), "a daemon is already running"); |
| 232 | self.nd += 1; |
| 233 | let log = self.root.join(format!("daemon-{}.log", self.nd)); |
| 234 | let f = std::fs::File::create(&log).unwrap(); |
| 235 | let _ = std::fs::remove_file(self.sock()); |
| 236 | let mut c = Command::new(&self.bin); |
| 237 | c.arg("daemon"); |
| 238 | self.cmd_env(&mut c); |
| 239 | for (k, v) in once { |
| 240 | c.env(k, v); |
| 241 | } |
| 242 | c.process_group(0) |
| 243 | .stdin(Stdio::null()) |
| 244 | .stdout(f.try_clone().unwrap()) |
| 245 | .stderr(f); |
| 246 | let child = c.spawn().expect("spawn daemon"); |
| 247 | self.daemon = Some(child); |
| 248 | for _ in 0..1200 { |
| 249 | std::thread::sleep(Duration::from_millis(50)); |
| 250 | let exited = self.daemon.as_mut().unwrap().try_wait().unwrap().is_some(); |
| 251 | if exited { |
| 252 | let child = self.daemon.take().unwrap(); |
| 253 | return Err(self.down_of(child, &log)); |
| 254 | } |
| 255 | let text = std::fs::read_to_string(&log).unwrap_or_default(); |
| 256 | if self.sock().exists() && text.contains("Replay reconcile:") { |
| 257 | let line = text |
| 258 | .lines() |
| 259 | .find(|l| l.contains("Backend:")) |
| 260 | .unwrap_or("no Backend line") |
| 261 | .trim() |
| 262 | .to_string(); |
| 263 | if !line.contains("CPU-reference") { |
| 264 | self.kill_daemon(); |
| 265 | panic!( |
| 266 | "daemon is not the CPU reference build ({line}); no GPU use allowed here" |
| 267 | ); |
| 268 | } |
| 269 | self.backend = line; |
| 270 | self.mac_line = text |
| 271 | .lines() |
| 272 | .find(|l| l.starts_with("Authorize MAC:")) |
| 273 | .unwrap_or("Authorize MAC: no line") |
| 274 | .to_string(); |
| 275 | if let Some(m) = text.lines().find(|l| l.contains("model_sha256=")) { |
| 276 | if let Some(i) = m.find("model_sha256=") { |
| 277 | self.model = m[i + 13..].split([',', ')']).next().unwrap().to_string(); |
| 278 | } |
| 279 | } |
| 280 | return Ok(()); |
| 281 | } |
| 282 | } |
| 283 | self.kill_daemon(); |
| 284 | panic!("daemon did not come up in 60 s: {}", self.root.display()); |
| 285 | } |
| 286 | |
| 287 | /// SIGKILL the daemon this rig started (std `Child::kill` is SIGKILL). |
| 288 | fn kill_daemon(&mut self) { |
| 289 | if let Some(mut c) = self.daemon.take() { |
| 290 | let _ = c.kill(); |
| 291 | let st = c.wait().unwrap(); |
| 292 | assert!( |
| 293 | st.signal() == Some(9) || st.code().is_some(), |
| 294 | "daemon end: {st:?}" |
| 295 | ); |
| 296 | } |
| 297 | let _ = std::fs::remove_file(self.sock()); |
| 298 | } |
| 299 | |
| 300 | fn cli_cmd(&self, args: &[&str]) -> Command { |
| 301 | let mut c = Command::new(&self.bin); |
| 302 | c.arg("compose").args(args); |
| 303 | self.cmd_env(&mut c); |
| 304 | c |
| 305 | } |
| 306 | |
| 307 | fn cli(&self, args: &[&str]) -> Out { |
| 308 | let o = self.cli_cmd(args).output().expect("run aien compose"); |
| 309 | let stdout = String::from_utf8_lossy(&o.stdout).to_string(); |
| 310 | let json = stdout |
| 311 | .lines() |
| 312 | .rev() |
| 313 | .find_map(|l| serde_json::from_str::<Value>(l).ok()) |
| 314 | .unwrap_or_else(|| json!({"unparsed": stdout})); |
| 315 | Out { |
| 316 | code: o.status.code().unwrap_or(-1), |
| 317 | json, |
| 318 | stdout, |
| 319 | stderr: String::from_utf8_lossy(&o.stderr).to_string(), |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | /// Run `aien compose <args>` with AIEN_FAULT_HOLD=`point`, wait until it |
| 324 | /// holds there, then SIGKILL it. Returns the held process's stderr. |
| 325 | fn cli_killed_at(&self, args: &[&str], point: &str) { |
| 326 | let hold = self.root.join(format!("hold-{point}")); |
| 327 | let _ = std::fs::remove_file(&hold); |
| 328 | let mut c = self.cli_cmd(args); |
| 329 | c.env("AIEN_FAULT_HOLD", point) |
| 330 | .env("AIEN_FAULT_HOLD_FILE", &hold) |
| 331 | .stdin(Stdio::null()) |
| 332 | .stdout(std::fs::File::create(self.root.join("held.out")).unwrap()) |
| 333 | .stderr(std::fs::File::create(self.root.join("held.err")).unwrap()); |
| 334 | let mut child = c.spawn().expect("spawn held cli"); |
| 335 | let mut pid = None; |
| 336 | for _ in 0..1200 { |
| 337 | std::thread::sleep(Duration::from_millis(50)); |
| 338 | if let Ok(t) = std::fs::read_to_string(&hold) { |
| 339 | if let Some(p) = t |
| 340 | .split_whitespace() |
| 341 | .next() |
| 342 | .and_then(|p| p.parse::<u32>().ok()) |
| 343 | { |
| 344 | pid = Some(p); |
| 345 | break; |
| 346 | } |
| 347 | } |
| 348 | if child.try_wait().unwrap().is_some() { |
| 349 | panic!( |
| 350 | "cli exited before the hold point {point}: out={} err={}", |
| 351 | std::fs::read_to_string(self.root.join("held.out")).unwrap_or_default(), |
| 352 | std::fs::read_to_string(self.root.join("held.err")).unwrap_or_default() |
| 353 | ); |
| 354 | } |
| 355 | } |
| 356 | let pid = pid.unwrap_or_else(|| { |
| 357 | let _ = child.kill(); |
| 358 | panic!("cli never reached hold point {point}") |
| 359 | }); |
| 360 | assert_eq!(pid, child.id(), "the hold file names our child"); |
| 361 | child.kill().unwrap(); |
| 362 | let st = child.wait().unwrap(); |
| 363 | assert_eq!( |
| 364 | st.signal(), |
| 365 | Some(9), |
| 366 | "{point}: killed by SIGKILL, got {st:?}" |
| 367 | ); |
| 368 | } |
| 369 | |
| 370 | /// `aien allen <args>` against this rig's daemon (scoped memory commands). |
| 371 | fn allen(&self, args: &[&str]) -> Out { |
| 372 | let mut c = Command::new(&self.bin); |
| 373 | c.arg("allen").args(args); |
| 374 | self.cmd_env(&mut c); |
| 375 | let o = c.output().expect("run aien allen"); |
| 376 | let stdout = String::from_utf8_lossy(&o.stdout).to_string(); |
| 377 | let json = stdout |
| 378 | .lines() |
| 379 | .rev() |
| 380 | .find_map(|l| serde_json::from_str::<Value>(l).ok()) |
| 381 | .unwrap_or_else(|| json!({"unparsed": stdout})); |
| 382 | Out { |
| 383 | code: o.status.code().unwrap_or(-1), |
| 384 | json, |
| 385 | stdout, |
| 386 | stderr: String::from_utf8_lossy(&o.stderr).to_string(), |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | /// Everything the daemon wrote down that a note could leak into: compose |
| 391 | /// records, every daemon log, the provenance dir. One string per line. |
| 392 | fn observable_lines(&self) -> std::collections::BTreeSet<String> { |
| 393 | let mut t = self.all_records_text(); |
| 394 | for n in 1..=self.nd { |
| 395 | t += "\n"; |
| 396 | t += &std::fs::read_to_string(self.root.join(format!("daemon-{n}.log"))) |
| 397 | .unwrap_or_default(); |
| 398 | } |
| 399 | for e in std::fs::read_dir(self.root.join("prov")) |
| 400 | .into_iter() |
| 401 | .flatten() |
| 402 | .flatten() |
| 403 | { |
| 404 | if e.path().is_file() { |
| 405 | t += "\n"; |
| 406 | t += &String::from_utf8_lossy(&std::fs::read(e.path()).unwrap()); |
| 407 | } |
| 408 | } |
| 409 | t.lines().map(str::to_string).collect() |
| 410 | } |
| 411 | |
| 412 | /// Memory key files of the ALLEN memory store beside the compose home. |
| 413 | fn memory_keys(&self) -> std::collections::BTreeSet<PathBuf> { |
| 414 | // The memory store is `<home>.allen-memory/` beside the compose home, keys in its `keys/` |
| 415 | // (aien-allen-memory store.rs), not inside the home itself. |
| 416 | let mut out = std::collections::BTreeSet::new(); |
| 417 | let mut stack = vec![PathBuf::from(format!( |
| 418 | "{}.allen-memory", |
| 419 | self.compose().display() |
| 420 | ))]; |
| 421 | while let Some(d) = stack.pop() { |
| 422 | for e in std::fs::read_dir(&d).into_iter().flatten().flatten() { |
| 423 | let p = e.path(); |
| 424 | if p.is_dir() { |
| 425 | stack.push(p); |
| 426 | } else if p.extension().is_some_and(|x| x == "key") |
| 427 | && p.parent().is_some_and(|q| q.ends_with("keys")) |
| 428 | { |
| 429 | out.insert(p); |
| 430 | } |
| 431 | } |
| 432 | } |
| 433 | out |
| 434 | } |
| 435 | |
| 436 | /// `aien compose propose --context ctx`; the task's MemoryReport. |
| 437 | fn propose_memory(&self, ctx: Option<&str>) -> (Out, Value) { |
| 438 | let mut a = vec![ |
| 439 | "propose", |
| 440 | "--goal", |
| 441 | "Create the file R9.md with a short plain-text note about the project.", |
| 442 | "--workspace", |
| 443 | ]; |
| 444 | let ws = s(&self.ws()); |
| 445 | a.push(&ws); |
| 446 | if let Some(c) = ctx { |
| 447 | a.extend(["--context", c]); |
| 448 | } |
| 449 | let o = self.cli(&a); |
| 450 | let m = o.json["report"]["memory"].clone(); |
| 451 | assert!(m.is_object(), "no MemoryReport in: {}", o.all()); |
| 452 | (o, m) |
| 453 | } |
| 454 | |
| 455 | /// One model-daemon session (SmolLM2 on the CPU reference backend, never the |
| 456 | /// GPU): one real `aien compose propose` per file name. The daemon is then |
| 457 | /// SIGKILLed; the case continues on a model-less daemon over the same state. |
| 458 | /// A proposal that does not commit is retried (the model is sampled), up to 3 times. |
| 459 | fn proposals(&mut self, files: &[&str]) { |
| 460 | let m = std::env::var("AIEN_PROPOSER_MODEL").unwrap_or_else(|_| { |
| 461 | format!( |
| 462 | "{}/models/SmolLM2-1.7B-Instruct-31b70e2e869a", |
| 463 | std::env::var("HOME").unwrap() |
| 464 | ) |
| 465 | }); |
| 466 | let m = PathBuf::from(m); |
| 467 | let saved = self.env.clone(); |
| 468 | self.env |
| 469 | .push(("AIEN_MODEL_PATH".into(), s(&m.join("model.safetensors")))); |
| 470 | self.env |
| 471 | .push(("AIEN_TOKENIZER_PATH".into(), s(&m.join("tokenizer.json")))); |
| 472 | self.env |
| 473 | .push(("AIEN_COMPOSE_EDIT_BUDGET_MS".into(), "590000".into())); |
| 474 | self.env |
| 475 | .push(("AIEN_COMPOSE_DOC_BUDGET_MS".into(), "590000".into())); |
| 476 | self.start() |
| 477 | .unwrap_or_else(|d| panic!("proposer daemon: {}", d.log)); |
| 478 | let mut out = Vec::new(); |
| 479 | for (i, file) in files.iter().enumerate() { |
| 480 | let goal = format!( |
| 481 | "Create the file {file} with a short plain-text note that says the project keeps every change inside its workspace." |
| 482 | ); |
| 483 | let mut got = None; |
| 484 | for attempt in 0..3 { |
| 485 | let o = self.cli(&["propose", "--goal", &goal, "--workspace", &s(&self.ws())]); |
| 486 | let rep = &o.json["report"]; |
| 487 | if o.code == 0 && rep["committed"] == json!(true) { |
| 488 | let f = self.root.join(format!("S3-{}-{i}.json", self.case)); |
| 489 | std::fs::write(&f, o.json.to_string()).unwrap(); |
| 490 | got = Some(Prop { |
| 491 | report: f, |
| 492 | path: rep["proposal_path"].as_str().unwrap().to_string(), |
| 493 | content_sha256: rep["proposal_content_sha256"] |
| 494 | .as_str() |
| 495 | .unwrap() |
| 496 | .to_string(), |
| 497 | cx_promotion: rep["cx_promotion"].as_u64().unwrap(), |
| 498 | proposal_sha256: rep["proposal_sha256"].as_str().unwrap().to_string(), |
| 499 | }); |
| 500 | break; |
| 501 | } |
| 502 | eprintln!("propose attempt {attempt} did not commit: {}", o.all()); |
| 503 | } |
| 504 | out.push(got.expect("the model proposed a committable change in 3 attempts")); |
| 505 | } |
| 506 | self.kill_daemon(); |
| 507 | self.env = saved; |
| 508 | self.start() |
| 509 | .unwrap_or_else(|d| panic!("model-less restart: {}", d.log)); |
| 510 | self.props = out; |
| 511 | } |
| 512 | |
| 513 | /// Authorize proposal `i`; (its S3 report file, the daemon-minted grant id). |
| 514 | fn prepare(&self, i: usize) -> (PathBuf, u64) { |
| 515 | let p = &self.props[i]; |
| 516 | (p.report.clone(), self.authorize(p)) |
| 517 | } |
| 518 | |
| 519 | fn path(&self, i: usize) -> String { |
| 520 | self.props[i].path.clone() |
| 521 | } |
| 522 | |
| 523 | /// Are `bytes` exactly the content the model proposed for `i`? |
| 524 | fn is_content(&self, i: usize, bytes: &[u8]) -> bool { |
| 525 | sha(bytes) == self.props[i].content_sha256 |
| 526 | } |
| 527 | |
| 528 | /// `aien compose authorize` for `p`; with the MAC mode on it carries a desk |
| 529 | /// MAC under a fresh nonce. Returns the daemon-minted grant id. |
| 530 | fn authorize(&self, p: &Prop) -> u64 { |
| 531 | let o = self.authorize_raw(p, None); |
| 532 | assert_eq!(o.code, 0, "authorize: {}", o.all()); |
| 533 | o.json["authorization"]["id"].as_u64().expect("grant id") |
| 534 | } |
| 535 | |
| 536 | fn authorize_raw(&self, p: &Prop, proof: Option<(&str, &str)>) -> Out { |
| 537 | let (rep, ws) = (s(&p.report), s(&self.ws())); |
| 538 | let mut a = vec![ |
| 539 | "authorize", |
| 540 | "--report", |
| 541 | &rep, |
| 542 | "--workspace", |
| 543 | &ws, |
| 544 | "--approver", |
| 545 | "drake", |
| 546 | ]; |
| 547 | if let Some((nonce, mac)) = proof { |
| 548 | a.extend(["--desk-nonce", nonce, "--desk-mac", mac]); |
| 549 | } else if self.mac { |
| 550 | a.extend(["--desk", "1"]); |
| 551 | } |
| 552 | self.cli(&a) |
| 553 | } |
| 554 | |
| 555 | /// A desk MAC for `p` under the desk key now in the compose dir, for `nonce`. |
| 556 | fn desk_mac(&self, p: &Prop, nonce: &str) -> String { |
| 557 | DeskKey::load(&desk_key_path(&self.compose())) |
| 558 | .unwrap() |
| 559 | .sign_authorize(&AuthorizeBinding { |
| 560 | cx_promotion: p.cx_promotion, |
| 561 | proposal_sha256: p.proposal_sha256.clone(), |
| 562 | path: p.path.clone(), |
| 563 | content_sha256: p.content_sha256.clone(), |
| 564 | workspace: s(&self.ws()), |
| 565 | approver: "drake".into(), |
| 566 | constraints: vec![], |
| 567 | nonce: nonce.into(), |
| 568 | desk_key_id: DeskKey::load(&desk_key_path(&self.compose())) |
| 569 | .unwrap() |
| 570 | .id() |
| 571 | .to_string(), |
| 572 | }) |
| 573 | } |
| 574 | |
| 575 | /// Replace the desk key file with a new key (rotation while nothing runs). |
| 576 | fn rotate_desk_key(&self) { |
| 577 | let p = desk_key_path(&self.compose()); |
| 578 | std::fs::remove_file(&p).unwrap(); |
| 579 | DeskKey::create(&p).unwrap(); |
| 580 | } |
| 581 | |
| 582 | fn exec_args<'a>(&'a self, report: &'a Path, grant: &'a str) -> Vec<String> { |
| 583 | vec![ |
| 584 | "execute".into(), |
| 585 | "--report".into(), |
| 586 | s(report), |
| 587 | "--workspace".into(), |
| 588 | s(&self.ws()), |
| 589 | "--authorization".into(), |
| 590 | grant.into(), |
| 591 | ] |
| 592 | } |
| 593 | |
| 594 | fn execute(&self, report: &Path, grant: u64) -> Out { |
| 595 | let g = grant.to_string(); |
| 596 | let a = self.exec_args(report, &g); |
| 597 | let a: Vec<&str> = a.iter().map(String::as_str).collect(); |
| 598 | self.cli(&a) |
| 599 | } |
| 600 | |
| 601 | fn execute_killed_at(&self, report: &Path, grant: u64, point: &str) { |
| 602 | let g = grant.to_string(); |
| 603 | let a = self.exec_args(report, &g); |
| 604 | let a: Vec<&str> = a.iter().map(String::as_str).collect(); |
| 605 | self.cli_killed_at(&a, point); |
| 606 | } |
| 607 | |
| 608 | fn intents(&self) -> Vec<Value> { |
| 609 | let o = self.cli(&["effects"]); |
| 610 | assert_eq!(o.code, 0, "effects: {}", o.all()); |
| 611 | o.json["ledger"]["intents"].as_array().cloned().unwrap() |
| 612 | } |
| 613 | |
| 614 | fn states(&self) -> Vec<String> { |
| 615 | self.intents() |
| 616 | .iter() |
| 617 | .map(|i| i["state"].as_str().unwrap().to_string()) |
| 618 | .collect() |
| 619 | } |
| 620 | |
| 621 | fn file(&self, rel: &str) -> Option<(Vec<u8>, u64, i64, i64)> { |
| 622 | let p = self.ws().join(rel); |
| 623 | let m = std::fs::metadata(&p).ok()?; |
| 624 | Some(( |
| 625 | std::fs::read(&p).unwrap(), |
| 626 | m.ino(), |
| 627 | m.mtime(), |
| 628 | m.mtime_nsec(), |
| 629 | )) |
| 630 | } |
| 631 | |
| 632 | /// Kill the daemon with SIGKILL and start a fresh one over the same state. |
| 633 | fn crash_and_restart(&mut self) { |
| 634 | self.kill_daemon(); |
| 635 | self.start() |
| 636 | .unwrap_or_else(|d| panic!("restart: {}", d.log)); |
| 637 | } |
| 638 | |
| 639 | /// Everything the daemon recorded, as text (for "never claims X" checks). |
| 640 | fn all_records_text(&self) -> String { |
| 641 | let o = self.cli(&["recall"]); |
| 642 | o.json["recall"]["host"] |
| 643 | .as_array() |
| 644 | .map(|a| { |
| 645 | a.iter() |
| 646 | .filter_map(|r| r["text"].as_str()) |
| 647 | .collect::<Vec<_>>() |
| 648 | .join("\n") |
| 649 | }) |
| 650 | .unwrap_or_default() |
| 651 | } |
| 652 | } |
| 653 | |
| 654 | impl Drop for Rig { |
| 655 | fn drop(&mut self) { |
| 656 | let outcome = if std::thread::panicking() { |
| 657 | "FAIL" |
| 658 | } else { |
| 659 | "PASS" |
| 660 | }; |
| 661 | self.kill_daemon(); |
| 662 | let commit = Command::new("git") |
| 663 | .args([ |
| 664 | "-C", |
| 665 | env!("CARGO_MANIFEST_DIR"), |
| 666 | "rev-parse", |
| 667 | "--short=12", |
| 668 | "HEAD", |
| 669 | ]) |
| 670 | .output() |
| 671 | .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()) |
| 672 | .unwrap_or_default(); |
| 673 | let bin_sha = std::fs::read(&self.bin) |
| 674 | .map(|b| sha(&b)) |
| 675 | .unwrap_or_default(); |
| 676 | let line = json!({"case": self.case, "outcome": outcome, "commit": commit, |
| 677 | "bin_sha256": bin_sha, "backend": self.backend, "authorize_mac": self.mac_line, "model_sha256": self.model, |
| 678 | "detail": self.detail}); |
| 679 | println!("MATRIX_RECEIPT {line}"); |
| 680 | if let Ok(f) = std::env::var("AIEN_MATRIX_RECEIPTS") { |
| 681 | use std::io::Write; |
| 682 | if let Ok(mut h) = std::fs::OpenOptions::new() |
| 683 | .create(true) |
| 684 | .append(true) |
| 685 | .open(f) |
| 686 | { |
| 687 | let _ = writeln!(h, "{line}"); |
| 688 | } |
| 689 | } |
| 690 | } |
| 691 | } |
| 692 | |
| 693 | fn names_error(o: &Out, any: &[&str]) { |
| 694 | let t = o.all(); |
| 695 | assert!( |
| 696 | any.iter().any(|n| t.contains(n)), |
| 697 | "expected one of {any:?} in: {t}" |
| 698 | ); |
| 699 | } |
| 700 | |
| 701 | /// R1: killed before the intent is opened. |
| 702 | #[test] |
| 703 | #[ignore = "needs AIEN_BIN: compose-linked CPU build with fault-hold"] |
| 704 | fn r1_crash_before_commit() { |
| 705 | let mut r = Rig::new("R1"); |
| 706 | r.proposals(&["r1.md"]); |
| 707 | let (rep, grant) = r.prepare(0); |
| 708 | r.execute_killed_at(&rep, grant, "before_intent"); |
| 709 | r.crash_and_restart(); |
| 710 | assert!(r.file(&r.path(0)).is_none(), "no file written"); |
| 711 | assert!(r.intents().is_empty(), "no intent, so no grant spent"); |
| 712 | let rc = r.cli(&["reconcile"]); |
| 713 | assert_eq!(rc.code, 0, "{}", rc.all()); |
| 714 | let outcomes = rc.json["reconcile"]["outcomes"].as_array().unwrap(); |
| 715 | assert!( |
| 716 | outcomes.iter().all(|o| o["state"] != "DONE") && rc.json["reconcile"]["checked"] == 0, |
| 717 | "reconcile reports nothing: {}", |
| 718 | rc.json |
| 719 | ); |
| 720 | // The grant is still unspent: the same grant now does the effect, once. |
| 721 | let ok = r.execute(&rep, grant); |
| 722 | assert_eq!(ok.json["state"], "DONE", "{}", ok.all()); |
| 723 | assert!(r.is_content(0, &r.file(&r.path(0)).unwrap().0)); |
| 724 | let again = r.execute(&rep, grant); |
| 725 | assert_ne!(again.code, 0); |
| 726 | names_error(&again, &["AlreadySpent"]); |
| 727 | assert_eq!(r.states(), vec!["DONE"]); |
| 728 | r.detail = |
| 729 | "SIGKILL at before_intent; restart; nothing done; grant unspent then spent once".into(); |
| 730 | } |
| 731 | |
| 732 | /// R2: killed after the intent is durable, before the write. |
| 733 | #[test] |
| 734 | #[ignore = "needs AIEN_BIN: compose-linked CPU build with fault-hold"] |
| 735 | fn r2_crash_after_intent_before_write() { |
| 736 | let mut r = Rig::new("R2"); |
| 737 | r.proposals(&["r2.md"]); |
| 738 | let (rep, grant) = r.prepare(0); |
| 739 | r.execute_killed_at(&rep, grant, "after_intent"); |
| 740 | r.crash_and_restart(); |
| 741 | assert!(r.file(&r.path(0)).is_none(), "the write never happened"); |
| 742 | let st = r.states(); |
| 743 | assert_eq!(st.len(), 1, "{st:?}"); |
| 744 | assert_eq!( |
| 745 | st[0], "NOT_DONE", |
| 746 | "an intent whose write never happened settles NOT_DONE, got {st:?}" |
| 747 | ); |
| 748 | let rc = r.cli(&["reconcile"]); |
| 749 | assert_eq!(rc.code, 0, "{}", rc.all()); |
| 750 | assert!( |
| 751 | rc.json["reconcile"]["outcomes"] |
| 752 | .as_array() |
| 753 | .unwrap() |
| 754 | .iter() |
| 755 | .all(|o| o["state"] != "DONE"), |
| 756 | "{}", |
| 757 | rc.json |
| 758 | ); |
| 759 | // Re-executing the same grant is refused and writes nothing. |
| 760 | let again = r.execute(&rep, grant); |
| 761 | assert_ne!(again.code, 0, "{}", again.all()); |
| 762 | names_error(&again, &["AlreadySpent", "ReconciliationRequired"]); |
| 763 | assert!(r.file(&r.path(0)).is_none()); |
| 764 | assert_eq!(r.intents().len(), 1, "no second intent"); |
| 765 | r.detail = format!("SIGKILL at after_intent; restart settled {}", st[0]); |
| 766 | } |
| 767 | |
| 768 | /// R3: killed after the write, before the ack. |
| 769 | #[test] |
| 770 | #[ignore = "needs AIEN_BIN: compose-linked CPU build with fault-hold"] |
| 771 | fn r3_crash_after_write_before_ack() { |
| 772 | let mut r = Rig::new("R3"); |
| 773 | r.proposals(&["r3.md"]); |
| 774 | let (rep, grant) = r.prepare(0); |
| 775 | r.execute_killed_at(&rep, grant, "after_write"); |
| 776 | let before = r |
| 777 | .file(&r.path(0)) |
| 778 | .expect("the write happened before the crash"); |
| 779 | assert!(r.is_content(0, &before.0)); |
| 780 | r.crash_and_restart(); |
| 781 | // The world matches content_sha256 inside the workspace: DONE. |
| 782 | assert_eq!(r.states(), vec!["DONE"]); |
| 783 | let again = r.execute(&rep, grant); |
| 784 | assert_ne!(again.code, 0, "{}", again.all()); |
| 785 | names_error(&again, &["AlreadySpent"]); |
| 786 | let after = r.file(&r.path(0)).unwrap(); |
| 787 | assert_eq!( |
| 788 | (before.1, before.2, before.3), |
| 789 | (after.1, after.2, after.3), |
| 790 | "same inode and mtime: the file was written once" |
| 791 | ); |
| 792 | assert_eq!(r.intents().len(), 1); |
| 793 | r.detail = "SIGKILL at after_write; restart reconciled DONE; no second write".into(); |
| 794 | } |
| 795 | |
| 796 | /// R3b: same crash, but the file is changed while nothing is running. |
| 797 | #[test] |
| 798 | #[ignore = "needs AIEN_BIN: compose-linked CPU build with fault-hold"] |
| 799 | fn r3b_crash_after_write_then_file_modified_is_unresolved() { |
| 800 | let mut r = Rig::new("R3b"); |
| 801 | r.proposals(&["r3b.md"]); |
| 802 | let (rep, grant) = r.prepare(0); |
| 803 | r.execute_killed_at(&rep, grant, "after_write"); |
| 804 | r.kill_daemon(); |
| 805 | std::fs::write(r.ws().join(r.path(0)), "someone else wrote this\n").unwrap(); |
| 806 | r.start().unwrap_or_else(|d| panic!("restart: {}", d.log)); |
| 807 | let st = r.states(); |
| 808 | assert_eq!(st, vec!["UNRESOLVED"], "never DONE for changed bytes"); |
| 809 | let rc = r.cli(&["reconcile"]); |
| 810 | assert!( |
| 811 | rc.json["reconcile"]["outcomes"] |
| 812 | .as_array() |
| 813 | .map(|a| a.iter().all(|o| o["state"] != "DONE")) |
| 814 | .expect("reconcile outcomes"), |
| 815 | "{}", |
| 816 | rc.json |
| 817 | ); |
| 818 | assert_eq!(r.states(), vec!["UNRESOLVED"]); |
| 819 | assert_eq!( |
| 820 | std::fs::read_to_string(r.ws().join(r.path(0))).unwrap(), |
| 821 | "someone else wrote this\n", |
| 822 | "the daemon did not overwrite the modified file" |
| 823 | ); |
| 824 | r.detail = "SIGKILL at after_write; file modified; restart settled UNRESOLVED".into(); |
| 825 | } |
| 826 | |
| 827 | /// R4: damaged state is refused with a named error, never reset. |
| 828 | #[test] |
| 829 | #[ignore = "needs AIEN_BIN: compose-linked CPU build with fault-hold"] |
| 830 | fn r4_corrupted_state_is_refused_not_reinitialised() { |
| 831 | // (a) the compose ledger (Cortex journal), truncated between runs. |
| 832 | let mut r = Rig::new("R4"); |
| 833 | r.proposals(&["r4.md"]); |
| 834 | let (rep, grant) = r.prepare(0); |
| 835 | assert_eq!(r.execute(&rep, grant).json["state"], "DONE"); |
| 836 | r.kill_daemon(); |
| 837 | let cx = r.compose().join("cortex.cx"); |
| 838 | let len = std::fs::metadata(&cx).unwrap().len(); |
| 839 | let f = std::fs::OpenOptions::new().write(true).open(&cx).unwrap(); |
| 840 | f.set_len(len / 2).unwrap(); |
| 841 | drop(f); |
| 842 | let damaged = std::fs::read(&cx).unwrap(); |
| 843 | let verdict = match r.start() { |
| 844 | Err(d) => { |
| 845 | assert_ne!(d.code, Some(0), "{}", d.log); |
| 846 | assert!(!d.log.is_empty(), "a refusal says something"); |
| 847 | format!( |
| 848 | "daemon refused to start (code {:?}): {}", |
| 849 | d.code, |
| 850 | d.log.lines().last().unwrap_or("") |
| 851 | ) |
| 852 | } |
| 853 | Ok(()) => { |
| 854 | // Serving is allowed only if every compose command is refused. |
| 855 | let o = r.cli(&["recall"]); |
| 856 | assert!( |
| 857 | o.json["ok"] == json!(false) && o.json["error"].is_string(), |
| 858 | "damaged ledger answered as if healthy: {}", |
| 859 | o.all() |
| 860 | ); |
| 861 | let e = o.json["error"].as_str().unwrap().to_string(); |
| 862 | let o2 = r.cli(&["effects"]); |
| 863 | assert_ne!(o2.code, 0, "effects must not succeed: {}", o2.all()); |
| 864 | format!("compose refused with a named error: {e}") |
| 865 | } |
| 866 | }; |
| 867 | assert_eq!( |
| 868 | std::fs::read(&cx).unwrap(), |
| 869 | damaged, |
| 870 | "the damaged ledger was not silently reinitialised or repaired" |
| 871 | ); |
| 872 | assert!( |
| 873 | r.is_content(0, &r.file(&r.path(0)).unwrap().0), |
| 874 | "committed result untouched" |
| 875 | ); |
| 876 | r.detail = verdict; |
| 877 | r.kill_daemon(); |
| 878 | |
| 879 | // (b) the idempotency state file: damaged -> the daemon refuses to start. |
| 880 | let mut r2 = Rig::new("R4b"); |
| 881 | std::fs::write( |
| 882 | r2.root.join("state/processed_operations.json"), |
| 883 | b"{not json", |
| 884 | ) |
| 885 | .unwrap(); |
| 886 | let d = match r2.start() { |
| 887 | Err(d) => d, |
| 888 | Ok(()) => panic!("daemon started over damaged idempotency state"), |
| 889 | }; |
| 890 | assert_eq!(d.code, Some(1), "{}", d.log); |
| 891 | assert!( |
| 892 | d.log.contains("idempotency state") && d.log.contains("damaged"), |
| 893 | "{}", |
| 894 | d.log |
| 895 | ); |
| 896 | assert_eq!( |
| 897 | std::fs::read(r2.root.join("state/processed_operations.json")).unwrap(), |
| 898 | b"{not json", |
| 899 | "not reset" |
| 900 | ); |
| 901 | r2.detail = "idempotency state damaged: Fatal named, exit 1, file untouched".into(); |
| 902 | } |
| 903 | |
| 904 | /// R5: the CPU build says so; GPU demands are refused, never silently served by the CPU. |
| 905 | #[test] |
| 906 | #[ignore = "needs AIEN_BIN: compose-linked CPU build with fault-hold"] |
| 907 | fn r5_missing_gpu_is_honest() { |
| 908 | let mut r = Rig::new("R5"); |
| 909 | r.proposals(&["r5.md"]); |
| 910 | assert!(r.backend.contains("CPU-reference"), "{}", r.backend); |
| 911 | assert!(r.backend.contains("explicit fallback"), "{}", r.backend); |
| 912 | let log = (1..=r.nd) |
| 913 | .map(|n| std::fs::read_to_string(r.root.join(format!("daemon-{n}.log"))).unwrap()) |
| 914 | .collect::<Vec<_>>() |
| 915 | .join("\n"); |
| 916 | assert!( |
| 917 | !log.contains("Omega CTA budget:") && !log.contains("Omega marker spin:"), |
| 918 | "no GPU engine lines in a CPU build: {log}" |
| 919 | ); |
| 920 | let (rep, grant) = r.prepare(0); |
| 921 | let done = r.execute(&rep, grant); |
| 922 | assert_eq!(done.json["state"], "DONE", "{}", done.all()); |
| 923 | // No receipt, record or CLI output claims GPU execution. |
| 924 | let mut text = r.all_records_text() + &done.all(); |
| 925 | for e in std::fs::read_dir(r.root.join("prov")).unwrap().flatten() { |
| 926 | if e.path().is_file() { |
| 927 | text += &String::from_utf8_lossy(&std::fs::read(e.path()).unwrap()); |
| 928 | } |
| 929 | } |
| 930 | let low = text.to_lowercase(); |
| 931 | for w in ["gpu", "blackwell", "gb10", "omega_gpu", "cuda"] { |
| 932 | assert!(!low.contains(w), "a receipt or record mentions {w:?}"); |
| 933 | } |
| 934 | r.kill_daemon(); |
| 935 | // Demanding the GPU on a build without it is a refusal, not a CPU run. |
| 936 | for (k, v) in [ |
| 937 | ("AIEN_REQUIRE_BLACKWELL", "1"), |
| 938 | ("AIEN_GPU_BACKEND", "omega"), |
| 939 | ] { |
| 940 | let d = match r.start_with(&[(k, v)]) { |
| 941 | Err(d) => d, |
| 942 | Ok(()) => panic!("daemon served with {k}={v} on a CPU build"), |
| 943 | }; |
| 944 | assert_eq!(d.code, Some(1), "{k}: {}", d.log); |
| 945 | assert!(d.log.contains("GB10 GPU is required"), "{k}: {}", d.log); |
| 946 | assert!(!r.sock().exists()); |
| 947 | } |
| 948 | r.detail = |
| 949 | "CPU-reference reported; no GPU claim in records; GPU demand refused (exit 1)".into(); |
| 950 | } |
| 951 | |
| 952 | /// R6: stale, spent, revoked and replayed permission. |
| 953 | #[test] |
| 954 | #[ignore = "needs AIEN_BIN: compose-linked CPU build with fault-hold"] |
| 955 | fn r6_stale_permission_is_not_spendable() { |
| 956 | let mut r = Rig::new("R6"); |
| 957 | r.proposals(&["r6a.md", "r6b.md", "r6c.md"]); |
| 958 | // (a) minted by daemon A, spent, kill -9, daemon B: AlreadySpent, no second write. |
| 959 | let (rep, grant) = r.prepare(0); |
| 960 | assert_eq!(r.execute(&rep, grant).json["state"], "DONE"); |
| 961 | let first = r.file(&r.path(0)).unwrap(); |
| 962 | r.crash_and_restart(); |
| 963 | let again = r.execute(&rep, grant); |
| 964 | assert_ne!(again.code, 0, "{}", again.all()); |
| 965 | names_error(&again, &["AlreadySpent"]); |
| 966 | let second = r.file(&r.path(0)).unwrap(); |
| 967 | assert_eq!((first.1, first.2, first.3), (second.1, second.2, second.3)); |
| 968 | assert_eq!(r.intents().len(), 1); |
| 969 | |
| 970 | // (b) a revoked grant stays unusable, also across a kill -9 restart. |
| 971 | let (rep_b, grant_b) = r.prepare(1); |
| 972 | let rv = r.cli(&[ |
| 973 | "revoke", |
| 974 | "--authorization", |
| 975 | &grant_b.to_string(), |
| 976 | "--approver", |
| 977 | "drake", |
| 978 | ]); |
| 979 | assert_eq!(rv.code, 0, "{}", rv.all()); |
| 980 | r.crash_and_restart(); |
| 981 | let o = r.execute(&rep_b, grant_b); |
| 982 | assert_ne!(o.code, 0, "{}", o.all()); |
| 983 | names_error(&o, &["Revoked"]); |
| 984 | assert!(r.file(&r.path(1)).is_none()); |
| 985 | |
| 986 | // (c) a grant older than an operator stop stays stale after resume. |
| 987 | let (rep_c, grant_c) = r.prepare(2); |
| 988 | assert_eq!(r.cli(&["stop", "--approver", "drake"]).code, 0); |
| 989 | assert_eq!(r.cli(&["resume", "--approver", "drake"]).code, 0); |
| 990 | let o = r.execute(&rep_c, grant_c); |
| 991 | assert_ne!(o.code, 0, "{}", o.all()); |
| 992 | names_error(&o, &["Stale"]); |
| 993 | assert!(r.file(&r.path(2)).is_none()); |
| 994 | |
| 995 | // (d) authorizing the already-spent proposal again is refused AlreadySpent, |
| 996 | // after the stop + resume above (sc#320: before the fix a stop/resume made |
| 997 | // `authorize` skip the spent grant and mint a second one, and a second DONE |
| 998 | // effect ran). With the desk MAC on, a valid fresh (nonce, MAC) is refused |
| 999 | // the same way, and sending it again mints nothing either. |
| 1000 | let p0 = r.props[0].clone(); |
| 1001 | let before = r.file(&r.path(0)); |
| 1002 | let au = if r.mac { |
| 1003 | let nonce = "r6d-nonce"; |
| 1004 | let mac = r.desk_mac(&p0, nonce); |
| 1005 | let first = r.authorize_raw(&p0, Some((nonce, &mac))); |
| 1006 | let again = r.authorize_raw(&p0, Some((nonce, &mac))); |
| 1007 | assert_ne!(again.code, 0, "{}", again.all()); |
| 1008 | names_error(&again, &["AlreadySpent", "Replayed"]); |
| 1009 | first |
| 1010 | } else { |
| 1011 | r.authorize_raw(&p0, None) |
| 1012 | }; |
| 1013 | assert_ne!(au.code, 0, "second grant minted: {}", au.all()); |
| 1014 | names_error(&au, &["AlreadySpent"]); |
| 1015 | let o = r.execute(&rep, grant); |
| 1016 | assert_ne!(o.code, 0); |
| 1017 | assert_eq!(r.intents().len(), 1, "exactly one effect for the proposal"); |
| 1018 | assert_eq!(r.states(), vec!["DONE"]); |
| 1019 | assert_eq!(r.file(&r.path(0)), before, "file untouched by (d)"); |
| 1020 | r.detail = format!( |
| 1021 | "a-c PASS; (d) authorize on a spent proposal after stop+resume refused: {}", |
| 1022 | au.all().chars().take(120).collect::<String>() |
| 1023 | ); |
| 1024 | } |
| 1025 | |
| 1026 | /// Model B: the same tiny checkpoint with one weight byte changed (a different file digest). |
| 1027 | fn make_models(root: &Path) -> (PathBuf, PathBuf) { |
| 1028 | let src = |
| 1029 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../aien-inference-abi/fixtures/openwaldo-byte"); |
| 1030 | let a = root.join("model-a"); |
| 1031 | let b = root.join("model-b"); |
| 1032 | for d in [&a, &b] { |
| 1033 | std::fs::create_dir_all(d).unwrap(); |
| 1034 | for f in [ |
| 1035 | "config.json", |
| 1036 | "tokenizer.json", |
| 1037 | "model.safetensors", |
| 1038 | "generation_config.json", |
| 1039 | ] { |
| 1040 | let p = src.join(f); |
| 1041 | if p.exists() { |
| 1042 | std::fs::copy(&p, d.join(f)).unwrap(); |
| 1043 | } |
| 1044 | } |
| 1045 | } |
| 1046 | // Room for the daemon warm-up prompt and a chat turn (the fixture declares 16 positions). |
| 1047 | for d in [&a, &b] { |
| 1048 | let mut c: Value = |
| 1049 | serde_json::from_slice(&std::fs::read(d.join("config.json")).unwrap()).unwrap(); |
| 1050 | c["max_position_embeddings"] = json!(2048); |
| 1051 | std::fs::write(d.join("config.json"), c.to_string()).unwrap(); |
| 1052 | } |
| 1053 | // A Zephyr-layout chat template, so the daemon accepts a chat turn on a tiny test model. |
| 1054 | let tc = json!({"chat_template": |
| 1055 | "{% for m in messages %}<|user|>\n{{ m.content }}</s>\n{% endfor %}<|assistant|>\n"}); |
| 1056 | for d in [&a, &b] { |
| 1057 | std::fs::write(d.join("tokenizer_config.json"), tc.to_string()).unwrap(); |
| 1058 | } |
| 1059 | let mut w = std::fs::read(b.join("model.safetensors")).unwrap(); |
| 1060 | let n = w.len(); |
| 1061 | w[n - 1] ^= 0x01; |
| 1062 | std::fs::write(b.join("model.safetensors"), w).unwrap(); |
| 1063 | (a, b) |
| 1064 | } |
| 1065 | |
| 1066 | fn model_env(r: &mut Rig, dir: &Path) { |
| 1067 | r.env |
| 1068 | .retain(|(k, _)| k != "AIEN_MODEL_PATH" && k != "AIEN_TOKENIZER_PATH"); |
| 1069 | r.env |
| 1070 | .push(("AIEN_MODEL_PATH".into(), s(&dir.join("model.safetensors")))); |
| 1071 | r.env |
| 1072 | .push(("AIEN_TOKENIZER_PATH".into(), s(&dir.join("tokenizer.json")))); |
| 1073 | } |
| 1074 | |
| 1075 | /// Hex lineage (record 1 digest) and machine id of the home the daemon opened. |
| 1076 | fn home_lineage(r: &Rig) -> [u8; 32] { |
| 1077 | let o = r.cli(&["recall", "--ids", "1"]); |
| 1078 | assert_eq!(o.code, 0, "{}", o.all()); |
| 1079 | aien_allen::unhex32(o.json["recall"]["cited"][0]["digest"].as_str().unwrap()) |
| 1080 | .expect("record 1 digest is 32 bytes hex") |
| 1081 | } |
| 1082 | |
| 1083 | /// One generation by the daemon; returns its generation record id. |
| 1084 | fn generate(r: &Rig) -> u64 { |
| 1085 | let client = AienRuntimeClient::new(r.sock()); |
| 1086 | let result = r.rt.block_on(client.stream_turn_recorded( |
| 1087 | vec![ChatTurn { |
| 1088 | role: "user".into(), |
| 1089 | content: "hi".into(), |
| 1090 | }], |
| 1091 | 4, |
| 1092 | 0.0, |
| 1093 | )); |
| 1094 | match result { |
| 1095 | Ok((_, Some(id))) => id, |
| 1096 | Ok((_, None)) => panic!("the daemon wrote no generation record"), |
| 1097 | Err(error) => { |
| 1098 | // This fixture deliberately caps its generation. Incomplete output |
| 1099 | // is not a successful turn, but its daemon-owned record still exists. |
| 1100 | assert!(error.contains("max_tokens"), "{error}"); |
| 1101 | let report = |
| 1102 | r.rt.block_on(client.send_command( |
| 1103 | aien_runtime::control::ControlCommand::ComposeRecall { |
| 1104 | ids: vec![], |
| 1105 | prefix: None, |
| 1106 | }, |
| 1107 | )) |
| 1108 | .expect("recall evidence"); |
| 1109 | let aien_runtime::control::ControlResponse::ComposeRecalled(report) = report else { |
| 1110 | panic!("recall response") |
| 1111 | }; |
| 1112 | report |
| 1113 | .host |
| 1114 | .iter() |
| 1115 | .rev() |
| 1116 | .find_map(|record| { |
| 1117 | let value: Value = serde_json::from_str(record.text.as_deref()?).ok()?; |
| 1118 | (record.verified && value["generation"] == 1).then_some(record.id) |
| 1119 | }) |
| 1120 | .expect("the daemon retained generation evidence") |
| 1121 | } |
| 1122 | } |
| 1123 | } |
| 1124 | |
| 1125 | fn record_text(r: &Rig, id: u64) -> Value { |
| 1126 | let o = r.cli(&["recall", "--ids", &id.to_string()]); |
| 1127 | serde_json::from_str(o.json["recall"]["cited"][0]["text"].as_str().unwrap()).unwrap() |
| 1128 | } |
| 1129 | |
| 1130 | /// R7: the daemon restarts with a different model. |
| 1131 | #[test] |
| 1132 | #[ignore = "needs AIEN_BIN: compose-linked CPU build with fault-hold"] |
| 1133 | fn r7_different_model_on_restart() { |
| 1134 | let mut r = Rig::new("R7"); |
| 1135 | let (ma, mb) = make_models(&r.root); |
| 1136 | r.proposals(&["r7.md"]); |
| 1137 | r.kill_daemon(); |
| 1138 | model_env(&mut r, &ma); |
| 1139 | // Create the home, then engage ALLEN: a subject bound to this home's lineage, adopted once. |
| 1140 | r.start().unwrap(); |
| 1141 | let lineage = home_lineage(&r); |
| 1142 | r.kill_daemon(); |
| 1143 | let mut f = support::fx("r7"); |
| 1144 | f.cortex = lineage; |
| 1145 | let chain = support::chain(&f, 2); |
| 1146 | let subj = support::write_head(&r.root.join("subject.bin"), chain.last().unwrap()); |
| 1147 | r.env.push(("AIEN_ALLEN_SUBJECT".into(), s(&subj))); |
| 1148 | let agent = aien_allen::hex(&f.agent); |
| 1149 | r.start_with(&[("AIEN_ALLEN_ADOPT", &agent)]) |
| 1150 | .unwrap_or_else(|d| panic!("ALLEN adopt: {}", d.log)); |
| 1151 | let model_a = r.model.clone(); |
| 1152 | assert_ne!(model_a, "none", "the real checkpoint loaded with a digest"); |
| 1153 | let pin_bytes = std::fs::read(pin_path(&r.compose())).expect("pin written"); |
| 1154 | let (rep, grant) = r.prepare(0); |
| 1155 | assert_eq!(r.execute(&rep, grant).json["state"], "DONE"); |
| 1156 | let g1 = generate(&r); |
| 1157 | let rec1 = record_text(&r, g1); |
| 1158 | assert_eq!(rec1["model_sha256"], json!(model_a)); |
| 1159 | let done = r.file(&r.path(0)).unwrap(); |
| 1160 | |
| 1161 | // kill -9, restart with model B. |
| 1162 | r.kill_daemon(); |
| 1163 | model_env(&mut r, &mb); |
| 1164 | r.start() |
| 1165 | .unwrap_or_else(|d| panic!("restart on model B: {}", d.log)); |
| 1166 | assert_ne!( |
| 1167 | r.model, model_a, |
| 1168 | "the restart loaded a different file digest" |
| 1169 | ); |
| 1170 | let g2 = generate(&r); |
| 1171 | let rec2 = record_text(&r, g2); |
| 1172 | assert_eq!(rec2["model_sha256"], json!(r.model)); |
| 1173 | assert_ne!( |
| 1174 | rec1["model_sha256"], rec2["model_sha256"], |
| 1175 | "generation records show the change" |
| 1176 | ); |
| 1177 | // Earlier committed results remain; identity unchanged. |
| 1178 | assert_eq!(r.states(), vec!["DONE"]); |
| 1179 | let now = r.file(&r.path(0)).unwrap(); |
| 1180 | assert_eq!((done.0.clone(), done.1, done.2), (now.0, now.1, now.2)); |
| 1181 | assert_eq!( |
| 1182 | pin_bytes, |
| 1183 | std::fs::read(pin_path(&r.compose())).unwrap(), |
| 1184 | "ALLEN pin unchanged" |
| 1185 | ); |
| 1186 | let log2 = std::fs::read_to_string(r.root.join(format!("daemon-{}.log", r.nd))).unwrap(); |
| 1187 | assert!( |
| 1188 | log2.contains(&format!("ALLEN: engaged agent={agent} head_sequence=2")), |
| 1189 | "ALLEN identity unchanged: {log2}" |
| 1190 | ); |
| 1191 | r.detail = format!( |
| 1192 | "model {} -> {}; ALLEN agent {} unchanged", |
| 1193 | &model_a[..12], |
| 1194 | &r.model[..12], |
| 1195 | &agent[..12] |
| 1196 | ); |
| 1197 | } |
| 1198 | |
| 1199 | /// R8: a compose home pinned to another agent is refused; nothing executes. |
| 1200 | #[test] |
| 1201 | #[ignore = "needs AIEN_BIN: compose-linked CPU build with fault-hold"] |
| 1202 | fn r8_foreign_identity_is_refused() { |
| 1203 | let mut r = Rig::new("R8"); |
| 1204 | r.proposals(&["r8.md"]); |
| 1205 | let lineage = home_lineage(&r); |
| 1206 | r.kill_daemon(); |
| 1207 | // Agent A adopts the home. |
| 1208 | let mut fa = support::fx("agent-a"); |
| 1209 | fa.cortex = lineage; |
| 1210 | let subj_a = support::write_head( |
| 1211 | &r.root.join("a.bin"), |
| 1212 | support::chain(&fa, 2).last().unwrap(), |
| 1213 | ); |
| 1214 | let agent_a = aien_allen::hex(&fa.agent); |
| 1215 | r.start_with(&[ |
| 1216 | ("AIEN_ALLEN_SUBJECT", &s(&subj_a)), |
| 1217 | ("AIEN_ALLEN_ADOPT", &agent_a), |
| 1218 | ]) |
| 1219 | .unwrap_or_else(|d| panic!("adopt: {}", d.log)); |
| 1220 | let pin = std::fs::read(pin_path(&r.compose())).unwrap(); |
| 1221 | // A real grant minted by A, spent by nobody yet. |
| 1222 | let (rep, grant) = r.prepare(0); |
| 1223 | r.kill_daemon(); |
| 1224 | // Agent B (another logical agent, same lineage claim) starts over A's home. |
| 1225 | let mut fb = support::fx("agent-b"); |
| 1226 | fb.cortex = lineage; |
| 1227 | let subj_b = support::write_head( |
| 1228 | &r.root.join("b.bin"), |
| 1229 | support::chain(&fb, 2).last().unwrap(), |
| 1230 | ); |
| 1231 | let d = match r.start_with(&[("AIEN_ALLEN_SUBJECT", &s(&subj_b))]) { |
| 1232 | Err(d) => d, |
| 1233 | Ok(()) => { |
| 1234 | // The home opens lazily: the first compose call must be fatal. |
| 1235 | let _ = r.cli(&["recall"]); |
| 1236 | std::thread::sleep(Duration::from_millis(500)); |
| 1237 | let child = r.daemon.take().unwrap(); |
| 1238 | let log = r.root.join(format!("daemon-{}.log", r.nd)); |
| 1239 | r.down_of(child, &log) |
| 1240 | } |
| 1241 | }; |
| 1242 | assert_eq!( |
| 1243 | d.code, |
| 1244 | Some(aien_allen::EXIT_REFUSED), |
| 1245 | "signal {:?}: {}", |
| 1246 | d.signal, |
| 1247 | d.log |
| 1248 | ); |
| 1249 | assert!(d.log.contains("FATAL ALLEN refused"), "{}", d.log); |
| 1250 | let refusal = d |
| 1251 | .log |
| 1252 | .lines() |
| 1253 | .find(|l| l.contains("FATAL ALLEN refused")) |
| 1254 | .unwrap() |
| 1255 | .to_string(); |
| 1256 | assert_eq!( |
| 1257 | pin, |
| 1258 | std::fs::read(pin_path(&r.compose())).unwrap(), |
| 1259 | "not rebound" |
| 1260 | ); |
| 1261 | assert!(r.file(&r.path(0)).is_none(), "nothing executed"); |
| 1262 | // Under B: a real grant is not spendable (no daemon serves B), and a fresh |
| 1263 | // desk-style request has nothing to talk to. |
| 1264 | let o = r.execute(&rep, grant); |
| 1265 | assert_ne!(o.code, 0, "{}", o.all()); |
| 1266 | assert_ne!(o.json["state"], "DONE", "{}", o.all()); |
| 1267 | assert!(r.file(&r.path(0)).is_none(), "B executed A's grant"); |
| 1268 | // Positive control: the same grant is real, A executes it exactly once. |
| 1269 | r.start_with(&[("AIEN_ALLEN_SUBJECT", &s(&subj_a))]) |
| 1270 | .unwrap_or_else(|d| panic!("agent A restart: {}", d.log)); |
| 1271 | assert!(r.intents().is_empty(), "no effect was opened under B"); |
| 1272 | let ok = r.execute(&rep, grant); |
| 1273 | assert_eq!(ok.json["state"], "DONE", "{}", ok.all()); |
| 1274 | assert_eq!(r.intents().len(), 1); |
| 1275 | r.detail = refusal.chars().take(200).collect(); |
| 1276 | } |
| 1277 | |
| 1278 | /// M1: an authorize MAC replayed after a SIGKILL restart is `Replayed`, with no |
| 1279 | /// second grant. The desk MAC is on in both matrix modes (the row is about it). |
| 1280 | #[test] |
| 1281 | #[ignore = "needs AIEN_BIN: compose-linked CPU build with fault-hold"] |
| 1282 | fn m1_mac_replay_across_sigkill_restart() { |
| 1283 | let mut r = Rig::with_mac("M1", true); |
| 1284 | r.proposals(&["m1.md"]); |
| 1285 | let p = r.props[0].clone(); |
| 1286 | let nonce = "m1-nonce"; |
| 1287 | let mac = r.desk_mac(&p, nonce); |
| 1288 | let ok = r.authorize_raw(&p, Some((nonce, &mac))); |
| 1289 | assert_eq!(ok.code, 0, "{}", ok.all()); |
| 1290 | let grant = ok.json["authorization"]["id"].as_u64().expect("grant id"); |
| 1291 | // Real-process crash mid-effect, then SIGKILL of the daemon and a restart. |
| 1292 | r.execute_killed_at(&p.report, grant, "after_write"); |
| 1293 | r.crash_and_restart(); |
| 1294 | assert_eq!(r.states(), vec!["DONE"]); |
| 1295 | let replay = r.authorize_raw(&p, Some((nonce, &mac))); |
| 1296 | assert_ne!(replay.code, 0, "{}", replay.all()); |
| 1297 | names_error(&replay, &["Replayed"]); |
| 1298 | // No second grant: the only grant is spent, the next id does not exist, and |
| 1299 | // the ledger still holds the one effect. |
| 1300 | let again = r.execute(&p.report, grant); |
| 1301 | assert_ne!(again.code, 0, "{}", again.all()); |
| 1302 | names_error(&again, &["AlreadySpent"]); |
| 1303 | let next = r.execute(&p.report, grant + 1); |
| 1304 | assert_ne!(next.code, 0, "{}", next.all()); |
| 1305 | assert_ne!(next.json["state"], "DONE", "{}", next.all()); |
| 1306 | assert_eq!(r.intents().len(), 1); |
| 1307 | // A second replay after a second kill -9 restart is still refused. |
| 1308 | r.crash_and_restart(); |
| 1309 | let replay2 = r.authorize_raw(&p, Some((nonce, &mac))); |
| 1310 | names_error(&replay2, &["Replayed"]); |
| 1311 | r.detail = "SIGKILL at after_write; restart DONE; same nonce+MAC twice (across 2 restarts) -> Replayed; grant+1 does not exist".into(); |
| 1312 | } |
| 1313 | |
| 1314 | /// M2: the desk key is rotated while an intent is in flight (SIGKILL at |
| 1315 | /// fault_hold). The old key's MAC is refused afterwards, and the ambiguous |
| 1316 | /// outcome (the file changed while nothing ran) stays UNRESOLVED, never DONE. |
| 1317 | #[test] |
| 1318 | #[ignore = "needs AIEN_BIN: compose-linked CPU build with fault-hold"] |
| 1319 | fn m2_rotated_desk_key_during_inflight_intent() { |
| 1320 | let mut r = Rig::with_mac("M2", true); |
| 1321 | r.proposals(&["m2.md"]); |
| 1322 | let p = r.props[0].clone(); |
| 1323 | let (n1, n2) = ("m2-nonce-1", "m2-nonce-2"); |
| 1324 | let mac1 = r.desk_mac(&p, n1); |
| 1325 | let old_key_mac2 = r.desk_mac(&p, n2); // signed by the key that is about to go |
| 1326 | let ok = r.authorize_raw(&p, Some((n1, &mac1))); |
| 1327 | assert_eq!(ok.code, 0, "{}", ok.all()); |
| 1328 | let grant = ok.json["authorization"]["id"].as_u64().expect("grant id"); |
| 1329 | r.execute_killed_at(&p.report, grant, "after_write"); |
| 1330 | r.kill_daemon(); |
| 1331 | // Ambiguity: someone else changes the file; the desk key is rotated. |
| 1332 | std::fs::write(r.ws().join(r.path(0)), "someone else wrote this\n").unwrap(); |
| 1333 | r.rotate_desk_key(); |
| 1334 | r.start().unwrap_or_else(|d| panic!("restart: {}", d.log)); |
| 1335 | assert_eq!( |
| 1336 | r.states(), |
| 1337 | vec!["UNRESOLVED"], |
| 1338 | "never DONE for changed bytes" |
| 1339 | ); |
| 1340 | // The old MACs are refused (a fresh nonce under the old key; the used one). |
| 1341 | let stale = r.authorize_raw(&p, Some((n2, &old_key_mac2))); |
| 1342 | assert_ne!(stale.code, 0, "{}", stale.all()); |
| 1343 | names_error(&stale, &["DeskMacInvalid"]); |
| 1344 | let used = r.authorize_raw(&p, Some((n1, &mac1))); |
| 1345 | assert_ne!(used.code, 0, "{}", used.all()); |
| 1346 | names_error(&used, &["DeskMacInvalid", "Replayed"]); |
| 1347 | let used_why = used.all().chars().take(100).collect::<String>(); |
| 1348 | // Control: the rotated key's MAC is accepted by the MAC check itself (it is |
| 1349 | // then refused further on because the proposal is already spent/unresolved, |
| 1350 | // which is not a MAC error). |
| 1351 | let fresh = r.desk_mac(&p, "m2-nonce-3"); |
| 1352 | let ctl = r.authorize_raw(&p, Some(("m2-nonce-3", &fresh))); |
| 1353 | let ctl_text = ctl.all(); |
| 1354 | assert!( |
| 1355 | !ctl_text.contains("DeskMacInvalid") && !ctl_text.contains("DeskMacRequired"), |
| 1356 | "rotated key rejected by the MAC check: {ctl_text}" |
| 1357 | ); |
| 1358 | // ...and an UNRESOLVED intent is unsettled: no new grant until reconcile |
| 1359 | // (sc#320: never a second effect for the same commit). |
| 1360 | assert_ne!(ctl.code, 0, "{ctl_text}"); |
| 1361 | names_error(&ctl, &["ReconciliationRequired"]); |
| 1362 | let rc = r.cli(&["reconcile"]); |
| 1363 | assert!( |
| 1364 | rc.json["reconcile"]["outcomes"] |
| 1365 | .as_array() |
| 1366 | .map(|a| a.iter().all(|o| o["state"] != "DONE")) |
| 1367 | .expect("reconcile outcomes"), |
| 1368 | "{}", |
| 1369 | rc.json |
| 1370 | ); |
| 1371 | assert_eq!(r.states(), vec!["UNRESOLVED"], "never DONE"); |
| 1372 | assert_eq!( |
| 1373 | std::fs::read_to_string(r.ws().join(r.path(0))).unwrap(), |
| 1374 | "someone else wrote this\n" |
| 1375 | ); |
| 1376 | r.detail = format!( |
| 1377 | "SIGKILL at after_write; file changed; desk key rotated; old-key MAC DeskMacInvalid; used MAC: {used_why}; UNRESOLVED kept; control (new key) passes MAC check, then ReconciliationRequired: code {}", |
| 1378 | ctl.code |
| 1379 | ); |
| 1380 | } |
| 1381 | |
| 1382 | /// R9: memory leakage, on the real composed path with a live SmolLM2 proposer. |
| 1383 | /// A note remembered in one context never reaches a task in another; a forgotten |
| 1384 | /// note is gone; an unreadable (key-missing) note is counted, never shown. |
| 1385 | /// LIMIT: the memory block is part of the model prompt, which the daemon does not |
| 1386 | /// expose; so "not shown" is checked on the MemoryReport counts and on every |
| 1387 | /// observable the daemon writes (task output, records, logs, provenance). |
| 1388 | #[test] |
| 1389 | #[ignore = "needs AIEN_BIN: compose-linked CPU build with fault-hold"] |
| 1390 | fn r9_memory_does_not_leak() { |
| 1391 | let mut r = Rig::new("R9"); |
| 1392 | // Home, then ALLEN engaged (as R8). |
| 1393 | r.start().unwrap(); |
| 1394 | let lineage = home_lineage(&r); |
| 1395 | r.kill_daemon(); |
| 1396 | let mut f = support::fx("r9"); |
| 1397 | f.cortex = lineage; |
| 1398 | let subj = support::write_head( |
| 1399 | &r.root.join("subject.bin"), |
| 1400 | support::chain(&f, 2).last().unwrap(), |
| 1401 | ); |
| 1402 | r.env.push(("AIEN_ALLEN_SUBJECT".into(), s(&subj))); |
| 1403 | let agent = aien_allen::hex(&f.agent); |
| 1404 | r.start_with(&[("AIEN_ALLEN_ADOPT", &agent)]) |
| 1405 | .unwrap_or_else(|d| panic!("ALLEN adopt: {}", d.log)); |
| 1406 | r.kill_daemon(); |
| 1407 | // The live proposer for the rest of the case. |
| 1408 | let m = PathBuf::from(std::env::var("AIEN_PROPOSER_MODEL").unwrap_or_else(|_| { |
| 1409 | format!( |
| 1410 | "{}/models/SmolLM2-1.7B-Instruct-31b70e2e869a", |
| 1411 | std::env::var("HOME").unwrap() |
| 1412 | ) |
| 1413 | })); |
| 1414 | r.env |
| 1415 | .push(("AIEN_MODEL_PATH".into(), s(&m.join("model.safetensors")))); |
| 1416 | r.env |
| 1417 | .push(("AIEN_TOKENIZER_PATH".into(), s(&m.join("tokenizer.json")))); |
| 1418 | r.env |
| 1419 | .push(("AIEN_COMPOSE_EDIT_BUDGET_MS".into(), "590000".into())); |
| 1420 | r.env |
| 1421 | .push(("AIEN_COMPOSE_DOC_BUDGET_MS".into(), "590000".into())); |
| 1422 | r.start() |
| 1423 | .unwrap_or_else(|d| panic!("proposer daemon: {}", d.log)); |
| 1424 | |
| 1425 | let put = |r: &Rig, ctx: &str, text: &str| { |
| 1426 | let o = r.allen(&["memory", "put", "--context", ctx, "--text", text]); |
| 1427 | assert_eq!(o.code, 0, "put {ctx}: {}", o.all()); |
| 1428 | }; |
| 1429 | let (a1, a2) = ( |
| 1430 | "ZEBRA-ALPHA-7731 lives only in personal", |
| 1431 | "ZEBRA-ALPHA-7732 also personal", |
| 1432 | ); |
| 1433 | let b1 = "KIWI-BETA-4420 lives only in work"; |
| 1434 | put(&r, "personal", a1); |
| 1435 | put(&r, "personal", a2); |
| 1436 | put(&r, "work", b1); |
| 1437 | |
| 1438 | // No context named: no memory at all. |
| 1439 | let (o0, m0) = r.propose_memory(None); |
| 1440 | assert_eq!(m0["state"], "not_requested", "{}", o0.all()); |
| 1441 | assert_eq!(m0["items_included"], 0); |
| 1442 | |
| 1443 | // Test 1: a task in context B (work) sees B's one note, none of A's. |
| 1444 | let before = r.observable_lines(); |
| 1445 | let (ob, mb) = r.propose_memory(Some("work")); |
| 1446 | assert_eq!(mb["context"], "work", "{mb}"); |
| 1447 | assert_eq!(mb["state"], "included", "{mb}"); |
| 1448 | assert_eq!(mb["items_included"], 1, "only the work note: {mb}"); |
| 1449 | assert_eq!(mb["items_unresolved"], 0, "{mb}"); |
| 1450 | let new_b: String = r |
| 1451 | .observable_lines() |
| 1452 | .difference(&before) |
| 1453 | .cloned() |
| 1454 | .collect::<Vec<_>>() |
| 1455 | .join("\n") |
| 1456 | + &ob.all(); |
| 1457 | assert!( |
| 1458 | !new_b.contains("ZEBRA-ALPHA"), |
| 1459 | "a personal note appeared in a work task: {new_b}" |
| 1460 | ); |
| 1461 | // And the other way round: a personal task has two notes, never the work one. |
| 1462 | let before = r.observable_lines(); |
| 1463 | let (oa, ma) = r.propose_memory(Some("personal")); |
| 1464 | assert_eq!(ma["items_included"], 2, "{ma}"); |
| 1465 | let new_a: String = r |
| 1466 | .observable_lines() |
| 1467 | .difference(&before) |
| 1468 | .cloned() |
| 1469 | .collect::<Vec<_>>() |
| 1470 | .join("\n") |
| 1471 | + &oa.all(); |
| 1472 | assert!( |
| 1473 | !new_a.contains("KIWI-BETA"), |
| 1474 | "a work note appeared in a personal task: {new_a}" |
| 1475 | ); |
| 1476 | |
| 1477 | // Test 2: forget the work note; the next work task has none, text is gone. |
| 1478 | let rec = r.allen(&["memory", "recall", "--context", "work"]); |
| 1479 | let item = rec.json["result"]["result"]["items"][0]["item"] |
| 1480 | .as_str() |
| 1481 | .unwrap_or_else(|| panic!("work item id in {}", rec.all())) |
| 1482 | .to_string(); |
| 1483 | let fg = r.allen(&["memory", "forget", "--context", "work", "--item", &item]); |
| 1484 | assert_eq!(fg.code, 0, "{}", fg.all()); |
| 1485 | let before = r.observable_lines(); |
| 1486 | let (of, mf) = r.propose_memory(Some("work")); |
| 1487 | assert_eq!( |
| 1488 | mf["items_included"], 0, |
| 1489 | "forgotten note still included: {mf}" |
| 1490 | ); |
| 1491 | assert_eq!(mf["items_unresolved"], 0, "{mf}"); |
| 1492 | let rec2 = r.allen(&["memory", "recall", "--context", "work"]); |
| 1493 | let new_f: String = r |
| 1494 | .observable_lines() |
| 1495 | .difference(&before) |
| 1496 | .cloned() |
| 1497 | .collect::<Vec<_>>() |
| 1498 | .join("\n") |
| 1499 | + &of.all() |
| 1500 | + &rec2.all(); |
| 1501 | assert!( |
| 1502 | !new_f.contains("KIWI-BETA"), |
| 1503 | "a forgotten note is still visible: {new_f}" |
| 1504 | ); |
| 1505 | |
| 1506 | // Test 3: a note whose key is gone is counted unresolved and never shown. |
| 1507 | let keys_before = r.memory_keys(); |
| 1508 | let secret = "OPAL-GAMMA-9915 unreadable on purpose"; |
| 1509 | put(&r, "project:r9c", secret); |
| 1510 | let new_keys: Vec<_> = r.memory_keys().difference(&keys_before).cloned().collect(); |
| 1511 | assert_eq!(new_keys.len(), 1, "one new key file: {new_keys:?}"); |
| 1512 | std::fs::remove_file(&new_keys[0]).unwrap(); |
| 1513 | let before = r.observable_lines(); |
| 1514 | let (ou, mu) = r.propose_memory(Some("project:r9c")); |
| 1515 | assert_eq!(mu["items_unresolved"], 1, "{mu}"); |
| 1516 | assert_eq!(mu["items_included"], 0, "{mu}"); |
| 1517 | let rec3 = r.allen(&["memory", "recall", "--context", "project:r9c"]); |
| 1518 | let new_u: String = r |
| 1519 | .observable_lines() |
| 1520 | .difference(&before) |
| 1521 | .cloned() |
| 1522 | .collect::<Vec<_>>() |
| 1523 | .join("\n") |
| 1524 | + &ou.all() |
| 1525 | + &rec3.all(); |
| 1526 | assert!( |
| 1527 | !new_u.contains("OPAL-GAMMA"), |
| 1528 | "an unreadable note's text was shown: {new_u}" |
| 1529 | ); |
| 1530 | r.detail = format!( |
| 1531 | "work={} personal={} after-forget={} key-missing: unresolved={} included={}; block text itself not observable (UNVERIFIED), counts + all observables checked", |
| 1532 | mb["items_included"], ma["items_included"], mf["items_included"], |
| 1533 | mu["items_unresolved"], mu["items_included"] |
| 1534 | ); |
| 1535 | } |