Elffuss BraidHub

utopia-ia/elffuss-braid public

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