Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/synapse/blob/main/crates/synapse-api/src/tree.rs # synapse A component of the AienOS ecosystem. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `synapse / crates / synapse-api / src / tree.rs` 1178 lines ยท 42933 bytes Raw Blame History 1 //! Shared Merkle tree store with a bounded cache (ADR 0003 sections 5.1 and 5.6, step C1). 2 //! 3 //! Every repository state is a persistent Merkle tree of directory nodes named by their 4 //! [`TreeDigest`]. Nodes are immutable and content-addressed, so every tree that contains an 5 //! unchanged subtree shares the one node for it: memory grows with what changed, not with the 6 //! number of revisions or workspaces. This replaces the unbounded per-changeset flat 7 //! `VirtualTree` cache measured in Gate 4 section 4. 8 //! 9 //! [`TreeStore`] holds the nodes. Its memory is bounded: the accounted bytes of every node, the 10 //! hash tables, and the changeset root memo never exceed [`TreeCacheConfig::max_bytes`]. Base 11 //! trees are *pinned* (they are the source the other trees are rebuilt from, so they are never 12 //! evicted, and pinning one that does not fit is refused); every other node and memo entry is 13 //! evictable, least recently used first. A walk that reaches an evicted node fails with 14 //! `RefusalCode::TreeNodeNotFound`, and the caller rebuilds that tree from its source (base tree 15 //! plus changeset mutations), which reproduces the same digests. 16 //! 17 //! Byte accounting is conservative: it counts every heap allocation's requested size plus 18 //! [`ALLOC_OVERHEAD_BYTES`] for allocator headers and rounding, and hash tables by their bucket 19 //! capacity. A test with a counting allocator checks that the accounted figure never falls below 20 //! the bytes actually allocated (`tests/c1_tree_digest.rs`). 21 //! 22 //! Walks run in canonical entry order ([`synapse_core::tree_entry_order`]), which lists full 23 //! paths in byte order, so tree pages and diffs come out in the same order as `git ls-tree -r` 24 //! and `git diff-tree -r`. Paging seeks by subtree file counts, so a page costs the depth of the 25 //! tree plus the entries returned, without building a flat list of the whole tree. 26 27 use serde::{Deserialize, Serialize}; 28 use std::collections::{BTreeMap, HashMap}; 29 use std::mem::size_of; 30 use std::sync::Arc; 31 use synapse_core::{ 32 tree_entry_order, validate_repo_relative_path, BlobDigest, ChangesetId, FileMode, GitOid, 33 RefusalCode, SynapseError, SynapseResult, TreeDigest, TreeNodeEncoder, 34 }; 35 36 /// Default bound on tree memory: 64 MiB. 37 pub const DEFAULT_TREE_CACHE_BYTES: usize = 64 * 1024 * 1024; 38 /// Smallest bound accepted: 1 MiB, enough for the overlay nodes of any one tree to coexist. 39 pub const MIN_TREE_CACHE_BYTES: usize = 1024 * 1024; 40 /// Bytes charged per heap allocation on top of its requested size (glibc malloc: an 8-byte 41 /// chunk header and 16-byte granularity). 42 pub const ALLOC_OVERHEAD_BYTES: usize = 16; 43 44 /// Configuration of a [`TreeStore`]. 45 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] 46 pub struct TreeCacheConfig { 47 /// Upper bound on the store's accounted bytes (pinned base trees included). 48 pub max_bytes: usize, 49 } 50 51 impl Default for TreeCacheConfig { 52 fn default() -> Self { 53 Self { 54 max_bytes: DEFAULT_TREE_CACHE_BYTES, 55 } 56 } 57 } 58 59 /// One file in a tree: the native fields bound by the [`TreeDigest`] plus the Git blob OID. 60 /// 61 /// `git_blob_oid` is a bridge attribute kept beside the native fields so listings can answer 62 /// `git ls-tree` parity without re-reading blob bytes. It is a function of the blob content, is 63 /// never encoded into a tree node, and never affects a `TreeDigest`. 64 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 65 pub struct TreeFile { 66 pub mode: FileMode, 67 pub blob_digest: BlobDigest, 68 pub size_bytes: u64, 69 pub git_blob_oid: GitOid, 70 } 71 72 /// What a tree entry names. 73 #[derive(Debug, Clone, Copy, PartialEq, Eq)] 74 pub enum TreeEntryKind { 75 File(TreeFile), 76 /// A non-empty subdirectory: its node digest and the number of files anywhere below it. 77 Dir { 78 digest: TreeDigest, 79 file_count: u64, 80 }, 81 } 82 83 /// One entry of a tree node. 84 #[derive(Debug, Clone, PartialEq, Eq)] 85 pub struct TreeEntry { 86 pub name: Box, 87 pub kind: TreeEntryKind, 88 } 89 90 impl TreeEntry { 91 fn is_dir(&self) -> bool { 92 matches!(self.kind, TreeEntryKind::Dir { .. }) 93 } 94 } 95 96 /// One immutable directory node: entries in canonical order, its digest, and derived counts. 97 #[derive(Debug)] 98 pub struct TreeNode { 99 digest: TreeDigest, 100 entries: Box<[TreeEntry]>, 101 file_count: u64, 102 encoded_len: usize, 103 } 104 105 impl TreeNode { 106 /// Build a node from entries in any order. Entries are sorted canonically; invalid or 107 /// duplicate names are refused with `RefusalCode::TreeNodeMalformed`. 108 pub fn new(mut entries: Vec) -> SynapseResult { 109 entries.sort_by(|a, b| tree_entry_order(&a.name, a.is_dir(), &b.name, b.is_dir())); 110 let mut enc = TreeNodeEncoder::new(entries.len() as u32); 111 let mut file_count = 0u64; 112 for e in &entries { 113 match &e.kind { 114 TreeEntryKind::File(f) => { 115 enc.file(&e.name, f.mode, &f.blob_digest, f.size_bytes)?; 116 file_count += 1; 117 } 118 TreeEntryKind::Dir { 119 digest, 120 file_count: n, 121 } => { 122 enc.dir(&e.name, digest)?; 123 file_count += n; 124 } 125 } 126 } 127 let (digest, bytes) = enc.finish()?; 128 Ok(Self { 129 digest, 130 entries: entries.into_boxed_slice(), 131 file_count, 132 encoded_len: bytes.len(), 133 }) 134 } 135 136 pub fn digest(&self) -> TreeDigest { 137 self.digest 138 } 139 140 pub fn entries(&self) -> &[TreeEntry] { 141 &self.entries 142 } 143 144 /// Files anywhere below this node. 145 pub fn file_count(&self) -> u64 { 146 self.file_count 147 } 148 149 /// Length of this node's canonical encoding (the bytes its digest covers). 150 pub fn encoded_len(&self) -> usize { 151 self.encoded_len 152 } 153 154 /// Accounted heap bytes of this node (see the module documentation). 155 pub fn heap_bytes(&self) -> usize { 156 // ArcInner (two counters plus the node) and the entry slice, each one allocation. 157 let mut bytes = 2 * size_of::() + size_of::() + ALLOC_OVERHEAD_BYTES; 158 if !self.entries.is_empty() { 159 bytes += self.entries.len() * size_of::() + ALLOC_OVERHEAD_BYTES; 160 } 161 for e in self.entries.iter() { 162 bytes += e.name.len() + ALLOC_OVERHEAD_BYTES; 163 } 164 bytes 165 } 166 } 167 168 /// A path-level difference between two trees. 169 #[derive(Debug, Clone, PartialEq, Eq)] 170 pub struct TreeDiffEntry { 171 pub path: String, 172 pub old: Option, 173 pub new: Option, 174 } 175 176 /// Counters and gauges of a [`TreeStore`]. 177 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] 178 pub struct TreeStoreStats { 179 /// Configured bound. 180 pub max_bytes: usize, 181 /// Accounted bytes now (nodes, tables, memo). 182 pub total_bytes: usize, 183 /// Highest `total_bytes` observed after any insertion. 184 pub high_water_bytes: usize, 185 /// Accounted bytes of pinned (base) nodes. 186 pub pinned_bytes: usize, 187 pub nodes: usize, 188 pub pinned_nodes: usize, 189 pub memoized_roots: usize, 190 /// Changeset trees built (cold path); a memo hit does not count. 191 pub root_builds: u64, 192 /// Changeset tree lookups answered from the memo (warm path). 193 pub root_hits: u64, 194 pub node_hits: u64, 195 pub node_misses: u64, 196 pub nodes_inserted: u64, 197 /// Canonical encoded bytes of the inserted nodes (the bytes a cold build writes and hashes). 198 pub encoded_bytes_inserted: u64, 199 pub nodes_evicted: u64, 200 pub roots_evicted: u64, 201 } 202 203 struct Slot { 204 node: Arc, 205 bytes: usize, 206 tick: u64, 207 pins: u32, 208 } 209 210 struct RootMemo { 211 digest: TreeDigest, 212 tick: u64, 213 } 214 215 enum Victim { 216 Node(TreeDigest), 217 Root(ChangesetId), 218 } 219 220 /// Content-addressed store of tree nodes with a byte bound (see the module documentation). 221 pub struct TreeStore { 222 config: TreeCacheConfig, 223 nodes: HashMap, 224 roots: HashMap, 225 node_bytes: usize, 226 tick: u64, 227 stats: TreeStoreStats, 228 } 229 230 /// Accounted bytes of a hashbrown table that can hold `capacity` items without growing. 231 fn table_bytes(capacity: usize) -> usize { 232 if capacity == 0 { 233 return 0; 234 } 235 let buckets = (capacity * 8).div_ceil(7).next_power_of_two(); 236 buckets * (size_of::<(K, V)>() + 1) + 16 + ALLOC_OVERHEAD_BYTES 237 } 238 239 /// Accounted table bytes after one more insertion into a table holding `len` of `capacity`. 240 fn table_bytes_after_insert(len: usize, capacity: usize) -> usize { 241 if len < capacity { 242 return table_bytes::(capacity); 243 } 244 // hashbrown doubles its bucket count (from 0 to 4 buckets, capacity 3). 245 let grown = if capacity < 3 { 246 3 247 } else { 248 let buckets = (capacity * 8).div_ceil(7).next_power_of_two(); 249 buckets * 2 * 7 / 8 250 }; 251 table_bytes::(grown) 252 } 253 254 fn not_found(digest: TreeDigest) -> SynapseError { 255 SynapseError::new( 256 RefusalCode::TreeNodeNotFound, 257 format!("tree node {digest} is not in the tree store (evicted or never built)"), 258 ) 259 } 260 261 /// Does `a` followed by `b` start with `prefix`? 262 fn concat_starts_with(a: &str, b: &str, prefix: &str) -> bool { 263 if prefix.len() <= a.len() { 264 return a.starts_with(prefix); 265 } 266 prefix.starts_with(a) && b.starts_with(&prefix[a.len()..]) 267 } 268 269 /// How the files below directory path `dir` (ending in `/`) relate to a path prefix. 270 enum PrefixRelation { 271 All, 272 Some, 273 None, 274 } 275 276 fn relate(dir: &str, prefix: &str) -> PrefixRelation { 277 if dir.starts_with(prefix) { 278 PrefixRelation::All 279 } else if prefix.starts_with(dir) { 280 PrefixRelation::Some 281 } else { 282 PrefixRelation::None 283 } 284 } 285 286 impl TreeStore { 287 /// Open an empty store. A bound below [`MIN_TREE_CACHE_BYTES`] is refused with 288 /// `RefusalCode::BackpressureOverCapacity`. 289 pub fn new(config: TreeCacheConfig) -> SynapseResult { 290 if config.max_bytes < MIN_TREE_CACHE_BYTES { 291 return Err(SynapseError::new( 292 RefusalCode::BackpressureOverCapacity, 293 format!( 294 "tree cache bound {} bytes is below the minimum {MIN_TREE_CACHE_BYTES}", 295 config.max_bytes 296 ), 297 )); 298 } 299 let mut store = Self { 300 config, 301 nodes: HashMap::new(), 302 roots: HashMap::new(), 303 node_bytes: 0, 304 tick: 0, 305 stats: TreeStoreStats { 306 max_bytes: config.max_bytes, 307 ..TreeStoreStats::default() 308 }, 309 }; 310 // The empty tree always exists (an empty repository) and is pinned. 311 let empty = store.insert(TreeNode::new(Vec::new())?); 312 store.pin(empty)?; 313 Ok(store) 314 } 315 316 pub fn config(&self) -> TreeCacheConfig { 317 self.config 318 } 319 320 /// Accounted bytes now. 321 pub fn total_bytes(&self) -> usize { 322 self.node_bytes 323 + table_bytes::(self.nodes.capacity()) 324 + table_bytes::(self.roots.capacity()) 325 } 326 327 pub fn stats(&self) -> TreeStoreStats { 328 let mut s = self.stats; 329 s.total_bytes = self.total_bytes(); 330 s.nodes = self.nodes.len(); 331 s.memoized_roots = self.roots.len(); 332 s 333 } 334 335 fn next_tick(&mut self) -> u64 { 336 self.tick += 1; 337 self.tick 338 } 339 340 /// Is the node for `digest` present? 341 pub fn contains(&self, digest: TreeDigest) -> bool { 342 self.nodes.contains_key(&digest) 343 } 344 345 /// Fetch a node, marking it recently used. 346 pub fn get(&mut self, digest: TreeDigest) -> SynapseResult> { 347 let tick = self.next_tick(); 348 match self.nodes.get_mut(&digest) { 349 Some(slot) => { 350 slot.tick = tick; 351 self.stats.node_hits += 1; 352 Ok(Arc::clone(&slot.node)) 353 } 354 None => { 355 self.stats.node_misses += 1; 356 Err(not_found(digest)) 357 } 358 } 359 } 360 361 /// Insert a node (deduplicated by digest) and return its digest, evicting least recently 362 /// used unpinned nodes and memo entries first so the bound holds after the insertion. 363 pub fn insert(&mut self, node: TreeNode) -> TreeDigest { 364 let digest = node.digest; 365 let tick = self.next_tick(); 366 if let Some(slot) = self.nodes.get_mut(&digest) { 367 slot.tick = tick; 368 return digest; 369 } 370 let bytes = node.heap_bytes(); 371 let encoded = node.encoded_len() as u64; 372 self.make_room(bytes, true, false); 373 self.nodes.insert( 374 digest, 375 Slot { 376 node: Arc::new(node), 377 bytes, 378 tick, 379 pins: 0, 380 }, 381 ); 382 self.node_bytes += bytes; 383 self.stats.nodes_inserted += 1; 384 self.stats.encoded_bytes_inserted += encoded; 385 self.note_high_water(); 386 digest 387 } 388 389 fn note_high_water(&mut self) { 390 let total = self.total_bytes(); 391 if total > self.stats.high_water_bytes { 392 self.stats.high_water_bytes = total; 393 } 394 } 395 396 /// Evict least recently used victims until `incoming` more bytes (plus any table growth from 397 /// one insertion into the node or root table) fit under the bound. 398 fn make_room(&mut self, incoming: usize, into_nodes: bool, into_roots: bool) { 399 let need = |s: &Self| { 400 let nodes_table = if into_nodes { 401 table_bytes_after_insert::(s.nodes.len(), s.nodes.capacity()) 402 } else { 403 table_bytes::(s.nodes.capacity()) 404 }; 405 let roots_table = if into_roots { 406 table_bytes_after_insert::(s.roots.len(), s.roots.capacity()) 407 } else { 408 table_bytes::(s.roots.capacity()) 409 }; 410 s.node_bytes + nodes_table + roots_table + incoming 411 }; 412 if need(self) <= self.config.max_bytes { 413 return; 414 } 415 // Evict down to seven eighths of the bound so eviction runs in batches. 416 let target = self.config.max_bytes - self.config.max_bytes / 8; 417 let mut victims: Vec<(u64, Victim)> = self 418 .nodes 419 .iter() 420 .filter(|(_, s)| s.pins == 0) 421 .map(|(d, s)| (s.tick, Victim::Node(*d))) 422 .chain(self.roots.iter().map(|(c, r)| (r.tick, Victim::Root(*c)))) 423 .collect(); 424 victims.sort_unstable_by_key(|(t, _)| *t); 425 for (_, v) in victims { 426 if need(self) <= target { 427 break; 428 } 429 match v { 430 Victim::Node(d) => { 431 if let Some(slot) = self.nodes.remove(&d) { 432 self.node_bytes -= slot.bytes; 433 self.stats.nodes_evicted += 1; 434 } 435 } 436 Victim::Root(c) => { 437 self.roots.remove(&c); 438 self.stats.roots_evicted += 1; 439 } 440 } 441 } 442 } 443 444 /// Pin every node reachable from `root` so it is never evicted. Fails with 445 /// `TreeNodeNotFound` if the tree is incomplete, or `BackpressureOverCapacity` if the pinned 446 /// bytes would exceed the bound; on failure nothing stays pinned by this call. 447 pub fn pin(&mut self, root: TreeDigest) -> SynapseResult<()> { 448 let mut pinned: Vec = Vec::new(); 449 let mut stack = vec![root]; 450 let mut result = Ok(()); 451 while let Some(d) = stack.pop() { 452 let Some(slot) = self.nodes.get_mut(&d) else { 453 result = Err(not_found(d)); 454 break; 455 }; 456 slot.pins += 1; 457 if slot.pins == 1 { 458 self.stats.pinned_bytes += slot.bytes; 459 self.stats.pinned_nodes += 1; 460 } 461 pinned.push(d); 462 for e in slot.node.entries.iter() { 463 if let TreeEntryKind::Dir { digest, .. } = e.kind { 464 stack.push(digest); 465 } 466 } 467 } 468 if result.is_ok() && self.stats.pinned_bytes > self.config.max_bytes { 469 result = Err(SynapseError::new( 470 RefusalCode::BackpressureOverCapacity, 471 format!( 472 "pinned base trees need {} bytes, over the tree cache bound {}", 473 self.stats.pinned_bytes, self.config.max_bytes 474 ), 475 )); 476 } 477 if result.is_err() { 478 for d in pinned { 479 if let Some(slot) = self.nodes.get_mut(&d) { 480 slot.pins -= 1; 481 if slot.pins == 0 { 482 self.stats.pinned_bytes -= slot.bytes; 483 self.stats.pinned_nodes -= 1; 484 } 485 } 486 } 487 } 488 result 489 } 490 491 /// Release one pin taken by [`TreeStore::pin`] on `root`; nodes left with no pin become 492 /// evictable. 493 pub fn unpin(&mut self, root: TreeDigest) { 494 let mut stack = vec![root]; 495 while let Some(d) = stack.pop() { 496 let Some(slot) = self.nodes.get_mut(&d) else { 497 continue; 498 }; 499 if slot.pins == 0 { 500 continue; 501 } 502 slot.pins -= 1; 503 if slot.pins == 0 { 504 self.stats.pinned_bytes -= slot.bytes; 505 self.stats.pinned_nodes -= 1; 506 } 507 for e in slot.node.entries.iter() { 508 if let TreeEntryKind::Dir { digest, .. } = e.kind { 509 stack.push(digest); 510 } 511 } 512 } 513 } 514 515 /// Remembered root of a changeset tree, if its root node is still present. 516 pub fn memo_root(&mut self, changeset: ChangesetId) -> Option { 517 let tick = self.next_tick(); 518 let memo = self.roots.get_mut(&changeset)?; 519 if !self.nodes.contains_key(&memo.digest) { 520 return None; 521 } 522 memo.tick = tick; 523 self.stats.root_hits += 1; 524 Some(memo.digest) 525 } 526 527 /// Remember the root of a changeset tree (an evictable memo entry). 528 pub fn remember_root(&mut self, changeset: ChangesetId, digest: TreeDigest) { 529 let tick = self.next_tick(); 530 if let Some(m) = self.roots.get_mut(&changeset) { 531 m.digest = digest; 532 m.tick = tick; 533 return; 534 } 535 self.make_room(0, false, true); 536 self.roots.insert(changeset, RootMemo { digest, tick }); 537 self.note_high_water(); 538 } 539 540 /// Forget a changeset's memoized root (exact invalidation; its nodes stay shared). 541 pub fn forget_root(&mut self, changeset: ChangesetId) { 542 self.roots.remove(&changeset); 543 } 544 545 pub(crate) fn count_root_build(&mut self) { 546 self.stats.root_builds += 1; 547 } 548 549 /// Number of memoized changeset roots. 550 pub fn memoized_roots(&self) -> usize { 551 self.roots.len() 552 } 553 554 /// Look up the file at `path`. 555 pub fn lookup(&mut self, root: TreeDigest, path: &str) -> SynapseResult> { 556 let mut node = self.get(root)?; 557 let mut segments = path.split('/').peekable(); 558 while let Some(seg) = segments.next() { 559 let last = segments.peek().is_none(); 560 let found = node 561 .entries 562 .iter() 563 .find(|e| &*e.name == seg) 564 .map(|e| e.kind); 565 match (found, last) { 566 (Some(TreeEntryKind::File(f)), true) => return Ok(Some(f)), 567 (Some(TreeEntryKind::Dir { digest, .. }), false) => node = self.get(digest)?, 568 _ => return Ok(None), 569 } 570 } 571 Ok(None) 572 } 573 574 /// Number of files whose full path starts with `prefix` (empty prefix: every file). 575 pub fn count_files(&mut self, root: TreeDigest, prefix: &str) -> SynapseResult { 576 let node = self.get(root)?; 577 if prefix.is_empty() { 578 return Ok(node.file_count); 579 } 580 let mut dir = String::new(); 581 self.count_rec(&node, &mut dir, prefix) 582 } 583 584 fn count_rec(&mut self, node: &TreeNode, dir: &mut String, prefix: &str) -> SynapseResult { 585 let mut n = 0; 586 for e in node.entries.iter() { 587 match e.kind { 588 TreeEntryKind::File(_) => n += u64::from(concat_starts_with(dir, &e.name, prefix)), 589 TreeEntryKind::Dir { digest, file_count } => { 590 let len = dir.len(); 591 dir.push_str(&e.name); 592 dir.push('/'); 593 match relate(dir, prefix) { 594 PrefixRelation::All => n += file_count, 595 PrefixRelation::Some => { 596 let child = self.get(digest)?; 597 n += self.count_rec(&child, dir, prefix)?; 598 } 599 PrefixRelation::None => {} 600 } 601 dir.truncate(len); 602 } 603 } 604 } 605 Ok(n) 606 } 607 608 /// Up to `limit` files whose path starts with `prefix`, skipping the first `offset` of them, 609 /// in path byte order. Whole subtrees inside the skipped range are passed over by count. 610 pub fn page_files( 611 &mut self, 612 root: TreeDigest, 613 prefix: &str, 614 offset: u64, 615 limit: usize, 616 ) -> SynapseResult> { 617 let node = self.get(root)?; 618 let mut out = Vec::with_capacity(limit.min(4096)); 619 let mut skip = offset; 620 let mut dir = String::new(); 621 self.page_rec(&node, &mut dir, prefix, &mut skip, limit, &mut out)?; 622 Ok(out) 623 } 624 625 fn page_rec( 626 &mut self, 627 node: &TreeNode, 628 dir: &mut String, 629 prefix: &str, 630 skip: &mut u64, 631 limit: usize, 632 out: &mut Vec<(String, TreeFile)>, 633 ) -> SynapseResult<()> { 634 for e in node.entries.iter() { 635 if out.len() >= limit { 636 return Ok(()); 637 } 638 match e.kind { 639 TreeEntryKind::File(f) => { 640 if concat_starts_with(dir, &e.name, prefix) { 641 if *skip > 0 { 642 *skip -= 1; 643 } else { 644 let mut path = String::with_capacity(dir.len() + e.name.len()); 645 path.push_str(dir); 646 path.push_str(&e.name); 647 out.push((path, f)); 648 } 649 } 650 } 651 TreeEntryKind::Dir { digest, file_count } => { 652 let len = dir.len(); 653 dir.push_str(&e.name); 654 dir.push('/'); 655 let descend = match relate(dir, prefix) { 656 PrefixRelation::All if *skip >= file_count => { 657 *skip -= file_count; 658 false 659 } 660 PrefixRelation::All | PrefixRelation::Some => true, 661 PrefixRelation::None => false, 662 }; 663 if descend { 664 let child = self.get(digest)?; 665 self.page_rec(&child, dir, prefix, skip, limit, out)?; 666 } 667 dir.truncate(len); 668 } 669 } 670 } 671 Ok(()) 672 } 673 674 /// Every file of the tree in path byte order. 675 pub fn files(&mut self, root: TreeDigest) -> SynapseResult> { 676 let n = self.count_files(root, "")?; 677 self.page_files(root, "", 0, n as usize) 678 } 679 680 /// Path-level differences from tree `old` to tree `new`, in path byte order. Equal subtrees 681 /// (equal digests) are skipped without being read. 682 pub fn diff(&mut self, old: TreeDigest, new: TreeDigest) -> SynapseResult> { 683 let mut out = Vec::new(); 684 if old != new { 685 let a = self.get(old)?; 686 let b = self.get(new)?; 687 let mut dir = String::new(); 688 self.diff_rec(&a, &b, &mut dir, &mut out)?; 689 } 690 Ok(out) 691 } 692 693 fn emit_all( 694 &mut self, 695 entry: &TreeEntry, 696 dir: &mut String, 697 added: bool, 698 out: &mut Vec, 699 ) -> SynapseResult<()> { 700 let len = dir.len(); 701 dir.push_str(&entry.name); 702 match entry.kind { 703 TreeEntryKind::File(f) => out.push(TreeDiffEntry { 704 path: dir.clone(), 705 old: (!added).then_some(f), 706 new: added.then_some(f), 707 }), 708 TreeEntryKind::Dir { digest, .. } => { 709 dir.push('/'); 710 let node = self.get(digest)?; 711 for e in node.entries.iter() { 712 self.emit_all(e, dir, added, out)?; 713 } 714 } 715 } 716 dir.truncate(len); 717 Ok(()) 718 } 719 720 fn diff_rec( 721 &mut self, 722 a: &TreeNode, 723 b: &TreeNode, 724 dir: &mut String, 725 out: &mut Vec, 726 ) -> SynapseResult<()> { 727 let (ea, eb) = (&a.entries, &b.entries); 728 let (mut i, mut j) = (0, 0); 729 while i < ea.len() || j < eb.len() { 730 let ord = match (ea.get(i), eb.get(j)) { 731 (Some(x), Some(y)) => tree_entry_order(&x.name, x.is_dir(), &y.name, y.is_dir()), 732 (Some(_), None) => std::cmp::Ordering::Less, 733 _ => std::cmp::Ordering::Greater, 734 }; 735 match ord { 736 std::cmp::Ordering::Less => { 737 self.emit_all(&ea[i], dir, false, out)?; 738 i += 1; 739 } 740 std::cmp::Ordering::Greater => { 741 self.emit_all(&eb[j], dir, true, out)?; 742 j += 1; 743 } 744 std::cmp::Ordering::Equal => { 745 match (ea[i].kind, eb[j].kind) { 746 (TreeEntryKind::File(x), TreeEntryKind::File(y)) => { 747 if x.blob_digest != y.blob_digest || x.mode != y.mode { 748 let mut path = dir.clone(); 749 path.push_str(&ea[i].name); 750 out.push(TreeDiffEntry { 751 path, 752 old: Some(x), 753 new: Some(y), 754 }); 755 } 756 } 757 ( 758 TreeEntryKind::Dir { digest: x, .. }, 759 TreeEntryKind::Dir { digest: y, .. }, 760 ) => { 761 if x != y { 762 let len = dir.len(); 763 dir.push_str(&ea[i].name); 764 dir.push('/'); 765 let (na, nb) = (self.get(x)?, self.get(y)?); 766 self.diff_rec(&na, &nb, dir, out)?; 767 dir.truncate(len); 768 } 769 } 770 // Equal order implies equal name and kind. 771 _ => unreachable!("tree_entry_order Equal with differing kinds"), 772 } 773 i += 1; 774 j += 1; 775 } 776 } 777 } 778 Ok(()) 779 } 780 781 /// Bytes of canonical node encoding reachable from `root` (each distinct node once), and the 782 /// number of distinct nodes. Used for the memory-bandwidth bound of a full walk. 783 pub fn encoded_bytes(&mut self, root: TreeDigest) -> SynapseResult<(u64, u64)> { 784 let mut seen = std::collections::HashSet::new(); 785 let mut stack = vec![root]; 786 let (mut bytes, mut nodes) = (0u64, 0u64); 787 while let Some(d) = stack.pop() { 788 if !seen.insert(d) { 789 continue; 790 } 791 let node = self.get(d)?; 792 bytes += node.encoded_len as u64; 793 nodes += 1; 794 for e in node.entries.iter() { 795 if let TreeEntryKind::Dir { digest, .. } = e.kind { 796 stack.push(digest); 797 } 798 } 799 } 800 Ok((bytes, nodes)) 801 } 802 } 803 804 /// A mutable edit of one tree: opens only the directories on touched paths, applies path 805 /// mutations in order with the same rules as the flat overlay it replaces, and writes back only 806 /// the changed nodes ([`TreeEdit::finish`]). Unchanged subtrees keep their digests. 807 pub struct TreeEdit { 808 root: EditDir, 809 /// Canonical bytes of the nodes written by `finish` (for cold-build bounds). 810 written_bytes: u64, 811 written_nodes: u64, 812 } 813 814 enum EditDir { 815 Stored { digest: TreeDigest, file_count: u64 }, 816 Open(BTreeMap, EditEntry>), 817 } 818 819 enum EditEntry { 820 File(TreeFile), 821 Dir(EditDir), 822 } 823 824 impl EditDir { 825 fn open(&mut self, store: &mut TreeStore) -> SynapseResult<&mut BTreeMap, EditEntry>> { 826 if let EditDir::Stored { digest, .. } = *self { 827 let node = store.get(digest)?; 828 let map = node 829 .entries 830 .iter() 831 .map(|e| { 832 let v = match e.kind { 833 TreeEntryKind::File(f) => EditEntry::File(f), 834 TreeEntryKind::Dir { digest, file_count } => { 835 EditEntry::Dir(EditDir::Stored { digest, file_count }) 836 } 837 }; 838 (e.name.clone(), v) 839 }) 840 .collect(); 841 *self = EditDir::Open(map); 842 } 843 match self { 844 EditDir::Open(map) => Ok(map), 845 EditDir::Stored { .. } => unreachable!("opened above"), 846 } 847 } 848 } 849 850 impl TreeEdit { 851 /// Start editing the tree `base` (its root node must be present). 852 pub fn new(store: &mut TreeStore, base: TreeDigest) -> SynapseResult { 853 let file_count = store.get(base)?.file_count; 854 Ok(Self { 855 root: EditDir::Stored { 856 digest: base, 857 file_count, 858 }, 859 written_bytes: 0, 860 written_nodes: 0, 861 }) 862 } 863 864 /// Create or replace the file at `path`. A file at an ancestor path is replaced by a 865 /// directory, and a directory at `path` (with everything below it) is replaced by the file. 866 pub fn upsert( 867 &mut self, 868 store: &mut TreeStore, 869 path: &str, 870 file: TreeFile, 871 ) -> SynapseResult<()> { 872 validate_repo_relative_path(path)?; 873 let mut segments: Vec<&str> = path.split('/').collect(); 874 let name = segments.pop().expect("validated path is non-empty"); 875 let mut dir = &mut self.root; 876 for seg in segments { 877 let map = dir.open(store)?; 878 let slot = map 879 .entry(seg.into()) 880 .or_insert_with(|| EditEntry::Dir(EditDir::Open(BTreeMap::new()))); 881 if matches!(slot, EditEntry::File(_)) { 882 *slot = EditEntry::Dir(EditDir::Open(BTreeMap::new())); 883 } 884 dir = match slot { 885 EditEntry::Dir(d) => d, 886 EditEntry::File(_) => unreachable!("replaced above"), 887 }; 888 } 889 dir.open(store)?.insert(name.into(), EditEntry::File(file)); 890 Ok(()) 891 } 892 893 /// Remove the file at `path`. A missing path, or a path naming a directory, is left as is. 894 pub fn delete(&mut self, store: &mut TreeStore, path: &str) -> SynapseResult<()> { 895 validate_repo_relative_path(path)?; 896 let mut segments: Vec<&str> = path.split('/').collect(); 897 let name = segments.pop().expect("validated path is non-empty"); 898 let mut dir = &mut self.root; 899 for seg in segments { 900 let map = dir.open(store)?; 901 dir = match map.get_mut(seg) { 902 Some(EditEntry::Dir(d)) => d, 903 _ => return Ok(()), 904 }; 905 } 906 let map = dir.open(store)?; 907 if matches!(map.get(name), Some(EditEntry::File(_))) { 908 map.remove(name); 909 } 910 Ok(()) 911 } 912 913 /// Overlay every file of tree `other` onto this edit, as if each were upserted in path 914 /// order: files of `other` win, a file and a directory at the same path resolve to 915 /// `other`'s entry, and subtrees equal on both sides are not opened. 916 pub fn overlay(&mut self, store: &mut TreeStore, other: TreeDigest) -> SynapseResult<()> { 917 let node = store.get(other)?; 918 overlay_dir(&mut self.root, &node, store) 919 } 920 921 /// Write the changed nodes and return the new root digest. 922 pub fn finish(self, store: &mut TreeStore) -> SynapseResult { 923 self.finish_with_counts(store).map(|(digest, _, _)| digest) 924 } 925 926 /// Like [`TreeEdit::finish`], also returning the canonical bytes and count of nodes written. 927 pub fn finish_with_counts( 928 mut self, 929 store: &mut TreeStore, 930 ) -> SynapseResult<(TreeDigest, u64, u64)> { 931 let root = std::mem::replace( 932 &mut self.root, 933 EditDir::Stored { 934 digest: TreeDigest::empty(), 935 file_count: 0, 936 }, 937 ); 938 let digest = match self.freeze(root, store)? { 939 Some((digest, _)) => digest, 940 None => store.insert(TreeNode::new(Vec::new())?), 941 }; 942 Ok((digest, self.written_bytes, self.written_nodes)) 943 } 944 945 /// Freeze a directory bottom-up. Returns `None` for an empty directory (pruned). 946 fn freeze( 947 &mut self, 948 dir: EditDir, 949 store: &mut TreeStore, 950 ) -> SynapseResult> { 951 let map = match dir { 952 EditDir::Stored { digest, file_count } => return Ok(Some((digest, file_count))), 953 EditDir::Open(map) => map, 954 }; 955 let mut entries = Vec::with_capacity(map.len()); 956 for (name, entry) in map { 957 match entry { 958 EditEntry::File(f) => entries.push(TreeEntry { 959 name, 960 kind: TreeEntryKind::File(f), 961 }), 962 EditEntry::Dir(d) => { 963 if let Some((digest, file_count)) = self.freeze(d, store)? { 964 entries.push(TreeEntry { 965 name, 966 kind: TreeEntryKind::Dir { digest, file_count }, 967 }); 968 } 969 } 970 } 971 } 972 if entries.is_empty() { 973 return Ok(None); 974 } 975 let node = TreeNode::new(entries)?; 976 let file_count = node.file_count; 977 self.written_bytes += node.encoded_len as u64; 978 self.written_nodes += 1; 979 Ok(Some((store.insert(node), file_count))) 980 } 981 } 982 983 fn overlay_dir(dir: &mut EditDir, other: &TreeNode, store: &mut TreeStore) -> SynapseResult<()> { 984 if let EditDir::Stored { digest, .. } = dir { 985 if *digest == other.digest { 986 return Ok(()); 987 } 988 } 989 let map = dir.open(store)?; 990 for e in other.entries.iter() { 991 match e.kind { 992 TreeEntryKind::File(f) => { 993 map.insert(e.name.clone(), EditEntry::File(f)); 994 } 995 TreeEntryKind::Dir { digest, file_count } => match map.get_mut(&e.name) { 996 Some(EditEntry::Dir(mine)) => { 997 let child = store.get(digest)?; 998 overlay_dir(mine, &child, store)?; 999 } 1000 _ => { 1001 map.insert( 1002 e.name.clone(), 1003 EditEntry::Dir(EditDir::Stored { digest, file_count }), 1004 ); 1005 } 1006 }, 1007 } 1008 } 1009 Ok(()) 1010 } 1011 1012 #[cfg(test)] 1013 mod tests { 1014 use super::*; 1015 1016 fn file(content: &[u8]) -> TreeFile { 1017 TreeFile { 1018 mode: FileMode::Regular644, 1019 blob_digest: BlobDigest::compute(content), 1020 size_bytes: content.len() as u64, 1021 git_blob_oid: GitOid::compute_blob(content), 1022 } 1023 } 1024 1025 fn build(store: &mut TreeStore, files: &[(&str, &[u8])]) -> TreeDigest { 1026 let mut edit = TreeEdit::new(store, TreeDigest::empty()).unwrap(); 1027 for (p, c) in files { 1028 edit.upsert(store, p, file(c)).unwrap(); 1029 } 1030 edit.finish(store).unwrap() 1031 } 1032 1033 fn paths(store: &mut TreeStore, root: TreeDigest) -> Vec { 1034 store 1035 .files(root) 1036 .unwrap() 1037 .into_iter() 1038 .map(|(p, _)| p) 1039 .collect() 1040 } 1041 1042 #[test] 1043 fn digest_is_independent_of_edit_order_and_history() { 1044 let mut s = TreeStore::new(TreeCacheConfig::default()).unwrap(); 1045 let a = build(&mut s, &[("x/y", b"1"), ("a-b", b"2"), ("a/c", b"3")]); 1046 let b = build(&mut s, &[("a/c", b"3"), ("x/y", b"1"), ("a-b", b"2")]); 1047 assert_eq!(a, b); 1048 // Add then delete returns to the same digest. 1049 let mut e = TreeEdit::new(&mut s, a).unwrap(); 1050 e.upsert(&mut s, "z/new", file(b"9")).unwrap(); 1051 e.delete(&mut s, "z/new").unwrap(); 1052 assert_eq!(e.finish(&mut s).unwrap(), a); 1053 assert_eq!(paths(&mut s, a), vec!["a-b", "a/c", "x/y"]); 1054 } 1055 1056 #[test] 1057 fn upsert_replaces_file_dir_collisions_and_delete_prunes_empty_dirs() { 1058 let mut s = TreeStore::new(TreeCacheConfig::default()).unwrap(); 1059 let root = build(&mut s, &[("a", b"f"), ("d/e/f", b"g"), ("d/h", b"i")]); 1060 let mut e = TreeEdit::new(&mut s, root).unwrap(); 1061 e.upsert(&mut s, "a/b", file(b"new")).unwrap(); // file a becomes dir a 1062 e.upsert(&mut s, "d/e", file(b"file")).unwrap(); // dir d/e becomes file d/e 1063 e.delete(&mut s, "d/h").unwrap(); 1064 e.delete(&mut s, "nope/x").unwrap(); 1065 let r2 = e.finish(&mut s).unwrap(); 1066 assert_eq!(paths(&mut s, r2), vec!["a/b", "d/e"]); 1067 let mut e = TreeEdit::new(&mut s, r2).unwrap(); 1068 e.delete(&mut s, "a/b").unwrap(); 1069 e.delete(&mut s, "d/e").unwrap(); 1070 assert_eq!(e.finish(&mut s).unwrap(), TreeDigest::empty()); 1071 } 1072 1073 #[test] 1074 fn paging_with_offset_and_prefix_matches_a_flat_listing() { 1075 let mut s = TreeStore::new(TreeCacheConfig::default()).unwrap(); 1076 let names: Vec = (0..200) 1077 .map(|i| format!("d{}/s{}/f{i}", i % 7, i % 3)) 1078 .chain((0..20).map(|i| format!("d1-top{i}"))) 1079 .collect(); 1080 let files: Vec<(&str, &[u8])> = names.iter().map(|n| (n.as_str(), n.as_bytes())).collect(); 1081 let root = build(&mut s, &files); 1082 let mut flat: Vec = names.clone(); 1083 flat.sort(); 1084 for prefix in ["", "d1", "d1/", "d1/s", "d1/s2/", "d1-", "zz"] { 1085 let expect: Vec<&String> = flat.iter().filter(|p| p.starts_with(prefix)).collect(); 1086 assert_eq!(s.count_files(root, prefix).unwrap(), expect.len() as u64); 1087 for (offset, limit) in [(0, 1000), (0, 7), (5, 13), (expect.len(), 4)] { 1088 let got = s.page_files(root, prefix, offset as u64, limit).unwrap(); 1089 let want: Vec<&String> = expect.iter().skip(offset).take(limit).copied().collect(); 1090 let got: Vec<&String> = got.iter().map(|(p, _)| p).collect(); 1091 assert_eq!(got, want, "prefix {prefix:?} offset {offset} limit {limit}"); 1092 } 1093 } 1094 } 1095 1096 #[test] 1097 fn diff_skips_equal_subtrees_and_reports_in_path_order() { 1098 let mut s = TreeStore::new(TreeCacheConfig::default()).unwrap(); 1099 let a = build( 1100 &mut s, 1101 &[("a", b"1"), ("big/x", b"2"), ("big/y", b"3"), ("k/l", b"4")], 1102 ); 1103 let b = build( 1104 &mut s, 1105 &[ 1106 ("a/z", b"1"), 1107 ("big/x", b"2"), 1108 ("big/y", b"3"), 1109 ("k/l", b"5"), 1110 ], 1111 ); 1112 let d = s.diff(a, b).unwrap(); 1113 let summary: Vec<(String, bool, bool)> = d 1114 .iter() 1115 .map(|e| (e.path.clone(), e.old.is_some(), e.new.is_some())) 1116 .collect(); 1117 assert_eq!( 1118 summary, 1119 vec![ 1120 ("a".into(), true, false), 1121 ("a/z".into(), false, true), 1122 ("k/l".into(), true, true), 1123 ] 1124 ); 1125 let hits_before = s.stats().node_hits; 1126 assert!(s.diff(a, a).unwrap().is_empty()); 1127 assert_eq!(s.stats().node_hits, hits_before, "equal roots are not read"); 1128 } 1129 1130 #[test] 1131 fn overlay_matches_upserting_every_file_of_the_other_tree() { 1132 let mut s = TreeStore::new(TreeCacheConfig::default()).unwrap(); 1133 let a = build( 1134 &mut s, 1135 &[("x", b"1"), ("d/p", b"2"), ("d/q", b"3"), ("e/f", b"4")], 1136 ); 1137 let b = build( 1138 &mut s, 1139 &[("x/y", b"5"), ("d/q", b"6"), ("e", b"7"), ("n", b"8")], 1140 ); 1141 let mut e = TreeEdit::new(&mut s, a).unwrap(); 1142 e.overlay(&mut s, b).unwrap(); 1143 let merged = e.finish(&mut s).unwrap(); 1144 let mut e = TreeEdit::new(&mut s, a).unwrap(); 1145 for (p, f) in s.files(b).unwrap() { 1146 e.upsert(&mut s, &p, f).unwrap(); 1147 } 1148 assert_eq!(merged, e.finish(&mut s).unwrap()); 1149 assert_eq!(paths(&mut s, merged), vec!["d/p", "d/q", "e", "n", "x/y"]); 1150 } 1151 1152 #[test] 1153 fn bound_is_enforced_pinned_nodes_survive_and_evicted_nodes_are_reported() { 1154 let mut s = TreeStore::new(TreeCacheConfig { 1155 max_bytes: MIN_TREE_CACHE_BYTES, 1156 }) 1157 .unwrap(); 1158 let base = build(&mut s, &[("keep/me", b"base")]); 1159 s.pin(base).unwrap(); 1160 let mut last = base; 1161 for i in 0..4000u32 { 1162 let mut e = TreeEdit::new(&mut s, base).unwrap(); 1163 e.upsert(&mut s, &format!("gen/{i}/f"), file(&i.to_le_bytes())) 1164 .unwrap(); 1165 last = e.finish(&mut s).unwrap(); 1166 assert!(s.total_bytes() <= MIN_TREE_CACHE_BYTES); 1167 } 1168 let st = s.stats(); 1169 assert!(st.nodes_evicted > 0, "{st:?}"); 1170 assert!(st.high_water_bytes <= MIN_TREE_CACHE_BYTES); 1171 assert!(s.contains(base) && s.contains(last)); 1172 assert_eq!(paths(&mut s, base), vec!["keep/me"]); 1173 let err = TreeStore::new(TreeCacheConfig { max_bytes: 1024 }) 1174 .err() 1175 .unwrap(); 1176 assert_eq!(err.code, RefusalCode::BackpressureOverCapacity); 1177 } 1178 }