utopia-ia/elffuss-braid public
Changesets · Branches · Tags · Compare
| Changeset | 1d081fd6ef47e612a1e93e2ea391330dbfc9ed46c4e8c8d8d0fd62405f38154a |
|---|---|
| Author | KikoCis <KikoCis@users.noreply.github.com> · 2026-10-16 03:46 +02:00 |
| Committer | KikoCis <KikoCis@users.noreply.github.com> · 2026-10-16 03:46 +02:00 |
| Parents | 818b87322bb6, f2b4da620c53 |
8 files changed
modified crates/engine/src/access.rs +88 −31
| @@ -9,8 +9,9 @@ | ||
| 9 | 9 | |
| 10 | 10 | use braid_format::changeset::{MAX_INLINE_CHANGES_BYTES, decode_change_list}; |
| 11 | 11 | use braid_format::{ |
| 12 | - Change, Changes, Changeset, Entry, EntryKind, Kind, Node, ObjectId, Objects, TreeError, | |
| 13 | - build_directory, read_directory, | |
| 12 | + Change, Changes, Changeset, Entry, EntryEdit, EntryKind, Kind, Node, NodeCache, ObjectId, | |
| 13 | + Objects, TreeError, Updated, build_directory, check_edits, find_entry, read_directory, | |
| 14 | + update_directory, | |
| 14 | 15 | }; |
| 15 | 16 | |
| 16 | 17 | use crate::error::{Error, store_error}; |
| @@ -70,32 +71,52 @@ | ||
| 70 | 71 | if id == EMPTY_TREE { |
| 71 | 72 | return Ok(Vec::new()); |
| 72 | 73 | } |
| 73 | - // `read_directory` sees a node it cannot fetch as missing; remember why. | |
| 74 | 74 | let mut failure = None; |
| 75 | - let read = read_directory(id, |node| match objects.get(node) { | |
| 76 | - Ok(Some((Kind::Tree, bytes))) => Some(bytes), | |
| 77 | - Ok(Some((found, _))) => { | |
| 78 | - failure.get_or_insert(Error::WrongKind { | |
| 79 | - id: *node, | |
| 80 | - expected: Kind::Tree, | |
| 81 | - found, | |
| 82 | - }); | |
| 83 | - None | |
| 75 | + read_directory(id, fetch_node(objects, &mut failure)) | |
| 76 | + .map_err(|error| tree_error(id, failure, error)) | |
| 77 | +} | |
| 78 | + | |
| 79 | +/// Fetches the nodes of trees for the readers of the format crate, which | |
| 80 | +/// see a node they cannot fetch as missing: `failure` keeps why. The empty | |
| 81 | +/// tree is known without reading it. | |
| 82 | +fn fetch_node<'a, O: Objects>( | |
| 83 | + objects: &'a O, | |
| 84 | + failure: &'a mut Option<Error>, | |
| 85 | +) -> impl FnMut(&ObjectId) -> Option<Vec<u8>> + 'a { | |
| 86 | + move |node| { | |
| 87 | + if *node == EMPTY_TREE { | |
| 88 | + return Some(empty_tree_node()); | |
| 84 | 89 | } |
| 85 | - Ok(None) => None, | |
| 86 | - Err(error) => { | |
| 87 | - failure.get_or_insert(store_error(error)); | |
| 88 | - None | |
| 90 | + match objects.get(node) { | |
| 91 | + Ok(Some((Kind::Tree, bytes))) => Some(bytes), | |
| 92 | + Ok(Some((found, _))) => { | |
| 93 | + failure.get_or_insert(Error::WrongKind { | |
| 94 | + id: *node, | |
| 95 | + expected: Kind::Tree, | |
| 96 | + found, | |
| 97 | + }); | |
| 98 | + None | |
| 99 | + } | |
| 100 | + Ok(None) => None, | |
| 101 | + Err(error) => { | |
| 102 | + failure.get_or_insert(store_error(error)); | |
| 103 | + None | |
| 104 | + } | |
| 89 | 105 | } |
| 90 | - }); | |
| 91 | - read.map_err(|error| match (failure, error) { | |
| 106 | + } | |
| 107 | +} | |
| 108 | + | |
| 109 | +/// The error for the directory `id`, which a reader of the format crate | |
| 110 | +/// failed on: why a node could not be fetched, if that was it. | |
| 111 | +fn tree_error(id: ObjectId, failure: Option<Error>, error: TreeError) -> Error { | |
| 112 | + match (failure, error) { | |
| 92 | 113 | (Some(failure), _) => failure, |
| 93 | 114 | (None, TreeError::MissingNode(node)) => Error::Missing { |
| 94 | 115 | id: node, |
| 95 | 116 | kind: Kind::Tree, |
| 96 | 117 | }, |
| 97 | 118 | (None, error) => Error::Tree { id, error }, |
| 98 | - }) | |
| 119 | + } | |
| 99 | 120 | } |
| 100 | 121 | |
| 101 | 122 | /// Stores a directory: builds its canonical nodes from `entries`, in any |
| @@ -196,11 +217,14 @@ | ||
| 196 | 217 | .map(|index| &entries[index].kind) |
| 197 | 218 | } |
| 198 | 219 | |
| 199 | -/// Directories read during one operation, by id, so that each one is fetched | |
| 200 | -/// and checked once. | |
| 220 | +/// Directories read during one operation, so that each one, or each node of | |
| 221 | +/// a split one, is fetched and checked once. | |
| 201 | 222 | pub(crate) struct Trees<'o, O> { |
| 202 | 223 | objects: &'o O, |
| 224 | + /// Directories read whole, by id. | |
| 203 | 225 | directories: HashMap<ObjectId, Rc<[Entry]>>, |
| 226 | + /// Nodes read one path at a time. | |
| 227 | + nodes: NodeCache, | |
| 204 | 228 | } |
| 205 | 229 | |
| 206 | 230 | impl<'o, O: Objects> Trees<'o, O> { |
| @@ -208,6 +232,7 @@ | ||
| 208 | 232 | Trees { |
| 209 | 233 | objects, |
| 210 | 234 | directories: HashMap::new(), |
| 235 | + nodes: NodeCache::new(), | |
| 211 | 236 | } |
| 212 | 237 | } |
| 213 | 238 | |
| @@ -233,6 +258,41 @@ | ||
| 233 | 258 | } |
| 234 | 259 | } |
| 235 | 260 | |
| 261 | + /// The entry named `name` in the directory `dir`. Only the nodes on the | |
| 262 | + /// way to the name are read, unless the directory was read whole already. | |
| 263 | + pub(crate) fn entry(&mut self, dir: ObjectId, name: &[u8]) -> Result<Option<EntryKind>, Error> { | |
| 264 | + if let Some(entries) = self.directories.get(&dir) { | |
| 265 | + return Ok(lookup(entries, name).cloned()); | |
| 266 | + } | |
| 267 | + let mut failure = None; | |
| 268 | + find_entry( | |
| 269 | + &mut self.nodes, | |
| 270 | + dir, | |
| 271 | + name, | |
| 272 | + fetch_node(self.objects, &mut failure), | |
| 273 | + ) | |
| 274 | + .map_err(|error| tree_error(dir, failure, error)) | |
| 275 | + } | |
| 276 | + | |
| 277 | + /// The directory `base` after `edits`, sorted by name: its new root, | |
| 278 | + /// how many entries it has, and the nodes to store. Only the nodes on | |
| 279 | + /// the way to the edited names, and their neighbours where boundaries | |
| 280 | + /// move, are read. | |
| 281 | + pub(crate) fn update(&mut self, base: ObjectId, edits: &[EntryEdit]) -> Result<Updated, Error> { | |
| 282 | + let mut failure = None; | |
| 283 | + update_directory( | |
| 284 | + &mut self.nodes, | |
| 285 | + base, | |
| 286 | + edits, | |
| 287 | + fetch_node(self.objects, &mut failure), | |
| 288 | + ) | |
| 289 | + .map_err(|error| match check_edits(edits) { | |
| 290 | + // The edits are checked before any node is read. | |
| 291 | + Err(invalid) => Error::Entries(invalid), | |
| 292 | + Ok(()) => tree_error(base, failure, error), | |
| 293 | + }) | |
| 294 | + } | |
| 295 | + | |
| 236 | 296 | /// What is at `path` in the tree `root`. |
| 237 | 297 | pub(crate) fn find(&mut self, root: ObjectId, path: &[u8]) -> Result<Found, Error> { |
| 238 | 298 | let mut dir = root; |
| @@ -240,12 +300,11 @@ | ||
| 240 | 300 | loop { |
| 241 | 301 | let slash = path[start..].iter().position(|byte| *byte == b'/'); |
| 242 | 302 | let end = slash.map_or(path.len(), |slash| start + slash); |
| 243 | - let entries = self.read(dir)?; | |
| 244 | - match (lookup(&entries, &path[start..end]), slash) { | |
| 303 | + match (self.entry(dir, &path[start..end])?, slash) { | |
| 245 | 304 | (None, _) => return Ok(Found::Absent), |
| 246 | - (Some(kind), None) => return Ok(Found::Entry(kind.clone())), | |
| 305 | + (Some(kind), None) => return Ok(Found::Entry(kind)), | |
| 247 | 306 | (Some(EntryKind::Tree { tree }), Some(_)) => { |
| 248 | - dir = *tree; | |
| 307 | + dir = tree; | |
| 249 | 308 | start = end + 1; |
| 250 | 309 | } |
| 251 | 310 | (Some(_), Some(_)) => return Ok(Found::Blocked(end)), |
| @@ -265,10 +324,9 @@ | ||
| 265 | 324 | let mut start = 0; |
| 266 | 325 | while let Some(slash) = path[start..].iter().position(|byte| *byte == b'/') { |
| 267 | 326 | let end = start + slash; |
| 268 | - let entries = self.read(dir)?; | |
| 269 | - match lookup(&entries, &path[start..end]) { | |
| 327 | + match self.entry(dir, &path[start..end])? { | |
| 270 | 328 | Some(EntryKind::Tree { tree }) => { |
| 271 | - dir = *tree; | |
| 329 | + dir = tree; | |
| 272 | 330 | deepest = end; |
| 273 | 331 | start = end + 1; |
| 274 | 332 | } |
| @@ -290,10 +348,9 @@ | ||
| 290 | 348 | let mut start = 0; |
| 291 | 349 | while let Some(slash) = path[start..].iter().position(|byte| *byte == b'/') { |
| 292 | 350 | let end = start + slash; |
| 293 | - let entries = self.read(dir)?; | |
| 294 | - match lookup(&entries, &path[start..end]) { | |
| 351 | + match self.entry(dir, &path[start..end])? { | |
| 295 | 352 | Some(EntryKind::Tree { tree }) => { |
| 296 | - dir = *tree; | |
| 353 | + dir = tree; | |
| 297 | 354 | start = end + 1; |
| 298 | 355 | } |
| 299 | 356 | Some(_) => return Ok(None), |
modified crates/engine/src/apply.rs +110 −114
| @@ -2,15 +2,15 @@ | ||
| 2 | 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | 3 | |
| 4 | 4 | //! Applying a change list to a tree by path copying: only the directories on |
| 5 | -//! changed paths are read and rebuilt; every other subtree is shared with the | |
| 6 | -//! base tree. | |
| 5 | +//! changed paths are rebuilt; every other subtree is shared with the base | |
| 6 | +//! tree. In a large directory, split into nodes, only the nodes on the way to | |
| 7 | +//! the changed names are read and rewritten. | |
| 7 | 8 | |
| 8 | 9 | use std::collections::{BTreeMap, btree_map}; |
| 9 | -use std::rc::Rc; | |
| 10 | 10 | |
| 11 | 11 | use braid_format::name::forbidden_as_symlink; |
| 12 | 12 | use braid_format::{ |
| 13 | - Change, ChangeOp, Entry, EntryKind, Kind, ObjectId, Objects, build_directory, validate_path, | |
| 13 | + Change, ChangeOp, EntryEdit, EntryKind, Kind, NewNode, ObjectId, Objects, validate_path, | |
| 14 | 14 | }; |
| 15 | 15 | |
| 16 | 16 | use crate::access::{EMPTY_TREE, Trees, empty_tree_node, read_object}; |
| @@ -47,20 +47,12 @@ | ||
| 47 | 47 | pub(crate) struct Applied { |
| 48 | 48 | /// The new root tree. |
| 49 | 49 | pub(crate) root: ObjectId, |
| 50 | - /// Every node of every directory rebuilt, children before parents. | |
| 50 | + /// Every node the rebuilt directories did not have before, children | |
| 51 | + /// before parents, each with the node of the same directory it most | |
| 52 | + /// likely replaces: a hint for the store, which may keep it as a delta. | |
| 51 | 53 | pub(crate) nodes: Vec<NewNode>, |
| 52 | 54 | } |
| 53 | 55 | |
| 54 | -/// A tree node rebuilt by applying changes. | |
| 55 | -#[derive(Debug)] | |
| 56 | -pub(crate) struct NewNode { | |
| 57 | - pub(crate) id: ObjectId, | |
| 58 | - pub(crate) bytes: Vec<u8>, | |
| 59 | - /// The node it most likely replaces, of the same directory before the | |
| 60 | - /// change: a hint for the store, which may keep it as a delta. | |
| 61 | - pub(crate) similar: Option<ObjectId>, | |
| 62 | -} | |
| 63 | - | |
| 64 | 56 | /// A structural problem found while applying, at `path`. |
| 65 | 57 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 66 | 58 | pub(crate) struct Problem { |
| @@ -183,28 +175,6 @@ | ||
| 183 | 175 | Ok(()) |
| 184 | 176 | } |
| 185 | 177 | |
| 186 | -/// For each of the `count` nodes of a rebuilt directory, children before | |
| 187 | -/// parents, the node of the directory before the change, `base` with | |
| 188 | -/// `entries`, that it most likely replaces. A split directory with as many | |
| 189 | -/// nodes as before pairs them in order, since boundaries depend only on | |
| 190 | -/// names; otherwise only the root is paired, with the old root. | |
| 191 | -fn similar_nodes(base: Option<ObjectId>, entries: &[Entry], count: usize) -> Vec<Option<ObjectId>> { | |
| 192 | - let mut similar = vec![None; count]; | |
| 193 | - let Some(base) = base.filter(|base| *base != EMPTY_TREE) else { | |
| 194 | - return similar; | |
| 195 | - }; | |
| 196 | - if count > 1 | |
| 197 | - && let Ok(old) = build_directory(entries.to_vec()) | |
| 198 | - && old.nodes.len() == count | |
| 199 | - { | |
| 200 | - return old.nodes.iter().map(|(id, _)| Some(*id)).collect(); | |
| 201 | - } | |
| 202 | - if let Some(root) = similar.last_mut() { | |
| 203 | - *root = Some(base); | |
| 204 | - } | |
| 205 | - similar | |
| 206 | -} | |
| 207 | - | |
| 208 | 178 | /// One change, seen from the directory being rebuilt. |
| 209 | 179 | #[derive(Clone, Copy)] |
| 210 | 180 | struct Item<'a> { |
| @@ -268,18 +238,15 @@ | ||
| 268 | 238 | base_root: ObjectId, |
| 269 | 239 | items: Vec<Item<'_>>, |
| 270 | 240 | ) -> Result<Option<ObjectId>, Error> { |
| 271 | - let mut stack = vec![Frame::open(ctx.trees, Some(base_root), items)?]; | |
| 241 | + let mut stack = vec![Frame::open(Some(base_root), items)]; | |
| 272 | 242 | // What the frame closed last became, for the frame below it. |
| 273 | 243 | let mut closed = None; |
| 274 | 244 | while let Some(frame) = stack.last_mut() { |
| 275 | 245 | if let Some(directory) = closed.take() { |
| 276 | 246 | frame.settle(ctx, directory); |
| 277 | 247 | } |
| 278 | - match frame.advance(ctx) { | |
| 279 | - Some((below, nested)) => { | |
| 280 | - let child = Frame::open(ctx.trees, below, nested)?; | |
| 281 | - stack.push(child); | |
| 282 | - } | |
| 248 | + match frame.advance(ctx)? { | |
| 249 | + Some((below, nested)) => stack.push(Frame::open(below, nested)), | |
| 283 | 250 | None => { |
| 284 | 251 | if let Some(frame) = stack.pop() { |
| 285 | 252 | closed = Some(frame.close(ctx)?); |
| @@ -296,18 +263,18 @@ | ||
| 296 | 263 | dir: &'a [u8], |
| 297 | 264 | /// Its tree before the change, if it existed. |
| 298 | 265 | base: Option<ObjectId>, |
| 299 | - /// Its entries before the change, in name order. | |
| 300 | - existing: Rc<[Entry]>, | |
| 301 | - /// How many of `existing` are copied or replaced already. | |
| 302 | - next: usize, | |
| 303 | 266 | /// The changes under each name not resolved yet, in name order. |
| 304 | 267 | groups: btree_map::IntoIter<&'a [u8], Group<'a>>, |
| 305 | - /// Its entries after the change, so far. | |
| 306 | - entries: Vec<Entry>, | |
| 268 | + /// The names resolved so far whose entry changes, in name order. | |
| 269 | + edits: Vec<EntryEdit>, | |
| 307 | 270 | /// The name whose directory the frame above is rebuilding. |
| 308 | 271 | waiting: Option<Waiting<'a>>, |
| 309 | 272 | } |
| 310 | 273 | |
| 274 | +/// A directory to rebuild before the one above it: its tree before the | |
| 275 | +/// change, if it existed, and the changes below it. | |
| 276 | +type Below<'a> = (Option<ObjectId>, Vec<Item<'a>>); | |
| 277 | + | |
| 311 | 278 | /// A name that must be, or become, a directory, waiting for it to be rebuilt. |
| 312 | 279 | struct Waiting<'a> { |
| 313 | 280 | name: &'a [u8], |
| @@ -331,11 +298,8 @@ | ||
| 331 | 298 | impl<'a> Frame<'a> { |
| 332 | 299 | /// Opens the directory whose tree is `base` (`None` if it does not |
| 333 | 300 | /// exist), to rebuild it with `items`, of which there is at least one. |
| 334 | - fn open<O: Objects>( | |
| 335 | - trees: &mut Trees<'_, O>, | |
| 336 | - base: Option<ObjectId>, | |
| 337 | - items: Vec<Item<'a>>, | |
| 338 | - ) -> Result<Self, Error> { | |
| 301 | + /// Nothing is read until a name is resolved. | |
| 302 | + fn open(base: Option<ObjectId>, items: Vec<Item<'a>>) -> Self { | |
| 339 | 303 | let dir = items.first().map_or(&b""[..], Item::dir); |
| 340 | 304 | let mut groups: BTreeMap<&'a [u8], Group<'a>> = BTreeMap::new(); |
| 341 | 305 | for item in items { |
| @@ -351,39 +315,39 @@ | ||
| 351 | 315 | }), |
| 352 | 316 | } |
| 353 | 317 | } |
| 354 | - let existing = trees.read_or_empty(base)?; | |
| 355 | - Ok(Frame { | |
| 318 | + Frame { | |
| 356 | 319 | dir, |
| 357 | 320 | base, |
| 358 | - entries: Vec::with_capacity(existing.len() + groups.len()), | |
| 359 | - existing, | |
| 360 | - next: 0, | |
| 361 | 321 | groups: groups.into_iter(), |
| 322 | + edits: Vec::new(), | |
| 362 | 323 | waiting: None, |
| 363 | - }) | |
| 324 | + } | |
| 364 | 325 | } |
| 365 | 326 | |
| 366 | 327 | /// Resolves names in order until one must be a directory rebuilt first, |
| 367 | 328 | /// and returns what to rebuild it from. |
| 368 | - fn advance<O>( | |
| 329 | + fn advance<O: Objects>( | |
| 369 | 330 | &mut self, |
| 370 | 331 | ctx: &mut Ctx<'_, '_, O>, |
| 371 | - ) -> Option<(Option<ObjectId>, Vec<Item<'a>>)> { | |
| 332 | + ) -> Result<Option<Below<'a>>, Error> { | |
| 372 | 333 | while let Some((name, group)) = self.groups.next() { |
| 373 | - let current = self.take(name); | |
| 374 | - match plan(ctx, self.dir, name, current, group) { | |
| 375 | - Step::Done(kind) => self.push(name, kind), | |
| 334 | + let current = match self.base { | |
| 335 | + Some(base) => ctx.trees.entry(base, name)?, | |
| 336 | + None => None, | |
| 337 | + }; | |
| 338 | + match plan(ctx, self.dir, name, current.clone(), group) { | |
| 339 | + Step::Done(kind) => self.record(name, current, kind), | |
| 376 | 340 | Step::Descend { |
| 377 | 341 | below, |
| 378 | 342 | nested, |
| 379 | 343 | waiting, |
| 380 | 344 | } => { |
| 381 | 345 | self.waiting = Some(waiting); |
| 382 | - return Some((below, nested)); | |
| 346 | + return Ok(Some((below, nested))); | |
| 383 | 347 | } |
| 384 | 348 | } |
| 385 | 349 | } |
| 386 | - None | |
| 350 | + Ok(None) | |
| 387 | 351 | } |
| 388 | 352 | |
| 389 | 353 | /// The frame above rebuilt the directory this one waits for, as |
| @@ -395,33 +359,16 @@ | ||
| 395 | 359 | direct, |
| 396 | 360 | }) = self.waiting.take() |
| 397 | 361 | { |
| 398 | - let kind = settle(ctx, self.dir, name, current, direct, directory); | |
| 399 | - self.push(name, kind); | |
| 362 | + let kind = settle(ctx, self.dir, name, current.clone(), direct, directory); | |
| 363 | + self.record(name, current, kind); | |
| 400 | 364 | } |
| 401 | 365 | } |
| 402 | 366 | |
| 403 | - /// Copies the entries named before `name`, and takes the one named | |
| 404 | - /// `name`, if there is one. | |
| 405 | - fn take(&mut self, name: &[u8]) -> Option<EntryKind> { | |
| 406 | - while let Some(entry) = self | |
| 407 | - .existing | |
| 408 | - .get(self.next) | |
| 409 | - .filter(|entry| entry.name.as_slice() < name) | |
| 410 | - { | |
| 411 | - self.entries.push(entry.clone()); | |
| 412 | - self.next += 1; | |
| 413 | - } | |
| 414 | - let entry = self | |
| 415 | - .existing | |
| 416 | - .get(self.next) | |
| 417 | - .filter(|entry| entry.name == name)?; | |
| 418 | - self.next += 1; | |
| 419 | - Some(entry.kind.clone()) | |
| 420 | - } | |
| 421 | - | |
| 422 | - fn push(&mut self, name: &[u8], kind: Option<EntryKind>) { | |
| 423 | - if let Some(kind) = kind { | |
| 424 | - self.entries.push(Entry { | |
| 367 | + /// Records the entry the name `name` gets, `kind`, if it is not the one | |
| 368 | + /// it has, `current`. | |
| 369 | + fn record(&mut self, name: &[u8], current: Option<EntryKind>, kind: Option<EntryKind>) { | |
| 370 | + if kind != current { | |
| 371 | + self.edits.push(EntryEdit { | |
| 425 | 372 | name: name.to_vec(), |
| 426 | 373 | kind, |
| 427 | 374 | }); |
| @@ -429,29 +376,22 @@ | ||
| 429 | 376 | } |
| 430 | 377 | |
| 431 | 378 | /// Finishes the directory, and returns its new tree, or `None` if it has |
| 432 | - /// no entries left. | |
| 433 | - fn close<O>(mut self, ctx: &mut Ctx<'_, '_, O>) -> Result<Option<ObjectId>, Error> { | |
| 434 | - self.entries | |
| 435 | - .extend(self.existing[self.next..].iter().cloned()); | |
| 436 | - if self.entries.is_empty() { | |
| 379 | + /// no entries left. Only the nodes on the way to the names that changed | |
| 380 | + /// are read and rewritten. | |
| 381 | + fn close<O: Objects>(self, ctx: &mut Ctx<'_, '_, O>) -> Result<Option<ObjectId>, Error> { | |
| 382 | + if self.edits.is_empty() { | |
| 383 | + // Nothing changed: the directory stays as it was, unless it was | |
| 384 | + // empty, as no braid tree holds an empty directory. | |
| 385 | + return Ok(self.base.filter(|base| *base != EMPTY_TREE)); | |
| 386 | + } | |
| 387 | + let updated = ctx | |
| 388 | + .trees | |
| 389 | + .update(self.base.unwrap_or(EMPTY_TREE), &self.edits)?; | |
| 390 | + if updated.entries == 0 { | |
| 437 | 391 | return Ok(None); |
| 438 | 392 | } |
| 439 | - let directory = build_directory(self.entries).map_err(Error::Entries)?; | |
| 440 | - let id = directory.root(); | |
| 441 | - let similar = similar_nodes(self.base, &self.existing, directory.nodes.len()); | |
| 442 | - // A node that did not change is its own old version: no hint. | |
| 443 | - ctx.nodes.extend( | |
| 444 | - directory | |
| 445 | - .nodes | |
| 446 | - .into_iter() | |
| 447 | - .zip(similar) | |
| 448 | - .map(|((id, bytes), similar)| NewNode { | |
| 449 | - id, | |
| 450 | - bytes, | |
| 451 | - similar: similar.filter(|similar| *similar != id), | |
| 452 | - }), | |
| 453 | - ); | |
| 454 | - Ok(Some(id)) | |
| 393 | + ctx.nodes.extend(updated.nodes); | |
| 394 | + Ok(Some(updated.root)) | |
| 455 | 395 | } |
| 456 | 396 | } |
| 457 | 397 | |
| @@ -545,7 +485,8 @@ | ||
| 545 | 485 | use crate::access::{entry_at, read_tree}; |
| 546 | 486 | use crate::diff::diff; |
| 547 | 487 | use crate::path::MAX_PATH_DEPTH; |
| 548 | - use crate::testing::{Hinted, Repo, deep_path, delete, gitlink, text_map}; | |
| 488 | + use crate::testing::{Counted, Hinted, Repo, deep_path, delete, gitlink, text_map}; | |
| 489 | + use braid_format::{Entry, MemoryObjects, build_directory}; | |
| 549 | 490 | |
| 550 | 491 | fn problem(result: Result<ObjectId, Error>) -> (String, ApplyProblem) { |
| 551 | 492 | match result { |
| @@ -820,7 +761,7 @@ | ||
| 820 | 761 | )); |
| 821 | 762 | } |
| 822 | 763 | |
| 823 | - fn file(objects: &Hinted, path: &str, content: &str) -> Change { | |
| 764 | + fn file<O: Objects>(objects: &O, path: &str, content: &str) -> Change { | |
| 824 | 765 | Change { |
| 825 | 766 | path: path.as_bytes().to_vec(), |
| 826 | 767 | op: ChangeOp::File { |
| @@ -899,6 +840,61 @@ | ||
| 899 | 840 | } |
| 900 | 841 | } |
| 901 | 842 | |
| 843 | + /// Adding, changing or removing one file of a wide directory reads and | |
| 844 | + /// writes a few nodes, whatever the number of files: the nodes on the | |
| 845 | + /// way to it, and a neighbour where a boundary moves. | |
| 846 | + #[test] | |
| 847 | + fn one_file_of_a_wide_directory_costs_a_few_nodes() { | |
| 848 | + const MOST_READ: usize = 6; | |
| 849 | + const MOST_WRITTEN: usize = 5; | |
| 850 | + let path = |i: usize| format!("wide/f{i:05}.txt"); | |
| 851 | + let mut costs = Vec::new(); | |
| 852 | + for count in [2_000usize, 20_000] { | |
| 853 | + let objects = Counted::default(); | |
| 854 | + let files: Vec<Change> = (0..count) | |
| 855 | + .map(|i| file(&objects, &path(i), &i.to_string())) | |
| 856 | + .collect(); | |
| 857 | + let base = apply(&objects, EMPTY_TREE, &files).unwrap(); | |
| 858 | + let edits = [ | |
| 859 | + // A new file at the end, as the benchmark adds them. | |
| 860 | + file(&objects, &path(count), "new"), | |
| 861 | + file(&objects, &path(count / 2), "changed"), | |
| 862 | + delete(&path(count / 3)), | |
| 863 | + file(&objects, "wide/0-first", "new"), | |
| 864 | + ]; | |
| 865 | + for edit in edits { | |
| 866 | + objects.take(); | |
| 867 | + let new = apply(&objects, base, std::slice::from_ref(&edit)).unwrap(); | |
| 868 | + let (reads, writes) = objects.take(); | |
| 869 | + costs.push((count, reads, writes)); | |
| 870 | + | |
| 871 | + // The same tree as building it from scratch. | |
| 872 | + let scratch = MemoryObjects::new(); | |
| 873 | + let mut all: Vec<Change> = files | |
| 874 | + .iter() | |
| 875 | + .filter(|change| change.path != edit.path) | |
| 876 | + .cloned() | |
| 877 | + .collect(); | |
| 878 | + if edit.op != ChangeOp::Delete { | |
| 879 | + all.push(edit.clone()); | |
| 880 | + } | |
| 881 | + assert_eq!(new, apply(&scratch, EMPTY_TREE, &all).unwrap()); | |
| 882 | + } | |
| 883 | + } | |
| 884 | + let most = |count| { | |
| 885 | + costs | |
| 886 | + .iter() | |
| 887 | + .filter(|(c, ..)| *c == count) | |
| 888 | + .fold((0, 0), |(r, w), (_, reads, writes)| { | |
| 889 | + (r.max(*reads), w.max(*writes)) | |
| 890 | + }) | |
| 891 | + }; | |
| 892 | + let (small, large) = (most(2_000), most(20_000)); | |
| 893 | + assert!(large.0 <= MOST_READ && large.1 <= MOST_WRITTEN, "{costs:?}"); | |
| 894 | + assert!(large.0 <= small.0 + 1, "{costs:?}"); | |
| 895 | + println!("files, objects read, objects written: {costs:?}"); | |
| 896 | + } | |
| 897 | + | |
| 902 | 898 | #[test] |
| 903 | 899 | fn deep_paths_need_little_stack() { |
| 904 | 900 | // The walks keep their own stacks. At the depth limit they fit in a |
modified crates/engine/src/land.rs +6 −4
| @@ -32,7 +32,7 @@ | ||
| 32 | 32 | }; |
| 33 | 33 | use unicode_normalization::UnicodeNormalization; |
| 34 | 34 | |
| 35 | -use crate::access::{Found, Trees, lookup, read_blob, read_changes, read_changeset}; | |
| 35 | +use crate::access::{Found, Trees, read_blob, read_changes, read_changeset}; | |
| 36 | 36 | use crate::ancestry::all_ancestors; |
| 37 | 37 | use crate::apply::{Applied, apply_sorted, write_nodes}; |
| 38 | 38 | use crate::commit::store_assembled; |
| @@ -626,10 +626,9 @@ | ||
| 626 | 626 | let slash = path[start..].iter().position(|byte| *byte == b'/'); |
| 627 | 627 | let end = slash.map_or(path.len(), |slash| start + slash); |
| 628 | 628 | let name = &path[start..end]; |
| 629 | - let entries = self.trees.read(dir)?; | |
| 630 | - match (lookup(&entries, name), slash) { | |
| 629 | + match (self.trees.entry(dir, name)?, slash) { | |
| 631 | 630 | (Some(EntryKind::Tree { tree }), Some(_)) => { |
| 632 | - dir = *tree; | |
| 631 | + dir = tree; | |
| 633 | 632 | start = end + 1; |
| 634 | 633 | } |
| 635 | 634 | // The head has this name already. |
| @@ -640,6 +639,9 @@ | ||
| 640 | 639 | return Ok(()); |
| 641 | 640 | } |
| 642 | 641 | let parent = &path[..start.saturating_sub(1)]; |
| 642 | + // A new name is compared with every name of the | |
| 643 | + // directory: only now is it read whole. | |
| 644 | + let entries = self.trees.read(dir)?; | |
| 643 | 645 | let index = self.folded_names(dir, &entries); |
| 644 | 646 | let others = index.get(&fold(name)).cloned().unwrap_or_default(); |
| 645 | 647 | for other in others { |
modified crates/engine/src/lib.rs +7 −3
| @@ -44,9 +44,13 @@ | ||
| 44 | 44 | //! [`apply`], [`diff`], [`admit`], [`land`] and [`merge`] read only the |
| 45 | 45 | //! directories on the changed paths, so their cost follows the size of the |
| 46 | 46 | //! change times the depth of the tree, plus the size of each directory they |
| 47 | -//! touch. The free ancestry functions walk history and are proportional to | |
| 48 | -//! the distance they cover; [`History`] reads derived data instead, so its | |
| 49 | -//! queries cost what they visit once that data exists. | |
| 47 | +//! touch. A large directory is split into nodes, and [`apply`], [`admit`], | |
| 48 | +//! [`entry_at`] and the lookups of [`land`] and [`merge`] read and write | |
| 49 | +//! only the nodes on the way to the names they need, so its size counts | |
| 50 | +//! only through its depth; [`diff`] reads both versions of each directory | |
| 51 | +//! that differs whole. The free ancestry functions walk history and are | |
| 52 | +//! proportional to the distance they cover; [`History`] reads derived data | |
| 53 | +//! instead, so its queries cost what they visit once that data exists. | |
| 50 | 54 | //! |
| 51 | 55 | //! [`Objects`]: braid_format::Objects |
| 52 | 56 |
modified crates/engine/src/testing.rs +30 −1
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | //! Helpers for the unit tests: an in-memory repository with short ways to |
| 5 | 5 | //! write files, trees and changesets, and to read them back. |
| 6 | 6 | |
| 7 | -use std::cell::RefCell; | |
| 7 | +use std::cell::{Cell, RefCell}; | |
| 8 | 8 | use std::collections::BTreeMap; |
| 9 | 9 | use std::convert::Infallible; |
| 10 | 10 | |
| @@ -43,6 +43,35 @@ | ||
| 43 | 43 | } |
| 44 | 44 | } |
| 45 | 45 | |
| 46 | +/// Objects in memory that count the objects read and written. | |
| 47 | +#[derive(Default)] | |
| 48 | +pub(crate) struct Counted { | |
| 49 | + pub(crate) objects: MemoryObjects, | |
| 50 | + pub(crate) reads: Cell<usize>, | |
| 51 | + pub(crate) writes: Cell<usize>, | |
| 52 | +} | |
| 53 | + | |
| 54 | +impl Counted { | |
| 55 | + /// The reads and writes since the last call, and starts counting again. | |
| 56 | + pub(crate) fn take(&self) -> (usize, usize) { | |
| 57 | + (self.reads.replace(0), self.writes.replace(0)) | |
| 58 | + } | |
| 59 | +} | |
| 60 | + | |
| 61 | +impl Objects for Counted { | |
| 62 | + type Error = Infallible; | |
| 63 | + | |
| 64 | + fn get(&self, id: &ObjectId) -> Result<Option<(Kind, Vec<u8>)>, Self::Error> { | |
| 65 | + self.reads.set(self.reads.get() + 1); | |
| 66 | + self.objects.get(id) | |
| 67 | + } | |
| 68 | + | |
| 69 | + fn put(&self, kind: Kind, payload: &[u8]) -> Result<ObjectId, Self::Error> { | |
| 70 | + self.writes.set(self.writes.get() + 1); | |
| 71 | + self.objects.put(kind, payload) | |
| 72 | + } | |
| 73 | +} | |
| 74 | + | |
| 46 | 75 | use crate::access::{EMPTY_TREE, read_blob, read_changeset, read_tree}; |
| 47 | 76 | use crate::apply::apply; |
| 48 | 77 | use crate::commit::commit; |
modified crates/format/src/lib.rs +2 −1
| @@ -25,5 +25,6 @@ | ||
| 25 | 25 | pub use name::{NameError, PathError, validate_name, validate_path}; |
| 26 | 26 | pub use objects::{MemoryObjects, Objects}; |
| 27 | 27 | pub use tree::{ |
| 28 | - Directory, Entry, EntryKind, GitId, Node, TreeError, build_directory, read_directory, | |
| 28 | + Directory, Entry, EntryEdit, EntryKind, GitId, NewNode, Node, NodeCache, TreeError, Updated, | |
| 29 | + build_directory, check_edits, find_entry, read_directory, update_directory, | |
| 29 | 30 | }; |
modified crates/format/src/tree.rs +1137 −89
| @@ -11,8 +11,17 @@ | ||
| 11 | 11 | //! [`MAX_NODE_ENTRIES`]. The same set of entries therefore always gives the |
| 12 | 12 | //! same nodes and the same root id, whatever order it was edited in, and an |
| 13 | 13 | //! edit only touches the nodes on its path. |
| 14 | - | |
| 14 | +//! | |
| 15 | +//! [`build_directory`] makes every node of a directory from all of its | |
| 16 | +//! entries, and [`read_directory`] reads them all back. [`find_entry`] and | |
| 17 | +//! [`update_directory`] work one path at a time instead: they read only the | |
| 18 | +//! nodes on the way to the names they look up or edit, so what they cost | |
| 19 | +//! follows the number of names and the depth of the directory, not its size. | |
| 20 | + | |
| 21 | +use core::cmp::Ordering; | |
| 15 | 22 | use core::fmt; |
| 23 | +use std::collections::HashMap; | |
| 24 | +use std::rc::Rc; | |
| 16 | 25 | |
| 17 | 26 | use crate::codec::{DecodeError, Reader, put_bytes, put_id, put_uv}; |
| 18 | 27 | use crate::id::{Kind, ObjectId}; |
| @@ -260,12 +269,16 @@ | ||
| 260 | 269 | |
| 261 | 270 | /// Checks one entry on its own: its name, and the symlink restriction. |
| 262 | 271 | pub fn validate_entry(entry: &Entry) -> Result<(), TreeError> { |
| 263 | - validate_name(&entry.name).map_err(|error| TreeError::Name { | |
| 264 | - name: entry.name.clone(), | |
| 272 | + check_entry(&entry.name, &entry.kind) | |
| 273 | +} | |
| 274 | + | |
| 275 | +fn check_entry(name: &[u8], kind: &EntryKind) -> Result<(), TreeError> { | |
| 276 | + validate_name(name).map_err(|error| TreeError::Name { | |
| 277 | + name: name.to_vec(), | |
| 265 | 278 | error, |
| 266 | 279 | })?; |
| 267 | - if matches!(entry.kind, EntryKind::Symlink { .. }) && forbidden_as_symlink(&entry.name) { | |
| 268 | - return Err(TreeError::SymlinkName(entry.name.clone())); | |
| 280 | + if matches!(kind, EntryKind::Symlink { .. }) && forbidden_as_symlink(name) { | |
| 281 | + return Err(TreeError::SymlinkName(name.to_vec())); | |
| 269 | 282 | } |
| 270 | 283 | Ok(()) |
| 271 | 284 | } |
| @@ -417,27 +430,186 @@ | ||
| 417 | 430 | } |
| 418 | 431 | } |
| 419 | 432 | |
| 420 | -/// Whether a node ends after an item named `name` that makes its size `count`. | |
| 421 | -fn ends_node(level: u8, name: &[u8], count: usize) -> bool { | |
| 422 | - if count >= MAX_NODE_ENTRIES { | |
| 423 | - return true; | |
| 433 | +/// Whether a node ends after an item that makes it hold `count` items. | |
| 434 | +/// `hit`, whether the item's name hashes below the threshold, is only asked | |
| 435 | +/// when it matters. | |
| 436 | +fn ends(count: usize, hit: impl FnOnce() -> bool) -> bool { | |
| 437 | + count >= MAX_NODE_ENTRIES || (count >= MIN_NODE_ENTRIES && hit()) | |
| 438 | +} | |
| 439 | + | |
| 440 | +/// The splitting rule, with one hasher kept for every name it looks at. | |
| 441 | +struct Splitter { | |
| 442 | + hasher: blake3::Hasher, | |
| 443 | +} | |
| 444 | + | |
| 445 | +impl Splitter { | |
| 446 | + fn new() -> Self { | |
| 447 | + Splitter { | |
| 448 | + hasher: blake3::Hasher::new_derive_key(SPLIT_CONTEXT), | |
| 449 | + } | |
| 450 | + } | |
| 451 | + | |
| 452 | + /// Whether `H(level, name)` falls below the threshold. | |
| 453 | + fn hit(&mut self, level: u8, name: &[u8]) -> bool { | |
| 454 | + self.hasher.reset(); | |
| 455 | + self.hasher.update(&[level]); | |
| 456 | + self.hasher.update(name); | |
| 457 | + let digest = self.hasher.finalize(); | |
| 458 | + let head = digest.as_bytes(); | |
| 459 | + u32::from_le_bytes([head[0], head[1], head[2], head[3]]) < SPLIT_THRESHOLD | |
| 460 | + } | |
| 461 | + | |
| 462 | + /// Whether a node of `level` ends after an item named `name` that makes | |
| 463 | + /// it hold `count` items. | |
| 464 | + fn ends(&mut self, level: u8, name: &[u8], count: usize) -> bool { | |
| 465 | + ends(count, || self.hit(level, name)) | |
| 466 | + } | |
| 467 | +} | |
| 468 | + | |
| 469 | +/// What the nodes of one level of a split directory hold: entries in the | |
| 470 | +/// leaves, references to the nodes below in internal nodes. | |
| 471 | +trait Item: Clone + PartialEq { | |
| 472 | + /// The name that orders items and that the splitting rule hashes. | |
| 473 | + fn name(&self) -> &[u8]; | |
| 474 | + /// How many entries of the directory it stands for. | |
| 475 | + fn entries(&self) -> u64; | |
| 476 | + /// The node of `level` that holds `items`. | |
| 477 | + fn node(level: u8, items: Vec<Self>) -> Node; | |
| 478 | + /// The items of `node`, if it holds this kind of item. | |
| 479 | + fn items(node: &Node) -> Option<&[Self]>; | |
| 480 | +} | |
| 481 | + | |
| 482 | +impl Item for Entry { | |
| 483 | + fn name(&self) -> &[u8] { | |
| 484 | + &self.name | |
| 485 | + } | |
| 486 | + | |
| 487 | + fn entries(&self) -> u64 { | |
| 488 | + 1 | |
| 489 | + } | |
| 490 | + | |
| 491 | + fn node(_: u8, items: Vec<Self>) -> Node { | |
| 492 | + Node::Leaf(items) | |
| 493 | + } | |
| 494 | + | |
| 495 | + fn items(node: &Node) -> Option<&[Self]> { | |
| 496 | + match node { | |
| 497 | + Node::Leaf(entries) => Some(entries), | |
| 498 | + _ => None, | |
| 499 | + } | |
| 500 | + } | |
| 501 | +} | |
| 502 | + | |
| 503 | +impl Item for Child { | |
| 504 | + fn name(&self) -> &[u8] { | |
| 505 | + &self.last_name | |
| 506 | + } | |
| 507 | + | |
| 508 | + fn entries(&self) -> u64 { | |
| 509 | + self.entry_count | |
| 510 | + } | |
| 511 | + | |
| 512 | + fn node(level: u8, items: Vec<Self>) -> Node { | |
| 513 | + Node::Internal { | |
| 514 | + level, | |
| 515 | + children: items, | |
| 516 | + } | |
| 517 | + } | |
| 518 | + | |
| 519 | + fn items(node: &Node) -> Option<&[Self]> { | |
| 520 | + match node { | |
| 521 | + Node::Internal { children, .. } => Some(children), | |
| 522 | + _ => None, | |
| 523 | + } | |
| 524 | + } | |
| 525 | +} | |
| 526 | + | |
| 527 | +/// A node cut by a [`Chunker`]: the reference a parent holds to it, and its | |
| 528 | +/// encoding. | |
| 529 | +struct Made { | |
| 530 | + child: Child, | |
| 531 | + bytes: Vec<u8>, | |
| 532 | +} | |
| 533 | + | |
| 534 | +/// Cuts the items of one level, given in name order, into nodes. | |
| 535 | +struct Chunker<I> { | |
| 536 | + level: u8, | |
| 537 | + /// The items of the node being filled. | |
| 538 | + run: Vec<I>, | |
| 539 | + made: Vec<Made>, | |
| 540 | +} | |
| 541 | + | |
| 542 | +impl<I: Item> Chunker<I> { | |
| 543 | + fn new(level: u8) -> Self { | |
| 544 | + Chunker { | |
| 545 | + level, | |
| 546 | + run: Vec::new(), | |
| 547 | + made: Vec::new(), | |
| 548 | + } | |
| 549 | + } | |
| 550 | + | |
| 551 | + /// How many items the node being filled holds with one more. | |
| 552 | + fn next_count(&self) -> usize { | |
| 553 | + self.run.len() + 1 | |
| 554 | + } | |
| 555 | + | |
| 556 | + /// Whether the last item ended a node, so that the next one starts a | |
| 557 | + /// new one. | |
| 558 | + fn at_boundary(&self) -> bool { | |
| 559 | + self.run.is_empty() | |
| 560 | + } | |
| 561 | + | |
| 562 | + /// Adds the next item, and ends its node after it if `cut`. | |
| 563 | + fn push(&mut self, item: I, cut: bool) { | |
| 564 | + self.run.push(item); | |
| 565 | + if cut { | |
| 566 | + self.cut(); | |
| 567 | + } | |
| 568 | + } | |
| 569 | + | |
| 570 | + /// Adds the next item, and ends its node where the splitting rule says. | |
| 571 | + fn add(&mut self, item: I, splitter: &mut Splitter) { | |
| 572 | + let cut = splitter.ends(self.level, item.name(), self.next_count()); | |
| 573 | + self.push(item, cut); | |
| 574 | + } | |
| 575 | + | |
| 576 | + /// Ends the node being filled, if it holds anything. | |
| 577 | + fn cut(&mut self) { | |
| 578 | + let Some(last) = self.run.last() else { | |
| 579 | + return; | |
| 580 | + }; | |
| 581 | + let last_name = last.name().to_vec(); | |
| 582 | + // Saturating: only references read from a corrupt directory could | |
| 583 | + // add up past the largest count. | |
| 584 | + let entry_count = self | |
| 585 | + .run | |
| 586 | + .iter() | |
| 587 | + .fold(0u64, |sum, item| sum.saturating_add(item.entries())); | |
| 588 | + let node = I::node(self.level, core::mem::take(&mut self.run)); | |
| 589 | + let bytes = node.encode(); | |
| 590 | + self.made.push(Made { | |
| 591 | + child: Child { | |
| 592 | + last_name, | |
| 593 | + node: ObjectId::hash(Kind::Tree, &bytes), | |
| 594 | + entry_count, | |
| 595 | + }, | |
| 596 | + bytes, | |
| 597 | + }); | |
| 424 | 598 | } |
| 425 | - if count < MIN_NODE_ENTRIES { | |
| 426 | - return false; | |
| 599 | + | |
| 600 | + /// Ends the last node, and returns every node cut, in order. | |
| 601 | + fn finish(mut self) -> Vec<Made> { | |
| 602 | + self.cut(); | |
| 603 | + self.made | |
| 427 | 604 | } |
| 428 | - let mut hasher = blake3::Hasher::new_derive_key(SPLIT_CONTEXT); | |
| 429 | - hasher.update(&[level]); | |
| 430 | - hasher.update(name); | |
| 431 | - let digest = hasher.finalize(); | |
| 432 | - let head = digest.as_bytes(); | |
| 433 | - u32::from_le_bytes([head[0], head[1], head[2], head[3]]) < SPLIT_THRESHOLD | |
| 434 | 605 | } |
| 435 | 606 | |
| 436 | -fn push_node(nodes: &mut Vec<(ObjectId, Vec<u8>)>, node: &Node) -> ObjectId { | |
| 437 | - let bytes = node.encode(); | |
| 438 | - let id = ObjectId::hash(Kind::Tree, &bytes); | |
| 439 | - nodes.push((id, bytes)); | |
| 440 | - id | |
| 607 | +/// One node of a directory built from scratch. | |
| 608 | +struct Built { | |
| 609 | + id: ObjectId, | |
| 610 | + bytes: Vec<u8>, | |
| 611 | + /// Whether it holds entries: a flat node or a leaf. | |
| 612 | + holds_entries: bool, | |
| 441 | 613 | } |
| 442 | 614 | |
| 443 | 615 | /// Builds the canonical nodes of a directory from its entries, in any order. |
| @@ -447,105 +619,792 @@ | ||
| 447 | 619 | for entry in &entries { |
| 448 | 620 | validate_entry(entry)?; |
| 449 | 621 | } |
| 622 | + let nodes = build_nodes(entries) | |
| 623 | + .into_iter() | |
| 624 | + .map(|node| (node.id, node.bytes)) | |
| 625 | + .collect(); | |
| 626 | + Ok(Directory { nodes }) | |
| 627 | +} | |
| 450 | 628 | |
| 451 | - let mut nodes = Vec::new(); | |
| 629 | +/// The canonical nodes of sorted, valid entries, children before parents. | |
| 630 | +fn build_nodes(entries: Vec<Entry>) -> Vec<Built> { | |
| 452 | 631 | if entries.len() <= MAX_FLAT_ENTRIES { |
| 453 | - push_node(&mut nodes, &Node::Flat(entries)); | |
| 454 | - return Ok(Directory { nodes }); | |
| 455 | - } | |
| 456 | - | |
| 457 | - // Leaves. | |
| 458 | - let total = entries.len(); | |
| 459 | - let mut children = Vec::new(); | |
| 460 | - let mut run = Vec::new(); | |
| 461 | - for (i, entry) in entries.into_iter().enumerate() { | |
| 462 | - let ends = ends_node(0, &entry.name, run.len() + 1); | |
| 463 | - run.push(entry); | |
| 464 | - if ends || i + 1 == total { | |
| 465 | - let last_name = run | |
| 466 | - .last() | |
| 467 | - .map(|e: &Entry| e.name.clone()) | |
| 468 | - .unwrap_or_default(); | |
| 469 | - let entry_count = run.len() as u64; | |
| 470 | - let node = push_node(&mut nodes, &Node::Leaf(core::mem::take(&mut run))); | |
| 471 | - children.push(Child { | |
| 472 | - last_name, | |
| 473 | - node, | |
| 474 | - entry_count, | |
| 475 | - }); | |
| 476 | - } | |
| 632 | + let bytes = Node::Flat(entries).encode(); | |
| 633 | + return vec![Built { | |
| 634 | + id: ObjectId::hash(Kind::Tree, &bytes), | |
| 635 | + bytes, | |
| 636 | + holds_entries: true, | |
| 637 | + }]; | |
| 477 | 638 | } |
| 478 | - | |
| 639 | + let mut splitter = Splitter::new(); | |
| 640 | + let mut nodes = Vec::new(); | |
| 641 | + let mut leaves = Chunker::new(0); | |
| 642 | + for entry in entries { | |
| 643 | + leaves.add(entry, &mut splitter); | |
| 644 | + } | |
| 645 | + let mut children = keep(&mut nodes, leaves.finish(), true); | |
| 479 | 646 | // Internal levels, until one node is left. |
| 480 | 647 | let mut level = 1u8; |
| 481 | 648 | while children.len() > 1 { |
| 482 | - let total = children.len(); | |
| 483 | - let mut parents = Vec::new(); | |
| 484 | - let mut run: Vec<Child> = Vec::new(); | |
| 485 | - for (i, child) in children.into_iter().enumerate() { | |
| 486 | - let ends = ends_node(level, &child.last_name, run.len() + 1); | |
| 487 | - run.push(child); | |
| 488 | - if ends || i + 1 == total { | |
| 489 | - let last_name = run.last().map(|c| c.last_name.clone()).unwrap_or_default(); | |
| 490 | - let entry_count = run.iter().map(|c| c.entry_count).sum(); | |
| 491 | - let node = push_node( | |
| 492 | - &mut nodes, | |
| 493 | - &Node::Internal { | |
| 494 | - level, | |
| 495 | - children: core::mem::take(&mut run), | |
| 496 | - }, | |
| 497 | - ); | |
| 498 | - parents.push(Child { | |
| 499 | - last_name, | |
| 500 | - node, | |
| 501 | - entry_count, | |
| 502 | - }); | |
| 503 | - } | |
| 649 | + let mut chunker = Chunker::new(level); | |
| 650 | + for child in children { | |
| 651 | + chunker.add(child, &mut splitter); | |
| 504 | 652 | } |
| 505 | - children = parents; | |
| 653 | + children = keep(&mut nodes, chunker.finish(), false); | |
| 506 | 654 | level += 1; |
| 507 | 655 | } |
| 508 | - Ok(Directory { nodes }) | |
| 656 | + nodes | |
| 657 | +} | |
| 658 | + | |
| 659 | +/// Moves the nodes of one level into `nodes`, and returns the references to | |
| 660 | +/// them, for the level above. | |
| 661 | +fn keep(nodes: &mut Vec<Built>, made: Vec<Made>, holds_entries: bool) -> Vec<Child> { | |
| 662 | + made.into_iter() | |
| 663 | + .map(|made| { | |
| 664 | + nodes.push(Built { | |
| 665 | + id: made.child.node, | |
| 666 | + bytes: made.bytes, | |
| 667 | + holds_entries, | |
| 668 | + }); | |
| 669 | + made.child | |
| 670 | + }) | |
| 671 | + .collect() | |
| 509 | 672 | } |
| 510 | 673 | |
| 511 | 674 | /// Reads every entry of the directory rooted at `root`, fetching nodes through |
| 512 | 675 | /// `fetch`, and checks that the nodes are exactly the canonical split of those |
| 513 | 676 | /// entries. |
| 677 | +/// | |
| 678 | +/// The check goes node by node instead of building the directory again. Each | |
| 679 | +/// node must hash to its id and be what the reference to it says: its level, | |
| 680 | +/// its last name and its number of entries. The entries must ascend from one | |
| 681 | +/// leaf to the next, and every node must end where the splitting rule ends | |
| 682 | +/// it, and nowhere before, except the last node of each level, which the end | |
| 683 | +/// of the directory ends. With a root of two children or more, over more | |
| 684 | +/// entries than a flat node holds, that is the canonical split. | |
| 514 | 685 | pub fn read_directory( |
| 515 | 686 | root: ObjectId, |
| 516 | 687 | mut fetch: impl FnMut(&ObjectId) -> Option<Vec<u8>>, |
| 517 | 688 | ) -> Result<Vec<Entry>, TreeError> { |
| 518 | - let mut entries = Vec::new(); | |
| 519 | - collect(root, &mut fetch, &mut entries, None)?; | |
| 520 | - if build_directory(entries.clone())?.root() != root { | |
| 521 | - return Err(TreeError::NotCanonical); | |
| 522 | - } | |
| 523 | - Ok(entries) | |
| 689 | + let (level, children) = match fetched(root, &mut fetch)? { | |
| 690 | + Node::Flat(entries) => return Ok(entries), | |
| 691 | + Node::Leaf(_) => return Err(TreeError::NotCanonical), | |
| 692 | + Node::Internal { level, children } => (level, children), | |
| 693 | + }; | |
| 694 | + let total = split_total(&children)?; | |
| 695 | + let mut whole = Whole { | |
| 696 | + fetch, | |
| 697 | + splitter: Splitter::new(), | |
| 698 | + last_name: children | |
| 699 | + .last() | |
| 700 | + .map(|child| child.last_name.clone()) | |
| 701 | + .unwrap_or_default(), | |
| 702 | + // The counts are checked as the nodes are read: do not trust them | |
| 703 | + // with a large allocation before. | |
| 704 | + entries: Vec::with_capacity(usize::try_from(total).map_or(0, |total| total.min(1 << 16))), | |
| 705 | + }; | |
| 706 | + whole.below(level, &children, true)?; | |
| 707 | + Ok(whole.entries) | |
| 524 | 708 | } |
| 525 | 709 | |
| 526 | -fn collect( | |
| 710 | +/// Fetches the node `id`, checks that its bytes hash to its id, and decodes | |
| 711 | +/// it. | |
| 712 | +fn fetched( | |
| 527 | 713 | id: ObjectId, |
| 528 | 714 | fetch: &mut impl FnMut(&ObjectId) -> Option<Vec<u8>>, |
| 529 | - entries: &mut Vec<Entry>, | |
| 530 | - expected_level: Option<u8>, | |
| 531 | -) -> Result<(), TreeError> { | |
| 715 | +) -> Result<Node, TreeError> { | |
| 532 | 716 | let bytes = fetch(&id).ok_or(TreeError::MissingNode(id))?; |
| 533 | 717 | if ObjectId::hash(Kind::Tree, &bytes) != id { |
| 534 | 718 | return Err(TreeError::NotCanonical); |
| 535 | 719 | } |
| 536 | - match (Node::decode(&bytes)?, expected_level) { | |
| 537 | - (Node::Flat(found), None) => entries.extend(found), | |
| 538 | - (Node::Leaf(found), Some(0)) => entries.extend(found), | |
| 539 | - (Node::Internal { level, children }, expected) if expected.is_none_or(|e| e == level) => { | |
| 540 | - for child in children { | |
| 541 | - collect(child.node, fetch, entries, Some(level - 1))?; | |
| 720 | + Node::decode(&bytes) | |
| 721 | +} | |
| 722 | + | |
| 723 | +/// A split directory being read whole, and checked node by node. | |
| 724 | +struct Whole<F> { | |
| 725 | + fetch: F, | |
| 726 | + splitter: Splitter, | |
| 727 | + /// The last name of the directory: the last node of every level ends | |
| 728 | + /// with it. | |
| 729 | + last_name: Vec<u8>, | |
| 730 | + entries: Vec<Entry>, | |
| 731 | +} | |
| 732 | + | |
| 733 | +impl<F: FnMut(&ObjectId) -> Option<Vec<u8>>> Whole<F> { | |
| 734 | + /// Checks where an internal node of `level` with `children` ends, then | |
| 735 | + /// reads every node below it, in order. | |
| 736 | + fn below(&mut self, level: u8, children: &[Child], last: bool) -> Result<(), TreeError> { | |
| 737 | + self.cuts(level, children, last)?; | |
| 738 | + for child in children { | |
| 739 | + let node = fetched(child.node, &mut self.fetch)?; | |
| 740 | + check_child(&node, level - 1, child)?; | |
| 741 | + let last = child.last_name == self.last_name; | |
| 742 | + match node { | |
| 743 | + Node::Leaf(entries) => { | |
| 744 | + self.cuts(0, &entries, last)?; | |
| 745 | + if let (Some(previous), Some(first)) = (self.entries.last(), entries.first()) | |
| 746 | + && first.name <= previous.name | |
| 747 | + { | |
| 748 | + return Err(TreeError::NotCanonical); | |
| 749 | + } | |
| 750 | + self.entries.extend(entries); | |
| 751 | + } | |
| 752 | + Node::Internal { level, children } => self.below(level, &children, last)?, | |
| 753 | + Node::Flat(_) => return Err(TreeError::NotCanonical), | |
| 754 | + } | |
| 755 | + } | |
| 756 | + Ok(()) | |
| 757 | + } | |
| 758 | + | |
| 759 | + /// Checks that a node of `level` that holds `items` ends where the | |
| 760 | + /// splitting rule ends it, and nowhere before. The last node of a level, | |
| 761 | + /// `last`, ends with the directory instead. | |
| 762 | + fn cuts<I: Item>(&mut self, level: u8, items: &[I], last: bool) -> Result<(), TreeError> { | |
| 763 | + for (index, item) in items.iter().enumerate() { | |
| 764 | + let end = index + 1 == items.len(); | |
| 765 | + if end && last { | |
| 766 | + break; | |
| 767 | + } | |
| 768 | + if self.splitter.ends(level, item.name(), index + 1) != end { | |
| 769 | + return Err(TreeError::NotCanonical); | |
| 542 | 770 | } |
| 543 | 771 | } |
| 544 | - _ => return Err(TreeError::NotCanonical), | |
| 772 | + Ok(()) | |
| 773 | + } | |
| 774 | +} | |
| 775 | + | |
| 776 | +// --------------------------------------------------------------------------- | |
| 777 | +// One path at a time | |
| 778 | + | |
| 779 | +/// One edit of a directory: the entry a name gets, or its removal. | |
| 780 | +#[derive(Clone, Debug, PartialEq, Eq)] | |
| 781 | +pub struct EntryEdit { | |
| 782 | + /// The name. | |
| 783 | + pub name: Vec<u8>, | |
| 784 | + /// What the name becomes; `None` removes it. Removing a name the | |
| 785 | + /// directory does not have changes nothing. | |
| 786 | + pub kind: Option<EntryKind>, | |
| 787 | +} | |
| 788 | + | |
| 789 | +/// Checks edits on their own: names strictly ascending, and every entry they | |
| 790 | +/// set valid. | |
| 791 | +pub fn check_edits(edits: &[EntryEdit]) -> Result<(), TreeError> { | |
| 792 | + check_ascending(edits.iter().map(|edit| edit.name.as_slice()))?; | |
| 793 | + for edit in edits { | |
| 794 | + if let Some(kind) = &edit.kind { | |
| 795 | + check_entry(&edit.name, kind)?; | |
| 796 | + } | |
| 545 | 797 | } |
| 546 | 798 | Ok(()) |
| 547 | 799 | } |
| 548 | 800 | |
| 801 | +/// A node that an update of a directory made, and that the directory did not | |
| 802 | +/// have before. | |
| 803 | +#[derive(Clone, Debug, PartialEq, Eq)] | |
| 804 | +pub struct NewNode { | |
| 805 | + /// Its id. | |
| 806 | + pub id: ObjectId, | |
| 807 | + /// Its encoding. | |
| 808 | + pub bytes: Vec<u8>, | |
| 809 | + /// The node of the directory before the update that it most likely | |
| 810 | + /// replaces: a hint for a store that may keep it as a difference from | |
| 811 | + /// that node, as [`Objects::put_similar`](crate::Objects::put_similar) | |
| 812 | + /// takes. | |
| 813 | + pub similar: Option<ObjectId>, | |
| 814 | +} | |
| 815 | + | |
| 816 | +/// A directory after an update. | |
| 817 | +#[derive(Clone, Debug, PartialEq, Eq)] | |
| 818 | +pub struct Updated { | |
| 819 | + /// Its id: the id of its root node. | |
| 820 | + pub root: ObjectId, | |
| 821 | + /// How many entries it holds. | |
| 822 | + pub entries: u64, | |
| 823 | + /// Its nodes that the directory before the update did not have, children | |
| 824 | + /// before parents. With the nodes it kept, they are exactly the nodes | |
| 825 | + /// that [`build_directory`] makes of its entries. | |
| 826 | + pub nodes: Vec<NewNode>, | |
| 827 | +} | |
| 828 | + | |
| 829 | +/// Nodes of directories, each fetched, checked against its id and decoded | |
| 830 | +/// once, for the readers that go one path at a time. | |
| 831 | +#[derive(Debug, Default)] | |
| 832 | +pub struct NodeCache { | |
| 833 | + nodes: HashMap<ObjectId, Rc<Node>>, | |
| 834 | +} | |
| 835 | + | |
| 836 | +impl NodeCache { | |
| 837 | + /// An empty cache. | |
| 838 | + pub fn new() -> Self { | |
| 839 | + Self::default() | |
| 840 | + } | |
| 841 | + | |
| 842 | + /// How many nodes it holds: each was fetched once. | |
| 843 | + pub fn len(&self) -> usize { | |
| 844 | + self.nodes.len() | |
| 845 | + } | |
| 846 | + | |
| 847 | + /// Whether it holds no node. | |
| 848 | + pub fn is_empty(&self) -> bool { | |
| 849 | + self.nodes.is_empty() | |
| 850 | + } | |
| 851 | + | |
| 852 | + /// The node `id`. The first time, it is fetched through `fetch`, checked | |
| 853 | + /// against its id and decoded. | |
| 854 | + pub fn get( | |
| 855 | + &mut self, | |
| 856 | + id: ObjectId, | |
| 857 | + fetch: &mut impl FnMut(&ObjectId) -> Option<Vec<u8>>, | |
| 858 | + ) -> Result<Rc<Node>, TreeError> { | |
| 859 | + if let Some(node) = self.nodes.get(&id) { | |
| 860 | + return Ok(Rc::clone(node)); | |
| 861 | + } | |
| 862 | + let node = Rc::new(fetched(id, fetch)?); | |
| 863 | + self.nodes.insert(id, Rc::clone(&node)); | |
| 864 | + Ok(node) | |
| 865 | + } | |
| 866 | +} | |
| 867 | + | |
| 868 | +/// The entry named `name` in the directory whose root node is `root`, or | |
| 869 | +/// `None` if it has none. | |
| 870 | +/// | |
| 871 | +/// A split directory is searched from the root down: each internal node leads | |
| 872 | +/// to the child whose last name is the first at or after `name`, so only the | |
| 873 | +/// nodes on that path are read. Each of them is checked against its id and | |
| 874 | +/// against the reference that leads to it: its level, its last name and its | |
| 875 | +/// number of entries. Whether the directory as a whole is the canonical split | |
| 876 | +/// of its entries is what [`read_directory`] checks, by reading all of it. | |
| 877 | +pub fn find_entry( | |
| 878 | + cache: &mut NodeCache, | |
| 879 | + root: ObjectId, | |
| 880 | + name: &[u8], | |
| 881 | + mut fetch: impl FnMut(&ObjectId) -> Option<Vec<u8>>, | |
| 882 | +) -> Result<Option<EntryKind>, TreeError> { | |
| 883 | + let mut node = cache.get(root, &mut fetch)?; | |
| 884 | + match &*node { | |
| 885 | + Node::Flat(entries) => return Ok(search(entries, name)), | |
| 886 | + Node::Leaf(_) => return Err(TreeError::NotCanonical), | |
| 887 | + Node::Internal { children, .. } => { | |
| 888 | + split_total(children)?; | |
| 889 | + } | |
| 890 | + } | |
| 891 | + loop { | |
| 892 | + let (level, children) = match &*node { | |
| 893 | + Node::Leaf(entries) => return Ok(search(entries, name)), | |
| 894 | + Node::Internal { level, children } => (*level, children), | |
| 895 | + Node::Flat(_) => return Err(TreeError::NotCanonical), | |
| 896 | + }; | |
| 897 | + let index = children.partition_point(|child| child.last_name.as_slice() < name); | |
| 898 | + let Some(child) = children.get(index) else { | |
| 899 | + // After the last name of the directory. | |
| 900 | + return Ok(None); | |
| 901 | + }; | |
| 902 | + let below = cache.get(child.node, &mut fetch)?; | |
| 903 | + check_child(&below, level - 1, child)?; | |
| 904 | + node = below; | |
| 905 | + } | |
| 906 | +} | |
| 907 | + | |
| 908 | +/// Applies `edits`, sorted by name, to the directory whose root node is | |
| 909 | +/// `root`, and returns the directory they make: its root, its number of | |
| 910 | +/// entries, and the nodes to store. The result is exactly what | |
| 911 | +/// [`build_directory`] makes of the edited entries, node for node. | |
| 912 | +/// | |
| 913 | +/// A flat directory is built again from its entries. A split one is updated | |
| 914 | +/// in place, one run of leaves at a time. A run starts at the leaf that holds | |
| 915 | +/// the first name left to edit, or would hold it: every boundary before it is | |
| 916 | +/// unchanged, since where a node ends depends only on the names up to there. The run | |
| 917 | +/// is cut into new leaves by the splitting rule, edits included, and it goes | |
| 918 | +/// on into the following leaves until a new leaf ends exactly where an old | |
| 919 | +/// one ended: from there the rule sees the same names from the same start, | |
| 920 | +/// so every following leaf is unchanged, up to the next name to edit. The | |
| 921 | +/// new leaves replace the old ones of the run in the level above, which is | |
| 922 | +/// updated the same way, up to the root. Only the nodes of the runs, and the | |
| 923 | +/// nodes on the paths that lead to them, are read. A directory that grows | |
| 924 | +/// past [`MAX_FLAT_ENTRIES`] entries is split, and one that shrinks to that | |
| 925 | +/// many or fewer is read whole and made flat again. | |
| 926 | +/// | |
| 927 | +/// The edits are checked before any node is read: an invalid one is an | |
| 928 | +/// error. Every node read is checked against its id and the reference that | |
| 929 | +/// leads to it, and the old boundaries inside the runs are checked against | |
| 930 | +/// the splitting rule; the rest of the directory is assumed canonical, as | |
| 931 | +/// every directory this crate builds is. | |
| 932 | +pub fn update_directory( | |
| 933 | + cache: &mut NodeCache, | |
| 934 | + root: ObjectId, | |
| 935 | + edits: &[EntryEdit], | |
| 936 | + mut fetch: impl FnMut(&ObjectId) -> Option<Vec<u8>>, | |
| 937 | +) -> Result<Updated, TreeError> { | |
| 938 | + check_edits(edits)?; | |
| 939 | + let top = cache.get(root, &mut fetch)?; | |
| 940 | + match &*top { | |
| 941 | + Node::Flat(entries) => { | |
| 942 | + // An empty node is nothing for a store to start from. | |
| 943 | + let similar = (!entries.is_empty()).then_some(root); | |
| 944 | + Ok(rebuilt( | |
| 945 | + root, | |
| 946 | + similar, | |
| 947 | + merge_items(entries.iter().cloned(), entry_changes(edits)), | |
| 948 | + )) | |
| 949 | + } | |
| 950 | + Node::Leaf(_) => Err(TreeError::NotCanonical), | |
| 951 | + Node::Internal { level, children } => { | |
| 952 | + let entry_count = split_total(children)?; | |
| 953 | + let last_name = children | |
| 954 | + .last() | |
| 955 | + .map(|child| child.last_name.clone()) | |
| 956 | + .unwrap_or_default(); | |
| 957 | + Split { | |
| 958 | + cache, | |
| 959 | + fetch: &mut fetch, | |
| 960 | + root: Child { | |
| 961 | + last_name, | |
| 962 | + node: root, | |
| 963 | + entry_count, | |
| 964 | + }, | |
| 965 | + height: *level, | |
| 966 | + splitter: Splitter::new(), | |
| 967 | + made: Vec::new(), | |
| 968 | + } | |
| 969 | + .update(edits) | |
| 970 | + } | |
| 971 | + } | |
| 972 | +} | |
| 973 | + | |
| 974 | +/// The entry named `name` among sorted entries. | |
| 975 | +fn search(entries: &[Entry], name: &[u8]) -> Option<EntryKind> { | |
| 976 | + entries | |
| 977 | + .binary_search_by(|entry| entry.name.as_slice().cmp(name)) | |
| 978 | + .ok() | |
| 979 | + .map(|index| entries[index].kind.clone()) | |
| 980 | +} | |
| 981 | + | |
| 982 | +/// The number of entries under a split directory's root, whose children | |
| 983 | +/// are `children`: it has at least two, else the one below would be the | |
| 984 | +/// root, and more entries than a flat node holds. | |
| 985 | +fn split_total(children: &[Child]) -> Result<u64, TreeError> { | |
| 986 | + let total = children | |
| 987 | + .iter() | |
| 988 | + .try_fold(0u64, |sum, child| sum.checked_add(child.entry_count)); | |
| 989 | + match total { | |
| 990 | + Some(total) if children.len() >= 2 && total > MAX_FLAT_ENTRIES as u64 => Ok(total), | |
| 991 | + _ => Err(TreeError::NotCanonical), | |
| 992 | + } | |
| 993 | +} | |
| 994 | + | |
| 995 | +/// Checks that `node`, reached through `child`, is what that reference says: | |
| 996 | +/// a node of `level`, with the same last name and number of entries. | |
| 997 | +fn check_child(node: &Node, level: u8, child: &Child) -> Result<(), TreeError> { | |
| 998 | + let (last, count) = match node { | |
| 999 | + Node::Leaf(entries) if level == 0 => ( | |
| 1000 | + entries.last().map(|entry| entry.name.as_slice()), | |
| 1001 | + Some(entries.len() as u64), | |
| 1002 | + ), | |
| 1003 | + Node::Internal { | |
| 1004 | + level: found, | |
| 1005 | + children, | |
| 1006 | + } if *found == level => ( | |
| 1007 | + children.last().map(|child| child.last_name.as_slice()), | |
| 1008 | + children | |
| 1009 | + .iter() | |
| 1010 | + .try_fold(0u64, |sum, child| sum.checked_add(child.entry_count)), | |
| 1011 | + ), | |
| 1012 | + _ => return Err(TreeError::NotCanonical), | |
| 1013 | + }; | |
| 1014 | + if last == Some(child.last_name.as_slice()) && count == Some(child.entry_count) { | |
| 1015 | + Ok(()) | |
| 1016 | + } else { | |
| 1017 | + Err(TreeError::NotCanonical) | |
| 1018 | + } | |
| 1019 | +} | |
| 1020 | + | |
| 1021 | +/// Edits as changes to the items of the leaf level. | |
| 1022 | +fn entry_changes(edits: &[EntryEdit]) -> Vec<(Vec<u8>, Option<Entry>)> { | |
| 1023 | + edits | |
| 1024 | + .iter() | |
| 1025 | + .map(|edit| { | |
| 1026 | + let entry = edit.kind.clone().map(|kind| Entry { | |
| 1027 | + name: edit.name.clone(), | |
| 1028 | + kind, | |
| 1029 | + }); | |
| 1030 | + (edit.name.clone(), entry) | |
| 1031 | + }) | |
| 1032 | + .collect() | |
| 1033 | +} | |
| 1034 | + | |
| 1035 | +/// Sorted items after sorted changes, each of which sets the item of a name | |
| 1036 | +/// or removes it. | |
| 1037 | +fn merge_items<I: Item>( | |
| 1038 | + old: impl IntoIterator<Item = I>, | |
| 1039 | + changes: impl IntoIterator<Item = (Vec<u8>, Option<I>)>, | |
| 1040 | +) -> Vec<I> { | |
| 1041 | + let mut merged = Vec::new(); | |
| 1042 | + let mut old = old.into_iter().peekable(); | |
| 1043 | + for (name, new) in changes { | |
| 1044 | + while let Some(item) = old.next_if(|item| item.name() < name.as_slice()) { | |
| 1045 | + merged.push(item); | |
| 1046 | + } | |
| 1047 | + old.next_if(|item| item.name() == name.as_slice()); | |
| 1048 | + merged.extend(new); | |
| 1049 | + } | |
| 1050 | + merged.extend(old); | |
| 1051 | + merged | |
| 1052 | +} | |
| 1053 | + | |
| 1054 | +/// The directory of `entries`, sorted and valid, built from scratch to | |
| 1055 | +/// replace the one whose root was `old_root`: every node but that root, the | |
| 1056 | +/// ones that hold entries paired with `similar`. | |
| 1057 | +fn rebuilt(old_root: ObjectId, similar: Option<ObjectId>, entries: Vec<Entry>) -> Updated { | |
| 1058 | + let count = entries.len() as u64; | |
| 1059 | + let built = build_nodes(entries); | |
| 1060 | + let root = built.last().map_or(old_root, |node| node.id); | |
| 1061 | + let nodes = built | |
| 1062 | + .into_iter() | |
| 1063 | + .filter(|node| node.id != old_root) | |
| 1064 | + .map(|node| NewNode { | |
| 1065 | + similar: similar.filter(|_| node.holds_entries), | |
| 1066 | + id: node.id, | |
| 1067 | + bytes: node.bytes, | |
| 1068 | + }) | |
| 1069 | + .collect(); | |
| 1070 | + Updated { | |
| 1071 | + root, | |
| 1072 | + entries: count, | |
| 1073 | + nodes, | |
| 1074 | + } | |
| 1075 | +} | |
| 1076 | + | |
| 1077 | +/// The changes to the items of one level: the item each name gets, or its | |
| 1078 | +/// removal, in name order. | |
| 1079 | +type ItemChanges<I> = Vec<(Vec<u8>, Option<I>)>; | |
| 1080 | + | |
| 1081 | +/// A split directory being updated. | |
| 1082 | +struct Split<'c, F> { | |
| 1083 | + cache: &'c mut NodeCache, | |
| 1084 | + fetch: F, | |
| 1085 | + /// The reference to its root before the update. | |
| 1086 | + root: Child, | |
| 1087 | + /// The level of that root. | |
| 1088 | + height: u8, | |
| 1089 | + splitter: Splitter, | |
| 1090 | + /// The nodes made so far that the directory did not have, children | |
| 1091 | + /// before parents, with their level and the node each most likely | |
| 1092 | + /// replaces. | |
| 1093 | + made: Vec<(u8, Made, Option<ObjectId>)>, | |
| 1094 | +} | |
| 1095 | + | |
| 1096 | +impl<F: FnMut(&ObjectId) -> Option<Vec<u8>>> Split<'_, F> { | |
| 1097 | + fn node(&mut self, id: ObjectId) -> Result<Rc<Node>, TreeError> { | |
| 1098 | + self.cache.get(id, &mut self.fetch) | |
| 1099 | + } | |
| 1100 | + | |
| 1101 | + fn update(mut self, edits: &[EntryEdit]) -> Result<Updated, TreeError> { | |
| 1102 | + let (mut changes, gained) = self.level::<Entry>(0, entry_changes(edits))?; | |
| 1103 | + let entries = i128::from(self.root.entry_count) + gained; | |
| 1104 | + if entries <= MAX_FLAT_ENTRIES as i128 { | |
| 1105 | + // Few enough entries for one flat node: read them all. | |
| 1106 | + let (old, largest) = self.entries()?; | |
| 1107 | + return Ok(rebuilt( | |
| 1108 | + self.root.node, | |
| 1109 | + largest, | |
| 1110 | + merge_items(old, entry_changes(edits)), | |
| 1111 | + )); | |
| 1112 | + } | |
| 1113 | + let entries = u64::try_from(entries).map_err(|_| TreeError::NotCanonical)?; | |
| 1114 | + for level in 1..self.height { | |
| 1115 | + if changes.is_empty() { | |
| 1116 | + // No node changed below this level, so none above it does. | |
| 1117 | + break; | |
| 1118 | + } | |
| 1119 | + changes = self.level::<Child>(level, changes)?.0; | |
| 1120 | + } | |
| 1121 | + if changes.is_empty() { | |
| 1122 | + // Edits that set names to the entries they had. | |
| 1123 | + debug_assert!(self.made.is_empty()); | |
| 1124 | + return Ok(Updated { | |
| 1125 | + root: self.root.node, | |
| 1126 | + entries, | |
| 1127 | + nodes: Vec::new(), | |
| 1128 | + }); | |
| 1129 | + } | |
| 1130 | + | |
| 1131 | + // The old root is the only node of its level, so the level is cut | |
| 1132 | + // again whole, and so is every level above it, until one node is left. | |
| 1133 | + let old_root = self.root.node; | |
| 1134 | + let node = self.node(old_root)?; | |
| 1135 | + let children = Child::items(&node).ok_or(TreeError::NotCanonical)?; | |
| 1136 | + let mut level = self.height; | |
| 1137 | + let mut chunker = Chunker::new(level); | |
| 1138 | + for child in merge_items(children.iter().cloned(), changes) { | |
| 1139 | + chunker.add(child, &mut self.splitter); | |
| 1140 | + } | |
| 1141 | + let mut top = self.record(level, chunker.finish(), Some(old_root)); | |
| 1142 | + while top.len() > 1 { | |
| 1143 | + level = level.checked_add(1).ok_or(TreeError::NotCanonical)?; | |
| 1144 | + let mut chunker = Chunker::new(level); | |
| 1145 | + for child in top { | |
| 1146 | + chunker.add(child, &mut self.splitter); | |
| 1147 | + } | |
| 1148 | + top = self.record(level, chunker.finish(), None); | |
| 1149 | + } | |
| 1150 | + let mut root = top.pop().ok_or(TreeError::NotCanonical)?; | |
| 1151 | + // A root with one child is not one: the first level with one node | |
| 1152 | + // holds the root, so the levels that lost all but one node go. | |
| 1153 | + while level > 0 { | |
| 1154 | + let children = self.children_of(&root, level)?; | |
| 1155 | + if children.len() != 1 { | |
| 1156 | + break; | |
| 1157 | + } | |
| 1158 | + root = children.into_iter().next().ok_or(TreeError::NotCanonical)?; | |
| 1159 | + level -= 1; | |
| 1160 | + } | |
| 1161 | + if level == 0 || root.entry_count != entries { | |
| 1162 | + return Err(TreeError::NotCanonical); | |
| 1163 | + } | |
| 1164 | + let nodes = self | |
| 1165 | + .made | |
| 1166 | + .into_iter() | |
| 1167 | + .filter(|(made_level, ..)| *made_level <= level) | |
| 1168 | + .map(|(_, made, similar)| NewNode { | |
| 1169 | + id: made.child.node, | |
| 1170 | + bytes: made.bytes, | |
| 1171 | + similar, | |
| 1172 | + }) | |
| 1173 | + .collect(); | |
| 1174 | + Ok(Updated { | |
| 1175 | + root: root.node, | |
| 1176 | + entries, | |
| 1177 | + nodes, | |
| 1178 | + }) | |
| 1179 | + } | |
| 1180 | + | |
| 1181 | + /// Keeps the nodes a whole level was cut into, the ones that are new | |
| 1182 | + /// paired with `similar`, and returns the references to all of them. | |
| 1183 | + fn record(&mut self, level: u8, made: Vec<Made>, similar: Option<ObjectId>) -> Vec<Child> { | |
| 1184 | + made.into_iter() | |
| 1185 | + .map(|made| { | |
| 1186 | + let child = made.child.clone(); | |
| 1187 | + if Some(child.node) != similar { | |
| 1188 | + self.made.push((level, made, similar)); | |
| 1189 | + } | |
| 1190 | + child | |
| 1191 | + }) | |
| 1192 | + .collect() | |
| 1193 | + } | |
| 1194 | + | |
| 1195 | + /// The children of the internal node of `level` that `node` refers to, | |
| 1196 | + /// made by this update or read from the directory. | |
| 1197 | + fn children_of(&mut self, node: &Child, level: u8) -> Result<Vec<Child>, TreeError> { | |
| 1198 | + let found = match self | |
| 1199 | + .made | |
| 1200 | + .iter() | |
| 1201 | + .find(|(_, made, _)| made.child.node == node.node) | |
| 1202 | + { | |
| 1203 | + Some((_, made, _)) => Rc::new(Node::decode(&made.bytes)?), | |
| 1204 | + None => self.node(node.node)?, | |
| 1205 | + }; | |
| 1206 | + check_child(&found, level, node)?; | |
| 1207 | + Child::items(&found) | |
| 1208 | + .map(<[Child]>::to_vec) | |
| 1209 | + .ok_or(TreeError::NotCanonical) | |
| 1210 | + } | |
| 1211 | + | |
| 1212 | + /// The node of `level` before the update that holds `name`, or would: | |
| 1213 | + /// the first whose last name is at or after `name`, or the last node of | |
| 1214 | + /// the level for a name after every other. With `after`, the first whose | |
| 1215 | + /// last name is after `name`, if there is one. | |
| 1216 | + fn locate(&mut self, level: u8, name: &[u8], after: bool) -> Result<Option<Child>, TreeError> { | |
| 1217 | + if after && name >= self.root.last_name.as_slice() { | |
| 1218 | + return Ok(None); | |
| 1219 | + } | |
| 1220 | + let mut current = self.root.clone(); | |
| 1221 | + let mut at = self.height; | |
| 1222 | + while at > level { | |
| 1223 | + let node = self.node(current.node)?; | |
| 1224 | + check_child(&node, at, ¤t)?; | |
| 1225 | + let children = Child::items(&node).ok_or(TreeError::NotCanonical)?; | |
| 1226 | + let index = children.partition_point(|child| { | |
| 1227 | + if after { | |
| 1228 | + child.last_name.as_slice() <= name | |
| 1229 | + } else { | |
| 1230 | + child.last_name.as_slice() < name | |
| 1231 | + } | |
| 1232 | + }); | |
| 1233 | + current = match (children.get(index), after) { | |
| 1234 | + (Some(child), _) => child.clone(), | |
| 1235 | + (None, false) => children.last().ok_or(TreeError::NotCanonical)?.clone(), | |
| 1236 | + // The node above ends after `name`, so one of its children does. | |
| 1237 | + (None, true) => return Err(TreeError::NotCanonical), | |
| 1238 | + }; | |
| 1239 | + at -= 1; | |
| 1240 | + } | |
| 1241 | + Ok(Some(current)) | |
| 1242 | + } | |
| 1243 | + | |
| 1244 | + /// Applies `changes` to the level `level`, below the root, one run at a | |
| 1245 | + /// time, and returns the changes this makes to the level above, with | |
| 1246 | + /// how many entries the directory gained (lost, if negative). | |
| 1247 | + fn level<I: Item>( | |
| 1248 | + &mut self, | |
| 1249 | + level: u8, | |
| 1250 | + changes: ItemChanges<I>, | |
| 1251 | + ) -> Result<(ItemChanges<Child>, i128), TreeError> { | |
| 1252 | + let mut above = Vec::new(); | |
| 1253 | + let mut gained = 0i128; | |
| 1254 | + let mut changes = changes.into_iter().peekable(); | |
| 1255 | + while let Some((name, _)) = changes.peek() { | |
| 1256 | + // The run starts at the node that holds the first name left to | |
| 1257 | + // change, or would: every boundary before it stays. | |
| 1258 | + let mut old = self | |
| 1259 | + .locate(level, name, false)? | |
| 1260 | + .ok_or(TreeError::NotCanonical)?; | |
| 1261 | + let mut chunker = Chunker::new(level); | |
| 1262 | + let mut replaced: Vec<Child> = Vec::new(); | |
| 1263 | + loop { | |
| 1264 | + let node = self.node(old.node)?; | |
| 1265 | + check_child(&node, level, &old)?; | |
| 1266 | + let items = I::items(&node).ok_or(TreeError::NotCanonical)?; | |
| 1267 | + if let (Some(previous), Some(first)) = (replaced.last(), items.first()) | |
| 1268 | + && first.name() <= previous.last_name.as_slice() | |
| 1269 | + { | |
| 1270 | + return Err(TreeError::NotCanonical); | |
| 1271 | + } | |
| 1272 | + // The last node of the level also takes every name after it. | |
| 1273 | + let last = old.last_name == self.root.last_name; | |
| 1274 | + let mut index = 0; | |
| 1275 | + loop { | |
| 1276 | + let change = changes | |
| 1277 | + .peek() | |
| 1278 | + .map(|(name, _)| name.as_slice()) | |
| 1279 | + .filter(|name| last || *name <= old.last_name.as_slice()); | |
| 1280 | + let order = match (items.get(index), change) { | |
| 1281 | + (None, None) => break, | |
| 1282 | + (Some(_), None) => Ordering::Less, | |
| 1283 | + (None, Some(_)) => Ordering::Greater, | |
| 1284 | + (Some(item), Some(name)) => item.name().cmp(name), | |
| 1285 | + }; | |
| 1286 | + if order == Ordering::Greater { | |
| 1287 | + // A name the node does not have. | |
| 1288 | + if let Some((name, Some(new))) = changes.next() { | |
| 1289 | + gained += i128::from(new.entries()); | |
| 1290 | + let cut = self.splitter.ends(level, &name, chunker.next_count()); | |
| 1291 | + chunker.push(new, cut); | |
| 1292 | + } | |
| 1293 | + continue; | |
| 1294 | + } | |
| 1295 | + let item = &items[index]; | |
| 1296 | + index += 1; | |
| 1297 | + // The same name gives the same hash: compute it once, for | |
| 1298 | + // the old boundary and for the new one. | |
| 1299 | + let mut hit = None; | |
| 1300 | + let splitter = &mut self.splitter; | |
| 1301 | + let mut hit_of = | |
| 1302 | + || *hit.get_or_insert_with(|| splitter.hit(level, item.name())); | |
| 1303 | + let ended = ends(index, &mut hit_of); | |
| 1304 | + let boundary = match (index == items.len(), last) { | |
| 1305 | + (false, _) => Some(false), | |
| 1306 | + (true, false) => Some(true), | |
| 1307 | + // The end of the directory ends the last node anyway. | |
| 1308 | + (true, true) => None, | |
| 1309 | + }; | |
| 1310 | + if boundary.is_some_and(|boundary| boundary != ended) { | |
| 1311 | + return Err(TreeError::NotCanonical); | |
| 1312 | + } | |
| 1313 | + let new = match order { | |
| 1314 | + Ordering::Equal => { | |
| 1315 | + let (_, new) = changes.next().ok_or(TreeError::NotCanonical)?; | |
| 1316 | + gained -= i128::from(item.entries()); | |
| 1317 | + if let Some(new) = &new { | |
| 1318 | + gained += i128::from(new.entries()); | |
| 1319 | + } | |
| 1320 | + new | |
| 1321 | + } | |
| 1322 | + _ => Some(item.clone()), | |
| 1323 | + }; | |
| 1324 | + if let Some(new) = new { | |
| 1325 | + let cut = ends(chunker.next_count(), &mut hit_of); | |
| 1326 | + chunker.push(new, cut); | |
| 1327 | + } | |
| 1328 | + } | |
| 1329 | + replaced.push(old); | |
| 1330 | + if chunker.at_boundary() || last { | |
| 1331 | + // Cut where an old node was cut, or at the end of the | |
| 1332 | + // level: what follows is unchanged. | |
| 1333 | + break; | |
| 1334 | + } | |
| 1335 | + let after = replaced | |
| 1336 | + .last() | |
| 1337 | + .map(|node| node.last_name.clone()) | |
| 1338 | + .unwrap_or_default(); | |
| 1339 | + old = self | |
| 1340 | + .locate(level, &after, true)? | |
| 1341 | + .ok_or(TreeError::NotCanonical)?; | |
| 1342 | + } | |
| 1343 | + self.settle(level, &replaced, chunker.finish(), &mut above); | |
| 1344 | + } | |
| 1345 | + Ok((above, gained)) | |
| 1346 | + } | |
| 1347 | + | |
| 1348 | + /// Keeps the nodes a run of `level` made in place of the `replaced` ones, | |
| 1349 | + /// each paired with the old node that held its last name or would have, | |
| 1350 | + /// and adds what this changes to `above`, the level above. | |
| 1351 | + fn settle( | |
| 1352 | + &mut self, | |
| 1353 | + level: u8, | |
| 1354 | + replaced: &[Child], | |
| 1355 | + made: Vec<Made>, | |
| 1356 | + above: &mut ItemChanges<Child>, | |
| 1357 | + ) { | |
| 1358 | + let mut old = replaced.iter().peekable(); | |
| 1359 | + for made in made { | |
| 1360 | + let name = made.child.last_name.as_slice(); | |
| 1361 | + while let Some(gone) = old.next_if(|old| old.last_name.as_slice() < name) { | |
| 1362 | + above.push((gone.last_name.clone(), None)); | |
| 1363 | + } | |
| 1364 | + if old | |
| 1365 | + .next_if(|old| old.last_name.as_slice() == name) | |
| 1366 | + .is_some_and(|old| *old == made.child) | |
| 1367 | + { | |
| 1368 | + // The same node as before. | |
| 1369 | + continue; | |
| 1370 | + } | |
| 1371 | + let similar = replaced | |
| 1372 | + .iter() | |
| 1373 | + .find(|old| old.last_name.as_slice() >= name) | |
| 1374 | + .or(replaced.last()) | |
| 1375 | + .map(|old| old.node); | |
| 1376 | + above.push((made.child.last_name.clone(), Some(made.child.clone()))); | |
| 1377 | + self.made.push((level, made, similar)); | |
| 1378 | + } | |
| 1379 | + above.extend(old.map(|gone| (gone.last_name.clone(), None))); | |
| 1380 | + } | |
| 1381 | + | |
| 1382 | + /// Every entry of the directory before the update, in order, and its | |
| 1383 | + /// largest leaf. | |
| 1384 | + fn entries(&mut self) -> Result<(Vec<Entry>, Option<ObjectId>), TreeError> { | |
| 1385 | + let mut entries: Vec<Entry> = Vec::new(); | |
| 1386 | + let mut largest: Option<(usize, ObjectId)> = None; | |
| 1387 | + // No name sorts before the empty one. | |
| 1388 | + let mut next = self.locate(0, b"", false)?; | |
| 1389 | + while let Some(leaf) = next { | |
| 1390 | + let node = self.node(leaf.node)?; | |
| 1391 | + check_child(&node, 0, &leaf)?; | |
| 1392 | + let found = Entry::items(&node).ok_or(TreeError::NotCanonical)?; | |
| 1393 | + if let (Some(previous), Some(first)) = (entries.last(), found.first()) | |
| 1394 | + && first.name <= previous.name | |
| 1395 | + { | |
| 1396 | + return Err(TreeError::NotCanonical); | |
| 1397 | + } | |
| 1398 | + if largest.is_none_or(|(len, _)| found.len() > len) { | |
| 1399 | + largest = Some((found.len(), leaf.node)); | |
| 1400 | + } | |
| 1401 | + entries.extend_from_slice(found); | |
| 1402 | + next = self.locate(0, &leaf.last_name, true)?; | |
| 1403 | + } | |
| 1404 | + Ok((entries, largest.map(|(_, id)| id))) | |
| 1405 | + } | |
| 1406 | +} | |
| 1407 | + | |
| 549 | 1408 | #[cfg(test)] |
| 550 | 1409 | mod tests { |
| 551 | 1410 | use super::*; |
| @@ -734,4 +1593,193 @@ | ||
| 734 | 1593 | assert!(Node::decode(&[FORMAT, NODE_LEAF, 0]).is_err()); |
| 735 | 1594 | assert!(Node::decode(&[FORMAT, NODE_INTERNAL, 0, 0]).is_err()); |
| 736 | 1595 | } |
| 1596 | + | |
| 1597 | + type Store = HashMap<ObjectId, Vec<u8>>; | |
| 1598 | + | |
| 1599 | + /// How `read_directory` checked a directory before it went node by node: | |
| 1600 | + /// it read every entry, built the directory again and compared the roots. | |
| 1601 | + fn read_by_building_again(root: ObjectId, store: &Store) -> Result<Vec<Entry>, TreeError> { | |
| 1602 | + fn collect( | |
| 1603 | + id: ObjectId, | |
| 1604 | + store: &Store, | |
| 1605 | + entries: &mut Vec<Entry>, | |
| 1606 | + expected_level: Option<u8>, | |
| 1607 | + ) -> Result<(), TreeError> { | |
| 1608 | + let bytes = store.get(&id).ok_or(TreeError::MissingNode(id))?; | |
| 1609 | + match (Node::decode(bytes)?, expected_level) { | |
| 1610 | + (Node::Flat(found), None) => entries.extend(found), | |
| 1611 | + (Node::Leaf(found), Some(0)) => entries.extend(found), | |
| 1612 | + (Node::Internal { level, children }, expected) | |
| 1613 | + if expected.is_none_or(|e| e == level) => | |
| 1614 | + { | |
| 1615 | + for child in children { | |
| 1616 | + collect(child.node, store, entries, Some(level - 1))?; | |
| 1617 | + } | |
| 1618 | + } | |
| 1619 | + _ => return Err(TreeError::NotCanonical), | |
| 1620 | + } | |
| 1621 | + Ok(()) | |
| 1622 | + } | |
| 1623 | + let mut entries = Vec::new(); | |
| 1624 | + collect(root, store, &mut entries, None)?; | |
| 1625 | + if build_directory(entries.clone())?.root() != root { | |
| 1626 | + return Err(TreeError::NotCanonical); | |
| 1627 | + } | |
| 1628 | + Ok(entries) | |
| 1629 | + } | |
| 1630 | + | |
| 1631 | + /// A directory always split, its nodes cut where `cut` says, given the | |
| 1632 | + /// level, the number of items the node would hold and whether the name | |
| 1633 | + /// hashes below the threshold; nodes never grow past the limit. | |
| 1634 | + fn cut_with( | |
| 1635 | + entries: Vec<Entry>, | |
| 1636 | + mut cut: impl FnMut(u8, usize, bool) -> bool, | |
| 1637 | + ) -> (ObjectId, Store) { | |
| 1638 | + fn level<I: Item>( | |
| 1639 | + level: u8, | |
| 1640 | + items: Vec<I>, | |
| 1641 | + store: &mut Store, | |
| 1642 | + cut: &mut impl FnMut(u8, usize, bool) -> bool, | |
| 1643 | + ) -> Vec<Child> { | |
| 1644 | + let mut splitter = Splitter::new(); | |
| 1645 | + let mut chunker = Chunker::new(level); | |
| 1646 | + for item in items { | |
| 1647 | + let count = chunker.next_count(); | |
| 1648 | + let hit = splitter.hit(level, item.name()); | |
| 1649 | + let ends = cut(level, count, hit) || count >= MAX_NODE_ENTRIES; | |
| 1650 | + chunker.push(item, ends); | |
| 1651 | + } | |
| 1652 | + chunker | |
| 1653 | + .finish() | |
| 1654 | + .into_iter() | |
| 1655 | + .map(|made| { | |
| 1656 | + store.insert(made.child.node, made.bytes); | |
| 1657 | + made.child | |
| 1658 | + }) | |
| 1659 | + .collect() | |
| 1660 | + } | |
| 1661 | + let mut store = Store::new(); | |
| 1662 | + let mut children = level(0, entries, &mut store, &mut cut); | |
| 1663 | + let mut at = 1; | |
| 1664 | + while children.len() > 1 { | |
| 1665 | + children = level(at, children, &mut store, &mut cut); | |
| 1666 | + at += 1; | |
| 1667 | + } | |
| 1668 | + (children[0].node, store) | |
| 1669 | + } | |
| 1670 | + | |
| 1671 | + /// Ways to cut the nodes of one level other than by the splitting rule, | |
| 1672 | + /// which the others follow. | |
| 1673 | + #[derive(Clone, Copy, Debug)] | |
| 1674 | + enum Cut { | |
| 1675 | + /// The splitting rule everywhere. | |
| 1676 | + Rule, | |
| 1677 | + /// The `k`th cut of the rule is not made. | |
| 1678 | + Skip(usize), | |
| 1679 | + /// A cut after the `k`th item of the level, besides the rule's. | |
| 1680 | + Extra(usize), | |
| 1681 | + /// The `k`th cut of the rule is made one item later. | |
| 1682 | + Late(usize), | |
| 1683 | + /// Cut wherever a name hashes below the threshold, however few items | |
| 1684 | + /// the node holds. | |
| 1685 | + NoMinimum, | |
| 1686 | + /// Nodes of `k` items. | |
| 1687 | + Fixed(usize), | |
| 1688 | + } | |
| 1689 | + | |
| 1690 | + fn cutter(target: u8, way: Cut) -> impl FnMut(u8, usize, bool) -> bool { | |
| 1691 | + let (mut cuts, mut items, mut late) = (0, 0, false); | |
| 1692 | + move |level, count, hit| { | |
| 1693 | + let rule = ends(count, || hit); | |
| 1694 | + if level != target { | |
| 1695 | + return rule; | |
| 1696 | + } | |
| 1697 | + items += 1; | |
| 1698 | + cuts += usize::from(rule); | |
| 1699 | + match way { | |
| 1700 | + Cut::Rule => rule, | |
| 1701 | + Cut::Skip(k) => rule && cuts != k, | |
| 1702 | + Cut::Extra(k) => rule || items == k, | |
| 1703 | + Cut::Late(k) => { | |
| 1704 | + if std::mem::take(&mut late) { | |
| 1705 | + return true; | |
| 1706 | + } | |
| 1707 | + late = rule && cuts == k; | |
| 1708 | + rule && !late | |
| 1709 | + } | |
| 1710 | + Cut::NoMinimum => hit, | |
| 1711 | + Cut::Fixed(k) => count >= k, | |
| 1712 | + } | |
| 1713 | + } | |
| 1714 | + } | |
| 1715 | + | |
| 1716 | + fn cut() -> impl proptest::strategy::Strategy<Value = Cut> { | |
| 1717 | + use proptest::prelude::*; | |
| 1718 | + prop_oneof![ | |
| 1719 | + Just(Cut::Rule), | |
| 1720 | + (1usize..40).prop_map(Cut::Skip), | |
| 1721 | + (1usize..4_000).prop_map(Cut::Extra), | |
| 1722 | + (1usize..40).prop_map(Cut::Late), | |
| 1723 | + Just(Cut::NoMinimum), | |
| 1724 | + (1usize..=MAX_NODE_ENTRIES).prop_map(Cut::Fixed), | |
| 1725 | + ] | |
| 1726 | + } | |
| 1727 | + | |
| 1728 | + proptest::proptest! { | |
| 1729 | + #![proptest_config(proptest::prelude::ProptestConfig::with_cases(48))] | |
| 1730 | + | |
| 1731 | + /// Checking node by node accepts and refuses exactly the trees that | |
| 1732 | + /// building again and comparing did, whichever way their nodes are cut. | |
| 1733 | + #[test] | |
| 1734 | + fn reading_checks_what_building_again_checked( | |
| 1735 | + count in 900usize..4_000, | |
| 1736 | + seed in proptest::prelude::any::<u64>(), | |
| 1737 | + target in 0u8..3, | |
| 1738 | + way in cut(), | |
| 1739 | + ) { | |
| 1740 | + let entries: Vec<Entry> = (0..count as u64) | |
| 1741 | + .map(|i| { | |
| 1742 | + let name = format!("{:x}-{i}", seed.wrapping_mul(i + 1) % 7919); | |
| 1743 | + (name.clone(), file(&name, "x")) | |
| 1744 | + }) | |
| 1745 | + .collect::<std::collections::BTreeMap<_, _>>() | |
| 1746 | + .into_values() | |
| 1747 | + .collect(); | |
| 1748 | + let (root, store) = cut_with(entries.clone(), cutter(target, way)); | |
| 1749 | + let fetch = |id: &ObjectId| store.get(id).cloned(); | |
| 1750 | + let read = read_directory(root, fetch); | |
| 1751 | + proptest::prop_assert_eq!(&read, &read_by_building_again(root, &store)); | |
| 1752 | + if matches!(way, Cut::Rule) && entries.len() > MAX_FLAT_ENTRIES { | |
| 1753 | + proptest::prop_assert_eq!(read, Ok(entries)); | |
| 1754 | + } | |
| 1755 | + } | |
| 1756 | + } | |
| 1757 | + | |
| 1758 | + #[test] | |
| 1759 | + fn reading_refuses_a_root_with_one_child() { | |
| 1760 | + let dir = build_directory(many(3_000, "x")).unwrap(); | |
| 1761 | + let root = dir.root(); | |
| 1762 | + let mut store: Store = dir.nodes.into_iter().collect(); | |
| 1763 | + let Node::Internal { level, children } = Node::decode(&store[&root]).unwrap() else { | |
| 1764 | + panic!("split"); | |
| 1765 | + }; | |
| 1766 | + let above = Node::Internal { | |
| 1767 | + level: level + 1, | |
| 1768 | + children: vec![Child { | |
| 1769 | + last_name: children.last().unwrap().last_name.clone(), | |
| 1770 | + node: root, | |
| 1771 | + entry_count: 3_000, | |
| 1772 | + }], | |
| 1773 | + }; | |
| 1774 | + store.insert(above.id(), above.encode()); | |
| 1775 | + let fetch = |id: &ObjectId| store.get(id).cloned(); | |
| 1776 | + assert_eq!( | |
| 1777 | + read_directory(above.id(), fetch), | |
| 1778 | + Err(TreeError::NotCanonical) | |
| 1779 | + ); | |
| 1780 | + assert_eq!( | |
| 1781 | + read_by_building_again(above.id(), &store), | |
| 1782 | + Err(TreeError::NotCanonical) | |
| 1783 | + ); | |
| 1784 | + } | |
| 737 | 1785 | } |
added crates/format/tests/update.rs +733 −0
| @@ -0,0 +1,733 @@ | ||
| 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 | +} |