| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Updating a directory one path at a time gives exactly the nodes of |
| 5 | //! building it again from scratch, and a small edit reads and writes only a |
| 6 | //! few nodes, however large the directory. |
| 7 | //! |
| 8 | //! `BRAID_TREE_CASES=<n>` runs `n` random cases instead of the default |
| 9 | //! number, for long runs. |
| 10 | |
| 11 | use std::cell::Cell; |
| 12 | use std::collections::{BTreeMap, HashMap, HashSet}; |
| 13 | |
| 14 | use braid_format::tree::{MAX_FLAT_ENTRIES, MAX_NODE_ENTRIES}; |
| 15 | use braid_format::{ |
| 16 | Entry, EntryEdit, EntryKind, GitId, Kind, Node, NodeCache, ObjectId, TreeError, Updated, |
| 17 | build_directory, find_entry, read_directory, update_directory, validate_name, |
| 18 | }; |
| 19 | use proptest::prelude::*; |
| 20 | use proptest::test_runner::TestCaseError; |
| 21 | |
| 22 | /// Cases of the random test; `BRAID_TREE_CASES` sets another number. |
| 23 | const DEFAULT_CASES: u32 = 24; |
| 24 | |
| 25 | fn cases() -> u32 { |
| 26 | match std::env::var("BRAID_TREE_CASES") { |
| 27 | Ok(value) => value |
| 28 | .trim() |
| 29 | .parse() |
| 30 | .unwrap_or_else(|_| panic!("BRAID_TREE_CASES must be a number, not {value:?}")), |
| 31 | Err(_) => DEFAULT_CASES, |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | type Entries = BTreeMap<Vec<u8>, EntryKind>; |
| 36 | |
| 37 | /// Nodes by id, as a store holds them. |
| 38 | type Store = HashMap<ObjectId, Vec<u8>>; |
| 39 | |
| 40 | fn kind(salt: u64, variant: u64) -> EntryKind { |
| 41 | let blob = ObjectId::hash(Kind::Blob, &salt.to_le_bytes()); |
| 42 | match variant % 11 { |
| 43 | 0 => EntryKind::Executable { blob, size: salt }, |
| 44 | 1 => EntryKind::Symlink { blob, size: salt }, |
| 45 | 2 => EntryKind::Tree { tree: blob }, |
| 46 | 3 => EntryKind::Gitlink { |
| 47 | commit: GitId::Sha1([salt as u8; 20]), |
| 48 | }, |
| 49 | _ => EntryKind::File { blob, size: salt }, |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | /// A position among the entries as they are when it is used, as a fraction |
| 54 | /// of their number. |
| 55 | #[derive(Clone, Copy, Debug)] |
| 56 | struct Pos(u64); |
| 57 | |
| 58 | impl Pos { |
| 59 | fn of(self, len: usize) -> usize { |
| 60 | ((len as u128 * u128::from(self.0)) >> 64) as usize |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | fn pos() -> impl Strategy<Value = Pos> { |
| 65 | any::<u64>().prop_map(Pos) |
| 66 | } |
| 67 | |
| 68 | /// A small, deterministic generator, so that a case is described by a few |
| 69 | /// numbers that proptest can shrink. |
| 70 | fn mix(seed: u64, i: u64) -> u64 { |
| 71 | let mut x = seed ^ i.wrapping_mul(0x9e37_79b9_7f4a_7c15); |
| 72 | x ^= x >> 31; |
| 73 | x = x.wrapping_mul(0xbf58_476d_1ce4_e5b9); |
| 74 | x ^= x >> 29; |
| 75 | x |
| 76 | } |
| 77 | |
| 78 | /// The `i`th name of a directory in one of several styles: numbered like the |
| 79 | /// files of a generated directory, random-looking, sharing long prefixes, or |
| 80 | /// of mixed lengths and bytes, Unicode included. |
| 81 | fn name(style: u8, seed: u64, i: u64) -> Vec<u8> { |
| 82 | let r = mix(seed, i); |
| 83 | match style % 4 { |
| 84 | 0 => format!("f{i:06}.txt").into_bytes(), |
| 85 | 1 => format!("{r:016x}").into_bytes(), |
| 86 | 2 => format!("component-{}-{i:07}", r % 5).into_bytes(), |
| 87 | _ => { |
| 88 | const BYTES: &[u8] = b"abcXYZ019._- \xc3\xa9"; |
| 89 | let len = 1 + (r % 13) as usize; |
| 90 | let mut name: Vec<u8> = (0..len) |
| 91 | .map(|k| BYTES[(mix(r, k as u64) % BYTES.len() as u64) as usize]) |
| 92 | .collect(); |
| 93 | name.extend_from_slice(format!("{i}").as_bytes()); |
| 94 | // Keep it valid UTF-8 when it holds half of a two-byte letter. |
| 95 | String::from_utf8_lossy(&name).into_owned().into_bytes() |
| 96 | } |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | /// A directory of `count` distinct valid names. |
| 101 | fn directory(count: usize, style: u8, seed: u64) -> Entries { |
| 102 | let mut entries = Entries::new(); |
| 103 | let mut i = 0u64; |
| 104 | while entries.len() < count { |
| 105 | let name = name(style, seed, i); |
| 106 | if validate_name(&name).is_ok() { |
| 107 | entries.insert(name, kind(mix(seed, i), mix(seed, i + 1))); |
| 108 | } |
| 109 | i += 1; |
| 110 | } |
| 111 | entries |
| 112 | } |
| 113 | |
| 114 | /// One step of a batch of edits, applied to the entries as they are by then. |
| 115 | #[derive(Clone, Debug)] |
| 116 | enum Op { |
| 117 | /// New content for the entry at this position. |
| 118 | Modify(Pos), |
| 119 | /// Remove the entry at this position. |
| 120 | Delete(Pos), |
| 121 | /// A new name right after the entry at this position. |
| 122 | AddAfter(Pos), |
| 123 | /// Remove a run of neighbours, from this position. |
| 124 | DeleteRun(Pos, usize), |
| 125 | /// New content for a run of neighbours. |
| 126 | ModifyRun(Pos, usize), |
| 127 | /// New names, one after the other, right after this position. |
| 128 | AddRun(Pos, usize), |
| 129 | /// The content of one entry moves to a new name next to another. |
| 130 | Rename(Pos, Pos), |
| 131 | /// Remove, or change, the first or last entries. |
| 132 | DeleteFirst(usize), |
| 133 | DeleteLast(usize), |
| 134 | ModifyFirst(usize), |
| 135 | ModifyLast(usize), |
| 136 | /// New names before every other, or after. |
| 137 | AddFirst(usize), |
| 138 | AddLast(usize), |
| 139 | } |
| 140 | |
| 141 | fn op() -> impl Strategy<Value = Op> { |
| 142 | prop_oneof![ |
| 143 | 3 => pos().prop_map(Op::Modify), |
| 144 | 3 => pos().prop_map(Op::Delete), |
| 145 | 3 => pos().prop_map(Op::AddAfter), |
| 146 | 1 => (pos(), 1usize..700).prop_map(|(i, n)| Op::DeleteRun(i, n)), |
| 147 | 1 => (pos(), 1usize..700).prop_map(|(i, n)| Op::ModifyRun(i, n)), |
| 148 | 1 => (pos(), 1usize..700).prop_map(|(i, n)| Op::AddRun(i, n)), |
| 149 | 2 => (pos(), pos()).prop_map(|(a, b)| Op::Rename(a, b)), |
| 150 | 1 => (1usize..40).prop_map(Op::DeleteFirst), |
| 151 | 1 => (1usize..40).prop_map(Op::DeleteLast), |
| 152 | 1 => (1usize..40).prop_map(Op::ModifyFirst), |
| 153 | 1 => (1usize..40).prop_map(Op::ModifyLast), |
| 154 | 1 => (1usize..40).prop_map(Op::AddFirst), |
| 155 | 1 => (1usize..40).prop_map(Op::AddLast), |
| 156 | ] |
| 157 | } |
| 158 | |
| 159 | /// The name at `index` among `entries`, which must not be empty. |
| 160 | fn nth(entries: &Entries, index: &Pos) -> Vec<u8> { |
| 161 | entries |
| 162 | .keys() |
| 163 | .nth(index.of(entries.len())) |
| 164 | .cloned() |
| 165 | .expect("not empty") |
| 166 | } |
| 167 | |
| 168 | /// A name that sorts right after `name`, before any longer one that starts |
| 169 | /// with it. |
| 170 | fn after(name: &[u8], tag: u64) -> Vec<u8> { |
| 171 | let mut next = name.to_vec(); |
| 172 | next.push(b'\x01'); |
| 173 | next.extend_from_slice(format!("{tag:05}").as_bytes()); |
| 174 | next |
| 175 | } |
| 176 | |
| 177 | /// Applies `ops` to a copy of `entries`. |
| 178 | fn edited(entries: &Entries, ops: &[Op], seed: u64) -> Entries { |
| 179 | let mut new = entries.clone(); |
| 180 | let mut tag = 0u64; |
| 181 | let fresh = |tag: &mut u64| { |
| 182 | *tag += 1; |
| 183 | kind(mix(seed ^ 0x5eed, *tag), mix(seed, *tag)) |
| 184 | }; |
| 185 | for op in ops { |
| 186 | if new.is_empty() { |
| 187 | new.insert(b"seed".to_vec(), fresh(&mut tag)); |
| 188 | continue; |
| 189 | } |
| 190 | let names: Vec<Vec<u8>> = match op { |
| 191 | Op::Modify(i) | Op::Delete(i) | Op::AddAfter(i) | Op::Rename(i, _) => { |
| 192 | vec![nth(&new, i)] |
| 193 | } |
| 194 | Op::DeleteRun(i, n) | Op::ModifyRun(i, n) | Op::AddRun(i, n) => { |
| 195 | let start = i.of(new.len()); |
| 196 | new.keys().skip(start).take(*n).cloned().collect() |
| 197 | } |
| 198 | Op::DeleteFirst(n) | Op::ModifyFirst(n) | Op::AddFirst(n) => { |
| 199 | new.keys().take(*n).cloned().collect() |
| 200 | } |
| 201 | Op::DeleteLast(n) | Op::ModifyLast(n) | Op::AddLast(n) => { |
| 202 | new.keys().rev().take(*n).cloned().collect() |
| 203 | } |
| 204 | }; |
| 205 | match op { |
| 206 | Op::Modify(_) | Op::ModifyRun(..) | Op::ModifyFirst(_) | Op::ModifyLast(_) => { |
| 207 | for name in names { |
| 208 | new.insert(name, fresh(&mut tag)); |
| 209 | } |
| 210 | } |
| 211 | Op::Delete(_) | Op::DeleteRun(..) | Op::DeleteFirst(_) | Op::DeleteLast(_) => { |
| 212 | for name in names { |
| 213 | new.remove(&name); |
| 214 | } |
| 215 | } |
| 216 | Op::AddAfter(_) => { |
| 217 | let name = after(&names[0], tag); |
| 218 | new.insert(name, fresh(&mut tag)); |
| 219 | } |
| 220 | Op::AddRun(_, n) => { |
| 221 | for _ in 0..*n { |
| 222 | let name = after(&names[0], tag); |
| 223 | new.insert(name, fresh(&mut tag)); |
| 224 | } |
| 225 | } |
| 226 | Op::Rename(_, to) => { |
| 227 | if let Some(content) = new.remove(&names[0]) |
| 228 | && !new.is_empty() |
| 229 | { |
| 230 | let next = after(&nth(&new, to), tag); |
| 231 | tag += 1; |
| 232 | new.insert(next, content); |
| 233 | } |
| 234 | } |
| 235 | Op::AddFirst(n) => { |
| 236 | for k in 0..*n { |
| 237 | new.insert(format!("\u{1}first{k:03}").into_bytes(), fresh(&mut tag)); |
| 238 | } |
| 239 | } |
| 240 | Op::AddLast(n) => { |
| 241 | for k in 0..*n { |
| 242 | new.insert(format!("\u{10ffff}{k:03}").into_bytes(), fresh(&mut tag)); |
| 243 | } |
| 244 | } |
| 245 | } |
| 246 | } |
| 247 | new |
| 248 | } |
| 249 | |
| 250 | /// The edits that turn `old` into `new`, with a few that change nothing: |
| 251 | /// names set to the entry they have, and removals of names that are absent. |
| 252 | fn edits(old: &Entries, new: &Entries, idle: &[Pos]) -> Vec<EntryEdit> { |
| 253 | let mut edits: BTreeMap<Vec<u8>, Option<EntryKind>> = BTreeMap::new(); |
| 254 | for (name, kind) in new { |
| 255 | if old.get(name) != Some(kind) { |
| 256 | edits.insert(name.clone(), Some(kind.clone())); |
| 257 | } |
| 258 | } |
| 259 | for name in old.keys() { |
| 260 | if !new.contains_key(name) { |
| 261 | edits.insert(name.clone(), None); |
| 262 | } |
| 263 | } |
| 264 | for (k, index) in idle.iter().enumerate() { |
| 265 | if new.is_empty() { |
| 266 | break; |
| 267 | } |
| 268 | let name = nth(new, index); |
| 269 | if k % 2 == 0 { |
| 270 | edits |
| 271 | .entry(name.clone()) |
| 272 | .or_insert_with(|| Some(new[&name].clone())); |
| 273 | } else { |
| 274 | edits.entry(after(&name, 99_999)).or_insert(None); |
| 275 | } |
| 276 | } |
| 277 | edits |
| 278 | .into_iter() |
| 279 | .map(|(name, kind)| EntryEdit { name, kind }) |
| 280 | .collect() |
| 281 | } |
| 282 | |
| 283 | fn as_entries(entries: &Entries) -> Vec<Entry> { |
| 284 | entries |
| 285 | .iter() |
| 286 | .map(|(name, kind)| Entry { |
| 287 | name: name.clone(), |
| 288 | kind: kind.clone(), |
| 289 | }) |
| 290 | .collect() |
| 291 | } |
| 292 | |
| 293 | /// Builds `entries` from scratch, and returns the root and the store of its |
| 294 | /// nodes. |
| 295 | fn stored(entries: &Entries) -> (ObjectId, Store) { |
| 296 | let directory = build_directory(as_entries(entries)).unwrap(); |
| 297 | (directory.root(), directory.nodes.into_iter().collect()) |
| 298 | } |
| 299 | |
| 300 | /// Updates the directory `root` of `store` with `edits`, and counts the |
| 301 | /// nodes it fetches. |
| 302 | fn update(store: &Store, root: ObjectId, edits: &[EntryEdit]) -> (Updated, usize) { |
| 303 | let fetched = Cell::new(0); |
| 304 | let mut cache = NodeCache::new(); |
| 305 | let updated = update_directory(&mut cache, root, edits, |id| { |
| 306 | fetched.set(fetched.get() + 1); |
| 307 | store.get(id).cloned() |
| 308 | }) |
| 309 | .unwrap(); |
| 310 | (updated, fetched.get()) |
| 311 | } |
| 312 | |
| 313 | /// Checks an update against building the new entries from scratch: the same |
| 314 | /// root, the same nodes byte for byte, none missing and none extra, every |
| 315 | /// node written after its children, and hints that name old nodes. |
| 316 | fn check_update(old_store: &Store, updated: &Updated, new: &Entries) -> Result<(), TestCaseError> { |
| 317 | let expected = build_directory(as_entries(new)).unwrap(); |
| 318 | prop_assert_eq!(updated.root, expected.root()); |
| 319 | prop_assert_eq!(updated.entries, new.len() as u64); |
| 320 | |
| 321 | let expected_nodes: Store = expected.nodes.iter().cloned().collect(); |
| 322 | let mut written = HashSet::new(); |
| 323 | for node in &updated.nodes { |
| 324 | prop_assert_eq!( |
| 325 | expected_nodes.get(&node.id), |
| 326 | Some(&node.bytes), |
| 327 | "a node written is not one of the new directory" |
| 328 | ); |
| 329 | prop_assert!( |
| 330 | !old_store.contains_key(&node.id), |
| 331 | "an old node is written again" |
| 332 | ); |
| 333 | prop_assert!(written.insert(node.id), "a node is written twice"); |
| 334 | if let Node::Internal { children, .. } = Node::decode(&node.bytes).unwrap() { |
| 335 | for child in children { |
| 336 | prop_assert!( |
| 337 | written.contains(&child.node) || old_store.contains_key(&child.node), |
| 338 | "a node is written before its children" |
| 339 | ); |
| 340 | } |
| 341 | } |
| 342 | if let Some(similar) = node.similar { |
| 343 | prop_assert!(old_store.contains_key(&similar), "a hint names no old node"); |
| 344 | prop_assert_ne!(similar, node.id); |
| 345 | } |
| 346 | } |
| 347 | for (id, bytes) in &expected.nodes { |
| 348 | prop_assert!( |
| 349 | written.contains(id) || old_store.get(id) == Some(bytes), |
| 350 | "a node of the new directory is neither written nor kept" |
| 351 | ); |
| 352 | } |
| 353 | |
| 354 | // Read back through the old nodes and the new ones. |
| 355 | let mut store = old_store.clone(); |
| 356 | store.extend(updated.nodes.iter().map(|n| (n.id, n.bytes.clone()))); |
| 357 | prop_assert_eq!( |
| 358 | read_directory(updated.root, |id| store.get(id).cloned()).unwrap(), |
| 359 | as_entries(new) |
| 360 | ); |
| 361 | Ok(()) |
| 362 | } |
| 363 | |
| 364 | /// Directories of 1,000 to 20,000 entries, sometimes just around the limit |
| 365 | /// of a flat node. |
| 366 | fn shape() -> impl Strategy<Value = (usize, u8, u64)> { |
| 367 | ( |
| 368 | prop_oneof![ |
| 369 | 3 => 1_000usize..20_000, |
| 370 | 1 => (MAX_FLAT_ENTRIES - 24)..(MAX_FLAT_ENTRIES + 40), |
| 371 | ], |
| 372 | any::<u8>(), |
| 373 | any::<u64>(), |
| 374 | ) |
| 375 | } |
| 376 | |
| 377 | proptest! { |
| 378 | #![proptest_config(ProptestConfig::with_cases(cases()))] |
| 379 | |
| 380 | #[test] |
| 381 | fn updates_build_what_building_from_scratch_builds( |
| 382 | (count, style, seed) in shape(), |
| 383 | ops in prop::collection::vec(op(), 1..12), |
| 384 | idle in prop::collection::vec(pos(), 0..3), |
| 385 | ) { |
| 386 | let old = directory(count, style, seed); |
| 387 | let new = edited(&old, &ops, seed); |
| 388 | let edits = edits(&old, &new, &idle); |
| 389 | let (root, store) = stored(&old); |
| 390 | let (updated, _) = update(&store, root, &edits); |
| 391 | check_update(&store, &updated, &new)?; |
| 392 | } |
| 393 | |
| 394 | #[test] |
| 395 | fn lookups_find_what_the_directory_holds( |
| 396 | (count, style, seed) in shape(), |
| 397 | probes in prop::collection::vec(pos(), 1..40), |
| 398 | ) { |
| 399 | let entries = directory(count, style, seed); |
| 400 | let (root, store) = stored(&entries); |
| 401 | let mut cache = NodeCache::new(); |
| 402 | let mut fetch = |id: &ObjectId| store.get(id).cloned(); |
| 403 | for probe in &probes { |
| 404 | let name = nth(&entries, probe); |
| 405 | let found = find_entry(&mut cache, root, &name, &mut fetch).unwrap(); |
| 406 | prop_assert_eq!(found.as_ref(), entries.get(&name)); |
| 407 | let absent = after(&name, 99_999); |
| 408 | prop_assert_eq!(find_entry(&mut cache, root, &absent, &mut fetch).unwrap(), None); |
| 409 | } |
| 410 | for name in [&b"\x01"[..], "\u{10ffff}".as_bytes()] { |
| 411 | prop_assert_eq!(find_entry(&mut cache, root, name, &mut fetch).unwrap(), None); |
| 412 | } |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | /// Edits across the limit of a flat node, both ways, and down to nothing. |
| 417 | #[test] |
| 418 | fn crossing_the_flat_limit_both_ways() { |
| 419 | let old = directory(MAX_FLAT_ENTRIES, 0, 7); |
| 420 | let (root, store) = stored(&old); |
| 421 | let one_more = edited(&old, &[Op::AddLast(1)], 7); |
| 422 | let (grown, _) = update(&store, root, &edits(&old, &one_more, &[])); |
| 423 | check_update(&store, &grown, &one_more).unwrap(); |
| 424 | assert!(grown.nodes.len() >= 3, "split into leaves under a root"); |
| 425 | |
| 426 | // The split directory alone, so that its old nodes are all a store has. |
| 427 | let (split_root, split_store) = stored(&one_more); |
| 428 | assert_eq!(split_root, grown.root); |
| 429 | let (shrunk, _) = update(&split_store, split_root, &edits(&one_more, &old, &[])); |
| 430 | check_update(&split_store, &shrunk, &old).unwrap(); |
| 431 | assert_eq!(shrunk.root, root, "flat again, as it was"); |
| 432 | |
| 433 | let big = directory(5_000, 1, 3); |
| 434 | let (root, store) = stored(&big); |
| 435 | let (gone, _) = update(&store, root, &edits(&big, &Entries::new(), &[])); |
| 436 | check_update(&store, &gone, &Entries::new()).unwrap(); |
| 437 | assert_eq!(gone.entries, 0); |
| 438 | } |
| 439 | |
| 440 | /// The root of a split directory moves down a level when its subtrees but |
| 441 | /// one empty, and back up when they fill again. |
| 442 | #[test] |
| 443 | fn the_root_moves_down_and_up_a_level() { |
| 444 | // A directory whose root is two levels above its leaves, and whose last |
| 445 | // subtree alone is too large for a flat node. |
| 446 | let (old, root, store, children) = (0..) |
| 447 | .find_map(|seed| { |
| 448 | let entries = directory(12_000, 1, seed); |
| 449 | let (root, store) = stored(&entries); |
| 450 | match Node::decode(&store[&root]).unwrap() { |
| 451 | Node::Internal { level: 2, children } |
| 452 | if children.last()?.entry_count > MAX_FLAT_ENTRIES as u64 => |
| 453 | { |
| 454 | Some((entries, root, store, children)) |
| 455 | } |
| 456 | _ => None, |
| 457 | } |
| 458 | }) |
| 459 | .unwrap(); |
| 460 | // Every entry under the last child of the root stays. |
| 461 | let kept = children.last().unwrap(); |
| 462 | let first_kept = children[children.len() - 2].last_name.clone(); |
| 463 | let fewer: Entries = old |
| 464 | .iter() |
| 465 | .filter(|(name, _)| **name > first_kept) |
| 466 | .map(|(name, kind)| (name.clone(), kind.clone())) |
| 467 | .collect(); |
| 468 | assert_eq!(fewer.len() as u64, kept.entry_count); |
| 469 | assert!(fewer.len() > MAX_FLAT_ENTRIES, "still split"); |
| 470 | |
| 471 | let (down, _) = update(&store, root, &edits(&old, &fewer, &[])); |
| 472 | check_update(&store, &down, &fewer).unwrap(); |
| 473 | let (down_root, down_store) = stored(&fewer); |
| 474 | assert_eq!(down.root, down_root); |
| 475 | assert_eq!(down.root, kept.node, "the last subtree's root is the root"); |
| 476 | assert!(down.nodes.is_empty(), "every node it needs is there"); |
| 477 | assert!(levels(&down_store, down_root) < 3, "the root moved down"); |
| 478 | |
| 479 | let (up, _) = update(&down_store, down_root, &edits(&fewer, &old, &[])); |
| 480 | check_update(&down_store, &up, &old).unwrap(); |
| 481 | assert_eq!(up.root, root, "and back up, as it was"); |
| 482 | } |
| 483 | |
| 484 | /// How many levels of nodes the directory `root` has: 1 when it is flat. |
| 485 | fn levels(store: &Store, root: ObjectId) -> usize { |
| 486 | match Node::decode(&store[&root]).unwrap() { |
| 487 | Node::Internal { level, .. } => usize::from(level) + 1, |
| 488 | _ => 1, |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | /// Edits of one entry each: a new name next to one at a position, the |
| 493 | /// removal of that one, or new content for it; and the same at both ends. |
| 494 | fn single_edits(entries: &Entries) -> Vec<EntryEdit> { |
| 495 | let names: Vec<&Vec<u8>> = entries.keys().collect(); |
| 496 | let set = |name: Vec<u8>, salt: u64| EntryEdit { |
| 497 | name, |
| 498 | kind: Some(kind(salt, 7)), |
| 499 | }; |
| 500 | let mut edits = Vec::new(); |
| 501 | for k in 0..40u64 { |
| 502 | let name = names[Pos(mix(5, k)).of(names.len())]; |
| 503 | edits.push(set(after(name, k), k)); |
| 504 | edits.push(EntryEdit { |
| 505 | name: name.clone(), |
| 506 | kind: None, |
| 507 | }); |
| 508 | edits.push(set(name.clone(), k + 1_000)); |
| 509 | } |
| 510 | let (first, last) = (names[0], names[names.len() - 1]); |
| 511 | edits.push(set(b"\x01first".to_vec(), 1)); |
| 512 | edits.push(set("\u{10ffff}".as_bytes().to_vec(), 2)); |
| 513 | for name in [first, last] { |
| 514 | edits.push(EntryEdit { |
| 515 | name: name.clone(), |
| 516 | kind: None, |
| 517 | }); |
| 518 | } |
| 519 | edits |
| 520 | } |
| 521 | |
| 522 | /// A one-entry edit of a directory reads the nodes on its path and a few |
| 523 | /// neighbours, and writes about as many, whatever the size of the directory: |
| 524 | /// the bound depends only on the number of levels, which grows with the |
| 525 | /// logarithm of the size. |
| 526 | #[test] |
| 527 | fn one_entry_edits_read_and_write_a_few_nodes() { |
| 528 | // Per level: the node on the path and, while the boundaries move, the |
| 529 | // next ones. Measured here, one edit reads one node more than there are |
| 530 | // levels at most, and writes as many as it reads. |
| 531 | const READS_PER_LEVEL: usize = 2; |
| 532 | const WRITES_PER_LEVEL: usize = 2; |
| 533 | // Building a large directory from scratch to compare is slow in a debug |
| 534 | // build: every edit is counted, one in this many is also compared. |
| 535 | const COMPARED: usize = 31; |
| 536 | let mut report = Vec::new(); |
| 537 | for count in [2_000usize, 20_000, 100_000] { |
| 538 | let old = directory(count, 0, 11); |
| 539 | let (root, store) = stored(&old); |
| 540 | let levels = levels(&store, root); |
| 541 | let (mut max_read, mut max_written, mut reads, mut writes) = (0, 0, 0, 0); |
| 542 | let edits = single_edits(&old); |
| 543 | for (k, edit) in edits.iter().enumerate() { |
| 544 | let (updated, read) = update(&store, root, std::slice::from_ref(edit)); |
| 545 | if k % COMPARED == 0 || k + 4 >= edits.len() { |
| 546 | let mut new = old.clone(); |
| 547 | match &edit.kind { |
| 548 | Some(kind) => new.insert(edit.name.clone(), kind.clone()), |
| 549 | None => new.remove(&edit.name), |
| 550 | }; |
| 551 | check_update(&store, &updated, &new).unwrap(); |
| 552 | } |
| 553 | max_read = max_read.max(read); |
| 554 | max_written = max_written.max(updated.nodes.len()); |
| 555 | reads += read; |
| 556 | writes += updated.nodes.len(); |
| 557 | } |
| 558 | assert!( |
| 559 | max_read <= READS_PER_LEVEL * levels, |
| 560 | "{count} entries, {levels} levels: an edit read {max_read} of {} nodes", |
| 561 | store.len() |
| 562 | ); |
| 563 | assert!( |
| 564 | max_written <= WRITES_PER_LEVEL * levels, |
| 565 | "{count} entries, {levels} levels: an edit wrote {max_written} nodes" |
| 566 | ); |
| 567 | report.push(Work { |
| 568 | entries: count, |
| 569 | levels, |
| 570 | nodes: store.len(), |
| 571 | most_read: max_read, |
| 572 | most_written: max_written, |
| 573 | reads, |
| 574 | writes, |
| 575 | edits: edits.len(), |
| 576 | }); |
| 577 | } |
| 578 | // Beyond the levels, the size of the directory makes no difference: the |
| 579 | // average edit of the largest directory reads no more per level than one |
| 580 | // of the smallest, give or take one node. |
| 581 | let per_level = |work: &Work| work.reads as f64 / (work.edits * work.levels) as f64; |
| 582 | let (small, large) = (per_level(&report[0]), per_level(&report[2])); |
| 583 | assert!(large <= small + 1.0, "{report:#?}"); |
| 584 | println!("{report:#?}"); |
| 585 | } |
| 586 | |
| 587 | /// What the edits of one directory read and wrote. |
| 588 | #[derive(Debug)] |
| 589 | #[allow(dead_code)] // Printed. |
| 590 | struct Work { |
| 591 | entries: usize, |
| 592 | levels: usize, |
| 593 | nodes: usize, |
| 594 | most_read: usize, |
| 595 | most_written: usize, |
| 596 | reads: usize, |
| 597 | writes: usize, |
| 598 | edits: usize, |
| 599 | } |
| 600 | |
| 601 | #[test] |
| 602 | fn invalid_edits_are_refused_before_anything_is_read() { |
| 603 | let entries = directory(3_000, 0, 1); |
| 604 | let (root, store) = stored(&entries); |
| 605 | let file = kind(1, 5); |
| 606 | // Edits, and what the error must be. |
| 607 | type Case = (Vec<EntryEdit>, fn(&TreeError) -> bool); |
| 608 | let cases: [Case; 3] = [ |
| 609 | ( |
| 610 | vec![ |
| 611 | EntryEdit { |
| 612 | name: b"b".to_vec(), |
| 613 | kind: Some(file.clone()), |
| 614 | }, |
| 615 | EntryEdit { |
| 616 | name: b"a".to_vec(), |
| 617 | kind: None, |
| 618 | }, |
| 619 | ], |
| 620 | |error| matches!(error, TreeError::Unsorted { index: 1 }), |
| 621 | ), |
| 622 | ( |
| 623 | vec![EntryEdit { |
| 624 | name: b".git".to_vec(), |
| 625 | kind: Some(file.clone()), |
| 626 | }], |
| 627 | |error| matches!(error, TreeError::Name { .. }), |
| 628 | ), |
| 629 | ( |
| 630 | vec![EntryEdit { |
| 631 | name: b".gitmodules".to_vec(), |
| 632 | kind: Some(EntryKind::Symlink { |
| 633 | blob: ObjectId::hash(Kind::Blob, b"x"), |
| 634 | size: 1, |
| 635 | }), |
| 636 | }], |
| 637 | |error| matches!(error, TreeError::SymlinkName(_)), |
| 638 | ), |
| 639 | ]; |
| 640 | for (edits, expected) in cases { |
| 641 | let fetched = Cell::new(0); |
| 642 | let result = update_directory(&mut NodeCache::new(), root, &edits, |id| { |
| 643 | fetched.set(fetched.get() + 1); |
| 644 | store.get(id).cloned() |
| 645 | }); |
| 646 | let error = result.unwrap_err(); |
| 647 | assert!(expected(&error), "{error:?}"); |
| 648 | assert_eq!(fetched.get(), 0); |
| 649 | } |
| 650 | } |
| 651 | |
| 652 | /// The nodes on the way to an edit are checked against the references that |
| 653 | /// lead to them, and the boundaries the edit reads against the splitting |
| 654 | /// rule. |
| 655 | #[test] |
| 656 | fn damaged_directories_are_refused() { |
| 657 | let entries = directory(3_000, 0, 2); |
| 658 | let (root, store) = stored(&entries); |
| 659 | let edit = |name: &[u8]| { |
| 660 | vec![EntryEdit { |
| 661 | name: name.to_vec(), |
| 662 | kind: Some(kind(9, 9)), |
| 663 | }] |
| 664 | }; |
| 665 | let first = entries.keys().next().unwrap().clone(); |
| 666 | |
| 667 | // A leaf that is missing. |
| 668 | let Node::Internal { children, level } = Node::decode(&store[&root]).unwrap() else { |
| 669 | panic!("a split directory"); |
| 670 | }; |
| 671 | assert_eq!(level, 1); |
| 672 | let mut missing = store.clone(); |
| 673 | missing.remove(&children[0].node); |
| 674 | let result = update_directory(&mut NodeCache::new(), root, &edit(&first), |id| { |
| 675 | missing.get(id).cloned() |
| 676 | }); |
| 677 | assert_eq!(result, Err(TreeError::MissingNode(children[0].node))); |
| 678 | |
| 679 | // A root whose first reference gives a wrong count of entries. |
| 680 | let mut wrong = children.clone(); |
| 681 | wrong[0].entry_count += 1; |
| 682 | let forged = Node::Internal { |
| 683 | level, |
| 684 | children: wrong, |
| 685 | }; |
| 686 | let mut forged_store = store.clone(); |
| 687 | forged_store.insert(forged.id(), forged.encode()); |
| 688 | let result = update_directory(&mut NodeCache::new(), forged.id(), &edit(&first), |id| { |
| 689 | forged_store.get(id).cloned() |
| 690 | }); |
| 691 | assert_eq!(result, Err(TreeError::NotCanonical)); |
| 692 | let result = find_entry(&mut NodeCache::new(), forged.id(), &first, |id| { |
| 693 | forged_store.get(id).cloned() |
| 694 | }); |
| 695 | assert_eq!(result, Err(TreeError::NotCanonical)); |
| 696 | |
| 697 | // Two leaves cut at the wrong place: the first one ends early. |
| 698 | let Node::Leaf(left) = Node::decode(&store[&children[0].node]).unwrap() else { |
| 699 | panic!("a leaf"); |
| 700 | }; |
| 701 | let Node::Leaf(right) = Node::decode(&store[&children[1].node]).unwrap() else { |
| 702 | panic!("a leaf"); |
| 703 | }; |
| 704 | let cut = left.len() - 1; |
| 705 | let early = Node::Leaf(left[..cut].to_vec()); |
| 706 | let mut moved = vec![left[cut].clone()]; |
| 707 | moved.extend(right.iter().cloned()); |
| 708 | assert!(moved.len() <= MAX_NODE_ENTRIES); |
| 709 | let late = Node::Leaf(moved); |
| 710 | let mut recut = children.clone(); |
| 711 | recut[0] = braid_format::tree::Child { |
| 712 | last_name: left[cut - 1].name.clone(), |
| 713 | node: early.id(), |
| 714 | entry_count: cut as u64, |
| 715 | }; |
| 716 | recut[1] = braid_format::tree::Child { |
| 717 | last_name: children[1].last_name.clone(), |
| 718 | node: late.id(), |
| 719 | entry_count: children[1].entry_count + 1, |
| 720 | }; |
| 721 | let bad_root = Node::Internal { |
| 722 | level, |
| 723 | children: recut, |
| 724 | }; |
| 725 | let mut bad_store = store.clone(); |
| 726 | for node in [&early, &late, &bad_root] { |
| 727 | bad_store.insert(node.id(), node.encode()); |
| 728 | } |
| 729 | let result = update_directory(&mut NodeCache::new(), bad_root.id(), &edit(&first), |id| { |
| 730 | bad_store.get(id).cloned() |
| 731 | }); |
| 732 | assert_eq!(result, Err(TreeError::NotCanonical)); |
| 733 | } |