Skip to main content

znippy_plugin_git/
sections.rs

1//! `GitIndexBuilder` — turns a set of git objects into the three reserved
2//! sections a `git`-format archive carries.
3//!
4//! The caller (gunnar's `repack()`, or a test) hands over the canonical bytes of
5//! every object it is sealing. The builder derives each object's oid **by
6//! hashing those bytes**, so the oid it indexes and the `relative_path` the
7//! archive stores cannot drift apart — there is no second place where an oid is
8//! spelled.
9//!
10//! Payloads are retained only for commits and trees. Blobs are leaves in the
11//! reachability graph and contribute nothing but their oid, so their bytes are
12//! dropped as soon as they are hashed. On a real repository that is the
13//! difference between holding the metadata and holding the repository.
14//!
15//! The oid index needs lookup **row numbers**, which only exist once the sink has
16//! sorted the lookup — hence [`GitIndexBuilder::into_reserved_builder`], which
17//! defers exactly that step to `ArrowIpcSink::finish`.
18//!
19//! ## Two tiers, one seal path
20//!
21//! A `git` archive holds a repository one of two ways, and the builder has a
22//! constructor for each:
23//!
24//! | constructor | data entries | derived sections |
25//! |---|---|---|
26//! | [`GitIndexBuilder::new`] | one per object, named by its oid | `__gunnar_oid__`, `__gunnar_graph__`, `__gunnar_reach__` |
27//! | [`GitIndexBuilder::pack_tier`] | `pack-<id>.pack` / `.idx` | none — the pack's own `.idx` is the index |
28//!
29//! [`with_section`](GitIndexBuilder::with_section) — the refs and secrets push
30//! logs — works identically on both, because it is the *server's* log and has
31//! nothing to do with how the objects are laid out. That is the reason both
32//! tiers route through this one type instead of growing a second writer.
33
34use std::collections::HashMap;
35
36use anyhow::{Result, anyhow, bail};
37use znippy_common::{
38    GUNNAR_GRAPH_MODULE, GUNNAR_OID_MODULE, GUNNAR_REACH_MODULE, ReservedSection,
39    ReservedSectionBuilder,
40};
41
42use crate::graph::{CommitNode, assign_generations, build_graph_batch, graph_schema};
43use crate::object::{GitHashKind, GitObjectKind, parse_canonical};
44use crate::oid_index::{OidEntry, build_section};
45use crate::reach::{ObjectFacts, OrdinalSpace, ReachPolicy, build_reach, build_reach_batch, reach_schema};
46
47/// Accumulates objects and emits the reserved sections.
48pub struct GitIndexBuilder {
49    hash: GitHashKind,
50    /// oid hex → object kind, in insertion order via `order`.
51    kinds: HashMap<String, GitObjectKind>,
52    order: Vec<String>,
53    /// Tree payloads, kept for the reachability closure.
54    trees: HashMap<String, Vec<u8>>,
55    /// Commit rows, before generation numbers are assigned.
56    commits: Vec<CommitNode>,
57    reach: ReachPolicy,
58    /// When false, `__gunnar_reach__` is not emitted at all — an archive that
59    /// declares no bitmaps is a different thing from one that declares empty
60    /// bitmaps, and a consumer must be able to tell them apart.
61    emit_reach: bool,
62    /// This archive's objects live in **packfiles**, not as one entry per oid.
63    ///
64    /// See [`GitIndexBuilder::pack_tier`]. The three derived sections are then
65    /// not emitted at all, because the pack's own `.idx` already is the oid
66    /// index and emitting an empty `__gunnar_oid__` beside it would state, in a
67    /// section consumers trust, that the archive holds no objects.
68    objects_in_packs: bool,
69    /// Already-built sections handed in by the caller — the sealed
70    /// `__gunnar_refs__` and `__gunnar_secrets__` push logs.
71    ///
72    /// They come in ready-made rather than being built here because their
73    /// contents are a *log*, owned and appended to by the running server, not
74    /// something derivable from the object set. Routing them through this one
75    /// builder is what keeps a single seal path (LAW 5): gunnar's `repack()`
76    /// hands over refs and secrets, and every reserved section the archive ends
77    /// up carrying is emitted by the same code.
78    extra: Vec<ReservedSection>,
79}
80
81impl GitIndexBuilder {
82    pub fn new(hash: GitHashKind) -> Self {
83        Self {
84            hash,
85            kinds: HashMap::new(),
86            order: Vec::new(),
87            trees: HashMap::new(),
88            commits: Vec::new(),
89            reach: ReachPolicy::default(),
90            emit_reach: true,
91            objects_in_packs: false,
92            extra: Vec::new(),
93        }
94    }
95
96    /// A builder for a **pack-tier** archive: one whose data entries are
97    /// `pack-<id>.pack` / `pack-<id>.idx` rather than one entry per object.
98    ///
99    /// This is what gunnar's `repack()` seals. The reasoning is not znippy's to
100    /// re-argue but is worth stating, because it decides what this builder must
101    /// *not* emit: a git object inside a pack is already deflated and often a
102    /// delta, so a tier that stores inflated content per oid pays a full
103    /// inflate-plus-deflate round trip on every fetch, for ever, and can never
104    /// be pack-copied. Measured on gunnar's own fixture, a znippy archive of
105    /// 60000 small git objects came out **3.4× larger than its input** — the
106    /// tier inflated rather than compressed.
107    ///
108    /// So the three derived sections are not emitted:
109    ///
110    /// * `__gunnar_oid__` — the pack's `.idx` **is** the oid index, and a far
111    ///   better one: it addresses pack offsets, which is what a reader needs.
112    /// * `__gunnar_graph__` / `__gunnar_reach__` — derived from object payloads
113    ///   this builder never sees.
114    ///
115    /// They are omitted rather than emitted empty. An empty `__gunnar_oid__`
116    /// beside a pack holding a million objects is not a smaller truth, it is a
117    /// false one, and [`GitOidIndex::open`](crate::GitOidIndex::open) returning
118    /// `None` is the state a consumer can act on.
119    ///
120    /// [`with_section`](Self::with_section) still works and is the point: refs
121    /// and secrets are sealed the same way, through this one composition point,
122    /// whichever tier the archive holds (LAW 5).
123    pub fn pack_tier(hash: GitHashKind) -> Self {
124        Self {
125            objects_in_packs: true,
126            ..Self::new(hash)
127        }
128    }
129
130    /// True when this builder seals a pack tier rather than loose objects.
131    pub fn is_pack_tier(&self) -> bool {
132        self.objects_in_packs
133    }
134
135    /// Seal an already-built reserved section — the `__gunnar_refs__` or
136    /// `__gunnar_secrets__` push log — alongside the object sections.
137    ///
138    /// Refused unless the module is reserved: a section the manifest readers do
139    /// not classify as reserved is merged into the *data* index, which silently
140    /// corrupts `list`, `decompress` and the iceberg sink. Catching it here
141    /// names the offending module, instead of surfacing later as a wrong file
142    /// count.
143    pub fn with_section(mut self, section: ReservedSection) -> Result<Self> {
144        if !znippy_common::is_reserved_module(&section.module_name) {
145            bail!(
146                "'{}' is not a reserved module — sealing it would merge it into the data index",
147                section.module_name
148            );
149        }
150        self.extra.push(section);
151        Ok(self)
152    }
153
154    pub fn with_reach_policy(mut self, policy: ReachPolicy) -> Self {
155        self.reach = policy;
156        self
157    }
158
159    /// Do not emit `__gunnar_reach__`. Use when the bitmaps' build cost is not
160    /// wanted for this repack.
161    pub fn without_reach(mut self) -> Self {
162        self.emit_reach = false;
163        self
164    }
165
166    pub fn hash_kind(&self) -> GitHashKind {
167        self.hash
168    }
169
170    pub fn len(&self) -> usize {
171        self.order.len()
172    }
173
174    pub fn is_empty(&self) -> bool {
175        self.order.is_empty()
176    }
177
178    /// Add one object from its canonical bytes. Returns the oid hex — which is
179    /// also the `relative_path` the archive must store the object under.
180    pub fn push_canonical(&mut self, canonical_bytes: &[u8]) -> Result<String> {
181        // Refused rather than accepted-and-ignored. A pack-tier builder emits no
182        // oid index, so an object handed to it would be silently absent from
183        // every section — and the archive would still seal, still verify, and
184        // still be wrong. The two tiers are alternatives, not a mixture.
185        if self.objects_in_packs {
186            bail!(
187                "this is a pack-tier archive: its objects live in `pack-<id>.pack`, and the \
188                 pack's own `.idx` is the oid index. Use `GitIndexBuilder::new` to seal loose \
189                 objects instead."
190            );
191        }
192        let obj = parse_canonical(canonical_bytes)
193            .ok_or_else(|| anyhow!("not a canonical git object (`<type> <size>\\0<content>`)"))?;
194        let oid = self.hash.oid_hex_of(canonical_bytes);
195        if self.kinds.insert(oid.clone(), obj.kind).is_none() {
196            self.order.push(oid.clone());
197        }
198        match obj.kind {
199            GitObjectKind::Tree => {
200                self.trees.insert(oid.clone(), obj.payload.to_vec());
201            }
202            GitObjectKind::Commit => {
203                let h = crate::object::parse_commit(obj.payload);
204                self.commits.push(CommitNode {
205                    oid: oid.clone(),
206                    parents: h.parents,
207                    tree: h.tree,
208                    committer_time: h.committer_time,
209                    generation: 0,
210                });
211            }
212            _ => {}
213        }
214        Ok(oid)
215    }
216
217    /// Add many objects at once.
218    pub fn extend_canonical<'a, I: IntoIterator<Item = &'a [u8]>>(
219        &mut self,
220        objects: I,
221    ) -> Result<Vec<String>> {
222        objects.into_iter().map(|b| self.push_canonical(b)).collect()
223    }
224
225    /// The distinct objects in oid-lexicographic order — the ordinal space,
226    /// whose index IS each oid's ordinal. This is the order `__gunnar_reach__`
227    /// bitmaps address and the `ordinal` column of `__gunnar_oid__` records. The
228    /// hex→ordinal map that used to accompany it is gone: oid ⇄ ordinal is
229    /// served off the raw buffer built below by [`crate::reach::OrdinalSpace`].
230    fn sorted_oids(&self) -> Vec<&str> {
231        let mut sorted: Vec<&str> = self.order.iter().map(|s| s.as_str()).collect();
232        sorted.sort_unstable();
233        sorted
234    }
235
236    /// Build the sections against an explicit path → first-lookup-row mapping.
237    ///
238    /// Separated from [`into_reserved_builder`](Self::into_reserved_builder) so
239    /// it is testable without sealing an archive, and so the sink path and the
240    /// direct path are the same code (LAW 5).
241    pub fn build_sections(&self, first_row: &HashMap<&str, u64>) -> Result<Vec<ReservedSection>> {
242        // A pack tier derives nothing from object payloads it never saw. Not an
243        // early return over an empty vector by accident: see
244        // [`GitIndexBuilder::pack_tier`] for why absent beats empty here.
245        if self.objects_in_packs {
246            return Ok(Vec::new());
247        }
248        let sorted = self.sorted_oids();
249
250        let mut entries = Vec::with_capacity(sorted.len());
251        // The flat, sorted, fixed-width ordinal space — built once here, in the
252        // same loop that decodes each oid, and borrowed as an `OrdinalSpace`
253        // below. Sorted order IS ordinal order, so this needs no sort of its own.
254        let mut oids_raw = Vec::with_capacity(sorted.len() * self.hash.oid_len());
255        for (i, oid_hex) in sorted.iter().enumerate() {
256            let raw = hex::decode(oid_hex)
257                .map_err(|e| anyhow!("oid {oid_hex} is not hex: {e}"))?;
258            if raw.len() != self.hash.oid_len() {
259                bail!(
260                    "oid {oid_hex} is {} bytes, expected {} for {:?}",
261                    raw.len(),
262                    self.hash.oid_len(),
263                    self.hash
264                );
265            }
266            let row = *first_row.get(*oid_hex).ok_or_else(|| {
267                anyhow!(
268                    "object {oid_hex} was indexed but no archive entry has it as its \
269                     relative_path — the archive and the git index disagree"
270                )
271            })?;
272            oids_raw.extend_from_slice(&raw);
273            entries.push(OidEntry { oid: raw, lookup_row: row, ordinal: i as u32 });
274        }
275
276        let mut sections = vec![ReservedSection::raw(
277            GUNNAR_OID_MODULE,
278            build_section(&entries, self.hash)?,
279        )];
280
281        let commits = assign_generations(self.commits.clone());
282        sections.push(ReservedSection::arrow(
283            GUNNAR_GRAPH_MODULE,
284            graph_schema(),
285            vec![build_graph_batch(&commits)?],
286        ));
287
288        if self.emit_reach {
289            let facts = ObjectFacts {
290                ordinal: OrdinalSpace::new(&oids_raw, self.hash.oid_len()),
291                trees: &self.trees,
292                oid_len: self.hash.oid_len(),
293            };
294            let reach = build_reach(&commits, &facts, self.reach);
295            sections.push(ReservedSection::arrow(
296                GUNNAR_REACH_MODULE,
297                reach_schema(),
298                vec![build_reach_batch(&reach)?],
299            ));
300        }
301        Ok(sections)
302    }
303
304    /// Every reserved section this archive will carry: the object sections from
305    /// [`build_sections`](Self::build_sections), then the caller's push logs.
306    ///
307    /// The one composition point. Both the direct path and the sink path go
308    /// through it, so a section added here cannot reach one and miss the other.
309    pub fn finish_sections(mut self, first_row: &HashMap<&str, u64>) -> Result<Vec<ReservedSection>> {
310        let mut sections = self.build_sections(first_row)?;
311        sections.append(&mut self.extra);
312        Ok(sections)
313    }
314
315    /// Hand the builder to `ArrowIpcSink::with_reserved_builder`.
316    ///
317    /// The closure runs at seal time with the sink's final sorted lookup, so
318    /// `__gunnar_oid__` points at the rows the archive actually has. It fails
319    /// loudly — rather than emitting a silently wrong index — if an object it
320    /// was given is not present in the archive as a `relative_path`.
321    pub fn into_reserved_builder(self) -> ReservedSectionBuilder {
322        Box::new(move |view| {
323            let rows = view.first_rows();
324            let first_row: HashMap<&str, u64> = rows.into_iter().collect();
325            self.finish_sections(&first_row)
326        })
327    }
328}
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333    use crate::object::{GitObjectKind, canonical};
334    use crate::oid_index::GitOidIndex;
335    use znippy_common::ReservedPayload;
336
337    #[test]
338    fn a_missing_archive_entry_is_a_loud_error_not_a_wrong_index() {
339        let mut b = GitIndexBuilder::new(GitHashKind::Sha256);
340        let oid = b.push_canonical(&canonical(GitObjectKind::Blob, b"hi")).unwrap();
341        let empty: HashMap<&str, u64> = HashMap::new();
342        let err = b.build_sections(&empty).unwrap_err().to_string();
343        assert!(err.contains(&oid), "error should name the missing oid: {err}");
344    }
345
346    /// A pack-tier archive emits the push logs and **nothing derived**. The
347    /// distinction that matters is absent-versus-empty: an empty
348    /// `__gunnar_oid__` beside a pack of a million objects would read, to every
349    /// consumer, as "this archive holds nothing".
350    #[test]
351    fn a_pack_tier_emits_the_push_logs_and_no_derived_section() {
352        let dir = tempfile::tempdir().unwrap();
353        let refs = crate::refs::RefLog::new(dir.path().join("refs.log"));
354        refs.push(&[crate::refs::RefUpdate::set("refs/heads/main", &"a".repeat(64))])
355            .unwrap();
356
357        let b = GitIndexBuilder::pack_tier(GitHashKind::Sha256)
358            .with_section(refs.seal_section().unwrap())
359            .unwrap();
360        assert!(b.is_pack_tier());
361
362        let empty: HashMap<&str, u64> = HashMap::new();
363        let derived = b.build_sections(&empty).unwrap();
364        assert!(
365            derived.is_empty(),
366            "a pack tier must derive no section from objects it never saw, got {:?}",
367            derived.iter().map(|s| s.module_name.clone()).collect::<Vec<_>>()
368        );
369
370        let all = b.finish_sections(&empty).unwrap();
371        let names: Vec<&str> = all.iter().map(|s| s.module_name.as_str()).collect();
372        assert_eq!(
373            names,
374            vec![znippy_common::GUNNAR_REFS_MODULE],
375            "the push log is the only section a pack tier carries"
376        );
377    }
378
379    /// The mirror, and the reason the test above is not vacuous: the SAME calls
380    /// on a loose-object builder do emit the derived sections. Without this a
381    /// builder that had stopped emitting them entirely would still pass.
382    #[test]
383    fn a_loose_object_builder_still_emits_all_three_derived_sections() {
384        let mut b = GitIndexBuilder::new(GitHashKind::Sha256);
385        let oid = b.push_canonical(&canonical(GitObjectKind::Blob, b"hi")).unwrap();
386        assert!(!b.is_pack_tier());
387        let rows: HashMap<&str, u64> = [(oid.as_str(), 0u64)].into_iter().collect();
388        let names: Vec<String> = b
389            .build_sections(&rows)
390            .unwrap()
391            .iter()
392            .map(|s| s.module_name.clone())
393            .collect();
394        assert_eq!(
395            names,
396            vec![
397                znippy_common::GUNNAR_OID_MODULE,
398                znippy_common::GUNNAR_GRAPH_MODULE,
399                znippy_common::GUNNAR_REACH_MODULE
400            ]
401        );
402    }
403
404    /// Handing an object to a pack-tier builder is refused, not ignored. If it
405    /// were ignored the archive would seal, verify and be silently wrong: the
406    /// object would be in no section at all.
407    #[test]
408    fn a_pack_tier_refuses_a_loose_object_rather_than_dropping_it() {
409        let mut b = GitIndexBuilder::pack_tier(GitHashKind::Sha256);
410        let err = b
411            .push_canonical(&canonical(GitObjectKind::Blob, b"hi"))
412            .unwrap_err()
413            .to_string();
414        assert!(
415            err.contains("pack-tier") || err.contains("pack tier") || err.contains("pack-<id>"),
416            "the refusal must say which tier this is: {err}"
417        );
418        assert_eq!(b.len(), 0, "the refused object must not have been recorded");
419    }
420
421    #[test]
422    fn ordinals_are_oid_lexicographic_and_match_the_oid_index() {
423        let mut b = GitIndexBuilder::new(GitHashKind::Sha1);
424        let mut oids = Vec::new();
425        for i in 0..40u32 {
426            oids.push(b.push_canonical(&canonical(GitObjectKind::Blob, format!("b{i}").as_bytes())).unwrap());
427        }
428        let rows: HashMap<&str, u64> =
429            oids.iter().enumerate().map(|(i, o)| (o.as_str(), i as u64 * 2)).collect();
430        let sections = b.build_sections(&rows).unwrap();
431
432        let ReservedPayload::Raw(oid_bytes) = &sections[0].payload else {
433            panic!("first section must be the raw oid index")
434        };
435        let index = GitOidIndex::parse(oid_bytes.clone()).unwrap();
436
437        let mut sorted = oids.clone();
438        sorted.sort();
439        for (i, o) in sorted.iter().enumerate() {
440            let hit = index.lookup_hex(o).unwrap();
441            assert_eq!(hit.ordinal, i as u32, "ordinal must be the oid-lexicographic rank");
442            assert_eq!(hit.lookup_row, rows[o.as_str()]);
443        }
444    }
445}