ifc_lite_git/tree.rs
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Trees: the manifest of one version, mapping `key -> node address`.
6//!
7//! This is where the entity key lives, and it is the whole of the
8//! GUID-agnostic design. A node address is its content ([`crate::node`]); the
9//! key that names it is here. So a from-scratch re-export that regenerates
10//! every `GlobalId` rewrites tree **keys** and leaves every node address
11//! untouched — the version reads as unchanged content under a key remapping,
12//! which is the rename case `@ifc-lite/diff`'s content-matching tiers resolve
13//! for one-to-one matches. They deliberately abstain where a match is not
14//! one-to-one — a group of re-GUIDed coincident duplicates yields no remapping
15//! at all — which is the same open case as relationship endpoints under
16//! deduplication (`crate::node::Node::Relationship`).
17//!
18//! # Chunking
19//!
20//! A real delivery is hundreds of thousands of entities. A monolithic manifest
21//! would be rewritten in full for a two-element change, so the manifest is
22//! split into content-addressed chunks and a tree is the list of chunk
23//! addresses; unchanged chunks are reused by reference between commits.
24//!
25//! Boundaries are **content-derived**, not positional. With fixed-size chunks,
26//! inserting one entity shifts every subsequent entry and invalidates every
27//! chunk after the insertion point. With a boundary chosen from the content
28//! itself, an insertion disturbs one chunk. This is the packfile problem git
29//! already solved; the design is reused, the code is not — git is GPL-2.0 and
30//! cannot enter an MPL-2.0 tree (see the spec set, index §6.2).
31
32use crate::address::{sort_key, Address, CanonicalWriter};
33
34/// Magic announcing the tree-chunk format.
35pub const CHUNK_MAGIC: &[u8; 4] = b"IGC1";
36/// Magic announcing the tree format.
37pub const TREE_MAGIC: &[u8; 4] = b"IGT1";
38/// Format version within both magics.
39pub const TREE_FORMAT_VERSION: u8 = 0;
40
41/// Target entries per chunk. Boundaries are content-derived, so this is an
42/// average rather than a cap — see the `is_boundary` predicate below.
43pub const TARGET_CHUNK_ENTRIES: usize = 512;
44
45/// One entry: an entity key, the node carrying its content, and its class.
46///
47/// `ifc_type` is duplicated here from the node deliberately, so listing a
48/// version's contents needs no node fetch. It costs a few bytes per entry and
49/// saves a random read per entry.
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct TreeEntry {
52 /// The entity's stable identity in THIS version — typically `GlobalId`.
53 pub key: String,
54 /// Address of the node carrying the entity's content.
55 pub node: Address,
56 /// Exact IFC EXPRESS PascalCase class.
57 pub ifc_type: String,
58}
59
60/// A run of entries, content-addressed so an unchanged run is reused.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct TreeChunk {
63 pub entries: Vec<TreeEntry>,
64}
65
66impl TreeChunk {
67 /// Canonical bytes and address.
68 pub fn encode(&self) -> (Address, Vec<u8>) {
69 let mut w = CanonicalWriter::new(CHUNK_MAGIC, 0, TREE_FORMAT_VERSION);
70 w.u32(self.entries.len() as u32);
71 for entry in &self.entries {
72 w.string(&entry.key);
73 w.address(&entry.node);
74 w.string(&entry.ifc_type);
75 }
76 w.finish()
77 }
78
79 pub fn address(&self) -> Address {
80 self.encode().0
81 }
82}
83
84/// A version's manifest: ordered chunk addresses.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct Tree {
87 pub chunks: Vec<Address>,
88 /// Total entries across all chunks, so a count needs no chunk fetch.
89 pub entry_count: u32,
90}
91
92impl Tree {
93 pub fn encode(&self) -> (Address, Vec<u8>) {
94 let mut w = CanonicalWriter::new(TREE_MAGIC, 0, TREE_FORMAT_VERSION);
95 w.u32(self.entry_count);
96 w.u32(self.chunks.len() as u32);
97 for chunk in &self.chunks {
98 w.address(chunk);
99 }
100 w.finish()
101 }
102
103 pub fn address(&self) -> Address {
104 self.encode().0
105 }
106}
107
108/// Should a chunk end after this entry?
109///
110/// Hash the canonical key and node address together, so repeated content under
111/// different entity keys does not force either one huge chunk or singleton chunks.
112/// An entry's boundary still depends only on that entry, never its position.
113fn is_boundary(entry: &TreeEntry, target: usize) -> bool {
114 let mut w = CanonicalWriter::new(b"IGB1", 0, TREE_FORMAT_VERSION);
115 w.string(&entry.key).address(&entry.node);
116 let digest = w.finish().0;
117 let bytes = digest.as_bytes();
118 boundary_probe(bytes, target)
119}
120
121/// Retain the v0/default 16-bit boundaries; larger targets use all 64 probe bits.
122fn boundary_probe(bytes: &[u8; 32], target: usize) -> bool {
123 if target <= 65_536 {
124 usize::from(u16::from_le_bytes([bytes[0], bytes[1]])).is_multiple_of(target)
125 } else {
126 let probe = u64::from_le_bytes(bytes[..8].try_into().expect("eight digest bytes"));
127 probe.is_multiple_of(target as u64)
128 }
129}
130
131/// Build a tree from entries, chunking on content-derived boundaries.
132///
133/// Entries are sorted by NFC-normalized key bytes first, so the same set
134/// of entries always produces the same tree regardless of the order the caller
135/// walked the model in.
136pub fn build_tree(mut entries: Vec<TreeEntry>) -> (Tree, Vec<TreeChunk>) {
137 build_tree_with_target(std::mem::take(&mut entries), TARGET_CHUNK_ENTRIES)
138}
139
140/// [`build_tree`] with an explicit chunk target, for tests that need small
141/// chunks without a hundred thousand entries.
142pub fn build_tree_with_target(
143 mut entries: Vec<TreeEntry>,
144 target: usize,
145) -> (Tree, Vec<TreeChunk>) {
146 assert!(target > 0, "chunk target must be positive");
147 entries.sort_by_cached_key(|entry| (sort_key(&entry.key), entry.node, sort_key(&entry.ifc_type)));
148
149 let entry_count = entries.len() as u32;
150 let mut chunks: Vec<TreeChunk> = Vec::new();
151 let mut current: Vec<TreeEntry> = Vec::new();
152
153 for entry in entries {
154 let boundary = is_boundary(&entry, target);
155 current.push(entry);
156 if boundary {
157 chunks.push(TreeChunk {
158 entries: std::mem::take(&mut current),
159 });
160 }
161 }
162 if !current.is_empty() {
163 chunks.push(TreeChunk { entries: current });
164 }
165
166 let tree = Tree {
167 chunks: chunks.iter().map(TreeChunk::address).collect(),
168 entry_count,
169 };
170 (tree, chunks)
171}
172
173#[cfg(test)]
174#[path = "tree_tests.rs"]
175mod tests;