Skip to main content

znippy_plugin_git/
exploded_arrow.rs

1//! **The exploded objects table: ONE Arrow IPC file, one row per object.**
2//!
3//! # What this replaces, and what it measured
4//!
5//! [`crate::exploded`] holds `oid → [kind][payload…]` in **redb**. It works, and
6//! it is the wrong medium — MEASURED on `linux.git`, oden 2026-08-13,
7//! 11 697 976 objects:
8//!
9//! | | |
10//! |---|---:|
11//! | pack as pushed (verbatim, deflated + delta-encoded) | 6.4 GB |
12//! | its objects fully resolved (`git verify-pack -v`, summed) | **16.8 GB** |
13//! | `objects.exploded` on disk | **204 GB** |
14//!
15//! So the 2026-08-08 eager decision was RIGHT — resolved content is **2.6×** the
16//! pack, comfortably inside the 3× it budgeted — and the medium was wrong by
17//! **12×**. redb is a copy-on-write B-tree: 11.7 million small keys committed in
18//! [`FLUSH_BYTES`] batches rewrite interior pages over and over, and 187 of
19//! those 204 GB are page churn rather than anybody's data.
20//!
21//! It cost throughput for the same reason. [`crate::indexer`] fans a drained
22//! batch across N workers with `gatling_for_each` (LAW 3, never rayon) and every
23//! one of them then queued behind redb's single write transaction — MEASURED:
24//! **96.8% of ONE core** with 31 idle while the exploder ran.
25//!
26//! # The shape
27//!
28//! One table, one file, the payload IN the row — which is what this engine
29//! already does everywhere else ([`crate::reach`] stores a bitmap as
30//! `DataType::Binary`, [`crate::secrets`] a ciphertext):
31//!
32//! ```text
33//!   oid | object_type | mode | path | payload
34//! ```
35//!
36//! An Arrow IPC stream is `[schema message][batch message]…` — append-only, no
37//! pages to rewrite, so the file is the payload total plus framing. Each flush
38//! encodes one batch with [`IpcDataGenerator`] and appends it with
39//! [`write_message`]; nothing earlier in the file is ever touched again.
40//!
41//! `payload` is `LargeBinary` and not `Binary` deliberately: `Binary` offsets are
42//! `i32`, so one batch would cap at 2 GiB of payload and overflow *silently* on a
43//! corpus nobody tested. The wider offset costs four bytes a row.
44//!
45//! ## `mode` and `path` — the row IS a file
46//!
47//! A git object on its own is content without a name. The two nullable columns
48//! carry the name when the caller knows it (a tree walk does; a bare pack
49//! resolve does not), which is what lets this table be read as a filesystem
50//! rather than as a content-addressed bag. They are **nullable and best-effort**
51//! for a reason that is inherent and not a shortcut: one blob is reachable at
52//! many paths in many commits, so a path column can only ever record *a* path —
53//! the one it was first exploded at. Null means "not known here", never "at the
54//! root".
55//!
56//! # Reopening is cheap, and the index is lazy
57//!
58//! A batch's *metadata* carries its row count and its body length, so
59//! [`ExplodedArchive::open`] walks the message framing — seeking over the bodies,
60//! reading kilobytes — and knows how many rows the table holds and where every
61//! batch begins without touching a gigabyte. That is what `adopt_journal` needs
62//! on startup.
63//!
64//! The `oid → row` index costs one sequential pass and is therefore built on the
65//! **first lookup**, not on open. A push-heavy process never pays for it; a
66//! process that reads pays once. After that a point read is two `pread`s — the
67//! schema message and the one batch — decoded through [`StreamDecoder`], so it
68//! never scans the batches in front of the one it wants.
69//!
70//! # The lookup is ragnar's static tree — see [`OidTree`]
71//!
72//! That index used to be a `Vec<(Vec<u8>, Located)>` walked with
73//! `binary_search_by`: one heap allocation per oid — **11.7 million** of them on
74//! `linux.git` — and a `log₂ n` chain of dependent loads over scattered `Vec`
75//! headers. It is now the same `stree` (`znippy-zoomies`) this crate already puts
76//! over oids in [`crate::oid_index`], over flat parallel arrays.
77//! `nornir-workspace.toml`'s performance law names that structure by name; this
78//! is the second place in this crate that obeys it, and it obeys it by reusing
79//! [`crate::oid_index::key_for_oid`] rather than deriving a second key.
80//!
81//! # Droppable, and it is one `rm`
82//!
83//! Every row is re-derivable from the verbatim pack bytes, so the file can be
84//! deleted without consulting a client:
85//! [`crate::git_ops::Absorber::adopt_journal`] compares this table's row count
86//! against the `objects` table's and re-queues every pack if it is short. Absent
87//! means fall back and rebuild; it never means wrong. One file, one delete —
88//! which is the property the engine's own tests assert.
89
90use std::fs::{File, OpenOptions};
91use std::io::{Read, Seek, SeekFrom, Write};
92use std::os::unix::fs::FileExt;
93use std::path::{Path, PathBuf};
94use std::sync::Arc;
95use std::sync::Mutex;
96use std::sync::atomic::{AtomicU64, Ordering};
97
98use anyhow::{Context, Result};
99use znippy_common::arrow::array::{
100    Array, FixedSizeBinaryArray, FixedSizeBinaryBuilder, LargeBinaryArray, LargeBinaryBuilder,
101    StringArray, StringBuilder, UInt8Array, UInt8Builder, UInt32Array, UInt32Builder,
102};
103use znippy_common::arrow::buffer::Buffer;
104use znippy_common::arrow::datatypes::{DataType, Field, Schema, SchemaRef};
105use znippy_common::arrow::ipc::reader::StreamDecoder;
106use znippy_common::arrow::ipc::writer::{
107    DictionaryTracker, IpcDataGenerator, IpcWriteOptions, write_message,
108};
109use znippy_common::arrow::ipc::root_as_message;
110use znippy_common::arrow::record_batch::RecordBatch;
111use znippy_zoomies::stree::STree64Mmap;
112
113use crate::object::GitObjectKind;
114use crate::oid_index::key_for_oid;
115
116pub const COL_OID: &str = "oid";
117pub const COL_TYPE: &str = "object_type";
118pub const COL_MODE: &str = "mode";
119pub const COL_PATH: &str = "path";
120pub const COL_PAYLOAD: &str = "payload";
121
122/// Buffered payload bytes that force a flush.
123///
124/// Not a memory *limit* — one object can exceed it on its own and is written
125/// anyway. It is what keeps a 2 GiB push from holding its whole resolved content
126/// in RAM before the first batch reaches the file.
127pub const FLUSH_BYTES: usize = 64 << 20;
128
129/// `oid | object_type | mode | path | payload`.
130///
131/// `oid_len` is a parameter because this engine serves both sha1 (20 bytes) and
132/// sha256 (32); a hardcoded 20 would silently truncate every sha256 key.
133/// **How each row's payload is stored** — `ENC_RAW` or `ENC_ZLIB`. Lever 3
134/// (2026-09-04): the eager pool was 1.67 GB of inflated commits and trees, 61 %
135/// of everything the store kept above the pack. Arrow IPC's own body
136/// compression is per BUFFER, so a point read could not lift one row out of a
137/// compressed batch and the `pread` extent fast path — the whole reason the
138/// pool is fast — would have died with it (`payload_data_offset` refuses
139/// compressed batches for exactly that reason; MEASURED 200 000× read
140/// amplification without the extent). So the compression is per ROW: the
141/// extent pread returns one compressed payload and inflates just that one.
142/// zlib, because the crate already has it (`flate2`, zlib-rs — pure Rust), and
143/// because it is the codec git itself uses per object, so the ratios are known
144/// ground.
145pub const COL_ENC: &str = "enc";
146pub const ENC_RAW: u8 = 0;
147pub const ENC_ZLIB: u8 = 1;
148/// Rows shorter than this are never compressed: a zlib header and trailer are
149/// 8 bytes, and a tiny tree does not earn them back. Set from
150/// `examples/explode_compress_ratio.rs` over the kernel mirror's pool.
151pub const MIN_ROW_COMPRESS: usize = 128;
152/// A compressed row must be at least this much smaller than the raw one to be
153/// kept compressed, or the inflate on every read buys nothing.
154const COMPRESS_KEEP_IF_UNDER_PERCENT: usize = 90;
155
156/// Schema v2 (2026-09-04): `enc` sits BEFORE `payload`, so the payload's data
157/// buffer stays the LAST buffer of the batch — which is what
158/// [`payload_data_offset`] reads the extent off. A v1 file has no `enc` column;
159/// every reader treats a missing column as [`ENC_RAW`], so pools written before
160/// this open unchanged and are never rewritten for it.
161pub fn exploded_schema(oid_len: usize) -> SchemaRef {
162    Arc::new(Schema::new(vec![
163        Field::new(COL_OID, DataType::FixedSizeBinary(oid_len as i32), false),
164        Field::new(COL_TYPE, DataType::UInt8, false),
165        Field::new(COL_MODE, DataType::UInt32, true),
166        Field::new(COL_PATH, DataType::Utf8, true),
167        Field::new(COL_ENC, DataType::UInt8, false),
168        Field::new(COL_PAYLOAD, DataType::LargeBinary, false),
169    ]))
170}
171
172/// Schema v1 — what every pool written before 2026-09-04 carries, and what this
173/// build keeps appending to such a pool (see `ExplodedArchive::legacy_v1`).
174pub fn exploded_schema_v1(oid_len: usize) -> SchemaRef {
175    Arc::new(Schema::new(vec![
176        Field::new(COL_OID, DataType::FixedSizeBinary(oid_len as i32), false),
177        Field::new(COL_TYPE, DataType::UInt8, false),
178        Field::new(COL_MODE, DataType::UInt32, true),
179        Field::new(COL_PATH, DataType::Utf8, true),
180        Field::new(COL_PAYLOAD, DataType::LargeBinary, false),
181    ]))
182}
183
184/// Compress one row's payload for storage, or `None` when it is not worth it
185/// (too short, or zlib did not get it under the keep threshold).
186///
187/// **`default` (level 6), not `fast`, and that is a measurement**
188/// (`examples/explode_compress_ratio.rs`, the kernel mirror's eager pool,
189/// 1 722 249 rows / 1 609 688 036 B of commits and tags, 2026-09-04):
190///
191/// | level | pool after | ratio | saved |
192/// |---|---:|---:|---:|
193/// | fast | 1 138 092 314 B | 1.41× | 471 595 722 B |
194/// | **default** | **889 639 690 B** | **1.81×** | **720 048 346 B** |
195///
196/// Inflate cost is the SAME at both — 3.07 µs/row mean over 20 000 sampled
197/// rows — because zlib decode speed does not depend on the level. So the read
198/// path pays +3 µs on a point read (first-read p50 was 3.9 µs) whichever level
199/// is chosen, and the only thing the level decides is how much disk that buys:
200/// 44.7 % of the pool at `default` against 29.3 % at `fast`. The write pays
201/// more CPU at `default`, on the indexer's threads, once per object.
202fn compress_row(raw: &[u8]) -> Option<Vec<u8>> {
203    use std::io::Write as _;
204    if raw.len() < MIN_ROW_COMPRESS {
205        return None;
206    }
207    let mut e = flate2::write::ZlibEncoder::new(
208        Vec::with_capacity(raw.len() / 2 + 16),
209        flate2::Compression::default(),
210    );
211    e.write_all(raw).ok()?;
212    let z = e.finish().ok()?;
213    (z.len() * 100 < raw.len() * COMPRESS_KEEP_IF_UNDER_PERCENT).then_some(z)
214}
215
216/// The row's payload as the caller wants it — inflated if it was stored
217/// compressed. `bytes` is exactly what the column (or the extent pread) held.
218fn row_payload(enc: u8, bytes: &[u8]) -> Result<Vec<u8>> {
219    use std::io::Read as _;
220    match enc {
221        ENC_RAW => Ok(bytes.to_vec()),
222        ENC_ZLIB => {
223            let mut out = Vec::with_capacity(bytes.len() * 3);
224            flate2::read::ZlibDecoder::new(bytes)
225                .read_to_end(&mut out)
226                .context("inflating a compressed exploded row")?;
227            Ok(out)
228        }
229        other => anyhow::bail!("exploded row carries unknown encoding {other}"),
230    }
231}
232
233/// The `enc` column of a decoded batch, or `None` on a v1 batch (every row raw).
234fn enc_column(batch: &RecordBatch) -> Option<&UInt8Array> {
235    batch
236        .column_by_name(COL_ENC)
237        .and_then(|c| c.as_any().downcast_ref::<UInt8Array>())
238}
239
240#[inline]
241fn enc_at(enc: Option<&UInt8Array>, row: usize) -> u8 {
242    enc.map_or(ENC_RAW, |e| e.value(row))
243}
244
245/// The pack type codes, the same mapping [`crate::exploded`] uses, so the two
246/// media cannot disagree about what a `2` means.
247pub fn kind_code(k: GitObjectKind) -> u8 {
248    match k {
249        GitObjectKind::Commit => 1,
250        GitObjectKind::Tree => 2,
251        GitObjectKind::Blob => 3,
252        GitObjectKind::Tag => 4,
253    }
254}
255
256pub fn kind_of(code: u8) -> Option<GitObjectKind> {
257    match code {
258        1 => Some(GitObjectKind::Commit),
259        2 => Some(GitObjectKind::Tree),
260        3 => Some(GitObjectKind::Blob),
261        4 => Some(GitObjectKind::Tag),
262        _ => None,
263    }
264}
265
266/// **A row that retires an oid.**
267///
268/// The file is append-only, so `retain` cannot reach back and delete: it appends
269/// rows that say *this oid is gone*, and the index fold applies them in file
270/// order, so the last word about an oid wins. Dropping only from the in-memory
271/// index is what a first cut did, and it was WRONG in the way that matters —
272/// `a_wholly_dead_pack_does_not_come_back_when_the_store_is_reopened` came back
273/// with **551 commits instead of 1**, because a reopen rebuilds the index from
274/// the file and resurrected every row `gc` had retired.
275///
276/// `0` and not a sixth column: git's pack type codes are 1–7 and 0 is not one of
277/// them, so [`kind_of`] already answers `None` for it. A tombstone costs an oid
278/// and an empty payload, not a byte on every live row.
279pub const TOMBSTONE: u8 = 0;
280
281/// One buffered row, waiting for the next batch. `code` rather than a
282/// [`GitObjectKind`] because a tombstone is a row with no kind.
283#[derive(Debug, Clone)]
284struct Pending {
285    oid: Vec<u8>,
286    code: u8,
287    mode: Option<u32>,
288    path: Option<String>,
289    /// Where this row's bytes are in [`PendingBatch::arena`]. **Not a
290    /// `Vec<u8>`** — see [`PendingBatch`].
291    pay: std::ops::Range<usize>,
292}
293
294/// The rows buffered for the next batch, and **one arena holding their bytes**.
295///
296/// # Why the bytes are not in the row
297///
298/// `payload: Vec<u8>` cost one heap allocation and one `memcpy` of the whole
299/// object **per buffered row**, and on the lazy write-back path that allocation
300/// is a second copy of bytes the reader is holding anyway. MEASURED by lane AA,
301/// 2026-08-30: reading one 3 145 728 B object through `gunnar-cli` allocated
302/// 6 340 693 B — *exactly two copies* — and the second was this one.
303///
304/// An arena makes the write an `extend_from_slice` into a buffer that grows
305/// geometrically and is reused after every flush, so the bytes attributable to
306/// one admitted read amortise to zero and a **declined** read costs nothing at
307/// all (the admission gate returns before this is reached). LAW: zero copy.
308#[derive(Default)]
309struct PendingBatch {
310    rows: Vec<Pending>,
311    arena: Vec<u8>,
312}
313
314impl PendingBatch {
315    fn is_empty(&self) -> bool {
316        self.rows.is_empty()
317    }
318    /// Buffer one row's bytes and return the range they landed in.
319    fn stash(&mut self, payload: &[u8]) -> std::ops::Range<usize> {
320        let start = self.arena.len();
321        self.arena.extend_from_slice(payload);
322        start..self.arena.len()
323    }
324    fn bytes(&self, r: &Pending) -> &[u8] {
325        &self.arena[r.pay.clone()]
326    }
327    /// Hand the batch over for encoding and keep the arena's capacity: the next
328    /// batch reuses the same allocation, which is what makes the per-read cost
329    /// amortise.
330    fn take(&mut self) -> (Vec<Pending>, Vec<u8>) {
331        let rows = std::mem::take(&mut self.rows);
332        let arena = std::mem::replace(&mut self.arena, Vec::with_capacity(0));
333        (rows, arena)
334    }
335}
336
337/// Where one batch message sits in the file. Recovered from the framing walk,
338/// which reads metadata and seeks over bodies.
339#[derive(Debug, Clone, Copy, PartialEq, Eq)]
340struct Batch {
341    /// Byte offset of the message's continuation marker.
342    at: u64,
343    /// Bytes the whole message occupies: `8 + metadata + body`.
344    len: u64,
345    /// Rows in it — read from the metadata, so counting them costs no body read.
346    rows: u32,
347    /// Absolute byte offset of the message BODY — where the buffer offsets the
348    /// metadata declares are measured from.
349    body: u64,
350    /// The payload DATA buffer's offset within the body, from the metadata's
351    /// own buffer table. [`EXTENT_UNAVAILABLE`] when the body is compressed or
352    /// the buffer layout is not the one [`exploded_schema`] writes — a point
353    /// read then falls back to decoding the batch, which is slow and correct.
354    pay_data: u64,
355}
356
357/// Sentinel for "no byte extent could be computed for this row/batch" — the
358/// fall-back-and-decode marker, never an offset a file could really have.
359const EXTENT_UNAVAILABLE: u64 = u64::MAX;
360
361/// The payload DATA buffer's offset within the message body, read from the
362/// batch metadata alone.
363///
364/// The payload is [`exploded_schema`]'s LAST field and a `LargeBinary`'s data
365/// buffer is its last buffer, so the table's final buffer entry IS the payload
366/// bytes — asserted by also counting the buffers (12: validity+data for oid and
367/// object_type, validity+data for mode, validity+offsets+data for path and for
368/// payload). `None` when the count disagrees or the body is compressed;
369/// [`ExplodedArchive::content`] then decodes the batch instead of guessing.
370fn payload_data_offset(meta: &[u8]) -> Option<u64> {
371    let msg = root_as_message(meta).ok()?;
372    let rb = msg.header_as_record_batch()?;
373    if rb.compression().is_some() {
374        return None;
375    }
376    let bufs = rb.buffers()?;
377    // 12 buffers is schema v1 (oid 2, type 2, mode 2, path 3, payload 3); 14 is
378    // v2 with the `enc` column's two. In both the payload's data buffer is the
379    // last one, which is the only fact used below.
380    if bufs.len() != 12 && bufs.len() != 14 {
381        return None;
382    }
383    let last = bufs.get(bufs.len() - 1);
384    (last.offset() >= 0).then(|| last.offset() as u64)
385}
386
387/// Where one object's row is — and where its payload BYTES are.
388///
389/// The extent is what makes a point read one small `pread` instead of a whole
390/// 64 MiB batch decode. MEASURED without it, rust-lang/rust push, 2026-08-19:
391/// the pre-ack connectivity walk visited commits and trees in graph order —
392/// effectively random across ~574 batches against a 4-slot cache — and decoded
393/// 6.7 GB/s of page cache to serve ~98 objects/s, one core pinned for hours, a
394/// ~200 000× read amplification. The extent costs 16 bytes per live oid.
395#[derive(Debug, Clone, Copy, PartialEq, Eq)]
396struct Located {
397    batch: u32,
398    row: u32,
399    kind: GitObjectKind,
400    /// Absolute file offset of this row's payload bytes, or
401    /// [`EXTENT_UNAVAILABLE`] — then the read falls back to the batch decode.
402    pay_at: u64,
403    /// Payload length in bytes. Meaningless when `pay_at` is the sentinel.
404    pay_len: u64,
405    /// [`ENC_RAW`] or [`ENC_ZLIB`] — carried in the index so the extent fast
406    /// path knows whether to inflate without decoding the batch.
407    enc: u8,
408}
409
410/// **`oid → Located`, as ragnar's static tree over flat arrays.**
411///
412/// Three parallel arrays in one oid-ascending order, plus an [`STree64Mmap`]
413/// built over the first of them:
414///
415/// ```text
416///   keys  count * 8         i64 little-endian, ascending — the stree keyspace
417///   oids  count * oid_len   the FULL oid, for the verify step
418///   locs  count             batch, row, kind
419/// ```
420///
421/// ## Why this and not the `Vec<(Vec<u8>, Located)>` it replaces
422///
423/// That vector cost one heap allocation *per oid* — 11.7 M of them for
424/// `linux.git` — and its `binary_search_by` chased `log₂ n` dependent loads over
425/// `Vec` headers scattered across the heap before it could compare a byte. Here
426/// the oid bytes are contiguous, and `stree` routes through 64-byte nodes with a
427/// branchless AVX2 compare. `nornir-workspace.toml` names this structure as the
428/// one to use, and [`crate::oid_index`] already uses it over exactly these keys —
429/// so the key function is **imported from there**, not written again.
430///
431/// ## The 8-byte key is a FILTER, not a key — and this is where a wrong answer
432/// would come from
433///
434/// The key is [`key_for_oid`]: the first eight bytes of the oid, big-endian, top
435/// bit flipped so unsigned byte order becomes signed `i64` order (without the
436/// flip every oid starting `0x80..0xff` — half of them — sorts below every oid
437/// starting `0x00..0x7f`, and the keyspace `stree` requires to be ascending is
438/// not). **Twelve** of a sha1 oid's twenty bytes are not in the key at all (24 of
439/// 32 for sha256), so two distinct objects **can** share one key.
440///
441/// How likely, honestly: for `linux.git`'s 11.7 M objects, birthday arithmetic
442/// gives n²/2 · 2⁻⁶⁴ ≈ **3.7 × 10⁻⁶** — one table in ~270 000. So it will not
443/// happen by accident on one repository, and that is exactly why a verify-less
444/// probe would ship and pass every test anyone bothered to write. It does not
445/// stay accidental: finding *some* pair of contents whose oids share eight bytes
446/// is a 2³² birthday search — hours of commodity hashing, not a research result —
447/// and both objects are then perfectly ordinary blobs a client may push. (Hitting
448/// a *specific* stored oid's prefix is 2⁶⁴ and is not a threat.) A hosted forge
449/// serves oids that other people chose, so this is a property to hold by
450/// construction rather than a probability to accept.
451///
452/// So `stree` narrows and never decides. It routes to *a* member of the run of
453/// equal keys — which member is its own business, because its leaf scan starts at
454/// a block boundary that can fall in the middle of the run — so
455/// [`expand_run`](Self::expand_run) walks **both** directions to the run's ends,
456/// and [`find`](Self::find) then compares the **whole oid** against every
457/// candidate. Skipping that comparison would not merely be sloppy: a `have`
458/// negotiation for an oid this table has never seen, whose first eight bytes
459/// happen to match a stored one, would be answered with **the other object's
460/// bytes** — a silently wrong object, which is far worse than a slow one.
461struct OidTree {
462    /// Width of one oid. `0` only when the tree is empty.
463    oid_len: usize,
464    count: usize,
465    keys: Vec<u8>,
466    oids: Vec<u8>,
467    locs: Vec<Located>,
468    /// `None` for an empty table — `STree64Mmap::new_with_stride` asserts
469    /// `count > 0`.
470    tree: Option<STree64Mmap>,
471}
472
473/// Which member of a run of equal oids survives the fold — the two callers
474/// genuinely differ, and the difference is not cosmetic.
475#[derive(Debug, Clone, Copy, PartialEq, Eq)]
476enum Keep {
477    /// [`ExplodedArchive::flush`]'s incremental extension: an oid already in the
478    /// index keeps the [`Located`] it already had. That is what
479    /// [`ExplodedArchive::explode_at`] documents — a blob is reachable at many
480    /// paths and the table records the **first** name it was seen at.
481    First,
482    /// [`ExplodedArchive::index_now`]'s rebuild from the file: batches are walked
483    /// in file order and rows in row order, so the **last** word about an oid
484    /// wins. That is what makes a [`TOMBSTONE`] durable rather than advisory.
485    Last,
486}
487
488/// Accumulates sightings in the order they happen, then folds them.
489///
490/// Sightings, not entries: the same oid may arrive many times, and a `None`
491/// [`Located`] is a [`TOMBSTONE`] row saying the oid is gone. Nothing is
492/// deduplicated until [`finish`](Self::finish), because which sighting wins
493/// depends on their order and on [`Keep`].
494struct OidTreeBuilder {
495    /// Taken from the first oid pushed; every later one must match it.
496    oid_len: usize,
497    oids: Vec<u8>,
498    locs: Vec<Option<Located>>,
499}
500
501impl OidTreeBuilder {
502    fn with_capacity(rows: usize) -> Self {
503        Self { oid_len: 0, oids: Vec::new(), locs: Vec::with_capacity(rows) }
504    }
505
506    /// Record one sighting. `loc` is `None` for a tombstone row.
507    ///
508    /// A width that disagrees with the rows already pushed is refused rather
509    /// than padded: a truncated or extended oid would sort and compare as a
510    /// different object.
511    fn push(&mut self, oid: &[u8], loc: Option<Located>) -> Result<()> {
512        if self.locs.is_empty() && self.oids.is_empty() {
513            self.oid_len = oid.len();
514            self.oids.reserve(self.locs.capacity() * self.oid_len);
515        }
516        anyhow::ensure!(
517            oid.len() == self.oid_len,
518            "the exploded index holds {}-byte oids and a {}-byte one arrived",
519            self.oid_len,
520            oid.len()
521        );
522        self.oids.extend_from_slice(oid);
523        self.locs.push(loc);
524        Ok(())
525    }
526
527    fn oid_at(&self, i: usize) -> &[u8] {
528        &self.oids[i * self.oid_len..(i + 1) * self.oid_len]
529    }
530
531    /// Sort, fold each run of equal oids down to its winner, drop the ones whose
532    /// winner is a tombstone, and build the tree.
533    fn finish(self, keep: Keep) -> OidTree {
534        let n = self.locs.len();
535        let mut order: Vec<u32> = (0..n as u32).collect();
536        // STABLE, and load-bearing: `Keep` is about *insertion* order within a
537        // run of equal oids, so an unstable sort would make "first sighting"
538        // and "last word wins" both mean "whichever one the sort happened to
539        // leave there".
540        order.sort_by(|&a, &b| self.oid_at(a as usize).cmp(self.oid_at(b as usize)));
541
542        let mut keys: Vec<u8> = Vec::with_capacity(n * 8);
543        let mut oids: Vec<u8> = Vec::with_capacity(n * self.oid_len);
544        let mut locs: Vec<Located> = Vec::with_capacity(n);
545        let mut i = 0usize;
546        while i < n {
547            let oid = self.oid_at(order[i] as usize);
548            let mut j = i + 1;
549            while j < n && self.oid_at(order[j] as usize) == oid {
550                j += 1;
551            }
552            let pick = match keep {
553                Keep::First => order[i],
554                Keep::Last => order[j - 1],
555            } as usize;
556            if let Some(loc) = self.locs[pick] {
557                // Ascending oid order gives ascending keys, because
558                // `key_for_oid` is order-preserving over the oid's leading
559                // bytes — the property `stree` needs and the reason for the
560                // sign-bit flip.
561                keys.extend_from_slice(&key_for_oid(oid).to_le_bytes());
562                oids.extend_from_slice(oid);
563                locs.push(loc);
564            }
565            i = j;
566        }
567
568        let count = locs.len();
569        let tree = (count > 0).then(|| STree64Mmap::new_with_stride(&keys, count, 8));
570        OidTree { oid_len: self.oid_len, count, keys, oids, locs, tree }
571    }
572}
573
574impl OidTree {
575    fn len(&self) -> usize {
576        self.count
577    }
578
579    fn oid_at(&self, i: usize) -> &[u8] {
580        &self.oids[i * self.oid_len..(i + 1) * self.oid_len]
581    }
582
583    fn key_at(&self, i: usize) -> i64 {
584        i64::from_le_bytes(self.keys[i * 8..i * 8 + 8].try_into().unwrap())
585    }
586
587    /// Widen a hit to the whole run of equal keys. `stree` routes to *a* member
588    /// of the run — its leaf scan starts at a block boundary, which can fall
589    /// anywhere inside one — so both directions are walked rather than assumed.
590    fn expand_run(&self, pos: usize, key: i64) -> std::ops::Range<usize> {
591        let mut lo = pos;
592        while lo > 0 && self.key_at(lo - 1) == key {
593            lo -= 1;
594        }
595        let mut hi = pos + 1;
596        while hi < self.count && self.key_at(hi) == key {
597            hi += 1;
598        }
599        lo..hi
600    }
601
602    /// Resolve an oid. `None` when absent — never another object's row.
603    fn find(&self, oid: &[u8]) -> Option<Located> {
604        if oid.len() != self.oid_len {
605            return None;
606        }
607        let tree = self.tree.as_ref()?;
608        let key = key_for_oid(oid);
609        let pos = tree.find_exact(key, &self.keys)?;
610        self.verify(pos, key, oid)
611    }
612
613    /// The full-oid comparison the whole structure's correctness rests on.
614    fn verify(&self, pos: usize, key: i64, oid: &[u8]) -> Option<Located> {
615        self.expand_run(pos, key)
616            .find(|&i| self.oid_at(i) == oid)
617            .map(|i| self.locs[i])
618    }
619
620    /// Every live entry, in ascending oid order — what `of_kind` and `retain`
621    /// fold over.
622    fn iter(&self) -> impl Iterator<Item = (&[u8], Located)> + '_ {
623        (0..self.count).map(move |i| (self.oid_at(i), self.locs[i]))
624    }
625
626    /// The **baseline** the tree has to agree with: `binary_search` over the very
627    /// same oid array, followed by the very same run-and-verify. It is the
628    /// finder this file shipped with, and it exists so "the stree returns the
629    /// same row" is a measurement rather than an assertion.
630    #[cfg(test)]
631    fn find_by_binary_search(&self, oid: &[u8]) -> Option<Located> {
632        if oid.len() != self.oid_len || self.count == 0 {
633            return None;
634        }
635        let mut lo = 0usize;
636        let mut hi = self.count;
637        while lo < hi {
638            let mid = lo + (hi - lo) / 2;
639            if self.oid_at(mid) < oid { lo = mid + 1 } else { hi = mid }
640        }
641        (lo < self.count && self.oid_at(lo) == oid).then(|| self.locs[lo])
642    }
643
644    /// The **unverified** candidate run for a key: every entry sharing that
645    /// 8-byte prefix. Normally length 1; length > 1 is a real prefix collision.
646    /// Exposed so a test can prove the collision it constructed is real and that
647    /// the verify step is what tells the candidates apart.
648    #[cfg(test)]
649    fn candidate_run(&self, key: i64) -> std::ops::Range<usize> {
650        let Some(tree) = self.tree.as_ref() else { return 0..0 };
651        let Some(pos) = tree.find_exact(key, &self.keys) else { return 0..0 };
652        self.expand_run(pos, key)
653    }
654}
655
656/// Counters, all of them applied output.
657#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
658pub struct Stats {
659    pub rows: u64,
660    pub written: u64,
661    pub served: u64,
662    pub rederived: u64,
663    pub absent: u64,
664}
665
666/// §14's derived table for one repository.
667pub struct ExplodedArchive {
668    path: PathBuf,
669    /// The schema message: the file's first message, kept so a point read can
670    /// feed a [`StreamDecoder`] without re-reading it from disk each time.
671    schema_msg: Mutex<Option<Vec<u8>>>,
672    /// Every batch message in the file, in order. Cheap — one entry per 64 MiB.
673    batches: Mutex<Vec<Batch>>,
674    /// `oid → Located` as an [`OidTree`]. `None` until the first lookup forces
675    /// the pass that builds it, so a push-only process never pays for it.
676    index: Mutex<Option<OidTree>>,
677    /// The last few decoded batches, most recent first.
678    ///
679    /// Not an optimisation looking for a problem: without it every point read
680    /// decodes its whole batch, and the 2687-object push guard went from 4 s to
681    /// **over 100 s** — 2687 lookups × one 106 MiB batch each. A batch is
682    /// `Arc`-backed, so a hit is a clone of pointers.
683    cache: Mutex<Vec<(u32, RecordBatch)>>,
684    pending: Mutex<PendingBatch>,
685    pending_bytes: AtomicU64,
686    /// Bytes in the file. Kept here rather than stat'ed so the append offset and
687    /// the batch table cannot drift apart.
688    end: Mutex<u64>,
689    oid_len: Mutex<Option<usize>>,
690    policy: ExplodePolicy,
691    skipped: AtomicU64,
692    written: AtomicU64,
693    served: AtomicU64,
694    /// The subset of `served` answered by the extent `pread` fast path.
695    pread_served: AtomicU64,
696    rederived: AtomicU64,
697    absent: AtomicU64,
698    /// The file was written with schema v1 (no `enc` column). Every batch this
699    /// process appends to it is then written in v1 shape too — raw, no `enc` —
700    /// because an IPC stream has ONE schema message and a six-column batch
701    /// under a five-column schema does not decode. The pool is a cache; it moves
702    /// to v2 the day it is dropped and rebuilt, never in place.
703    legacy_v1: std::sync::atomic::AtomicBool,
704    /// The file has been evicted ([`Self::retire`]): it is unlinked or about to
705    /// be. A flush is then a no-op instead of an `O_CREAT` that brings the file
706    /// back as an orphan nobody lists, and a failed read of it is a miss.
707    retired: std::sync::atomic::AtomicBool,
708}
709
710impl ExplodedArchive {
711    /// Open or create the table, with the policy `ZNIPPY_GIT_EXPLODE` names.
712    /// Reads kilobytes, never the payloads.
713    pub fn open(path: &Path) -> Result<Self> {
714        Self::open_with_policy(path, ExplodePolicy::from_env()?)
715    }
716
717    /// Open with an explicit policy — what a test or a per-tenant configuration
718    /// uses, so the setting is not reachable only through the environment.
719    pub fn open_with_policy(path: &Path, policy: ExplodePolicy) -> Result<Self> {
720        if let Some(parent) = path.parent()
721            && !parent.as_os_str().is_empty()
722        {
723            std::fs::create_dir_all(parent)
724                .with_context(|| format!("creating {}", parent.display()))?;
725        }
726        let (schema_msg, batches, end, oid_len) = Self::walk(path)?;
727        let legacy_v1 = schema_msg.as_ref().is_some_and(|m| !Self::schema_has_enc(m));
728        Ok(Self {
729            legacy_v1: std::sync::atomic::AtomicBool::new(legacy_v1),
730            retired: std::sync::atomic::AtomicBool::new(false),
731            path: path.to_path_buf(),
732            schema_msg: Mutex::new(schema_msg),
733            batches: Mutex::new(batches),
734            index: Mutex::new(None),
735            cache: Mutex::new(Vec::new()),
736            pending: Mutex::new(PendingBatch::default()),
737            pending_bytes: AtomicU64::new(0),
738            end: Mutex::new(end),
739            oid_len: Mutex::new(oid_len),
740            policy,
741            skipped: AtomicU64::new(0),
742            written: AtomicU64::new(0),
743            served: AtomicU64::new(0),
744            pread_served: AtomicU64::new(0),
745            rederived: AtomicU64::new(0),
746            absent: AtomicU64::new(0),
747        })
748    }
749
750    pub fn path(&self) -> &Path {
751        &self.path
752    }
753
754    /// **This file is about to be unlinked by an eviction.** Called with the
755    /// segment already out of the pool's list and BEFORE the unlink, under the
756    /// append lock, so a flush that is already writing finishes first and every
757    /// later one is a no-op. Without it, a holder of an `Arc` taken before the
758    /// eviction (a reader's snapshot, the indexer's `flush`/`of_kind`) re-created
759    /// the path with `O_CREAT` after the unlink: an orphan file no pool lists,
760    /// counted by no budget, adopted as a segment on the next open. Buffered
761    /// rows are dropped: this is a cache, every row is re-derivable.
762    pub fn retire(&self) {
763        let end = self.end.lock().unwrap_or_else(|e| e.into_inner());
764        self.retired.store(true, Ordering::Release);
765        drop(end);
766        if let Ok(mut p) = self.pending.lock() {
767            let _ = p.take();
768        }
769        self.pending_bytes.store(0, Ordering::Release);
770    }
771
772    /// See [`Self::retire`].
773    pub fn is_retired(&self) -> bool {
774        self.retired.load(Ordering::Acquire)
775    }
776
777    /// **Drop every derived, rebuildable structure**: the `oid → Located`
778    /// tree (~50 B per row — 700 MB on linux, and re-extended on every flush
779    /// while a reader keeps it alive) and the decoded-batch cache. What the
780    /// memory watchdog's flush reaches for ([`crate::memguard`]); the next
781    /// lookup rebuilds the tree from the file in one pass.
782    pub fn drop_caches(&self) {
783        if let Ok(mut i) = self.index.lock() {
784            *i = None;
785        }
786        if let Ok(mut c) = self.cache.lock() {
787            c.clear();
788        }
789    }
790
791    /// Walk the message framing: `[0xFFFFFFFF][len u32][metadata][body]`.
792    ///
793    /// The metadata flatbuffer carries `bodyLength`, so this SEEKS over every
794    /// payload — opening a 17 GB table touches kilobytes. It also carries a
795    /// record batch's row `length`, which is how `rows()` answers without
796    /// decoding anything.
797    ///
798    /// A torn tail — a half-written message at EOF — stops the walk and keeps
799    /// what came before it, and the file is truncated to that boundary on the
800    /// next append. The table is derived, so a partial batch is re-exploded
801    /// rather than being an error a client ever sees.
802    #[allow(clippy::type_complexity)]
803    fn walk(path: &Path) -> Result<(Option<Vec<u8>>, Vec<Batch>, u64, Option<usize>)> {
804        let Ok(mut f) = File::open(path) else {
805            return Ok((None, Vec::new(), 0, None));
806        };
807        let total = f.metadata()?.len();
808        let mut schema_msg: Option<Vec<u8>> = None;
809        let mut oid_len: Option<usize> = None;
810        let mut batches = Vec::new();
811        let mut at = 0u64;
812        while at + 8 <= total {
813            f.seek(SeekFrom::Start(at))?;
814            let mut hdr = [0u8; 8];
815            if f.read_exact(&mut hdr).is_err() {
816                break;
817            }
818            if u32::from_le_bytes(hdr[0..4].try_into().unwrap()) != 0xFFFF_FFFF {
819                break;
820            }
821            let meta_len = u32::from_le_bytes(hdr[4..8].try_into().unwrap()) as u64;
822            if meta_len == 0 {
823                break; // end-of-stream marker
824            }
825            if at + 8 + meta_len > total {
826                break; // torn metadata
827            }
828            let mut meta = vec![0u8; meta_len as usize];
829            if f.read_exact(&mut meta).is_err() {
830                break;
831            }
832            let Ok(msg) = root_as_message(&meta) else {
833                break;
834            };
835            let body = msg.bodyLength().max(0) as u64;
836            let whole = 8 + meta_len + body;
837            if at + whole > total {
838                break; // torn body
839            }
840            if let Some(rb) = msg.header_as_record_batch() {
841                batches.push(Batch {
842                    at,
843                    len: whole,
844                    rows: rb.length().max(0) as u32,
845                    body: at + 8 + meta_len,
846                    pay_data: payload_data_offset(&meta).unwrap_or(EXTENT_UNAVAILABLE),
847                });
848            } else if msg.header_as_schema().is_some() {
849                schema_msg = Some({
850                    let mut whole_msg = Vec::with_capacity((8 + meta_len) as usize);
851                    whole_msg.extend_from_slice(&hdr);
852                    whole_msg.extend_from_slice(&meta);
853                    whole_msg
854                });
855                oid_len = Self::oid_len_of_schema_msg(schema_msg.as_ref().unwrap());
856            }
857            at += whole;
858        }
859        Ok((schema_msg, batches, at, oid_len))
860    }
861
862    /// The declared oid width, so a reopened table refuses a hash it cannot
863    /// hold instead of writing a batch no reader can line up.
864    /// The schema inside a stream schema message (`msg` = the 8-byte
865    /// continuation header + the flatbuffer), read off the flatbuffer directly.
866    ///
867    /// Not through `StreamDecoder`: fed a schema message alone it returns
868    /// `Ok(None)` and its `schema()` stays `None` — MEASURED 2026-09-05 with a
869    /// probe on a file this writer had just produced (`decode=Ok(false)
870    /// schema=None`). `oid_len_of_schema_msg` had used exactly that path since
871    /// it was written and therefore always answered `None`; nothing depended on
872    /// it, so nothing noticed. `legacy_v1` does depend on it, which is how it
873    /// surfaced: a fresh v2 file was read as v1 and the next append was written
874    /// five columns wide under a six-column schema.
875    fn schema_of_msg(msg: &[u8]) -> Option<Schema> {
876        let meta = msg.get(8..)?;
877        let m = root_as_message(meta).ok()?;
878        let fb = m.header_as_schema()?;
879        Some(znippy_common::arrow::ipc::convert::fb_to_schema(fb))
880    }
881
882    /// Whether the file's schema message carries the v2 `enc` column.
883    fn schema_has_enc(msg: &[u8]) -> bool {
884        Self::schema_of_msg(msg).is_some_and(|s| s.field_with_name(COL_ENC).is_ok())
885    }
886
887    fn oid_len_of_schema_msg(msg: &[u8]) -> Option<usize> {
888        let schema = Self::schema_of_msg(msg)?;
889        match schema.field_with_name(COL_OID).ok()?.data_type() {
890            DataType::FixedSizeBinary(n) => Some(*n as usize),
891            _ => None,
892        }
893    }
894
895    /// One resolved object with no name attached — what [`crate::exploded::PayloadSink`]
896    /// can supply.
897    pub fn explode(&self, oid: &[u8], kind: GitObjectKind, payload: &[u8]) -> Result<()> {
898        self.explode_at(oid, kind, None, None, payload)
899    }
900
901    /// One resolved object **with its name**: the mode and path a tree walk knows.
902    ///
903    /// A blob is reachable at many paths, so this records the first one seen and
904    /// never rewrites it — a row that already exists is not re-keyed by a second
905    /// sighting, because "which of its names" is not a question this table
906    /// pretends to answer.
907    pub fn explode_at(
908        &self,
909        oid: &[u8],
910        kind: GitObjectKind,
911        mode: Option<u32>,
912        path: Option<&str>,
913        payload: &[u8],
914    ) -> Result<()> {
915        if !self.policy.wants(kind) {
916            self.skipped.fetch_add(1, Ordering::Relaxed);
917            return Ok(());
918        }
919        {
920            let mut p = self
921                .pending
922                .lock()
923                .map_err(|_| anyhow::anyhow!("exploded pending poisoned"))?;
924            // **One `extend_from_slice` into the arena, no allocation of its
925            // own.** This line was `payload.to_vec()` — a whole second copy of
926            // the object the caller is holding, which is the byte lane AA
927            // measured on 2026-08-30.
928            let pay = p.stash(payload);
929            p.rows.push(Pending {
930                oid: oid.to_vec(),
931                code: kind_code(kind),
932                mode,
933                path: path.map(str::to_owned),
934                pay,
935            });
936        }
937        let n = self
938            .pending_bytes
939            .fetch_add(payload.len() as u64, Ordering::AcqRel)
940            + payload.len() as u64;
941        if n >= FLUSH_BYTES as u64 {
942            self.flush()?;
943        }
944        Ok(())
945    }
946
947    /// `v1`: write the batch in schema v1 — no `enc` column, every row raw —
948    /// because the file it is appended to was opened with a v1 schema message.
949    fn build_batch(rows: &[Pending], arena: &[u8], oid_len: usize, v1: bool) -> Result<RecordBatch> {
950        if v1 {
951            let mut oid_b = FixedSizeBinaryBuilder::with_capacity(rows.len(), oid_len as i32);
952            let mut kind_b = UInt8Builder::with_capacity(rows.len());
953            let mut mode_b = UInt32Builder::with_capacity(rows.len());
954            let mut path_b = StringBuilder::new();
955            let mut pay_b = LargeBinaryBuilder::new();
956            for r in rows {
957                oid_b
958                    .append_value(&r.oid)
959                    .map_err(|e| anyhow::anyhow!("exploded oid column: {e}"))?;
960                kind_b.append_value(r.code);
961                mode_b.append_option(r.mode);
962                path_b.append_option(r.path.as_deref());
963                pay_b.append_value(&arena[r.pay.clone()]);
964            }
965            return RecordBatch::try_new(
966                exploded_schema_v1(oid_len),
967                vec![
968                    Arc::new(oid_b.finish()),
969                    Arc::new(kind_b.finish()),
970                    Arc::new(mode_b.finish()),
971                    Arc::new(path_b.finish()),
972                    Arc::new(pay_b.finish()),
973                ],
974            )
975            .context("building a v1 exploded batch");
976        }
977        let mut oid_b = FixedSizeBinaryBuilder::with_capacity(rows.len(), oid_len as i32);
978        let mut kind_b = UInt8Builder::with_capacity(rows.len());
979        let mut mode_b = UInt32Builder::with_capacity(rows.len());
980        let mut path_b = StringBuilder::new();
981        let mut enc_b = UInt8Builder::with_capacity(rows.len());
982        let mut pay_b = LargeBinaryBuilder::new();
983        for r in rows {
984            oid_b
985                .append_value(&r.oid)
986                .map_err(|e| anyhow::anyhow!("exploded oid column: {e}"))?;
987            kind_b.append_value(r.code);
988            mode_b.append_option(r.mode);
989            path_b.append_option(r.path.as_deref());
990            // Per row, at build time: the pending arena keeps rows raw (so the
991            // pending-serve path hands them out untouched), and what lands in
992            // the file is whatever is smaller.
993            let raw = &arena[r.pay.clone()];
994            match compress_row(raw) {
995                Some(z) => {
996                    enc_b.append_value(ENC_ZLIB);
997                    pay_b.append_value(&z);
998                }
999                None => {
1000                    enc_b.append_value(ENC_RAW);
1001                    pay_b.append_value(raw);
1002                }
1003            }
1004        }
1005        RecordBatch::try_new(
1006            exploded_schema(oid_len),
1007            vec![
1008                Arc::new(oid_b.finish()),
1009                Arc::new(kind_b.finish()),
1010                Arc::new(mode_b.finish()),
1011                Arc::new(path_b.finish()),
1012                Arc::new(enc_b.finish()),
1013                Arc::new(pay_b.finish()),
1014            ],
1015        )
1016        .context("building the exploded batch")
1017    }
1018
1019    /// Append the buffered rows as ONE batch message. Nothing already in the
1020    /// file is read or rewritten.
1021    pub fn flush(&self) -> Result<u64> {
1022        let (rows, arena) = {
1023            let mut p = self
1024                .pending
1025                .lock()
1026                .map_err(|_| anyhow::anyhow!("exploded pending poisoned"))?;
1027            if p.is_empty() {
1028                return Ok(0);
1029            }
1030            self.pending_bytes.store(0, Ordering::Release);
1031            p.take()
1032        };
1033        let n = rows.len() as u64;
1034        let width = rows[0].oid.len();
1035        anyhow::ensure!(
1036            rows.iter().all(|r| r.oid.len() == width),
1037            "one exploded batch cannot hold two hash widths"
1038        );
1039        {
1040            let mut w = self
1041                .oid_len
1042                .lock()
1043                .map_err(|_| anyhow::anyhow!("exploded oid width poisoned"))?;
1044            match *w {
1045                Some(have) => anyhow::ensure!(
1046                    have == width,
1047                    "this table holds {have}-byte oids and a {width}-byte one arrived"
1048                ),
1049                None => *w = Some(width),
1050            }
1051        }
1052
1053        let batch = Self::build_batch(&rows, &arena, width, self.legacy_v1.load(Ordering::Relaxed))?;
1054        let opts = IpcWriteOptions::default();
1055        let ipc = IpcDataGenerator::default();
1056        let mut tracker = DictionaryTracker::new(false);
1057
1058        // The file is opened per flush rather than held: an append writes at a
1059        // known offset and closing between batches is what makes a crashed
1060        // process leave a file whose last complete message is intact.
1061        let mut end = self
1062            .end
1063            .lock()
1064            .map_err(|_| anyhow::anyhow!("exploded end poisoned"))?;
1065        if self.retired.load(Ordering::Acquire) {
1066            // Evicted: its path is gone, and opening it with `create` would
1067            // bring it back as an orphan. The rows were a cache.
1068            return Ok(0);
1069        }
1070        let mut f = OpenOptions::new()
1071            .create(true)
1072            .read(true)
1073            .write(true)
1074            .truncate(false)
1075            .open(&self.path)
1076            .with_context(|| format!("opening {}", self.path.display()))?;
1077        // Drop anything after the last complete message before appending — a
1078        // torn tail from a previous crash must not sit in the middle of the
1079        // stream, where every later batch would be unreachable.
1080        if f.metadata()?.len() != *end {
1081            f.set_len(*end)
1082                .with_context(|| format!("truncating {} to {}", self.path.display(), *end))?;
1083        }
1084        f.seek(SeekFrom::Start(*end))?;
1085
1086        let mut schema_guard = self
1087            .schema_msg
1088            .lock()
1089            .map_err(|_| anyhow::anyhow!("exploded schema poisoned"))?;
1090        if schema_guard.is_none() {
1091            let enc =
1092                ipc.schema_to_bytes_with_dictionary_tracker(&exploded_schema(width), &mut tracker, &opts);
1093            let mut msg = Vec::new();
1094            let (meta, body) = write_message(&mut msg, enc, &opts)
1095                .map_err(|e| anyhow::anyhow!("encoding the exploded schema: {e}"))?;
1096            debug_assert_eq!(meta + body, msg.len());
1097            f.write_all(&msg).context("writing the exploded schema")?;
1098            *end += msg.len() as u64;
1099            *schema_guard = Some(msg);
1100        }
1101        drop(schema_guard);
1102
1103        let (dicts, enc) = ipc
1104            .encode(&batch, &mut tracker, &opts, &mut Default::default())
1105            .map_err(|e| anyhow::anyhow!("encoding an exploded batch: {e}"))?;
1106        anyhow::ensure!(
1107            dicts.is_empty(),
1108            "the exploded schema has no dictionary columns, yet {} arrived",
1109            dicts.len()
1110        );
1111        let mut msg = Vec::new();
1112        let (meta, body) = write_message(&mut msg, enc, &opts)
1113            .map_err(|e| anyhow::anyhow!("encoding an exploded batch: {e}"))?;
1114        debug_assert_eq!(meta + body, msg.len());
1115        f.write_all(&msg).context("appending an exploded batch")?;
1116
1117        let placed = Batch {
1118            at: *end,
1119            len: msg.len() as u64,
1120            rows: rows.len() as u32,
1121            // `meta` from `write_message` is the 8-byte prefix plus the padded
1122            // metadata, so the body begins exactly `meta` bytes in — and the
1123            // metadata slice between prefix and body is what the offset helper
1124            // parses, the same bytes `walk` reads back after a reopen.
1125            body: *end + meta as u64,
1126            pay_data: payload_data_offset(&msg[8..meta]).unwrap_or(EXTENT_UNAVAILABLE),
1127        };
1128        *end += msg.len() as u64;
1129
1130        // Recorded while the append lock is still held, so the batch table stays
1131        // in file order under N concurrent exploders. Correctness would survive
1132        // it being out of order — a lookup addresses a batch by its slot, not by
1133        // its offset — but a table that reads back in file order is one a human
1134        // can check against the file with `od`.
1135        let batch_no = {
1136            let mut b = self
1137                .batches
1138                .lock()
1139                .map_err(|_| anyhow::anyhow!("exploded batches poisoned"))?;
1140            b.push(placed);
1141            (b.len() - 1) as u32
1142        };
1143        drop(end);
1144
1145        // Only extend an index that already exists. Building one here would make
1146        // the first push pay for a structure no reader has asked for.
1147        let mut idx = self
1148            .index
1149            .lock()
1150            .map_err(|_| anyhow::anyhow!("exploded index poisoned"))?;
1151        if let Some(old) = idx.take() {
1152            // Retired oids are collected and applied in ONE pass. Removing them
1153            // one at a time is quadratic, and a `gc` retires millions.
1154            let mut retired: std::collections::HashSet<&[u8]> = std::collections::HashSet::new();
1155            for r in rows.iter() {
1156                if kind_of(r.code).is_none() {
1157                    retired.insert(r.oid.as_slice());
1158                }
1159            }
1160            let mut b = OidTreeBuilder::with_capacity(old.len() + rows.len());
1161            for (oid, loc) in old.iter() {
1162                if !retired.contains(oid) {
1163                    b.push(oid, Some(loc))?;
1164                }
1165            }
1166            let pay = batch
1167                .column_by_name(COL_PAYLOAD)
1168                .and_then(|c| c.as_any().downcast_ref::<LargeBinaryArray>())
1169                .context("the exploded table has no payload column")?;
1170            // Freshly built, never sliced, so these offsets are byte-for-byte
1171            // what the encoder just wrote into the file — the same equivalence
1172            // `index_now` relies on after a reopen.
1173            let off = pay.value_offsets();
1174            let enc = enc_column(&batch);
1175            for (i, r) in rows.iter().enumerate() {
1176                if let Some(kind) = kind_of(r.code)
1177                    && !retired.contains(r.oid.as_slice())
1178                {
1179                    let (pay_at, pay_len) = if placed.pay_data == EXTENT_UNAVAILABLE {
1180                        (EXTENT_UNAVAILABLE, 0)
1181                    } else {
1182                        (
1183                            placed.body + placed.pay_data + off[i] as u64,
1184                            (off[i + 1] - off[i]) as u64,
1185                        )
1186                    };
1187                    b.push(
1188                        &r.oid,
1189                        Some(Located {
1190                            batch: batch_no,
1191                            row: i as u32,
1192                            kind,
1193                            pay_at,
1194                            pay_len,
1195                            enc: enc_at(enc, i),
1196                        }),
1197                    )?;
1198                }
1199            }
1200            // `Keep::First`, because the surviving entries were pushed before
1201            // this batch's rows: an oid already in the index keeps the row it
1202            // already had, which is what `explode_at` documents about names.
1203            *idx = Some(b.finish(Keep::First));
1204        }
1205        self.written.fetch_add(n, Ordering::Relaxed);
1206        Ok(n)
1207    }
1208
1209    /// How many decoded batches stay resident. Four × [`FLUSH_BYTES`] is the
1210    /// worst case, and a batch is `Arc`-backed so a hit copies pointers.
1211    const CACHE: usize = 4;
1212
1213    /// Read one batch message off disk and decode it — or hand back the decoded
1214    /// copy if it is one of the last [`Self::CACHE`].
1215    ///
1216    /// Two `pread`s on a miss: the schema message and the batch. It never reads
1217    /// the batches in front of the one it wants — the property a stream reader
1218    /// iterating from byte zero does not have.
1219    fn read_batch(&self, no: u32) -> Result<RecordBatch> {
1220        {
1221            let mut c = self
1222                .cache
1223                .lock()
1224                .map_err(|_| anyhow::anyhow!("exploded batch cache poisoned"))?;
1225            if let Some(at) = c.iter().position(|(n, _)| *n == no) {
1226                let hit = c.remove(at);
1227                let batch = hit.1.clone();
1228                c.insert(0, hit);
1229                return Ok(batch);
1230            }
1231        }
1232        let placed = {
1233            let b = self
1234                .batches
1235                .lock()
1236                .map_err(|_| anyhow::anyhow!("exploded batches poisoned"))?;
1237            *b.get(no as usize)
1238                .with_context(|| format!("exploded batch {no} is not in this table"))?
1239        };
1240        let schema_msg = {
1241            let s = self
1242                .schema_msg
1243                .lock()
1244                .map_err(|_| anyhow::anyhow!("exploded schema poisoned"))?;
1245            s.clone()
1246                .context("the exploded table has batches but no schema message")?
1247        };
1248        let f = File::open(&self.path)
1249            .with_context(|| format!("opening {}", self.path.display()))?;
1250        let mut raw = vec![0u8; placed.len as usize];
1251        f.read_exact_at(&mut raw, placed.at)
1252            .with_context(|| format!("reading exploded batch {no}"))?;
1253
1254        let mut dec = StreamDecoder::new();
1255        let mut head = Buffer::from_vec(schema_msg);
1256        dec.decode(&mut head)
1257            .map_err(|e| anyhow::anyhow!("decoding the exploded schema: {e}"))?;
1258        let mut body = Buffer::from_vec(raw);
1259        let batch = dec
1260            .decode(&mut body)
1261            .map_err(|e| anyhow::anyhow!("decoding exploded batch {no}: {e}"))?
1262            .with_context(|| format!("exploded batch {no} decoded to no rows"))?;
1263        {
1264            let mut c = self
1265                .cache
1266                .lock()
1267                .map_err(|_| anyhow::anyhow!("exploded batch cache poisoned"))?;
1268            c.retain(|(n, _)| *n != no);
1269            c.insert(0, (no, batch.clone()));
1270            c.truncate(Self::CACHE);
1271        }
1272        Ok(batch)
1273    }
1274
1275    /// Build `oid → Located` with one sequential pass, applying every
1276    /// [`TOMBSTONE`] in file order so a retired oid stays retired across a
1277    /// reopen. Called on the first lookup, never on open.
1278    fn index_now(&self) -> Result<()> {
1279        {
1280            let idx = self
1281                .index
1282                .lock()
1283                .map_err(|_| anyhow::anyhow!("exploded index poisoned"))?;
1284            if idx.is_some() {
1285                return Ok(());
1286            }
1287        }
1288        let (count, rows, placed) = {
1289            let b = self
1290                .batches
1291                .lock()
1292                .map_err(|_| anyhow::anyhow!("exploded batches poisoned"))?;
1293            // The row total is in the batch metadata the framing walk already
1294            // read, so the builder's arrays are sized once instead of doubling
1295            // their way to 11.7 million.
1296            (b.len() as u32, b.iter().map(|x| x.rows as usize).sum::<usize>(), b.clone())
1297        };
1298        // Every row is recorded as a sighting and the fold happens once, at
1299        // `finish`. The `HashMap<Vec<u8>, Located>` this replaced allocated —
1300        // and then dropped — one `Vec<u8>` per oid on a corpus with 11.7 M of
1301        // them, to compute an answer a single stable sort gives.
1302        let mut fold = OidTreeBuilder::with_capacity(rows);
1303        for no in 0..count {
1304            let batch = self.read_batch(no)?;
1305            let oid = batch
1306                .column_by_name(COL_OID)
1307                .and_then(|c| c.as_any().downcast_ref::<FixedSizeBinaryArray>())
1308                .context("the exploded table has no oid column")?;
1309            let kinds = batch
1310                .column_by_name(COL_TYPE)
1311                .and_then(|c| c.as_any().downcast_ref::<UInt8Array>())
1312                .context("the exploded table has no object_type column")?;
1313            let pay = batch
1314                .column_by_name(COL_PAYLOAD)
1315                .and_then(|c| c.as_any().downcast_ref::<LargeBinaryArray>())
1316                .context("the exploded table has no payload column")?;
1317            // The decoded offsets carry the SAME values the file's offsets
1318            // buffer holds — a StreamDecoder copies buffers verbatim — so the
1319            // extent needs no second parse of the body.
1320            let off = pay.value_offsets();
1321            let enc = enc_column(&batch);
1322            let b = placed[no as usize];
1323            for i in 0..batch.num_rows() {
1324                // A tombstone is pushed as a sighting with no location, not
1325                // skipped: batches are walked in file order and rows in row
1326                // order, so `Keep::Last` gives the last word about an oid — and
1327                // when that word is a tombstone the oid is dropped, which is
1328                // what makes the tombstone durable rather than advisory.
1329                fold.push(
1330                    oid.value(i),
1331                    kind_of(kinds.value(i)).map(|kind| {
1332                        let (pay_at, pay_len) = if b.pay_data == EXTENT_UNAVAILABLE {
1333                            (EXTENT_UNAVAILABLE, 0)
1334                        } else {
1335                            (
1336                                b.body + b.pay_data + off[i] as u64,
1337                                (off[i + 1] - off[i]) as u64,
1338                            )
1339                        };
1340                        Located { batch: no, row: i as u32, kind, pay_at, pay_len, enc: enc_at(enc, i) }
1341                    }),
1342                )?;
1343            }
1344        }
1345        let out = fold.finish(Keep::Last);
1346        let mut idx = self
1347            .index
1348            .lock()
1349            .map_err(|_| anyhow::anyhow!("exploded index poisoned"))?;
1350        if idx.is_none() {
1351            *idx = Some(out);
1352        }
1353        Ok(())
1354    }
1355
1356    fn find(&self, oid: &[u8]) -> Result<Option<Located>> {
1357        self.index_now()?;
1358        let idx = self
1359            .index
1360            .lock()
1361            .map_err(|_| anyhow::anyhow!("exploded index poisoned"))?;
1362        Ok(idx.as_ref().expect("index_now built it").find(oid))
1363    }
1364
1365    /// The object's kind and bytes, or `None` — *fall back and rebuild*, never
1366    /// *wrong*.
1367    pub fn content(&self, oid: &[u8]) -> Result<Option<(GitObjectKind, Vec<u8>)>> {
1368        // A buffered row has not been written yet, and a read must not miss it:
1369        // an "absent" that is really "not flushed" sends the caller off to
1370        // re-resolve a whole pack for an object we are holding in RAM.
1371        {
1372            let p = self
1373                .pending
1374                .lock()
1375                .map_err(|_| anyhow::anyhow!("exploded pending poisoned"))?;
1376            if let Some(r) = p.rows.iter().rev().find(|r| r.oid == oid) {
1377                let Some(kind) = kind_of(r.code) else {
1378                    // The newest buffered word about this oid retires it.
1379                    self.absent.fetch_add(1, Ordering::Relaxed);
1380                    return Ok(None);
1381                };
1382                self.served.fetch_add(1, Ordering::Relaxed);
1383                return Ok(Some((kind, p.bytes(r).to_vec())));
1384            }
1385        }
1386        let Some(loc) = self.find(oid)? else {
1387            self.absent.fetch_add(1, Ordering::Relaxed);
1388            return Ok(None);
1389        };
1390        // ── the point read IS a point read ──────────────────────────────────
1391        //
1392        // One pread of exactly the payload's bytes, addressed by the extent the
1393        // index carries. The batch-decode below is the FALLBACK — correct for a
1394        // compressed or foreign-layout batch — not the path a healthy table
1395        // takes: taking it per object is what turned a rust-lang/rust
1396        // connectivity walk into hours of one-core batch decoding (2026-08-19).
1397        if loc.pay_at != EXTENT_UNAVAILABLE {
1398            let f = File::open(&self.path)
1399                .with_context(|| format!("opening {}", self.path.display()))?;
1400            let mut buf = vec![0u8; loc.pay_len as usize];
1401            f.read_exact_at(&mut buf, loc.pay_at)
1402                .with_context(|| format!("preading payload at {}", loc.pay_at))?;
1403            self.served.fetch_add(1, Ordering::Relaxed);
1404            self.pread_served.fetch_add(1, Ordering::Relaxed);
1405            // The extent held the row as stored; a compressed row is inflated
1406            // here, from the index's `enc`, without decoding the batch.
1407            return Ok(Some((loc.kind, row_payload(loc.enc, &buf)?)));
1408        }
1409        let batch = self.read_batch(loc.batch)?;
1410        let pay = batch
1411            .column_by_name(COL_PAYLOAD)
1412            .and_then(|c| c.as_any().downcast_ref::<LargeBinaryArray>())
1413            .context("the exploded table has no payload column")?;
1414        let enc = enc_at(enc_column(&batch), loc.row as usize);
1415        self.served.fetch_add(1, Ordering::Relaxed);
1416        Ok(Some((loc.kind, row_payload(enc, pay.value(loc.row as usize))?)))
1417    }
1418
1419    /// Point reads served by the extent `pread` rather than a batch decode —
1420    /// how a test proves the fast path is the one actually taken, instead of
1421    /// timing something.
1422    pub fn pread_served(&self) -> u64 {
1423        self.pread_served.load(Ordering::Relaxed)
1424    }
1425
1426    /// The name this object was first exploded at, if any caller knew one.
1427    /// `None` is "not recorded", never "at the root".
1428    pub fn name(&self, oid: &[u8]) -> Result<Option<(Option<u32>, Option<String>)>> {
1429        {
1430            let p = self
1431                .pending
1432                .lock()
1433                .map_err(|_| anyhow::anyhow!("exploded pending poisoned"))?;
1434            if let Some(r) = p.rows.iter().rev().find(|r| r.oid == oid) {
1435                return match kind_of(r.code) {
1436                    Some(_) => Ok(Some((r.mode, r.path.clone()))),
1437                    None => Ok(None),
1438                };
1439            }
1440        }
1441        let Some(loc) = self.find(oid)? else {
1442            return Ok(None);
1443        };
1444        let batch = self.read_batch(loc.batch)?;
1445        let mode = batch
1446            .column_by_name(COL_MODE)
1447            .and_then(|c| c.as_any().downcast_ref::<UInt32Array>())
1448            .context("the exploded table has no mode column")?;
1449        let path = batch
1450            .column_by_name(COL_PATH)
1451            .and_then(|c| c.as_any().downcast_ref::<StringArray>())
1452            .context("the exploded table has no path column")?;
1453        let i = loc.row as usize;
1454        Ok(Some((
1455            (!mode.is_null(i)).then(|| mode.value(i)),
1456            (!path.is_null(i)).then(|| path.value(i).to_owned()),
1457        )))
1458    }
1459
1460    pub fn has(&self, oid: &[u8]) -> Result<bool> {
1461        {
1462            let p = self
1463                .pending
1464                .lock()
1465                .map_err(|_| anyhow::anyhow!("exploded pending poisoned"))?;
1466            if let Some(r) = p.rows.iter().rev().find(|r| r.oid == oid) {
1467                return Ok(kind_of(r.code).is_some());
1468            }
1469        }
1470        Ok(self.find(oid)?.is_some())
1471    }
1472
1473    /// Every oid of one kind, with its payload. The graph fold's input.
1474    ///
1475    /// Driven by the **index**, not by a scan of the file, because the file
1476    /// holds superseded and retired rows too. A scan that read the file directly
1477    /// is exactly how `gc`'d commits came back after a reopen.
1478    pub fn of_kind(&self, kind: GitObjectKind) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
1479        self.flush()?;
1480        self.index_now()?;
1481        // Grouped by batch so each one is decoded once, in file order.
1482        let mut by_batch: std::collections::BTreeMap<u32, Vec<(u32, Vec<u8>)>> =
1483            std::collections::BTreeMap::new();
1484        {
1485            let idx = self
1486                .index
1487                .lock()
1488                .map_err(|_| anyhow::anyhow!("exploded index poisoned"))?;
1489            for (oid, loc) in idx.as_ref().expect("index_now built it").iter() {
1490                if loc.kind == kind {
1491                    by_batch.entry(loc.batch).or_default().push((loc.row, oid.to_vec()));
1492                }
1493            }
1494        }
1495        let mut out = Vec::new();
1496        for (no, mut wanted) in by_batch {
1497            wanted.sort_unstable_by_key(|(r, _)| *r);
1498            let batch = self.read_batch(no)?;
1499            let pay = batch
1500                .column_by_name(COL_PAYLOAD)
1501                .and_then(|c| c.as_any().downcast_ref::<LargeBinaryArray>())
1502                .context("the exploded table has no payload column")?;
1503            let enc = enc_column(&batch);
1504            for (row, oid) in wanted {
1505                out.push((oid, row_payload(enc_at(enc, row as usize), pay.value(row as usize))?));
1506            }
1507        }
1508        Ok(out)
1509    }
1510
1511    /// Retire every oid `live` rejects, **durably**.
1512    ///
1513    /// The file is append-only, so this appends a [`TOMBSTONE`] row per retired
1514    /// oid rather than deleting anything. The bytes of the dead rows stay until
1515    /// the table is rebuilt — reclaiming them means rewriting up to 17 GB, which
1516    /// is a job with its own proof obligations and not something to smuggle into
1517    /// `gc` — but the *rows* are gone from every reader, including a reopened
1518    /// one.
1519    ///
1520    /// Dropping only from the in-memory index is what a first cut did. Seen RED
1521    /// by `store::tests::a_wholly_dead_pack_does_not_come_back_when_the_store_is_reopened`:
1522    /// **"the graph after gc + reopen holds 551 commits, not the one live one"**.
1523    pub fn retain(&self, live: &dyn Fn(&[u8]) -> bool) -> Result<u64> {
1524        self.flush()?;
1525        self.index_now()?;
1526        let dead: Vec<Vec<u8>> = {
1527            let idx = self
1528                .index
1529                .lock()
1530                .map_err(|_| anyhow::anyhow!("exploded index poisoned"))?;
1531            idx.as_ref()
1532                .expect("index_now built it")
1533                .iter()
1534                .filter(|(oid, _)| !live(oid))
1535                .map(|(oid, _)| oid.to_vec())
1536                .collect()
1537        };
1538        if dead.is_empty() {
1539            return Ok(0);
1540        }
1541        {
1542            let mut p = self
1543                .pending
1544                .lock()
1545                .map_err(|_| anyhow::anyhow!("exploded pending poisoned"))?;
1546            for oid in &dead {
1547                p.rows.push(Pending {
1548                    oid: oid.clone(),
1549                    code: TOMBSTONE,
1550                    mode: None,
1551                    path: None,
1552                    pay: 0..0,
1553                });
1554            }
1555        }
1556        // Written before returning, so a `gc` that says it retired rows has
1557        // already said so on disk.
1558        self.flush()?;
1559        Ok(dead.len() as u64)
1560    }
1561
1562    /// Rows in the table. Answered from batch metadata when no index has been
1563    /// built, so startup does not read a payload.
1564    pub fn rows(&self) -> Result<u64> {
1565        let pending = {
1566            let p = self
1567                .pending
1568                .lock()
1569                .map_err(|_| anyhow::anyhow!("exploded pending poisoned"))?;
1570            p.rows.len() as u64
1571        };
1572        {
1573            let idx = self
1574                .index
1575                .lock()
1576                .map_err(|_| anyhow::anyhow!("exploded index poisoned"))?;
1577            if let Some(idx) = idx.as_ref() {
1578                return Ok(idx.len() as u64 + pending);
1579            }
1580        }
1581        let b = self
1582            .batches
1583            .lock()
1584            .map_err(|_| anyhow::anyhow!("exploded batches poisoned"))?;
1585        Ok(b.iter().map(|x| x.rows as u64).sum::<u64>() + pending)
1586    }
1587
1588    /// Bytes the table occupies — the number redb could not keep anywhere near
1589    /// its payload total.
1590    pub fn disk_bytes(&self) -> u64 {
1591        std::fs::metadata(&self.path).map(|m| m.len()).unwrap_or(0)
1592    }
1593
1594    pub fn note_rederived(&self) {
1595        self.rederived.fetch_add(1, Ordering::Relaxed);
1596    }
1597
1598    /// What this table is configured to keep.
1599    pub fn policy(&self) -> ExplodePolicy {
1600        self.policy
1601    }
1602
1603    /// Objects the policy declined, COUNTED: a table short because of policy and
1604    /// one short because of a fault must not look alike to `adopt_journal`.
1605    pub fn skipped(&self) -> u64 {
1606        self.skipped.load(Ordering::Relaxed)
1607    }
1608
1609    pub fn stats(&self) -> Stats {
1610        Stats {
1611            rows: self.rows().unwrap_or(0),
1612            written: self.written.load(Ordering::Relaxed),
1613            served: self.served.load(Ordering::Relaxed),
1614            rederived: self.rederived.load(Ordering::Relaxed),
1615            absent: self.absent.load(Ordering::Relaxed),
1616        }
1617    }
1618
1619    /// The engine-wide counter type, so no caller can tell the medium apart by
1620    /// its instruments.
1621    pub fn engine_stats(&self) -> crate::exploded::ExplodedStats {
1622        let s = self.stats();
1623        crate::exploded::ExplodedStats {
1624            rows: s.rows,
1625            written: s.written,
1626            served: s.served,
1627            rederived: s.rederived,
1628            absent: s.absent,
1629        }
1630    }
1631}
1632
1633impl crate::exploded::PayloadSink for ExplodedArchive {
1634    /// The policy, asked before the payload exists rather than after — and the
1635    /// `skipped` counter is bumped here, which is the only place the object is
1636    /// ever seen when the answer is no.
1637    fn wants(&self, kind: GitObjectKind) -> bool {
1638        if self.policy.wants(kind) {
1639            return true;
1640        }
1641        self.skipped.fetch_add(1, Ordering::Relaxed);
1642        false
1643    }
1644
1645    fn explode(&self, oid: &[u8], kind: GitObjectKind, payload: &[u8]) -> Result<()> {
1646        ExplodedArchive::explode(self, oid, kind, payload)
1647    }
1648
1649    fn flush(&self) -> Result<()> {
1650        ExplodedArchive::flush(self).map(|_| ())
1651    }
1652}
1653
1654// ════════════════════════════════════════════════════════════════════════════
1655// The policy: what gets exploded at all
1656// ════════════════════════════════════════════════════════════════════════════
1657
1658/// **How much of a pack is resolved into the exploded table.**
1659///
1660/// Three values and not a boolean, because a flat off-switch reintroduces a
1661/// correctness bug this table exists to fix. Commit and tree payloads used to
1662/// live only in RAM, so a **clean** shutdown came back with every pack's
1663/// `indexed` bit legitimately set and an EMPTY graph — MEASURED on oden
1664/// 2026-08-08: 2687 rows and **0 of 551 commits**, `reachable()` returning a
1665/// commit instead of its closure and `gc` seeing an empty live set.
1666///
1667/// MEASURED on `linux.git`: resolved content is 16.8 GB against a 6.4 GB pack,
1668/// and blobs are nearly all of it. So [`Graph`](ExplodePolicy::Graph) buys the
1669/// correctness fix for a small fraction of the disk, and
1670/// [`Full`](ExplodePolicy::Full) — one-lookup content reads, thin-pack bases,
1671/// and the path columns that make the table a filesystem — is the part worth
1672/// charging for.
1673///
1674/// **The default is [`Commits`](ExplodePolicy::Commits) since lane Q
1675/// (2026-08-30), and the change is a measurement.** §14's `indexed` bit is
1676/// derived by comparing this table's row count against the index's, so a table
1677/// that is *deliberately* short is indistinguishable, on disk, from one that was
1678/// dropped — see [`crate::git_ops::Absorber::adopt_journal`], which weakens that
1679/// comparison for every deliberately-short policy and cannot make it exact
1680/// without a durable per-kind count. That weakening is the price of the
1681/// default, it is stated here rather than hidden, and it costs a store that
1682/// really did lose its table one extra fall-back read per object rather than a
1683/// re-ingest.
1684#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1685pub enum ExplodePolicy {
1686    /// Store nothing. Reads re-resolve, and every pack is re-queued on reopen —
1687    /// which is what rebuilds the graph, since nothing it is folded from is on
1688    /// disk.
1689    Off,
1690    /// Commits and trees, both eager. The shape lane Q shipped first and
1691    /// **measured**: on the real `torvalds/linux` mirror the tree payloads
1692    /// alone are **28.24 GB — 3.24× the 8.13 GiB pack** — and folding them into
1693    /// RAM took peak RSS to 50.9 GiB. Kept as a setting, because a small
1694    /// repository that is read constantly wants exactly this; not the default,
1695    /// because an appliance ships with 16 GB.
1696    Graph,
1697    /// **Commits and tags only — the SHIPPED DEFAULT since lane Q
1698    /// (2026-08-30).**
1699    ///
1700    /// The index-only-at-push shape of
1701    /// `ideas/lazy-explode-index-only-at-push.md`, in full. Commits are what
1702    /// `graph` and `reach` fold and what a visibility or pull check reads; a
1703    /// tag is what a clone peels. Both are small and both stay eager, so
1704    /// neither ever stalls. **Trees and blobs** — 90 % of the objects and
1705    /// essentially all of the bytes — are written into
1706    /// [`crate::exploded_cache`]'s budgeted pool by the FIRST reader that
1707    /// inflates one, and evicted from it when the budget says so.
1708    ///
1709    /// Trees became lazy when [`crate::reach::TreeSource`] replaced the
1710    /// resident `HashMap<String, Vec<u8>>` that [`crate::serve`]'s closure walk
1711    /// and the reachability builder both read. That map was the 28.24 GB above.
1712    ///
1713    /// MEASURED, `torvalds/linux`, oden 2026-08-30, /data bytes per pack byte:
1714    ///
1715    /// | | eager (`Full`) | `Graph` | `Commits` |
1716    /// |---|---:|---:|---:|
1717    /// | at ack | 1.05× | 1.05× | 1.05× |
1718    /// | at index-complete | 22.4× (lane P, 78 % done) | 4.58× | see the lane Q rows |
1719    #[default]
1720    Commits,
1721    /// Every object, eagerly, with no bound. What shipped before lane Q and
1722    /// what the 17× measurement is of; kept so a bench can measure the
1723    /// unbounded shape and so a store written under it still opens.
1724    Full,
1725}
1726
1727impl ExplodePolicy {
1728    pub const fn wants(self, kind: GitObjectKind) -> bool {
1729        match self {
1730            ExplodePolicy::Off => false,
1731            ExplodePolicy::Graph => matches!(kind, GitObjectKind::Commit | GitObjectKind::Tree),
1732            ExplodePolicy::Commits => matches!(kind, GitObjectKind::Commit | GitObjectKind::Tag),
1733            ExplodePolicy::Full => true,
1734        }
1735    }
1736    pub const fn as_str(self) -> &'static str {
1737        match self {
1738            ExplodePolicy::Off => "off",
1739            ExplodePolicy::Graph => "graph",
1740            ExplodePolicy::Commits => "commits",
1741            ExplodePolicy::Full => "full",
1742        }
1743    }
1744    /// An unknown value is an ERROR, never a silent fall back to the default: a
1745    /// typo that quietly disables a paid tier is not noticed until a bill is
1746    /// wrong.
1747    pub fn parse(s: &str) -> Result<Self> {
1748        match s.trim().to_ascii_lowercase().as_str() {
1749            "off" | "none" => Ok(ExplodePolicy::Off),
1750            "graph" | "commits-and-trees" => Ok(ExplodePolicy::Graph),
1751            "commits" | "lazy" | "commits-only" => Ok(ExplodePolicy::Commits),
1752            "full" | "all" => Ok(ExplodePolicy::Full),
1753            other => anyhow::bail!(
1754                "unknown explode policy {other:?}; expected off, commits, graph or full"
1755            ),
1756        }
1757    }
1758    /// Reads `ZNIPPY_GIT_EXPLODE` ([`crate::arms::ENV_EXPLODE`]) through the
1759    /// crate's one counted door, once per store open.
1760    pub fn from_env() -> Result<Self> {
1761        match crate::arms::read_env(crate::arms::ENV_EXPLODE) {
1762            Some(v) => Self::parse(&v),
1763            None => Ok(explode_default()),
1764        }
1765    }
1766
1767    /// The discriminant, for the atomic behind [`set_explode_default`]. Private
1768    /// because it is storage and not a contract — the wire spelling is
1769    /// [`ExplodePolicy::as_str`].
1770    const fn as_u8(self) -> u8 {
1771        match self {
1772            ExplodePolicy::Off => 0,
1773            ExplodePolicy::Graph => 1,
1774            ExplodePolicy::Commits => 2,
1775            ExplodePolicy::Full => 3,
1776        }
1777    }
1778
1779    const fn from_u8(v: u8) -> Self {
1780        match v {
1781            0 => ExplodePolicy::Off,
1782            1 => ExplodePolicy::Graph,
1783            3 => ExplodePolicy::Full,
1784            _ => ExplodePolicy::Commits,
1785        }
1786    }
1787}
1788
1789/// What [`ExplodePolicy::from_env`] answers when [`crate::arms::ENV_EXPLODE`] is unset.
1790/// [`ExplodePolicy::default`] unless an embedder said otherwise.
1791static EXPLODE_DEFAULT: std::sync::atomic::AtomicU8 =
1792    std::sync::atomic::AtomicU8::new(ExplodePolicy::Commits.as_u8());
1793
1794/// The current process-wide default — what an unset environment means right now.
1795pub fn explode_default() -> ExplodePolicy {
1796    ExplodePolicy::from_u8(EXPLODE_DEFAULT.load(Ordering::Relaxed))
1797}
1798
1799/// **Set the process-wide default explode policy** for every store opened AFTER this call
1800/// (an explicit [`crate::arms::ENV_EXPLODE`] still wins). The twin of
1801/// [`crate::arms::set_graph_cache_default`], for an embedder that learns its role at runtime
1802/// and cannot set the environment — edition 2024 makes `set_var` unsafe, and gunnar forbids
1803/// `unsafe` — such as gunnar's twin, which holds packs, serves no reads, and must store no
1804/// exploded pool at all ([`ExplodePolicy::Off`]).
1805pub fn set_explode_default(policy: ExplodePolicy) {
1806    EXPLODE_DEFAULT.store(policy.as_u8(), Ordering::Relaxed);
1807}
1808
1809#[cfg(test)]
1810mod tests {
1811    use super::*;
1812    use crate::exploded::PayloadSink as _;
1813
1814    fn tmp(name: &str) -> PathBuf {
1815        let d = std::env::temp_dir().join(format!("exploded-arrow-{}-{name}", std::process::id()));
1816        let _ = std::fs::remove_dir_all(&d);
1817        std::fs::create_dir_all(&d).unwrap();
1818        d.join("objects.exploded")
1819    }
1820
1821    fn oid(n: u8) -> [u8; 20] {
1822        [n; 20]
1823    }
1824
1825    /// ★ ONE TABLE, and the payload is IN the row.
1826    ///
1827    /// Red-first: drop the payload column and nothing below compiles; widen
1828    /// `payload` to `Binary` and this fails on the type it asserts.
1829    #[test]
1830    fn the_table_holds_the_payload_and_a_name_in_one_row() {
1831        let s = exploded_schema(20);
1832        let names: Vec<&str> = s.fields().iter().map(|f| f.name().as_str()).collect();
1833        // `enc` sits before `payload` so the payload data buffer stays the last
1834        // buffer of the batch — `payload_data_offset` depends on that.
1835        assert_eq!(names, vec![COL_OID, COL_TYPE, COL_MODE, COL_PATH, COL_ENC, COL_PAYLOAD]);
1836        assert_eq!(
1837            s.field_with_name(COL_PAYLOAD).unwrap().data_type(),
1838            &DataType::LargeBinary,
1839            "Binary offsets are i32 and would cap one batch at 2 GiB of payload"
1840        );
1841        assert!(
1842            s.field_with_name(COL_PATH).unwrap().is_nullable(),
1843            "a bare pack resolve knows no path; null must be a legal answer"
1844        );
1845    }
1846
1847    /// ★ THE WHOLE POINT: the file stays near the payload total.
1848    ///
1849    /// redb held 16.8 GB of kernel payload in a 204 GB file — 12×. An Arrow IPC
1850    /// stream has no pages to rewrite, so the overhead is framing. Red-first:
1851    /// put this back on a copy-on-write B-tree and it fails.
1852    #[test]
1853    fn the_file_stays_close_to_the_payload_total() {
1854        let t = ExplodedArchive::open_with_policy(&tmp("size"), ExplodePolicy::Full).unwrap();
1855        let payload = vec![7u8; 4096];
1856        let n = 2000u64;
1857        for i in 0..n {
1858            let mut o = [0u8; 20];
1859            o[..8].copy_from_slice(&i.to_le_bytes());
1860            t.explode(&o, GitObjectKind::Blob, &payload).unwrap();
1861        }
1862        t.flush().unwrap();
1863        let payload_total = n * payload.len() as u64;
1864        let on_disk = t.disk_bytes();
1865        assert!(
1866            on_disk < payload_total + payload_total / 4,
1867            "{on_disk} bytes on disk against {payload_total} of payload — the medium is amplifying"
1868        );
1869        assert_eq!(t.rows().unwrap(), n);
1870    }
1871
1872    /// ★ A point read is one small `pread` of the payload's own bytes, and it
1873    /// is the path ACTUALLY taken — counted, not timed.
1874    ///
1875    /// Red-first, measured on a rust-lang/rust push (2026-08-19): without the
1876    /// extent, every `content` decoded its whole 64 MiB batch against a 4-slot
1877    /// cache, and the pre-ack connectivity walk — graph order, so effectively
1878    /// random across ~574 batches — decoded 6.7 GB/s of page cache to serve
1879    /// ~98 objects/s, one core pinned for hours. Both index-building paths are
1880    /// exercised: the in-process flush extension AND `index_now` after a
1881    /// reopen, against multi-batch tables with varied payload sizes, so a
1882    /// mis-computed extent returns the WRONG BYTES here rather than in a
1883    /// customer's clone.
1884    #[test]
1885    fn a_point_read_preads_the_exact_payload_without_decoding_the_batch() {
1886        let path = tmp("pread");
1887        let pay = |b: u8, i: u8| vec![b ^ i; 100 + i as usize * 7];
1888        let t = ExplodedArchive::open_with_policy(&path, ExplodePolicy::Full).unwrap();
1889        // Batch 0, then force the index to exist so batch 1 goes through the
1890        // flush EXTENSION path rather than a later index_now.
1891        for i in 0..40u8 {
1892            t.explode(&[i; 20], GitObjectKind::Blob, &pay(0, i)).unwrap();
1893        }
1894        t.flush().unwrap();
1895        assert!(t.content(&[0u8; 20]).unwrap().is_some(), "build the index");
1896        for i in 40..80u8 {
1897            t.explode(&[i; 20], GitObjectKind::Blob, &pay(1, i)).unwrap();
1898        }
1899        t.flush().unwrap();
1900
1901        let before = t.pread_served();
1902        for i in 0..80u8 {
1903            let (kind, got) = t.content(&[i; 20]).unwrap().expect("every oid is live");
1904            assert_eq!(kind, GitObjectKind::Blob);
1905            let want = if i < 40 { pay(0, i) } else { pay(1, i) };
1906            assert_eq!(got, want, "oid {i}: the pread returned some OTHER bytes");
1907        }
1908        assert_eq!(
1909            t.pread_served() - before,
1910            80,
1911            "a read fell back to the batch decode — the extent was not computed"
1912        );
1913
1914        // Reopen: the framing walk + index_now must reproduce the same extents
1915        // from the file alone.
1916        drop(t);
1917        let t = ExplodedArchive::open_with_policy(&path, ExplodePolicy::Full).unwrap();
1918        for i in 0..80u8 {
1919            let (_, got) = t.content(&[i; 20]).unwrap().expect("survives a reopen");
1920            let want = if i < 40 { pay(0, i) } else { pay(1, i) };
1921            assert_eq!(got, want, "oid {i} after reopen");
1922        }
1923        assert_eq!(t.pread_served(), 80, "the reopened table must pread too");
1924    }
1925
1926    /// **Lever 3: a compressible row is stored compressed and read back whole, on
1927    /// every read path.** Three rows: a 4 KiB compressible one (stored zlib), a
1928    /// row under [`MIN_ROW_COMPRESS`] (stored raw), and a 4 KiB incompressible
1929    /// one (zlib cannot get it under the keep threshold — stored raw). Asserted
1930    /// on the `enc` column read straight off the file, on the file being smaller
1931    /// than the payloads, and on `content` (the pread fast path — `pread_served`
1932    /// moves) and `of_kind` (the batch-decode path) both handing back the
1933    /// original bytes.
1934    ///
1935    /// Seen RED by returning `bytes.to_vec()` for `ENC_ZLIB` in `row_payload`:
1936    /// "the pread path returned the stored bytes, not the payload" — 4096 bytes
1937    /// expected, ~60 came back. Restored.
1938    #[test]
1939    fn a_compressible_row_is_stored_compressed_and_read_back_whole() {
1940        let path = tmp("lever3");
1941        let t = ExplodedArchive::open_with_policy(&path, ExplodePolicy::Full).unwrap();
1942        let big: Vec<u8> = b"tree 0123456789abcdef0123456789abcdef01234567\nparent x\n"
1943            .iter()
1944            .cycle()
1945            .take(4096)
1946            .copied()
1947            .collect();
1948        let tiny = b"tree x\n".to_vec();
1949        let noise: Vec<u8> = {
1950            let mut x: u32 = 0x1234_5678;
1951            (0..4096)
1952                .map(|_| {
1953                    x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1954                    (x >> 24) as u8
1955                })
1956                .collect()
1957        };
1958        assert!(tiny.len() < MIN_ROW_COMPRESS && big.len() >= MIN_ROW_COMPRESS);
1959        t.explode(&oid(1), GitObjectKind::Commit, &big).unwrap();
1960        t.explode(&oid(2), GitObjectKind::Commit, &tiny).unwrap();
1961        t.explode(&oid(3), GitObjectKind::Blob, &noise).unwrap();
1962        t.flush().unwrap();
1963
1964        // The file holds the compressed row: smaller than the payloads it
1965        // carries, which a raw pool never is.
1966        let file = std::fs::metadata(&path).unwrap().len() as usize;
1967        assert!(
1968            file < big.len() + tiny.len() + noise.len(),
1969            "the pool did not compress: {file} B for {} B of payload",
1970            big.len() + tiny.len() + noise.len()
1971        );
1972
1973        // The `enc` column, read off the file as the plain IPC stream it is.
1974        let rd = znippy_common::arrow::ipc::reader::StreamReader::try_new(
1975            std::fs::File::open(&path).unwrap(),
1976            None,
1977        )
1978        .unwrap();
1979        let mut encs = std::collections::BTreeMap::new();
1980        for b in rd {
1981            let b = b.unwrap();
1982            let oids = b
1983                .column_by_name(COL_OID)
1984                .and_then(|c| c.as_any().downcast_ref::<FixedSizeBinaryArray>())
1985                .unwrap();
1986            let enc = enc_column(&b).expect("a v2 pool has the enc column");
1987            for i in 0..b.num_rows() {
1988                encs.insert(oids.value(i)[0], enc.value(i));
1989            }
1990        }
1991        assert_eq!(encs[&1], ENC_ZLIB, "the compressible row is stored compressed");
1992        assert_eq!(encs[&2], ENC_RAW, "a row under the floor stays raw");
1993        assert_eq!(encs[&3], ENC_RAW, "an incompressible row stays raw");
1994
1995        // The pread fast path inflates.
1996        let before = t.pread_served();
1997        let (k, got) = t.content(&oid(1)).unwrap().unwrap();
1998        assert_eq!(k, GitObjectKind::Commit);
1999        assert_eq!(got, big, "the pread path returned the stored bytes, not the payload");
2000        assert_eq!(t.content(&oid(2)).unwrap().unwrap().1, tiny);
2001        assert_eq!(t.content(&oid(3)).unwrap().unwrap().1, noise);
2002        assert_eq!(t.pread_served() - before, 3, "all three went through the extent pread");
2003
2004        // The batch-decode path (`of_kind`) inflates too.
2005        let commits = t.of_kind(GitObjectKind::Commit).unwrap();
2006        let by: std::collections::HashMap<u8, Vec<u8>> =
2007            commits.into_iter().map(|(o, p)| (o[0], p)).collect();
2008        assert_eq!(by[&1], big, "of_kind returned the stored bytes, not the payload");
2009        assert_eq!(by[&2], tiny);
2010
2011        // And across a reopen, where the index is rebuilt from the file.
2012        drop(t);
2013        let t = ExplodedArchive::open_with_policy(&path, ExplodePolicy::Full).unwrap();
2014        assert_eq!(t.content(&oid(1)).unwrap().unwrap().1, big, "after reopen");
2015        assert_eq!(t.content(&oid(3)).unwrap().unwrap().1, noise, "after reopen");
2016    }
2017
2018    /// **A v1 pool — no `enc` column — still reads, every row raw.** Written by
2019    /// hand in v1's shape (five columns, the same framing `flush` uses), then
2020    /// opened by this build: the extent is computed (12 buffers is accepted),
2021    /// `enc` is absent and read as [`ENC_RAW`], and the bytes come back as
2022    /// written. This is the promise that lets an existing appliance's pools
2023    /// open unchanged.
2024    ///
2025    /// Seen RED by making `payload_data_offset` accept only 14 buffers: the
2026    /// pread count stayed 0 ("a v1 pool must still take the extent fast path").
2027    /// Restored.
2028    #[test]
2029    fn a_v1_pool_without_the_enc_column_reads_raw() {
2030        use znippy_common::arrow::array::{
2031            FixedSizeBinaryBuilder, LargeBinaryBuilder, StringBuilder, UInt32Builder,
2032        };
2033        use znippy_common::arrow::ipc::writer::{write_message, DictionaryTracker, IpcDataGenerator, IpcWriteOptions};
2034        let path = tmp("v1pool");
2035        let v1_schema: SchemaRef = Arc::new(Schema::new(vec![
2036            Field::new(COL_OID, DataType::FixedSizeBinary(20), false),
2037            Field::new(COL_TYPE, DataType::UInt8, false),
2038            Field::new(COL_MODE, DataType::UInt32, true),
2039            Field::new(COL_PATH, DataType::Utf8, true),
2040            Field::new(COL_PAYLOAD, DataType::LargeBinary, false),
2041        ]));
2042        let payloads: Vec<Vec<u8>> = (1..=5u8)
2043            .map(|i| b"tree abc\n".iter().cycle().take(300 + i as usize * 100).copied().collect())
2044            .collect();
2045        let mut oid_b = FixedSizeBinaryBuilder::with_capacity(5, 20);
2046        let mut kind_b = UInt8Builder::with_capacity(5);
2047        let mut mode_b = UInt32Builder::with_capacity(5);
2048        let mut path_b = StringBuilder::new();
2049        let mut pay_b = LargeBinaryBuilder::new();
2050        for (i, p) in payloads.iter().enumerate() {
2051            oid_b.append_value(oid(i as u8 + 1)).unwrap();
2052            kind_b.append_value(kind_code(GitObjectKind::Commit));
2053            mode_b.append_null();
2054            path_b.append_null();
2055            pay_b.append_value(p);
2056        }
2057        let batch = RecordBatch::try_new(
2058            v1_schema.clone(),
2059            vec![
2060                Arc::new(oid_b.finish()),
2061                Arc::new(kind_b.finish()),
2062                Arc::new(mode_b.finish()),
2063                Arc::new(path_b.finish()),
2064                Arc::new(pay_b.finish()),
2065            ],
2066        )
2067        .unwrap();
2068        let opts = IpcWriteOptions::default();
2069        let ipc = IpcDataGenerator::default();
2070        let mut tracker = DictionaryTracker::new(false);
2071        let mut file = Vec::new();
2072        {
2073            let enc = ipc.schema_to_bytes_with_dictionary_tracker(&v1_schema, &mut tracker, &opts);
2074            let mut msg = Vec::new();
2075            write_message(&mut msg, enc, &opts).unwrap();
2076            file.extend_from_slice(&msg);
2077        }
2078        {
2079            let (_, enc) = ipc.encode(&batch, &mut tracker, &opts, &mut Default::default()).unwrap();
2080            let mut msg = Vec::new();
2081            write_message(&mut msg, enc, &opts).unwrap();
2082            file.extend_from_slice(&msg);
2083        }
2084        std::fs::write(&path, &file).unwrap();
2085
2086        let t = ExplodedArchive::open_with_policy(&path, ExplodePolicy::Full).unwrap();
2087        for (i, p) in payloads.iter().enumerate() {
2088            let (k, got) = t.content(&oid(i as u8 + 1)).unwrap().expect("a v1 row is live");
2089            assert_eq!(k, GitObjectKind::Commit);
2090            assert_eq!(&got, p, "v1 row {} must read back raw", i + 1);
2091        }
2092        assert_eq!(t.pread_served(), 5, "a v1 pool must still take the extent fast path");
2093        // And it keeps working when this build appends to it: the appended
2094        // batch must be v1-shaped, because the stream's one schema message is
2095        // v1 — a six-column batch under it would not decode. Proven by reading
2096        // every batch back through Arrow's own stream reader afterwards.
2097        t.explode(&oid(9), GitObjectKind::Commit, &payloads[0]).unwrap();
2098        t.flush().unwrap();
2099        assert_eq!(t.content(&oid(9)).unwrap().unwrap().1, payloads[0]);
2100        assert_eq!(t.content(&oid(1)).unwrap().unwrap().1, payloads[0]);
2101        let rd = znippy_common::arrow::ipc::reader::StreamReader::try_new(
2102            std::fs::File::open(&path).unwrap(),
2103            None,
2104        )
2105        .unwrap();
2106        let mut rows = 0;
2107        for b in rd {
2108            let b = b.expect("every batch in a v1 file decodes under the v1 schema");
2109            assert!(enc_column(&b).is_none(), "a batch appended to a v1 pool must be v1-shaped");
2110            rows += b.num_rows();
2111        }
2112        assert_eq!(rows, 6, "five v1 rows and the one appended");
2113    }
2114
2115    #[test]
2116    fn a_payload_round_trips_through_the_table() {
2117        let t = ExplodedArchive::open_with_policy(&tmp("rt"), ExplodePolicy::Full).unwrap();
2118        t.explode(&oid(1), GitObjectKind::Commit, b"tree deadbeef\n")
2119            .unwrap();
2120        t.explode(&oid(2), GitObjectKind::Blob, b"hello world")
2121            .unwrap();
2122        t.flush().unwrap();
2123        assert_eq!(
2124            t.content(&oid(2)).unwrap().unwrap(),
2125            (GitObjectKind::Blob, b"hello world".to_vec())
2126        );
2127        assert_eq!(
2128            t.content(&oid(1)).unwrap().unwrap(),
2129            (GitObjectKind::Commit, b"tree deadbeef\n".to_vec())
2130        );
2131        assert!(t.has(&oid(1)).unwrap());
2132        assert!(!t.has(&oid(9)).unwrap());
2133    }
2134
2135    /// The row is a FILE: mode and path survive the round trip.
2136    #[test]
2137    fn a_row_can_carry_the_name_it_was_seen_at() {
2138        let t = ExplodedArchive::open_with_policy(&tmp("named"), ExplodePolicy::Full).unwrap();
2139        t.explode_at(
2140            &oid(1),
2141            GitObjectKind::Blob,
2142            Some(0o100755),
2143            Some("scripts/build.sh"),
2144            b"#!/bin/sh\n",
2145        )
2146        .unwrap();
2147        t.explode(&oid(2), GitObjectKind::Blob, b"anonymous").unwrap();
2148        t.flush().unwrap();
2149        assert_eq!(
2150            t.name(&oid(1)).unwrap().unwrap(),
2151            (Some(0o100755), Some("scripts/build.sh".to_owned()))
2152        );
2153        assert_eq!(
2154            t.name(&oid(2)).unwrap().unwrap(),
2155            (None, None),
2156            "null is 'not recorded', and must not read as a real name"
2157        );
2158    }
2159
2160    /// Reopening finds every row without reading a payload, and appends continue
2161    /// the SAME stream rather than starting a second one.
2162    #[test]
2163    fn the_table_survives_a_reopen_and_keeps_appending() {
2164        let p = tmp("reopen");
2165        {
2166            let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2167            t.explode(&oid(5), GitObjectKind::Tree, b"100644 f\0").unwrap();
2168            t.flush().unwrap();
2169        }
2170        let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2171        assert_eq!(t.rows().unwrap(), 1, "row count comes from batch metadata");
2172        t.explode(&oid(6), GitObjectKind::Blob, b"second session").unwrap();
2173        t.flush().unwrap();
2174        assert_eq!(t.rows().unwrap(), 2);
2175        assert_eq!(
2176            t.content(&oid(5)).unwrap().unwrap(),
2177            (GitObjectKind::Tree, b"100644 f\0".to_vec())
2178        );
2179        assert_eq!(
2180            t.content(&oid(6)).unwrap().unwrap(),
2181            (GitObjectKind::Blob, b"second session".to_vec())
2182        );
2183
2184        // And a third open sees both — one schema message, two batches.
2185        let again = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2186        assert_eq!(again.rows().unwrap(), 2);
2187        assert_eq!(again.batches.lock().unwrap().len(), 2);
2188    }
2189
2190    /// A read must not miss a row that is buffered but not yet written — an
2191    /// "absent" that is really "not flushed" sends the caller off to re-resolve
2192    /// a whole pack for an object we are holding.
2193    #[test]
2194    fn an_unflushed_row_is_still_served() {
2195        let t = ExplodedArchive::open_with_policy(&tmp("unflushed"), ExplodePolicy::Full).unwrap();
2196        t.explode(&oid(4), GitObjectKind::Commit, b"buffered").unwrap();
2197        assert_eq!(
2198            t.content(&oid(4)).unwrap().unwrap(),
2199            (GitObjectKind::Commit, b"buffered".to_vec())
2200        );
2201        assert!(t.has(&oid(4)).unwrap());
2202    }
2203
2204    #[test]
2205    fn an_absent_oid_is_none_and_counted() {
2206        let t = ExplodedArchive::open_with_policy(&tmp("absent"), ExplodePolicy::Full).unwrap();
2207        assert!(t.content(&oid(3)).unwrap().is_none());
2208        assert_eq!(t.stats().absent, 1);
2209        assert_eq!(t.stats().served, 0);
2210    }
2211
2212    #[test]
2213    fn of_kind_selects_by_kind() {
2214        let t = ExplodedArchive::open_with_policy(&tmp("kind"), ExplodePolicy::Full).unwrap();
2215        t.explode(&oid(1), GitObjectKind::Commit, b"c1").unwrap();
2216        t.explode(&oid(2), GitObjectKind::Blob, b"bb").unwrap();
2217        t.explode(&oid(3), GitObjectKind::Commit, b"c2").unwrap();
2218        let commits = t.of_kind(GitObjectKind::Commit).unwrap();
2219        assert_eq!(commits.len(), 2);
2220        assert!(commits.iter().all(|(_, p)| p[0] == b'c'));
2221    }
2222
2223    /// ★ A RETIRED ROW STAYS RETIRED ACROSS A REOPEN.
2224    ///
2225    /// The file is append-only, so `retain` writes a [`TOMBSTONE`] rather than
2226    /// deleting. Seen RED with an index-only `retain`: the reopen below rebuilds
2227    /// from the file and brought the dead row back — which is
2228    /// `store::tests::a_wholly_dead_pack_does_not_come_back_when_the_store_is_reopened`
2229    /// failing with "551 commits, not the one live one", reached from here in
2230    /// three lines instead of a whole gc.
2231    #[test]
2232    fn retain_drops_only_what_is_dead_and_the_drop_survives_a_reopen() {
2233        let p = tmp("retain");
2234        {
2235            let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2236            t.explode(&oid(1), GitObjectKind::Blob, b"a").unwrap();
2237            t.explode(&oid(2), GitObjectKind::Blob, b"b").unwrap();
2238            t.flush().unwrap();
2239            assert_eq!(t.retain(&|o: &[u8]| o[0] == 1).unwrap(), 1);
2240            assert!(t.has(&oid(1)).unwrap());
2241            assert!(!t.has(&oid(2)).unwrap());
2242            assert_eq!(
2243                t.of_kind(GitObjectKind::Blob).unwrap().len(),
2244                1,
2245                "a scan must not resurrect what retain dropped"
2246            );
2247        }
2248        let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2249        assert!(t.has(&oid(1)).unwrap(), "the live row did not survive");
2250        assert!(
2251            !t.has(&oid(2)).unwrap(),
2252            "a reopen resurrected a retired row — the tombstone is not durable"
2253        );
2254        assert!(t.content(&oid(2)).unwrap().is_none());
2255        assert_eq!(t.of_kind(GitObjectKind::Blob).unwrap().len(), 1);
2256    }
2257
2258    /// sha256 keys are not truncated to sha1 width, and a table refuses a width
2259    /// it cannot hold.
2260    #[test]
2261    fn a_sha256_oid_keeps_all_thirty_two_bytes() {
2262        let p = tmp("sha256");
2263        let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2264        let o = [3u8; 32];
2265        t.explode(&o, GitObjectKind::Tree, b"t").unwrap();
2266        t.flush().unwrap();
2267        assert!(t.has(&o).unwrap());
2268        assert_eq!(t.content(&o).unwrap().unwrap().1, b"t");
2269
2270        t.explode(&oid(1), GitObjectKind::Blob, b"narrow").unwrap();
2271        let err = t.flush().expect_err("a 20-byte oid cannot join a 32-byte table");
2272        assert!(format!("{err}").contains("32-byte oids"), "{err}");
2273    }
2274
2275    /// A torn tail is truncated away rather than left mid-stream, where every
2276    /// later batch would be unreachable.
2277    #[test]
2278    fn a_torn_tail_is_dropped_and_the_table_keeps_working() {
2279        let p = tmp("torn");
2280        {
2281            let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2282            t.explode(&oid(1), GitObjectKind::Blob, b"complete").unwrap();
2283            t.flush().unwrap();
2284        }
2285        // Half a message, as a killed process leaves.
2286        {
2287            let mut f = OpenOptions::new().append(true).open(&p).unwrap();
2288            f.write_all(&[0xFF, 0xFF, 0xFF, 0xFF, 0x40, 0x00, 0x00, 0x00, 1, 2, 3])
2289                .unwrap();
2290        }
2291        let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2292        assert_eq!(t.rows().unwrap(), 1, "the torn message contributes nothing");
2293        t.explode(&oid(2), GitObjectKind::Blob, b"after").unwrap();
2294        t.flush().unwrap();
2295        assert_eq!(t.rows().unwrap(), 2);
2296        assert_eq!(
2297            t.content(&oid(2)).unwrap().unwrap().1,
2298            b"after".to_vec(),
2299            "the append landed at the last good boundary, not after the garbage"
2300        );
2301    }
2302
2303    #[test]
2304    fn graph_keeps_commits_and_trees_and_drops_blobs() {
2305        let p = ExplodePolicy::Graph;
2306        assert!(p.wants(GitObjectKind::Commit));
2307        assert!(p.wants(GitObjectKind::Tree));
2308        assert!(!p.wants(GitObjectKind::Blob));
2309        assert!(!ExplodePolicy::Off.wants(GitObjectKind::Commit));
2310        assert!(ExplodePolicy::Full.wants(GitObjectKind::Blob));
2311        assert!(ExplodePolicy::Commits.wants(GitObjectKind::Commit));
2312        assert!(!ExplodePolicy::Commits.wants(GitObjectKind::Tree));
2313        assert_eq!(
2314            ExplodePolicy::default(),
2315            ExplodePolicy::Commits,
2316            "the shipped default is the lane Q one: commits and tags eager, trees \
2317             and blobs lazy and budgeted. `Full` is what put 22.4x the pack into \
2318             /data on the rig; `Graph` is what put 28.24 GB of tree payloads there \
2319             and 50.9 GiB of them in RAM."
2320        );
2321    }
2322
2323    /// ★ THE SETTING: a declined object is not stored, and is COUNTED — so a
2324    /// table short by policy and one short by fault do not look alike.
2325    #[test]
2326    fn a_declined_object_is_not_stored_and_is_counted() {
2327        let t = ExplodedArchive::open_with_policy(&tmp("policy"), ExplodePolicy::Graph).unwrap();
2328        t.explode(&oid(1), GitObjectKind::Commit, b"c").unwrap();
2329        t.explode(&oid(2), GitObjectKind::Blob, b"bbbb").unwrap();
2330        t.flush().unwrap();
2331        assert!(t.has(&oid(1)).unwrap());
2332        assert!(!t.has(&oid(2)).unwrap());
2333        assert_eq!(t.skipped(), 1);
2334        assert_eq!(t.rows().unwrap(), 1);
2335    }
2336
2337    /// `Off` writes no file at all — the whole point of the free tier.
2338    #[test]
2339    fn off_stores_nothing_and_leaves_no_file() {
2340        let p = tmp("off");
2341        let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Off).unwrap();
2342        t.explode(&oid(1), GitObjectKind::Commit, b"c").unwrap();
2343        t.explode(&oid(2), GitObjectKind::Blob, b"b").unwrap();
2344        assert_eq!(t.flush().unwrap(), 0);
2345        assert_eq!(t.rows().unwrap(), 0);
2346        assert_eq!(t.skipped(), 2);
2347        assert!(!p.exists(), "a disabled table must not create a file");
2348    }
2349
2350    // ════════════════════════════════════════════════════════════════════════
2351    // The stree in front of the lookup
2352    // ════════════════════════════════════════════════════════════════════════
2353
2354    /// `n` oids in `groups` of `per` that share their first EIGHT bytes and
2355    /// differ only after them — the collision is CONSTRUCTED, never hoped for.
2356    ///
2357    /// The prefixes deliberately straddle `0x80`: half the oids in a real repo
2358    /// start there, and they are the half a non-order-preserving key would sort
2359    /// onto the wrong side of the keyspace.
2360    fn colliding_oids(groups: usize, per: usize) -> Vec<[u8; 20]> {
2361        let mut out = Vec::with_capacity(groups * per);
2362        for g in 0..groups {
2363            let mut z = (g as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
2364            z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
2365            z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
2366            let prefix = (z ^ (z >> 31)).to_be_bytes();
2367            for k in 0..per {
2368                let mut o = [0u8; 20];
2369                o[..8].copy_from_slice(&prefix);
2370                o[8] = k as u8;
2371                o[9..13].copy_from_slice(&(g as u32).to_be_bytes());
2372                out.push(o);
2373            }
2374        }
2375        out
2376    }
2377
2378    /// ★ THE STREE RETURNS THE ROW THE BINARY SEARCH RETURNED — including on
2379    /// 8-byte prefix collisions, of which this table has 1000.
2380    ///
2381    /// Three answers are compared for every oid: the `stree` probe, the
2382    /// `binary_search` over the identical oid array that this file shipped with,
2383    /// and the **applied output** — the payload `content` hands back, which is
2384    /// unique per oid, so a wrong row is a wrong payload and not a passing
2385    /// assertion about a `Located` nobody read.
2386    ///
2387    /// Seen RED by deleting the full-oid comparison from `OidTree::verify` (i.e.
2388    /// `.find(|&i| self.oid_at(i) == oid)` → `.next()`, the "stree already found
2389    /// it" mistake): **"the stree and the binary search disagree at
2390    /// 0000000000000000010000000000000000000000: Some(Located { batch: 0, row: 0,
2391    /// kind: Blob }) vs Some(Located { batch: 0, row: 1, kind: Blob })"** — the
2392    /// probe was handed the row of the prefix-mate stored one slot earlier.
2393    #[test]
2394    fn the_stree_agrees_with_the_binary_search_it_replaced_on_colliding_prefixes() {
2395        let t = ExplodedArchive::open_with_policy(&tmp("stree-agree"), ExplodePolicy::Full).unwrap();
2396        let oids = colliding_oids(1000, 4);
2397        for (i, o) in oids.iter().enumerate() {
2398            t.explode(o, GitObjectKind::Blob, format!("payload-{i}").as_bytes())
2399                .unwrap();
2400        }
2401        t.flush().unwrap();
2402        // Force the index, then reach into it: the two finders must sit over the
2403        // SAME arrays, or this compares two indexes rather than two finders.
2404        t.index_now().unwrap();
2405        let idx = t.index.lock().unwrap();
2406        let tree = idx.as_ref().expect("index_now built it");
2407        assert_eq!(tree.len(), oids.len());
2408
2409        // The premise: the collisions are real in the built tree.
2410        let mut colliding_runs = 0usize;
2411        for o in &oids {
2412            let run = tree.candidate_run(key_for_oid(o));
2413            assert_eq!(
2414                run.len(),
2415                4,
2416                "expected a 4-entry candidate run for {}, got {run:?} — the collision \
2417                 the rest of this test rests on is not there",
2418                hex::encode(o)
2419            );
2420            colliding_runs += 1;
2421        }
2422        assert_eq!(colliding_runs, oids.len());
2423        // And the sign boundary is really crossed, or the key's top-bit flip is
2424        // untested by this corpus.
2425        assert!(
2426            oids.iter().any(|o| o[0] >= 0x80) && oids.iter().any(|o| o[0] < 0x80),
2427            "premise: the prefixes must straddle 0x80"
2428        );
2429
2430        for o in &oids {
2431            assert_eq!(
2432                tree.find(o),
2433                tree.find_by_binary_search(o),
2434                "the stree and the binary search disagree at {}: {:?} vs {:?}",
2435                hex::encode(o),
2436                tree.find(o),
2437                tree.find_by_binary_search(o)
2438            );
2439            assert!(tree.find(o).is_some(), "{} vanished", hex::encode(o));
2440        }
2441        // An oid on a colliding prefix that was never stored must MISS, in both
2442        // finders — this is the query a verify-less probe answers with somebody
2443        // else's row.
2444        for o in oids.iter().step_by(4) {
2445            let mut absent = *o;
2446            absent[8] = 0xff;
2447            assert_eq!(tree.find(&absent), None, "{} was never stored", hex::encode(absent));
2448            assert_eq!(tree.find_by_binary_search(&absent), None);
2449        }
2450        drop(idx);
2451
2452        // Applied output: each oid's own payload, not its prefix-mate's.
2453        for (i, o) in oids.iter().enumerate() {
2454            assert_eq!(
2455                t.content(o).unwrap().unwrap().1,
2456                format!("payload-{i}").into_bytes(),
2457                "{} came back with another object's bytes",
2458                hex::encode(o)
2459            );
2460        }
2461    }
2462
2463    /// ★ A TOMBSTONE STILL RETIRES AN OID WITH THE STREE IN FRONT — and its
2464    /// prefix-mates do not go with it, nor stand in for it.
2465    ///
2466    /// Two failure modes live here and both return a wrong answer rather than an
2467    /// error: a fold that keeps the *first* sighting rather than the last leaves
2468    /// the retired oid resolvable, and a probe that trusts the 8-byte key answers
2469    /// the retired oid with the row of the live oid it collides with.
2470    ///
2471    /// Seen RED three times:
2472    ///
2473    /// * `Keep::Last` → `Keep::First` in `index_now`: **"a reopen resurrected a
2474    ///   retired oid: 0000000000000000000000000000000000000000"**. The same break
2475    ///   also reds the older, coarser
2476    ///   `retain_drops_only_what_is_dead_and_the_drop_survives_a_reopen`.
2477    /// * the full-oid comparison dropped from `OidTree::verify`:
2478    ///   **"0000000000000000000000000000000000000000 was retired"** — the dead
2479    ///   oid answered `has` with its live prefix-mate's row, in-process, before
2480    ///   any reopen.
2481    /// * the incremental fold in `flush` no longer filtering the retired set
2482    ///   (`if !retired.contains(oid)` → `if true`): the same message, from the
2483    ///   live process rather than from a reopen.
2484    #[test]
2485    fn a_tombstoned_oid_stays_absent_when_a_live_oid_shares_its_prefix() {
2486        let p = tmp("stree-tomb");
2487        // Four oids per prefix: one is retired, three stay.
2488        let oids = colliding_oids(64, 4);
2489        let dead: Vec<[u8; 20]> = oids.iter().copied().step_by(4).collect();
2490        {
2491            let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2492            for (i, o) in oids.iter().enumerate() {
2493                t.explode(o, GitObjectKind::Blob, format!("live-{i}").as_bytes())
2494                    .unwrap();
2495            }
2496            t.flush().unwrap();
2497            let retired = t.retain(&|o: &[u8]| !dead.iter().any(|d| d == o)).unwrap();
2498            assert_eq!(retired, dead.len() as u64);
2499            for d in &dead {
2500                assert!(!t.has(d).unwrap(), "{} was retired", hex::encode(d));
2501                assert!(
2502                    t.content(d).unwrap().is_none(),
2503                    "the retired oid {} was answered with a prefix-mate's row",
2504                    hex::encode(d)
2505                );
2506            }
2507            for (i, o) in oids.iter().enumerate() {
2508                if i % 4 == 0 {
2509                    continue;
2510                }
2511                assert_eq!(
2512                    t.content(o).unwrap().unwrap().1,
2513                    format!("live-{i}").into_bytes(),
2514                    "{} is alive and must still answer with its OWN bytes",
2515                    hex::encode(o)
2516                );
2517            }
2518        }
2519        // ★ And a reopen — which rebuilds the tree from the file, tombstones and
2520        // all — finds every live row and none of the dead.
2521        let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2522        for (i, o) in oids.iter().enumerate() {
2523            if i % 4 == 0 {
2524                assert!(
2525                    !t.has(o).unwrap(),
2526                    "a reopen resurrected a retired oid: {}",
2527                    hex::encode(o)
2528                );
2529            } else {
2530                assert_eq!(
2531                    t.content(o).unwrap().unwrap().1,
2532                    format!("live-{i}").into_bytes(),
2533                    "a reopen lost or misrouted the live oid {}",
2534                    hex::encode(o)
2535                );
2536            }
2537        }
2538        assert_eq!(
2539            t.of_kind(GitObjectKind::Blob).unwrap().len(),
2540            oids.len() - dead.len()
2541        );
2542        // Only now — `rows()` answers from batch metadata until an index exists,
2543        // and the file still holds the retired rows and their tombstones. This
2544        // assertion measured 320 against 192 when it was made before the reads
2545        // above, which is the documented behaviour of `rows()` and not the
2546        // tombstone leaking.
2547        assert_eq!(t.rows().unwrap(), (oids.len() - dead.len()) as u64);
2548    }
2549
2550    /// The incremental extension in `flush` and the from-scratch rebuild in
2551    /// `index_now` must land on the same tree — one of them runs while a push is
2552    /// hot and the other after a restart, and a difference between them is a
2553    /// bug that only appears to the second process.
2554    ///
2555    /// Seen RED twice, once from each side, and the two reds are mirror images —
2556    /// which is what tells you the test compares the folds rather than one of
2557    /// them against itself:
2558    ///
2559    /// * incremental path drops the `retired` filter over the entries it carries
2560    ///   forward (`if !retired.contains(oid)` → `if true`): **"the two folds kept
2561    ///   a different number of oids: left: 150, right: 200"** — the live index
2562    ///   kept the 50 it had been told to retire.
2563    /// * `Keep::Last` → `Keep::First` in `index_now`: **"left: 200, right: 150"**
2564    ///   — the rebuild kept them instead.
2565    #[test]
2566    fn the_incremental_index_and_a_rebuilt_one_agree() {
2567        let p = tmp("stree-incr");
2568        let oids = colliding_oids(50, 4);
2569        let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2570        // Build the index FIRST, so every flush below takes the incremental path.
2571        t.index_now().unwrap();
2572        for (i, o) in oids.iter().enumerate() {
2573            t.explode(o, GitObjectKind::Blob, format!("v-{i}").as_bytes())
2574                .unwrap();
2575            if i % 37 == 0 {
2576                t.flush().unwrap();
2577            }
2578        }
2579        t.flush().unwrap();
2580        t.retain(&|o: &[u8]| o[8] != 3).unwrap();
2581        let live: Vec<(Vec<u8>, Vec<u8>)> = {
2582            let idx = t.index.lock().unwrap();
2583            idx.as_ref()
2584                .unwrap()
2585                .iter()
2586                .map(|(o, l)| (o.to_vec(), vec![l.batch as u8, l.row as u8]))
2587                .collect()
2588        };
2589        drop(t);
2590
2591        let again = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2592        again.index_now().unwrap();
2593        let rebuilt = again.index.lock().unwrap();
2594        let rebuilt = rebuilt.as_ref().unwrap();
2595        assert_eq!(rebuilt.len(), live.len(), "the two folds kept a different number of oids");
2596        for (o, _) in &live {
2597            assert!(
2598                rebuilt.find(o).is_some(),
2599                "the live process and a reopen disagree about {}: Some(..) vs None",
2600                hex::encode(o)
2601            );
2602        }
2603        for o in oids.iter().filter(|o| o[8] == 3) {
2604            assert!(rebuilt.find(o).is_none(), "{} was retired", hex::encode(o));
2605        }
2606    }
2607
2608    /// The measurement behind the change, re-takeable: three finders over the
2609    /// SAME 1 000 000 entries — the `Vec<(Vec<u8>, Located)>` this file shipped
2610    /// with, a binary search over the flat array, and the stree.
2611    ///
2612    /// `--ignored` because it is a measurement, not a guard: it asserts only that
2613    /// the three agree, and prints the times. Run it with
2614    /// `cargo test --release -p znippy-plugin-git --lib exploded_arrow -- --ignored --nocapture`
2615    /// — a debug build measures the borrow checker, not the machine.
2616    ///
2617    /// ## Measured, oden 2026-08-14, `--release`, 1 000 000 entries, 200 000
2618    /// probes (half misses), three runs
2619    ///
2620    /// | arm | ns/probe | vs shipped |
2621    /// |---|---:|---:|
2622    /// | `Vec<(Vec<u8>, Located)>` + `binary_search` (what shipped) | 836 / 862 / 961 | 1.00 |
2623    /// | flat oid array + `binary_search` | 339 / 339 / 348 | 0.40 |
2624    /// | **stree** | **164 / 175 / 185** | **0.21** |
2625    ///
2626    /// So the structure is worth **~2×** on its own and the flattening another
2627    /// **~2.5×**, and the two together take a point lookup to a fifth of what it
2628    /// cost. **The box was NOT quiet** — `/proc/loadavg` 1-min 29.7–31.5 on 32
2629    /// cores, other agents building throughout — so the absolute figures are
2630    /// upper bounds. The ratios are reported instead, and each arm's own spread
2631    /// across the three runs (14% / 2.7% / 12%) is far narrower than the 5×
2632    /// and 2× between them.
2633    #[test]
2634    #[ignore = "measurement; run under --release with --ignored"]
2635    fn lookup_cost_before_and_after() {
2636        use std::time::Instant;
2637        let n = 1_000_000usize;
2638        // 4 oids per prefix, so ~25% of probes land in a run of four and the
2639        // verify step is exercised rather than skipped.
2640        let oids = colliding_oids(n / 4, 4);
2641        let mut b = OidTreeBuilder::with_capacity(oids.len());
2642        for (i, o) in oids.iter().enumerate() {
2643            b.push(o, Some(Located { batch: (i / 100_000) as u32, row: i as u32, kind: GitObjectKind::Blob, pay_at: EXTENT_UNAVAILABLE, pay_len: 0, enc: ENC_RAW }))
2644                .unwrap();
2645        }
2646        let build = Instant::now();
2647        let tree = b.finish(Keep::Last);
2648        let build = build.elapsed();
2649
2650        // The shape this replaced: one heap allocation per oid.
2651        let mut old: Vec<(Vec<u8>, Located)> =
2652            tree.iter().map(|(o, l)| (o.to_vec(), l)).collect();
2653        old.sort_by(|a, b| a.0.cmp(&b.0));
2654
2655        // A miss-heavy probe order, and NOT in oid order — a `have` negotiation
2656        // is random and half of it misses.
2657        let mut probes: Vec<[u8; 20]> = Vec::with_capacity(200_000);
2658        for i in (0..oids.len()).step_by(oids.len() / 100_000) {
2659            probes.push(oids[i]);
2660            let mut m = oids[i];
2661            m[8] = 0xfe;
2662            probes.push(m);
2663        }
2664
2665        let mut sink = 0u64;
2666        let t0 = Instant::now();
2667        for p in &probes {
2668            if let Ok(i) = old.binary_search_by(|(o, _)| o.as_slice().cmp(&p[..])) {
2669                sink += old[i].1.row as u64;
2670            }
2671        }
2672        let vec_of_vec = t0.elapsed();
2673        let t0 = Instant::now();
2674        for p in &probes {
2675            if let Some(l) = tree.find_by_binary_search(p) {
2676                sink += l.row as u64;
2677            }
2678        }
2679        let flat_bsearch = t0.elapsed();
2680        let t0 = Instant::now();
2681        for p in &probes {
2682            if let Some(l) = tree.find(p) {
2683                sink += l.row as u64;
2684            }
2685        }
2686        let stree = t0.elapsed();
2687
2688        // The arms must be the same question.
2689        for p in &probes {
2690            let want = tree.find_by_binary_search(p);
2691            assert_eq!(tree.find(p), want, "arms disagree at {}", hex::encode(p));
2692        }
2693        let per = |d: std::time::Duration| d.as_secs_f64() * 1e9 / probes.len() as f64;
2694        println!(
2695            "exploded oid lookup, {} entries ({} groups of 4 colliding prefixes), \
2696             {} probes half of them misses:\n  \
2697             Vec<(Vec<u8>,Located)> binary_search  {:>7.1} ns/probe\n  \
2698             flat array binary_search             {:>7.1} ns/probe\n  \
2699             stree                                {:>7.1} ns/probe\n  \
2700             tree build (sort + fold + stree)      {:.3} s   sink={sink}",
2701            tree.len(),
2702            oids.len() / 4,
2703            probes.len(),
2704            per(vec_of_vec),
2705            per(flat_bsearch),
2706            per(stree),
2707            build.as_secs_f64(),
2708        );
2709    }
2710
2711    #[test]
2712    fn an_unknown_policy_is_refused() {
2713        assert_eq!(ExplodePolicy::parse("full").unwrap(), ExplodePolicy::Full);
2714        let err = ExplodePolicy::parse("ful").expect_err("a typo must be refused");
2715        assert!(format!("{err}").contains("unknown explode policy"), "{err}");
2716    }
2717}
2718