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                let mut whole_msg = Vec::with_capacity((8 + meta_len) as usize);
850                whole_msg.extend_from_slice(&hdr);
851                whole_msg.extend_from_slice(&meta);
852                // A schema message the IPC guard refuses is where the good part
853                // of the file ends, like a torn tail: the table is derived and
854                // is re-exploded from there.
855                if znippy_common::ipc_guard::check_stream(&whole_msg).is_err() {
856                    break;
857                }
858                schema_msg = Some(whole_msg);
859                oid_len = Self::oid_len_of_schema_msg(schema_msg.as_ref().unwrap());
860            }
861            at += whole;
862        }
863        Ok((schema_msg, batches, at, oid_len))
864    }
865
866    /// The declared oid width, so a reopened table refuses a hash it cannot
867    /// hold instead of writing a batch no reader can line up.
868    /// The schema inside a stream schema message (`msg` = the 8-byte
869    /// continuation header + the flatbuffer), read off the flatbuffer directly.
870    ///
871    /// Not through `StreamDecoder`: fed a schema message alone it returns
872    /// `Ok(None)` and its `schema()` stays `None` — MEASURED 2026-09-05 with a
873    /// probe on a file this writer had just produced (`decode=Ok(false)
874    /// schema=None`). `oid_len_of_schema_msg` had used exactly that path since
875    /// it was written and therefore always answered `None`; nothing depended on
876    /// it, so nothing noticed. `legacy_v1` does depend on it, which is how it
877    /// surfaced: a fresh v2 file was read as v1 and the next append was written
878    /// five columns wide under a six-column schema.
879    fn schema_of_msg(msg: &[u8]) -> Option<Schema> {
880        // `fb_to_schema` panics on a schema with no field vector or a type it
881        // half-knows: the IPC guard checks the message first.
882        znippy_common::ipc_guard::check_stream(msg).ok()?;
883        let meta = msg.get(8..)?;
884        let m = root_as_message(meta).ok()?;
885        let fb = m.header_as_schema()?;
886        Some(znippy_common::arrow::ipc::convert::fb_to_schema(fb))
887    }
888
889    /// Whether the file's schema message carries the v2 `enc` column.
890    fn schema_has_enc(msg: &[u8]) -> bool {
891        Self::schema_of_msg(msg).is_some_and(|s| s.field_with_name(COL_ENC).is_ok())
892    }
893
894    fn oid_len_of_schema_msg(msg: &[u8]) -> Option<usize> {
895        let schema = Self::schema_of_msg(msg)?;
896        match schema.field_with_name(COL_OID).ok()?.data_type() {
897            DataType::FixedSizeBinary(n) => Some(*n as usize),
898            _ => None,
899        }
900    }
901
902    /// One resolved object with no name attached — what [`crate::exploded::PayloadSink`]
903    /// can supply.
904    pub fn explode(&self, oid: &[u8], kind: GitObjectKind, payload: &[u8]) -> Result<()> {
905        self.explode_at(oid, kind, None, None, payload)
906    }
907
908    /// One resolved object **with its name**: the mode and path a tree walk knows.
909    ///
910    /// A blob is reachable at many paths, so this records the first one seen and
911    /// never rewrites it — a row that already exists is not re-keyed by a second
912    /// sighting, because "which of its names" is not a question this table
913    /// pretends to answer.
914    pub fn explode_at(
915        &self,
916        oid: &[u8],
917        kind: GitObjectKind,
918        mode: Option<u32>,
919        path: Option<&str>,
920        payload: &[u8],
921    ) -> Result<()> {
922        if !self.policy.wants(kind) {
923            self.skipped.fetch_add(1, Ordering::Relaxed);
924            return Ok(());
925        }
926        {
927            let mut p = self
928                .pending
929                .lock()
930                .map_err(|_| anyhow::anyhow!("exploded pending poisoned"))?;
931            // **One `extend_from_slice` into the arena, no allocation of its
932            // own.** This line was `payload.to_vec()` — a whole second copy of
933            // the object the caller is holding, which is the byte lane AA
934            // measured on 2026-08-30.
935            let pay = p.stash(payload);
936            p.rows.push(Pending {
937                oid: oid.to_vec(),
938                code: kind_code(kind),
939                mode,
940                path: path.map(str::to_owned),
941                pay,
942            });
943        }
944        let n = self
945            .pending_bytes
946            .fetch_add(payload.len() as u64, Ordering::AcqRel)
947            + payload.len() as u64;
948        if n >= FLUSH_BYTES as u64 {
949            self.flush()?;
950        }
951        Ok(())
952    }
953
954    /// `v1`: write the batch in schema v1 — no `enc` column, every row raw —
955    /// because the file it is appended to was opened with a v1 schema message.
956    fn build_batch(rows: &[Pending], arena: &[u8], oid_len: usize, v1: bool) -> Result<RecordBatch> {
957        if v1 {
958            let mut oid_b = FixedSizeBinaryBuilder::with_capacity(rows.len(), oid_len as i32);
959            let mut kind_b = UInt8Builder::with_capacity(rows.len());
960            let mut mode_b = UInt32Builder::with_capacity(rows.len());
961            let mut path_b = StringBuilder::new();
962            let mut pay_b = LargeBinaryBuilder::new();
963            for r in rows {
964                oid_b
965                    .append_value(&r.oid)
966                    .map_err(|e| anyhow::anyhow!("exploded oid column: {e}"))?;
967                kind_b.append_value(r.code);
968                mode_b.append_option(r.mode);
969                path_b.append_option(r.path.as_deref());
970                pay_b.append_value(&arena[r.pay.clone()]);
971            }
972            return RecordBatch::try_new(
973                exploded_schema_v1(oid_len),
974                vec![
975                    Arc::new(oid_b.finish()),
976                    Arc::new(kind_b.finish()),
977                    Arc::new(mode_b.finish()),
978                    Arc::new(path_b.finish()),
979                    Arc::new(pay_b.finish()),
980                ],
981            )
982            .context("building a v1 exploded batch");
983        }
984        let mut oid_b = FixedSizeBinaryBuilder::with_capacity(rows.len(), oid_len as i32);
985        let mut kind_b = UInt8Builder::with_capacity(rows.len());
986        let mut mode_b = UInt32Builder::with_capacity(rows.len());
987        let mut path_b = StringBuilder::new();
988        let mut enc_b = UInt8Builder::with_capacity(rows.len());
989        let mut pay_b = LargeBinaryBuilder::new();
990        for r in rows {
991            oid_b
992                .append_value(&r.oid)
993                .map_err(|e| anyhow::anyhow!("exploded oid column: {e}"))?;
994            kind_b.append_value(r.code);
995            mode_b.append_option(r.mode);
996            path_b.append_option(r.path.as_deref());
997            // Per row, at build time: the pending arena keeps rows raw (so the
998            // pending-serve path hands them out untouched), and what lands in
999            // the file is whatever is smaller.
1000            let raw = &arena[r.pay.clone()];
1001            match compress_row(raw) {
1002                Some(z) => {
1003                    enc_b.append_value(ENC_ZLIB);
1004                    pay_b.append_value(&z);
1005                }
1006                None => {
1007                    enc_b.append_value(ENC_RAW);
1008                    pay_b.append_value(raw);
1009                }
1010            }
1011        }
1012        RecordBatch::try_new(
1013            exploded_schema(oid_len),
1014            vec![
1015                Arc::new(oid_b.finish()),
1016                Arc::new(kind_b.finish()),
1017                Arc::new(mode_b.finish()),
1018                Arc::new(path_b.finish()),
1019                Arc::new(enc_b.finish()),
1020                Arc::new(pay_b.finish()),
1021            ],
1022        )
1023        .context("building the exploded batch")
1024    }
1025
1026    /// Append the buffered rows as ONE batch message. Nothing already in the
1027    /// file is read or rewritten.
1028    pub fn flush(&self) -> Result<u64> {
1029        let (rows, arena) = {
1030            let mut p = self
1031                .pending
1032                .lock()
1033                .map_err(|_| anyhow::anyhow!("exploded pending poisoned"))?;
1034            if p.is_empty() {
1035                return Ok(0);
1036            }
1037            self.pending_bytes.store(0, Ordering::Release);
1038            p.take()
1039        };
1040        let n = rows.len() as u64;
1041        let width = rows[0].oid.len();
1042        anyhow::ensure!(
1043            rows.iter().all(|r| r.oid.len() == width),
1044            "one exploded batch cannot hold two hash widths"
1045        );
1046        {
1047            let mut w = self
1048                .oid_len
1049                .lock()
1050                .map_err(|_| anyhow::anyhow!("exploded oid width poisoned"))?;
1051            match *w {
1052                Some(have) => anyhow::ensure!(
1053                    have == width,
1054                    "this table holds {have}-byte oids and a {width}-byte one arrived"
1055                ),
1056                None => *w = Some(width),
1057            }
1058        }
1059
1060        let batch = Self::build_batch(&rows, &arena, width, self.legacy_v1.load(Ordering::Relaxed))?;
1061        let opts = IpcWriteOptions::default();
1062        let ipc = IpcDataGenerator::default();
1063        let mut tracker = DictionaryTracker::new(false);
1064
1065        // The file is opened per flush rather than held: an append writes at a
1066        // known offset and closing between batches is what makes a crashed
1067        // process leave a file whose last complete message is intact.
1068        let mut end = self
1069            .end
1070            .lock()
1071            .map_err(|_| anyhow::anyhow!("exploded end poisoned"))?;
1072        if self.retired.load(Ordering::Acquire) {
1073            // Evicted: its path is gone, and opening it with `create` would
1074            // bring it back as an orphan. The rows were a cache.
1075            return Ok(0);
1076        }
1077        let mut f = OpenOptions::new()
1078            .create(true)
1079            .read(true)
1080            .write(true)
1081            .truncate(false)
1082            .open(&self.path)
1083            .with_context(|| format!("opening {}", self.path.display()))?;
1084        // Drop anything after the last complete message before appending — a
1085        // torn tail from a previous crash must not sit in the middle of the
1086        // stream, where every later batch would be unreachable.
1087        if f.metadata()?.len() != *end {
1088            f.set_len(*end)
1089                .with_context(|| format!("truncating {} to {}", self.path.display(), *end))?;
1090        }
1091        f.seek(SeekFrom::Start(*end))?;
1092
1093        let mut schema_guard = self
1094            .schema_msg
1095            .lock()
1096            .map_err(|_| anyhow::anyhow!("exploded schema poisoned"))?;
1097        if schema_guard.is_none() {
1098            let enc =
1099                ipc.schema_to_bytes_with_dictionary_tracker(&exploded_schema(width), &mut tracker, &opts);
1100            let mut msg = Vec::new();
1101            let (meta, body) = write_message(&mut msg, enc, &opts)
1102                .map_err(|e| anyhow::anyhow!("encoding the exploded schema: {e}"))?;
1103            debug_assert_eq!(meta + body, msg.len());
1104            f.write_all(&msg).context("writing the exploded schema")?;
1105            *end += msg.len() as u64;
1106            *schema_guard = Some(msg);
1107        }
1108        drop(schema_guard);
1109
1110        let (dicts, enc) = ipc
1111            .encode(&batch, &mut tracker, &opts, &mut Default::default())
1112            .map_err(|e| anyhow::anyhow!("encoding an exploded batch: {e}"))?;
1113        anyhow::ensure!(
1114            dicts.is_empty(),
1115            "the exploded schema has no dictionary columns, yet {} arrived",
1116            dicts.len()
1117        );
1118        let mut msg = Vec::new();
1119        let (meta, body) = write_message(&mut msg, enc, &opts)
1120            .map_err(|e| anyhow::anyhow!("encoding an exploded batch: {e}"))?;
1121        debug_assert_eq!(meta + body, msg.len());
1122        f.write_all(&msg).context("appending an exploded batch")?;
1123
1124        let placed = Batch {
1125            at: *end,
1126            len: msg.len() as u64,
1127            rows: rows.len() as u32,
1128            // `meta` from `write_message` is the 8-byte prefix plus the padded
1129            // metadata, so the body begins exactly `meta` bytes in — and the
1130            // metadata slice between prefix and body is what the offset helper
1131            // parses, the same bytes `walk` reads back after a reopen.
1132            body: *end + meta as u64,
1133            pay_data: payload_data_offset(&msg[8..meta]).unwrap_or(EXTENT_UNAVAILABLE),
1134        };
1135        *end += msg.len() as u64;
1136
1137        // Recorded while the append lock is still held, so the batch table stays
1138        // in file order under N concurrent exploders. Correctness would survive
1139        // it being out of order — a lookup addresses a batch by its slot, not by
1140        // its offset — but a table that reads back in file order is one a human
1141        // can check against the file with `od`.
1142        let batch_no = {
1143            let mut b = self
1144                .batches
1145                .lock()
1146                .map_err(|_| anyhow::anyhow!("exploded batches poisoned"))?;
1147            b.push(placed);
1148            (b.len() - 1) as u32
1149        };
1150        drop(end);
1151
1152        // Only extend an index that already exists. Building one here would make
1153        // the first push pay for a structure no reader has asked for.
1154        let mut idx = self
1155            .index
1156            .lock()
1157            .map_err(|_| anyhow::anyhow!("exploded index poisoned"))?;
1158        if let Some(old) = idx.take() {
1159            // Retired oids are collected and applied in ONE pass. Removing them
1160            // one at a time is quadratic, and a `gc` retires millions.
1161            let mut retired: std::collections::HashSet<&[u8]> = std::collections::HashSet::new();
1162            for r in rows.iter() {
1163                if kind_of(r.code).is_none() {
1164                    retired.insert(r.oid.as_slice());
1165                }
1166            }
1167            let mut b = OidTreeBuilder::with_capacity(old.len() + rows.len());
1168            for (oid, loc) in old.iter() {
1169                if !retired.contains(oid) {
1170                    b.push(oid, Some(loc))?;
1171                }
1172            }
1173            let pay = batch
1174                .column_by_name(COL_PAYLOAD)
1175                .and_then(|c| c.as_any().downcast_ref::<LargeBinaryArray>())
1176                .context("the exploded table has no payload column")?;
1177            // Freshly built, never sliced, so these offsets are byte-for-byte
1178            // what the encoder just wrote into the file — the same equivalence
1179            // `index_now` relies on after a reopen.
1180            let off = pay.value_offsets();
1181            let enc = enc_column(&batch);
1182            for (i, r) in rows.iter().enumerate() {
1183                if let Some(kind) = kind_of(r.code)
1184                    && !retired.contains(r.oid.as_slice())
1185                {
1186                    let (pay_at, pay_len) = if placed.pay_data == EXTENT_UNAVAILABLE {
1187                        (EXTENT_UNAVAILABLE, 0)
1188                    } else {
1189                        (
1190                            placed.body + placed.pay_data + off[i] as u64,
1191                            (off[i + 1] - off[i]) as u64,
1192                        )
1193                    };
1194                    b.push(
1195                        &r.oid,
1196                        Some(Located {
1197                            batch: batch_no,
1198                            row: i as u32,
1199                            kind,
1200                            pay_at,
1201                            pay_len,
1202                            enc: enc_at(enc, i),
1203                        }),
1204                    )?;
1205                }
1206            }
1207            // `Keep::First`, because the surviving entries were pushed before
1208            // this batch's rows: an oid already in the index keeps the row it
1209            // already had, which is what `explode_at` documents about names.
1210            *idx = Some(b.finish(Keep::First));
1211        }
1212        self.written.fetch_add(n, Ordering::Relaxed);
1213        Ok(n)
1214    }
1215
1216    /// How many decoded batches stay resident. Four × [`FLUSH_BYTES`] is the
1217    /// worst case, and a batch is `Arc`-backed so a hit copies pointers.
1218    const CACHE: usize = 4;
1219
1220    /// Read one batch message off disk and decode it — or hand back the decoded
1221    /// copy if it is one of the last [`Self::CACHE`].
1222    ///
1223    /// Two `pread`s on a miss: the schema message and the batch. It never reads
1224    /// the batches in front of the one it wants — the property a stream reader
1225    /// iterating from byte zero does not have.
1226    fn read_batch(&self, no: u32) -> Result<RecordBatch> {
1227        {
1228            let mut c = self
1229                .cache
1230                .lock()
1231                .map_err(|_| anyhow::anyhow!("exploded batch cache poisoned"))?;
1232            if let Some(at) = c.iter().position(|(n, _)| *n == no) {
1233                let hit = c.remove(at);
1234                let batch = hit.1.clone();
1235                c.insert(0, hit);
1236                return Ok(batch);
1237            }
1238        }
1239        let placed = {
1240            let b = self
1241                .batches
1242                .lock()
1243                .map_err(|_| anyhow::anyhow!("exploded batches poisoned"))?;
1244            *b.get(no as usize)
1245                .with_context(|| format!("exploded batch {no} is not in this table"))?
1246        };
1247        let schema_msg = {
1248            let s = self
1249                .schema_msg
1250                .lock()
1251                .map_err(|_| anyhow::anyhow!("exploded schema poisoned"))?;
1252            s.clone()
1253                .context("the exploded table has batches but no schema message")?
1254        };
1255        let f = File::open(&self.path)
1256            .with_context(|| format!("opening {}", self.path.display()))?;
1257        let mut raw = vec![0u8; placed.len as usize];
1258        f.read_exact_at(&mut raw, placed.at)
1259            .with_context(|| format!("reading exploded batch {no}"))?;
1260
1261        // The batch is read off disk under the schema message held apart: the
1262        // IPC guard checks both before arrow sees them, so a hostile file is an
1263        // `Err` and never an arrow-ipc panic or abort. Metadata only, no copy.
1264        znippy_common::ipc_guard::check_batches_after_schema(&schema_msg, &raw)
1265            .map_err(|e| anyhow::anyhow!("exploded batch {no}: {e}"))?;
1266        let mut dec = StreamDecoder::new();
1267        let mut head = Buffer::from_vec(schema_msg);
1268        dec.decode(&mut head)
1269            .map_err(|e| anyhow::anyhow!("decoding the exploded schema: {e}"))?;
1270        let mut body = Buffer::from_vec(raw);
1271        let batch = dec
1272            .decode(&mut body)
1273            .map_err(|e| anyhow::anyhow!("decoding exploded batch {no}: {e}"))?
1274            .with_context(|| format!("exploded batch {no} decoded to no rows"))?;
1275        {
1276            let mut c = self
1277                .cache
1278                .lock()
1279                .map_err(|_| anyhow::anyhow!("exploded batch cache poisoned"))?;
1280            c.retain(|(n, _)| *n != no);
1281            c.insert(0, (no, batch.clone()));
1282            c.truncate(Self::CACHE);
1283        }
1284        Ok(batch)
1285    }
1286
1287    /// Build `oid → Located` with one sequential pass, applying every
1288    /// [`TOMBSTONE`] in file order so a retired oid stays retired across a
1289    /// reopen. Called on the first lookup, never on open.
1290    fn index_now(&self) -> Result<()> {
1291        {
1292            let idx = self
1293                .index
1294                .lock()
1295                .map_err(|_| anyhow::anyhow!("exploded index poisoned"))?;
1296            if idx.is_some() {
1297                return Ok(());
1298            }
1299        }
1300        let (count, rows, placed) = {
1301            let b = self
1302                .batches
1303                .lock()
1304                .map_err(|_| anyhow::anyhow!("exploded batches poisoned"))?;
1305            // The row total is in the batch metadata the framing walk already
1306            // read, so the builder's arrays are sized once instead of doubling
1307            // their way to 11.7 million. The count is only a size HINT, and
1308            // a file's metadata can claim any count: each batch's is capped by
1309            // its own length in bytes (every row carries at least its oid), so
1310            // a hostile file cannot size the index past the file itself.
1311            let hint = |x: &Batch| (x.rows as u64).min(x.len) as usize;
1312            (b.len() as u32, b.iter().map(hint).sum::<usize>(), b.clone())
1313        };
1314        // Every row is recorded as a sighting and the fold happens once, at
1315        // `finish`. The `HashMap<Vec<u8>, Located>` this replaced allocated —
1316        // and then dropped — one `Vec<u8>` per oid on a corpus with 11.7 M of
1317        // them, to compute an answer a single stable sort gives.
1318        let mut fold = OidTreeBuilder::with_capacity(rows);
1319        for no in 0..count {
1320            let batch = self.read_batch(no)?;
1321            let oid = batch
1322                .column_by_name(COL_OID)
1323                .and_then(|c| c.as_any().downcast_ref::<FixedSizeBinaryArray>())
1324                .context("the exploded table has no oid column")?;
1325            let kinds = batch
1326                .column_by_name(COL_TYPE)
1327                .and_then(|c| c.as_any().downcast_ref::<UInt8Array>())
1328                .context("the exploded table has no object_type column")?;
1329            let pay = batch
1330                .column_by_name(COL_PAYLOAD)
1331                .and_then(|c| c.as_any().downcast_ref::<LargeBinaryArray>())
1332                .context("the exploded table has no payload column")?;
1333            // The decoded offsets carry the SAME values the file's offsets
1334            // buffer holds — a StreamDecoder copies buffers verbatim — so the
1335            // extent needs no second parse of the body.
1336            let off = pay.value_offsets();
1337            let enc = enc_column(&batch);
1338            let b = placed[no as usize];
1339            for i in 0..batch.num_rows() {
1340                // A tombstone is pushed as a sighting with no location, not
1341                // skipped: batches are walked in file order and rows in row
1342                // order, so `Keep::Last` gives the last word about an oid — and
1343                // when that word is a tombstone the oid is dropped, which is
1344                // what makes the tombstone durable rather than advisory.
1345                fold.push(
1346                    oid.value(i),
1347                    kind_of(kinds.value(i)).map(|kind| {
1348                        let (pay_at, pay_len) = if b.pay_data == EXTENT_UNAVAILABLE {
1349                            (EXTENT_UNAVAILABLE, 0)
1350                        } else {
1351                            (
1352                                b.body + b.pay_data + off[i] as u64,
1353                                (off[i + 1] - off[i]) as u64,
1354                            )
1355                        };
1356                        Located { batch: no, row: i as u32, kind, pay_at, pay_len, enc: enc_at(enc, i) }
1357                    }),
1358                )?;
1359            }
1360        }
1361        let out = fold.finish(Keep::Last);
1362        let mut idx = self
1363            .index
1364            .lock()
1365            .map_err(|_| anyhow::anyhow!("exploded index poisoned"))?;
1366        if idx.is_none() {
1367            *idx = Some(out);
1368        }
1369        Ok(())
1370    }
1371
1372    fn find(&self, oid: &[u8]) -> Result<Option<Located>> {
1373        self.index_now()?;
1374        let idx = self
1375            .index
1376            .lock()
1377            .map_err(|_| anyhow::anyhow!("exploded index poisoned"))?;
1378        Ok(idx.as_ref().expect("index_now built it").find(oid))
1379    }
1380
1381    /// The object's kind and bytes, or `None` — *fall back and rebuild*, never
1382    /// *wrong*.
1383    pub fn content(&self, oid: &[u8]) -> Result<Option<(GitObjectKind, Vec<u8>)>> {
1384        // A buffered row has not been written yet, and a read must not miss it:
1385        // an "absent" that is really "not flushed" sends the caller off to
1386        // re-resolve a whole pack for an object we are holding in RAM.
1387        {
1388            let p = self
1389                .pending
1390                .lock()
1391                .map_err(|_| anyhow::anyhow!("exploded pending poisoned"))?;
1392            if let Some(r) = p.rows.iter().rev().find(|r| r.oid == oid) {
1393                let Some(kind) = kind_of(r.code) else {
1394                    // The newest buffered word about this oid retires it.
1395                    self.absent.fetch_add(1, Ordering::Relaxed);
1396                    return Ok(None);
1397                };
1398                self.served.fetch_add(1, Ordering::Relaxed);
1399                return Ok(Some((kind, p.bytes(r).to_vec())));
1400            }
1401        }
1402        let Some(loc) = self.find(oid)? else {
1403            self.absent.fetch_add(1, Ordering::Relaxed);
1404            return Ok(None);
1405        };
1406        // ── the point read IS a point read ──────────────────────────────────
1407        //
1408        // One pread of exactly the payload's bytes, addressed by the extent the
1409        // index carries. The batch-decode below is the FALLBACK — correct for a
1410        // compressed or foreign-layout batch — not the path a healthy table
1411        // takes: taking it per object is what turned a rust-lang/rust
1412        // connectivity walk into hours of one-core batch decoding (2026-08-19).
1413        if loc.pay_at != EXTENT_UNAVAILABLE {
1414            let f = File::open(&self.path)
1415                .with_context(|| format!("opening {}", self.path.display()))?;
1416            let mut buf = vec![0u8; loc.pay_len as usize];
1417            f.read_exact_at(&mut buf, loc.pay_at)
1418                .with_context(|| format!("preading payload at {}", loc.pay_at))?;
1419            self.served.fetch_add(1, Ordering::Relaxed);
1420            self.pread_served.fetch_add(1, Ordering::Relaxed);
1421            // The extent held the row as stored; a compressed row is inflated
1422            // here, from the index's `enc`, without decoding the batch.
1423            return Ok(Some((loc.kind, row_payload(loc.enc, &buf)?)));
1424        }
1425        let batch = self.read_batch(loc.batch)?;
1426        let pay = batch
1427            .column_by_name(COL_PAYLOAD)
1428            .and_then(|c| c.as_any().downcast_ref::<LargeBinaryArray>())
1429            .context("the exploded table has no payload column")?;
1430        let enc = enc_at(enc_column(&batch), loc.row as usize);
1431        self.served.fetch_add(1, Ordering::Relaxed);
1432        Ok(Some((loc.kind, row_payload(enc, pay.value(loc.row as usize))?)))
1433    }
1434
1435    /// Point reads served by the extent `pread` rather than a batch decode —
1436    /// how a test proves the fast path is the one actually taken, instead of
1437    /// timing something.
1438    pub fn pread_served(&self) -> u64 {
1439        self.pread_served.load(Ordering::Relaxed)
1440    }
1441
1442    /// The name this object was first exploded at, if any caller knew one.
1443    /// `None` is "not recorded", never "at the root".
1444    pub fn name(&self, oid: &[u8]) -> Result<Option<(Option<u32>, Option<String>)>> {
1445        {
1446            let p = self
1447                .pending
1448                .lock()
1449                .map_err(|_| anyhow::anyhow!("exploded pending poisoned"))?;
1450            if let Some(r) = p.rows.iter().rev().find(|r| r.oid == oid) {
1451                return match kind_of(r.code) {
1452                    Some(_) => Ok(Some((r.mode, r.path.clone()))),
1453                    None => Ok(None),
1454                };
1455            }
1456        }
1457        let Some(loc) = self.find(oid)? else {
1458            return Ok(None);
1459        };
1460        let batch = self.read_batch(loc.batch)?;
1461        let mode = batch
1462            .column_by_name(COL_MODE)
1463            .and_then(|c| c.as_any().downcast_ref::<UInt32Array>())
1464            .context("the exploded table has no mode column")?;
1465        let path = batch
1466            .column_by_name(COL_PATH)
1467            .and_then(|c| c.as_any().downcast_ref::<StringArray>())
1468            .context("the exploded table has no path column")?;
1469        let i = loc.row as usize;
1470        Ok(Some((
1471            (!mode.is_null(i)).then(|| mode.value(i)),
1472            (!path.is_null(i)).then(|| path.value(i).to_owned()),
1473        )))
1474    }
1475
1476    pub fn has(&self, oid: &[u8]) -> Result<bool> {
1477        {
1478            let p = self
1479                .pending
1480                .lock()
1481                .map_err(|_| anyhow::anyhow!("exploded pending poisoned"))?;
1482            if let Some(r) = p.rows.iter().rev().find(|r| r.oid == oid) {
1483                return Ok(kind_of(r.code).is_some());
1484            }
1485        }
1486        Ok(self.find(oid)?.is_some())
1487    }
1488
1489    /// Every oid of one kind, with its payload. The graph fold's input.
1490    ///
1491    /// Driven by the **index**, not by a scan of the file, because the file
1492    /// holds superseded and retired rows too. A scan that read the file directly
1493    /// is exactly how `gc`'d commits came back after a reopen.
1494    pub fn of_kind(&self, kind: GitObjectKind) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
1495        self.flush()?;
1496        self.index_now()?;
1497        // Grouped by batch so each one is decoded once, in file order.
1498        let mut by_batch: std::collections::BTreeMap<u32, Vec<(u32, Vec<u8>)>> =
1499            std::collections::BTreeMap::new();
1500        {
1501            let idx = self
1502                .index
1503                .lock()
1504                .map_err(|_| anyhow::anyhow!("exploded index poisoned"))?;
1505            for (oid, loc) in idx.as_ref().expect("index_now built it").iter() {
1506                if loc.kind == kind {
1507                    by_batch.entry(loc.batch).or_default().push((loc.row, oid.to_vec()));
1508                }
1509            }
1510        }
1511        let mut out = Vec::new();
1512        for (no, mut wanted) in by_batch {
1513            wanted.sort_unstable_by_key(|(r, _)| *r);
1514            let batch = self.read_batch(no)?;
1515            let pay = batch
1516                .column_by_name(COL_PAYLOAD)
1517                .and_then(|c| c.as_any().downcast_ref::<LargeBinaryArray>())
1518                .context("the exploded table has no payload column")?;
1519            let enc = enc_column(&batch);
1520            for (row, oid) in wanted {
1521                out.push((oid, row_payload(enc_at(enc, row as usize), pay.value(row as usize))?));
1522            }
1523        }
1524        Ok(out)
1525    }
1526
1527    /// Retire every oid `live` rejects, **durably**.
1528    ///
1529    /// The file is append-only, so this appends a [`TOMBSTONE`] row per retired
1530    /// oid rather than deleting anything. The bytes of the dead rows stay until
1531    /// the table is rebuilt — reclaiming them means rewriting up to 17 GB, which
1532    /// is a job with its own proof obligations and not something to smuggle into
1533    /// `gc` — but the *rows* are gone from every reader, including a reopened
1534    /// one.
1535    ///
1536    /// Dropping only from the in-memory index is what a first cut did. Seen RED
1537    /// by `store::tests::a_wholly_dead_pack_does_not_come_back_when_the_store_is_reopened`:
1538    /// **"the graph after gc + reopen holds 551 commits, not the one live one"**.
1539    pub fn retain(&self, live: &dyn Fn(&[u8]) -> bool) -> Result<u64> {
1540        self.flush()?;
1541        self.index_now()?;
1542        let dead: Vec<Vec<u8>> = {
1543            let idx = self
1544                .index
1545                .lock()
1546                .map_err(|_| anyhow::anyhow!("exploded index poisoned"))?;
1547            idx.as_ref()
1548                .expect("index_now built it")
1549                .iter()
1550                .filter(|(oid, _)| !live(oid))
1551                .map(|(oid, _)| oid.to_vec())
1552                .collect()
1553        };
1554        if dead.is_empty() {
1555            return Ok(0);
1556        }
1557        {
1558            let mut p = self
1559                .pending
1560                .lock()
1561                .map_err(|_| anyhow::anyhow!("exploded pending poisoned"))?;
1562            for oid in &dead {
1563                p.rows.push(Pending {
1564                    oid: oid.clone(),
1565                    code: TOMBSTONE,
1566                    mode: None,
1567                    path: None,
1568                    pay: 0..0,
1569                });
1570            }
1571        }
1572        // Written before returning, so a `gc` that says it retired rows has
1573        // already said so on disk.
1574        self.flush()?;
1575        Ok(dead.len() as u64)
1576    }
1577
1578    /// Rows in the table. Answered from batch metadata when no index has been
1579    /// built, so startup does not read a payload.
1580    pub fn rows(&self) -> Result<u64> {
1581        let pending = {
1582            let p = self
1583                .pending
1584                .lock()
1585                .map_err(|_| anyhow::anyhow!("exploded pending poisoned"))?;
1586            p.rows.len() as u64
1587        };
1588        {
1589            let idx = self
1590                .index
1591                .lock()
1592                .map_err(|_| anyhow::anyhow!("exploded index poisoned"))?;
1593            if let Some(idx) = idx.as_ref() {
1594                return Ok(idx.len() as u64 + pending);
1595            }
1596        }
1597        let b = self
1598            .batches
1599            .lock()
1600            .map_err(|_| anyhow::anyhow!("exploded batches poisoned"))?;
1601        Ok(b.iter().map(|x| x.rows as u64).sum::<u64>() + pending)
1602    }
1603
1604    /// Bytes the table occupies — the number redb could not keep anywhere near
1605    /// its payload total.
1606    pub fn disk_bytes(&self) -> u64 {
1607        std::fs::metadata(&self.path).map(|m| m.len()).unwrap_or(0)
1608    }
1609
1610    pub fn note_rederived(&self) {
1611        self.rederived.fetch_add(1, Ordering::Relaxed);
1612    }
1613
1614    /// What this table is configured to keep.
1615    pub fn policy(&self) -> ExplodePolicy {
1616        self.policy
1617    }
1618
1619    /// Objects the policy declined, COUNTED: a table short because of policy and
1620    /// one short because of a fault must not look alike to `adopt_journal`.
1621    pub fn skipped(&self) -> u64 {
1622        self.skipped.load(Ordering::Relaxed)
1623    }
1624
1625    pub fn stats(&self) -> Stats {
1626        Stats {
1627            rows: self.rows().unwrap_or(0),
1628            written: self.written.load(Ordering::Relaxed),
1629            served: self.served.load(Ordering::Relaxed),
1630            rederived: self.rederived.load(Ordering::Relaxed),
1631            absent: self.absent.load(Ordering::Relaxed),
1632        }
1633    }
1634
1635    /// The engine-wide counter type, so no caller can tell the medium apart by
1636    /// its instruments.
1637    pub fn engine_stats(&self) -> crate::exploded::ExplodedStats {
1638        let s = self.stats();
1639        crate::exploded::ExplodedStats {
1640            rows: s.rows,
1641            written: s.written,
1642            served: s.served,
1643            rederived: s.rederived,
1644            absent: s.absent,
1645        }
1646    }
1647}
1648
1649impl crate::exploded::PayloadSink for ExplodedArchive {
1650    /// The policy, asked before the payload exists rather than after — and the
1651    /// `skipped` counter is bumped here, which is the only place the object is
1652    /// ever seen when the answer is no.
1653    fn wants(&self, kind: GitObjectKind) -> bool {
1654        if self.policy.wants(kind) {
1655            return true;
1656        }
1657        self.skipped.fetch_add(1, Ordering::Relaxed);
1658        false
1659    }
1660
1661    fn explode(&self, oid: &[u8], kind: GitObjectKind, payload: &[u8]) -> Result<()> {
1662        ExplodedArchive::explode(self, oid, kind, payload)
1663    }
1664
1665    fn flush(&self) -> Result<()> {
1666        ExplodedArchive::flush(self).map(|_| ())
1667    }
1668}
1669
1670// ════════════════════════════════════════════════════════════════════════════
1671// The policy: what gets exploded at all
1672// ════════════════════════════════════════════════════════════════════════════
1673
1674/// **How much of a pack is resolved into the exploded table.**
1675///
1676/// Three values and not a boolean, because a flat off-switch reintroduces a
1677/// correctness bug this table exists to fix. Commit and tree payloads used to
1678/// live only in RAM, so a **clean** shutdown came back with every pack's
1679/// `indexed` bit legitimately set and an EMPTY graph — MEASURED on oden
1680/// 2026-08-08: 2687 rows and **0 of 551 commits**, `reachable()` returning a
1681/// commit instead of its closure and `gc` seeing an empty live set.
1682///
1683/// MEASURED on `linux.git`: resolved content is 16.8 GB against a 6.4 GB pack,
1684/// and blobs are nearly all of it. So [`Graph`](ExplodePolicy::Graph) buys the
1685/// correctness fix for a small fraction of the disk, and
1686/// [`Full`](ExplodePolicy::Full) — one-lookup content reads, thin-pack bases,
1687/// and the path columns that make the table a filesystem — is the part worth
1688/// charging for.
1689///
1690/// **The default is [`Commits`](ExplodePolicy::Commits) since lane Q
1691/// (2026-08-30), and the change is a measurement.** §14's `indexed` bit is
1692/// derived by comparing this table's row count against the index's, so a table
1693/// that is *deliberately* short is indistinguishable, on disk, from one that was
1694/// dropped — see [`crate::git_ops::Absorber::adopt_journal`], which weakens that
1695/// comparison for every deliberately-short policy and cannot make it exact
1696/// without a durable per-kind count. That weakening is the price of the
1697/// default, it is stated here rather than hidden, and it costs a store that
1698/// really did lose its table one extra fall-back read per object rather than a
1699/// re-ingest.
1700#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1701pub enum ExplodePolicy {
1702    /// Store nothing. Reads re-resolve, and every pack is re-queued on reopen —
1703    /// which is what rebuilds the graph, since nothing it is folded from is on
1704    /// disk.
1705    Off,
1706    /// Commits and trees, both eager. The shape lane Q shipped first and
1707    /// **measured**: on the real `torvalds/linux` mirror the tree payloads
1708    /// alone are **28.24 GB — 3.24× the 8.13 GiB pack** — and folding them into
1709    /// RAM took peak RSS to 50.9 GiB. Kept as a setting, because a small
1710    /// repository that is read constantly wants exactly this; not the default,
1711    /// because an appliance ships with 16 GB.
1712    Graph,
1713    /// **Commits and tags only — the SHIPPED DEFAULT since lane Q
1714    /// (2026-08-30).**
1715    ///
1716    /// The index-only-at-push shape of
1717    /// `ideas/lazy-explode-index-only-at-push.md`, in full. Commits are what
1718    /// `graph` and `reach` fold and what a visibility or pull check reads; a
1719    /// tag is what a clone peels. Both are small and both stay eager, so
1720    /// neither ever stalls. **Trees and blobs** — 90 % of the objects and
1721    /// essentially all of the bytes — are written into
1722    /// [`crate::exploded_cache`]'s budgeted pool by the FIRST reader that
1723    /// inflates one, and evicted from it when the budget says so.
1724    ///
1725    /// Trees became lazy when [`crate::reach::TreeSource`] replaced the
1726    /// resident `HashMap<String, Vec<u8>>` that [`crate::serve`]'s closure walk
1727    /// and the reachability builder both read. That map was the 28.24 GB above.
1728    ///
1729    /// MEASURED, `torvalds/linux`, oden 2026-08-30, /data bytes per pack byte:
1730    ///
1731    /// | | eager (`Full`) | `Graph` | `Commits` |
1732    /// |---|---:|---:|---:|
1733    /// | at ack | 1.05× | 1.05× | 1.05× |
1734    /// | at index-complete | 22.4× (lane P, 78 % done) | 4.58× | see the lane Q rows |
1735    #[default]
1736    Commits,
1737    /// Every object, eagerly, with no bound. What shipped before lane Q and
1738    /// what the 17× measurement is of; kept so a bench can measure the
1739    /// unbounded shape and so a store written under it still opens.
1740    Full,
1741}
1742
1743impl ExplodePolicy {
1744    pub const fn wants(self, kind: GitObjectKind) -> bool {
1745        match self {
1746            ExplodePolicy::Off => false,
1747            ExplodePolicy::Graph => matches!(kind, GitObjectKind::Commit | GitObjectKind::Tree),
1748            ExplodePolicy::Commits => matches!(kind, GitObjectKind::Commit | GitObjectKind::Tag),
1749            ExplodePolicy::Full => true,
1750        }
1751    }
1752    pub const fn as_str(self) -> &'static str {
1753        match self {
1754            ExplodePolicy::Off => "off",
1755            ExplodePolicy::Graph => "graph",
1756            ExplodePolicy::Commits => "commits",
1757            ExplodePolicy::Full => "full",
1758        }
1759    }
1760    /// An unknown value is an ERROR, never a silent fall back to the default: a
1761    /// typo that quietly disables a paid tier is not noticed until a bill is
1762    /// wrong.
1763    pub fn parse(s: &str) -> Result<Self> {
1764        match s.trim().to_ascii_lowercase().as_str() {
1765            "off" | "none" => Ok(ExplodePolicy::Off),
1766            "graph" | "commits-and-trees" => Ok(ExplodePolicy::Graph),
1767            "commits" | "lazy" | "commits-only" => Ok(ExplodePolicy::Commits),
1768            "full" | "all" => Ok(ExplodePolicy::Full),
1769            other => anyhow::bail!(
1770                "unknown explode policy {other:?}; expected off, commits, graph or full"
1771            ),
1772        }
1773    }
1774    /// Reads `ZNIPPY_GIT_EXPLODE` ([`crate::arms::ENV_EXPLODE`]) through the
1775    /// crate's one counted door, once per store open.
1776    pub fn from_env() -> Result<Self> {
1777        match crate::arms::read_env(crate::arms::ENV_EXPLODE) {
1778            Some(v) => Self::parse(&v),
1779            None => Ok(explode_default()),
1780        }
1781    }
1782
1783    /// The discriminant, for the atomic behind [`set_explode_default`]. Private
1784    /// because it is storage and not a contract — the wire spelling is
1785    /// [`ExplodePolicy::as_str`].
1786    const fn as_u8(self) -> u8 {
1787        match self {
1788            ExplodePolicy::Off => 0,
1789            ExplodePolicy::Graph => 1,
1790            ExplodePolicy::Commits => 2,
1791            ExplodePolicy::Full => 3,
1792        }
1793    }
1794
1795    const fn from_u8(v: u8) -> Self {
1796        match v {
1797            0 => ExplodePolicy::Off,
1798            1 => ExplodePolicy::Graph,
1799            3 => ExplodePolicy::Full,
1800            _ => ExplodePolicy::Commits,
1801        }
1802    }
1803}
1804
1805/// What [`ExplodePolicy::from_env`] answers when [`crate::arms::ENV_EXPLODE`] is unset.
1806/// [`ExplodePolicy::default`] unless an embedder said otherwise.
1807static EXPLODE_DEFAULT: std::sync::atomic::AtomicU8 =
1808    std::sync::atomic::AtomicU8::new(ExplodePolicy::Commits.as_u8());
1809
1810/// The current process-wide default — what an unset environment means right now.
1811pub fn explode_default() -> ExplodePolicy {
1812    ExplodePolicy::from_u8(EXPLODE_DEFAULT.load(Ordering::Relaxed))
1813}
1814
1815/// **Set the process-wide default explode policy** for every store opened AFTER this call
1816/// (an explicit [`crate::arms::ENV_EXPLODE`] still wins). The twin of
1817/// [`crate::arms::set_graph_cache_default`], for an embedder that learns its role at runtime
1818/// and cannot set the environment — edition 2024 makes `set_var` unsafe, and gunnar forbids
1819/// `unsafe` — such as gunnar's twin, which holds packs, serves no reads, and must store no
1820/// exploded pool at all ([`ExplodePolicy::Off`]).
1821pub fn set_explode_default(policy: ExplodePolicy) {
1822    EXPLODE_DEFAULT.store(policy.as_u8(), Ordering::Relaxed);
1823}
1824
1825#[cfg(test)]
1826mod tests {
1827    use super::*;
1828    use crate::exploded::PayloadSink as _;
1829
1830    fn tmp(name: &str) -> PathBuf {
1831        let d = std::env::temp_dir().join(format!("exploded-arrow-{}-{name}", std::process::id()));
1832        let _ = std::fs::remove_dir_all(&d);
1833        std::fs::create_dir_all(&d).unwrap();
1834        d.join("objects.exploded")
1835    }
1836
1837    fn oid(n: u8) -> [u8; 20] {
1838        [n; 20]
1839    }
1840
1841    /// ★ ONE TABLE, and the payload is IN the row.
1842    ///
1843    /// Red-first: drop the payload column and nothing below compiles; widen
1844    /// `payload` to `Binary` and this fails on the type it asserts.
1845    #[test]
1846    fn the_table_holds_the_payload_and_a_name_in_one_row() {
1847        let s = exploded_schema(20);
1848        let names: Vec<&str> = s.fields().iter().map(|f| f.name().as_str()).collect();
1849        // `enc` sits before `payload` so the payload data buffer stays the last
1850        // buffer of the batch — `payload_data_offset` depends on that.
1851        assert_eq!(names, vec![COL_OID, COL_TYPE, COL_MODE, COL_PATH, COL_ENC, COL_PAYLOAD]);
1852        assert_eq!(
1853            s.field_with_name(COL_PAYLOAD).unwrap().data_type(),
1854            &DataType::LargeBinary,
1855            "Binary offsets are i32 and would cap one batch at 2 GiB of payload"
1856        );
1857        assert!(
1858            s.field_with_name(COL_PATH).unwrap().is_nullable(),
1859            "a bare pack resolve knows no path; null must be a legal answer"
1860        );
1861    }
1862
1863    /// ★ THE WHOLE POINT: the file stays near the payload total.
1864    ///
1865    /// redb held 16.8 GB of kernel payload in a 204 GB file — 12×. An Arrow IPC
1866    /// stream has no pages to rewrite, so the overhead is framing. Red-first:
1867    /// put this back on a copy-on-write B-tree and it fails.
1868    #[test]
1869    fn the_file_stays_close_to_the_payload_total() {
1870        let t = ExplodedArchive::open_with_policy(&tmp("size"), ExplodePolicy::Full).unwrap();
1871        let payload = vec![7u8; 4096];
1872        let n = 2000u64;
1873        for i in 0..n {
1874            let mut o = [0u8; 20];
1875            o[..8].copy_from_slice(&i.to_le_bytes());
1876            t.explode(&o, GitObjectKind::Blob, &payload).unwrap();
1877        }
1878        t.flush().unwrap();
1879        let payload_total = n * payload.len() as u64;
1880        let on_disk = t.disk_bytes();
1881        assert!(
1882            on_disk < payload_total + payload_total / 4,
1883            "{on_disk} bytes on disk against {payload_total} of payload — the medium is amplifying"
1884        );
1885        assert_eq!(t.rows().unwrap(), n);
1886    }
1887
1888    /// ★ A point read is one small `pread` of the payload's own bytes, and it
1889    /// is the path ACTUALLY taken — counted, not timed.
1890    ///
1891    /// Red-first, measured on a rust-lang/rust push (2026-08-19): without the
1892    /// extent, every `content` decoded its whole 64 MiB batch against a 4-slot
1893    /// cache, and the pre-ack connectivity walk — graph order, so effectively
1894    /// random across ~574 batches — decoded 6.7 GB/s of page cache to serve
1895    /// ~98 objects/s, one core pinned for hours. Both index-building paths are
1896    /// exercised: the in-process flush extension AND `index_now` after a
1897    /// reopen, against multi-batch tables with varied payload sizes, so a
1898    /// mis-computed extent returns the WRONG BYTES here rather than in a
1899    /// customer's clone.
1900    #[test]
1901    fn a_point_read_preads_the_exact_payload_without_decoding_the_batch() {
1902        let path = tmp("pread");
1903        let pay = |b: u8, i: u8| vec![b ^ i; 100 + i as usize * 7];
1904        let t = ExplodedArchive::open_with_policy(&path, ExplodePolicy::Full).unwrap();
1905        // Batch 0, then force the index to exist so batch 1 goes through the
1906        // flush EXTENSION path rather than a later index_now.
1907        for i in 0..40u8 {
1908            t.explode(&[i; 20], GitObjectKind::Blob, &pay(0, i)).unwrap();
1909        }
1910        t.flush().unwrap();
1911        assert!(t.content(&[0u8; 20]).unwrap().is_some(), "build the index");
1912        for i in 40..80u8 {
1913            t.explode(&[i; 20], GitObjectKind::Blob, &pay(1, i)).unwrap();
1914        }
1915        t.flush().unwrap();
1916
1917        let before = t.pread_served();
1918        for i in 0..80u8 {
1919            let (kind, got) = t.content(&[i; 20]).unwrap().expect("every oid is live");
1920            assert_eq!(kind, GitObjectKind::Blob);
1921            let want = if i < 40 { pay(0, i) } else { pay(1, i) };
1922            assert_eq!(got, want, "oid {i}: the pread returned some OTHER bytes");
1923        }
1924        assert_eq!(
1925            t.pread_served() - before,
1926            80,
1927            "a read fell back to the batch decode — the extent was not computed"
1928        );
1929
1930        // Reopen: the framing walk + index_now must reproduce the same extents
1931        // from the file alone.
1932        drop(t);
1933        let t = ExplodedArchive::open_with_policy(&path, ExplodePolicy::Full).unwrap();
1934        for i in 0..80u8 {
1935            let (_, got) = t.content(&[i; 20]).unwrap().expect("survives a reopen");
1936            let want = if i < 40 { pay(0, i) } else { pay(1, i) };
1937            assert_eq!(got, want, "oid {i} after reopen");
1938        }
1939        assert_eq!(t.pread_served(), 80, "the reopened table must pread too");
1940    }
1941
1942    /// **Lever 3: a compressible row is stored compressed and read back whole, on
1943    /// every read path.** Three rows: a 4 KiB compressible one (stored zlib), a
1944    /// row under [`MIN_ROW_COMPRESS`] (stored raw), and a 4 KiB incompressible
1945    /// one (zlib cannot get it under the keep threshold — stored raw). Asserted
1946    /// on the `enc` column read straight off the file, on the file being smaller
1947    /// than the payloads, and on `content` (the pread fast path — `pread_served`
1948    /// moves) and `of_kind` (the batch-decode path) both handing back the
1949    /// original bytes.
1950    ///
1951    /// Seen RED by returning `bytes.to_vec()` for `ENC_ZLIB` in `row_payload`:
1952    /// "the pread path returned the stored bytes, not the payload" — 4096 bytes
1953    /// expected, ~60 came back. Restored.
1954    #[test]
1955    fn a_compressible_row_is_stored_compressed_and_read_back_whole() {
1956        let path = tmp("lever3");
1957        let t = ExplodedArchive::open_with_policy(&path, ExplodePolicy::Full).unwrap();
1958        let big: Vec<u8> = b"tree 0123456789abcdef0123456789abcdef01234567\nparent x\n"
1959            .iter()
1960            .cycle()
1961            .take(4096)
1962            .copied()
1963            .collect();
1964        let tiny = b"tree x\n".to_vec();
1965        let noise: Vec<u8> = {
1966            let mut x: u32 = 0x1234_5678;
1967            (0..4096)
1968                .map(|_| {
1969                    x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1970                    (x >> 24) as u8
1971                })
1972                .collect()
1973        };
1974        assert!(tiny.len() < MIN_ROW_COMPRESS && big.len() >= MIN_ROW_COMPRESS);
1975        t.explode(&oid(1), GitObjectKind::Commit, &big).unwrap();
1976        t.explode(&oid(2), GitObjectKind::Commit, &tiny).unwrap();
1977        t.explode(&oid(3), GitObjectKind::Blob, &noise).unwrap();
1978        t.flush().unwrap();
1979
1980        // The file holds the compressed row: smaller than the payloads it
1981        // carries, which a raw pool never is.
1982        let file = std::fs::metadata(&path).unwrap().len() as usize;
1983        assert!(
1984            file < big.len() + tiny.len() + noise.len(),
1985            "the pool did not compress: {file} B for {} B of payload",
1986            big.len() + tiny.len() + noise.len()
1987        );
1988
1989        // The `enc` column, read off the file as the plain IPC stream it is.
1990        let rd = znippy_common::arrow::ipc::reader::StreamReader::try_new(
1991            std::fs::File::open(&path).unwrap(),
1992            None,
1993        )
1994        .unwrap();
1995        let mut encs = std::collections::BTreeMap::new();
1996        for b in rd {
1997            let b = b.unwrap();
1998            let oids = b
1999                .column_by_name(COL_OID)
2000                .and_then(|c| c.as_any().downcast_ref::<FixedSizeBinaryArray>())
2001                .unwrap();
2002            let enc = enc_column(&b).expect("a v2 pool has the enc column");
2003            for i in 0..b.num_rows() {
2004                encs.insert(oids.value(i)[0], enc.value(i));
2005            }
2006        }
2007        assert_eq!(encs[&1], ENC_ZLIB, "the compressible row is stored compressed");
2008        assert_eq!(encs[&2], ENC_RAW, "a row under the floor stays raw");
2009        assert_eq!(encs[&3], ENC_RAW, "an incompressible row stays raw");
2010
2011        // The pread fast path inflates.
2012        let before = t.pread_served();
2013        let (k, got) = t.content(&oid(1)).unwrap().unwrap();
2014        assert_eq!(k, GitObjectKind::Commit);
2015        assert_eq!(got, big, "the pread path returned the stored bytes, not the payload");
2016        assert_eq!(t.content(&oid(2)).unwrap().unwrap().1, tiny);
2017        assert_eq!(t.content(&oid(3)).unwrap().unwrap().1, noise);
2018        assert_eq!(t.pread_served() - before, 3, "all three went through the extent pread");
2019
2020        // The batch-decode path (`of_kind`) inflates too.
2021        let commits = t.of_kind(GitObjectKind::Commit).unwrap();
2022        let by: std::collections::HashMap<u8, Vec<u8>> =
2023            commits.into_iter().map(|(o, p)| (o[0], p)).collect();
2024        assert_eq!(by[&1], big, "of_kind returned the stored bytes, not the payload");
2025        assert_eq!(by[&2], tiny);
2026
2027        // And across a reopen, where the index is rebuilt from the file.
2028        drop(t);
2029        let t = ExplodedArchive::open_with_policy(&path, ExplodePolicy::Full).unwrap();
2030        assert_eq!(t.content(&oid(1)).unwrap().unwrap().1, big, "after reopen");
2031        assert_eq!(t.content(&oid(3)).unwrap().unwrap().1, noise, "after reopen");
2032    }
2033
2034    /// **A v1 pool — no `enc` column — still reads, every row raw.** Written by
2035    /// hand in v1's shape (five columns, the same framing `flush` uses), then
2036    /// opened by this build: the extent is computed (12 buffers is accepted),
2037    /// `enc` is absent and read as [`ENC_RAW`], and the bytes come back as
2038    /// written. This is the promise that lets an existing appliance's pools
2039    /// open unchanged.
2040    ///
2041    /// Seen RED by making `payload_data_offset` accept only 14 buffers: the
2042    /// pread count stayed 0 ("a v1 pool must still take the extent fast path").
2043    /// Restored.
2044    #[test]
2045    fn a_v1_pool_without_the_enc_column_reads_raw() {
2046        use znippy_common::arrow::array::{
2047            FixedSizeBinaryBuilder, LargeBinaryBuilder, StringBuilder, UInt32Builder,
2048        };
2049        use znippy_common::arrow::ipc::writer::{write_message, DictionaryTracker, IpcDataGenerator, IpcWriteOptions};
2050        let path = tmp("v1pool");
2051        let v1_schema: SchemaRef = Arc::new(Schema::new(vec![
2052            Field::new(COL_OID, DataType::FixedSizeBinary(20), false),
2053            Field::new(COL_TYPE, DataType::UInt8, false),
2054            Field::new(COL_MODE, DataType::UInt32, true),
2055            Field::new(COL_PATH, DataType::Utf8, true),
2056            Field::new(COL_PAYLOAD, DataType::LargeBinary, false),
2057        ]));
2058        let payloads: Vec<Vec<u8>> = (1..=5u8)
2059            .map(|i| b"tree abc\n".iter().cycle().take(300 + i as usize * 100).copied().collect())
2060            .collect();
2061        let mut oid_b = FixedSizeBinaryBuilder::with_capacity(5, 20);
2062        let mut kind_b = UInt8Builder::with_capacity(5);
2063        let mut mode_b = UInt32Builder::with_capacity(5);
2064        let mut path_b = StringBuilder::new();
2065        let mut pay_b = LargeBinaryBuilder::new();
2066        for (i, p) in payloads.iter().enumerate() {
2067            oid_b.append_value(oid(i as u8 + 1)).unwrap();
2068            kind_b.append_value(kind_code(GitObjectKind::Commit));
2069            mode_b.append_null();
2070            path_b.append_null();
2071            pay_b.append_value(p);
2072        }
2073        let batch = RecordBatch::try_new(
2074            v1_schema.clone(),
2075            vec![
2076                Arc::new(oid_b.finish()),
2077                Arc::new(kind_b.finish()),
2078                Arc::new(mode_b.finish()),
2079                Arc::new(path_b.finish()),
2080                Arc::new(pay_b.finish()),
2081            ],
2082        )
2083        .unwrap();
2084        let opts = IpcWriteOptions::default();
2085        let ipc = IpcDataGenerator::default();
2086        let mut tracker = DictionaryTracker::new(false);
2087        let mut file = Vec::new();
2088        {
2089            let enc = ipc.schema_to_bytes_with_dictionary_tracker(&v1_schema, &mut tracker, &opts);
2090            let mut msg = Vec::new();
2091            write_message(&mut msg, enc, &opts).unwrap();
2092            file.extend_from_slice(&msg);
2093        }
2094        {
2095            let (_, enc) = ipc.encode(&batch, &mut tracker, &opts, &mut Default::default()).unwrap();
2096            let mut msg = Vec::new();
2097            write_message(&mut msg, enc, &opts).unwrap();
2098            file.extend_from_slice(&msg);
2099        }
2100        std::fs::write(&path, &file).unwrap();
2101
2102        let t = ExplodedArchive::open_with_policy(&path, ExplodePolicy::Full).unwrap();
2103        for (i, p) in payloads.iter().enumerate() {
2104            let (k, got) = t.content(&oid(i as u8 + 1)).unwrap().expect("a v1 row is live");
2105            assert_eq!(k, GitObjectKind::Commit);
2106            assert_eq!(&got, p, "v1 row {} must read back raw", i + 1);
2107        }
2108        assert_eq!(t.pread_served(), 5, "a v1 pool must still take the extent fast path");
2109        // And it keeps working when this build appends to it: the appended
2110        // batch must be v1-shaped, because the stream's one schema message is
2111        // v1 — a six-column batch under it would not decode. Proven by reading
2112        // every batch back through Arrow's own stream reader afterwards.
2113        t.explode(&oid(9), GitObjectKind::Commit, &payloads[0]).unwrap();
2114        t.flush().unwrap();
2115        assert_eq!(t.content(&oid(9)).unwrap().unwrap().1, payloads[0]);
2116        assert_eq!(t.content(&oid(1)).unwrap().unwrap().1, payloads[0]);
2117        let rd = znippy_common::arrow::ipc::reader::StreamReader::try_new(
2118            std::fs::File::open(&path).unwrap(),
2119            None,
2120        )
2121        .unwrap();
2122        let mut rows = 0;
2123        for b in rd {
2124            let b = b.expect("every batch in a v1 file decodes under the v1 schema");
2125            assert!(enc_column(&b).is_none(), "a batch appended to a v1 pool must be v1-shaped");
2126            rows += b.num_rows();
2127        }
2128        assert_eq!(rows, 6, "five v1 rows and the one appended");
2129    }
2130
2131    #[test]
2132    fn a_payload_round_trips_through_the_table() {
2133        let t = ExplodedArchive::open_with_policy(&tmp("rt"), ExplodePolicy::Full).unwrap();
2134        t.explode(&oid(1), GitObjectKind::Commit, b"tree deadbeef\n")
2135            .unwrap();
2136        t.explode(&oid(2), GitObjectKind::Blob, b"hello world")
2137            .unwrap();
2138        t.flush().unwrap();
2139        assert_eq!(
2140            t.content(&oid(2)).unwrap().unwrap(),
2141            (GitObjectKind::Blob, b"hello world".to_vec())
2142        );
2143        assert_eq!(
2144            t.content(&oid(1)).unwrap().unwrap(),
2145            (GitObjectKind::Commit, b"tree deadbeef\n".to_vec())
2146        );
2147        assert!(t.has(&oid(1)).unwrap());
2148        assert!(!t.has(&oid(9)).unwrap());
2149    }
2150
2151    /// The row is a FILE: mode and path survive the round trip.
2152    #[test]
2153    fn a_row_can_carry_the_name_it_was_seen_at() {
2154        let t = ExplodedArchive::open_with_policy(&tmp("named"), ExplodePolicy::Full).unwrap();
2155        t.explode_at(
2156            &oid(1),
2157            GitObjectKind::Blob,
2158            Some(0o100755),
2159            Some("scripts/build.sh"),
2160            b"#!/bin/sh\n",
2161        )
2162        .unwrap();
2163        t.explode(&oid(2), GitObjectKind::Blob, b"anonymous").unwrap();
2164        t.flush().unwrap();
2165        assert_eq!(
2166            t.name(&oid(1)).unwrap().unwrap(),
2167            (Some(0o100755), Some("scripts/build.sh".to_owned()))
2168        );
2169        assert_eq!(
2170            t.name(&oid(2)).unwrap().unwrap(),
2171            (None, None),
2172            "null is 'not recorded', and must not read as a real name"
2173        );
2174    }
2175
2176    /// Reopening finds every row without reading a payload, and appends continue
2177    /// the SAME stream rather than starting a second one.
2178    #[test]
2179    fn the_table_survives_a_reopen_and_keeps_appending() {
2180        let p = tmp("reopen");
2181        {
2182            let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2183            t.explode(&oid(5), GitObjectKind::Tree, b"100644 f\0").unwrap();
2184            t.flush().unwrap();
2185        }
2186        let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2187        assert_eq!(t.rows().unwrap(), 1, "row count comes from batch metadata");
2188        t.explode(&oid(6), GitObjectKind::Blob, b"second session").unwrap();
2189        t.flush().unwrap();
2190        assert_eq!(t.rows().unwrap(), 2);
2191        assert_eq!(
2192            t.content(&oid(5)).unwrap().unwrap(),
2193            (GitObjectKind::Tree, b"100644 f\0".to_vec())
2194        );
2195        assert_eq!(
2196            t.content(&oid(6)).unwrap().unwrap(),
2197            (GitObjectKind::Blob, b"second session".to_vec())
2198        );
2199
2200        // And a third open sees both — one schema message, two batches.
2201        let again = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2202        assert_eq!(again.rows().unwrap(), 2);
2203        assert_eq!(again.batches.lock().unwrap().len(), 2);
2204    }
2205
2206    /// A read must not miss a row that is buffered but not yet written — an
2207    /// "absent" that is really "not flushed" sends the caller off to re-resolve
2208    /// a whole pack for an object we are holding.
2209    #[test]
2210    fn an_unflushed_row_is_still_served() {
2211        let t = ExplodedArchive::open_with_policy(&tmp("unflushed"), ExplodePolicy::Full).unwrap();
2212        t.explode(&oid(4), GitObjectKind::Commit, b"buffered").unwrap();
2213        assert_eq!(
2214            t.content(&oid(4)).unwrap().unwrap(),
2215            (GitObjectKind::Commit, b"buffered".to_vec())
2216        );
2217        assert!(t.has(&oid(4)).unwrap());
2218    }
2219
2220    #[test]
2221    fn an_absent_oid_is_none_and_counted() {
2222        let t = ExplodedArchive::open_with_policy(&tmp("absent"), ExplodePolicy::Full).unwrap();
2223        assert!(t.content(&oid(3)).unwrap().is_none());
2224        assert_eq!(t.stats().absent, 1);
2225        assert_eq!(t.stats().served, 0);
2226    }
2227
2228    #[test]
2229    fn of_kind_selects_by_kind() {
2230        let t = ExplodedArchive::open_with_policy(&tmp("kind"), ExplodePolicy::Full).unwrap();
2231        t.explode(&oid(1), GitObjectKind::Commit, b"c1").unwrap();
2232        t.explode(&oid(2), GitObjectKind::Blob, b"bb").unwrap();
2233        t.explode(&oid(3), GitObjectKind::Commit, b"c2").unwrap();
2234        let commits = t.of_kind(GitObjectKind::Commit).unwrap();
2235        assert_eq!(commits.len(), 2);
2236        assert!(commits.iter().all(|(_, p)| p[0] == b'c'));
2237    }
2238
2239    /// ★ A RETIRED ROW STAYS RETIRED ACROSS A REOPEN.
2240    ///
2241    /// The file is append-only, so `retain` writes a [`TOMBSTONE`] rather than
2242    /// deleting. Seen RED with an index-only `retain`: the reopen below rebuilds
2243    /// from the file and brought the dead row back — which is
2244    /// `store::tests::a_wholly_dead_pack_does_not_come_back_when_the_store_is_reopened`
2245    /// failing with "551 commits, not the one live one", reached from here in
2246    /// three lines instead of a whole gc.
2247    #[test]
2248    fn retain_drops_only_what_is_dead_and_the_drop_survives_a_reopen() {
2249        let p = tmp("retain");
2250        {
2251            let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2252            t.explode(&oid(1), GitObjectKind::Blob, b"a").unwrap();
2253            t.explode(&oid(2), GitObjectKind::Blob, b"b").unwrap();
2254            t.flush().unwrap();
2255            assert_eq!(t.retain(&|o: &[u8]| o[0] == 1).unwrap(), 1);
2256            assert!(t.has(&oid(1)).unwrap());
2257            assert!(!t.has(&oid(2)).unwrap());
2258            assert_eq!(
2259                t.of_kind(GitObjectKind::Blob).unwrap().len(),
2260                1,
2261                "a scan must not resurrect what retain dropped"
2262            );
2263        }
2264        let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2265        assert!(t.has(&oid(1)).unwrap(), "the live row did not survive");
2266        assert!(
2267            !t.has(&oid(2)).unwrap(),
2268            "a reopen resurrected a retired row — the tombstone is not durable"
2269        );
2270        assert!(t.content(&oid(2)).unwrap().is_none());
2271        assert_eq!(t.of_kind(GitObjectKind::Blob).unwrap().len(), 1);
2272    }
2273
2274    /// sha256 keys are not truncated to sha1 width, and a table refuses a width
2275    /// it cannot hold.
2276    #[test]
2277    fn a_sha256_oid_keeps_all_thirty_two_bytes() {
2278        let p = tmp("sha256");
2279        let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2280        let o = [3u8; 32];
2281        t.explode(&o, GitObjectKind::Tree, b"t").unwrap();
2282        t.flush().unwrap();
2283        assert!(t.has(&o).unwrap());
2284        assert_eq!(t.content(&o).unwrap().unwrap().1, b"t");
2285
2286        t.explode(&oid(1), GitObjectKind::Blob, b"narrow").unwrap();
2287        let err = t.flush().expect_err("a 20-byte oid cannot join a 32-byte table");
2288        assert!(format!("{err}").contains("32-byte oids"), "{err}");
2289    }
2290
2291    /// A torn tail is truncated away rather than left mid-stream, where every
2292    /// later batch would be unreachable.
2293    #[test]
2294    fn a_torn_tail_is_dropped_and_the_table_keeps_working() {
2295        let p = tmp("torn");
2296        {
2297            let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2298            t.explode(&oid(1), GitObjectKind::Blob, b"complete").unwrap();
2299            t.flush().unwrap();
2300        }
2301        // Half a message, as a killed process leaves.
2302        {
2303            let mut f = OpenOptions::new().append(true).open(&p).unwrap();
2304            f.write_all(&[0xFF, 0xFF, 0xFF, 0xFF, 0x40, 0x00, 0x00, 0x00, 1, 2, 3])
2305                .unwrap();
2306        }
2307        let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2308        assert_eq!(t.rows().unwrap(), 1, "the torn message contributes nothing");
2309        t.explode(&oid(2), GitObjectKind::Blob, b"after").unwrap();
2310        t.flush().unwrap();
2311        assert_eq!(t.rows().unwrap(), 2);
2312        assert_eq!(
2313            t.content(&oid(2)).unwrap().unwrap().1,
2314            b"after".to_vec(),
2315            "the append landed at the last good boundary, not after the garbage"
2316        );
2317    }
2318
2319    #[test]
2320    fn graph_keeps_commits_and_trees_and_drops_blobs() {
2321        let p = ExplodePolicy::Graph;
2322        assert!(p.wants(GitObjectKind::Commit));
2323        assert!(p.wants(GitObjectKind::Tree));
2324        assert!(!p.wants(GitObjectKind::Blob));
2325        assert!(!ExplodePolicy::Off.wants(GitObjectKind::Commit));
2326        assert!(ExplodePolicy::Full.wants(GitObjectKind::Blob));
2327        assert!(ExplodePolicy::Commits.wants(GitObjectKind::Commit));
2328        assert!(!ExplodePolicy::Commits.wants(GitObjectKind::Tree));
2329        assert_eq!(
2330            ExplodePolicy::default(),
2331            ExplodePolicy::Commits,
2332            "the shipped default is the lane Q one: commits and tags eager, trees \
2333             and blobs lazy and budgeted. `Full` is what put 22.4x the pack into \
2334             /data on the rig; `Graph` is what put 28.24 GB of tree payloads there \
2335             and 50.9 GiB of them in RAM."
2336        );
2337    }
2338
2339    /// ★ THE SETTING: a declined object is not stored, and is COUNTED — so a
2340    /// table short by policy and one short by fault do not look alike.
2341    #[test]
2342    fn a_declined_object_is_not_stored_and_is_counted() {
2343        let t = ExplodedArchive::open_with_policy(&tmp("policy"), ExplodePolicy::Graph).unwrap();
2344        t.explode(&oid(1), GitObjectKind::Commit, b"c").unwrap();
2345        t.explode(&oid(2), GitObjectKind::Blob, b"bbbb").unwrap();
2346        t.flush().unwrap();
2347        assert!(t.has(&oid(1)).unwrap());
2348        assert!(!t.has(&oid(2)).unwrap());
2349        assert_eq!(t.skipped(), 1);
2350        assert_eq!(t.rows().unwrap(), 1);
2351    }
2352
2353    /// `Off` writes no file at all — the whole point of the free tier.
2354    #[test]
2355    fn off_stores_nothing_and_leaves_no_file() {
2356        let p = tmp("off");
2357        let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Off).unwrap();
2358        t.explode(&oid(1), GitObjectKind::Commit, b"c").unwrap();
2359        t.explode(&oid(2), GitObjectKind::Blob, b"b").unwrap();
2360        assert_eq!(t.flush().unwrap(), 0);
2361        assert_eq!(t.rows().unwrap(), 0);
2362        assert_eq!(t.skipped(), 2);
2363        assert!(!p.exists(), "a disabled table must not create a file");
2364    }
2365
2366    // ════════════════════════════════════════════════════════════════════════
2367    // The stree in front of the lookup
2368    // ════════════════════════════════════════════════════════════════════════
2369
2370    /// `n` oids in `groups` of `per` that share their first EIGHT bytes and
2371    /// differ only after them — the collision is CONSTRUCTED, never hoped for.
2372    ///
2373    /// The prefixes deliberately straddle `0x80`: half the oids in a real repo
2374    /// start there, and they are the half a non-order-preserving key would sort
2375    /// onto the wrong side of the keyspace.
2376    fn colliding_oids(groups: usize, per: usize) -> Vec<[u8; 20]> {
2377        let mut out = Vec::with_capacity(groups * per);
2378        for g in 0..groups {
2379            let mut z = (g as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
2380            z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
2381            z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
2382            let prefix = (z ^ (z >> 31)).to_be_bytes();
2383            for k in 0..per {
2384                let mut o = [0u8; 20];
2385                o[..8].copy_from_slice(&prefix);
2386                o[8] = k as u8;
2387                o[9..13].copy_from_slice(&(g as u32).to_be_bytes());
2388                out.push(o);
2389            }
2390        }
2391        out
2392    }
2393
2394    /// ★ THE STREE RETURNS THE ROW THE BINARY SEARCH RETURNED — including on
2395    /// 8-byte prefix collisions, of which this table has 1000.
2396    ///
2397    /// Three answers are compared for every oid: the `stree` probe, the
2398    /// `binary_search` over the identical oid array that this file shipped with,
2399    /// and the **applied output** — the payload `content` hands back, which is
2400    /// unique per oid, so a wrong row is a wrong payload and not a passing
2401    /// assertion about a `Located` nobody read.
2402    ///
2403    /// Seen RED by deleting the full-oid comparison from `OidTree::verify` (i.e.
2404    /// `.find(|&i| self.oid_at(i) == oid)` → `.next()`, the "stree already found
2405    /// it" mistake): **"the stree and the binary search disagree at
2406    /// 0000000000000000010000000000000000000000: Some(Located { batch: 0, row: 0,
2407    /// kind: Blob }) vs Some(Located { batch: 0, row: 1, kind: Blob })"** — the
2408    /// probe was handed the row of the prefix-mate stored one slot earlier.
2409    #[test]
2410    fn the_stree_agrees_with_the_binary_search_it_replaced_on_colliding_prefixes() {
2411        let t = ExplodedArchive::open_with_policy(&tmp("stree-agree"), ExplodePolicy::Full).unwrap();
2412        let oids = colliding_oids(1000, 4);
2413        for (i, o) in oids.iter().enumerate() {
2414            t.explode(o, GitObjectKind::Blob, format!("payload-{i}").as_bytes())
2415                .unwrap();
2416        }
2417        t.flush().unwrap();
2418        // Force the index, then reach into it: the two finders must sit over the
2419        // SAME arrays, or this compares two indexes rather than two finders.
2420        t.index_now().unwrap();
2421        let idx = t.index.lock().unwrap();
2422        let tree = idx.as_ref().expect("index_now built it");
2423        assert_eq!(tree.len(), oids.len());
2424
2425        // The premise: the collisions are real in the built tree.
2426        let mut colliding_runs = 0usize;
2427        for o in &oids {
2428            let run = tree.candidate_run(key_for_oid(o));
2429            assert_eq!(
2430                run.len(),
2431                4,
2432                "expected a 4-entry candidate run for {}, got {run:?} — the collision \
2433                 the rest of this test rests on is not there",
2434                hex::encode(o)
2435            );
2436            colliding_runs += 1;
2437        }
2438        assert_eq!(colliding_runs, oids.len());
2439        // And the sign boundary is really crossed, or the key's top-bit flip is
2440        // untested by this corpus.
2441        assert!(
2442            oids.iter().any(|o| o[0] >= 0x80) && oids.iter().any(|o| o[0] < 0x80),
2443            "premise: the prefixes must straddle 0x80"
2444        );
2445
2446        for o in &oids {
2447            assert_eq!(
2448                tree.find(o),
2449                tree.find_by_binary_search(o),
2450                "the stree and the binary search disagree at {}: {:?} vs {:?}",
2451                hex::encode(o),
2452                tree.find(o),
2453                tree.find_by_binary_search(o)
2454            );
2455            assert!(tree.find(o).is_some(), "{} vanished", hex::encode(o));
2456        }
2457        // An oid on a colliding prefix that was never stored must MISS, in both
2458        // finders — this is the query a verify-less probe answers with somebody
2459        // else's row.
2460        for o in oids.iter().step_by(4) {
2461            let mut absent = *o;
2462            absent[8] = 0xff;
2463            assert_eq!(tree.find(&absent), None, "{} was never stored", hex::encode(absent));
2464            assert_eq!(tree.find_by_binary_search(&absent), None);
2465        }
2466        drop(idx);
2467
2468        // Applied output: each oid's own payload, not its prefix-mate's.
2469        for (i, o) in oids.iter().enumerate() {
2470            assert_eq!(
2471                t.content(o).unwrap().unwrap().1,
2472                format!("payload-{i}").into_bytes(),
2473                "{} came back with another object's bytes",
2474                hex::encode(o)
2475            );
2476        }
2477    }
2478
2479    /// ★ A TOMBSTONE STILL RETIRES AN OID WITH THE STREE IN FRONT — and its
2480    /// prefix-mates do not go with it, nor stand in for it.
2481    ///
2482    /// Two failure modes live here and both return a wrong answer rather than an
2483    /// error: a fold that keeps the *first* sighting rather than the last leaves
2484    /// the retired oid resolvable, and a probe that trusts the 8-byte key answers
2485    /// the retired oid with the row of the live oid it collides with.
2486    ///
2487    /// Seen RED three times:
2488    ///
2489    /// * `Keep::Last` → `Keep::First` in `index_now`: **"a reopen resurrected a
2490    ///   retired oid: 0000000000000000000000000000000000000000"**. The same break
2491    ///   also reds the older, coarser
2492    ///   `retain_drops_only_what_is_dead_and_the_drop_survives_a_reopen`.
2493    /// * the full-oid comparison dropped from `OidTree::verify`:
2494    ///   **"0000000000000000000000000000000000000000 was retired"** — the dead
2495    ///   oid answered `has` with its live prefix-mate's row, in-process, before
2496    ///   any reopen.
2497    /// * the incremental fold in `flush` no longer filtering the retired set
2498    ///   (`if !retired.contains(oid)` → `if true`): the same message, from the
2499    ///   live process rather than from a reopen.
2500    #[test]
2501    fn a_tombstoned_oid_stays_absent_when_a_live_oid_shares_its_prefix() {
2502        let p = tmp("stree-tomb");
2503        // Four oids per prefix: one is retired, three stay.
2504        let oids = colliding_oids(64, 4);
2505        let dead: Vec<[u8; 20]> = oids.iter().copied().step_by(4).collect();
2506        {
2507            let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2508            for (i, o) in oids.iter().enumerate() {
2509                t.explode(o, GitObjectKind::Blob, format!("live-{i}").as_bytes())
2510                    .unwrap();
2511            }
2512            t.flush().unwrap();
2513            let retired = t.retain(&|o: &[u8]| !dead.iter().any(|d| d == o)).unwrap();
2514            assert_eq!(retired, dead.len() as u64);
2515            for d in &dead {
2516                assert!(!t.has(d).unwrap(), "{} was retired", hex::encode(d));
2517                assert!(
2518                    t.content(d).unwrap().is_none(),
2519                    "the retired oid {} was answered with a prefix-mate's row",
2520                    hex::encode(d)
2521                );
2522            }
2523            for (i, o) in oids.iter().enumerate() {
2524                if i % 4 == 0 {
2525                    continue;
2526                }
2527                assert_eq!(
2528                    t.content(o).unwrap().unwrap().1,
2529                    format!("live-{i}").into_bytes(),
2530                    "{} is alive and must still answer with its OWN bytes",
2531                    hex::encode(o)
2532                );
2533            }
2534        }
2535        // ★ And a reopen — which rebuilds the tree from the file, tombstones and
2536        // all — finds every live row and none of the dead.
2537        let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2538        for (i, o) in oids.iter().enumerate() {
2539            if i % 4 == 0 {
2540                assert!(
2541                    !t.has(o).unwrap(),
2542                    "a reopen resurrected a retired oid: {}",
2543                    hex::encode(o)
2544                );
2545            } else {
2546                assert_eq!(
2547                    t.content(o).unwrap().unwrap().1,
2548                    format!("live-{i}").into_bytes(),
2549                    "a reopen lost or misrouted the live oid {}",
2550                    hex::encode(o)
2551                );
2552            }
2553        }
2554        assert_eq!(
2555            t.of_kind(GitObjectKind::Blob).unwrap().len(),
2556            oids.len() - dead.len()
2557        );
2558        // Only now — `rows()` answers from batch metadata until an index exists,
2559        // and the file still holds the retired rows and their tombstones. This
2560        // assertion measured 320 against 192 when it was made before the reads
2561        // above, which is the documented behaviour of `rows()` and not the
2562        // tombstone leaking.
2563        assert_eq!(t.rows().unwrap(), (oids.len() - dead.len()) as u64);
2564    }
2565
2566    /// The incremental extension in `flush` and the from-scratch rebuild in
2567    /// `index_now` must land on the same tree — one of them runs while a push is
2568    /// hot and the other after a restart, and a difference between them is a
2569    /// bug that only appears to the second process.
2570    ///
2571    /// Seen RED twice, once from each side, and the two reds are mirror images —
2572    /// which is what tells you the test compares the folds rather than one of
2573    /// them against itself:
2574    ///
2575    /// * incremental path drops the `retired` filter over the entries it carries
2576    ///   forward (`if !retired.contains(oid)` → `if true`): **"the two folds kept
2577    ///   a different number of oids: left: 150, right: 200"** — the live index
2578    ///   kept the 50 it had been told to retire.
2579    /// * `Keep::Last` → `Keep::First` in `index_now`: **"left: 200, right: 150"**
2580    ///   — the rebuild kept them instead.
2581    #[test]
2582    fn the_incremental_index_and_a_rebuilt_one_agree() {
2583        let p = tmp("stree-incr");
2584        let oids = colliding_oids(50, 4);
2585        let t = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2586        // Build the index FIRST, so every flush below takes the incremental path.
2587        t.index_now().unwrap();
2588        for (i, o) in oids.iter().enumerate() {
2589            t.explode(o, GitObjectKind::Blob, format!("v-{i}").as_bytes())
2590                .unwrap();
2591            if i % 37 == 0 {
2592                t.flush().unwrap();
2593            }
2594        }
2595        t.flush().unwrap();
2596        t.retain(&|o: &[u8]| o[8] != 3).unwrap();
2597        let live: Vec<(Vec<u8>, Vec<u8>)> = {
2598            let idx = t.index.lock().unwrap();
2599            idx.as_ref()
2600                .unwrap()
2601                .iter()
2602                .map(|(o, l)| (o.to_vec(), vec![l.batch as u8, l.row as u8]))
2603                .collect()
2604        };
2605        drop(t);
2606
2607        let again = ExplodedArchive::open_with_policy(&p, ExplodePolicy::Full).unwrap();
2608        again.index_now().unwrap();
2609        let rebuilt = again.index.lock().unwrap();
2610        let rebuilt = rebuilt.as_ref().unwrap();
2611        assert_eq!(rebuilt.len(), live.len(), "the two folds kept a different number of oids");
2612        for (o, _) in &live {
2613            assert!(
2614                rebuilt.find(o).is_some(),
2615                "the live process and a reopen disagree about {}: Some(..) vs None",
2616                hex::encode(o)
2617            );
2618        }
2619        for o in oids.iter().filter(|o| o[8] == 3) {
2620            assert!(rebuilt.find(o).is_none(), "{} was retired", hex::encode(o));
2621        }
2622    }
2623
2624    /// The measurement behind the change, re-takeable: three finders over the
2625    /// SAME 1 000 000 entries — the `Vec<(Vec<u8>, Located)>` this file shipped
2626    /// with, a binary search over the flat array, and the stree.
2627    ///
2628    /// `--ignored` because it is a measurement, not a guard: it asserts only that
2629    /// the three agree, and prints the times. Run it with
2630    /// `cargo test --release -p znippy-plugin-git --lib exploded_arrow -- --ignored --nocapture`
2631    /// — a debug build measures the borrow checker, not the machine.
2632    ///
2633    /// ## Measured, oden 2026-08-14, `--release`, 1 000 000 entries, 200 000
2634    /// probes (half misses), three runs
2635    ///
2636    /// | arm | ns/probe | vs shipped |
2637    /// |---|---:|---:|
2638    /// | `Vec<(Vec<u8>, Located)>` + `binary_search` (what shipped) | 836 / 862 / 961 | 1.00 |
2639    /// | flat oid array + `binary_search` | 339 / 339 / 348 | 0.40 |
2640    /// | **stree** | **164 / 175 / 185** | **0.21** |
2641    ///
2642    /// So the structure is worth **~2×** on its own and the flattening another
2643    /// **~2.5×**, and the two together take a point lookup to a fifth of what it
2644    /// cost. **The box was NOT quiet** — `/proc/loadavg` 1-min 29.7–31.5 on 32
2645    /// cores, other agents building throughout — so the absolute figures are
2646    /// upper bounds. The ratios are reported instead, and each arm's own spread
2647    /// across the three runs (14% / 2.7% / 12%) is far narrower than the 5×
2648    /// and 2× between them.
2649    #[test]
2650    #[ignore = "measurement; run under --release with --ignored"]
2651    fn lookup_cost_before_and_after() {
2652        use std::time::Instant;
2653        let n = 1_000_000usize;
2654        // 4 oids per prefix, so ~25% of probes land in a run of four and the
2655        // verify step is exercised rather than skipped.
2656        let oids = colliding_oids(n / 4, 4);
2657        let mut b = OidTreeBuilder::with_capacity(oids.len());
2658        for (i, o) in oids.iter().enumerate() {
2659            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 }))
2660                .unwrap();
2661        }
2662        let build = Instant::now();
2663        let tree = b.finish(Keep::Last);
2664        let build = build.elapsed();
2665
2666        // The shape this replaced: one heap allocation per oid.
2667        let mut old: Vec<(Vec<u8>, Located)> =
2668            tree.iter().map(|(o, l)| (o.to_vec(), l)).collect();
2669        old.sort_by(|a, b| a.0.cmp(&b.0));
2670
2671        // A miss-heavy probe order, and NOT in oid order — a `have` negotiation
2672        // is random and half of it misses.
2673        let mut probes: Vec<[u8; 20]> = Vec::with_capacity(200_000);
2674        for i in (0..oids.len()).step_by(oids.len() / 100_000) {
2675            probes.push(oids[i]);
2676            let mut m = oids[i];
2677            m[8] = 0xfe;
2678            probes.push(m);
2679        }
2680
2681        let mut sink = 0u64;
2682        let t0 = Instant::now();
2683        for p in &probes {
2684            if let Ok(i) = old.binary_search_by(|(o, _)| o.as_slice().cmp(&p[..])) {
2685                sink += old[i].1.row as u64;
2686            }
2687        }
2688        let vec_of_vec = t0.elapsed();
2689        let t0 = Instant::now();
2690        for p in &probes {
2691            if let Some(l) = tree.find_by_binary_search(p) {
2692                sink += l.row as u64;
2693            }
2694        }
2695        let flat_bsearch = t0.elapsed();
2696        let t0 = Instant::now();
2697        for p in &probes {
2698            if let Some(l) = tree.find(p) {
2699                sink += l.row as u64;
2700            }
2701        }
2702        let stree = t0.elapsed();
2703
2704        // The arms must be the same question.
2705        for p in &probes {
2706            let want = tree.find_by_binary_search(p);
2707            assert_eq!(tree.find(p), want, "arms disagree at {}", hex::encode(p));
2708        }
2709        let per = |d: std::time::Duration| d.as_secs_f64() * 1e9 / probes.len() as f64;
2710        println!(
2711            "exploded oid lookup, {} entries ({} groups of 4 colliding prefixes), \
2712             {} probes half of them misses:\n  \
2713             Vec<(Vec<u8>,Located)> binary_search  {:>7.1} ns/probe\n  \
2714             flat array binary_search             {:>7.1} ns/probe\n  \
2715             stree                                {:>7.1} ns/probe\n  \
2716             tree build (sort + fold + stree)      {:.3} s   sink={sink}",
2717            tree.len(),
2718            oids.len() / 4,
2719            probes.len(),
2720            per(vec_of_vec),
2721            per(flat_bsearch),
2722            per(stree),
2723            build.as_secs_f64(),
2724        );
2725    }
2726
2727    #[test]
2728    fn an_unknown_policy_is_refused() {
2729        assert_eq!(ExplodePolicy::parse("full").unwrap(), ExplodePolicy::Full);
2730        let err = ExplodePolicy::parse("ful").expect_err("a typo must be refused");
2731        assert!(format!("{err}").contains("unknown explode policy"), "{err}");
2732    }
2733}
2734