Elffuss BraidHub

utopia-ia/elffuss-braid public

Store tests: many processes at once, and killed at random moments

The test binary runs copies of itself as child processes that put
objects, sync and acknowledge them, then increment a shared counter ref
with compare and swap, retrying on conflicts. With 32 processes at once,
fsck is clean, every acknowledged object is readable, every operation
moved the counter by exactly one, and the log has no gaps. A second test
kills the children with SIGKILL at random moments, round after round, and
checks the same after each round before writing on top of what the dead
left behind. BRAID_STRESS=1 runs more processes and rounds, and
BRAID_STRESS_SEED fixes the seed.
Changesetf574b55f562512c7de74009f15eefc833ab31e97b0fdb6a24d4a1ecdb1aa646a
AuthorKikoCis <KikoCis@users.noreply.github.com> · 2026-10-15 21:41 +02:00
CommitterKikoCis <KikoCis@users.noreply.github.com> · 2026-10-15 21:41 +02:00
Parentsec65e8b44b76

Browse the files at this changeset

1 file changed

added crates/store/tests/processes.rs +460 −0
@@ -0,0 +1,460 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Many processes sharing one store, and processes killed at random moments.
5+//!
6+//! The tests run copies of this test binary that execute only [`child`],
7+//! configured through environment variables. A child writes batches of
8+//! objects, syncs, and acknowledges each object in a file of its own. Then it
9+//! increments a shared counter ref with compare and swap, retrying when
10+//! another process got there first, and acknowledges that too. The parent
11+//! checks the store against the acknowledgements: fsck is clean, every
12+//! acknowledged object is readable, the log has no gaps, every operation
13+//! moved the counter up by exactly one, and every acknowledged increment is
14+//! in the log.
15+//!
16+//! `BRAID_STRESS=1` runs longer: more processes, more work, more rounds of
17+//! killing. `BRAID_STRESS_SEED` fixes the seed of the crash test.
18+
19+use std::collections::HashMap;
20+use std::convert::Infallible;
21+use std::env;
22+use std::fs::{self, File, OpenOptions};
23+use std::io::Write;
24+use std::path::{Path, PathBuf};
25+use std::process::{Child, Command, Stdio};
26+use std::sync::{Mutex, PoisonError};
27+use std::thread;
28+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
29+
30+use braid_store::{FsckReport, Kind, ObjectId, Objects, Options, RefUpdate, Store};
31+
32+/// Set in the environment of a child process.
33+const CHILD: &str = "BRAID_STORE_TEST_CHILD";
34+
35+/// The heavy tests share the disk, so they run one at a time.
36+static SERIAL: Mutex<()> = Mutex::new(());
37+
38+fn stress() -> bool {
39+ env::var_os("BRAID_STRESS").is_some_and(|value| value != "0")
40+}
41+
42+/// Small segments and frequent checkpoints, so that sealing and
43+/// checkpointing happen many times while processes race.
44+fn options() -> Options {
45+ Options {
46+ segment_size: 16 << 10,
47+ checkpoint_interval: 5,
48+ ..Options::default()
49+ }
50+}
51+
52+/// What one child process does.
53+struct Job {
54+ store: PathBuf,
55+ acks: PathBuf,
56+ child: u64,
57+ round: u64,
58+ iterations: u64,
59+ batch: u64,
60+}
61+
62+const OBJECTS_PER_BATCH: u64 = 6;
63+
64+/// The entry point of child processes. In a normal test run it does nothing.
65+#[test]
66+fn child() {
67+ if env::var_os(CHILD).is_none() {
68+ return;
69+ }
70+ let var = |name: &str| env::var(name).unwrap_or_else(|_| panic!("{name} is not set"));
71+ let number = |name: &str| var(name).parse::<u64>().expect("a number");
72+ run(&Job {
73+ store: var("BRAID_TEST_STORE").into(),
74+ acks: var("BRAID_TEST_ACKS").into(),
75+ child: number("BRAID_TEST_CHILD"),
76+ round: number("BRAID_TEST_ROUND"),
77+ iterations: number("BRAID_TEST_ITERATIONS"),
78+ batch: number("BRAID_TEST_BATCH"),
79+ });
80+}
81+
82+fn run(job: &Job) {
83+ let store = Store::open(&job.store, options()).expect("open the store");
84+ let mut acks = OpenOptions::new()
85+ .create(true)
86+ .append(true)
87+ .open(&job.acks)
88+ .expect("open the acknowledgements");
89+ let agent = format!("child-{}", job.child);
90+ let branch = format!("child/{}", job.child);
91+ for i in 0..job.iterations {
92+ let mut written = Vec::new();
93+ for j in 0..job.batch {
94+ let (kind, payload) = object(job.round, job.child, i, j);
95+ written.push((j, store.put(kind, &payload).expect("put")));
96+ }
97+ store.sync().expect("sync");
98+ // Acknowledged only once synced. One write per batch: a kill can
99+ // only cut the last line short, and partial lines are ignored.
100+ let mut lines = String::new();
101+ for (j, id) in &written {
102+ lines.push_str(&format!(
103+ "object {} {} {i} {j} {id}\n",
104+ job.round, job.child
105+ ));
106+ }
107+ acks.write_all(lines.as_bytes()).expect("acknowledge");
108+ let (seq, value) = increment(&store, &agent, &branch, written[0].1);
109+ acks.write_all(format!("increment {seq} {value}\n").as_bytes())
110+ .expect("acknowledge");
111+ }
112+}
113+
114+/// Adds one to the shared counter with compare and swap, retrying while
115+/// other processes get there first, and points `branch` at `tip` in the same
116+/// operation. Returns the operation's sequence number and the new value.
117+fn increment(store: &Store, agent: &str, branch: &str, tip: ObjectId) -> (u64, u64) {
118+ loop {
119+ let refs = store.refs().expect("read the refs");
120+ let current = refs.get("counter");
121+ let value = current.map_or(0, |id| counter_value(store, &id)) + 1;
122+ let next = store
123+ .put(Kind::Blob, value.to_string().as_bytes())
124+ .expect("put");
125+ store.sync().expect("sync");
126+ let updates = vec![
127+ RefUpdate::new("counter", current, Some(next)),
128+ RefUpdate::new(branch, refs.get(branch), Some(tip)),
129+ ];
130+ match store.transact(agent, "increment the counter", |_| {
131+ Ok::<_, Infallible>(updates)
132+ }) {
133+ Ok(op) => return (op.seq, value),
134+ Err(err) if err.is_conflict() => continue,
135+ Err(err) => panic!("transaction failed: {err}"),
136+ }
137+ }
138+}
139+
140+fn counter_value(store: &Store, id: &ObjectId) -> u64 {
141+ let (kind, payload) = store
142+ .get(id)
143+ .expect("read the counter")
144+ .expect("the counter's object is in the store");
145+ assert_eq!(kind, Kind::Blob);
146+ String::from_utf8(payload)
147+ .expect("text")
148+ .parse()
149+ .expect("a number")
150+}
151+
152+/// The object a child writes as number `j` of batch `i`. The first of every
153+/// batch is the same in every child of a round, so several processes store
154+/// the same object at the same moment.
155+fn object(round: u64, child: u64, i: u64, j: u64) -> (Kind, Vec<u8>) {
156+ if j == 0 {
157+ let text = format!("shared by every child of round {round}, batch {i}");
158+ return (Kind::Blob, text.into_bytes());
159+ }
160+ let mut rng = Rng::new(round, child, i, j);
161+ let kind = Kind::ALL[(rng.next() % Kind::ALL.len() as u64) as usize];
162+ let payload = match j % 3 {
163+ // Small enough to be stored raw.
164+ 1 => (0..rng.next() % 64).map(|_| rng.next() as u8).collect(),
165+ // Compressible.
166+ 2 => format!("round {round} child {child} batch {i} object {j}\n")
167+ .repeat(1 + (rng.next() % 300) as usize)
168+ .into_bytes(),
169+ // Noise, up to a third of a segment.
170+ _ => (0..100 + rng.next() % 20_000)
171+ .map(|_| rng.next() as u8)
172+ .collect(),
173+ };
174+ (kind, payload)
175+}
176+
177+/// SplitMix64.
178+struct Rng(u64);
179+
180+impl Rng {
181+ /// A generator for one object. Each part goes through the mixer, so
182+ /// different inputs give unrelated streams.
183+ fn new(round: u64, child: u64, i: u64, j: u64) -> Self {
184+ let mut rng = Rng(round);
185+ for part in [child, i, j] {
186+ rng.0 = rng.next() ^ part;
187+ }
188+ rng
189+ }
190+
191+ fn next(&mut self) -> u64 {
192+ self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
193+ let mut z = self.0;
194+ z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
195+ z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
196+ z ^ (z >> 31)
197+ }
198+}
199+
200+fn spawn(job: &Job, stderr: &Path) -> Child {
201+ let exe = env::current_exe().expect("the test binary");
202+ Command::new(exe)
203+ .args(["--exact", "child", "--nocapture", "--test-threads", "1"])
204+ .env(CHILD, "1")
205+ .env("BRAID_TEST_STORE", &job.store)
206+ .env("BRAID_TEST_ACKS", &job.acks)
207+ .env("BRAID_TEST_CHILD", job.child.to_string())
208+ .env("BRAID_TEST_ROUND", job.round.to_string())
209+ .env("BRAID_TEST_ITERATIONS", job.iterations.to_string())
210+ .env("BRAID_TEST_BATCH", job.batch.to_string())
211+ .stdin(Stdio::null())
212+ .stdout(Stdio::null())
213+ .stderr(File::create(stderr).expect("create a log for the child"))
214+ .spawn()
215+ .expect("start a child")
216+}
217+
218+/// What the children acknowledged.
219+#[derive(Debug, Default)]
220+struct Acks {
221+ /// Round, child, batch, number in the batch, and id.
222+ objects: Vec<(u64, u64, u64, u64, ObjectId)>,
223+ /// Sequence number and counter value.
224+ increments: Vec<(u64, u64)>,
225+}
226+
227+fn read_acks(dir: &Path) -> Acks {
228+ let mut acks = Acks::default();
229+ for entry in fs::read_dir(dir).expect("list acknowledgements") {
230+ let text = fs::read_to_string(entry.expect("an entry").path()).expect("read");
231+ // A kill can cut the last line short: it was never acknowledged.
232+ for line in text.split_inclusive('\n').filter(|l| l.ends_with('\n')) {
233+ let fields: Vec<&str> = line.split_whitespace().collect();
234+ let number = |i: usize| fields[i].parse::<u64>().expect("a number");
235+ match fields[0] {
236+ "object" => acks.objects.push((
237+ number(1),
238+ number(2),
239+ number(3),
240+ number(4),
241+ fields[5].parse().expect("an id"),
242+ )),
243+ "increment" => acks.increments.push((number(1), number(2))),
244+ other => panic!("unexpected acknowledgement {other:?}"),
245+ }
246+ }
247+ }
248+ acks
249+}
250+
251+/// Checks the store against the acknowledgements, and returns the number
252+/// of operations in the log with the fsck report.
253+fn verify(store: &Store, acks: &Acks, context: &str) -> (u64, FsckReport) {
254+ let report = store.fsck().expect("run fsck");
255+ assert!(
256+ report.is_clean(),
257+ "{context}: fsck found problems: {:#?}",
258+ report.problems
259+ );
260+
261+ for (round, child, i, j, id) in &acks.objects {
262+ let (kind, payload) = object(*round, *child, *i, *j);
263+ assert_eq!(*id, ObjectId::hash(kind, &payload), "{context}");
264+ let found = store.get(id).expect("read an acknowledged object");
265+ assert!(
266+ found == Some((kind, payload)),
267+ "{context}: object {id}, acknowledged by child {child} in round {round}, is not readable"
268+ );
269+ }
270+
271+ // No gaps: newest first, from the newest down to 1.
272+ let log = store.log(usize::MAX).expect("read the log");
273+ let operations = log.len() as u64;
274+ for (k, op) in log.iter().enumerate() {
275+ assert_eq!(op.seq, operations - k as u64, "{context}: gap in the log");
276+ }
277+ // Every operation moved the counter up by exactly one.
278+ let mut values = HashMap::new();
279+ let mut previous = None;
280+ for (expected, op) in (1..).zip(log.iter().rev()) {
281+ let update = op
282+ .updates
283+ .iter()
284+ .find(|update| update.name == "counter")
285+ .unwrap_or_else(|| panic!("{context}: operation {} skips the counter", op.seq));
286+ assert_eq!(update.old, previous, "{context}: operation {}", op.seq);
287+ let id = update.new.expect("the counter is never deleted");
288+ assert_eq!(
289+ counter_value(store, &id),
290+ expected,
291+ "{context}: operation {}",
292+ op.seq
293+ );
294+ values.insert(op.seq, expected);
295+ previous = Some(id);
296+ }
297+ assert_eq!(
298+ store.refs().expect("refs").get("counter"),
299+ previous,
300+ "{context}"
301+ );
302+ for (seq, value) in &acks.increments {
303+ assert_eq!(
304+ values.get(seq),
305+ Some(value),
306+ "{context}: acknowledged increment {seq} is not in the log"
307+ );
308+ }
309+ (operations, report)
310+}
311+
312+fn child_failure(child: u64, log: &Path) -> String {
313+ let output = fs::read_to_string(log).unwrap_or_default();
314+ format!("child {child} failed:\n{output}")
315+}
316+
317+#[test]
318+fn many_processes_share_one_store() {
319+ let _serial = SERIAL.lock().unwrap_or_else(PoisonError::into_inner);
320+ let (children, iterations) = if stress() { (48, 40) } else { (32, 3) };
321+ let dir = tempfile::tempdir().unwrap();
322+ let store_dir = dir.path().join("store");
323+ let acks_dir = dir.path().join("acks");
324+ let logs_dir = dir.path().join("logs");
325+ fs::create_dir(&acks_dir).unwrap();
326+ fs::create_dir(&logs_dir).unwrap();
327+ Store::init(&store_dir, options()).unwrap();
328+
329+ let running: Vec<(u64, Child)> = (0..children)
330+ .map(|child| {
331+ let job = Job {
332+ store: store_dir.clone(),
333+ acks: acks_dir.join(format!("{child}")),
334+ child,
335+ round: 0,
336+ iterations,
337+ batch: OBJECTS_PER_BATCH,
338+ };
339+ (child, spawn(&job, &logs_dir.join(format!("{child}"))))
340+ })
341+ .collect();
342+ for (child, mut process) in running {
343+ let status = process.wait().unwrap();
344+ assert!(
345+ status.success(),
346+ "{}",
347+ child_failure(child, &logs_dir.join(format!("{child}")))
348+ );
349+ }
350+
351+ let store = Store::open(&store_dir, options()).unwrap();
352+ let acks = read_acks(&acks_dir);
353+ assert_eq!(
354+ acks.objects.len() as u64,
355+ children * iterations * OBJECTS_PER_BATCH
356+ );
357+ assert_eq!(acks.increments.len() as u64, children * iterations);
358+ let (operations, report) = verify(&store, &acks, "after every process finished");
359+ assert_eq!(operations, children * iterations);
360+ assert!(report.sealed_segments > 0, "{report:?}");
361+ assert!(report.checkpoints > 0, "{report:?}");
362+}
363+
364+#[test]
365+fn processes_killed_at_random_moments() {
366+ let _serial = SERIAL.lock().unwrap_or_else(PoisonError::into_inner);
367+ let (children, rounds, window_ms) = if stress() {
368+ (32, 30, 800)
369+ } else {
370+ (32, 3, 400)
371+ };
372+ let seed = env::var("BRAID_STRESS_SEED")
373+ .ok()
374+ .and_then(|seed| seed.parse().ok())
375+ .unwrap_or_else(|| {
376+ SystemTime::now()
377+ .duration_since(UNIX_EPOCH)
378+ .map_or(0, |since| since.as_nanos() as u64)
379+ });
380+ let mut rng = Rng::new(seed, 0, 0, 0);
381+ let dir = tempfile::tempdir().unwrap();
382+ let store_dir = dir.path().join("store");
383+ let acks_dir = dir.path().join("acks");
384+ let logs_dir = dir.path().join("logs");
385+ fs::create_dir(&acks_dir).unwrap();
386+ fs::create_dir(&logs_dir).unwrap();
387+ Store::init(&store_dir, options()).unwrap();
388+
389+ let mut acknowledged = 0;
390+ for round in 1..=rounds {
391+ let started = Instant::now();
392+ let mut running: Vec<(u64, Child, Duration)> = (0..children)
393+ .map(|child| {
394+ let job = Job {
395+ store: store_dir.clone(),
396+ acks: acks_dir.join(format!("{round}-{child}")),
397+ child,
398+ round,
399+ // More than any child gets through before it is killed.
400+ iterations: u64::MAX,
401+ batch: OBJECTS_PER_BATCH,
402+ };
403+ let process = spawn(&job, &logs_dir.join(format!("{round}-{child}")));
404+ let kill_at = Duration::from_millis(rng.next() % window_ms);
405+ (child, process, kill_at)
406+ })
407+ .collect();
408+ running.sort_by_key(|(_, _, kill_at)| *kill_at);
409+ for (_, process, kill_at) in &mut running {
410+ if let Some(wait) = kill_at.checked_sub(started.elapsed()) {
411+ thread::sleep(wait);
412+ }
413+ // SIGKILL: no destructors, no flushing, locks released by the kernel.
414+ let _ = process.kill();
415+ }
416+ for (child, mut process, _) in running {
417+ let status = process.wait().unwrap();
418+ // Killed is expected. Exiting by itself means it failed.
419+ assert!(
420+ status.code().is_none(),
421+ "seed {seed}, round {round}: {}",
422+ child_failure(child, &logs_dir.join(format!("{round}-{child}")))
423+ );
424+ }
425+
426+ let context = format!("seed {seed}, round {round}");
427+ let store = Store::open(&store_dir, options()).unwrap();
428+ let acks = read_acks(&acks_dir);
429+ let (before, report) = verify(&store, &acks, &context);
430+ acknowledged = acks.increments.len();
431+ // Shown with --nocapture: what the kills left behind.
432+ eprintln!(
433+ "{context}: {before} operations, {} objects, {} segments ({} sealed), \
434+ leftovers: {} torn segment bytes, {} torn journal entries, \
435+ {} unindexed records, {} torn log bytes, {} temporary files",
436+ report.objects,
437+ report.segments,
438+ report.sealed_segments,
439+ report.torn_segment_bytes,
440+ report.torn_journal_entries,
441+ report.unindexed_records,
442+ report.torn_log_bytes,
443+ report.temporary_files,
444+ );
445+
446+ // Writing after the crash: segments of the dead are taken over, and
447+ // a torn end of the log is cut off.
448+ let tip = store
449+ .put(
450+ Kind::Blob,
451+ format!("written by the parent after round {round}").as_bytes(),
452+ )
453+ .unwrap();
454+ let (seq, _) = increment(&store, "parent", "parent", tip);
455+ assert_eq!(seq, before + 1, "{context}");
456+ verify(&store, &acks, &format!("{context}, after the parent wrote"));
457+ }
458+ // The children got work done before they were killed.
459+ assert!(acknowledged > 0, "seed {seed}: no child got anything done");
460+}