utopia-ia/elffuss-braid public
Changesets · Branches · Tags · Compare
| Changeset | ec65e8b44b761c451a5c5ca40c75f040bad0853a3148ff1470f6a6f8460c78d3 |
|---|---|
| Author | KikoCis <KikoCis@users.noreply.github.com> · 2026-10-15 21:41 +02:00 |
| Committer | KikoCis <KikoCis@users.noreply.github.com> · 2026-10-15 21:41 +02:00 |
| Parents | 31e0b6f636f3 |
2 files changed
added crates/store/tests/properties.rs +264 −0
| @@ -0,0 +1,264 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | + | |
| 4 | +//! Random sequences of operations, compared with simple reference models: | |
| 5 | +//! objects with `MemoryObjects`, the op log with a map and a list. | |
| 6 | + | |
| 7 | +use std::collections::{BTreeMap, HashSet}; | |
| 8 | +use std::convert::Infallible; | |
| 9 | + | |
| 10 | +use braid_format::MemoryObjects; | |
| 11 | +use braid_store::{Error, Kind, ObjectId, Objects, Options, RefUpdate, Store}; | |
| 12 | +use proptest::prelude::*; | |
| 13 | + | |
| 14 | +/// Cases per property: a few by default, many with `BRAID_STRESS=1`. Every | |
| 15 | +/// case flushes to disk, so the default stays small. | |
| 16 | +fn cases() -> u32 { | |
| 17 | + if std::env::var_os("BRAID_STRESS").is_some_and(|value| value != "0") { | |
| 18 | + 256 | |
| 19 | + } else { | |
| 20 | + 12 | |
| 21 | + } | |
| 22 | +} | |
| 23 | + | |
| 24 | +#[derive(Clone, Debug)] | |
| 25 | +enum ObjectOp { | |
| 26 | + Put(Kind, Vec<u8>), | |
| 27 | + /// Reads one of the objects stored so far, picked by this number. | |
| 28 | + Get(usize), | |
| 29 | + /// Reads an object that may not exist. | |
| 30 | + Probe(Kind, Vec<u8>), | |
| 31 | + Sync, | |
| 32 | + Reopen, | |
| 33 | +} | |
| 34 | + | |
| 35 | +fn kind() -> impl Strategy<Value = Kind> { | |
| 36 | + prop::sample::select(Kind::ALL.to_vec()) | |
| 37 | +} | |
| 38 | + | |
| 39 | +fn payload() -> impl Strategy<Value = Vec<u8>> { | |
| 40 | + prop_oneof![ | |
| 41 | + // Small: stored raw. | |
| 42 | + prop::collection::vec(any::<u8>(), 0..80), | |
| 43 | + // Repetitive: compressed. | |
| 44 | + (prop::collection::vec(any::<u8>(), 1..12), 8usize..400) | |
| 45 | + .prop_map(|(unit, times)| unit.repeat(times)), | |
| 46 | + // Noise: stored raw because it does not compress. | |
| 47 | + prop::collection::vec(any::<u8>(), 65..1500), | |
| 48 | + ] | |
| 49 | +} | |
| 50 | + | |
| 51 | +fn object_op() -> impl Strategy<Value = ObjectOp> { | |
| 52 | + prop_oneof![ | |
| 53 | + 8 => (kind(), payload()).prop_map(|(kind, payload)| ObjectOp::Put(kind, payload)), | |
| 54 | + 4 => any::<usize>().prop_map(ObjectOp::Get), | |
| 55 | + 1 => (kind(), payload()).prop_map(|(kind, payload)| ObjectOp::Probe(kind, payload)), | |
| 56 | + 1 => Just(ObjectOp::Sync), | |
| 57 | + 1 => Just(ObjectOp::Reopen), | |
| 58 | + ] | |
| 59 | +} | |
| 60 | + | |
| 61 | +proptest! { | |
| 62 | + #![proptest_config(ProptestConfig::with_cases(cases()))] | |
| 63 | + | |
| 64 | + /// Objects behave as in memory, across reopening and sealing. | |
| 65 | + #[test] | |
| 66 | + fn objects_behave_like_memory( | |
| 67 | + ops in prop::collection::vec(object_op(), 1..80), | |
| 68 | + segment_size in 64u64..6000, | |
| 69 | + ) { | |
| 70 | + let dir = tempfile::tempdir().unwrap(); | |
| 71 | + let options = Options { segment_size, ..Options::default() }; | |
| 72 | + let mut store = Store::init(dir.path(), options.clone()).unwrap(); | |
| 73 | + let model = MemoryObjects::new(); | |
| 74 | + let mut stored = Vec::new(); | |
| 75 | + for op in ops { | |
| 76 | + match op { | |
| 77 | + ObjectOp::Put(kind, payload) => { | |
| 78 | + let id = store.put(kind, &payload).unwrap(); | |
| 79 | + prop_assert_eq!(id, model.put(kind, &payload).unwrap()); | |
| 80 | + stored.push(id); | |
| 81 | + } | |
| 82 | + ObjectOp::Get(pick) => { | |
| 83 | + if !stored.is_empty() { | |
| 84 | + let id = stored[pick % stored.len()]; | |
| 85 | + prop_assert_eq!(store.get(&id).unwrap(), model.get(&id).unwrap()); | |
| 86 | + prop_assert_eq!(store.stat(&id).unwrap(), model.stat(&id).unwrap()); | |
| 87 | + } | |
| 88 | + } | |
| 89 | + ObjectOp::Probe(kind, payload) => { | |
| 90 | + let id = ObjectId::hash(kind, &payload); | |
| 91 | + prop_assert_eq!(store.get(&id).unwrap(), model.get(&id).unwrap()); | |
| 92 | + prop_assert_eq!(store.contains(&id).unwrap(), model.contains(&id).unwrap()); | |
| 93 | + prop_assert_eq!(store.stat(&id).unwrap(), model.stat(&id).unwrap()); | |
| 94 | + } | |
| 95 | + ObjectOp::Sync => store.sync().unwrap(), | |
| 96 | + ObjectOp::Reopen => { | |
| 97 | + drop(store); | |
| 98 | + store = Store::open(dir.path(), options.clone()).unwrap(); | |
| 99 | + } | |
| 100 | + } | |
| 101 | + } | |
| 102 | + store.sync().unwrap(); | |
| 103 | + drop(store); | |
| 104 | + let store = Store::open(dir.path(), options).unwrap(); | |
| 105 | + for id in model.ids() { | |
| 106 | + prop_assert_eq!(store.get(&id).unwrap(), model.get(&id).unwrap()); | |
| 107 | + prop_assert_eq!(store.stat(&id).unwrap(), model.stat(&id).unwrap()); | |
| 108 | + } | |
| 109 | + let report = store.fsck().unwrap(); | |
| 110 | + prop_assert!(report.is_clean(), "{:#?}", report.problems); | |
| 111 | + prop_assert_eq!(report.objects, model.len() as u64); | |
| 112 | + // One handle at a time never writes an object twice. | |
| 113 | + prop_assert_eq!(report.records, model.len() as u64); | |
| 114 | + } | |
| 115 | +} | |
| 116 | + | |
| 117 | +#[derive(Clone, Debug)] | |
| 118 | +enum LogOp { | |
| 119 | + /// Points ref `name` at value `value`, expecting what the model holds, | |
| 120 | + /// or a value it cannot hold if `stale`. | |
| 121 | + Set { | |
| 122 | + name: u8, | |
| 123 | + value: u8, | |
| 124 | + stale: bool, | |
| 125 | + }, | |
| 126 | + Delete { | |
| 127 | + name: u8, | |
| 128 | + }, | |
| 129 | + Undo, | |
| 130 | + Reopen, | |
| 131 | +} | |
| 132 | + | |
| 133 | +fn log_op() -> impl Strategy<Value = LogOp> { | |
| 134 | + prop_oneof![ | |
| 135 | + 6 => (0u8..4, 0u8..6, prop::bool::weighted(0.15)) | |
| 136 | + .prop_map(|(name, value, stale)| LogOp::Set { name, value, stale }), | |
| 137 | + 2 => (0u8..4).prop_map(|name| LogOp::Delete { name }), | |
| 138 | + 2 => Just(LogOp::Undo), | |
| 139 | + 1 => Just(LogOp::Reopen), | |
| 140 | + ] | |
| 141 | +} | |
| 142 | + | |
| 143 | +/// The op log as a map of refs and a list of operations. | |
| 144 | +#[derive(Default)] | |
| 145 | +struct Model { | |
| 146 | + refs: BTreeMap<String, ObjectId>, | |
| 147 | + /// Index `i` holds operation `i + 1`: what it undid, and its updates. | |
| 148 | + ops: Vec<(Option<u64>, Vec<RefUpdate>)>, | |
| 149 | +} | |
| 150 | + | |
| 151 | +impl Model { | |
| 152 | + fn apply(&mut self, undoes: Option<u64>, updates: Vec<RefUpdate>) { | |
| 153 | + for update in &updates { | |
| 154 | + match update.new { | |
| 155 | + Some(id) => self.refs.insert(update.name.clone(), id), | |
| 156 | + None => self.refs.remove(&update.name), | |
| 157 | + }; | |
| 158 | + } | |
| 159 | + self.ops.push((undoes, updates)); | |
| 160 | + } | |
| 161 | + | |
| 162 | + /// The operation an undo reverts: the newest that is neither an undo | |
| 163 | + /// nor undone. | |
| 164 | + fn undo_target(&self) -> Option<u64> { | |
| 165 | + let mut undone = HashSet::new(); | |
| 166 | + for (index, (undoes, _)) in self.ops.iter().enumerate().rev() { | |
| 167 | + let seq = index as u64 + 1; | |
| 168 | + if let Some(target) = undoes { | |
| 169 | + undone.insert(*target); | |
| 170 | + } else if !undone.contains(&seq) { | |
| 171 | + return Some(seq); | |
| 172 | + } | |
| 173 | + } | |
| 174 | + None | |
| 175 | + } | |
| 176 | +} | |
| 177 | + | |
| 178 | +fn value(n: u8) -> ObjectId { | |
| 179 | + ObjectId::hash(Kind::Changeset, &[n]) | |
| 180 | +} | |
| 181 | + | |
| 182 | +proptest! { | |
| 183 | + #![proptest_config(ProptestConfig::with_cases(cases()))] | |
| 184 | + | |
| 185 | + /// The op log behaves like the model, across reopening and checkpoints. | |
| 186 | + #[test] | |
| 187 | + fn op_log_behaves_like_a_model( | |
| 188 | + ops in prop::collection::vec(log_op(), 1..40), | |
| 189 | + checkpoint_interval in 0u64..5, | |
| 190 | + ) { | |
| 191 | + let dir = tempfile::tempdir().unwrap(); | |
| 192 | + let options = Options { checkpoint_interval, ..Options::default() }; | |
| 193 | + let mut store = Store::init(dir.path(), options.clone()).unwrap(); | |
| 194 | + for n in 0..6 { | |
| 195 | + store.put(Kind::Changeset, &[n]).unwrap(); | |
| 196 | + } | |
| 197 | + store.sync().unwrap(); | |
| 198 | + let mut model = Model::default(); | |
| 199 | + | |
| 200 | + for op in ops { | |
| 201 | + match op { | |
| 202 | + LogOp::Set { name, value: n, stale } => { | |
| 203 | + let name = format!("ref/{name}"); | |
| 204 | + let current = model.refs.get(&name).copied(); | |
| 205 | + let old = if stale { Some(value(200)) } else { current }; | |
| 206 | + let update = RefUpdate::new(name, old, Some(value(n))); | |
| 207 | + let result = store.transact("prop", "set", |_| { | |
| 208 | + Ok::<_, Infallible>(vec![update.clone()]) | |
| 209 | + }); | |
| 210 | + if stale { | |
| 211 | + prop_assert!(result.unwrap_err().is_conflict()); | |
| 212 | + } else { | |
| 213 | + let op = result.unwrap(); | |
| 214 | + prop_assert_eq!(op.seq, model.ops.len() as u64 + 1); | |
| 215 | + model.apply(None, vec![update]); | |
| 216 | + } | |
| 217 | + } | |
| 218 | + LogOp::Delete { name } => { | |
| 219 | + let name = format!("ref/{name}"); | |
| 220 | + let update = RefUpdate::new(name.clone(), model.refs.get(&name).copied(), None); | |
| 221 | + store | |
| 222 | + .transact("prop", "delete", |_| Ok::<_, Infallible>(vec![update.clone()])) | |
| 223 | + .unwrap(); | |
| 224 | + model.apply(None, vec![update]); | |
| 225 | + } | |
| 226 | + LogOp::Undo => match model.undo_target() { | |
| 227 | + None => prop_assert!(matches!(store.undo_last("prop"), Err(Error::NothingToUndo))), | |
| 228 | + Some(target) => { | |
| 229 | + let op = store.undo_last("prop").unwrap(); | |
| 230 | + prop_assert_eq!(op.undoes, Some(target)); | |
| 231 | + let reverted: Vec<RefUpdate> = model.ops[target as usize - 1] | |
| 232 | + .1 | |
| 233 | + .iter() | |
| 234 | + .map(|update| RefUpdate::new(update.name.clone(), update.new, update.old)) | |
| 235 | + .collect(); | |
| 236 | + prop_assert_eq!(&op.updates, &reverted); | |
| 237 | + model.apply(Some(target), reverted); | |
| 238 | + } | |
| 239 | + }, | |
| 240 | + LogOp::Reopen => { | |
| 241 | + drop(store); | |
| 242 | + store = Store::open(dir.path(), options.clone()).unwrap(); | |
| 243 | + } | |
| 244 | + } | |
| 245 | + let refs = store.refs().unwrap(); | |
| 246 | + prop_assert_eq!(refs.as_map(), &model.refs); | |
| 247 | + prop_assert_eq!(refs.seq(), model.ops.len() as u64); | |
| 248 | + } | |
| 249 | + | |
| 250 | + drop(store); | |
| 251 | + let store = Store::open(dir.path(), options).unwrap(); | |
| 252 | + let log = store.log(usize::MAX).unwrap(); | |
| 253 | + prop_assert_eq!(log.len(), model.ops.len()); | |
| 254 | + for (op, seq) in log.iter().zip((1..=model.ops.len() as u64).rev()) { | |
| 255 | + prop_assert_eq!(op.seq, seq); | |
| 256 | + let (undoes, updates) = &model.ops[seq as usize - 1]; | |
| 257 | + prop_assert_eq!(&op.undoes, undoes); | |
| 258 | + prop_assert_eq!(&op.updates, updates); | |
| 259 | + } | |
| 260 | + let report = store.fsck().unwrap(); | |
| 261 | + prop_assert!(report.is_clean(), "{:#?}", report.problems); | |
| 262 | + prop_assert_eq!(report.operations, model.ops.len() as u64); | |
| 263 | + } | |
| 264 | +} |
added crates/store/tests/store.rs +991 −0
| @@ -0,0 +1,991 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | + | |
| 4 | +//! The store through its public API: reopening, sealing, several handles, | |
| 5 | +//! torn tails, damage, and the op log. | |
| 6 | + | |
| 7 | +use std::convert::Infallible; | |
| 8 | +use std::fs::{self, OpenOptions}; | |
| 9 | +use std::io::Write; | |
| 10 | +use std::path::{Path, PathBuf}; | |
| 11 | + | |
| 12 | +use braid_store::{ | |
| 13 | + Durability, Error, Kind, ObjectId, Objects, Options, Problem, RefUpdate, Store, TransactError, | |
| 14 | +}; | |
| 15 | + | |
| 16 | +fn options(segment_size: u64, checkpoint_interval: u64) -> Options { | |
| 17 | + Options { | |
| 18 | + segment_size, | |
| 19 | + checkpoint_interval, | |
| 20 | + ..Options::default() | |
| 21 | + } | |
| 22 | +} | |
| 23 | + | |
| 24 | +fn new_store(options: Options) -> (tempfile::TempDir, Store) { | |
| 25 | + let dir = tempfile::tempdir().unwrap(); | |
| 26 | + let store = Store::init(dir.path().join("store"), options).unwrap(); | |
| 27 | + (dir, store) | |
| 28 | +} | |
| 29 | + | |
| 30 | +/// Files in `seg/` with this extension, sorted. | |
| 31 | +fn segment_files(store: &Store, extension: &str) -> Vec<PathBuf> { | |
| 32 | + let mut files: Vec<PathBuf> = fs::read_dir(store.root().join("seg")) | |
| 33 | + .unwrap() | |
| 34 | + .map(|entry| entry.unwrap().path()) | |
| 35 | + .filter(|path| path.extension().is_some_and(|ext| ext == extension)) | |
| 36 | + .collect(); | |
| 37 | + files.sort(); | |
| 38 | + files | |
| 39 | +} | |
| 40 | + | |
| 41 | +fn flip_byte(path: &Path, offset: u64) { | |
| 42 | + let mut bytes = fs::read(path).unwrap(); | |
| 43 | + bytes[offset as usize] ^= 0x20; | |
| 44 | + fs::write(path, bytes).unwrap(); | |
| 45 | +} | |
| 46 | + | |
| 47 | +fn append_bytes(path: &Path, bytes: &[u8]) { | |
| 48 | + OpenOptions::new() | |
| 49 | + .append(true) | |
| 50 | + .open(path) | |
| 51 | + .unwrap() | |
| 52 | + .write_all(bytes) | |
| 53 | + .unwrap(); | |
| 54 | +} | |
| 55 | + | |
| 56 | +/// A mix of payloads: tiny, compressible, incompressible. | |
| 57 | +fn payloads(n: usize) -> Vec<(Kind, Vec<u8>)> { | |
| 58 | + let mut state = 0x2545_f491_4f6c_dd1du64; | |
| 59 | + let mut next = move || { | |
| 60 | + state ^= state << 13; | |
| 61 | + state ^= state >> 7; | |
| 62 | + state ^= state << 17; | |
| 63 | + state | |
| 64 | + }; | |
| 65 | + (0..n) | |
| 66 | + .map(|i| { | |
| 67 | + let kind = Kind::ALL[i % Kind::ALL.len()]; | |
| 68 | + let payload = match i % 3 { | |
| 69 | + 0 => format!("small {i}").into_bytes(), | |
| 70 | + 1 => format!("line {i} of a compressible object\n") | |
| 71 | + .repeat(40) | |
| 72 | + .into_bytes(), | |
| 73 | + _ => (0..500 + i * 7).map(|_| next() as u8).collect(), | |
| 74 | + }; | |
| 75 | + (kind, payload) | |
| 76 | + }) | |
| 77 | + .collect() | |
| 78 | +} | |
| 79 | + | |
| 80 | +fn assert_clean(store: &Store) -> braid_store::FsckReport { | |
| 81 | + let report = store.fsck().unwrap(); | |
| 82 | + assert!(report.is_clean(), "{:#?}", report.problems); | |
| 83 | + report | |
| 84 | +} | |
| 85 | + | |
| 86 | +fn set(name: &str, old: Option<ObjectId>, new: Option<ObjectId>) -> Vec<RefUpdate> { | |
| 87 | + vec![RefUpdate::new(name, old, new)] | |
| 88 | +} | |
| 89 | + | |
| 90 | +#[test] | |
| 91 | +fn objects_survive_reopen() { | |
| 92 | + let (dir, store) = new_store(Options::default()); | |
| 93 | + let root = store.root().to_path_buf(); | |
| 94 | + let objects = payloads(30); | |
| 95 | + let ids: Vec<ObjectId> = objects | |
| 96 | + .iter() | |
| 97 | + .map(|(kind, payload)| store.put(*kind, payload).unwrap()) | |
| 98 | + .collect(); | |
| 99 | + store.sync().unwrap(); | |
| 100 | + for ((kind, payload), id) in objects.iter().zip(&ids) { | |
| 101 | + assert_eq!(*id, ObjectId::hash(*kind, payload)); | |
| 102 | + assert_eq!(store.get(id).unwrap(), Some((*kind, payload.clone()))); | |
| 103 | + } | |
| 104 | + drop(store); | |
| 105 | + | |
| 106 | + let store = Store::open(&root, Options::default()).unwrap(); | |
| 107 | + for ((kind, payload), id) in objects.iter().zip(&ids) { | |
| 108 | + assert!(store.contains(id).unwrap()); | |
| 109 | + assert_eq!(store.get(id).unwrap(), Some((*kind, payload.clone()))); | |
| 110 | + } | |
| 111 | + let absent = ObjectId::hash(Kind::Blob, b"never stored"); | |
| 112 | + assert_eq!(store.get(&absent).unwrap(), None); | |
| 113 | + assert!(!store.contains(&absent).unwrap()); | |
| 114 | + let report = assert_clean(&store); | |
| 115 | + assert_eq!(report.objects, 30); | |
| 116 | + assert_eq!(report.records, 30); | |
| 117 | + drop(dir); | |
| 118 | +} | |
| 119 | + | |
| 120 | +#[test] | |
| 121 | +fn stat_reads_only_the_header() { | |
| 122 | + let (_dir, a) = new_store(options(4096, 1000)); | |
| 123 | + let root = a.root().to_path_buf(); | |
| 124 | + let objects = payloads(40); | |
| 125 | + for (kind, payload) in &objects { | |
| 126 | + a.put(*kind, payload).unwrap(); | |
| 127 | + } | |
| 128 | + a.sync().unwrap(); | |
| 129 | + // Raw, compressed, sealed and open records alike, from another handle. | |
| 130 | + let b = Store::open(&root, options(4096, 1000)).unwrap(); | |
| 131 | + for (kind, payload) in &objects { | |
| 132 | + let id = ObjectId::hash(*kind, payload); | |
| 133 | + assert_eq!(b.stat(&id).unwrap(), Some((*kind, payload.len() as u64))); | |
| 134 | + } | |
| 135 | + let fresh = a.put(Kind::Tree, b"written after b opened").unwrap(); | |
| 136 | + assert_eq!(b.stat(&fresh).unwrap(), Some((Kind::Tree, 22))); | |
| 137 | + let absent = ObjectId::hash(Kind::Blob, b"never stored"); | |
| 138 | + assert_eq!(b.stat(&absent).unwrap(), None); | |
| 139 | + drop((a, b)); | |
| 140 | + | |
| 141 | + // A store with a single record at the start of a single segment. | |
| 142 | + let (_dir, store) = new_store(Options::default()); | |
| 143 | + let root = store.root().to_path_buf(); | |
| 144 | + let payload = b"payload damage does not reach stat"; | |
| 145 | + let id = store.put(Kind::Blob, payload).unwrap(); | |
| 146 | + store.sync().unwrap(); | |
| 147 | + let seg = segment_files(&store, "seg").remove(0); | |
| 148 | + drop(store); | |
| 149 | + | |
| 150 | + // Damage to the payload breaks get, not stat: stat never reads it. | |
| 151 | + flip_byte(&seg, 60); | |
| 152 | + let store = Store::open(&root, Options::default()).unwrap(); | |
| 153 | + assert!(matches!(store.get(&id), Err(Error::Corrupt { .. }))); | |
| 154 | + assert_eq!( | |
| 155 | + store.stat(&id).unwrap(), | |
| 156 | + Some((Kind::Blob, payload.len() as u64)) | |
| 157 | + ); | |
| 158 | + drop(store); | |
| 159 | + | |
| 160 | + // Damage to the header is caught by comparing it with the entry. | |
| 161 | + flip_byte(&seg, 12); | |
| 162 | + let store = Store::open(&root, Options::default()).unwrap(); | |
| 163 | + assert!(matches!(store.stat(&id), Err(Error::Corrupt { .. }))); | |
| 164 | +} | |
| 165 | + | |
| 166 | +#[test] | |
| 167 | +fn storing_twice_writes_once() { | |
| 168 | + let (_dir, store) = new_store(Options::default()); | |
| 169 | + let first = store.put(Kind::Blob, b"same").unwrap(); | |
| 170 | + let second = store.put(Kind::Blob, b"same").unwrap(); | |
| 171 | + assert_eq!(first, second); | |
| 172 | + // Same bytes, other kind: another object. | |
| 173 | + let tree = store.put(Kind::Tree, b"same").unwrap(); | |
| 174 | + assert_ne!(first, tree); | |
| 175 | + store.sync().unwrap(); | |
| 176 | + let report = assert_clean(&store); | |
| 177 | + assert_eq!(report.records, 2); | |
| 178 | +} | |
| 179 | + | |
| 180 | +#[test] | |
| 181 | +fn opening_needs_a_store() { | |
| 182 | + let dir = tempfile::tempdir().unwrap(); | |
| 183 | + assert!(matches!( | |
| 184 | + Store::open(dir.path(), Options::default()), | |
| 185 | + Err(Error::NotAStore { .. }) | |
| 186 | + )); | |
| 187 | + let store = Store::init(dir.path(), Options::default()).unwrap(); | |
| 188 | + drop(store); | |
| 189 | + // init is idempotent. | |
| 190 | + Store::init(dir.path(), Options::default()).unwrap(); | |
| 191 | + fs::write(dir.path().join("format"), "object-format=sha1\n").unwrap(); | |
| 192 | + assert!(matches!( | |
| 193 | + Store::open(dir.path(), Options::default()), | |
| 194 | + Err(Error::UnsupportedFormat { .. }) | |
| 195 | + )); | |
| 196 | +} | |
| 197 | + | |
| 198 | +#[test] | |
| 199 | +fn full_segments_are_sealed() { | |
| 200 | + let (_dir, store) = new_store(options(4096, 1000)); | |
| 201 | + let root = store.root().to_path_buf(); | |
| 202 | + let objects = payloads(120); | |
| 203 | + for (kind, payload) in &objects { | |
| 204 | + store.put(*kind, payload).unwrap(); | |
| 205 | + } | |
| 206 | + store.sync().unwrap(); | |
| 207 | + let sealed = segment_files(&store, "idx"); | |
| 208 | + assert!(sealed.len() >= 3, "{} sealed segments", sealed.len()); | |
| 209 | + // A sealed segment has no journal any more. | |
| 210 | + for idx in &sealed { | |
| 211 | + assert!(!idx.with_extension("jrn").exists()); | |
| 212 | + } | |
| 213 | + let report = assert_clean(&store); | |
| 214 | + assert_eq!(report.sealed_segments, sealed.len()); | |
| 215 | + assert_eq!(report.objects, 120); | |
| 216 | + drop(store); | |
| 217 | + | |
| 218 | + let store = Store::open(&root, options(4096, 1000)).unwrap(); | |
| 219 | + for (kind, payload) in &objects { | |
| 220 | + let id = ObjectId::hash(*kind, payload); | |
| 221 | + assert_eq!(store.get(&id).unwrap(), Some((*kind, payload.clone()))); | |
| 222 | + } | |
| 223 | +} | |
| 224 | + | |
| 225 | +#[test] | |
| 226 | +fn handles_see_each_other() { | |
| 227 | + let (_dir, a) = new_store(Options::default()); | |
| 228 | + let b = Store::open(a.root(), Options::default()).unwrap(); | |
| 229 | + let from_a = a.put(Kind::Blob, b"written by a").unwrap(); | |
| 230 | + let from_b = b.put(Kind::Blob, b"written by b").unwrap(); | |
| 231 | + // Each handle holds its own segment: the locks exclude each other even | |
| 232 | + // inside one process. | |
| 233 | + assert_eq!(segment_files(&a, "seg").len(), 2); | |
| 234 | + // A miss rescans the directory. | |
| 235 | + assert_eq!( | |
| 236 | + b.get(&from_a).unwrap(), | |
| 237 | + Some((Kind::Blob, b"written by a".to_vec())) | |
| 238 | + ); | |
| 239 | + assert_eq!( | |
| 240 | + a.get(&from_b).unwrap(), | |
| 241 | + Some((Kind::Blob, b"written by b".to_vec())) | |
| 242 | + ); | |
| 243 | + a.sync().unwrap(); | |
| 244 | + b.sync().unwrap(); | |
| 245 | + assert_clean(&a); | |
| 246 | +} | |
| 247 | + | |
| 248 | +#[test] | |
| 249 | +fn a_copy_in_another_writers_segment_is_reused() { | |
| 250 | + let (_dir, a) = new_store(Options::default()); | |
| 251 | + let b = Store::open(a.root(), Options::default()).unwrap(); | |
| 252 | + let id = a.put(Kind::Blob, b"shared content").unwrap(); | |
| 253 | + b.rescan().unwrap(); | |
| 254 | + // b relies on a's copy, which a has not flushed: b's sync flushes it. | |
| 255 | + assert_eq!(b.put(Kind::Blob, b"shared content").unwrap(), id); | |
| 256 | + b.sync().unwrap(); | |
| 257 | + let report = assert_clean(&b); | |
| 258 | + assert_eq!(report.records, 1); | |
| 259 | +} | |
| 260 | + | |
| 261 | +#[test] | |
| 262 | +fn a_damaged_copy_in_an_open_segment_is_written_again() { | |
| 263 | + let (_dir, a) = new_store(Options::default()); | |
| 264 | + let root = a.root().to_path_buf(); | |
| 265 | + let id = a.put(Kind::Blob, b"content that will be damaged").unwrap(); | |
| 266 | + a.sync().unwrap(); | |
| 267 | + drop(a); | |
| 268 | + let seg = Store::open(&root, Options::default()).unwrap(); | |
| 269 | + let path = segment_files(&seg, "seg").remove(0); | |
| 270 | + drop(seg); | |
| 271 | + flip_byte(&path, 60); | |
| 272 | + | |
| 273 | + let b = Store::open(&root, Options::default()).unwrap(); | |
| 274 | + assert!(matches!(b.get(&id), Err(Error::Corrupt { .. }))); | |
| 275 | + assert_eq!( | |
| 276 | + b.put(Kind::Blob, b"content that will be damaged").unwrap(), | |
| 277 | + id | |
| 278 | + ); | |
| 279 | + assert_eq!( | |
| 280 | + b.get(&id).unwrap(), | |
| 281 | + Some((Kind::Blob, b"content that will be damaged".to_vec())) | |
| 282 | + ); | |
| 283 | + b.sync().unwrap(); | |
| 284 | + // The damaged record is still reported. | |
| 285 | + let report = b.fsck().unwrap(); | |
| 286 | + assert!( | |
| 287 | + report | |
| 288 | + .problems | |
| 289 | + .iter() | |
| 290 | + .any(|p| matches!(p, Problem::BadEntry { id: bad, .. } if *bad == id)), | |
| 291 | + "{:#?}", | |
| 292 | + report.problems | |
| 293 | + ); | |
| 294 | +} | |
| 295 | + | |
| 296 | +#[test] | |
| 297 | +fn threads_share_a_handle() { | |
| 298 | + let (_dir, store) = new_store(options(16 << 10, 1000)); | |
| 299 | + let objects = payloads(200); | |
| 300 | + std::thread::scope(|scope| { | |
| 301 | + for chunk in objects.chunks(25) { | |
| 302 | + let store = &store; | |
| 303 | + scope.spawn(move || { | |
| 304 | + for (kind, payload) in chunk { | |
| 305 | + let id = store.put(*kind, payload).unwrap(); | |
| 306 | + assert_eq!(store.get(&id).unwrap(), Some((*kind, payload.clone()))); | |
| 307 | + } | |
| 308 | + store.sync().unwrap(); | |
| 309 | + }); | |
| 310 | + } | |
| 311 | + }); | |
| 312 | + let report = assert_clean(&store); | |
| 313 | + assert_eq!(report.objects, 200); | |
| 314 | +} | |
| 315 | + | |
| 316 | +#[test] | |
| 317 | +fn an_abandoned_full_segment_is_sealed_by_the_next_writer() { | |
| 318 | + let (_dir, a) = new_store(Options::default()); | |
| 319 | + let root = a.root().to_path_buf(); | |
| 320 | + for (kind, payload) in payloads(20) { | |
| 321 | + a.put(kind, &payload).unwrap(); | |
| 322 | + } | |
| 323 | + a.sync().unwrap(); | |
| 324 | + drop(a); | |
| 325 | + assert!(segment_files(&Store::open(&root, Options::default()).unwrap(), "idx").is_empty()); | |
| 326 | + | |
| 327 | + let b = Store::open(&root, options(1024, 1000)).unwrap(); | |
| 328 | + b.put(Kind::Blob, b"one more").unwrap(); | |
| 329 | + b.sync().unwrap(); | |
| 330 | + assert_eq!(segment_files(&b, "idx").len(), 1); | |
| 331 | + assert_eq!(segment_files(&b, "seg").len(), 2); | |
| 332 | + let report = assert_clean(&b); | |
| 333 | + assert_eq!(report.objects, 21); | |
| 334 | +} | |
| 335 | + | |
| 336 | +#[test] | |
| 337 | +fn a_torn_segment_tail_is_skipped() { | |
| 338 | + let (_dir, store) = new_store(Options::default()); | |
| 339 | + let root = store.root().to_path_buf(); | |
| 340 | + let first = payloads(10); | |
| 341 | + for (kind, payload) in &first { | |
| 342 | + store.put(*kind, payload).unwrap(); | |
| 343 | + } | |
| 344 | + store.sync().unwrap(); | |
| 345 | + let seg = segment_files(&store, "seg").remove(0); | |
| 346 | + drop(store); | |
| 347 | + // Half of a record, as a crash in the middle of an append leaves it. | |
| 348 | + let mut torn = fs::read(&seg).unwrap(); | |
| 349 | + torn.truncate(41); | |
| 350 | + append_bytes(&seg, &torn); | |
| 351 | + | |
| 352 | + let store = Store::open(&root, Options::default()).unwrap(); | |
| 353 | + let second = payloads(25); | |
| 354 | + for (kind, payload) in &second { | |
| 355 | + store.put(*kind, payload).unwrap(); | |
| 356 | + } | |
| 357 | + store.sync().unwrap(); | |
| 358 | + drop(store); | |
| 359 | + | |
| 360 | + let store = Store::open(&root, Options::default()).unwrap(); | |
| 361 | + for (kind, payload) in first.iter().chain(&second) { | |
| 362 | + let id = ObjectId::hash(*kind, payload); | |
| 363 | + assert_eq!(store.get(&id).unwrap(), Some((*kind, payload.clone()))); | |
| 364 | + } | |
| 365 | + let report = assert_clean(&store); | |
| 366 | + assert!(report.torn_segment_bytes >= 41, "{report:?}"); | |
| 367 | + assert_eq!(report.objects, 25); | |
| 368 | +} | |
| 369 | + | |
| 370 | +#[test] | |
| 371 | +fn a_torn_journal_tail_is_skipped_and_overwritten() { | |
| 372 | + let (_dir, store) = new_store(Options::default()); | |
| 373 | + let root = store.root().to_path_buf(); | |
| 374 | + let objects = payloads(12); | |
| 375 | + for (kind, payload) in &objects[..6] { | |
| 376 | + store.put(*kind, payload).unwrap(); | |
| 377 | + } | |
| 378 | + store.sync().unwrap(); | |
| 379 | + let jrn = segment_files(&store, "jrn").remove(0); | |
| 380 | + drop(store); | |
| 381 | + append_bytes(&jrn, &[0xab; 30]); | |
| 382 | + | |
| 383 | + let store = Store::open(&root, Options::default()).unwrap(); | |
| 384 | + for (kind, payload) in &objects[6..] { | |
| 385 | + store.put(*kind, payload).unwrap(); | |
| 386 | + } | |
| 387 | + store.sync().unwrap(); | |
| 388 | + assert_eq!(fs::metadata(&jrn).unwrap().len(), 12 * 64); | |
| 389 | + drop(store); | |
| 390 | + | |
| 391 | + let store = Store::open(&root, Options::default()).unwrap(); | |
| 392 | + for (kind, payload) in &objects { | |
| 393 | + let id = ObjectId::hash(*kind, payload); | |
| 394 | + assert_eq!(store.get(&id).unwrap(), Some((*kind, payload.clone()))); | |
| 395 | + } | |
| 396 | + let report = assert_clean(&store); | |
| 397 | + assert_eq!(report.torn_journal_entries, 0); | |
| 398 | +} | |
| 399 | + | |
| 400 | +#[test] | |
| 401 | +fn a_damaged_record_is_an_error_and_fsck_reports_it() { | |
| 402 | + let (_dir, store) = new_store(Options::default()); | |
| 403 | + let root = store.root().to_path_buf(); | |
| 404 | + let id = store | |
| 405 | + .put(Kind::Blob, b"a record that will lose a bit") | |
| 406 | + .unwrap(); | |
| 407 | + store.sync().unwrap(); | |
| 408 | + let seg = segment_files(&store, "seg").remove(0); | |
| 409 | + drop(store); | |
| 410 | + flip_byte(&seg, 60); | |
| 411 | + | |
| 412 | + let store = Store::open(&root, Options::default()).unwrap(); | |
| 413 | + let err = store.get(&id).unwrap_err(); | |
| 414 | + assert!(matches!(err, Error::Corrupt { .. }), "{err}"); | |
| 415 | + let report = store.fsck().unwrap(); | |
| 416 | + assert!(!report.is_clean()); | |
| 417 | + assert!( | |
| 418 | + report | |
| 419 | + .problems | |
| 420 | + .iter() | |
| 421 | + .any(|p| matches!(p, Problem::BadEntry { id: bad, .. } if *bad == id)), | |
| 422 | + "{:#?}", | |
| 423 | + report.problems | |
| 424 | + ); | |
| 425 | +} | |
| 426 | + | |
| 427 | +#[test] | |
| 428 | +fn content_that_does_not_match_its_id_is_an_error() { | |
| 429 | + let (_dir, store) = new_store(Options::default()); | |
| 430 | + let root = store.root().to_path_buf(); | |
| 431 | + let id = store.put(Kind::Blob, b"original content").unwrap(); | |
| 432 | + store.sync().unwrap(); | |
| 433 | + let seg = segment_files(&store, "seg").remove(0); | |
| 434 | + drop(store); | |
| 435 | + // Change the payload and fix the record's CRC, as a buggy writer might. | |
| 436 | + let mut bytes = fs::read(&seg).unwrap(); | |
| 437 | + bytes[52] = b'O'; | |
| 438 | + let crc = crc32c(&bytes[..52 + 16]); | |
| 439 | + bytes[68..72].copy_from_slice(&crc.to_le_bytes()); | |
| 440 | + fs::write(&seg, bytes).unwrap(); | |
| 441 | + | |
| 442 | + let store = Store::open(&root, Options::default()).unwrap(); | |
| 443 | + assert!(matches!(store.get(&id), Err(Error::Corrupt { .. }))); | |
| 444 | + let report = store.fsck().unwrap(); | |
| 445 | + assert!( | |
| 446 | + report | |
| 447 | + .problems | |
| 448 | + .iter() | |
| 449 | + .any(|p| matches!(p, Problem::BadRecord { .. })), | |
| 450 | + "{:#?}", | |
| 451 | + report.problems | |
| 452 | + ); | |
| 453 | +} | |
| 454 | + | |
| 455 | +/// CRC-32C, bit by bit, to forge a valid record in a test. | |
| 456 | +fn crc32c(bytes: &[u8]) -> u32 { | |
| 457 | + let mut crc = !0u32; | |
| 458 | + for byte in bytes { | |
| 459 | + crc ^= u32::from(*byte); | |
| 460 | + for _ in 0..8 { | |
| 461 | + crc = if crc & 1 != 0 { | |
| 462 | + (crc >> 1) ^ 0x82f6_3b78 | |
| 463 | + } else { | |
| 464 | + crc >> 1 | |
| 465 | + }; | |
| 466 | + } | |
| 467 | + } | |
| 468 | + !crc | |
| 469 | +} | |
| 470 | + | |
| 471 | +#[test] | |
| 472 | +fn a_damaged_index_is_reported_and_worked_around() { | |
| 473 | + let (_dir, store) = new_store(options(1024, 1000)); | |
| 474 | + let root = store.root().to_path_buf(); | |
| 475 | + let objects = payloads(20); | |
| 476 | + for (kind, payload) in &objects { | |
| 477 | + store.put(*kind, payload).unwrap(); | |
| 478 | + } | |
| 479 | + store.sync().unwrap(); | |
| 480 | + let idx = segment_files(&store, "idx").remove(0); | |
| 481 | + drop(store); | |
| 482 | + flip_byte(&idx, 1100); | |
| 483 | + | |
| 484 | + let store = Store::open(&root, options(1024, 1000)).unwrap(); | |
| 485 | + for (kind, payload) in &objects { | |
| 486 | + let id = ObjectId::hash(*kind, payload); | |
| 487 | + assert_eq!(store.get(&id).unwrap(), Some((*kind, payload.clone()))); | |
| 488 | + } | |
| 489 | + let report = store.fsck().unwrap(); | |
| 490 | + assert_eq!(report.objects, 20); | |
| 491 | + assert!( | |
| 492 | + matches!(report.problems.as_slice(), [Problem::BadIndex { .. }]), | |
| 493 | + "{:#?}", | |
| 494 | + report.problems | |
| 495 | + ); | |
| 496 | +} | |
| 497 | + | |
| 498 | +#[test] | |
| 499 | +fn transactions_compare_and_swap() { | |
| 500 | + let (_dir, store) = new_store(Options::default()); | |
| 501 | + let a = store.put(Kind::Changeset, b"a").unwrap(); | |
| 502 | + let b = store.put(Kind::Changeset, b"b").unwrap(); | |
| 503 | + store.sync().unwrap(); | |
| 504 | + assert!(store.refs().unwrap().is_empty()); | |
| 505 | + | |
| 506 | + let op = store | |
| 507 | + .transact("agent-1", "create main", |refs| { | |
| 508 | + assert_eq!(refs.seq(), 0); | |
| 509 | + Ok::<_, Infallible>(set("main", None, Some(a))) | |
| 510 | + }) | |
| 511 | + .unwrap(); | |
| 512 | + assert_eq!(op.seq, 1); | |
| 513 | + assert_eq!(op.agent, "agent-1"); | |
| 514 | + assert_eq!(store.refs().unwrap().get("main"), Some(a)); | |
| 515 | + | |
| 516 | + // A stale expectation is a conflict, and nothing is recorded. | |
| 517 | + let err = store | |
| 518 | + .transact("agent-2", "stale", |_| { | |
| 519 | + Ok::<_, Infallible>(set("main", None, Some(b))) | |
| 520 | + }) | |
| 521 | + .unwrap_err(); | |
| 522 | + assert!(err.is_conflict(), "{err}"); | |
| 523 | + assert_eq!(store.refs().unwrap().seq(), 1); | |
| 524 | + | |
| 525 | + store | |
| 526 | + .transact("agent-2", "move main", |refs| { | |
| 527 | + Ok::<_, Infallible>(set("main", refs.get("main"), Some(b))) | |
| 528 | + }) | |
| 529 | + .unwrap(); | |
| 530 | + | |
| 531 | + // Refused before anything is written. | |
| 532 | + let missing = ObjectId::hash(Kind::Changeset, b"not stored"); | |
| 533 | + let err = store | |
| 534 | + .transact("agent-1", "dangling", |_| { | |
| 535 | + Ok::<_, Infallible>(set("other", None, Some(missing))) | |
| 536 | + }) | |
| 537 | + .unwrap_err(); | |
| 538 | + assert!(matches!( | |
| 539 | + err, | |
| 540 | + TransactError::Store(Error::MissingObject { .. }) | |
| 541 | + )); | |
| 542 | + let err = store | |
| 543 | + .transact("agent-1", "twice", |_| { | |
| 544 | + Ok::<_, Infallible>(vec![ | |
| 545 | + RefUpdate::new("x", None, Some(a)), | |
| 546 | + RefUpdate::new("x", None, Some(b)), | |
| 547 | + ]) | |
| 548 | + }) | |
| 549 | + .unwrap_err(); | |
| 550 | + assert!(matches!( | |
| 551 | + err, | |
| 552 | + TransactError::Store(Error::DuplicateRef { .. }) | |
| 553 | + )); | |
| 554 | + let err = store | |
| 555 | + .transact("agent-1", "bad name", |_| { | |
| 556 | + Ok::<_, Infallible>(set("", None, Some(a))) | |
| 557 | + }) | |
| 558 | + .unwrap_err(); | |
| 559 | + assert!(matches!( | |
| 560 | + err, | |
| 561 | + TransactError::Store(Error::InvalidRefName { .. }) | |
| 562 | + )); | |
| 563 | + let err = store | |
| 564 | + .transact("agent-1", "aborted", |_| { | |
| 565 | + Err::<Vec<RefUpdate>, _>("changed my mind") | |
| 566 | + }) | |
| 567 | + .unwrap_err(); | |
| 568 | + assert!(matches!(err, TransactError::Aborted("changed my mind"))); | |
| 569 | + | |
| 570 | + // Delete, and several refs at once. | |
| 571 | + store | |
| 572 | + .transact("agent-3", "branch and delete", |refs| { | |
| 573 | + Ok::<_, Infallible>(vec![ | |
| 574 | + RefUpdate::new("main", refs.get("main"), None), | |
| 575 | + RefUpdate::new("feature", None, Some(a)), | |
| 576 | + ]) | |
| 577 | + }) | |
| 578 | + .unwrap(); | |
| 579 | + let refs = store.refs().unwrap(); | |
| 580 | + assert_eq!(refs.seq(), 3); | |
| 581 | + assert_eq!(refs.get("main"), None); | |
| 582 | + assert_eq!(refs.get("feature"), Some(a)); | |
| 583 | + assert_eq!(refs.len(), 1); | |
| 584 | + assert_clean(&store); | |
| 585 | +} | |
| 586 | + | |
| 587 | +#[test] | |
| 588 | +fn the_op_log_cannot_be_used_inside_a_transaction() { | |
| 589 | + let (_dir, store) = new_store(Options::default()); | |
| 590 | + let err = store | |
| 591 | + .transact("agent", "nested", |_| { | |
| 592 | + assert!(matches!(store.refs(), Err(Error::Reentrant))); | |
| 593 | + assert!(matches!(store.log(1), Err(Error::Reentrant))); | |
| 594 | + Err::<Vec<RefUpdate>, _>(()) | |
| 595 | + }) | |
| 596 | + .unwrap_err(); | |
| 597 | + assert!(matches!(err, TransactError::Aborted(()))); | |
| 598 | + // Objects can be written from inside, and are flushed before the record. | |
| 599 | + let op = store | |
| 600 | + .transact("agent", "write inside", |refs| { | |
| 601 | + let id = store.put(Kind::Blob, b"written inside").unwrap(); | |
| 602 | + Ok::<_, Infallible>(set("inside", refs.get("inside"), Some(id))) | |
| 603 | + }) | |
| 604 | + .unwrap(); | |
| 605 | + assert_eq!(op.seq, 1); | |
| 606 | + assert_clean(&store); | |
| 607 | +} | |
| 608 | + | |
| 609 | +#[test] | |
| 610 | +fn fsck_inside_a_transaction_is_refused() { | |
| 611 | + let (_dir, store) = new_store(Options::default()); | |
| 612 | + let err = store | |
| 613 | + .transact("agent", "nested", |_| { | |
| 614 | + assert!(matches!(store.fsck(), Err(Error::Reentrant))); | |
| 615 | + assert!(matches!(store.undo_last("x"), Err(Error::Reentrant))); | |
| 616 | + Err::<Vec<RefUpdate>, _>(()) | |
| 617 | + }) | |
| 618 | + .unwrap_err(); | |
| 619 | + assert!(matches!(err, TransactError::Aborted(()))); | |
| 620 | +} | |
| 621 | + | |
| 622 | +#[test] | |
| 623 | +fn many_threads_can_create_the_same_store() { | |
| 624 | + let dir = tempfile::tempdir().unwrap(); | |
| 625 | + let root = dir.path().join("a").join("store"); | |
| 626 | + std::thread::scope(|scope| { | |
| 627 | + for n in 0..8u8 { | |
| 628 | + let root = &root; | |
| 629 | + scope.spawn(move || { | |
| 630 | + let store = Store::init(root, Options::default()).unwrap(); | |
| 631 | + store.put(Kind::Blob, &[n]).unwrap(); | |
| 632 | + store.sync().unwrap(); | |
| 633 | + }); | |
| 634 | + } | |
| 635 | + }); | |
| 636 | + let store = Store::open(&root, Options::default()).unwrap(); | |
| 637 | + for n in 0..8u8 { | |
| 638 | + assert!(store.contains(&ObjectId::hash(Kind::Blob, &[n])).unwrap()); | |
| 639 | + } | |
| 640 | + assert_eq!( | |
| 641 | + fs::read_to_string(root.join("format")).unwrap(), | |
| 642 | + "object-format=blake3-dk-v1\n" | |
| 643 | + ); | |
| 644 | + assert_clean(&store); | |
| 645 | +} | |
| 646 | + | |
| 647 | +#[test] | |
| 648 | +fn the_log_is_newest_first_and_survives_reopen() { | |
| 649 | + let (_dir, store) = new_store(Options::default()); | |
| 650 | + let root = store.root().to_path_buf(); | |
| 651 | + let ids: Vec<ObjectId> = (0..5u8) | |
| 652 | + .map(|n| store.put(Kind::Changeset, &[n]).unwrap()) | |
| 653 | + .collect(); | |
| 654 | + for (n, id) in ids.iter().enumerate() { | |
| 655 | + store | |
| 656 | + .transact(&format!("agent-{n}"), &format!("step {n}"), |refs| { | |
| 657 | + Ok::<_, Infallible>(set("main", refs.get("main"), Some(*id))) | |
| 658 | + }) | |
| 659 | + .unwrap(); | |
| 660 | + } | |
| 661 | + drop(store); | |
| 662 | + let store = Store::open(&root, Options::default()).unwrap(); | |
| 663 | + let log = store.log(3).unwrap(); | |
| 664 | + assert_eq!( | |
| 665 | + log.iter().map(|op| op.seq).collect::<Vec<_>>(), | |
| 666 | + vec![5, 4, 3] | |
| 667 | + ); | |
| 668 | + assert_eq!(log[0].description, "step 4"); | |
| 669 | + assert_eq!(log[0].updates, set("main", Some(ids[3]), Some(ids[4]))); | |
| 670 | + assert_eq!(store.log(100).unwrap().len(), 5); | |
| 671 | + assert!(store.log(0).unwrap().is_empty()); | |
| 672 | + assert_eq!(store.refs().unwrap().get("main"), Some(ids[4])); | |
| 673 | +} | |
| 674 | + | |
| 675 | +#[test] | |
| 676 | +fn undo_steps_back_one_operation_at_a_time() { | |
| 677 | + let (_dir, store) = new_store(Options::default()); | |
| 678 | + let ids: Vec<ObjectId> = (0..3u8) | |
| 679 | + .map(|n| store.put(Kind::Changeset, &[n]).unwrap()) | |
| 680 | + .collect(); | |
| 681 | + for id in &ids { | |
| 682 | + store | |
| 683 | + .transact("agent", "advance", |refs| { | |
| 684 | + Ok::<_, Infallible>(set("main", refs.get("main"), Some(*id))) | |
| 685 | + }) | |
| 686 | + .unwrap(); | |
| 687 | + } | |
| 688 | + let undo = store.undo_last("fixer").unwrap(); | |
| 689 | + assert_eq!(undo.seq, 4); | |
| 690 | + assert_eq!(undo.undoes, Some(3)); | |
| 691 | + assert_eq!(undo.agent, "fixer"); | |
| 692 | + assert_eq!(store.refs().unwrap().get("main"), Some(ids[1])); | |
| 693 | + assert_eq!(store.undo_last("fixer").unwrap().undoes, Some(2)); | |
| 694 | + assert_eq!(store.refs().unwrap().get("main"), Some(ids[0])); | |
| 695 | + assert_eq!(store.undo_last("fixer").unwrap().undoes, Some(1)); | |
| 696 | + assert_eq!(store.refs().unwrap().get("main"), None); | |
| 697 | + assert!(matches!( | |
| 698 | + store.undo_last("fixer"), | |
| 699 | + Err(Error::NothingToUndo) | |
| 700 | + )); | |
| 701 | + | |
| 702 | + // A new operation can be undone; one whose ref moved since cannot. | |
| 703 | + store | |
| 704 | + .transact("agent", "again", |refs| { | |
| 705 | + Ok::<_, Infallible>(set("main", refs.get("main"), Some(ids[2]))) | |
| 706 | + }) | |
| 707 | + .unwrap(); | |
| 708 | + store | |
| 709 | + .transact("agent", "other", |refs| { | |
| 710 | + Ok::<_, Infallible>(set("other", refs.get("other"), Some(ids[0]))) | |
| 711 | + }) | |
| 712 | + .unwrap(); | |
| 713 | + assert_eq!(store.undo_last("fixer").unwrap().undoes, Some(8)); | |
| 714 | + assert_eq!(store.refs().unwrap().get("other"), None); | |
| 715 | + store | |
| 716 | + .transact("agent", "move main by hand", |refs| { | |
| 717 | + Ok::<_, Infallible>(set("main", refs.get("main"), Some(ids[1]))) | |
| 718 | + }) | |
| 719 | + .unwrap(); | |
| 720 | + // Undoing "move main by hand" works; undoing "again" after it does too. | |
| 721 | + assert_eq!(store.undo_last("fixer").unwrap().undoes, Some(10)); | |
| 722 | + assert_eq!(store.undo_last("fixer").unwrap().undoes, Some(7)); | |
| 723 | + assert_eq!(store.refs().unwrap().get("main"), None); | |
| 724 | + assert_clean(&store); | |
| 725 | +} | |
| 726 | + | |
| 727 | +#[test] | |
| 728 | +fn undo_reverts_every_ref_an_operation_changed() { | |
| 729 | + let (_dir, store) = new_store(Options::default()); | |
| 730 | + let a = store.put(Kind::Changeset, b"a").unwrap(); | |
| 731 | + let b = store.put(Kind::Changeset, b"b").unwrap(); | |
| 732 | + store | |
| 733 | + .transact("agent", "start", |_| { | |
| 734 | + Ok::<_, Infallible>(vec![ | |
| 735 | + RefUpdate::new("main", None, Some(a)), | |
| 736 | + RefUpdate::new("old", None, Some(b)), | |
| 737 | + ]) | |
| 738 | + }) | |
| 739 | + .unwrap(); | |
| 740 | + store | |
| 741 | + .transact("agent", "reshape", |refs| { | |
| 742 | + Ok::<_, Infallible>(vec![ | |
| 743 | + RefUpdate::new("main", refs.get("main"), Some(b)), | |
| 744 | + RefUpdate::new("old", refs.get("old"), None), | |
| 745 | + RefUpdate::new("new", None, Some(a)), | |
| 746 | + ]) | |
| 747 | + }) | |
| 748 | + .unwrap(); | |
| 749 | + let undo = store.undo_last("fixer").unwrap(); | |
| 750 | + assert_eq!(undo.undoes, Some(2)); | |
| 751 | + assert_eq!(undo.description, "undo operation 2"); | |
| 752 | + assert_eq!( | |
| 753 | + undo.updates, | |
| 754 | + vec![ | |
| 755 | + RefUpdate::new("main", Some(b), Some(a)), | |
| 756 | + RefUpdate::new("old", None, Some(b)), | |
| 757 | + RefUpdate::new("new", Some(a), None), | |
| 758 | + ] | |
| 759 | + ); | |
| 760 | + let refs = store.refs().unwrap(); | |
| 761 | + assert_eq!(refs.get("main"), Some(a)); | |
| 762 | + assert_eq!(refs.get("old"), Some(b)); | |
| 763 | + assert_eq!(refs.get("new"), None); | |
| 764 | + | |
| 765 | + // An operation that changed nothing is still an operation. | |
| 766 | + store | |
| 767 | + .transact("agent", "nothing", |_| Ok::<_, Infallible>(Vec::new())) | |
| 768 | + .unwrap(); | |
| 769 | + assert_eq!(store.undo_last("fixer").unwrap().undoes, Some(4)); | |
| 770 | + assert_eq!(store.undo_last("fixer").unwrap().undoes, Some(1)); | |
| 771 | + assert!(store.refs().unwrap().is_empty()); | |
| 772 | + assert!(matches!( | |
| 773 | + store.undo_last("fixer"), | |
| 774 | + Err(Error::NothingToUndo) | |
| 775 | + )); | |
| 776 | + let log = store.log(usize::MAX).unwrap(); | |
| 777 | + assert_eq!( | |
| 778 | + log.iter().map(|op| (op.seq, op.undoes)).collect::<Vec<_>>(), | |
| 779 | + vec![ | |
| 780 | + (6, Some(1)), | |
| 781 | + (5, Some(4)), | |
| 782 | + (4, None), | |
| 783 | + (3, Some(2)), | |
| 784 | + (2, None), | |
| 785 | + (1, None) | |
| 786 | + ] | |
| 787 | + ); | |
| 788 | + assert_clean(&store); | |
| 789 | +} | |
| 790 | + | |
| 791 | +#[test] | |
| 792 | +fn checkpoints_are_written_and_survive_damage() { | |
| 793 | + let (_dir, store) = new_store(options(256 << 20, 3)); | |
| 794 | + let root = store.root().to_path_buf(); | |
| 795 | + let ids: Vec<ObjectId> = (0..10u8) | |
| 796 | + .map(|n| store.put(Kind::Changeset, &[n]).unwrap()) | |
| 797 | + .collect(); | |
| 798 | + for (n, id) in ids.iter().enumerate() { | |
| 799 | + store | |
| 800 | + .transact("agent", "step", |refs| { | |
| 801 | + Ok::<_, Infallible>(vec![ | |
| 802 | + RefUpdate::new("main", refs.get("main"), Some(*id)), | |
| 803 | + RefUpdate::new(format!("tag/{n}"), None, Some(*id)), | |
| 804 | + ]) | |
| 805 | + }) | |
| 806 | + .unwrap(); | |
| 807 | + } | |
| 808 | + let mut checkpoints: Vec<String> = fs::read_dir(root.join("oplog")) | |
| 809 | + .unwrap() | |
| 810 | + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) | |
| 811 | + .filter(|name| name.starts_with("ckpt.")) | |
| 812 | + .collect(); | |
| 813 | + checkpoints.sort(); | |
| 814 | + assert_eq!(checkpoints, vec!["ckpt.6", "ckpt.9"]); | |
| 815 | + let report = assert_clean(&store); | |
| 816 | + assert_eq!(report.checkpoints, 2); | |
| 817 | + drop(store); | |
| 818 | + | |
| 819 | + // A fresh handle starts from the newest checkpoint. | |
| 820 | + let store = Store::open(&root, options(256 << 20, 3)).unwrap(); | |
| 821 | + let refs = store.refs().unwrap(); | |
| 822 | + assert_eq!(refs.seq(), 10); | |
| 823 | + assert_eq!(refs.get("main"), Some(ids[9])); | |
| 824 | + assert_eq!(refs.len(), 11); | |
| 825 | + drop(store); | |
| 826 | + | |
| 827 | + // A damaged checkpoint is skipped, and reported. | |
| 828 | + flip_byte(&root.join("oplog/ckpt.9"), 40); | |
| 829 | + let store = Store::open(&root, options(256 << 20, 3)).unwrap(); | |
| 830 | + let refs = store.refs().unwrap(); | |
| 831 | + assert_eq!(refs.seq(), 10); | |
| 832 | + assert_eq!(refs.get("tag/0"), Some(ids[0])); | |
| 833 | + let report = store.fsck().unwrap(); | |
| 834 | + assert!( | |
| 835 | + matches!(report.problems.as_slice(), [Problem::BadCheckpoint { .. }]), | |
| 836 | + "{:#?}", | |
| 837 | + report.problems | |
| 838 | + ); | |
| 839 | +} | |
| 840 | + | |
| 841 | +#[test] | |
| 842 | +fn a_torn_log_tail_is_ignored_then_cut_off() { | |
| 843 | + let (_dir, store) = new_store(Options::default()); | |
| 844 | + let root = store.root().to_path_buf(); | |
| 845 | + let a = store.put(Kind::Changeset, b"a").unwrap(); | |
| 846 | + let b = store.put(Kind::Changeset, b"b").unwrap(); | |
| 847 | + store | |
| 848 | + .transact("agent", "set a", |_| { | |
| 849 | + Ok::<_, Infallible>(set("main", None, Some(a))) | |
| 850 | + }) | |
| 851 | + .unwrap(); | |
| 852 | + let log = root.join("oplog/log"); | |
| 853 | + let good_len = fs::metadata(&log).unwrap().len(); | |
| 854 | + // The first half of a second record, as a crash mid-append leaves it. | |
| 855 | + store | |
| 856 | + .transact("agent", "set b", |_| { | |
| 857 | + Ok::<_, Infallible>(set("main", Some(a), Some(b))) | |
| 858 | + }) | |
| 859 | + .unwrap(); | |
| 860 | + drop(store); | |
| 861 | + let bytes = fs::read(&log).unwrap(); | |
| 862 | + let cut = good_len as usize + (bytes.len() - good_len as usize) / 2; | |
| 863 | + fs::write(&log, &bytes[..cut]).unwrap(); | |
| 864 | + | |
| 865 | + let store = Store::open(&root, Options::default()).unwrap(); | |
| 866 | + assert_eq!(store.refs().unwrap().get("main"), Some(a)); | |
| 867 | + let report = assert_clean(&store); | |
| 868 | + assert_eq!(report.torn_log_bytes, (cut as u64) - good_len); | |
| 869 | + assert_eq!(report.operations, 1); | |
| 870 | + // The next writer cuts the torn bytes off and appends in their place. | |
| 871 | + store | |
| 872 | + .transact("agent", "set b again", |refs| { | |
| 873 | + Ok::<_, Infallible>(set("main", refs.get("main"), Some(b))) | |
| 874 | + }) | |
| 875 | + .unwrap(); | |
| 876 | + let report = assert_clean(&store); | |
| 877 | + assert_eq!(report.torn_log_bytes, 0); | |
| 878 | + assert_eq!(report.operations, 2); | |
| 879 | + assert_eq!(store.log(10).unwrap()[0].seq, 2); | |
| 880 | +} | |
| 881 | + | |
| 882 | +#[test] | |
| 883 | +fn damage_in_the_middle_of_the_log_is_never_cut_off() { | |
| 884 | + let (_dir, store) = new_store(Options::default()); | |
| 885 | + let root = store.root().to_path_buf(); | |
| 886 | + let ids: Vec<ObjectId> = (0..3u8) | |
| 887 | + .map(|n| store.put(Kind::Changeset, &[n]).unwrap()) | |
| 888 | + .collect(); | |
| 889 | + for id in &ids { | |
| 890 | + store | |
| 891 | + .transact("agent", "advance", |refs| { | |
| 892 | + Ok::<_, Infallible>(set("main", refs.get("main"), Some(*id))) | |
| 893 | + }) | |
| 894 | + .unwrap(); | |
| 895 | + } | |
| 896 | + drop(store); | |
| 897 | + let log = root.join("oplog/log"); | |
| 898 | + flip_byte(&log, 20); | |
| 899 | + let before = fs::read(&log).unwrap(); | |
| 900 | + | |
| 901 | + let store = Store::open(&root, options(256 << 20, 0)).unwrap(); | |
| 902 | + assert!(matches!(store.refs(), Err(Error::Corrupt { .. }))); | |
| 903 | + let err = store | |
| 904 | + .transact("agent", "advance", |_| Ok::<_, Infallible>(Vec::new())) | |
| 905 | + .unwrap_err(); | |
| 906 | + assert!( | |
| 907 | + matches!(err, TransactError::Store(Error::Corrupt { .. })), | |
| 908 | + "{err}" | |
| 909 | + ); | |
| 910 | + assert_eq!(fs::read(&log).unwrap(), before); | |
| 911 | + let report = store.fsck().unwrap(); | |
| 912 | + assert!( | |
| 913 | + report | |
| 914 | + .problems | |
| 915 | + .iter() | |
| 916 | + .any(|p| matches!(p, Problem::BadOperation { offset: 0, .. })), | |
| 917 | + "{:#?}", | |
| 918 | + report.problems | |
| 919 | + ); | |
| 920 | +} | |
| 921 | + | |
| 922 | +#[test] | |
| 923 | +fn fsck_reports_refs_to_missing_objects() { | |
| 924 | + let (_dir, store) = new_store(Options::default()); | |
| 925 | + let root = store.root().to_path_buf(); | |
| 926 | + let id = store.put(Kind::Changeset, b"soon gone").unwrap(); | |
| 927 | + store | |
| 928 | + .transact("agent", "set", |_| { | |
| 929 | + Ok::<_, Infallible>(set("main", None, Some(id))) | |
| 930 | + }) | |
| 931 | + .unwrap(); | |
| 932 | + drop(store); | |
| 933 | + for entry in fs::read_dir(root.join("seg")).unwrap() { | |
| 934 | + fs::remove_file(entry.unwrap().path()).unwrap(); | |
| 935 | + } | |
| 936 | + let store = Store::open(&root, Options::default()).unwrap(); | |
| 937 | + let report = store.fsck().unwrap(); | |
| 938 | + assert_eq!( | |
| 939 | + report.problems, | |
| 940 | + vec![Problem::MissingObject { | |
| 941 | + name: "main".to_owned(), | |
| 942 | + id | |
| 943 | + }] | |
| 944 | + ); | |
| 945 | +} | |
| 946 | + | |
| 947 | +#[test] | |
| 948 | +fn full_durability_works_the_same() { | |
| 949 | + let options = Options { | |
| 950 | + durability: Durability::Full, | |
| 951 | + segment_size: 2048, | |
| 952 | + checkpoint_interval: 2, | |
| 953 | + }; | |
| 954 | + let (_dir, store) = new_store(options.clone()); | |
| 955 | + let root = store.root().to_path_buf(); | |
| 956 | + let objects = payloads(10); | |
| 957 | + let mut last = None; | |
| 958 | + for (kind, payload) in &objects { | |
| 959 | + let id = store.put(*kind, payload).unwrap(); | |
| 960 | + store.sync().unwrap(); | |
| 961 | + store | |
| 962 | + .transact("agent", "advance", |refs| { | |
| 963 | + Ok::<_, Infallible>(set("main", refs.get("main"), Some(id))) | |
| 964 | + }) | |
| 965 | + .unwrap(); | |
| 966 | + last = Some(id); | |
| 967 | + } | |
| 968 | + drop(store); | |
| 969 | + let store = Store::open(&root, options).unwrap(); | |
| 970 | + assert_eq!(store.refs().unwrap().get("main"), last); | |
| 971 | + let report = assert_clean(&store); | |
| 972 | + assert_eq!(report.operations, 10); | |
| 973 | +} | |
| 974 | + | |
| 975 | +#[test] | |
| 976 | +fn limits_are_enforced() { | |
| 977 | + let (_dir, store) = new_store(Options::default()); | |
| 978 | + let err = store | |
| 979 | + .transact(&"a".repeat(2000), "x", |_| Ok::<_, Infallible>(Vec::new())) | |
| 980 | + .unwrap_err(); | |
| 981 | + assert!(matches!(err, TransactError::Store(Error::TooLong { .. }))); | |
| 982 | + let err = store | |
| 983 | + .transact( | |
| 984 | + "a", | |
| 985 | + &"d".repeat(70_000), | |
| 986 | + |_| Ok::<_, Infallible>(Vec::new()), | |
| 987 | + ) | |
| 988 | + .unwrap_err(); | |
| 989 | + assert!(matches!(err, TransactError::Store(Error::TooLong { .. }))); | |
| 990 | + assert_eq!(store.refs().unwrap().seq(), 0); | |
| 991 | +} |