Skip to main content

znippy_plugin_git/
index_layout.rs

1//! One git object index, **three Arrow IPC layouts**, measured against each other.
2//!
3//! ## The question
4//!
5//! A git `.pack` carries no index at all. Git derives several *separate* files
6//! from it — `.idx` (oid → offset), `.rev` (offset → length), `.bitmap`,
7//! `.midx` — and two of the four facts a server actually needs on the hot path
8//! are in **none** of them:
9//!
10//! | fact | where git keeps it |
11//! |---|---|
12//! | oid | `.idx` |
13//! | byte extent (offset, len) | offset in `.idx`, length only via `.rev` or the next offset |
14//! | **type** | nowhere — an entry-header parse per object |
15//! | **uncompressed size** | nowhere — the same entry-header parse |
16//! | **delta base** | nowhere — the same entry-header parse, plus a varint |
17//!
18//! ## `delta_base` is an OFFSET, and the arms are named for what they were
19//!
20//! PLAN §13 settles it: `delta_base` is a `u64` **archive offset**, not a row
21//! ordinal into this table. An ordinal would be half the width and would index
22//! the very table it sits in — and it would break **silently** the first time
23//! the table is rebuilt in a different order, which §14 guarantees will happen
24//! because the whole index is a droppable cache. An offset is order-independent
25//! because the pack it addresses never moves; `PackWalk::rebased` shifts it with
26//! one addition and no table to keep in step. `0` is the sentinel for *no base*:
27//! archive offset 0 is a pack's `PACK` magic, so no entry can start there.
28//!
29//! It joined the schema after the three arms were named and measured, so the
30//! names now count **sections and tables, which is the variable under test** —
31//! not facts. [`FourTables`] is four IPC sections, [`OneTableFourColumns`] is
32//! one; both carry **five** payload columns today, and [`PackedPayload`] still
33//! carries one. Every ns figure quoted below was taken on the four-fact,
34//! 25-byte schema and is marked where that matters.
35//!
36//! So `cat-file --batch-check` over a pack is a varint decode per object, and a
37//! `have` negotiation of 1000 oids is 1000 of them. Consolidating all four facts
38//! into one index is the point of this module. The open question is what
39//! *shape* that index should have, and this module answers it by building three
40//! shapes behind [`ObjectIndex`] and benchmarking them
41//! (`examples/index_layout_bench.rs`).
42//!
43//! | arm | payload columns | buffers a full-row fetch touches |
44//! |---|---:|---:|
45//! | [`FourTables`] | 5, in four IPC sections | 5 |
46//! | [`OneTableFourColumns`] | 5, in one IPC section | 5 |
47//! | [`PackedPayload`] | **1**, in one IPC section | **1** |
48//!
49//! The first two were the original experiment, and they **tied at every size,
50//! batch size and hit rate**. The reason is visible in the table: Arrow is
51//! columnar, so "one table with five columns" is *not* row-contiguous. Both
52//! arms keep `offset`, `len`, `object_type`, `uncompressed_size` and
53//! `delta_base` in five separate buffers whose bases are megabytes apart
54//! (measured: 1 737 664 bytes between the `offset` and `size` buffers at
55//! 100 000 rows), so a full-row fetch costs five unrelated strides either way.
56//! **The number of tables was never the variable. The number of columns is** —
57//! which is what the third arm changes, and it is the only one that moves the
58//! number.
59//!
60//! ## What is deliberately shared, so the measurement is of the layout
61//!
62//! All three arms resolve `oid → ordinal` through the **same** [`crate::oid_index`]
63//! `stree` (LAW 5: reuse, do not twin — and a third oid index written by
64//! accident would have made the arms incomparable anyway). The two columnar arms
65//! share one `ColumnarPayload` holding every read path, so they cannot drift
66//! apart in the hot loop and the only thing between them is IPC framing.
67//!
68//! ## Zero-copy is asserted, not assumed
69//!
70//! All three arms decode with `StreamDecoder::with_require_alignment(true)`,
71//! which makes arrow **error** rather than silently allocate-and-copy when a
72//! buffer is misaligned. A layout that quietly copied its columns out of the IPC
73//! bytes on open would be a different (and much slower to build) thing than the
74//! one being claimed, so the reader refuses to be that thing.
75//! [`ObjectIndex::ipc_bytes`] plus each arm's `column_is_inside_ipc` let a test
76//! prove each array's data pointer actually lies inside the IPC buffer.
77//!
78//! # Measured
79//!
80//! oden, 32 cores, 2026-08-07, `--release --no-default-features`, sha1 oids,
81//! 100 000 lookups per cell, 5 runs per cell, 4 sizes × 3 hit rates × 7 access
82//! paths + 2 column scans. `/proc/loadavg` 0.96–2.98 (1-min) across the three
83//! sweeps — the first rotation started at 2.98, the other two at 1.53 and 1.35,
84//! and the reported figures are the geometric mean of all three, so no arm sat
85//! disproportionately in the busier one.
86//!
87//! Position is cancelled by **rotation**: the sweep is run three times with the
88//! arm order rotated, so each arm occupies each position exactly once. This
89//! matters — in the earlier two-arm work the arm timed second was measurably
90//! 1.1% slower at N ≥ 1e6 whichever layout it was, which is enough to invent a
91//! result out of nothing.
92//!
93//! **Noise band: median 8.9% run-to-run spread, p90 32.3%** over 270 cells
94//! (excluding the 1e3 scans, whose ns-per-row is below timer resolution). The
95//! p90 is carried almost entirely by the 100 000-object rows, where the index
96//! fits in L3; at 1e3 and 4e6 the bands are 2–20%. **Nothing below is claimed
97//! unless it clears its own cell's band.**
98//!
99//! ## First: the harness really does read all four facts
100//!
101//! This has to be established before any of the rest means anything. A harness
102//! that resolved the oid and threw the row away would measure the `stree` and
103//! nothing else, and would produce a tie no matter what the layouts did.
104//!
105//! [`ObjectIndex::ordinals_batch`] exists for exactly this: it resolves
106//! `oid → ordinal` and stops, touching no payload byte, and it is the same code
107//! in all three arms. Subtracting it from the full-row path isolates the payload
108//! gather — the only part any of these layouts can change:
109//!
110//! | objects | mix | stree floor | A payload | B payload | **C payload** | C/B |
111//! |---:|---|---:|---:|---:|---:|---:|
112//! | 1e3 | 100% hit | 50.3 | 6.3 | 6.1 | **1.5** | 0.24 |
113//! | 1e3 | 10% hit | 39.1 | 5.3 | 5.1 | **1.8** | 0.34 |
114//! | 1e5 | 50% hit | 58.6 | 15.0 | 14.0 | **10.6** | 0.76 |
115//! | 1e6 | 100% hit | 195.8 | 45.0 | 46.2 | **27.7** | 0.60 |
116//! | 1e6 | 10% hit | 113.4 | 11.4 | 11.1 | **7.2** | 0.65 |
117//! | 4e6 | 100% hit | 247.2 | 39.2 | 43.1 | **29.8** | 0.69 |
118//! | 4e6 | 50% hit | 199.6 | 30.9 | 27.9 | **20.9** | 0.75 |
119//! | 4e6 | 10% hit | 141.3 | 25.1 | 21.7 | **17.7** | 0.81 |
120//!
121//! ns per lookup, batch 1000, position-cancelled. The payload column is nowhere
122//! near zero and it differs between arms, so the facts are being read. It is
123//! **9–28% of a full-row lookup**; the shared `stree` is the other 72–91%.
124//!
125//! ## The owner was right: one column IS faster to fetch than four
126//!
127//! On the part of the work the layout controls, `PackedPayload` cuts the payload
128//! gather by **19–76%**, and by **25–40% at every size from 1e6 up**. One
129//! 25-byte stride against four strides megabytes apart, exactly as predicted.
130//! The single cell that does not show it (1e5, 100% hit, C/B 1.06) sits in the
131//! noisiest regime in the sweep, band 44%.
132//!
133//! Those cells are the **four-fact** schema. `delta_base` makes the packed
134//! record 33 bytes and gives the columnar arms a fifth stride, so the mechanism
135//! points the same way and the magnitudes are stale until re-measured. See
136//! "What the fifth column costs" below for the measurement that was actually
137//! taken after the column landed.
138//!
139//! **But the win is capped by Amdahl**, and this is the honest headline: the
140//! payload gather is only 9–28% of a lookup, so a 31% cut in it is a **4–8% cut
141//! end to end**. At 4e6 objects, 100% hit, position-cancelled `C/B`:
142//!
143//! | path | A ns | B ns | C ns | C/B | band | |
144//! |---|---:|---:|---:|---:|---:|---|
145//! | ordinals only (the floor) | 247.2 | 245.1 | 244.6 | 0.998 | 4.9% | tie, as it must be |
146//! | full row, serial `lookup` | 464.8 | 471.8 | 435.2 | **0.922** | 7.7% | **C faster** |
147//! | full row, batch 1 | 824.2 | 811.9 | 757.4 | 0.933 | 11.4% | inside band |
148//! | full row, batch 100 | 298.6 | 299.0 | 283.4 | **0.948** | 5.2% | **C faster** |
149//! | full row, batch 1000 | 286.4 | 288.3 | 274.4 | **0.952** | 2.8% | **C faster** |
150//! | full row, batch 10000 | 284.4 | 283.3 | 271.5 | 0.959 | 4.8% | inside band |
151//! | extents only, batch 1000 | 261.5 | 263.0 | 264.2 | 1.005 | 4.0% | tie |
152//!
153//! Three of the four full-row cells clear their band; the direction is the same
154//! in all seven and at every size. At 1e3 the win is larger and cleaner (C/B
155//! 0.898–0.931 at batch ≥ 100, bands 1.8–2.8%) because there the `stree` floor
156//! is small enough not to swamp it.
157//!
158//! **`extents` is a tie, and that is the mechanism confirming itself.** A
159//! partial-row fetch of two facts lets the columnar arms read two columns
160//! instead of four, while the packed arm reads the same 25 bytes it always
161//! reads. The advantage is exactly proportional to how much of the row you want,
162//! and at half a row it is gone.
163//!
164//! ## What the fifth column costs
165//!
166//! **Footprint: exactly 8 bytes per object, in every arm.** This is arithmetic,
167//! not an estimate, and the byte-exact guards below hold it there: the packed
168//! record goes 25 → 33 B, and each columnar arm gains one `u64` buffer of `8n`
169//! bytes. 800 kB per 100 000 objects; 32 MB at 4e6. The only *relative* change
170//! between arms is that `PackedPayload` now saves four per-column IPC buffers
171//! instead of three — MEASURED 50 560 B at 100 000 rows against the 38 016 B it
172//! saved before (`the_packed_arm_holds_the_same_payload_but_a_smaller_section`,
173//! which asserts the scaling law rather than the constant).
174//!
175//! **Latency: NOT re-measured, and no claim is made.** Two reasons, and the
176//! second is the one that will still be true tomorrow.
177//!
178//! Load was the first: the harness refuses above 1-minute load 4.0 and oden was
179//! carrying another agent's build at 9–26 for most of this change. That one
180//! cleared on its own (it fell to 2.1), so it is not the reason this is still
181//! unmeasured.
182//!
183//! **A before/after of a znippy change cannot be built in this tree, and that is
184//! structural.** A before/after needs the old and the new source resolved at the
185//! same time, which needs two znippy checkouts, and there is nowhere to put the
186//! second one — MEASURED by trying all three placements:
187//!
188//! | where the second checkout goes | what happens |
189//! |---|---|
190//! | anywhere under `~/git` | `package collision in the lockfile: znippy-common v0.9.13 (…/znippy-pre-deltabase) and znippy-common v0.9.13 (…/znippy) are different` |
191//! | anywhere outside it | `failed to read …/znippy-zoomies/lbzip2/Cargo.toml` |
192//!
193//! The cycle is the cause, not the placement: znippy's `xtask` and `tests`
194//! depend on `../../nornir`, and `nornir` depends back on
195//! `../znippy/znippy-common` — an absolute reference to *the* canonical
196//! checkout. So a second checkout drags the canonical one into its own resolve
197//! and two different copies of one version land in one lockfile. Move it out of
198//! `~/git` to escape that and it loses the `../../znippy-zoomies/…`
199//! path dependencies instead. Symlinking the siblings back does not help: cargo
200//! canonicalises, so `nornir` resolves to the real one and points at the real
201//! znippy again.
202//!
203//! Anyone wanting this number should therefore plan on **one checkout, timed
204//! twice** — build the bench, `git checkout` the other revision of these files
205//! in place, build again — and should not spend the hour discovering the above.
206//! That mutates a shared checkout for as long as it takes to compile, which is
207//! why it was not done here while another agent was working in this crate.
208//!
209//! What can be said without measuring, and is deliberately weaker than a
210//! number: the payload gather is 9–28% of a lookup, a columnar full-row fetch
211//! goes from four strides to five, and the packed record goes from ~1.4 cache
212//! lines to ~1.5. Both arms get slightly worse and the packed arm's *relative*
213//! advantage on full-row fetches should narrow a little. An 8-byte-per-row
214//! effect is in any case inside the 8.9% median / 32.3% p90 band this sweep
215//! already reports, so the honest expectation is a null result rather than a
216//! regression. **Re-run `examples/index_layout_bench.rs` on a quiet box before
217//! quoting any of the ns tables above as current.**
218//!
219//! ## …and it loses the scans, by a lot
220//!
221//! ns per row, full column scan, position-cancelled:
222//!
223//! | objects | scan | A | B | **C** | C/B |
224//! |---:|---|---:|---:|---:|---:|
225//! | 4e6 | `sum_uncompressed` (uses 8 B of every row) | 0.36 | 0.36 | **1.19** | **3.3×** |
226//! | 4e6 | `count_type` (uses 1 B of every row) | 0.09 | 0.09 | **1.32** | **14.4×** |
227//! | 1e6 | `count_type` | 0.09 | 0.09 | **1.27** | **14.0×** |
228//! | 1e5 | `count_type` | 0.09 | 0.09 | **0.51** | **5.5×** |
229//!
230//! The 4e6 rows clear their bands (4.5% and 34.7%) with room to spare, and the
231//! direction is identical at every size. This is the trade stated in
232//! [`PackedPayload`]'s docs, landing exactly where predicted: `count_type` drags
233//! 25 bytes through cache to use one, so it pays ~14× for the privilege of the
234//! 5% it won on full-row fetches. A quota gate or a type histogram over a
235//! 4-million-object repository is 5 ms on the columnar arms and 5 ms × 3–14 on
236//! this one.
237//!
238//! ## The other figures
239//!
240//! | | FourTables | OneTableFourColumns | PackedPayload |
241//! |---|---:|---:|---:|
242//! | resident (IPC + stree), 4e6 | 326.635 MiB | 326.634 MiB | 325.203 MiB |
243//! | build, 4e6 objects | 3.956 s | 4.052 s | 3.975 s |
244//!
245//! * **A vs B is still a tie**, now confirmed with a harness that provably reads
246//!   the payload: `A/B` ranges 0.96–1.06 and every cell is inside its band. Four
247//!   sections cost exactly **1048 bytes more than one, constant at every size** —
248//!   the framing of three extra IPC streams, 0.0003% at 4e6.
249//! * **`PackedPayload` is the smallest on disk**, by three per-column IPC
250//!   buffers: 38 016 B at 100 000 rows, 75 456 B at 200 000, i.e. `3 · n/8`. Its
251//!   *payload* is byte-identical (25 = 8 + 8 + 1 + 8).
252//! * **Build is a tie across all three** — within 2.5% at 4e6, inside the band.
253//!   Build is the oid sort and the `stree`, not the framing or the packing.
254//!
255//! ## What this means for the shape of the index
256//!
257//! Neither the packed arm nor the columnar ones is right everywhere, and the
258//! measurement says which is which rather than leaving it to taste:
259//!
260//! * The negotiation path (`want`/`have`, full row) is **5% faster packed**, and
261//!   the ceiling on that is the `stree`, not the payload — the next real win on
262//!   that path is in the oid step, not here.
263//! * The wire path (`extents`) is **indifferent**.
264//! * Analytics (quota gates, type histograms) are **3–14× slower packed**.
265//! * The packed arm gives up being four typed Arrow columns. A
266//!   `FixedSizeBinary(25)` is opaque to DuckDB / Polars / DataFusion, which can
267//!   query the other two arms straight off the IPC bytes with no consumer code.
268//!   That is a real cost and it is not a performance one.
269//!
270//! ## The stree header was the next experiment, and it was a negative result
271//!
272//! What this sweep *can* say, which the two-arm version could not, is that
273//! **the oid step is where the remaining time is**: the `ordinals_batch` floor is
274//! 72–91% of every full-row lookup, and it is identical in all three arms. The
275//! floor itself grows 39 ns → 247 ns from 1e3 to 4e6 objects, which is cache and
276//! TLB behaviour in the `stree`, not in any payload column.
277//!
278//! That pointed at `oid_index`'s 24-byte header (24 mod 64 = 24, so the key
279//! array is off-line by construction). It has now been built and measured —
280//! [`crate::oid_index::OidLayout`] and `examples/oid_align_bench.rs`, three arms
281//! separating the header offset from the allocator. **A 64-aligned keyspace
282//! takes 5.2% off cache-misses, reproducibly, and does not move the clock at
283//! all**: 0 of 24 cells clear their band, and 0 of 6 clear it again at 4e6 with
284//! the band tightened to 5%. The header is not where the oid step's time is, and
285//! the reason is instructive — `stree`'s internal nodes live in the tree's own
286//! `Vec`, not in this section, so the header could only ever move the leaf
287//! touch, and the pipelined batch walk was already hiding it. The full numbers
288//! and the mechanism are in [`crate::oid_index`].
289
290use std::sync::Arc;
291
292use anyhow::{Result, anyhow, bail};
293use znippy_common::arrow::array::{
294    Array, FixedSizeBinaryArray, UInt8Array, UInt64Array,
295};
296use znippy_common::arrow::buffer::{Buffer, MutableBuffer, ScalarBuffer};
297use znippy_common::arrow::datatypes::{DataType, Field, Schema, SchemaRef};
298use znippy_common::arrow::ipc::reader::StreamDecoder;
299use znippy_common::arrow::ipc::writer::StreamWriter;
300use znippy_common::arrow::record_batch::RecordBatch;
301
302use crate::object::GitHashKind;
303use crate::oid_index::{GitOidIndex, OidEntry, OidLayout, build_section_with_layout};
304
305// ── the four facts ────────────────────────────────────────────────────────────
306
307/// Object type, in git's own **pack entry** encoding.
308///
309/// This is not [`crate::object::GitObjectKind`] and must not be merged with it:
310/// that enum is the four *loose* object types, which is all a canonical
311/// `"<type> <size>\0…"` header can express. A packed object also comes in the
312/// two delta forms. Owned by the `git-storage-trait` contract; re-exported here
313/// so `crate::index_layout::ObjType` stays a valid path.
314pub use git_storage_trait::ObjType;
315
316/// One object, as the caller hands it to [`ObjectIndex::build`]. Order is
317/// irrelevant — every implementation sorts by oid and derives ordinals itself.
318#[derive(Debug, Clone, PartialEq, Eq)]
319pub struct IndexEntry {
320    /// 20 bytes (sha1) or 32 (sha256). All entries in one index must agree.
321    pub oid: Vec<u8>,
322    /// Start of the object's bytes within the archive.
323    pub offset: u64,
324    /// Length of those bytes as stored (compressed / delta-encoded).
325    pub len: u64,
326    pub obj_type: ObjType,
327    /// Inflated, post-delta-resolution size. The fact `.idx` and `.rev`
328    /// together still cannot answer.
329    pub uncompressed_size: u64,
330    /// `objects.delta_base` — the **archive offset** of the entry this one
331    /// deltas against, `0` for none (PLAN §13).
332    ///
333    /// An offset and not an ordinal, on purpose: it is in the same coordinate
334    /// space as [`offset`](Self::offset), so it survives a rebuild of this table
335    /// in any order and a rebase of the pack is one addition
336    /// ([`crate::pack_walk::PackWalk::rebased`]). `0` cannot collide with a real
337    /// base because archive offset 0 is a pack's `PACK` magic. A `REF_DELTA`
338    /// records `0` until its oid is resolved to an offset —
339    /// [`obj_type`](Self::obj_type) is what distinguishes that from *no base*.
340    pub delta_base: u64,
341}
342
343/// What a lookup resolves to: the ordinal plus all five facts.
344#[derive(Debug, Clone, Copy, PartialEq, Eq)]
345pub struct IndexRow {
346    /// Row ordinal — the oid-lexicographic rank, and the join key `FourTables`
347    /// uses across its four sections.
348    pub ordinal: u32,
349    pub offset: u64,
350    pub len: u64,
351    pub obj_type: ObjType,
352    pub uncompressed_size: u64,
353    /// See [`IndexEntry::delta_base`]. An archive offset, `0` for none — never
354    /// an ordinal, and in particular never *this* row's ordinal space.
355    pub delta_base: u64,
356}
357
358// ── the trait ─────────────────────────────────────────────────────────────────
359
360/// A git object index over Apache Arrow IPC.
361///
362/// `build` is `where Self: Sized`, so it stays out of the vtable and
363/// `Box<dyn ObjectIndex>` still works — which is how the bench drives both arms
364/// through one loop.
365pub trait ObjectIndex: Send + Sync {
366    fn build(entries: &[IndexEntry]) -> Result<Self>
367    where
368        Self: Sized;
369
370    /// Resolve one oid. `None` for an absent oid **and** for an oid of the
371    /// wrong width.
372    fn lookup(&self, oid: &[u8]) -> Option<IndexRow>;
373
374    /// The batch path, and the one that matters: `have` negotiation sends up to
375    /// 1000 oids at a time, the push connectivity check sends thousands.
376    /// Positional — `out[i]` answers `oids[i]`.
377    ///
378    /// This is the **full-row** access pattern: all five facts of each object.
379    fn lookup_batch(&self, oids: &[&[u8]]) -> Vec<Option<IndexRow>>;
380
381    /// oid → ordinal and **stop**. No payload column is touched at all.
382    ///
383    /// Identical in every implementation, because every implementation shares
384    /// the same `stree`. It is here as the **floor**: whatever this costs is
385    /// what no payload layout can remove, and `lookup_batch` minus this is the
386    /// only part any of these layouts can change. Without it a three-way tie is
387    /// unreadable — it could mean the layouts are equivalent, or it could mean
388    /// the harness never read a payload byte.
389    fn ordinals_batch(&self, oids: &[&[u8]]) -> Vec<Option<u32>>;
390
391    /// The **partial-row** access pattern: byte extent only, two of the five
392    /// facts. This is `extents(&[oid])`, what the wire path actually asks for
393    /// when it is about to copy bytes out of a pack.
394    fn extents_batch(&self, oids: &[&[u8]]) -> Vec<Option<(u64, u64)>>;
395
396    /// Full **column scan**: total uncompressed bytes over every object. The
397    /// quota gate. Reads one 8-byte fact per row and nothing else.
398    fn sum_uncompressed(&self) -> u64;
399
400    /// Full **column scan** with a predicate: how many objects of this type.
401    /// Reads one *byte* per row and nothing else — the most column-shaped
402    /// query there is, and the one a row-packed layout should lose worst.
403    fn count_type(&self, t: ObjType) -> usize;
404
405    fn name(&self) -> &'static str;
406
407    fn len(&self) -> usize;
408
409    fn is_empty(&self) -> bool {
410        self.len() == 0
411    }
412
413    /// Total bytes of Arrow IPC this index holds resident. Four sections or
414    /// one, this counts the same payload, so it is comparable across arms.
415    fn ipc_bytes(&self) -> usize;
416
417    /// IPC bytes plus the `stree` oid section — everything the index keeps
418    /// alive, excluding the handful of `Arc`'d schema/metadata allocations.
419    fn resident_bytes(&self) -> usize;
420
421    // ── the durable form ─────────────────────────────────────────────────────
422    //
423    // **The projection is the durable index, and redb is its tail** — the
424    // pattern the read stack was named for and, until 2026-09-04, did not
425    // have. `ObjectReadStack` used to keep EVERY row in redb for ever and
426    // re-derive this projection from a full B-tree scan on every open (a
427    // 382 B/object RAM floor, measured 744–966 on the kernel mirror), while
428    // the redb file grew to 208.5 B/object for 61 B of content — 2.9 GB
429    // written, 4 GiB allocated, for 14 M objects. The three methods below are
430    // what lets the stack persist the projection instead, fold the redb rows
431    // into it, and empty redb of what it folded — so redb holds only what
432    // arrived since the last fold, which is the whole of what a B-tree is
433    // good for here.
434
435    /// Whether this arm has a single-buffer form the stack can write down and
436    /// read back with [`from_persisted`](Self::from_persisted). An arm that
437    /// answers `false` is never persisted: the stack then keeps every row in
438    /// redb and rebuilds from it, which is the pre-2026-09-04 behaviour, kept
439    /// as a correct fallback rather than made an error.
440    ///
441    /// A `Sized` fn and not an associated const: a const would make the trait
442    /// not dyn-compatible, and the layout benches hold `&dyn ObjectIndex`.
443    fn persists() -> bool
444    where
445        Self: Sized,
446    {
447        false
448    }
449
450    /// **The bytes this index is persisted as** — one self-contained Arrow IPC
451    /// stream holding one record batch, or `None` for an arm with no such form.
452    fn persisted_bytes(&self) -> Option<&[u8]> {
453        None
454    }
455
456    /// Reconstruct this index from a buffer [`persisted_bytes`](Self::persisted_bytes)
457    /// produced — typically a memory-mapped `objects.index`, so every array is a
458    /// view into the page cache rather than a copy of it. Refuses a buffer this
459    /// arm did not write (a different arm's layout, a different format stamp).
460    fn from_persisted(buf: Buffer) -> Result<Self>
461    where
462        Self: Sized,
463    {
464        let _ = buf;
465        bail!("this index layout has no persisted form")
466    }
467
468    /// The raw oid at `ordinal`. Every arm keeps a `FixedSizeBinary` oid
469    /// column, so this is one bounds-checked slice, copied out — owned rather
470    /// than borrowed so that a stack holding its projection behind a lock can
471    /// answer it too. Positional, like Arrow's own `value(i)`: an ordinal past
472    /// `len()` (or, on a stack, a tail-tagged one) is a programming error and
473    /// panics rather than answering.
474    fn oid_at(&self, ordinal: u32) -> Vec<u8>;
475
476    /// Every fact of the row at `ordinal`, as the entry that would rebuild it.
477    /// The fold's merge reads the projection back through this.
478    fn entry_at(&self, ordinal: u32) -> IndexEntry;
479
480    /// `(offset, len)` of the row at `ordinal` — positional, no oid, no
481    /// allocation. The crash-recovery diff scans the whole projection through
482    /// this, so it must cost a column read and nothing more.
483    fn extent_at(&self, ordinal: u32) -> (u64, u64);
484
485    /// **Every oid, back to back, in ordinal order** — `len() × oid_len` bytes.
486    /// This IS the ordinal space the derived tables address (`__gunnar_reach__`
487    /// bitmaps, the commit graph's token), and on a persisted arm it is the oid
488    /// column's own bytes: the thing `objects.ordinal` used to cache in a file
489    /// of its own, with a header and an epoch to validate it, is a contiguous
490    /// buffer this index already holds. The default is the positional loop; the
491    /// columnar arms hand back their column.
492    fn oids_raw(&self) -> Vec<u8> {
493        let n = self.len() as u32;
494        let mut out = Vec::new();
495        for o in 0..n {
496            out.extend_from_slice(&self.oid_at(o));
497        }
498        out
499    }
500
501    /// All rows, in ordinal (= oid) order. `len()` allocations of `oid`, which
502    /// is the price of handing `build` a slice; the fold pays it once per fold
503    /// and nothing on the read path calls it.
504    fn entries(&self) -> Vec<IndexEntry> {
505        (0..self.len() as u32).map(|o| self.entry_at(o)).collect()
506    }
507}
508
509/// Schema-metadata key under which a persisted index stamps
510/// [`PERSISTED_FORMAT`]. A buffer without it, or with another value, is not
511/// this crate's index and [`ObjectIndex::from_persisted`] refuses it.
512pub const PERSISTED_FORMAT_KEY: &str = "znippy.index.format";
513/// Schema-metadata key naming the arm that wrote the buffer, so one arm cannot
514/// misread another's bytes as its own.
515pub const PERSISTED_LAYOUT_KEY: &str = "znippy.index.layout";
516/// **Bump in the same commit as any change to what a persisted column means.**
517/// The Arrow schema already versions the column *set* — a renamed or missing
518/// column fails `col()` — so this exists for the change a schema cannot see: the
519/// same six names carrying different semantics. `1` is the layout in use when
520/// persistence was introduced (2026-09-04).
521pub const PERSISTED_FORMAT: u64 = 1;
522
523/// The schema metadata every persisted arm writes.
524fn persisted_metadata(layout: &str) -> std::collections::HashMap<String, String> {
525    [
526        (PERSISTED_FORMAT_KEY.to_string(), PERSISTED_FORMAT.to_string()),
527        (PERSISTED_LAYOUT_KEY.to_string(), layout.to_string()),
528    ]
529    .into_iter()
530    .collect()
531}
532
533/// Refuse a decoded batch whose schema was not stamped by `layout` at
534/// [`PERSISTED_FORMAT`]. The error names what was found, because "wrong
535/// format" with no value behind it sends the reader to a hex dump.
536fn check_persisted_stamp(batch: &RecordBatch, layout: &str) -> Result<()> {
537    let meta = batch.schema_ref().metadata();
538    match meta.get(PERSISTED_FORMAT_KEY).map(String::as_str) {
539        Some(v) if v == PERSISTED_FORMAT.to_string() => {}
540        other => bail!(
541            "persisted index carries {PERSISTED_FORMAT_KEY}={other:?}, this build reads \
542             {PERSISTED_FORMAT}"
543        ),
544    }
545    match meta.get(PERSISTED_LAYOUT_KEY).map(String::as_str) {
546        Some(v) if v == layout => Ok(()),
547        other => bail!(
548            "persisted index was written by layout {other:?}, this projection is {layout}"
549        ),
550    }
551}
552
553// ── shared machinery: both arms are built from exactly this ───────────────────
554
555/// Column names, one place, so the two arms cannot drift apart on spelling.
556pub const COL_OID: &str = "oid";
557pub const COL_OFFSET: &str = "offset";
558pub const COL_LEN: &str = "len";
559pub const COL_TYPE: &str = "object_type";
560pub const COL_SIZE: &str = "uncompressed_size";
561pub const COL_DELTA_BASE: &str = "delta_base";
562
563/// The six Arrow arrays that carry the five facts, in oid-lexicographic order.
564/// The byte extent is one fact in two columns because that is what it is —
565/// `(offset, len)` — and splitting it lets a scan of just the offsets stay
566/// contiguous.
567pub struct Columns {
568    pub oid: FixedSizeBinaryArray,
569    pub offset: UInt64Array,
570    pub len: UInt64Array,
571    pub obj_type: UInt8Array,
572    pub size: UInt64Array,
573    /// Archive offset of the base entry, `0` for none. Same coordinate space as
574    /// `offset`, which is what makes a whole-column comparison against the
575    /// `offset` column meaningful (a delta's base is an entry in this table).
576    pub delta_base: UInt64Array,
577}
578
579/// Sort indices of `entries` into oid-lexicographic order, which is also the
580/// ordinal order and the order `oid_index::build_section` puts its keys in.
581///
582/// Ties on the full oid are impossible in a well-formed index and are checked
583/// for in [`validate`] rather than being silently deduplicated.
584fn oid_order(entries: &[IndexEntry]) -> Vec<u32> {
585    let mut order: Vec<u32> = (0..entries.len() as u32).collect();
586    order.sort_unstable_by(|&a, &b| entries[a as usize].oid.cmp(&entries[b as usize].oid));
587    order
588}
589
590/// Reject the two things that would make an index silently wrong: mixed oid
591/// widths, and a duplicate oid (which would give one object two ordinals and
592/// make the two arms disagree on which one a lookup returns).
593fn validate(entries: &[IndexEntry], order: &[u32]) -> Result<GitHashKind> {
594    let Some(first) = entries.first() else {
595        // An empty index is legitimate (an empty push) and its hash kind is
596        // arbitrary; sha1 keeps the section 20-byte shaped.
597        return Ok(GitHashKind::Sha1);
598    };
599    let hash = match first.oid.len() {
600        20 => GitHashKind::Sha1,
601        32 => GitHashKind::Sha256,
602        n => bail!("oid width {n} is neither sha1 (20) nor sha256 (32)"),
603    };
604    for e in entries {
605        if e.oid.len() != hash.oid_len() {
606            bail!(
607                "mixed oid widths: {} and {} in one index",
608                hash.oid_len(),
609                e.oid.len()
610            );
611        }
612    }
613    for w in order.windows(2) {
614        if entries[w[0] as usize].oid == entries[w[1] as usize].oid {
615            bail!(
616                "duplicate oid {} — one object cannot hold two ordinals",
617                hex::encode(&entries[w[0] as usize].oid)
618            );
619        }
620    }
621    Ok(hash)
622}
623
624/// The `stree` oid keyspace, shared verbatim by both arms.
625///
626/// `lookup_row` is set to the ordinal here. That is not a redefinition of the
627/// field: [`crate::oid_index::build_section`] is the lower-level API and its
628/// contract lets the caller choose what row an oid points at. This index's rows
629/// *are* its ordinals, and both arms use the ordinal, so nothing is lost.
630pub struct OidResolver {
631    tree: GitOidIndex,
632    section_bytes: usize,
633}
634
635impl OidResolver {
636    fn build(entries: &[IndexEntry], order: &[u32], hash: GitHashKind) -> Result<Self> {
637        Self::build_with(entries, order, hash, OidLayout::default())
638    }
639
640    /// [`build`](Self::build) with the section's cache-line layout chosen by the
641    /// caller. Only `PackedPayload::build_with_oid_layout` uses it; see there.
642    fn build_with(
643        entries: &[IndexEntry],
644        order: &[u32],
645        hash: GitHashKind,
646        layout: OidLayout,
647    ) -> Result<Self> {
648        let oid_entries: Vec<OidEntry> = order
649            .iter()
650            .enumerate()
651            .map(|(rank, &i)| OidEntry {
652                oid: entries[i as usize].oid.clone(),
653                lookup_row: rank as u64,
654                ordinal: rank as u32,
655            })
656            .collect();
657        let section = build_section_with_layout(&oid_entries, hash, layout)?;
658        let section_bytes = section.len();
659        // `parse_as`, not `parse`: `Compact64Alloc` is a reader-side allocation
660        // choice that the section's bytes cannot express.
661        Ok(Self { tree: GitOidIndex::parse_as(section, layout)?, section_bytes })
662    }
663
664    /// The resolver over an already-sorted oid column — a persisted index being
665    /// read back. Row `i` of the column IS ordinal `i`, which is what
666    /// [`from_persisted`](ObjectIndex::from_persisted) relies on and what
667    /// `build` guaranteed when it wrote the column in `oid_order`.
668    fn from_oid_column(oid: &FixedSizeBinaryArray, hash: GitHashKind) -> Result<Self> {
669        let oid_entries: Vec<OidEntry> = (0..oid.len())
670            .map(|i| OidEntry { oid: oid.value(i).to_vec(), lookup_row: i as u64, ordinal: i as u32 })
671            .collect();
672        let layout = OidLayout::default();
673        let section = build_section_with_layout(&oid_entries, hash, layout)?;
674        let section_bytes = section.len();
675        Ok(Self { tree: GitOidIndex::parse_as(section, layout)?, section_bytes })
676    }
677
678    #[inline]
679    fn ordinal(&self, oid: &[u8]) -> Option<u32> {
680        self.tree.lookup(oid).map(|h| h.ordinal)
681    }
682
683    #[inline]
684    fn ordinals(&self, oids: &[&[u8]]) -> Vec<Option<u32>> {
685        self.tree
686            .lookup_batch(oids)
687            .into_iter()
688            .map(|h| h.map(|h| h.ordinal))
689            .collect()
690    }
691}
692
693/// Materialise the five arrays from `entries` in `order`.
694///
695/// Both arms call this and nothing else, so any difference the bench reports is
696/// a difference of IPC packing, not of array construction.
697pub fn columns(entries: &[IndexEntry], order: &[u32], oid_len: usize) -> Columns {
698    let n = order.len();
699    let mut offset: Vec<u64> = Vec::with_capacity(n);
700    let mut len: Vec<u64> = Vec::with_capacity(n);
701    let mut ty: Vec<u8> = Vec::with_capacity(n);
702    let mut size: Vec<u64> = Vec::with_capacity(n);
703    let mut delta_base: Vec<u64> = Vec::with_capacity(n);
704    for &i in order {
705        let e = &entries[i as usize];
706        offset.push(e.offset);
707        len.push(e.len);
708        ty.push(e.obj_type.code());
709        size.push(e.uncompressed_size);
710        delta_base.push(e.delta_base);
711    }
712    Columns {
713        oid: oid_column(entries, order, oid_len),
714        offset: UInt64Array::new(ScalarBuffer::from(offset), None),
715        len: UInt64Array::new(ScalarBuffer::from(len), None),
716        obj_type: UInt8Array::new(ScalarBuffer::from(ty), None),
717        size: UInt64Array::new(ScalarBuffer::from(size), None),
718        delta_base: UInt64Array::new(ScalarBuffer::from(delta_base), None),
719    }
720}
721
722/// The oid column alone. Every arm stores it, and no arm packs it into the
723/// payload: the oid is the *key* the stree resolves against, not one of the
724/// facts a resolved lookup fetches, so putting it next to the payload would
725/// widen every payload read for a field nobody reads at lookup time.
726pub fn oid_column(entries: &[IndexEntry], order: &[u32], oid_len: usize) -> FixedSizeBinaryArray {
727    let mut bytes: Vec<u8> = Vec::with_capacity(order.len() * oid_len);
728    for &i in order {
729        bytes.extend_from_slice(&entries[i as usize].oid);
730    }
731    FixedSizeBinaryArray::new(oid_len as i32, Buffer::from_vec(bytes), None)
732}
733
734/// The five facts of one object, packed little-endian into `PACKED_LEN` bytes.
735///
736/// ```text
737///   0  u64 LE  offset               8
738///   8  u64 LE  len                  8
739///  16  u8      object type code     1
740///  17  u64 LE  uncompressed_size    8
741///  25  u64 LE  delta_base           8
742///                                  ══
743///                                  33
744/// ```
745///
746/// Fixed order, fixed width, no padding, no nulls. The type byte sits between
747/// the extent and the sizes rather than after them so the record is 33 bytes
748/// instead of 40 — the whole point of the arm is how few bytes a full-row fetch
749/// drags through cache, and 33 against 40 is 18% of that budget.
750///
751/// **This was 25 bytes before `delta_base` (PLAN §13) joined the schema.** The
752/// column is appended rather than inserted so the first four fields keep the
753/// offsets every reader here and every hand-decode in the tests already uses;
754/// the width is asserted byte for byte by
755/// `the_packed_record_is_the_documented_33_bytes`.
756pub const PACKED_LEN: usize = 33;
757const P_OFFSET: usize = 0;
758const P_LEN: usize = 8;
759const P_TYPE: usize = 16;
760const P_SIZE: usize = 17;
761const P_DELTA_BASE: usize = 25;
762
763/// One `FixedSizeBinary(PACKED_LEN)` element per object, in `order`.
764pub fn packed_column(entries: &[IndexEntry], order: &[u32]) -> FixedSizeBinaryArray {
765    let mut bytes: Vec<u8> = Vec::with_capacity(order.len() * PACKED_LEN);
766    for &i in order {
767        let e = &entries[i as usize];
768        bytes.extend_from_slice(&e.offset.to_le_bytes());
769        bytes.extend_from_slice(&e.len.to_le_bytes());
770        bytes.push(e.obj_type.code());
771        bytes.extend_from_slice(&e.uncompressed_size.to_le_bytes());
772        bytes.extend_from_slice(&e.delta_base.to_le_bytes());
773    }
774    debug_assert_eq!(bytes.len(), order.len() * PACKED_LEN);
775    FixedSizeBinaryArray::new(PACKED_LEN as i32, Buffer::from_vec(bytes), None)
776}
777
778#[inline]
779fn le64(r: &[u8], at: usize) -> u64 {
780    u64::from_le_bytes(r[at..at + 8].try_into().unwrap())
781}
782
783fn oid_field(oid_len: usize) -> Field {
784    Field::new(COL_OID, DataType::FixedSizeBinary(oid_len as i32), false)
785}
786
787/// Serialise one batch as a self-contained Arrow IPC **stream**.
788fn to_ipc(batch: &RecordBatch) -> Result<Vec<u8>> {
789    let mut out = Vec::with_capacity(64 + batch.get_array_memory_size());
790    {
791        let mut w = StreamWriter::try_new(&mut out, batch.schema_ref())
792            .map_err(|e| anyhow!("ipc writer: {e}"))?;
793        w.write(batch).map_err(|e| anyhow!("ipc write: {e}"))?;
794        w.finish().map_err(|e| anyhow!("ipc finish: {e}"))?;
795    }
796    Ok(out)
797}
798
799/// Decode an IPC stream **zero-copy**, and return the owning [`Buffer`] with it.
800///
801/// The `Vec<u8>` a writer produces is only 1-byte aligned, so it is first copied
802/// once into a `MutableBuffer` (64-byte aligned). After that every array in the
803/// batch is a view into `buffer` — enforced by `with_require_alignment(true)`,
804/// which errors instead of quietly re-allocating.
805fn decode_ipc(bytes: &[u8]) -> Result<(Buffer, RecordBatch)> {
806    let mut mb = MutableBuffer::with_capacity(bytes.len());
807    mb.extend_from_slice(bytes);
808    decode_ipc_buffer(mb.into())
809}
810
811/// The half of [`decode_ipc`] that does not control the buffer's alignment,
812/// split out so a test can hand it a deliberately misaligned one and prove
813/// `with_require_alignment(true)` is load-bearing rather than decoration.
814fn decode_ipc_buffer(owner: Buffer) -> Result<(Buffer, RecordBatch)> {
815    let mut cursor = owner.clone();
816    let mut decoder = StreamDecoder::new().with_require_alignment(true);
817    let mut found: Option<RecordBatch> = None;
818    while !cursor.is_empty() {
819        match decoder.decode(&mut cursor).map_err(|e| anyhow!("ipc decode: {e}"))? {
820            Some(b) if found.is_none() => found = Some(b),
821            Some(_) => bail!("index section holds more than one record batch"),
822            None => {}
823        }
824    }
825    decoder.finish().map_err(|e| anyhow!("ipc unfinished: {e}"))?;
826    found.ok_or_else(|| anyhow!("index section holds no record batch"))
827        .map(|b| (owner, b))
828}
829
830fn col<T: Array + Clone + 'static>(batch: &RecordBatch, name: &str) -> Result<T> {
831    batch
832        .column_by_name(name)
833        .ok_or_else(|| anyhow!("no `{name}` column"))?
834        .as_any()
835        .downcast_ref::<T>()
836        .cloned()
837        .ok_or_else(|| anyhow!("`{name}` has an unexpected type"))
838}
839
840/// True when `array`'s value bytes lie inside `ipc` — i.e. the decode really was
841/// zero-copy and not an aligned re-allocation behind our back.
842fn inside(ipc: &Buffer, values: &[u8]) -> bool {
843    if values.is_empty() {
844        // Nothing to point at; a zero-length column cannot disprove anything.
845        return true;
846    }
847    let base = ipc.as_ptr() as usize;
848    let p = values.as_ptr() as usize;
849    p >= base && p + values.len() <= base + ipc.len()
850}
851
852// ── shared read paths for the two columnar arms ───────────────────────────────
853
854/// The six arrays and **every** read path over them.
855///
856/// Both columnar arms hold one of these and neither has a hot path of its own,
857/// so they cannot drift apart (LAW 5) and the only thing the bench can see
858/// between them is how many IPC streams the arrays were framed into. That the
859/// two then tie is a fact about Arrow, not about this struct: `FourTables` and
860/// `OneTableFourColumns` both have **five payload columns in five separate
861/// buffers**, and a full-row fetch touches five distant strides either way. The
862/// number of *tables* was never the variable. The number of *columns* is, which
863/// is what [`PackedPayload`] changes.
864struct ColumnarPayload {
865    oid: FixedSizeBinaryArray,
866    offset: UInt64Array,
867    len: UInt64Array,
868    obj_type: UInt8Array,
869    size: UInt64Array,
870    delta_base: UInt64Array,
871}
872
873impl ColumnarPayload {
874    /// Five separate buffer reads, five strides.
875    #[inline]
876    fn row_at(&self, ordinal: u32) -> IndexRow {
877        let i = ordinal as usize;
878        IndexRow {
879            ordinal,
880            offset: self.offset.value(i),
881            len: self.len.value(i),
882            // A code the writer cannot produce cannot appear here: the column is
883            // built from `ObjType`, so the round trip is total. `Blob` is the
884            // only defensible fallback and it is unreachable in a section this
885            // crate wrote.
886            obj_type: ObjType::from_code(self.obj_type.value(i)).unwrap_or(ObjType::Blob),
887            uncompressed_size: self.size.value(i),
888            delta_base: self.delta_base.value(i),
889        }
890    }
891
892    /// Two of the five buffers.
893    #[inline]
894    fn extent_at(&self, ordinal: u32) -> (u64, u64) {
895        let i = ordinal as usize;
896        (self.offset.value(i), self.len.value(i))
897    }
898
899    /// The oid column's bytes, contiguous, in ordinal order. One copy out of
900    /// the (possibly mapped) buffer — the column is never sliced here, so its
901    /// value buffer is exactly `len × width` from offset 0, but the loop over
902    /// `value(i)` is kept rather than trusting that, because a wrong ordinal
903    /// space is believed by every bitmap built on it.
904    fn oids_raw(&self) -> Vec<u8> {
905        let n = self.oid.len();
906        let w = self.oid.value_length() as usize;
907        let mut out = Vec::with_capacity(n * w);
908        for i in 0..n {
909            out.extend_from_slice(self.oid.value(i));
910        }
911        out
912    }
913
914    /// All six, as the entry that would rebuild this row. The fold's merge
915    /// path; never the read path.
916    fn entry_at(&self, ordinal: u32) -> IndexEntry {
917        let i = ordinal as usize;
918        IndexEntry {
919            oid: self.oid.value(i).to_vec(),
920            offset: self.offset.value(i),
921            len: self.len.value(i),
922            obj_type: ObjType::from_code(self.obj_type.value(i)).unwrap_or(ObjType::Blob),
923            uncompressed_size: self.size.value(i),
924            delta_base: self.delta_base.value(i),
925        }
926    }
927
928    /// One contiguous `u64` run, start to end — the case columnar is for.
929    fn sum_uncompressed(&self) -> u64 {
930        self.size.values().iter().copied().fold(0u64, u64::wrapping_add)
931    }
932
933    /// One contiguous `u8` run: `n` bytes read to answer a question about `n`
934    /// rows, which is the least memory traffic any layout can do here.
935    fn count_type(&self, t: ObjType) -> usize {
936        let c = t.code();
937        self.obj_type.values().iter().filter(|&&x| x == c).count()
938    }
939
940    fn inside(&self, oid_ipc: &Buffer, extent_ipc: &Buffer, type_ipc: &Buffer, size_ipc: &Buffer) -> bool {
941        inside(oid_ipc, self.oid.value_data())
942            && inside(extent_ipc, self.offset.values().inner().as_slice())
943            && inside(extent_ipc, self.len.values().inner().as_slice())
944            && inside(extent_ipc, self.delta_base.values().inner().as_slice())
945            && inside(type_ipc, self.obj_type.values().inner().as_slice())
946            && inside(size_ipc, self.size.values().inner().as_slice())
947    }
948}
949
950/// The three schemas layout A frames its facts into, plus the oid schema.
951///
952/// `delta_base` rides in the **extent** section rather than in a fifth one, and
953/// the reason is what the section means: it is *where the bytes are*, and a
954/// delta base is an address in exactly the same coordinate space as `offset` —
955/// the two are compared against each other by every guard that proves the base
956/// resolves. Keeping it here also keeps layout A what the benchmark named it:
957/// **four IPC sections** against layout B's one. The section count is the
958/// variable under test, and adding a fifth section would have changed the
959/// experiment rather than the schema.
960fn extent_schema() -> SchemaRef {
961    Arc::new(Schema::new(vec![
962        Field::new(COL_OFFSET, DataType::UInt64, false),
963        Field::new(COL_LEN, DataType::UInt64, false),
964        Field::new(COL_DELTA_BASE, DataType::UInt64, false),
965    ]))
966}
967
968// ── Impl A — FourTables ───────────────────────────────────────────────────────
969
970/// Four Arrow IPC sections — oid, byte extent, type, size — joined by row
971/// ordinal.
972///
973/// This is git's own shape: `.idx`, `.rev` and the missing type/size files, each
974/// an independent artifact. A lookup resolves the oid to an ordinal and then
975/// indexes three further sections at that ordinal.
976///
977/// The name counts **sections**, which is this arm's whole difference from
978/// [`OneTableFourColumns`]. It carries five payload columns: `delta_base` joined
979/// the schema afterwards and shares the extent section, for the reason given on
980/// [`extent_schema`].
981pub struct FourTables {
982    oids: OidResolver,
983    /// Owning IPC buffers, kept alive because every array below is a view into
984    /// one of them. Four buffers, four allocations, four distinct page runs.
985    ipc: [Buffer; 4],
986    cols: ColumnarPayload,
987    rows: usize,
988}
989
990impl FourTables {
991    /// Section order: oid, extent, type, size.
992    pub fn ipc_section_lens(&self) -> [usize; 4] {
993        [self.ipc[0].len(), self.ipc[1].len(), self.ipc[2].len(), self.ipc[3].len()]
994    }
995
996    /// The oid column, straight out of its own section — proof that "four
997    /// tables" still gives a contiguous scannable column.
998    pub fn oid_column(&self) -> &FixedSizeBinaryArray {
999        &self.cols.oid
1000    }
1001
1002    /// Every column's bytes lie inside the section they were decoded from.
1003    pub fn column_is_inside_ipc(&self) -> bool {
1004        self.cols.inside(&self.ipc[0], &self.ipc[1], &self.ipc[2], &self.ipc[3])
1005    }
1006}
1007
1008impl ObjectIndex for FourTables {
1009    fn build(entries: &[IndexEntry]) -> Result<Self> {
1010        let order = oid_order(entries);
1011        let hash = validate(entries, &order)?;
1012        let oid_len = hash.oid_len();
1013        let c = columns(entries, &order, oid_len);
1014        let oids = OidResolver::build(entries, &order, hash)?;
1015
1016        let s_oid = Arc::new(Schema::new(vec![oid_field(oid_len)]));
1017        let s_type = Arc::new(Schema::new(vec![Field::new(COL_TYPE, DataType::UInt8, false)]));
1018        let s_size = Arc::new(Schema::new(vec![Field::new(COL_SIZE, DataType::UInt64, false)]));
1019
1020        let b_oid = RecordBatch::try_new(s_oid, vec![Arc::new(c.oid)])?;
1021        let b_extent = RecordBatch::try_new(
1022            extent_schema(),
1023            vec![Arc::new(c.offset), Arc::new(c.len), Arc::new(c.delta_base)],
1024        )?;
1025        let b_type = RecordBatch::try_new(s_type, vec![Arc::new(c.obj_type)])?;
1026        let b_size = RecordBatch::try_new(s_size, vec![Arc::new(c.size)])?;
1027
1028        let (ipc_oid, r_oid) = decode_ipc(&to_ipc(&b_oid)?)?;
1029        let (ipc_extent, r_extent) = decode_ipc(&to_ipc(&b_extent)?)?;
1030        let (ipc_type, r_type) = decode_ipc(&to_ipc(&b_type)?)?;
1031        let (ipc_size, r_size) = decode_ipc(&to_ipc(&b_size)?)?;
1032
1033        Ok(Self {
1034            oids,
1035            ipc: [ipc_oid, ipc_extent, ipc_type, ipc_size],
1036            cols: ColumnarPayload {
1037                oid: col(&r_oid, COL_OID)?,
1038                offset: col(&r_extent, COL_OFFSET)?,
1039                len: col(&r_extent, COL_LEN)?,
1040                obj_type: col(&r_type, COL_TYPE)?,
1041                size: col(&r_size, COL_SIZE)?,
1042                delta_base: col(&r_extent, COL_DELTA_BASE)?,
1043            },
1044            rows: order.len(),
1045        })
1046    }
1047
1048    fn lookup(&self, oid: &[u8]) -> Option<IndexRow> {
1049        self.oids.ordinal(oid).map(|o| self.cols.row_at(o))
1050    }
1051
1052    fn lookup_batch(&self, oids: &[&[u8]]) -> Vec<Option<IndexRow>> {
1053        self.oids.ordinals(oids).into_iter().map(|o| o.map(|o| self.cols.row_at(o))).collect()
1054    }
1055
1056    fn ordinals_batch(&self, oids: &[&[u8]]) -> Vec<Option<u32>> {
1057        self.oids.ordinals(oids)
1058    }
1059
1060    fn extents_batch(&self, oids: &[&[u8]]) -> Vec<Option<(u64, u64)>> {
1061        self.oids.ordinals(oids).into_iter().map(|o| o.map(|o| self.cols.extent_at(o))).collect()
1062    }
1063
1064    fn sum_uncompressed(&self) -> u64 {
1065        self.cols.sum_uncompressed()
1066    }
1067
1068    fn count_type(&self, t: ObjType) -> usize {
1069        self.cols.count_type(t)
1070    }
1071
1072    fn name(&self) -> &'static str {
1073        "FourTables"
1074    }
1075
1076    fn oid_at(&self, ordinal: u32) -> Vec<u8> {
1077        self.cols.oid.value(ordinal as usize).to_vec()
1078    }
1079
1080    fn entry_at(&self, ordinal: u32) -> IndexEntry {
1081        self.cols.entry_at(ordinal)
1082    }
1083
1084    fn extent_at(&self, ordinal: u32) -> (u64, u64) {
1085        self.cols.extent_at(ordinal)
1086    }
1087
1088    fn oids_raw(&self) -> Vec<u8> {
1089        self.cols.oids_raw()
1090    }
1091
1092    fn len(&self) -> usize {
1093        self.rows
1094    }
1095
1096    fn ipc_bytes(&self) -> usize {
1097        self.ipc.iter().map(|b| b.len()).sum()
1098    }
1099
1100    fn resident_bytes(&self) -> usize {
1101        self.ipc_bytes() + self.oids.section_bytes
1102    }
1103}
1104
1105// ── Impl B — OneTableFourColumns ──────────────────────────────────────────────
1106
1107/// One Arrow IPC section, one table, the facts one column each.
1108///
1109/// Arrow is columnar, so this is **not** row-contiguous: `offset` is its own
1110/// buffer, `len` is its own buffer, and a full-row fetch still touches five
1111/// strides that are megabytes apart. What it saves over [`FourTables`] is the
1112/// framing of three IPC streams and nothing else — which is exactly what the
1113/// measurement found.
1114///
1115/// The name counts the columns it had when it was named and measured; since
1116/// `delta_base` (PLAN §13) there are five payload columns here and in
1117/// [`FourTables`] alike, so the two are still separated by section count and
1118/// nothing else.
1119pub struct OneTableFourColumns {
1120    oids: OidResolver,
1121    ipc: Buffer,
1122    cols: ColumnarPayload,
1123    rows: usize,
1124}
1125
1126impl OneTableFourColumns {
1127    /// What this arm writes under [`PERSISTED_LAYOUT_KEY`], and the only value
1128    /// [`ObjectIndex::from_persisted`] accepts there.
1129    const LAYOUT_NAME: &'static str = "OneTableFourColumns";
1130
1131    /// The one constructor both `build` and `from_persisted` end in, so the
1132    /// column wiring is spelled once.
1133    fn from_decoded(oids: OidResolver, ipc: Buffer, r: &RecordBatch, rows: usize) -> Result<Self> {
1134        Ok(Self {
1135            oids,
1136            ipc,
1137            cols: ColumnarPayload {
1138                oid: col(r, COL_OID)?,
1139                offset: col(r, COL_OFFSET)?,
1140                len: col(r, COL_LEN)?,
1141                obj_type: col(r, COL_TYPE)?,
1142                size: col(r, COL_SIZE)?,
1143                delta_base: col(r, COL_DELTA_BASE)?,
1144            },
1145            rows,
1146        })
1147    }
1148
1149    pub fn oid_column(&self) -> &FixedSizeBinaryArray {
1150        &self.cols.oid
1151    }
1152
1153    /// All five arrays are views into the one IPC buffer.
1154    pub fn column_is_inside_ipc(&self) -> bool {
1155        self.cols.inside(&self.ipc, &self.ipc, &self.ipc, &self.ipc)
1156    }
1157
1158    /// **The bytes this index would be persisted as** — the single Arrow IPC
1159    /// stream every column is a view into, exactly as [`to_ipc`] framed it.
1160    ///
1161    /// [`ObjectIndex::ipc_bytes`] reports this buffer's *length*, which is
1162    /// enough to compare two layouts' footprints and not enough to write one
1163    /// down. `examples/tail_write_bench.rs` needs the bytes themselves: its
1164    /// no-tail arm has to rewrite the whole index on every push, and a
1165    /// measurement of that write is only honest if the bytes going to the file
1166    /// are the index's own and not a stand-in of the same size.
1167    ///
1168    /// A borrowed slice and not a `Vec`: the buffer is already resident and
1169    /// aligned, and handing out a copy would put an allocation inside the very
1170    /// write this exists to measure.
1171    pub fn ipc_slice(&self) -> &[u8] {
1172        self.ipc.as_slice()
1173    }
1174}
1175
1176impl ObjectIndex for OneTableFourColumns {
1177    fn build(entries: &[IndexEntry]) -> Result<Self> {
1178        let order = oid_order(entries);
1179        let hash = validate(entries, &order)?;
1180        let oid_len = hash.oid_len();
1181        let c = columns(entries, &order, oid_len);
1182        let oids = OidResolver::build(entries, &order, hash)?;
1183
1184        // The stamp rides inside the IPC bytes, so the persisted file needs no
1185        // framing of its own and `from_persisted` can refuse a foreign buffer
1186        // by reading the schema it already had to decode.
1187        let schema: SchemaRef = Arc::new(Schema::new_with_metadata(
1188            vec![
1189                oid_field(oid_len),
1190                Field::new(COL_OFFSET, DataType::UInt64, false),
1191                Field::new(COL_LEN, DataType::UInt64, false),
1192                Field::new(COL_TYPE, DataType::UInt8, false),
1193                Field::new(COL_SIZE, DataType::UInt64, false),
1194                Field::new(COL_DELTA_BASE, DataType::UInt64, false),
1195            ],
1196            persisted_metadata(Self::LAYOUT_NAME),
1197        ));
1198        let batch = RecordBatch::try_new(
1199            schema,
1200            vec![
1201                Arc::new(c.oid),
1202                Arc::new(c.offset),
1203                Arc::new(c.len),
1204                Arc::new(c.obj_type),
1205                Arc::new(c.size),
1206                Arc::new(c.delta_base),
1207            ],
1208        )?;
1209        let (ipc, r) = decode_ipc(&to_ipc(&batch)?)?;
1210        Self::from_decoded(oids, ipc, &r, order.len())
1211    }
1212
1213    fn persists() -> bool {
1214        true
1215    }
1216
1217    fn persisted_bytes(&self) -> Option<&[u8]> {
1218        Some(self.ipc.as_slice())
1219    }
1220
1221    /// The buffer is decoded in place — `decode_ipc_buffer`, not `decode_ipc`,
1222    /// so a memory-mapped file stays mapped and every column is a view into
1223    /// it — and the `stree` is rebuilt over its oid column. The stree is the
1224    /// one thing this does not read back: its section is a reader-side
1225    /// structure `GitOidIndex::parse_as` derives, and building it is O(n) in
1226    /// the oid count against the O(n log n) sort-and-encode a rebuild from
1227    /// redb pays, with no B-tree walk in front of it.
1228    fn from_persisted(buf: Buffer) -> Result<Self> {
1229        let (ipc, r) = decode_ipc_buffer(buf)?;
1230        check_persisted_stamp(&r, Self::LAYOUT_NAME)?;
1231        let oid: FixedSizeBinaryArray = col(&r, COL_OID)?;
1232        let hash = match oid.value_length() {
1233            20 => GitHashKind::Sha1,
1234            32 => GitHashKind::Sha256,
1235            w => bail!("persisted oid column is {w} bytes wide, expected 20 or 32"),
1236        };
1237        let oids = OidResolver::from_oid_column(&oid, hash)?;
1238        let rows = r.num_rows();
1239        Self::from_decoded(oids, ipc, &r, rows)
1240    }
1241
1242    fn oid_at(&self, ordinal: u32) -> Vec<u8> {
1243        self.cols.oid.value(ordinal as usize).to_vec()
1244    }
1245
1246    fn entry_at(&self, ordinal: u32) -> IndexEntry {
1247        self.cols.entry_at(ordinal)
1248    }
1249
1250    fn extent_at(&self, ordinal: u32) -> (u64, u64) {
1251        self.cols.extent_at(ordinal)
1252    }
1253
1254    fn oids_raw(&self) -> Vec<u8> {
1255        self.cols.oids_raw()
1256    }
1257
1258    fn lookup(&self, oid: &[u8]) -> Option<IndexRow> {
1259        self.oids.ordinal(oid).map(|o| self.cols.row_at(o))
1260    }
1261
1262    fn lookup_batch(&self, oids: &[&[u8]]) -> Vec<Option<IndexRow>> {
1263        self.oids.ordinals(oids).into_iter().map(|o| o.map(|o| self.cols.row_at(o))).collect()
1264    }
1265
1266    fn ordinals_batch(&self, oids: &[&[u8]]) -> Vec<Option<u32>> {
1267        self.oids.ordinals(oids)
1268    }
1269
1270    fn extents_batch(&self, oids: &[&[u8]]) -> Vec<Option<(u64, u64)>> {
1271        self.oids.ordinals(oids).into_iter().map(|o| o.map(|o| self.cols.extent_at(o))).collect()
1272    }
1273
1274    fn sum_uncompressed(&self) -> u64 {
1275        self.cols.sum_uncompressed()
1276    }
1277
1278    fn count_type(&self, t: ObjType) -> usize {
1279        self.cols.count_type(t)
1280    }
1281
1282    fn name(&self) -> &'static str {
1283        "OneTableFourColumns"
1284    }
1285
1286    fn len(&self) -> usize {
1287        self.rows
1288    }
1289
1290    fn ipc_bytes(&self) -> usize {
1291        self.ipc.len()
1292    }
1293
1294    fn resident_bytes(&self) -> usize {
1295        self.ipc_bytes() + self.oids.section_bytes
1296    }
1297}
1298
1299// ── Impl C — PackedPayload ────────────────────────────────────────────────────
1300
1301/// **One** payload column: all five facts of one object packed adjacently into
1302/// a single `FixedSizeBinary(33)` element.
1303///
1304/// This is the arm the first two were both missing. `FourTables` and
1305/// `OneTableFourColumns` differ in how many *tables* they use and agree in
1306/// having **five payload columns**, so a full-row fetch costs five buffer reads
1307/// at five unrelated addresses in both. Here it costs one:
1308///
1309/// ```text
1310/// per row, byte for byte (little-endian, no padding, no nulls):
1311///   0  u64  offset
1312///   8  u64  len
1313///  16  u8   object type code (1 commit, 2 tree, 3 blob, 4 tag, 6 ofs-delta, 7 ref-delta)
1314///  17  u64  uncompressed_size
1315///  25  u64  delta_base — archive offset of the base entry, 0 for none
1316///  33  ── next row
1317/// ```
1318///
1319/// **It was 24 bytes narrower before `delta_base` (PLAN §13).** A 33-byte record
1320/// spans one 64-byte cache line 49% of the time and two the rest, so a full-row
1321/// fetch is ~1.5 lines against the five the columnar arms touch — where at 25
1322/// bytes it was ~1.4 against four. The trade moved slightly, in both directions
1323/// at once, which is why the numbers below were re-taken rather than scaled.
1324///
1325/// The oid stays in its own column. It is the key the `stree` resolves
1326/// *against*, not one of the facts a resolved lookup fetches, so packing it in
1327/// would grow every payload read by 20 bytes nobody reads at lookup time.
1328///
1329/// ## The trade, stated before it is measured
1330///
1331/// * **Full-row access should win** — one stride instead of four.
1332/// * **Column scans should lose, and lose badly.** `count_type` reads one byte
1333///   per row; the columnar arms stream `n` bytes to answer it, this arm drags
1334///   `33n` through cache to use `n`. `sum_uncompressed` reads 8 of every 33
1335///   instead of 8 of every 8.
1336/// * It is **no longer typed Arrow columns**. A `FixedSizeBinary(33)` is
1337///   opaque to DuckDB / Polars / DataFusion, which can query the other two arms
1338///   directly off the IPC bytes. That is a real cost and it is not a
1339///   performance one.
1340pub struct PackedPayload {
1341    oids: OidResolver,
1342    ipc: Buffer,
1343    oid: FixedSizeBinaryArray,
1344    payload: FixedSizeBinaryArray,
1345    rows: usize,
1346}
1347
1348/// Column name of the single packed payload column.
1349pub const COL_PACKED: &str = "packed";
1350
1351impl PackedPayload {
1352    /// [`ObjectIndex::build`] with the `stree` section's [`OidLayout`] chosen
1353    /// explicitly — the whole apparatus of the alignment experiment
1354    /// (`examples/oid_align_bench.rs`).
1355    ///
1356    /// It lives on this arm alone rather than on the trait because
1357    /// `ordinals_batch` is **the same code in all three arms** (they share one
1358    /// [`OidResolver`]), so a second arm would add a second Arrow payload to
1359    /// keep resident and would measure nothing new. This is the arm the payload
1360    /// sweep picked.
1361    pub fn build_with_oid_layout(entries: &[IndexEntry], layout: OidLayout) -> Result<Self> {
1362        let order = oid_order(entries);
1363        let hash = validate(entries, &order)?;
1364        let oid_len = hash.oid_len();
1365        let oid_arr = oid_column(entries, &order, oid_len);
1366        let packed = packed_column(entries, &order);
1367        let oids = OidResolver::build_with(entries, &order, hash, layout)?;
1368        Self::assemble(oids, oid_arr, packed, oid_len, order.len())
1369    }
1370
1371    /// The cache-line phase of this index's `stree` keyspace — 0 for
1372    /// [`OidLayout::Aligned64`]. The bench asserts on it before quoting a
1373    /// number, because two arms that landed on the same phase would be one arm
1374    /// measured twice.
1375    pub fn keyspace_phase(&self) -> usize {
1376        self.oids.tree.keyspace_phase()
1377    }
1378
1379    /// Everything after the oid resolver: framing the two columns into one IPC
1380    /// stream and decoding it back zero-copy. Shared with `build` so the two
1381    /// cannot drift (LAW 5) — the only difference between them must be the
1382    /// `stree` layout, or the experiment is measuring two indexes.
1383    fn assemble(
1384        oids: OidResolver,
1385        oid_arr: FixedSizeBinaryArray,
1386        packed: FixedSizeBinaryArray,
1387        oid_len: usize,
1388        rows: usize,
1389    ) -> Result<Self> {
1390        let schema: SchemaRef = Arc::new(Schema::new(vec![
1391            oid_field(oid_len),
1392            Field::new(COL_PACKED, DataType::FixedSizeBinary(PACKED_LEN as i32), false),
1393        ]));
1394        let batch = RecordBatch::try_new(schema, vec![Arc::new(oid_arr), Arc::new(packed)])?;
1395        let (ipc, r) = decode_ipc(&to_ipc(&batch)?)?;
1396        Ok(Self { oids, ipc, oid: col(&r, COL_OID)?, payload: col(&r, COL_PACKED)?, rows })
1397    }
1398
1399    pub fn oid_column(&self) -> &FixedSizeBinaryArray {
1400        &self.oid
1401    }
1402
1403    pub fn column_is_inside_ipc(&self) -> bool {
1404        inside(&self.ipc, self.oid.value_data()) && inside(&self.ipc, self.payload.value_data())
1405    }
1406
1407    /// One buffer read, one stride.
1408    #[inline]
1409    fn row_at(&self, ordinal: u32) -> IndexRow {
1410        let r = self.payload.value(ordinal as usize);
1411        IndexRow {
1412            ordinal,
1413            offset: le64(r, P_OFFSET),
1414            len: le64(r, P_LEN),
1415            obj_type: ObjType::from_code(r[P_TYPE]).unwrap_or(ObjType::Blob),
1416            uncompressed_size: le64(r, P_SIZE),
1417            delta_base: le64(r, P_DELTA_BASE),
1418        }
1419    }
1420
1421    /// The same one buffer read — a partial row costs a packed layout exactly
1422    /// what a full row costs, which is half the point of the trade.
1423    #[inline]
1424    fn extent_at(&self, ordinal: u32) -> (u64, u64) {
1425        let r = self.payload.value(ordinal as usize);
1426        (le64(r, P_OFFSET), le64(r, P_LEN))
1427    }
1428}
1429
1430impl ObjectIndex for PackedPayload {
1431    fn build(entries: &[IndexEntry]) -> Result<Self> {
1432        let order = oid_order(entries);
1433        let hash = validate(entries, &order)?;
1434        let oid_len = hash.oid_len();
1435        let oid_arr = oid_column(entries, &order, oid_len);
1436        let packed = packed_column(entries, &order);
1437        let oids = OidResolver::build(entries, &order, hash)?;
1438        Self::assemble(oids, oid_arr, packed, oid_len, order.len())
1439    }
1440
1441    fn lookup(&self, oid: &[u8]) -> Option<IndexRow> {
1442        self.oids.ordinal(oid).map(|o| self.row_at(o))
1443    }
1444
1445    fn lookup_batch(&self, oids: &[&[u8]]) -> Vec<Option<IndexRow>> {
1446        self.oids.ordinals(oids).into_iter().map(|o| o.map(|o| self.row_at(o))).collect()
1447    }
1448
1449    fn ordinals_batch(&self, oids: &[&[u8]]) -> Vec<Option<u32>> {
1450        self.oids.ordinals(oids)
1451    }
1452
1453    fn extents_batch(&self, oids: &[&[u8]]) -> Vec<Option<(u64, u64)>> {
1454        self.oids.ordinals(oids).into_iter().map(|o| o.map(|o| self.extent_at(o))).collect()
1455    }
1456
1457    /// Strided: 8 useful bytes out of every 25 touched.
1458    fn sum_uncompressed(&self) -> u64 {
1459        let d = self.payload.value_data();
1460        let mut acc = 0u64;
1461        let mut i = P_SIZE;
1462        while i + 8 <= d.len() {
1463            acc = acc.wrapping_add(le64(d, i));
1464            i += PACKED_LEN;
1465        }
1466        acc
1467    }
1468
1469    /// Strided: 1 useful byte out of every 25 touched.
1470    fn count_type(&self, t: ObjType) -> usize {
1471        let c = t.code();
1472        let d = self.payload.value_data();
1473        let mut n = 0usize;
1474        let mut i = P_TYPE;
1475        while i < d.len() {
1476            if d[i] == c {
1477                n += 1;
1478            }
1479            i += PACKED_LEN;
1480        }
1481        n
1482    }
1483
1484    fn name(&self) -> &'static str {
1485        "PackedPayload"
1486    }
1487
1488    fn oid_at(&self, ordinal: u32) -> Vec<u8> {
1489        self.oid.value(ordinal as usize).to_vec()
1490    }
1491
1492    fn entry_at(&self, ordinal: u32) -> IndexEntry {
1493        let r = self.row_at(ordinal);
1494        IndexEntry {
1495            oid: self.oid.value(ordinal as usize).to_vec(),
1496            offset: r.offset,
1497            len: r.len,
1498            obj_type: r.obj_type,
1499            uncompressed_size: r.uncompressed_size,
1500            delta_base: r.delta_base,
1501        }
1502    }
1503
1504    fn extent_at(&self, ordinal: u32) -> (u64, u64) {
1505        // The inherent `extent_at` (one 33-byte stride, two fields out of it).
1506        PackedPayload::extent_at(self, ordinal)
1507    }
1508
1509    fn oids_raw(&self) -> Vec<u8> {
1510        let n = self.oid.len();
1511        let mut out = Vec::with_capacity(n * self.oid.value_length() as usize);
1512        for i in 0..n {
1513            out.extend_from_slice(self.oid.value(i));
1514        }
1515        out
1516    }
1517
1518    fn len(&self) -> usize {
1519        self.rows
1520    }
1521
1522    fn ipc_bytes(&self) -> usize {
1523        self.ipc.len()
1524    }
1525
1526    fn resident_bytes(&self) -> usize {
1527        self.ipc_bytes() + self.oids.section_bytes
1528    }
1529}
1530
1531// ── deterministic workload generation, shared by tests and the bench ──────────
1532
1533/// splitmix64. Seeded, so a bench run is reproducible and a historized series is
1534/// comparable at all.
1535pub struct Rng(pub u64);
1536
1537impl Rng {
1538    pub fn next_u64(&mut self) -> u64 {
1539        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
1540        let mut z = self.0;
1541        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
1542        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
1543        z ^ (z >> 31)
1544    }
1545
1546    pub fn fill(&mut self, out: &mut [u8]) {
1547        for c in out.chunks_mut(8) {
1548            let w = self.next_u64().to_le_bytes();
1549            let n = c.len();
1550            c.copy_from_slice(&w[..n]);
1551        }
1552    }
1553}
1554
1555/// `n` distinct entries with uniformly random oids.
1556///
1557/// Uniform randomness is the property under test, not a convenience: real oids
1558/// are hashes and share no prefixes, so a generator with structure would give
1559/// the stree an unrepresentative keyspace.
1560///
1561/// **Every `OfsDelta` entry carries a non-zero `delta_base`** — the offset of
1562/// the entry immediately before it, which is a real row of the same workload —
1563/// and every other entry carries `0`. LAW 2's identity-value trap is the whole
1564/// reason: a generator that left `delta_base` at `0` everywhere would let a
1565/// layout that never wrote the column, or read it from the wrong stride, pass
1566/// every comparison in this module. It is derived from `out.last()` rather than
1567/// from `rng`, so oids, offsets, lengths and types are bit-identical to what
1568/// this generator produced before the column existed and no earlier figure is
1569/// invalidated by the workload changing under it.
1570pub fn synthetic_entries(n: usize, oid_len: usize, seed: u64) -> Vec<IndexEntry> {
1571    let mut rng = Rng(seed);
1572    let mut seen = std::collections::HashSet::with_capacity(n * 2);
1573    let mut out: Vec<IndexEntry> = Vec::with_capacity(n);
1574    let mut off = 12u64; // past a pack header
1575    while out.len() < n {
1576        let mut oid = vec![0u8; oid_len];
1577        rng.fill(&mut oid);
1578        if !seen.insert(oid.clone()) {
1579            continue;
1580        }
1581        // Length distribution roughly like a real pack: mostly small, a long
1582        // tail. The exact shape does not affect a point lookup, but it keeps
1583        // the u64 columns from being all-identical, which would let a compressor
1584        // or a branch predictor flatter one arm over the other.
1585        let len = 32 + (rng.next_u64() % 4096);
1586        let ty = ObjType::ALL[(rng.next_u64() % 6) as usize];
1587        // An ofs-delta's base is the entry before it: always an offset that some
1588        // row of this same workload really starts at, never 0, and never a
1589        // forward reference. A ref-delta's base is named by oid and has no
1590        // offset until it is resolved, so it records the 0 sentinel — as does
1591        // every whole object.
1592        let delta_base = match (ty, out.last()) {
1593            (ObjType::OfsDelta, Some(prev)) => prev.offset,
1594            _ => 0,
1595        };
1596        out.push(IndexEntry {
1597            oid,
1598            offset: off,
1599            len,
1600            obj_type: ty,
1601            uncompressed_size: len * (1 + rng.next_u64() % 5),
1602            delta_base,
1603        });
1604        off += len;
1605    }
1606    out
1607}
1608
1609
1610#[cfg(test)]
1611mod tests {
1612    use super::*;
1613
1614    /// All three arms over the same entries. Every semantic test runs against
1615    /// the triple, because "the three layouts are one index" is the claim the
1616    /// whole comparison rests on.
1617    fn arms(entries: &[IndexEntry]) -> (FourTables, OneTableFourColumns, PackedPayload) {
1618        (
1619            FourTables::build(entries).expect("A builds"),
1620            OneTableFourColumns::build(entries).expect("B builds"),
1621            PackedPayload::build(entries).expect("C builds"),
1622        )
1623    }
1624
1625    /// The core correctness claim: **the three layouts are the same index**.
1626    ///
1627    /// Asserted on applied output — the five facts of every row, plus the
1628    /// ordinal — for every present oid, for absent oids, and through the
1629    /// serial, batch, extent-only and ordinal-only paths. A row-count or an
1630    /// `is_some()` check would pass for three indexes that disagreed on every
1631    /// value.
1632    ///
1633    /// Seen RED by changing `ColumnarPayload::row_at` to read `self.len.value(i)`
1634    /// for `offset`: "layouts disagree on 80313d462e6994e9e819193e6fdbd5f8390e92e3
1635    ///   left: IndexRow { ordinal: 259, offset: 344, len: 344, .. }
1636    ///  right: IndexRow { ordinal: 259, offset: 12, len: 344, .. }".
1637    /// Restored.
1638    ///
1639    /// Seen RED a second time, for the packed arm specifically, by swapping the
1640    /// `len` and `uncompressed_size` writes in `packed_column` only, so the
1641    /// writer and the reader disagree about the record layout:
1642    /// "C disagrees with A on 80313d462e6994e9e819193e6fdbd5f8390e92e3
1643    ///   left: IndexRow { offset: 12, len: 344, uncompressed_size: 1720 }
1644    ///  right: IndexRow { offset: 12, len: 1720, uncompressed_size: 344 }".
1645    /// Restored. Note that A and B stayed green throughout — only a guard that
1646    /// compares the packed arm against them can see this class of bug.
1647    ///
1648    /// Seen RED a third time, when `delta_base` was added, by dropping
1649    /// [`FourTables`] read `COL_LEN` into `ColumnarPayload::delta_base` — the
1650    /// single most plausible way to wire a new column in wrong, since both are
1651    /// `u64` columns of the same section: "A and B disagree on
1652    /// 80313d462e6994e9e819193e6fdbd5f8390e92e3 / left: IndexRow { ordinal: 259,
1653    /// offset: 12, len: 344, obj_type: Tree, uncompressed_size: 1720,
1654    /// **delta_base: 344** } / right: IndexRow { … **delta_base: 0** }". B and C
1655    /// were right and A was wrong, and only the row-for-row comparison said so.
1656    /// Restored.
1657    #[test]
1658    fn the_three_layouts_return_identical_rows() {
1659        for &oid_len in &[20usize, 32] {
1660            let entries = synthetic_entries(500, oid_len, 0xA11CE);
1661            let (a, b, c) = arms(&entries);
1662            assert_eq!(a.len(), 500);
1663            assert_eq!(b.len(), 500);
1664            assert_eq!(c.len(), 500);
1665
1666            // Not a blind guard: the workload has to carry the column at
1667            // something other than its identity value, or every arm agreeing on
1668            // `delta_base: 0` would prove nothing about `delta_base` at all.
1669            let with_base = entries.iter().filter(|e| e.delta_base != 0).count();
1670            assert!(
1671                with_base >= 50,
1672                "only {with_base} of 500 entries carry a non-zero delta_base — this guard would \
1673                 sit on the identity value and could not see a column that was never written"
1674            );
1675
1676            let mut hits = 0usize;
1677            for e in &entries {
1678                let ra = a.lookup(&e.oid).unwrap_or_else(|| {
1679                    panic!("{} missed {}", a.name(), hex::encode(&e.oid))
1680                });
1681                let rb = b.lookup(&e.oid).unwrap_or_else(|| {
1682                    panic!("{} missed {}", b.name(), hex::encode(&e.oid))
1683                });
1684                let rc = c.lookup(&e.oid).unwrap_or_else(|| {
1685                    panic!("{} missed {}", c.name(), hex::encode(&e.oid))
1686                });
1687                assert_eq!(ra, rb, "A and B disagree on {}", hex::encode(&e.oid));
1688                assert_eq!(
1689                    ra,
1690                    rc,
1691                    "C disagrees with A on {}",
1692                    hex::encode(&e.oid)
1693                );
1694                // …and all three agree with the input, not just with each other.
1695                assert_eq!(rc.offset, e.offset);
1696                assert_eq!(rc.len, e.len);
1697                assert_eq!(rc.obj_type, e.obj_type);
1698                assert_eq!(rc.uncompressed_size, e.uncompressed_size);
1699                assert_eq!(
1700                    rc.delta_base,
1701                    e.delta_base,
1702                    "delta_base did not survive C for {}",
1703                    hex::encode(&e.oid)
1704                );
1705                assert_eq!(ra.delta_base, e.delta_base, "delta_base did not survive A");
1706                assert_eq!(rb.delta_base, e.delta_base, "delta_base did not survive B");
1707                hits += 1;
1708            }
1709            assert_eq!(hits, 500, "every entry must resolve");
1710
1711            // Absent oids: same answer everywhere, and that answer is None.
1712            let absent = synthetic_entries(200, oid_len, 0xBEEF_0000);
1713            for e in &absent {
1714                assert_eq!(a.lookup(&e.oid), None);
1715                assert_eq!(b.lookup(&e.oid), None);
1716                assert_eq!(c.lookup(&e.oid), None);
1717            }
1718
1719            // Every batch path, on a mix, positionally.
1720            let mut q: Vec<&[u8]> = Vec::new();
1721            for (i, e) in entries.iter().enumerate() {
1722                q.push(&e.oid);
1723                if i < absent.len() {
1724                    q.push(&absent[i].oid);
1725                }
1726            }
1727            let ba = a.lookup_batch(&q);
1728            let bb = b.lookup_batch(&q);
1729            let bc = c.lookup_batch(&q);
1730            assert_eq!(ba.len(), q.len());
1731            assert_eq!(ba, bb, "A/B batch paths disagree at oid_len {oid_len}");
1732            assert_eq!(ba, bc, "A/C batch paths disagree at oid_len {oid_len}");
1733            let n_hits = ba.iter().filter(|r| r.is_some()).count();
1734            assert_eq!(n_hits, 500, "expected exactly the 500 present oids to hit");
1735            for (i, r) in ba.iter().enumerate() {
1736                assert_eq!(*r, c.lookup(q[i]), "C batch/serial disagree at {i}");
1737            }
1738
1739            // The partial-row and ordinal-only paths agree with the full row.
1740            let ea = a.extents_batch(&q);
1741            let ec = c.extents_batch(&q);
1742            assert_eq!(ea, ec, "extent paths disagree");
1743            let oa = a.ordinals_batch(&q);
1744            let oc = c.ordinals_batch(&q);
1745            assert_eq!(oa, oc, "ordinal paths disagree");
1746            for i in 0..q.len() {
1747                assert_eq!(ea[i], ba[i].map(|r| (r.offset, r.len)), "extent != row at {i}");
1748                assert_eq!(oa[i], ba[i].map(|r| r.ordinal), "ordinal != row at {i}");
1749            }
1750        }
1751    }
1752
1753    /// **`delta_base` is an offset that locates a row of this very table**, in
1754    /// all three arms — which is the property an ordinal could not have.
1755    ///
1756    /// Read back through the index (never from the input entries), every
1757    /// non-zero `delta_base` is looked up against the set of `offset`s the index
1758    /// itself reports, and it has to land on one, earlier in the archive than
1759    /// the delta that names it. `offset` and `delta_base` are the same
1760    /// coordinate space, and this is the assertion that says so.
1761    ///
1762    /// Seen RED by making `synthetic_entries` write `prev.offset + 1` as the
1763    /// delta base — a value one byte off a real entry boundary, which is
1764    /// precisely how an off-by-one in a rebase or in a varint would look:
1765    /// "A: delta_base 4601 of ordinal 1256 lands on no entry offset in this
1766    /// index". Restored to `prev.offset`.
1767    ///
1768    /// Seen RED a second time, on the ordinal question itself, by writing the
1769    /// base's *row index* into the column instead of its offset:
1770    /// "A: delta_base 2 of ordinal 1256 lands on no entry offset in this index"
1771    /// — a small number that is a perfectly valid row address and an invalid
1772    /// archive address, which is §13's decision failing loudly rather than
1773    /// silently. Restored.
1774    #[test]
1775    fn delta_base_locates_a_real_entry_in_every_arm() {
1776        let entries = synthetic_entries(2000, 20, 0xDE17A);
1777        let (a, b, c) = arms(&entries);
1778
1779        // The offsets this index reports, taken from the index and not from the
1780        // input: `lookup` of every stored oid.
1781        let offsets: std::collections::HashSet<u64> =
1782            entries.iter().filter_map(|e| a.lookup(&e.oid)).map(|r| r.offset).collect();
1783        assert_eq!(offsets.len(), 2000, "every row must report a distinct offset");
1784
1785        let arms: [(&str, &dyn ObjectIndex); 3] = [("A", &a), ("B", &b), ("C", &c)];
1786        let mut checked = 0usize;
1787        for (name, idx) in arms {
1788            let mut with_base = 0usize;
1789            for e in &entries {
1790                let row = idx.lookup(&e.oid).expect("stored oid resolves");
1791                if row.delta_base == 0 {
1792                    assert_ne!(
1793                        row.obj_type,
1794                        ObjType::OfsDelta,
1795                        "{name}: an ofs-delta with no recorded base is a row that cannot be \
1796                         resolved at all"
1797                    );
1798                    continue;
1799                }
1800                with_base += 1;
1801                assert!(
1802                    offsets.contains(&row.delta_base),
1803                    "{name}: delta_base {} of ordinal {} lands on no entry offset in this index",
1804                    row.delta_base,
1805                    row.ordinal
1806                );
1807                assert!(
1808                    row.delta_base < row.offset,
1809                    "{name}: delta_base {} is not earlier in the archive than the delta at {}",
1810                    row.delta_base,
1811                    row.offset
1812                );
1813            }
1814            assert!(
1815                with_base > 100,
1816                "{name}: only {with_base} of 2000 rows carried a base — nothing was proven"
1817            );
1818            checked += with_base;
1819        }
1820        assert!(checked > 300, "three arms must each have checked real bases");
1821    }
1822
1823    /// The two column scans return the same answer from all three arms, and
1824    /// that answer is the one computed straight from the input entries.
1825    ///
1826    /// This is the guard that makes the scan half of the benchmark meaningful:
1827    /// a strided reader that skipped rows would be very fast and very wrong.
1828    ///
1829    /// Seen RED by advancing `PackedPayload::sum_uncompressed` by `PACKED_LEN + 8`
1830    /// instead of `PACKED_LEN`: "C sum_uncompressed: left 8826373087920709042,
1831    /// right 12349770". The stride slipped out of phase, so it summed bytes
1832    /// straddling field boundaries — a fast, wrong scan that no timing
1833    /// assertion would ever have noticed. Restored.
1834    #[test]
1835    fn column_scans_agree_across_arms_and_with_the_input() {
1836        let entries = synthetic_entries(2000, 20, 0x5CA7);
1837        let (a, b, c) = arms(&entries);
1838
1839        let want: u64 = entries.iter().map(|e| e.uncompressed_size).sum();
1840        assert_eq!(a.sum_uncompressed(), want, "A sum_uncompressed");
1841        assert_eq!(b.sum_uncompressed(), want, "B sum_uncompressed");
1842        assert_eq!(c.sum_uncompressed(), want, "C sum_uncompressed");
1843        assert!(want > 0, "the workload must actually carry sizes");
1844
1845        let mut total = 0usize;
1846        for t in ObjType::ALL {
1847            let want = entries.iter().filter(|e| e.obj_type == t).count();
1848            assert_eq!(a.count_type(t), want, "A count_type({})", t.as_str());
1849            assert_eq!(b.count_type(t), want, "B count_type({})", t.as_str());
1850            assert_eq!(c.count_type(t), want, "C count_type({})", t.as_str());
1851            assert!(want > 0, "{} must appear in the workload", t.as_str());
1852            total += want;
1853        }
1854        assert_eq!(total, entries.len(), "the six types must partition the index");
1855    }
1856
1857    /// The packed record is 33 bytes laid out exactly as documented, read
1858    /// straight out of the IPC buffer rather than through the accessor that is
1859    /// under test. A layout that changed silently would still round-trip
1860    /// through its own reader; this pins it to the bytes.
1861    ///
1862    /// Seen RED by moving the type byte from offset 16 to offset 24 in
1863    /// `packed_column`: "row 0 byte 16 is 0 but the type code is 6". Restored.
1864    ///
1865    /// Seen RED again for the fifth field, by writing `e.offset` where
1866    /// `packed_column` writes `e.delta_base`: "row 0 bytes 25..33 must be the
1867    /// delta base / left: 368 / right: 12". Restored. Writing the *offset*
1868    /// there is the failure mode worth catching: it is a plausible archive
1869    /// offset, it is even a real entry boundary, so nothing downstream would
1870    /// look odd — only a comparison against the input entry tells the two
1871    /// apart.
1872    #[test]
1873    fn the_packed_record_is_the_documented_33_bytes() {
1874        let entries = synthetic_entries(64, 20, 0x9F);
1875        let c = PackedPayload::build(&entries).unwrap();
1876        assert_eq!(PACKED_LEN, 33);
1877        assert_eq!(PACKED_LEN, 8 + 8 + 1 + 8 + 8, "offset+len+type+size+delta_base");
1878
1879        let mut sorted: Vec<&IndexEntry> = entries.iter().collect();
1880        sorted.sort_by(|x, y| x.oid.cmp(&y.oid));
1881        let d = c.payload.value_data();
1882        assert_eq!(d.len(), 64 * PACKED_LEN, "payload column is not 33 bytes per row");
1883        assert!(
1884            sorted.iter().filter(|e| e.delta_base != 0).count() >= 4,
1885            "the fixture must carry real delta bases or bytes 25..33 are all zero"
1886        );
1887
1888        for (i, e) in sorted.iter().enumerate() {
1889            let r = &d[i * PACKED_LEN..(i + 1) * PACKED_LEN];
1890            assert_eq!(
1891                u64::from_le_bytes(r[0..8].try_into().unwrap()),
1892                e.offset,
1893                "row {i} bytes 0..8 must be the offset"
1894            );
1895            assert_eq!(
1896                u64::from_le_bytes(r[8..16].try_into().unwrap()),
1897                e.len,
1898                "row {i} bytes 8..16 must be the len"
1899            );
1900            assert_eq!(
1901                r[16],
1902                e.obj_type.code(),
1903                "row {i} byte 16 is {} but the type code is {}",
1904                r[16],
1905                e.obj_type.code()
1906            );
1907            assert_eq!(
1908                u64::from_le_bytes(r[17..25].try_into().unwrap()),
1909                e.uncompressed_size,
1910                "row {i} bytes 17..25 must be the uncompressed size"
1911            );
1912            assert_eq!(
1913                u64::from_le_bytes(r[25..33].try_into().unwrap()),
1914                e.delta_base,
1915                "row {i} bytes 25..33 must be the delta base"
1916            );
1917        }
1918    }
1919
1920    /// The whole premise of the third arm, asserted as a byte count rather than
1921    /// as an argument: a full-row fetch touches **one** payload buffer of 33
1922    /// bytes per row, where the columnar arms touch five buffers whose bases are
1923    /// megabytes apart.
1924    ///
1925    /// Seen RED by asserting the columnar arm's payload buffers were within 25
1926    /// bytes of each other: "offset and size buffers are 1737664 bytes apart,
1927    /// not adjacent" at 100 000 rows. That distance is the fact the packed arm
1928    /// exists to change. Restored to assert the true distances.
1929    #[test]
1930    fn a_packed_row_is_one_stride_and_a_columnar_row_is_five() {
1931        let entries = synthetic_entries(100_000, 20, 0x0FF5);
1932        let (_, b, c) = arms(&entries);
1933
1934        // Columnar: five payload buffers, and consecutive facts of ONE row are
1935        // ~800 kB apart because each column is 100000 × 8 bytes long.
1936        let base = |s: &[u8]| s.as_ptr() as usize;
1937        let off = base(b.cols.offset.values().inner().as_slice());
1938        let len = base(b.cols.len.values().inner().as_slice());
1939        let size = base(b.cols.size.values().inner().as_slice());
1940        let dbase = base(b.cols.delta_base.values().inner().as_slice());
1941        assert!(
1942            len.abs_diff(off) >= 800_000,
1943            "offset and len columns are only {} bytes apart — this arm is supposed to be \
1944             columnar",
1945            len.abs_diff(off)
1946        );
1947        assert!(size.abs_diff(off) >= 800_000);
1948        assert!(
1949            dbase.abs_diff(off) >= 800_000 && dbase.abs_diff(size) >= 800_000,
1950            "delta_base is {} bytes from offset and {} from size — the fifth fact must be its \
1951             own stride, not a field inside another column",
1952            dbase.abs_diff(off),
1953            dbase.abs_diff(size)
1954        );
1955
1956        // Packed: the five facts of one row are inside 33 consecutive bytes.
1957        let d = c.payload.value_data();
1958        assert_eq!(d.len(), 100_000 * PACKED_LEN);
1959        let row7 = &d[7 * PACKED_LEN..8 * PACKED_LEN];
1960        let r = c.lookup(&entries.iter().min_by_key(|e| e.oid.clone()).unwrap().oid);
1961        assert!(r.is_some(), "the lexicographically first oid must resolve");
1962        // Every fact of row 7 is readable from those 33 bytes alone.
1963        let from_bytes = IndexRow {
1964            ordinal: 7,
1965            offset: u64::from_le_bytes(row7[0..8].try_into().unwrap()),
1966            len: u64::from_le_bytes(row7[8..16].try_into().unwrap()),
1967            obj_type: ObjType::from_code(row7[16]).unwrap(),
1968            uncompressed_size: u64::from_le_bytes(row7[17..25].try_into().unwrap()),
1969            delta_base: u64::from_le_bytes(row7[25..33].try_into().unwrap()),
1970        };
1971        assert_eq!(
1972            from_bytes,
1973            c.row_at(7),
1974            "one 33-byte slice must carry the whole row"
1975        );
1976    }
1977
1978    /// The ordinal is the oid-lexicographic rank in **all three** arms, and it
1979    /// is the join key `FourTables` relies on. Asserted against an
1980    /// independently sorted copy of the input rather than against another arm.
1981    ///
1982    /// Seen RED by making `oid_order` sort by `offset` instead of by `oid`:
1983    /// "A ordinal is not the rank — left: 206, right: 0" on the first row.
1984    /// Restored.
1985    #[test]
1986    fn ordinals_are_the_oid_lexicographic_rank_in_every_arm() {
1987        let entries = synthetic_entries(300, 20, 7);
1988        let (a, b, c) = arms(&entries);
1989        let mut sorted: Vec<&IndexEntry> = entries.iter().collect();
1990        sorted.sort_by(|x, y| x.oid.cmp(&y.oid));
1991        for (rank, e) in sorted.iter().enumerate() {
1992            let ra = a.lookup(&e.oid).unwrap();
1993            let rb = b.lookup(&e.oid).unwrap();
1994            let rc = c.lookup(&e.oid).unwrap();
1995            assert_eq!(ra.ordinal as usize, rank, "A ordinal is not the rank");
1996            assert_eq!(rb.ordinal as usize, rank, "B ordinal is not the rank");
1997            assert_eq!(rc.ordinal as usize, rank, "C ordinal is not the rank");
1998            // The oid column of each arm, read at that ordinal, is that oid.
1999            assert_eq!(a.oid_column().value(rank), e.oid.as_slice());
2000            assert_eq!(b.oid_column().value(rank), e.oid.as_slice());
2001            assert_eq!(c.oid_column().value(rank), e.oid.as_slice());
2002        }
2003    }
2004
2005    /// Zero-copy, asserted by pointer containment rather than by hope, in all
2006    /// three arms.
2007    ///
2008    /// `decode_ipc` uses `with_require_alignment(true)`, so a misaligned buffer
2009    /// is an error, not a silent re-allocation. This proves the positive side:
2010    /// each array's bytes are *inside* the IPC buffer it came from.
2011    ///
2012    /// Seen RED by swapping `decode_ipc_buffer`'s `StreamDecoder` for the
2013    /// high-level `StreamReader` over a `Cursor` (which owns its own
2014    /// allocations): "FourTables columns were copied out of IPC". Restored.
2015    ///
2016    /// A weaker edit did **not** turn it red and is worth recording: replacing
2017    /// the `MutableBuffer` copy with `Buffer::from_vec(bytes.to_vec())` left the
2018    /// test green, because glibc happened to hand back an 8-aligned allocation
2019    /// for a ~57 kB `Vec`. Alignment by luck is not alignment, which is what
2020    /// [`require_alignment_is_load_bearing`] pins down separately.
2021    #[test]
2022    fn every_column_is_a_zero_copy_view_into_its_ipc_section() {
2023        let entries = synthetic_entries(1000, 32, 11);
2024        let (a, b, c) = arms(&entries);
2025        assert!(a.column_is_inside_ipc(), "FourTables columns were copied out of IPC");
2026        assert!(b.column_is_inside_ipc(), "OneTable columns were copied out of IPC");
2027        assert!(c.column_is_inside_ipc(), "PackedPayload columns were copied out of IPC");
2028
2029        // And the payload really is there: 1000 × 32 oid bytes + 1000 × 8 for
2030        // each of offset/len/size/delta_base + 1000 × 1 type = 65000 bytes
2031        // minimum.
2032        assert!(
2033            b.ipc_bytes() >= 65_000,
2034            "one-table section is {} bytes, too small to hold the payload",
2035            b.ipc_bytes()
2036        );
2037        assert!(a.ipc_bytes() >= 65_000);
2038        assert!(c.ipc_bytes() >= 65_000);
2039    }
2040
2041    /// `with_require_alignment(true)` is the thing that makes "zero-copy" a
2042    /// contract instead of a hope: with it off, arrow silently allocates a fresh
2043    /// aligned buffer and copies, and the only symptom is that opening a large
2044    /// index got slower and doubled its peak memory.
2045    ///
2046    /// The same IPC bytes are decoded twice — once from a 64-byte-aligned
2047    /// buffer, once from the identical bytes sitting at offset 4 of the same
2048    /// allocation. The first must succeed and be a view; the second must be
2049    /// **refused**.
2050    ///
2051    /// Seen RED by dropping `.with_require_alignment(true)` from
2052    /// `decode_ipc_buffer`: the misaligned decode returned `Ok` and the test
2053    /// panicked with "a misaligned buffer must be refused, not silently
2054    /// copied". Restored.
2055    #[test]
2056    fn require_alignment_is_load_bearing() {
2057        let entries = synthetic_entries(64, 20, 77);
2058        let order = oid_order(&entries);
2059        let c = columns(&entries, &order, 20);
2060        let batch = RecordBatch::try_new(
2061            extent_schema(),
2062            vec![Arc::new(c.offset), Arc::new(c.len), Arc::new(c.delta_base)],
2063        )
2064        .unwrap();
2065        let ipc = to_ipc(&batch).unwrap();
2066
2067        // Aligned: 64 bytes of padding then the stream, sliced back to the
2068        // stream's start — the pointer is 64-aligned.
2069        let mut mb = MutableBuffer::with_capacity(64 + ipc.len());
2070        mb.extend_from_slice(&[0u8; 64]);
2071        mb.extend_from_slice(&ipc);
2072        let padded: Buffer = mb.into();
2073        let (owner, ok) = decode_ipc_buffer(padded.slice(64)).expect("aligned decode must work");
2074        assert_eq!(ok.num_rows(), 64, "the aligned decode must yield all 64 rows");
2075        assert!(inside(&owner, ok.column(0).to_data().buffers()[0].as_slice()));
2076
2077        // Misaligned by 4: byte-identical stream, 4-byte-offset pointer.
2078        let mut mb = MutableBuffer::with_capacity(4 + ipc.len());
2079        mb.extend_from_slice(&[0u8; 4]);
2080        mb.extend_from_slice(&ipc);
2081        let skewed: Buffer = mb.into();
2082        let err = match decode_ipc_buffer(skewed.slice(4)) {
2083            Ok(_) => panic!("a misaligned buffer must be refused, not silently copied"),
2084            Err(e) => e.to_string(),
2085        };
2086        assert!(
2087            err.contains("Misaligned"),
2088            "the refusal must name the misalignment, got: {err}"
2089        );
2090    }
2091
2092    /// Four sections cost strictly more IPC framing than one, and the amount is
2093    /// asserted as a byte count, not as "greater than".
2094    ///
2095    /// Each Arrow IPC stream carries a schema message, a record-batch message
2096    /// header and an end-of-stream marker. Three extra copies of that is the
2097    /// entire structural overhead of layout A, and on a tiny index it dominates.
2098    ///
2099    /// Seen RED by asserting `>= 900`: "expected ≥900 bytes of extra framing
2100    /// for three extra sections, got 728 (A=4704 B=3976)". The bound below is
2101    /// the one the measurement supports — 728 bytes, ~243 per extra section,
2102    /// which is the schema + batch-header + EOS framing and not payload.
2103    #[test]
2104    fn four_sections_pay_three_extra_ipc_frames() {
2105        let entries = synthetic_entries(64, 20, 3);
2106        let (a, b, _) = arms(&entries);
2107        let extra = a.ipc_bytes() as i64 - b.ipc_bytes() as i64;
2108        assert!(
2109            (600..1200).contains(&extra),
2110            "expected 600..1200 bytes of extra framing for three extra sections, got {extra} \
2111             (A={} B={})",
2112            a.ipc_bytes(),
2113            b.ipc_bytes()
2114        );
2115        // The four sections are separately sized and the oid one is the biggest.
2116        let lens = a.ipc_section_lens();
2117        assert_eq!(lens.len(), 4);
2118        assert!(lens[0] > lens[2], "oid section {} must exceed type section {}", lens[0], lens[2]);
2119    }
2120
2121    /// The packed arm stores the same *payload* bytes — 33 per row against
2122    /// 8 + 8 + 1 + 8 + 8 — so nothing in the timing comparison is a
2123    /// memory-footprint effect in disguise. Its IPC **section** is nonetheless
2124    /// smaller, and the amount is asserted as a scaling law rather than as a
2125    /// constant, at two sizes, so it is attributed rather than hand-waved.
2126    ///
2127    /// Four fewer columns is four fewer per-column IPC buffers, and the
2128    /// saving grows linearly with row count at about `4 · n/8` bytes. It was
2129    /// `3 · n/8` — 38 016 B at 100 000 rows — before `delta_base` gave the
2130    /// columnar arm a fifth payload column. That is the only footprint
2131    /// difference between the three arms.
2132    ///
2133    /// Seen RED by asserting the two sections were within 4096 bytes of each
2134    /// other: "packed payload is 4525512 bytes against 4563528 columnar", which
2135    /// is what sent me to count buffers instead of guessing. Seen RED a second
2136    /// time by asserting the saving was *constant* across the two sizes:
2137    /// "saving did not scale: 38016 at 100000 rows, 75456 at 200000". Seen RED
2138    /// a third time by leaving the `3 · n/8` bound in place after the fifth
2139    /// column landed: "at 100000 rows the saving is 50560 B, not the ~37500 B
2140    /// that four fewer columns accounts for" — 50 560 B is `4 · n/8` plus
2141    /// framing, so the bound is counting real buffers rather than tracking a
2142    /// moving target.
2143    #[test]
2144    fn the_packed_arm_holds_the_same_payload_but_a_smaller_section() {
2145        let mut savings = Vec::new();
2146        for &n in &[100_000usize, 200_000] {
2147            let entries = synthetic_entries(n, 20, 0xBEE5);
2148            let (_, b, c) = arms(&entries);
2149
2150            // The payload itself is byte-for-byte the same size.
2151            let payload_bytes = n * (8 + 8 + 1 + 8 + 8);
2152            assert_eq!(c.payload.value_data().len(), payload_bytes);
2153            assert_eq!(c.payload.value_data().len(), n * PACKED_LEN);
2154
2155            let saving = b.ipc_bytes() as i64 - c.ipc_bytes() as i64;
2156            assert!(
2157                saving > 0,
2158                "the two-column section ({}) must not be larger than the six-column one ({})",
2159                c.ipc_bytes(),
2160                b.ipc_bytes()
2161            );
2162            // Four fewer columns, at roughly n/8 bytes of per-column buffer each.
2163            let expect = 4 * (n as i64) / 8;
2164            assert!(
2165                (expect..expect + 4096).contains(&saving),
2166                "at {n} rows the saving is {saving} B, not the ~{expect} B that four fewer \
2167                 columns accounts for"
2168            );
2169            savings.push(saving);
2170        }
2171        assert!(
2172            savings[1] > savings[0] * 3 / 2,
2173            "saving did not scale: {} at 100000 rows, {} at 200000",
2174            savings[0],
2175            savings[1]
2176        );
2177    }
2178
2179    /// LAW 2 — the 8-byte prefix collision, carried through all three arms.
2180    ///
2181    /// Two oids sharing their first eight bytes share one stree key, so the tree
2182    /// alone cannot tell them apart. Every arm must still return each oid's own
2183    /// four facts, and a third oid on the same prefix that was never inserted
2184    /// must miss.
2185    ///
2186    /// Seen RED by replacing `OidResolver::ordinal`'s verified `tree.lookup`
2187    /// with the unverified `tree.candidate_run(key_for_oid(oid)).start` — i.e.
2188    /// trusting the 8-byte prefix: "collision resolved to the wrong row —
2189    /// left: 1000, right: 2000". Both colliding oids came back as the first
2190    /// candidate. Restored.
2191    #[test]
2192    fn a_prefix_collision_resolves_to_the_right_row_in_every_arm() {
2193        let prefix = [0xde, 0xad, 0xbe, 0xef, 0x01, 0x02, 0x03, 0x04];
2194        // The two colliding entries carry *different* delta bases, so a column
2195        // read at the wrong ordinal shows up here too and not only in `offset`.
2196        let mk = |last: u8, off: u64, ty: ObjType| {
2197            let mut oid = vec![0u8; 20];
2198            oid[..8].copy_from_slice(&prefix);
2199            oid[8] = last;
2200            IndexEntry {
2201                oid,
2202                offset: off,
2203                len: 10,
2204                obj_type: ty,
2205                uncompressed_size: off * 2,
2206                delta_base: off / 2,
2207            }
2208        };
2209        let mut entries = vec![mk(0xaa, 1000, ObjType::Commit), mk(0xbb, 2000, ObjType::OfsDelta)];
2210        entries.extend(synthetic_entries(200, 20, 99));
2211        let (a, b, c) = arms(&entries);
2212
2213        for (last, off, ty) in [(0xaau8, 1000u64, ObjType::Commit), (0xbb, 2000, ObjType::OfsDelta)]
2214        {
2215            let oid = mk(last, off, ty).oid;
2216            let ra = a.lookup(&oid).expect("colliding oid must resolve in A");
2217            let rb = b.lookup(&oid).expect("colliding oid must resolve in B");
2218            let rc = c.lookup(&oid).expect("colliding oid must resolve in C");
2219            assert_eq!(ra, rb);
2220            assert_eq!(ra, rc);
2221            assert_eq!(ra.offset, off, "collision resolved to the wrong row");
2222            assert_eq!(ra.obj_type, ty);
2223            assert_eq!(ra.delta_base, off / 2, "collision resolved to the wrong delta base");
2224        }
2225        let never = mk(0xcc, 0, ObjType::Blob).oid;
2226        assert_eq!(a.lookup(&never), None, "unstored oid on a colliding prefix must miss");
2227        assert_eq!(b.lookup(&never), None);
2228        assert_eq!(c.lookup(&never), None);
2229    }
2230
2231    /// All six pack type codes survive the round trip in every arm, including
2232    /// the two delta kinds that are the reason this fact is stored at all.
2233    ///
2234    /// Seen RED by mapping `ObjType::RefDelta` to code 6 in `code()`, colliding
2235    /// with `OfsDelta`: "type did not survive the column — left: OfsDelta,
2236    /// right: RefDelta". Restored.
2237    #[test]
2238    fn all_six_pack_types_round_trip_including_the_deltas() {
2239        let entries: Vec<IndexEntry> = ObjType::ALL
2240            .iter()
2241            .enumerate()
2242            .map(|(i, &t)| {
2243                let mut oid = vec![0u8; 32];
2244                oid[0] = i as u8 * 17;
2245                oid[31] = i as u8;
2246                IndexEntry {
2247                    oid,
2248                    offset: 100 + i as u64,
2249                    len: 5,
2250                    obj_type: t,
2251                    uncompressed_size: 900 + i as u64,
2252                    // Only the two delta codes carry a base, which is the
2253                    // relationship the type column exists to express.
2254                    delta_base: match t {
2255                        ObjType::OfsDelta => 100,
2256                        _ => 0,
2257                    },
2258                }
2259            })
2260            .collect();
2261        let (a, b, c) = arms(&entries);
2262        let mut seen: Vec<ObjType> = Vec::new();
2263        for e in &entries {
2264            let ra = a.lookup(&e.oid).unwrap();
2265            assert_eq!(ra, b.lookup(&e.oid).unwrap());
2266            assert_eq!(ra, c.lookup(&e.oid).unwrap());
2267            assert_eq!(ra.obj_type, e.obj_type, "type did not survive the column");
2268            seen.push(ra.obj_type);
2269        }
2270        assert_eq!(seen, ObjType::ALL.to_vec(), "all six codes must be distinct");
2271        assert_eq!(ObjType::from_code(0), None);
2272        assert_eq!(ObjType::from_code(5), None, "git leaves 5 unused; it must not be mapped");
2273        assert_eq!(ObjType::from_code(8), None);
2274    }
2275
2276    /// An empty index and a one-row index are clean, not panics, in every arm.
2277    ///
2278    /// Seen RED by replacing `validate`'s empty-input `Ok(GitHashKind::Sha1)`
2279    /// with `bail!("an empty index")`: "A builds: an empty index" — every arm
2280    /// failed to construct at all. Restored.
2281    #[test]
2282    fn degenerate_sizes_are_clean_in_every_arm() {
2283        let (a, b, c) = arms(&[]);
2284        assert!(a.is_empty() && b.is_empty() && c.is_empty());
2285        let probe = vec![7u8; 20];
2286        assert_eq!(a.lookup(&probe), None);
2287        assert_eq!(b.lookup(&probe), None);
2288        assert_eq!(c.lookup(&probe), None);
2289        assert_eq!(c.lookup_batch(&[&probe[..]]), vec![None]);
2290        assert_eq!(c.extents_batch(&[&probe[..]]), vec![None]);
2291        // A scan over an empty index is 0, not a panic or a wrap.
2292        assert_eq!(c.sum_uncompressed(), 0);
2293        assert_eq!(c.count_type(ObjType::Blob), 0);
2294
2295        let one = synthetic_entries(1, 20, 5);
2296        let (a, b, c) = arms(&one);
2297        assert_eq!(a.lookup(&one[0].oid).unwrap(), b.lookup(&one[0].oid).unwrap());
2298        assert_eq!(a.lookup(&one[0].oid).unwrap(), c.lookup(&one[0].oid).unwrap());
2299        assert_eq!(c.lookup(&one[0].oid).unwrap().offset, one[0].offset);
2300        assert_eq!(c.sum_uncompressed(), one[0].uncompressed_size);
2301    }
2302
2303    /// A wrong-width oid is a miss, never a panic and never a wrong row —
2304    /// the query side of P-4.
2305    ///
2306    /// The width check inside `oid_index::lookup` is only a fast path; what
2307    /// actually makes this true is the **full-oid compare**, because
2308    /// `key_for_oid` zero-pads and an 8-byte truncation of a stored oid
2309    /// therefore lands on that oid's key. Seen RED by the same
2310    /// unverified-`candidate_run` edit as
2311    /// [`a_prefix_collision_resolves_to_the_right_row_in_every_arm`]:
2312    /// "a 8-byte oid must miss — left: Some(IndexRow { ordinal: 47, offset: 12,
2313    /// len: 1505, obj_type: RefDelta, uncompressed_size: 3010 }), right: None".
2314    /// Restored.
2315    #[test]
2316    fn a_wrong_width_oid_misses_in_every_arm() {
2317        let entries = synthetic_entries(64, 20, 21);
2318        let (a, b, c) = arms(&entries);
2319        let short = &entries[0].oid[..8];
2320        let mut long = entries[0].oid.clone();
2321        long.extend_from_slice(&[0u8; 12]);
2322        for q in [short, &long[..]] {
2323            assert_eq!(a.lookup(q), None, "a {}-byte oid must miss", q.len());
2324            assert_eq!(b.lookup(q), None);
2325            assert_eq!(c.lookup(q), None);
2326        }
2327        assert_eq!(a.lookup_batch(&[short, &long]), vec![None, None]);
2328        assert_eq!(b.lookup_batch(&[short, &long]), vec![None, None]);
2329        assert_eq!(c.lookup_batch(&[short, &long]), vec![None, None]);
2330    }
2331
2332    /// A duplicate oid, or a mix of sha1 and sha256, is refused at build.
2333    /// Silently keeping one of two identical oids would give the arms different
2334    /// ordinals for the same object and make every later comparison a lie.
2335    ///
2336    /// Seen RED by short-circuiting the duplicate scan in `validate` with
2337    /// `if false && …`: the build succeeded and the test panicked with
2338    /// "a duplicate oid must be refused at build". Restored.
2339    #[test]
2340    fn build_refuses_duplicates_and_mixed_widths() {
2341        fn why<T>(r: Result<T>, what: &str) -> String {
2342            match r {
2343                Ok(_) => panic!("{what} must be refused at build"),
2344                Err(e) => e.to_string(),
2345            }
2346        }
2347        let mut dup = synthetic_entries(4, 20, 1);
2348        dup.push(dup[0].clone());
2349        let err = why(FourTables::build(&dup), "a duplicate oid");
2350        assert!(err.contains("duplicate oid"), "{err}");
2351        assert!(OneTableFourColumns::build(&dup).is_err());
2352        assert!(PackedPayload::build(&dup).is_err());
2353
2354        let mut mixed = synthetic_entries(4, 20, 2);
2355        mixed.push(synthetic_entries(1, 32, 3).pop().unwrap());
2356        let err = why(PackedPayload::build(&mixed), "a mixed-width index");
2357        assert!(err.contains("mixed oid widths"), "{err}");
2358        assert!(FourTables::build(&mixed).is_err());
2359        assert!(OneTableFourColumns::build(&mixed).is_err());
2360    }
2361
2362    /// Every arm is `Send + Sync`, which is what lets a server share one index
2363    /// across connection handlers. A compile-time assertion, plus an actual
2364    /// cross-thread lookup so it is not only a type-level claim.
2365    ///
2366    /// Seen RED by dropping `Send + Sync` from the `ObjectIndex` supertrait
2367    /// list: "error[E0277]: `dyn index_layout::ObjectIndex` cannot be shared
2368    /// between threads safely" and the same for `Send` — the crate stopped
2369    /// compiling. Restored.
2370    #[test]
2371    fn an_index_can_be_shared_across_threads() {
2372        fn assert_send_sync<T: Send + Sync>() {}
2373        assert_send_sync::<FourTables>();
2374        assert_send_sync::<OneTableFourColumns>();
2375        assert_send_sync::<PackedPayload>();
2376
2377        let entries = synthetic_entries(256, 20, 42);
2378        let a: Arc<dyn ObjectIndex> = Arc::new(FourTables::build(&entries).unwrap());
2379        let b: Arc<dyn ObjectIndex> = Arc::new(OneTableFourColumns::build(&entries).unwrap());
2380        let c: Arc<dyn ObjectIndex> = Arc::new(PackedPayload::build(&entries).unwrap());
2381        let oids: Vec<Vec<u8>> = entries.iter().map(|e| e.oid.clone()).collect();
2382        let mut handles = Vec::new();
2383        for idx in [a, b, c] {
2384            let oids = oids.clone();
2385            handles.push(std::thread::spawn(move || {
2386                let refs: Vec<&[u8]> = oids.iter().map(|o| o.as_slice()).collect();
2387                idx.lookup_batch(&refs).iter().filter(|r| r.is_some()).count()
2388            }));
2389        }
2390        for h in handles {
2391            assert_eq!(h.join().unwrap(), 256, "every oid must resolve off-thread");
2392        }
2393    }
2394}