Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 8.8 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Power lost between flushes, simulated.
5//!
6//! A test watches every batch of flushes the store makes on its thread, and
7//! keeps a model of what a power loss could leave on the disk at any point:
8//! a file holds what it held when a batch last flushed it; a name created,
9//! renamed or removed in a directory stays that way once the directory is
10//! flushed; and the op log, the one file whose newest bytes could do harm,
11//! holds everything written to it so far, flushed or not. Right before every
12//! batch, the moment a crash between two flushes would cut the work short,
13//! the model is written out as a store of its own, and that store must be
14//! consistent: every ref points at an object it can read whole, with what
15//! that object needs, and fsck finds no ref to a missing object.
16
17use std::cell::RefCell;
18use std::collections::{BTreeMap, HashMap};
19use std::convert::Infallible;
20use std::fs;
21use std::path::{Path, PathBuf};
22use std::rc::Rc;
23
24use braid_format::{Kind, ObjectId, Objects};
25
26use crate::fsutil::observe::{self, When};
27use crate::{Durability, Error, Options, Problem, RefUpdate, Store};
28
29/// What a power loss could leave of each file, by path.
30#[derive(Clone, Debug, Default)]
31struct Disk {
32 files: BTreeMap<PathBuf, Vec<u8>>,
33}
34
35/// The model, and the stores it says a crash could leave.
36#[derive(Debug, Default)]
37struct Model {
38 disk: Disk,
39 /// What the disk could hold right before each batch.
40 crashes: Vec<Disk>,
41}
42
43impl Model {
44 fn before(&mut self, root: &Path) {
45 let mut disk = self.disk.clone();
46 // The log may hold its newest record although nobody flushed it.
47 let log = root.join("oplog").join("log");
48 if let Ok(bytes) = fs::read(&log) {
49 disk.files.insert(log, bytes);
50 }
51 self.crashes.push(disk);
52 }
53
54 fn after(&mut self, paths: &[PathBuf]) {
55 for path in paths {
56 if path.is_dir() {
57 self.flush_dir(path);
58 } else if let Ok(bytes) = fs::read(path) {
59 self.disk.files.insert(path.clone(), bytes);
60 }
61 }
62 }
63
64 /// A flushed directory keeps the names it has now: files removed from
65 /// it are gone, and files renamed into it are there with what they
66 /// hold, which was flushed before the rename. Other new names are there
67 /// with what their own flushes made durable, nothing so far.
68 fn flush_dir(&mut self, dir: &Path) {
69 self.disk
70 .files
71 .retain(|path, _| path.parent() != Some(dir) || path.exists());
72 let Ok(entries) = fs::read_dir(dir) else {
73 return;
74 };
75 for entry in entries.flatten() {
76 let path = entry.path();
77 if path.is_dir() || self.disk.files.contains_key(&path) {
78 continue;
79 }
80 let name = entry.file_name().to_string_lossy().into_owned();
81 let published = name == "format"
82 || name.starts_with("ckpt.")
83 || name.ends_with(".idx")
84 || name.ends_with(".midx");
85 let bytes = if published {
86 fs::read(&path).unwrap_or_default()
87 } else {
88 Vec::new()
89 };
90 self.disk.files.insert(path, bytes);
91 }
92 }
93}
94
95/// Writes `disk`, whose paths are under `root`, as a store under `to`.
96fn materialize(disk: &Disk, root: &Path, to: &Path) {
97 for dir in ["seg", "oplog"] {
98 fs::create_dir_all(to.join(dir)).unwrap();
99 }
100 for (path, bytes) in &disk.files {
101 let Ok(relative) = path.strip_prefix(root) else {
102 continue;
103 };
104 if relative
105 .file_name()
106 .is_some_and(|name| name.to_string_lossy().starts_with("tmp-"))
107 {
108 continue;
109 }
110 let target = to.join(relative);
111 fs::create_dir_all(target.parent().unwrap()).unwrap();
112 fs::write(target, bytes).unwrap();
113 }
114}
115
116/// Text that compresses, with a few bytes that differ from one version to
117/// the next, so that versions become deltas.
118fn text(version: u64) -> Vec<u8> {
119 let mut out = Vec::new();
120 for line in 0..120u64 {
121 let value = line.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ (line * version / 7);
122 out.extend_from_slice(format!("line {line}: {value:016x}\n").as_bytes());
123 }
124 out
125}
126
127fn run(durability: Durability) {
128 let dir = tempfile::tempdir().unwrap();
129 let root = dir.path().join("store");
130 let options = Options {
131 durability,
132 segment_size: 4096,
133 segment_records: 6,
134 merge_threshold: 3,
135 checkpoint_interval: 4,
136 };
137 let model = Rc::new(RefCell::new(Model::default()));
138 let hook_model = Rc::clone(&model);
139 let hook_root = root.clone();
140 let watching = observe::watch(move |when, paths| {
141 let mut model = hook_model.borrow_mut();
142 match when {
143 When::Before => model.before(&hook_root),
144 When::After => model.after(paths),
145 }
146 });
147
148 let store = Store::init(&root, options.clone()).unwrap();
149 // A second writer, whose copies the first relies on without them being
150 // flushed by their writer.
151 let other = Store::open(&root, options.clone()).unwrap();
152 let mut previous: Option<ObjectId> = None;
153 for round in 0..24u64 {
154 // Written before the transaction, flushed before it takes the lock.
155 let before = store
156 .put(Kind::Changeset, format!("round {round}").as_bytes())
157 .unwrap();
158 // Written by another writer that never flushes: the transaction
159 // finds it in that writer's open segment, and must flush that.
160 let shared = format!("written by the other writer in round {round}").repeat(3);
161 let theirs = other.put(Kind::Tree, shared.as_bytes()).unwrap();
162 if round % 2 == 1 {
163 store.rescan().unwrap();
164 }
165 store
166 .transact_with("agent", |refs| {
167 // Written inside, as a landing writes what it rebases: only
168 // the transaction flushes it, before its record.
169 let payload = text(round);
170 let tip = match previous {
171 Some(similar) if round % 3 != 0 => {
172 store.put_similar(Kind::Blob, &payload, &similar)
173 }
174 _ => store.put(Kind::Blob, &payload),
175 }
176 .unwrap();
177 previous = Some(tip);
178 Ok::<_, Infallible>((
179 vec![
180 RefUpdate::new("main", refs.get("main"), Some(tip)),
181 RefUpdate::new("before", refs.get("before"), Some(before)),
182 RefUpdate::new("theirs", refs.get("theirs"), Some(theirs)),
183 ],
184 "advance".to_owned(),
185 ))
186 })
187 .unwrap();
188 }
189 drop(watching);
190 let report = store.fsck().unwrap();
191 assert!(report.is_clean(), "{:#?}", report.problems);
192 // The workload went through every kind of flush.
193 let names: Vec<String> = fs::read_dir(root.join("seg"))
194 .unwrap()
195 .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
196 .collect();
197 assert!(
198 names.iter().any(|name| name.ends_with(".midx")),
199 "{names:?}"
200 );
201
202 let model = model.borrow();
203 assert!(model.crashes.len() > 50, "{}", model.crashes.len());
204 let mut moved = HashMap::new();
205 for (at, disk) in model.crashes.iter().enumerate() {
206 let crashed = tempfile::tempdir().unwrap();
207 let copy = crashed.path().join("store");
208 materialize(disk, &root, &copy);
209 let store = match Store::open(&copy, options.clone()) {
210 Ok(store) => store,
211 // Before the store was created: nothing to keep.
212 Err(Error::NotAStore { .. }) => continue,
213 Err(err) => panic!("{durability:?}, crash before batch {at}: {err}"),
214 };
215 let refs = store.refs().unwrap();
216 for (name, id) in refs.iter() {
217 let found = store.get(&id);
218 assert!(
219 matches!(found, Ok(Some(_))),
220 "{durability:?}, crash before batch {at}: ref {name} points at {id}, which reads {found:?}"
221 );
222 }
223 let report = store.fsck().unwrap();
224 assert!(
225 !report
226 .problems
227 .iter()
228 .any(|problem| matches!(problem, Problem::MissingObject { .. })),
229 "{durability:?}, crash before batch {at}: {:#?}",
230 report.problems
231 );
232 moved.insert(refs.seq(), at);
233 }
234 // Crashes cut the history at many points.
235 assert!(moved.len() > 10, "{moved:?}");
236}
237
238#[test]
239fn a_crash_between_flushes_never_leaves_a_ref_to_a_lost_object() {
240 run(Durability::Ordered);
241 run(Durability::Full);
242}