znippy_plugin_git/forest.rs
1//! **The forest a pack already is** — and the reason resolving one is a
2//! [`gatling`](znippy_zoomies::gatling_forkjoin) job rather than a `for` loop.
3//!
4//! Every pack entry has **at most one** delta base. One parent per node is the
5//! definition of a forest, so the dependents [`crate::resolve`] has always
6//! collected (`ofs_deps`, `ref_deps`) are not an incidental index — they are the
7//! **children lists** of a forest whose roots are the entries that delta against
8//! nothing in this pack. Two different roots' subtrees share no object and no
9//! ordering constraint, so they are independent work.
10//!
11//! # Why this exists (MEASURED, oden 2026-08-30, lane Z)
12//!
13//! `torvalds/linux --mirror`: 8.12 GiB pack, 13 948 244 objects, 11 215 872
14//! deltas, on the appliance's 4 vCPU / 16 GB shape. Time to ack **3974 s**, of
15//! which `resolve_ms=3159178` — **52.6 minutes inside `Resolver::run`'s
16//! fixpoint, on ONE thread at ~4200 obj/s while three vCPUs sat idle**. Stock
17//! git acks the same mirror in ~11 minutes. The connectivity walk everybody
18//! blamed was 7m59s of the 66m14s.
19//!
20//! # What the shape buys, beyond the cores
21//!
22//! The fixpoint held a base from the moment it resolved until its **last
23//! dependent's position in the pack**, which is a distance the pack format does
24//! not bound — that is what `base_budget` and Belady eviction exist to cap. A
25//! depth-first walk of one subtree holds a base only while its **own subtree**
26//! is being walked, so the live set is the **path from the root to the current
27//! node** and nothing else. The ceiling is still there and still honoured; it is
28//! simply far below it.
29//!
30//! # What it costs, exactly
31//!
32//! Three `Vec<u32>` over the walk: `parent` (one slot per entry), `child_start`
33//! (one per entry plus one) and `child_of` (one per delta). For the kernel pack
34//! that is 55.8 + 55.8 + 44.9 = **156.5 MB**, and it **replaces**
35//! `HashMap<u64, Vec<usize>> ofs_deps` (2.7 M keys, 2.7 M heap `Vec`s, 11.2 M
36//! `usize`s — ~230 MB) plus the fixpoint's `remaining`/`stuck` index vectors
37//! (111 MB each). The forest is the cheaper of the two representations of the
38//! same fact (LAW 5: it is built from `PackWalk::entries` and nothing else).
39
40use anyhow::{Result, bail};
41
42use crate::pack_walk::{DeltaBase, PackWalk};
43
44/// No parent — the entry is a root of its tree.
45pub const NO_PARENT: u32 = u32::MAX;
46
47/// A bitset over the pack's entries. One bit per entry: 1.7 MB for the kernel
48/// pack, against 111 MB for the `Vec<usize>` of indices it replaces.
49#[derive(Clone)]
50pub struct EntrySet {
51 words: Vec<u64>,
52 len: usize,
53 count: usize,
54}
55
56impl EntrySet {
57 pub fn new(len: usize) -> Self {
58 Self {
59 words: vec![0u64; len.div_ceil(64)],
60 len,
61 count: 0,
62 }
63 }
64
65 #[inline]
66 pub fn contains(&self, i: usize) -> bool {
67 i < self.len && (self.words[i >> 6] >> (i & 63)) & 1 == 1
68 }
69
70 #[inline]
71 pub fn insert(&mut self, i: usize) -> bool {
72 let (w, b) = (i >> 6, i & 63);
73 if (self.words[w] >> b) & 1 == 1 {
74 return false;
75 }
76 self.words[w] |= 1u64 << b;
77 self.count += 1;
78 true
79 }
80
81 /// How many entries are in the set — the round's object count, without a
82 /// second pass over the bits.
83 pub fn len(&self) -> usize {
84 self.count
85 }
86
87 pub fn is_empty(&self) -> bool {
88 self.count == 0
89 }
90
91 /// Fold another set of the same width in. What a fixpoint uses to say
92 /// "these are resolved now" without a pass over the entries.
93 pub fn union_with(&mut self, other: &EntrySet) {
94 debug_assert_eq!(self.len_bits(), other.len_bits());
95 let mut count = 0usize;
96 for (a, b) in self.words.iter_mut().zip(other.words.iter()) {
97 *a |= *b;
98 count += a.count_ones() as usize;
99 }
100 self.count = count;
101 }
102
103 /// How many entries the set spans, set or not.
104 pub fn len_bits(&self) -> usize {
105 self.len
106 }
107
108 pub fn clear(&mut self) {
109 self.words.iter_mut().for_each(|w| *w = 0);
110 self.count = 0;
111 }
112}
113
114/// **The dependents of every entry, as a forest.**
115///
116/// Children are in **ascending entry order** inside `child_of`, which is what
117/// makes a depth-first walk of a subtree a fixed sequence and therefore makes
118/// the resolver's output independent of how many workers walked it.
119pub struct DeltaForest {
120 parent: Vec<u32>,
121 child_start: Vec<u32>,
122 child_of: Vec<u32>,
123 /// Entries that delta against nothing at all: the roots that are resolvable
124 /// without a single lookup.
125 whole_roots: Vec<u32>,
126 /// Entries that delta against an oid. Their parent is not knowable from the
127 /// walk — an oid is what the resolver *computes* — so they are roots of
128 /// their own subtrees until a round places them.
129 ref_roots: Vec<u32>,
130}
131
132impl DeltaForest {
133 /// Build it from the walk, and from nothing else.
134 pub fn build(w: &PackWalk) -> Result<Self> {
135 let n = w.entries.len();
136 let mut parent = vec![NO_PARENT; n];
137 let mut whole_roots = Vec::new();
138 let mut ref_roots = Vec::new();
139 let mut kids = vec![0u32; n + 1];
140 for (i, e) in w.entries.iter().enumerate() {
141 match &e.delta_base {
142 DeltaBase::None => whole_roots.push(i as u32),
143 DeltaBase::Ref(_) => ref_roots.push(i as u32),
144 DeltaBase::Offset(o) => {
145 // Offsets ascend in entry order — the walk's own invariant —
146 // so the base is found by binary search and is always
147 // *earlier* than the entry that deltas against it.
148 let p = w.entries.binary_search_by_key(o, |x| x.offset).map_err(|_| {
149 anyhow::anyhow!(
150 "entry at offset {} deltas against offset {o} which no entry starts \
151 at — the pack is corrupt",
152 e.offset
153 )
154 })?;
155 if p >= i {
156 bail!(
157 "entry at offset {} deltas against offset {o}, which is not earlier \
158 in the pack — the pack is corrupt",
159 e.offset
160 );
161 }
162 parent[i] = p as u32;
163 kids[p] += 1;
164 }
165 }
166 }
167 // Counting sort into CSR: prefix-sum the per-parent counts, then fill in
168 // ascending entry order so every child list comes out sorted.
169 let mut child_start = vec![0u32; n + 1];
170 let mut acc = 0u32;
171 for i in 0..n {
172 child_start[i] = acc;
173 acc += kids[i];
174 }
175 child_start[n] = acc;
176 let mut fill = child_start.clone();
177 let mut child_of = vec![0u32; acc as usize];
178 for i in 0..n {
179 let p = parent[i];
180 if p != NO_PARENT {
181 child_of[fill[p as usize] as usize] = i as u32;
182 fill[p as usize] += 1;
183 }
184 }
185 Ok(Self {
186 parent,
187 child_start,
188 child_of,
189 whole_roots,
190 ref_roots,
191 })
192 }
193
194 pub fn entries(&self) -> usize {
195 self.parent.len()
196 }
197
198 #[inline]
199 pub fn children(&self, i: u32) -> &[u32] {
200 let (a, b) = (self.child_start[i as usize] as usize, self.child_start[i as usize + 1] as usize);
201 &self.child_of[a..b]
202 }
203
204 #[inline]
205 pub fn parent(&self, i: u32) -> u32 {
206 self.parent[i as usize]
207 }
208
209 /// The entries that need no lookup at all to resolve.
210 pub fn whole_roots(&self) -> &[u32] {
211 &self.whole_roots
212 }
213
214 /// The `REF_DELTA` entries, in ascending order.
215 pub fn ref_roots(&self) -> &[u32] {
216 &self.ref_roots
217 }
218
219 /// **Which entries a round covers**, given the roots it starts from.
220 ///
221 /// One forward sweep and no stack: a parent's index is always lower than its
222 /// child's (offsets ascend), so `i` is reachable exactly when its parent is,
223 /// and that is already decided by the time the sweep gets to `i`.
224 pub fn closure_of(&self, roots: &[u32]) -> EntrySet {
225 let n = self.entries();
226 let mut set = EntrySet::new(n);
227 let mut is_root = EntrySet::new(n);
228 for &r in roots {
229 is_root.insert(r as usize);
230 }
231 for i in 0..n {
232 let reachable = if is_root.contains(i) {
233 true
234 } else {
235 match self.parent[i] {
236 NO_PARENT => false,
237 p => set.contains(p as usize),
238 }
239 };
240 if reachable {
241 set.insert(i);
242 }
243 }
244 set
245 }
246
247 /// Total nodes in the subtree rooted at `r`, counting `r`. What a scheduler
248 /// weighs a unit by, and what a test asserts a partition against.
249 pub fn subtree_size(&self, r: u32) -> u64 {
250 let mut stack = vec![r];
251 let mut n = 0u64;
252 while let Some(x) = stack.pop() {
253 n += 1;
254 stack.extend_from_slice(self.children(x));
255 }
256 n
257 }
258}
259
260#[cfg(test)]
261mod tests {
262 use super::*;
263 use crate::object::GitHashKind;
264 use crate::pack_walk::walk;
265
266 /// The generated corpus first — a pack this repository states in source, so
267 /// the assertions below hold on a fresh clone — then whatever real packs
268 /// this machine happens to carry, which is the only place a **thin** pack
269 /// (a `REF_DELTA` root) turns up in the wild.
270 fn corpus(cap: usize) -> Vec<(String, Vec<u8>)> {
271 let mut out: Vec<(String, Vec<u8>)> =
272 vec![("the generated corpus".to_string(), crate::pack_fixture::corpus().pack.clone())];
273 let Ok(repos) = std::fs::read_dir(std::path::Path::new("/home/rickard/git")) else {
274 return out;
275 };
276 for repo in repos.flatten() {
277 let Ok(files) = std::fs::read_dir(repo.path().join(".git/objects/pack")) else {
278 continue;
279 };
280 for f in files.flatten() {
281 let p = f.path();
282 if p.extension().is_some_and(|e| e == "pack")
283 && f.metadata().map(|m| m.len() < 32 << 20).unwrap_or(false)
284 && let Ok(bytes) = std::fs::read(&p)
285 {
286 out.push((p.display().to_string(), bytes));
287 if out.len() >= cap {
288 return out;
289 }
290 }
291 }
292 }
293 out
294 }
295
296 #[test]
297 fn every_entry_has_at_most_one_parent_and_the_children_are_its_dependents() {
298 let mut seen = 0;
299 for (name, pack) in corpus(6) {
300 let w = walk(&pack, GitHashKind::Sha1.oid_len()).expect("walk");
301 let f = DeltaForest::build(&w).expect("forest");
302 assert_eq!(f.entries(), w.entries.len(), "{name}");
303 // Every OFS delta is a child of exactly the entry at its base offset.
304 let mut children_seen = 0usize;
305 for (i, e) in w.entries.iter().enumerate() {
306 match &e.delta_base {
307 crate::pack_walk::DeltaBase::Offset(o) => {
308 let p = f.parent(i as u32);
309 assert_ne!(p, NO_PARENT, "{name} entry {i}");
310 assert_eq!(w.entries[p as usize].offset, *o, "{name} entry {i}");
311 assert!(f.children(p).contains(&(i as u32)), "{name} entry {i}");
312 children_seen += 1;
313 }
314 _ => assert_eq!(f.parent(i as u32), NO_PARENT, "{name} entry {i}"),
315 }
316 }
317 let total: usize = (0..w.entries.len()).map(|i| f.children(i as u32).len()).sum();
318 assert_eq!(total, children_seen, "{name}: every child is somebody's");
319 // Children are ascending — the fixed sequence determinism rests on.
320 for i in 0..w.entries.len() {
321 let c = f.children(i as u32);
322 assert!(c.windows(2).all(|p| p[0] < p[1]), "{name} entry {i} children unsorted");
323 }
324 seen += 1;
325 }
326 assert!(seen > 0, "no real packs in the corpus — the assertion above proved nothing");
327 }
328
329 #[test]
330 fn the_closure_of_the_whole_roots_is_every_entry_that_is_not_a_ref_delta_subtree() {
331 for (name, pack) in corpus(6) {
332 let w = walk(&pack, GitHashKind::Sha1.oid_len()).expect("walk");
333 let f = DeltaForest::build(&w).expect("forest");
334 let set = f.closure_of(f.whole_roots());
335 // A self-contained pack has no ref deltas, so the closure is everything.
336 let refs = f.ref_roots().len();
337 if refs == 0 {
338 assert_eq!(set.len(), w.entries.len(), "{name}");
339 } else {
340 assert!(set.len() < w.entries.len(), "{name}");
341 }
342 // The two sets partition the pack: closure(whole) + closure(refs).
343 let rest = f.closure_of(f.ref_roots());
344 assert_eq!(set.len() + rest.len(), w.entries.len(), "{name}");
345 for i in 0..w.entries.len() {
346 assert!(set.contains(i) ^ rest.contains(i), "{name} entry {i} in both or neither");
347 }
348 }
349 }
350
351 #[test]
352 fn the_subtree_sizes_of_the_roots_sum_to_the_pack() {
353 for (name, pack) in corpus(4) {
354 let w = walk(&pack, GitHashKind::Sha1.oid_len()).expect("walk");
355 let f = DeltaForest::build(&w).expect("forest");
356 let total: u64 = f
357 .whole_roots()
358 .iter()
359 .chain(f.ref_roots().iter())
360 .map(|r| f.subtree_size(*r))
361 .sum();
362 assert_eq!(total, w.entries.len() as u64, "{name}");
363 }
364 }
365
366 #[test]
367 fn an_empty_pack_has_an_empty_forest() {
368 let set = EntrySet::new(0);
369 assert!(set.is_empty());
370 assert!(!set.contains(0));
371 }
372}