| 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::{CHUNKED_MIN, 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 | /// Stores a variant of one of the objects stored so far, picked by |
| 28 | /// this number, saying it is similar to that object, or to one that is |
| 29 | /// not in the store. |
| 30 | PutSimilar { |
| 31 | pick: usize, |
| 32 | kind: Kind, |
| 33 | edit: Edit, |
| 34 | absent_hint: bool, |
| 35 | }, |
| 36 | /// Reads one of the objects stored so far, picked by this number. |
| 37 | Get(usize), |
| 38 | /// Reads an object that may not exist. |
| 39 | Probe(Kind, Vec<u8>), |
| 40 | Sync, |
| 41 | Reopen, |
| 42 | } |
| 43 | |
| 44 | /// How a variant differs from the object it is made from. |
| 45 | #[derive(Clone, Debug)] |
| 46 | enum Edit { |
| 47 | /// These bytes replace those at a position, picked by the number. |
| 48 | Replace(usize, Vec<u8>), |
| 49 | /// These bytes go in at a position. |
| 50 | Insert(usize, Vec<u8>), |
| 51 | /// These bytes go at the end. |
| 52 | Append(Vec<u8>), |
| 53 | } |
| 54 | |
| 55 | impl Edit { |
| 56 | fn apply(&self, payload: &[u8]) -> Vec<u8> { |
| 57 | let mut out = payload.to_vec(); |
| 58 | match self { |
| 59 | Edit::Replace(at, bytes) if !out.is_empty() => { |
| 60 | let at = at % out.len(); |
| 61 | let end = (at + bytes.len()).min(out.len()); |
| 62 | out[at..end].copy_from_slice(&bytes[..end - at]); |
| 63 | } |
| 64 | Edit::Insert(at, bytes) => { |
| 65 | let at = at % (out.len() + 1); |
| 66 | out.splice(at..at, bytes.iter().copied()); |
| 67 | } |
| 68 | Edit::Replace(_, bytes) | Edit::Append(bytes) => out.extend_from_slice(bytes), |
| 69 | } |
| 70 | out |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | fn edit() -> impl Strategy<Value = Edit> { |
| 75 | let bytes = prop::collection::vec(any::<u8>(), 1..40); |
| 76 | prop_oneof![ |
| 77 | (any::<usize>(), bytes.clone()).prop_map(|(at, b)| Edit::Replace(at, b)), |
| 78 | (any::<usize>(), bytes.clone()).prop_map(|(at, b)| Edit::Insert(at, b)), |
| 79 | bytes.prop_map(Edit::Append), |
| 80 | ] |
| 81 | } |
| 82 | |
| 83 | fn kind() -> impl Strategy<Value = Kind> { |
| 84 | prop::sample::select(Kind::ALL.to_vec()) |
| 85 | } |
| 86 | |
| 87 | fn payload() -> impl Strategy<Value = Vec<u8>> { |
| 88 | prop_oneof![ |
| 89 | // Small: stored raw. |
| 90 | prop::collection::vec(any::<u8>(), 0..80), |
| 91 | // Repetitive: compressed. |
| 92 | (prop::collection::vec(any::<u8>(), 1..12), 8usize..400) |
| 93 | .prop_map(|(unit, times)| unit.repeat(times)), |
| 94 | // Noise: stored raw because it does not compress. |
| 95 | prop::collection::vec(any::<u8>(), 65..1500), |
| 96 | ] |
| 97 | } |
| 98 | |
| 99 | fn object_op() -> impl Strategy<Value = ObjectOp> { |
| 100 | prop_oneof![ |
| 101 | 8 => (kind(), payload()).prop_map(|(kind, payload)| ObjectOp::Put(kind, payload)), |
| 102 | 6 => (any::<usize>(), kind(), edit(), prop::bool::weighted(0.1)).prop_map( |
| 103 | |(pick, kind, edit, absent_hint)| ObjectOp::PutSimilar { pick, kind, edit, absent_hint } |
| 104 | ), |
| 105 | 4 => any::<usize>().prop_map(ObjectOp::Get), |
| 106 | 1 => (kind(), payload()).prop_map(|(kind, payload)| ObjectOp::Probe(kind, payload)), |
| 107 | 1 => Just(ObjectOp::Sync), |
| 108 | 1 => Just(ObjectOp::Reopen), |
| 109 | ] |
| 110 | } |
| 111 | |
| 112 | proptest! { |
| 113 | #![proptest_config(ProptestConfig::with_cases(cases()))] |
| 114 | |
| 115 | /// Objects behave as in memory, across reopening and sealing, whether |
| 116 | /// they are stored whole or as deltas: against the object named |
| 117 | /// similar, or against its base when that object is a delta itself. |
| 118 | #[test] |
| 119 | fn objects_behave_like_memory( |
| 120 | ops in prop::collection::vec(object_op(), 1..80), |
| 121 | segment_size in 64u64..6000, |
| 122 | ) { |
| 123 | let dir = tempfile::tempdir().unwrap(); |
| 124 | let options = Options { segment_size, ..Options::default() }; |
| 125 | let mut store = Store::init(dir.path(), options.clone()).unwrap(); |
| 126 | let model = MemoryObjects::new(); |
| 127 | let mut stored = Vec::new(); |
| 128 | for op in ops { |
| 129 | match op { |
| 130 | ObjectOp::Put(kind, payload) => { |
| 131 | let id = store.put(kind, &payload).unwrap(); |
| 132 | prop_assert_eq!(id, model.put(kind, &payload).unwrap()); |
| 133 | stored.push(id); |
| 134 | } |
| 135 | ObjectOp::PutSimilar { pick, kind, edit, absent_hint } => { |
| 136 | if stored.is_empty() { |
| 137 | continue; |
| 138 | } |
| 139 | let similar = stored[pick % stored.len()]; |
| 140 | let (_, original) = model.get(&similar).unwrap().expect("stored in the model"); |
| 141 | let payload = edit.apply(&original); |
| 142 | let hint = if absent_hint { |
| 143 | ObjectId::hash(Kind::Blob, &payload) |
| 144 | } else { |
| 145 | similar |
| 146 | }; |
| 147 | let id = store.put_similar(kind, &payload, &hint).unwrap(); |
| 148 | prop_assert_eq!(id, model.put(kind, &payload).unwrap()); |
| 149 | prop_assert_eq!(store.get(&id).unwrap(), model.get(&id).unwrap()); |
| 150 | stored.push(id); |
| 151 | } |
| 152 | ObjectOp::Get(pick) => { |
| 153 | if !stored.is_empty() { |
| 154 | let id = stored[pick % stored.len()]; |
| 155 | prop_assert_eq!(store.get(&id).unwrap(), model.get(&id).unwrap()); |
| 156 | prop_assert_eq!(store.stat(&id).unwrap(), model.stat(&id).unwrap()); |
| 157 | } |
| 158 | } |
| 159 | ObjectOp::Probe(kind, payload) => { |
| 160 | let id = ObjectId::hash(kind, &payload); |
| 161 | prop_assert_eq!(store.get(&id).unwrap(), model.get(&id).unwrap()); |
| 162 | prop_assert_eq!(store.contains(&id).unwrap(), model.contains(&id).unwrap()); |
| 163 | prop_assert_eq!(store.stat(&id).unwrap(), model.stat(&id).unwrap()); |
| 164 | } |
| 165 | ObjectOp::Sync => store.sync().unwrap(), |
| 166 | ObjectOp::Reopen => { |
| 167 | drop(store); |
| 168 | store = Store::open(dir.path(), options.clone()).unwrap(); |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | store.sync().unwrap(); |
| 173 | drop(store); |
| 174 | let store = Store::open(dir.path(), options).unwrap(); |
| 175 | for id in model.ids() { |
| 176 | prop_assert_eq!(store.get(&id).unwrap(), model.get(&id).unwrap()); |
| 177 | prop_assert_eq!(store.stat(&id).unwrap(), model.stat(&id).unwrap()); |
| 178 | } |
| 179 | let report = store.fsck().unwrap(); |
| 180 | prop_assert!(report.is_clean(), "{:#?}", report.problems); |
| 181 | prop_assert_eq!(report.objects, model.len() as u64); |
| 182 | // One handle at a time never writes an object twice. |
| 183 | prop_assert_eq!(report.records, model.len() as u64); |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | /// Cases for large blobs: each stores several megabytes. |
| 188 | fn large_cases() -> u32 { |
| 189 | if std::env::var_os("BRAID_STRESS").is_some_and(|value| value != "0") { |
| 190 | 48 |
| 191 | } else { |
| 192 | 4 |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | /// Bytes that do not compress. |
| 197 | fn noise(seed: u64, len: usize) -> Vec<u8> { |
| 198 | let mut state = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1; |
| 199 | let mut out = Vec::with_capacity(len + 8); |
| 200 | while out.len() < len { |
| 201 | state ^= state << 13; |
| 202 | state ^= state >> 7; |
| 203 | state ^= state << 17; |
| 204 | out.extend_from_slice(&state.to_le_bytes()); |
| 205 | } |
| 206 | out.truncate(len); |
| 207 | out |
| 208 | } |
| 209 | |
| 210 | /// How one version of a large blob is stored. |
| 211 | #[derive(Clone, Debug)] |
| 212 | struct LargeVersion { |
| 213 | edit: Edit, |
| 214 | /// Through `put_blob_from` rather than `put`. |
| 215 | streamed: bool, |
| 216 | /// With the previous version as a hint. |
| 217 | similar: bool, |
| 218 | reopen: bool, |
| 219 | } |
| 220 | |
| 221 | fn large_version() -> impl Strategy<Value = LargeVersion> { |
| 222 | ( |
| 223 | edit(), |
| 224 | any::<bool>(), |
| 225 | any::<bool>(), |
| 226 | prop::bool::weighted(0.3), |
| 227 | ) |
| 228 | .prop_map(|(edit, streamed, similar, reopen)| LargeVersion { |
| 229 | edit, |
| 230 | streamed, |
| 231 | similar, |
| 232 | reopen, |
| 233 | }) |
| 234 | } |
| 235 | |
| 236 | proptest! { |
| 237 | #![proptest_config(ProptestConfig::with_cases(large_cases()))] |
| 238 | |
| 239 | /// Versions of a blob around and above 4 MiB, where storage switches to |
| 240 | /// chunks, behave as in memory: stored whole, as deltas or in chunks, |
| 241 | /// streamed or not, across reopening. |
| 242 | #[test] |
| 243 | fn large_blobs_behave_like_memory( |
| 244 | seed in any::<u64>(), |
| 245 | size in (CHUNKED_MIN as usize - 3000)..(CHUNKED_MIN as usize + (2 << 20)), |
| 246 | versions in prop::collection::vec(large_version(), 1..5), |
| 247 | ) { |
| 248 | let dir = tempfile::tempdir().unwrap(); |
| 249 | let mut store = Store::init(dir.path(), Options::default()).unwrap(); |
| 250 | let model = MemoryObjects::new(); |
| 251 | let mut payload = noise(seed, size); |
| 252 | let mut previous = None; |
| 253 | for version in versions { |
| 254 | payload = version.edit.apply(&payload); |
| 255 | let id = match (version.streamed, previous) { |
| 256 | (true, _) => { |
| 257 | let (id, len) = store |
| 258 | .put_blob_from(&payload[..], Some(payload.len() as u64)) |
| 259 | .unwrap(); |
| 260 | prop_assert_eq!(len, payload.len() as u64); |
| 261 | id |
| 262 | } |
| 263 | (false, Some(previous)) if version.similar => { |
| 264 | store.put_similar(Kind::Blob, &payload, &previous).unwrap() |
| 265 | } |
| 266 | (false, _) => store.put(Kind::Blob, &payload).unwrap(), |
| 267 | }; |
| 268 | prop_assert_eq!(id, model.put(Kind::Blob, &payload).unwrap()); |
| 269 | if version.reopen { |
| 270 | store.sync().unwrap(); |
| 271 | drop(store); |
| 272 | store = Store::open(dir.path(), Options::default()).unwrap(); |
| 273 | } |
| 274 | prop_assert!(store.get(&id).unwrap() == model.get(&id).unwrap()); |
| 275 | prop_assert_eq!(store.stat(&id).unwrap(), model.stat(&id).unwrap()); |
| 276 | previous = Some(id); |
| 277 | } |
| 278 | store.sync().unwrap(); |
| 279 | drop(store); |
| 280 | let store = Store::open(dir.path(), Options::default()).unwrap(); |
| 281 | for id in model.ids() { |
| 282 | let mut out = Vec::new(); |
| 283 | prop_assert_eq!(store.read_to(&id, &mut out).unwrap(), model.stat(&id).unwrap()); |
| 284 | let (_, expected) = model.get(&id).unwrap().expect("stored in the model"); |
| 285 | prop_assert!(out == expected); |
| 286 | } |
| 287 | let report = store.fsck().unwrap(); |
| 288 | prop_assert!(report.is_clean(), "{:#?}", report.problems); |
| 289 | // Chunks are objects of their own. |
| 290 | prop_assert!(report.objects >= model.len() as u64); |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | #[derive(Clone, Debug)] |
| 295 | enum LogOp { |
| 296 | /// Points ref `name` at value `value`, expecting what the model holds, |
| 297 | /// or a value it cannot hold if `stale`. |
| 298 | Set { |
| 299 | name: u8, |
| 300 | value: u8, |
| 301 | stale: bool, |
| 302 | }, |
| 303 | Delete { |
| 304 | name: u8, |
| 305 | }, |
| 306 | Undo, |
| 307 | Reopen, |
| 308 | } |
| 309 | |
| 310 | fn log_op() -> impl Strategy<Value = LogOp> { |
| 311 | prop_oneof![ |
| 312 | 6 => (0u8..4, 0u8..6, prop::bool::weighted(0.15)) |
| 313 | .prop_map(|(name, value, stale)| LogOp::Set { name, value, stale }), |
| 314 | 2 => (0u8..4).prop_map(|name| LogOp::Delete { name }), |
| 315 | 2 => Just(LogOp::Undo), |
| 316 | 1 => Just(LogOp::Reopen), |
| 317 | ] |
| 318 | } |
| 319 | |
| 320 | /// The op log as a map of refs and a list of operations. |
| 321 | #[derive(Default)] |
| 322 | struct Model { |
| 323 | refs: BTreeMap<String, ObjectId>, |
| 324 | /// Index `i` holds operation `i + 1`: what it undid, and its updates. |
| 325 | ops: Vec<(Option<u64>, Vec<RefUpdate>)>, |
| 326 | } |
| 327 | |
| 328 | impl Model { |
| 329 | fn apply(&mut self, undoes: Option<u64>, updates: Vec<RefUpdate>) { |
| 330 | for update in &updates { |
| 331 | match update.new { |
| 332 | Some(id) => self.refs.insert(update.name.clone(), id), |
| 333 | None => self.refs.remove(&update.name), |
| 334 | }; |
| 335 | } |
| 336 | self.ops.push((undoes, updates)); |
| 337 | } |
| 338 | |
| 339 | /// The operation an undo reverts: the newest that is neither an undo |
| 340 | /// nor undone. |
| 341 | fn undo_target(&self) -> Option<u64> { |
| 342 | let mut undone = HashSet::new(); |
| 343 | for (index, (undoes, _)) in self.ops.iter().enumerate().rev() { |
| 344 | let seq = index as u64 + 1; |
| 345 | if let Some(target) = undoes { |
| 346 | undone.insert(*target); |
| 347 | } else if !undone.contains(&seq) { |
| 348 | return Some(seq); |
| 349 | } |
| 350 | } |
| 351 | None |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | fn value(n: u8) -> ObjectId { |
| 356 | ObjectId::hash(Kind::Changeset, &[n]) |
| 357 | } |
| 358 | |
| 359 | proptest! { |
| 360 | #![proptest_config(ProptestConfig::with_cases(cases()))] |
| 361 | |
| 362 | /// The op log behaves like the model, across reopening and checkpoints. |
| 363 | #[test] |
| 364 | fn op_log_behaves_like_a_model( |
| 365 | ops in prop::collection::vec(log_op(), 1..40), |
| 366 | checkpoint_interval in 0u64..5, |
| 367 | ) { |
| 368 | let dir = tempfile::tempdir().unwrap(); |
| 369 | let options = Options { checkpoint_interval, ..Options::default() }; |
| 370 | let mut store = Store::init(dir.path(), options.clone()).unwrap(); |
| 371 | for n in 0..6 { |
| 372 | store.put(Kind::Changeset, &[n]).unwrap(); |
| 373 | } |
| 374 | store.sync().unwrap(); |
| 375 | let mut model = Model::default(); |
| 376 | |
| 377 | for op in ops { |
| 378 | match op { |
| 379 | LogOp::Set { name, value: n, stale } => { |
| 380 | let name = format!("ref/{name}"); |
| 381 | let current = model.refs.get(&name).copied(); |
| 382 | let old = if stale { Some(value(200)) } else { current }; |
| 383 | let update = RefUpdate::new(name, old, Some(value(n))); |
| 384 | let result = store.transact("prop", "set", |_| { |
| 385 | Ok::<_, Infallible>(vec![update.clone()]) |
| 386 | }); |
| 387 | if stale { |
| 388 | prop_assert!(result.unwrap_err().is_conflict()); |
| 389 | } else { |
| 390 | let op = result.unwrap(); |
| 391 | prop_assert_eq!(op.seq, model.ops.len() as u64 + 1); |
| 392 | model.apply(None, vec![update]); |
| 393 | } |
| 394 | } |
| 395 | LogOp::Delete { name } => { |
| 396 | let name = format!("ref/{name}"); |
| 397 | let update = RefUpdate::new(name.clone(), model.refs.get(&name).copied(), None); |
| 398 | store |
| 399 | .transact("prop", "delete", |_| Ok::<_, Infallible>(vec![update.clone()])) |
| 400 | .unwrap(); |
| 401 | model.apply(None, vec![update]); |
| 402 | } |
| 403 | LogOp::Undo => match model.undo_target() { |
| 404 | None => prop_assert!(matches!(store.undo_last("prop"), Err(Error::NothingToUndo))), |
| 405 | Some(target) => { |
| 406 | let op = store.undo_last("prop").unwrap(); |
| 407 | prop_assert_eq!(op.undoes, Some(target)); |
| 408 | let reverted: Vec<RefUpdate> = model.ops[target as usize - 1] |
| 409 | .1 |
| 410 | .iter() |
| 411 | .map(|update| RefUpdate::new(update.name.clone(), update.new, update.old)) |
| 412 | .collect(); |
| 413 | prop_assert_eq!(&op.updates, &reverted); |
| 414 | model.apply(Some(target), reverted); |
| 415 | } |
| 416 | }, |
| 417 | LogOp::Reopen => { |
| 418 | drop(store); |
| 419 | store = Store::open(dir.path(), options.clone()).unwrap(); |
| 420 | } |
| 421 | } |
| 422 | let refs = store.refs().unwrap(); |
| 423 | prop_assert_eq!(refs.as_map(), &model.refs); |
| 424 | prop_assert_eq!(refs.seq(), model.ops.len() as u64); |
| 425 | } |
| 426 | |
| 427 | drop(store); |
| 428 | let store = Store::open(dir.path(), options).unwrap(); |
| 429 | let log = store.log(usize::MAX).unwrap(); |
| 430 | prop_assert_eq!(log.len(), model.ops.len()); |
| 431 | for (op, seq) in log.iter().zip((1..=model.ops.len() as u64).rev()) { |
| 432 | prop_assert_eq!(op.seq, seq); |
| 433 | let (undoes, updates) = &model.ops[seq as usize - 1]; |
| 434 | prop_assert_eq!(&op.undoes, undoes); |
| 435 | prop_assert_eq!(&op.updates, updates); |
| 436 | } |
| 437 | let report = store.fsck().unwrap(); |
| 438 | prop_assert!(report.is_clean(), "{:#?}", report.problems); |
| 439 | prop_assert_eq!(report.operations, model.ops.len() as u64); |
| 440 | } |
| 441 | } |