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 / allen_concurrency_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 | //! ALLEN under concurrent clients (arch#162): ONE real `aien daemon` process, |
| 17 | //! many real `aien allen ...` CLI processes at the same time over the real |
| 18 | //! socket. No in-process fakes: every call is an OS process, the crash is a |
| 19 | //! real SIGKILL of the daemon in the middle of a write burst. |
| 20 | //! |
| 21 | //! Points proved (ids are used in the assertion messages): |
| 22 | //! C1 identity: ALLEN is engaged once at daemon boot (not by clients), so this proves |
| 23 | //! one identity served consistently to concurrent clients: one agent, one pin, |
| 24 | //! one "ALLEN: engaged" line, unchanged after kill -9 + restart. It does NOT |
| 25 | //! claim concurrent creation of the identity. |
| 26 | //! C2 scoped memory: concurrent writers into work and personal; every item |
| 27 | //! present exactly once in its own scope; recall never crosses scopes. |
| 28 | //! C3 correction: concurrent corrections of one item end in one coherent |
| 29 | //! final value and version == 1 + number of acknowledged corrections. |
| 30 | //! C4 forgetting racing reads: no read that starts after forget returned |
| 31 | //! shows the canary; the item's key file exists before forget and is gone after |
| 32 | //! (the ciphertext stays in the immutable log; plaintext is never on disk, so a |
| 33 | //! plaintext file scan would prove nothing and is not used). |
| 34 | //! C5 recovery: kill -9 mid write burst, restart: identity unchanged, every |
| 35 | //! acknowledged write present, nothing half-present, forgotten stays so. |
| 36 | //! C6 persona: concurrent profile changes with the same expected revision |
| 37 | //! produce exactly one winner; a permission-looking key is refused. |
| 38 | //! LIMIT: that persona text cannot widen what compose may do is covered |
| 39 | //! by the profile crate's own tests and the approval desk, not here. |
| 40 | //! |
| 41 | //! No model is needed: memory commands never call one, the daemon runs with no |
| 42 | //! model path. Host CPU only. Needs a compose-linked `aien-cli` (the same |
| 43 | //! build the recovery matrix uses); run: |
| 44 | //! |
| 45 | //! ```text |
| 46 | //! env -u AIEN_OMEGA_DIR AIEN_OMEGA_COMPOSE_LIB=<librx_compose.a> CARGO_TARGET_DIR=<dir> \ |
| 47 | //! cargo test -p aien-cli --test allen_concurrency_test -- --ignored --nocapture |
| 48 | //! ``` |
| 49 | #[path = "../../aien-allen/tests/support/mod.rs"] |
| 50 | mod support; |
| 51 | |
| 52 | use aien_allen::binding::pin_path; |
| 53 | use serde_json::{json, Value}; |
| 54 | use std::collections::{BTreeMap, BTreeSet}; |
| 55 | use std::os::unix::process::{CommandExt, ExitStatusExt}; |
| 56 | use std::path::{Path, PathBuf}; |
| 57 | use std::process::{Child, Command, Stdio}; |
| 58 | use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; |
| 59 | use std::sync::Mutex; |
| 60 | use std::time::Duration; |
| 61 | |
| 62 | const CANARY: &str = "CONC-CANARY-5519-nobody-may-keep-this"; |
| 63 | |
| 64 | struct Out { |
| 65 | code: i32, |
| 66 | json: Value, |
| 67 | raw: String, |
| 68 | } |
| 69 | |
| 70 | impl Out { |
| 71 | fn ok(&self) -> bool { |
| 72 | self.code == 0 && self.json["ok"] == true |
| 73 | } |
| 74 | fn refusal(&self) -> Option<String> { |
| 75 | self.json["refused"]["code"].as_str().map(str::to_string) |
| 76 | } |
| 77 | fn result(&self) -> &Value { |
| 78 | &self.json["result"]["result"] |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | struct Rig { |
| 83 | _tmp: tempfile::TempDir, |
| 84 | root: PathBuf, |
| 85 | bin: PathBuf, |
| 86 | daemon: Option<Child>, |
| 87 | nd: u32, |
| 88 | env: Vec<(String, String)>, |
| 89 | } |
| 90 | |
| 91 | impl Rig { |
| 92 | fn new() -> Rig { |
| 93 | let bin = PathBuf::from( |
| 94 | std::env::var("AIEN_BIN").unwrap_or_else(|_| env!("CARGO_BIN_EXE_aien-cli").into()), |
| 95 | ); |
| 96 | // Short path: unix socket paths are limited to 108 bytes. |
| 97 | let tmp = tempfile::Builder::new() |
| 98 | .prefix("ac-") |
| 99 | .tempdir_in("/tmp") |
| 100 | .unwrap(); |
| 101 | let root = std::fs::canonicalize(tmp.path()).unwrap(); |
| 102 | for d in ["ws", "state", "home", "prov"] { |
| 103 | std::fs::create_dir_all(root.join(d)).unwrap(); |
| 104 | } |
| 105 | // sc#328: the daemon refuses to start without the (default) desk key. |
| 106 | aien_runtime::approved_auth::DeskKey::create(&aien_runtime::approved_auth::desk_key_path( |
| 107 | &root.join("compose"), |
| 108 | )) |
| 109 | .unwrap(); |
| 110 | Rig { |
| 111 | _tmp: tmp, |
| 112 | root, |
| 113 | bin, |
| 114 | daemon: None, |
| 115 | nd: 0, |
| 116 | env: Vec::new(), |
| 117 | } |
| 118 | } |
| 119 | fn sock(&self) -> PathBuf { |
| 120 | self.root.join("s") |
| 121 | } |
| 122 | fn compose(&self) -> PathBuf { |
| 123 | self.root.join("compose") |
| 124 | } |
| 125 | fn cmd_env(&self, c: &mut Command) { |
| 126 | c.current_dir(&self.root) |
| 127 | .env("HOME", self.root.join("home")) |
| 128 | .env("NO_COLOR", "1") |
| 129 | .env("AIEN_RUNTIME_SOCK", self.sock()) |
| 130 | .env("AIEN_RUNTIME_STATE_DIR", self.root.join("state")) |
| 131 | .env("AIEN_COMPOSE_DIR", self.compose()) |
| 132 | .env("AIEN_PROVENANCE_DIR", self.root.join("prov")) |
| 133 | .env("AIEN_REQUIRE_CHECKPOINT", "0"); |
| 134 | for k in [ |
| 135 | "AIEN_OMEGA_DIR", |
| 136 | "AIEN_OMEGA_GPU_LIB", |
| 137 | "AIEN_REQUIRE_BLACKWELL", |
| 138 | "AIEN_GPU_BACKEND", |
| 139 | "AIEN_MODEL_PATH", |
| 140 | "AIEN_TOKENIZER_PATH", |
| 141 | "AIEN_MODEL_DIR", |
| 142 | "AIEN_ALLEN_SUBJECT", |
| 143 | "AIEN_ALLEN_ADOPT", |
| 144 | "AIEN_FAULT_HOLD", |
| 145 | "AIEN_FAULT_HOLD_FILE", |
| 146 | ] { |
| 147 | c.env_remove(k); |
| 148 | } |
| 149 | for (k, v) in &self.env { |
| 150 | c.env(k, v); |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | /// Start the daemon; returns its log path. Panics when it does not serve. |
| 155 | fn start_with(&mut self, once: &[(&str, &str)]) -> PathBuf { |
| 156 | assert!(self.daemon.is_none()); |
| 157 | self.nd += 1; |
| 158 | let log = self.root.join(format!("daemon-{}.log", self.nd)); |
| 159 | let f = std::fs::File::create(&log).unwrap(); |
| 160 | let _ = std::fs::remove_file(self.sock()); |
| 161 | let mut c = Command::new(&self.bin); |
| 162 | c.arg("daemon"); |
| 163 | self.cmd_env(&mut c); |
| 164 | for (k, v) in once { |
| 165 | c.env(k, v); |
| 166 | } |
| 167 | c.process_group(0) |
| 168 | .stdin(Stdio::null()) |
| 169 | .stdout(f.try_clone().unwrap()) |
| 170 | .stderr(f); |
| 171 | self.daemon = Some(c.spawn().expect("spawn daemon")); |
| 172 | for _ in 0..1200 { |
| 173 | std::thread::sleep(Duration::from_millis(50)); |
| 174 | if let Some(st) = self.daemon.as_mut().unwrap().try_wait().unwrap() { |
| 175 | self.daemon = None; |
| 176 | panic!( |
| 177 | "daemon exited early ({st:?}): {}", |
| 178 | std::fs::read_to_string(&log).unwrap_or_default() |
| 179 | ); |
| 180 | } |
| 181 | let text = std::fs::read_to_string(&log).unwrap_or_default(); |
| 182 | if self.sock().exists() && text.contains("Replay reconcile:") { |
| 183 | let line = text.lines().find(|l| l.contains("Backend:")).unwrap_or(""); |
| 184 | assert!( |
| 185 | line.contains("CPU-reference"), |
| 186 | "daemon is not the CPU reference build ({line}); no GPU use here" |
| 187 | ); |
| 188 | return log; |
| 189 | } |
| 190 | } |
| 191 | self.kill(); |
| 192 | panic!("daemon did not come up in 60 s"); |
| 193 | } |
| 194 | |
| 195 | /// SIGKILL (kill -9) and reap; asserts it really died by signal 9. |
| 196 | fn kill(&mut self) { |
| 197 | if let Some(mut c) = self.daemon.take() { |
| 198 | let _ = c.kill(); |
| 199 | let st = c.wait().unwrap(); |
| 200 | assert_eq!(st.signal(), Some(9), "daemon end: {st:?}"); |
| 201 | } |
| 202 | let _ = std::fs::remove_file(self.sock()); |
| 203 | } |
| 204 | |
| 205 | fn run(&self, group: &str, args: &[&str]) -> Out { |
| 206 | let mut c = Command::new(&self.bin); |
| 207 | c.arg(group).args(args); |
| 208 | self.cmd_env(&mut c); |
| 209 | let o = c.output().expect("run aien"); |
| 210 | let raw = String::from_utf8_lossy(&o.stdout).to_string(); |
| 211 | let json = raw |
| 212 | .lines() |
| 213 | .rev() |
| 214 | .find_map(|l| serde_json::from_str::<Value>(l).ok()) |
| 215 | .unwrap_or_else(|| json!({"unparsed": raw})); |
| 216 | Out { |
| 217 | code: o.status.code().unwrap_or(-1), |
| 218 | json, |
| 219 | raw, |
| 220 | } |
| 221 | } |
| 222 | fn allen(&self, args: &[&str]) -> Out { |
| 223 | self.run("allen", args) |
| 224 | } |
| 225 | |
| 226 | fn rows(&self) -> Vec<Value> { |
| 227 | let o = self.allen(&["memory", "inspect", "--owner", "1"]); |
| 228 | assert!(o.ok(), "inspect: {}", o.raw); |
| 229 | o.result().as_array().expect("inspect rows").clone() |
| 230 | } |
| 231 | fn rows_of(&self, ctx: &str) -> Vec<Value> { |
| 232 | let o = self.allen(&["memory", "inspect", "--context", ctx]); |
| 233 | assert!(o.ok(), "inspect {ctx}: {}", o.raw); |
| 234 | o.result().as_array().expect("inspect rows").clone() |
| 235 | } |
| 236 | fn recall_texts(&self, ctx: &str) -> (Out, Vec<String>) { |
| 237 | self.recall_query(ctx, None) |
| 238 | } |
| 239 | /// recall is capped (16 items), so racing reads ask for the canary by substring. |
| 240 | fn recall_query(&self, ctx: &str, q: Option<&str>) -> (Out, Vec<String>) { |
| 241 | let mut a = vec!["memory", "recall", "--context", ctx]; |
| 242 | if let Some(q) = q { |
| 243 | a.extend(["--query", q]); |
| 244 | } |
| 245 | let o = self.allen(&a); |
| 246 | let t = o.result()["items"] |
| 247 | .as_array() |
| 248 | .map(|a| { |
| 249 | a.iter() |
| 250 | .filter_map(|r| r["text"].as_str().map(str::to_string)) |
| 251 | .collect() |
| 252 | }) |
| 253 | .unwrap_or_default(); |
| 254 | (o, t) |
| 255 | } |
| 256 | |
| 257 | /// The store directory `<compose>.allen-memory` (read-only use in this test). |
| 258 | fn mem_dir(&self) -> PathBuf { |
| 259 | PathBuf::from(format!("{}.allen-memory", self.compose().display())) |
| 260 | } |
| 261 | /// Key files of one item (`keys/<item>-v<n>.key`). The store keeps ciphertext in |
| 262 | /// its immutable log and destroys KEYS to forget or supersede (store.rs header). |
| 263 | fn key_files(&self, item: &str) -> Vec<String> { |
| 264 | let mut v: Vec<String> = std::fs::read_dir(self.mem_dir().join("keys")) |
| 265 | .into_iter() |
| 266 | .flatten() |
| 267 | .flatten() |
| 268 | .map(|e| e.file_name().to_string_lossy().to_string()) |
| 269 | .filter(|n| n.starts_with(&format!("{item}-v")) && n.ends_with(".key")) |
| 270 | .collect(); |
| 271 | v.sort(); |
| 272 | v |
| 273 | } |
| 274 | /// Log record files whose bytes name the item (its ciphertext records). |
| 275 | fn log_records_of(&self, item: &str) -> usize { |
| 276 | std::fs::read_dir(self.mem_dir().join("log")) |
| 277 | .into_iter() |
| 278 | .flatten() |
| 279 | .flatten() |
| 280 | .filter(|e| { |
| 281 | std::fs::read(e.path()) |
| 282 | .map(|b| b.windows(item.len()).any(|w| w == item.as_bytes())) |
| 283 | .unwrap_or(false) |
| 284 | }) |
| 285 | .count() |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | impl Drop for Rig { |
| 290 | fn drop(&mut self) { |
| 291 | if let Some(mut c) = self.daemon.take() { |
| 292 | let _ = c.kill(); |
| 293 | let _ = c.wait(); |
| 294 | } |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | fn s(p: &Path) -> String { |
| 299 | p.to_string_lossy().to_string() |
| 300 | } |
| 301 | |
| 302 | fn engaged_lines(log: &Path, agent: &str) -> usize { |
| 303 | std::fs::read_to_string(log) |
| 304 | .unwrap_or_default() |
| 305 | .lines() |
| 306 | .filter(|l| l.starts_with("ALLEN: engaged agent=")) |
| 307 | .filter(|l| l.contains(agent)) |
| 308 | .count() |
| 309 | } |
| 310 | |
| 311 | fn all_engaged_lines(log: &Path) -> usize { |
| 312 | std::fs::read_to_string(log) |
| 313 | .unwrap_or_default() |
| 314 | .lines() |
| 315 | .filter(|l| l.starts_with("ALLEN: engaged agent=")) |
| 316 | .count() |
| 317 | } |
| 318 | |
| 319 | /// The set of entries directly under the compose directory (and siblings named |
| 320 | /// compose.*): a second identity or memory system would show up here. |
| 321 | fn compose_entries(r: &Rig) -> BTreeSet<String> { |
| 322 | let mut set = BTreeSet::new(); |
| 323 | for d in [r.root.clone(), r.compose()] { |
| 324 | if let Ok(rd) = std::fs::read_dir(&d) { |
| 325 | for e in rd.flatten() { |
| 326 | let n = e.file_name().to_string_lossy().to_string(); |
| 327 | if n.contains("allen") || n.contains("pin") { |
| 328 | set.insert(format!("{}/{n}", d.file_name().unwrap().to_string_lossy())); |
| 329 | } |
| 330 | } |
| 331 | } |
| 332 | } |
| 333 | set |
| 334 | } |
| 335 | |
| 336 | #[test] |
| 337 | #[ignore = "needs a compose-linked CPU aien-cli (see the file header); host CPU, not GB10"] |
| 338 | fn allen_concurrent_clients_one_daemon() { |
| 339 | let mut r = Rig::new(); |
| 340 | |
| 341 | // ---- setup: a home exists, then ALLEN is adopted once (as the recovery matrix R8/R9). |
| 342 | r.start_with(&[]); |
| 343 | let lin = r.run("compose", &["recall", "--ids", "1"]); |
| 344 | assert_eq!(lin.code, 0, "{}", lin.raw); |
| 345 | let lineage = aien_allen::unhex32(lin.json["recall"]["cited"][0]["digest"].as_str().unwrap()) |
| 346 | .expect("record 1 digest"); |
| 347 | r.kill(); |
| 348 | let mut f = support::fx("allen-concurrency"); |
| 349 | f.cortex = lineage; |
| 350 | let subj = support::write_head( |
| 351 | &r.root.join("subject.bin"), |
| 352 | support::chain(&f, 2).last().unwrap(), |
| 353 | ); |
| 354 | let agent = aien_allen::hex(&f.agent); |
| 355 | r.env.push(("AIEN_ALLEN_SUBJECT".into(), s(&subj))); |
| 356 | let log1 = r.start_with(&[("AIEN_ALLEN_ADOPT", &agent)]); |
| 357 | |
| 358 | // ---- C1: N concurrent calls (status, put, inspect) all served by the one boot-time identity. |
| 359 | let mut c1_puts = BTreeMap::new(); |
| 360 | { |
| 361 | let results = Mutex::new(Vec::new()); |
| 362 | std::thread::scope(|sc| { |
| 363 | for i in 0..9 { |
| 364 | let (r, results) = (&r, &results); |
| 365 | sc.spawn(move || { |
| 366 | let out = match i % 3 { |
| 367 | 0 => r.allen(&["status"]), |
| 368 | 1 => r.allen(&[ |
| 369 | "memory", |
| 370 | "put", |
| 371 | "--context", |
| 372 | "work", |
| 373 | "--text", |
| 374 | &format!("first-contact-{i}"), |
| 375 | ]), |
| 376 | _ => r.allen(&["memory", "inspect", "--owner", "1"]), |
| 377 | }; |
| 378 | results.lock().unwrap().push((i, out)); |
| 379 | }); |
| 380 | } |
| 381 | }); |
| 382 | for (i, o) in results.into_inner().unwrap() { |
| 383 | assert!(o.ok(), "C1 concurrent call {i} failed: {}", o.raw); |
| 384 | if i % 3 == 0 { |
| 385 | assert_eq!(o.json["result"]["identity"], "engaged", "C1 {}", o.raw); |
| 386 | assert_eq!( |
| 387 | o.json["result"]["fingerprint"].as_str().unwrap(), |
| 388 | &agent[..8], |
| 389 | "C1 two different identities answered" |
| 390 | ); |
| 391 | } |
| 392 | if i % 3 == 1 { |
| 393 | c1_puts.insert( |
| 394 | o.result()["item"].as_str().unwrap().to_string(), |
| 395 | format!("first-contact-{i}"), |
| 396 | ); |
| 397 | } |
| 398 | } |
| 399 | } |
| 400 | assert_eq!( |
| 401 | all_engaged_lines(&log1), |
| 402 | 1, |
| 403 | "C1 exactly one engage line in the daemon log" |
| 404 | ); |
| 405 | assert_eq!(engaged_lines(&log1, &agent), 1, "C1 engaged agent is ours"); |
| 406 | let pin0 = std::fs::read(pin_path(&r.compose())).expect("pin file"); |
| 407 | let entries0 = compose_entries(&r); |
| 408 | assert_eq!(c1_puts.len(), 3); |
| 409 | |
| 410 | // ---- C2: concurrent writers into work and personal. |
| 411 | let mut expected: BTreeMap<String, (String, String)> = BTreeMap::new(); // item -> (scope, text) |
| 412 | for (item, text) in &c1_puts { |
| 413 | expected.insert(item.clone(), ("work".into(), text.clone())); |
| 414 | } |
| 415 | { |
| 416 | let acks = Mutex::new(Vec::new()); |
| 417 | std::thread::scope(|sc| { |
| 418 | for w in 0..6 { |
| 419 | let (r, acks) = (&r, &acks); |
| 420 | sc.spawn(move || { |
| 421 | let ctx = if w % 2 == 0 { "work" } else { "personal" }; |
| 422 | for i in 0..6 { |
| 423 | let text = format!("c2-{ctx}-w{w}-n{i}"); |
| 424 | let o = r.allen(&["memory", "put", "--context", ctx, "--text", &text]); |
| 425 | assert!(o.ok(), "C2 put refused: {}", o.raw); |
| 426 | acks.lock().unwrap().push(( |
| 427 | o.result()["item"].as_str().unwrap().to_string(), |
| 428 | ctx.to_string(), |
| 429 | text, |
| 430 | )); |
| 431 | } |
| 432 | }); |
| 433 | } |
| 434 | }); |
| 435 | for (item, ctx, text) in acks.into_inner().unwrap() { |
| 436 | assert!( |
| 437 | expected.insert(item, (ctx, text)).is_none(), |
| 438 | "C2 duplicate item id" |
| 439 | ); |
| 440 | } |
| 441 | } |
| 442 | for ctx in ["work", "personal"] { |
| 443 | let rows = r.rows_of(ctx); |
| 444 | let want: BTreeSet<&String> = expected |
| 445 | .values() |
| 446 | .filter(|(c, _)| c == ctx) |
| 447 | .map(|(_, t)| t) |
| 448 | .collect(); |
| 449 | let got: Vec<String> = rows |
| 450 | .iter() |
| 451 | .filter(|x| x["kind"] != "goal") |
| 452 | .map(|x| x["text"].as_str().unwrap_or("").to_string()) |
| 453 | .collect(); |
| 454 | assert_eq!( |
| 455 | got.len(), |
| 456 | want.len(), |
| 457 | "C2 {ctx}: item count (exactly once each): {got:?}" |
| 458 | ); |
| 459 | for t in &want { |
| 460 | assert_eq!( |
| 461 | got.iter().filter(|g| g == t).count(), |
| 462 | 1, |
| 463 | "C2 {ctx}: {t} present exactly once" |
| 464 | ); |
| 465 | } |
| 466 | for x in &rows { |
| 467 | assert_eq!( |
| 468 | x["scope"], ctx, |
| 469 | "C2 {ctx} inspect leaked another scope: {x}" |
| 470 | ); |
| 471 | } |
| 472 | let (o, texts) = r.recall_texts(ctx); |
| 473 | assert!(o.ok() && !texts.is_empty(), "C2 recall {ctx}: {}", o.raw); |
| 474 | for t in &texts { |
| 475 | assert!( |
| 476 | want.contains(t), |
| 477 | "C2 recall in {ctx} returned another scope's text: {t}" |
| 478 | ); |
| 479 | } |
| 480 | } |
| 481 | |
| 482 | // ---- C3: concurrent corrections of one item. |
| 483 | let c3 = r.allen(&[ |
| 484 | "memory", |
| 485 | "put", |
| 486 | "--context", |
| 487 | "work", |
| 488 | "--text", |
| 489 | "c3-original", |
| 490 | ]); |
| 491 | assert!(c3.ok(), "{}", c3.raw); |
| 492 | let c3_item = c3.result()["item"].as_str().unwrap().to_string(); |
| 493 | let corr_ok = Mutex::new(Vec::new()); |
| 494 | let corr_refused = AtomicUsize::new(0); |
| 495 | std::thread::scope(|sc| { |
| 496 | for k in 0..6 { |
| 497 | let (r, corr_ok, corr_refused, c3_item) = (&r, &corr_ok, &corr_refused, &c3_item); |
| 498 | sc.spawn(move || { |
| 499 | let text = format!("c3-corrected-by-{k}"); |
| 500 | let o = r.allen(&[ |
| 501 | "memory", |
| 502 | "correct", |
| 503 | "--context", |
| 504 | "work", |
| 505 | "--item", |
| 506 | c3_item, |
| 507 | "--text", |
| 508 | &text, |
| 509 | ]); |
| 510 | if o.ok() { |
| 511 | corr_ok |
| 512 | .lock() |
| 513 | .unwrap() |
| 514 | .push((o.result()["version"].as_u64().unwrap(), text)); |
| 515 | } else { |
| 516 | // A refusal must be a visible, coded one (conflict), never silence. |
| 517 | let code = o |
| 518 | .refusal() |
| 519 | .unwrap_or_else(|| panic!("C3 unexplained: {}", o.raw)); |
| 520 | assert!( |
| 521 | code == "conflict" || code == "io", |
| 522 | "C3 unexpected refusal {code}: {}", |
| 523 | o.raw |
| 524 | ); |
| 525 | corr_refused.fetch_add(1, Ordering::SeqCst); |
| 526 | } |
| 527 | }); |
| 528 | } |
| 529 | }); |
| 530 | let corr_ok = corr_ok.into_inner().unwrap(); |
| 531 | let versions: BTreeSet<u64> = corr_ok.iter().map(|(v, _)| *v).collect(); |
| 532 | assert_eq!( |
| 533 | versions.len(), |
| 534 | corr_ok.len(), |
| 535 | "C3 two corrections got the same version" |
| 536 | ); |
| 537 | let hist: Vec<Value> = r |
| 538 | .rows_of("work") |
| 539 | .into_iter() |
| 540 | .filter(|x| x["item"] == c3_item.as_str()) |
| 541 | .collect(); |
| 542 | // One row per version: the superseded ones are "corrected" and show no text. |
| 543 | assert_eq!( |
| 544 | hist.len() as u64, |
| 545 | 1 + corr_ok.len() as u64, |
| 546 | "C3 history length (no lost update)" |
| 547 | ); |
| 548 | let vs: Vec<u64> = hist |
| 549 | .iter() |
| 550 | .map(|x| x["version"].as_u64().unwrap()) |
| 551 | .collect(); |
| 552 | assert_eq!( |
| 553 | vs, |
| 554 | (1..=hist.len() as u64).collect::<Vec<_>>(), |
| 555 | "C3 history gap-free, in order" |
| 556 | ); |
| 557 | for x in &hist[..hist.len() - 1] { |
| 558 | assert_eq!(x["state"], "corrected", "C3 {x}"); |
| 559 | assert!( |
| 560 | x["text"].is_null(), |
| 561 | "C3 superseded text still readable: {x}" |
| 562 | ); |
| 563 | } |
| 564 | let row = hist.last().unwrap().clone(); |
| 565 | assert_eq!(row["state"], "live", "C3 final state"); |
| 566 | assert_eq!( |
| 567 | row["version"].as_u64().unwrap(), |
| 568 | 1 + corr_ok.len() as u64, |
| 569 | "C3 final version = 1 + acknowledged corrections (no lost update)" |
| 570 | ); |
| 571 | assert_eq!( |
| 572 | versions.iter().copied().collect::<Vec<_>>(), |
| 573 | (2..2 + corr_ok.len() as u64).collect::<Vec<_>>(), |
| 574 | "C3 revision history is gap-free" |
| 575 | ); |
| 576 | let top = corr_ok.iter().max_by_key(|(v, _)| *v).unwrap(); |
| 577 | assert_eq!( |
| 578 | row["text"].as_str().unwrap(), |
| 579 | top.1, |
| 580 | "C3 final text is the highest acknowledged version's text" |
| 581 | ); |
| 582 | assert_eq!( |
| 583 | corr_ok.len() + corr_refused.load(Ordering::SeqCst), |
| 584 | 6, |
| 585 | "C3 every correction was acknowledged or visibly refused" |
| 586 | ); |
| 587 | assert_eq!( |
| 588 | r.key_files(&c3_item), |
| 589 | vec![format!("{c3_item}-v{}.key", 1 + corr_ok.len())], |
| 590 | "C3 only the final version's key remains (superseded keys destroyed)" |
| 591 | ); |
| 592 | expected.insert(c3_item, ("work".into(), top.1.clone())); |
| 593 | |
| 594 | // ---- C6: persona. Same expected revision from six clients: exactly one wins. |
| 595 | { |
| 596 | let outs = Mutex::new(Vec::new()); |
| 597 | std::thread::scope(|sc| { |
| 598 | for k in 0..6 { |
| 599 | let (r, outs) = (&r, &outs); |
| 600 | sc.spawn(move || { |
| 601 | let o = r.allen(&["set", "--expect", "0", "--name", &format!("Nova{k}")]); |
| 602 | outs.lock().unwrap().push(o); |
| 603 | }); |
| 604 | } |
| 605 | }); |
| 606 | let outs = outs.into_inner().unwrap(); |
| 607 | assert_eq!( |
| 608 | outs.iter().filter(|o| o.ok()).count(), |
| 609 | 1, |
| 610 | "C6 exactly one winner" |
| 611 | ); |
| 612 | for o in outs.iter().filter(|o| !o.ok()) { |
| 613 | assert_eq!(o.refusal().as_deref(), Some("stale_update"), "C6 {}", o.raw); |
| 614 | } |
| 615 | let show = r.allen(&["show"]); |
| 616 | assert_eq!(show.json["result"]["revision"], 1, "C6 {}", show.raw); |
| 617 | let perm = r.allen(&["set", "--expect", "1", "--pref", "grant_admin=yes"]); |
| 618 | assert!( |
| 619 | !perm.ok(), |
| 620 | "C6 a permission-looking key was accepted: {}", |
| 621 | perm.raw |
| 622 | ); |
| 623 | assert_eq!( |
| 624 | perm.refusal().as_deref(), |
| 625 | Some("permission_key"), |
| 626 | "C6 {}", |
| 627 | perm.raw |
| 628 | ); |
| 629 | let show2 = r.allen(&["show"]); |
| 630 | assert_eq!( |
| 631 | show2.json["result"]["revision"], 1, |
| 632 | "C6 refused change moved the profile" |
| 633 | ); |
| 634 | } |
| 635 | |
| 636 | // ---- C4: forgetting racing reads. |
| 637 | let put = r.allen(&["memory", "put", "--context", "personal", "--text", CANARY]); |
| 638 | assert!(put.ok(), "{}", put.raw); |
| 639 | let canary_item = put.result()["item"].as_str().unwrap().to_string(); |
| 640 | // Evidence on the real item, before forget: its key file and its ciphertext record exist. |
| 641 | let keys_before = r.key_files(&canary_item); |
| 642 | let recs_before = r.log_records_of(&canary_item); |
| 643 | assert_eq!( |
| 644 | keys_before.len(), |
| 645 | 1, |
| 646 | "C4 before forget the item has its key: {keys_before:?}" |
| 647 | ); |
| 648 | assert!( |
| 649 | recs_before >= 1, |
| 650 | "C4 before forget the item has a log record" |
| 651 | ); |
| 652 | { |
| 653 | let forgot = AtomicBool::new(false); |
| 654 | let stop = AtomicBool::new(false); |
| 655 | let saw_before = AtomicUsize::new(0); |
| 656 | let reads_after = AtomicUsize::new(0); |
| 657 | let violations = Mutex::new(Vec::new()); |
| 658 | std::thread::scope(|sc| { |
| 659 | for _ in 0..3 { |
| 660 | sc.spawn(|| { |
| 661 | while !stop.load(Ordering::SeqCst) { |
| 662 | let started_after = forgot.load(Ordering::SeqCst); |
| 663 | let (o, texts) = r.recall_query("personal", Some("CONC-CANARY")); |
| 664 | assert!(o.ok(), "C4 read failed: {}", o.raw); |
| 665 | let has = o.raw.contains(CANARY) || texts.iter().any(|t| t == CANARY); |
| 666 | if started_after { |
| 667 | reads_after.fetch_add(1, Ordering::SeqCst); |
| 668 | if has { |
| 669 | violations.lock().unwrap().push(o.raw.clone()); |
| 670 | } |
| 671 | } else if has { |
| 672 | saw_before.fetch_add(1, Ordering::SeqCst); |
| 673 | } |
| 674 | } |
| 675 | }); |
| 676 | } |
| 677 | let _guard = StopOnDrop(&stop); |
| 678 | // Wait until readers have really seen the text, so the race is not vacuous. |
| 679 | for _ in 0..600 { |
| 680 | if saw_before.load(Ordering::SeqCst) >= 2 { |
| 681 | break; |
| 682 | } |
| 683 | std::thread::sleep(Duration::from_millis(50)); |
| 684 | } |
| 685 | assert!( |
| 686 | saw_before.load(Ordering::SeqCst) >= 2, |
| 687 | "C4 readers never saw the canary" |
| 688 | ); |
| 689 | let fg = r.allen(&[ |
| 690 | "memory", |
| 691 | "forget", |
| 692 | "--context", |
| 693 | "personal", |
| 694 | "--item", |
| 695 | &canary_item, |
| 696 | ]); |
| 697 | assert!(fg.ok(), "C4 forget: {}", fg.raw); |
| 698 | forgot.store(true, Ordering::SeqCst); |
| 699 | for _ in 0..600 { |
| 700 | if reads_after.load(Ordering::SeqCst) >= 6 { |
| 701 | break; |
| 702 | } |
| 703 | std::thread::sleep(Duration::from_millis(50)); |
| 704 | } |
| 705 | stop.store(true, Ordering::SeqCst); |
| 706 | }); |
| 707 | assert!( |
| 708 | reads_after.load(Ordering::SeqCst) >= 6, |
| 709 | "C4 too few reads after forget" |
| 710 | ); |
| 711 | assert!( |
| 712 | violations.lock().unwrap().is_empty(), |
| 713 | "C4 {} read(s) that started after forget returned still showed the canary; first: {}", |
| 714 | violations.lock().unwrap().len(), |
| 715 | violations |
| 716 | .lock() |
| 717 | .unwrap() |
| 718 | .first() |
| 719 | .map(|v| v.chars().take(300).collect::<String>()) |
| 720 | .unwrap_or_default() |
| 721 | ); |
| 722 | } |
| 723 | let row = r |
| 724 | .rows() |
| 725 | .into_iter() |
| 726 | .find(|x| x["item"] == canary_item.as_str()) |
| 727 | .expect("forgotten row remains"); |
| 728 | assert!(row["text"].is_null(), "C4 forgotten row shows text: {row}"); |
| 729 | assert!( |
| 730 | row["state"].as_str().unwrap().starts_with("forgotten"), |
| 731 | "{row}" |
| 732 | ); |
| 733 | let exp = r.allen(&["memory", "export", "--owner", "1"]); |
| 734 | assert!(!exp.raw.contains(CANARY), "C4 export shows the canary"); |
| 735 | // Ground truth (store.rs): forget destroys the key; the ciphertext stays in the immutable log. |
| 736 | // So the observable change is: key file present before, absent after; record still there. |
| 737 | assert!( |
| 738 | r.key_files(&canary_item).is_empty(), |
| 739 | "C4 key file of the forgotten item still on disk (before: {keys_before:?})" |
| 740 | ); |
| 741 | assert!( |
| 742 | r.log_records_of(&canary_item) >= recs_before, |
| 743 | "C4 the ciphertext record vanished (expected: kept, unreadable without the key)" |
| 744 | ); |
| 745 | |
| 746 | // ---- C5: kill -9 in the middle of a concurrent write burst, then restart. |
| 747 | let pin_before_kill = std::fs::read(pin_path(&r.compose())).unwrap(); |
| 748 | assert_eq!(pin0, pin_before_kill, "C1 pin changed during the run"); |
| 749 | // The only new directory since C1 is the profile store, created by the C6 `set`. |
| 750 | let entries1 = compose_entries(&r); |
| 751 | let added: Vec<&String> = entries1.difference(&entries0).collect(); |
| 752 | assert!( |
| 753 | entries0.is_subset(&entries1) |
| 754 | && added.len() == 1 |
| 755 | && added[0].ends_with("compose.allen-profile"), |
| 756 | "C1 a second identity/memory dir appeared: {added:?}" |
| 757 | ); |
| 758 | let attempts: Mutex<Vec<(String, String, Option<String>)>> = Mutex::new(Vec::new()); // ctx, text, acked item |
| 759 | let killing = AtomicBool::new(false); |
| 760 | let in_flight_unacked = AtomicUsize::new(0); |
| 761 | let acked = AtomicUsize::new(0); |
| 762 | let dead = AtomicBool::new(false); |
| 763 | std::thread::scope(|sc| { |
| 764 | for w in 0..6 { |
| 765 | let (r, attempts, acked, dead, killing, in_flight_unacked) = |
| 766 | (&r, &attempts, &acked, &dead, &killing, &in_flight_unacked); |
| 767 | sc.spawn(move || { |
| 768 | let ctx = if w % 2 == 0 { "work" } else { "personal" }; |
| 769 | for i in 0..40 { |
| 770 | if dead.load(Ordering::SeqCst) { |
| 771 | break; |
| 772 | } |
| 773 | let text = format!("c5-{ctx}-w{w}-n{i}"); |
| 774 | let issued_before_kill = !killing.load(Ordering::SeqCst); |
| 775 | let o = r.allen(&["memory", "put", "--context", ctx, "--text", &text]); |
| 776 | let item = if o.ok() { |
| 777 | acked.fetch_add(1, Ordering::SeqCst); |
| 778 | Some(o.result()["item"].as_str().unwrap().to_string()) |
| 779 | } else { |
| 780 | dead.store(true, Ordering::SeqCst); |
| 781 | if issued_before_kill { |
| 782 | in_flight_unacked.fetch_add(1, Ordering::SeqCst); |
| 783 | } |
| 784 | None |
| 785 | }; |
| 786 | attempts.lock().unwrap().push((ctx.into(), text, item)); |
| 787 | } |
| 788 | }); |
| 789 | } |
| 790 | let _guard = StopOnDrop(&dead); |
| 791 | // Kill once the burst is clearly in flight. |
| 792 | for _ in 0..1200 { |
| 793 | if acked.load(Ordering::SeqCst) >= 12 { |
| 794 | break; |
| 795 | } |
| 796 | std::thread::sleep(Duration::from_millis(10)); |
| 797 | } |
| 798 | assert!( |
| 799 | acked.load(Ordering::SeqCst) >= 12, |
| 800 | "C5 burst never got going" |
| 801 | ); |
| 802 | // kill -9 from the test thread while the writers keep going. |
| 803 | killing.store(true, Ordering::SeqCst); |
| 804 | let c = r.daemon.as_ref().expect("daemon").id(); |
| 805 | let st = Command::new("kill") |
| 806 | .args(["-9", &c.to_string()]) |
| 807 | .status() |
| 808 | .unwrap(); |
| 809 | assert!(st.success()); |
| 810 | }); |
| 811 | // Reap the killed daemon through the rig (asserts signal 9). |
| 812 | { |
| 813 | let mut d = r.daemon.take().unwrap(); |
| 814 | let st = d.wait().unwrap(); |
| 815 | assert_eq!(st.signal(), Some(9), "C5 daemon end: {st:?}"); |
| 816 | let _ = std::fs::remove_file(r.sock()); |
| 817 | } |
| 818 | let attempts = attempts.into_inner().unwrap(); |
| 819 | let n_acked = attempts.iter().filter(|a| a.2.is_some()).count(); |
| 820 | assert!(n_acked >= 12, "C5 acked {n_acked}"); |
| 821 | let in_flight = in_flight_unacked.load(Ordering::SeqCst); |
| 822 | assert!( |
| 823 | in_flight >= 1, |
| 824 | "C5 no write was in flight (issued before the kill, never acknowledged) when the kill landed" |
| 825 | ); |
| 826 | let log2 = r.start_with(&[]); // restart over the same state, no ADOPT |
| 827 | assert_eq!( |
| 828 | all_engaged_lines(&log2), |
| 829 | 1, |
| 830 | "C5 one engage line after restart" |
| 831 | ); |
| 832 | assert_eq!( |
| 833 | engaged_lines(&log2, &agent), |
| 834 | 1, |
| 835 | "C5 identity unchanged after restart" |
| 836 | ); |
| 837 | let st = r.allen(&["status"]); |
| 838 | assert_eq!( |
| 839 | st.json["result"]["fingerprint"].as_str().unwrap(), |
| 840 | &agent[..8], |
| 841 | "C5" |
| 842 | ); |
| 843 | assert_eq!( |
| 844 | pin0, |
| 845 | std::fs::read(pin_path(&r.compose())).unwrap(), |
| 846 | "C5 pin changed" |
| 847 | ); |
| 848 | assert_eq!( |
| 849 | compose_entries(&r), |
| 850 | entries1, |
| 851 | "C5 a second identity appeared" |
| 852 | ); |
| 853 | |
| 854 | let rows = r.rows(); |
| 855 | let ids: Vec<(String, u64)> = rows |
| 856 | .iter() |
| 857 | .map(|x| { |
| 858 | ( |
| 859 | x["item"].as_str().unwrap().to_string(), |
| 860 | x["version"].as_u64().unwrap(), |
| 861 | ) |
| 862 | }) |
| 863 | .collect(); |
| 864 | assert_eq!( |
| 865 | ids.len(), |
| 866 | ids.iter().collect::<BTreeSet<_>>().len(), |
| 867 | "C5 duplicate item rows" |
| 868 | ); |
| 869 | // Every earlier (pre-burst) acknowledged item is still exactly as it was. |
| 870 | for (item, (ctx, text)) in &expected { |
| 871 | let x = rows |
| 872 | .iter() |
| 873 | .rev() |
| 874 | .find(|x| x["item"] == item.as_str()) |
| 875 | .unwrap_or_else(|| panic!("C5 pre-burst item {item} lost")); |
| 876 | assert_eq!(x["scope"], ctx.as_str()); |
| 877 | assert_eq!( |
| 878 | x["text"].as_str(), |
| 879 | Some(text.as_str()), |
| 880 | "C5 pre-burst item changed" |
| 881 | ); |
| 882 | } |
| 883 | // Acknowledged burst writes: present, live, right scope, right text. |
| 884 | for (ctx, text, item) in &attempts { |
| 885 | let hit: Vec<&Value> = rows.iter().filter(|x| x["text"] == text.as_str()).collect(); |
| 886 | match item { |
| 887 | Some(id) => { |
| 888 | assert_eq!( |
| 889 | hit.len(), |
| 890 | 1, |
| 891 | "C5 acknowledged write {text} present exactly once" |
| 892 | ); |
| 893 | assert_eq!(hit[0]["item"], id.as_str()); |
| 894 | assert_eq!(hit[0]["scope"], ctx.as_str()); |
| 895 | assert_eq!(hit[0]["state"], "live", "C5 {text}"); |
| 896 | } |
| 897 | // Unacknowledged: either fully there or not at all, never twice or damaged. |
| 898 | None => { |
| 899 | assert!( |
| 900 | hit.len() <= 1, |
| 901 | "C5 unacknowledged write {text} appears {} times", |
| 902 | hit.len() |
| 903 | ); |
| 904 | if let Some(h) = hit.first() { |
| 905 | assert_eq!( |
| 906 | h["state"], "live", |
| 907 | "C5 unacknowledged write half-present: {h}" |
| 908 | ); |
| 909 | assert_eq!(h["scope"], ctx.as_str()); |
| 910 | } |
| 911 | } |
| 912 | } |
| 913 | } |
| 914 | // Nothing half-present anywhere: every row is live/corrected or cleanly forgotten, and |
| 915 | // every live text is one we wrote. |
| 916 | let known: BTreeSet<String> = expected |
| 917 | .values() |
| 918 | .map(|(_, t)| t.clone()) |
| 919 | .chain(attempts.iter().map(|a| a.1.clone())) |
| 920 | .collect(); |
| 921 | for x in &rows { |
| 922 | let state = x["state"].as_str().unwrap(); |
| 923 | if state.starts_with("forgotten") { |
| 924 | assert_eq!( |
| 925 | state, "forgotten", |
| 926 | "C5 forget left pending after restart: {x}" |
| 927 | ); |
| 928 | assert!(x["text"].is_null(), "C5 forgotten row has text: {x}"); |
| 929 | } else { |
| 930 | assert!( |
| 931 | state == "live" || state == "corrected", |
| 932 | "C5 row in odd state (half-present?): {x}" |
| 933 | ); |
| 934 | if state == "corrected" { |
| 935 | assert!(x["text"].is_null(), "C5 superseded text readable: {x}"); |
| 936 | continue; |
| 937 | } |
| 938 | let t = x["text"] |
| 939 | .as_str() |
| 940 | .unwrap_or_else(|| panic!("C5 live row without text: {x}")); |
| 941 | assert!(known.contains(t), "C5 text nobody wrote: {t}"); |
| 942 | } |
| 943 | } |
| 944 | // Forgotten stays forgotten. |
| 945 | let cr = rows |
| 946 | .iter() |
| 947 | .rev() |
| 948 | .find(|x| x["item"] == canary_item.as_str()) |
| 949 | .unwrap(); |
| 950 | assert_eq!(cr["state"], "forgotten", "C5 canary row"); |
| 951 | let (o, texts) = r.recall_query("personal", Some("CONC-CANARY")); |
| 952 | assert!( |
| 953 | o.ok() && !o.raw.contains(CANARY) && !texts.iter().any(|t| t == CANARY), |
| 954 | "C5 canary back" |
| 955 | ); |
| 956 | assert!( |
| 957 | r.key_files(&canary_item).is_empty(), |
| 958 | "C5 forgotten item has a key again after restart" |
| 959 | ); |
| 960 | // Scope isolation still holds after recovery. |
| 961 | for ctx in ["work", "personal"] { |
| 962 | for x in r.rows_of(ctx) { |
| 963 | assert_eq!(x["scope"], ctx, "C5 scope leak after restart"); |
| 964 | } |
| 965 | } |
| 966 | println!( |
| 967 | "CONC_RECEIPT {}", |
| 968 | json!({"acked_before_kill": n_acked, "in_flight_unacked_at_kill": in_flight, "attempts": attempts.len(), |
| 969 | "corrections_ok": corr_ok.len(), "agent": &agent[..8]}) |
| 970 | ); |
| 971 | } |
| 972 | |
| 973 | /// Sets the flag when dropped, so worker threads stop even if the test panics first. |
| 974 | struct StopOnDrop<'a>(&'a AtomicBool); |
| 975 | impl Drop for StopOnDrop<'_> { |
| 976 | fn drop(&mut self) { |
| 977 | self.0.store(true, Ordering::SeqCst); |
| 978 | } |
| 979 | } |