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//! ## Rickard 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 `/home/rickard/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//! `/home/rickard/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
422// ── shared machinery: both arms are built from exactly this ───────────────────
423
424/// Column names, one place, so the two arms cannot drift apart on spelling.
425pub const COL_OID: &str = "oid";
426pub const COL_OFFSET: &str = "offset";
427pub const COL_LEN: &str = "len";
428pub const COL_TYPE: &str = "object_type";
429pub const COL_SIZE: &str = "uncompressed_size";
430pub const COL_DELTA_BASE: &str = "delta_base";
431
432/// The six Arrow arrays that carry the five facts, in oid-lexicographic order.
433/// The byte extent is one fact in two columns because that is what it is —
434/// `(offset, len)` — and splitting it lets a scan of just the offsets stay
435/// contiguous.
436pub struct Columns {
437 pub oid: FixedSizeBinaryArray,
438 pub offset: UInt64Array,
439 pub len: UInt64Array,
440 pub obj_type: UInt8Array,
441 pub size: UInt64Array,
442 /// Archive offset of the base entry, `0` for none. Same coordinate space as
443 /// `offset`, which is what makes a whole-column comparison against the
444 /// `offset` column meaningful (a delta's base is an entry in this table).
445 pub delta_base: UInt64Array,
446}
447
448/// Sort indices of `entries` into oid-lexicographic order, which is also the
449/// ordinal order and the order `oid_index::build_section` puts its keys in.
450///
451/// Ties on the full oid are impossible in a well-formed index and are checked
452/// for in [`validate`] rather than being silently deduplicated.
453fn oid_order(entries: &[IndexEntry]) -> Vec<u32> {
454 let mut order: Vec<u32> = (0..entries.len() as u32).collect();
455 order.sort_unstable_by(|&a, &b| entries[a as usize].oid.cmp(&entries[b as usize].oid));
456 order
457}
458
459/// Reject the two things that would make an index silently wrong: mixed oid
460/// widths, and a duplicate oid (which would give one object two ordinals and
461/// make the two arms disagree on which one a lookup returns).
462fn validate(entries: &[IndexEntry], order: &[u32]) -> Result<GitHashKind> {
463 let Some(first) = entries.first() else {
464 // An empty index is legitimate (an empty push) and its hash kind is
465 // arbitrary; sha1 keeps the section 20-byte shaped.
466 return Ok(GitHashKind::Sha1);
467 };
468 let hash = match first.oid.len() {
469 20 => GitHashKind::Sha1,
470 32 => GitHashKind::Sha256,
471 n => bail!("oid width {n} is neither sha1 (20) nor sha256 (32)"),
472 };
473 for e in entries {
474 if e.oid.len() != hash.oid_len() {
475 bail!(
476 "mixed oid widths: {} and {} in one index",
477 hash.oid_len(),
478 e.oid.len()
479 );
480 }
481 }
482 for w in order.windows(2) {
483 if entries[w[0] as usize].oid == entries[w[1] as usize].oid {
484 bail!(
485 "duplicate oid {} — one object cannot hold two ordinals",
486 hex::encode(&entries[w[0] as usize].oid)
487 );
488 }
489 }
490 Ok(hash)
491}
492
493/// The `stree` oid keyspace, shared verbatim by both arms.
494///
495/// `lookup_row` is set to the ordinal here. That is not a redefinition of the
496/// field: [`crate::oid_index::build_section`] is the lower-level API and its
497/// contract lets the caller choose what row an oid points at. This index's rows
498/// *are* its ordinals, and both arms use the ordinal, so nothing is lost.
499pub struct OidResolver {
500 tree: GitOidIndex,
501 section_bytes: usize,
502}
503
504impl OidResolver {
505 fn build(entries: &[IndexEntry], order: &[u32], hash: GitHashKind) -> Result<Self> {
506 Self::build_with(entries, order, hash, OidLayout::default())
507 }
508
509 /// [`build`](Self::build) with the section's cache-line layout chosen by the
510 /// caller. Only `PackedPayload::build_with_oid_layout` uses it; see there.
511 fn build_with(
512 entries: &[IndexEntry],
513 order: &[u32],
514 hash: GitHashKind,
515 layout: OidLayout,
516 ) -> Result<Self> {
517 let oid_entries: Vec<OidEntry> = order
518 .iter()
519 .enumerate()
520 .map(|(rank, &i)| OidEntry {
521 oid: entries[i as usize].oid.clone(),
522 lookup_row: rank as u64,
523 ordinal: rank as u32,
524 })
525 .collect();
526 let section = build_section_with_layout(&oid_entries, hash, layout)?;
527 let section_bytes = section.len();
528 // `parse_as`, not `parse`: `Compact64Alloc` is a reader-side allocation
529 // choice that the section's bytes cannot express.
530 Ok(Self { tree: GitOidIndex::parse_as(section, layout)?, section_bytes })
531 }
532
533 #[inline]
534 fn ordinal(&self, oid: &[u8]) -> Option<u32> {
535 self.tree.lookup(oid).map(|h| h.ordinal)
536 }
537
538 #[inline]
539 fn ordinals(&self, oids: &[&[u8]]) -> Vec<Option<u32>> {
540 self.tree
541 .lookup_batch(oids)
542 .into_iter()
543 .map(|h| h.map(|h| h.ordinal))
544 .collect()
545 }
546}
547
548/// Materialise the five arrays from `entries` in `order`.
549///
550/// Both arms call this and nothing else, so any difference the bench reports is
551/// a difference of IPC packing, not of array construction.
552pub fn columns(entries: &[IndexEntry], order: &[u32], oid_len: usize) -> Columns {
553 let n = order.len();
554 let mut offset: Vec<u64> = Vec::with_capacity(n);
555 let mut len: Vec<u64> = Vec::with_capacity(n);
556 let mut ty: Vec<u8> = Vec::with_capacity(n);
557 let mut size: Vec<u64> = Vec::with_capacity(n);
558 let mut delta_base: Vec<u64> = Vec::with_capacity(n);
559 for &i in order {
560 let e = &entries[i as usize];
561 offset.push(e.offset);
562 len.push(e.len);
563 ty.push(e.obj_type.code());
564 size.push(e.uncompressed_size);
565 delta_base.push(e.delta_base);
566 }
567 Columns {
568 oid: oid_column(entries, order, oid_len),
569 offset: UInt64Array::new(ScalarBuffer::from(offset), None),
570 len: UInt64Array::new(ScalarBuffer::from(len), None),
571 obj_type: UInt8Array::new(ScalarBuffer::from(ty), None),
572 size: UInt64Array::new(ScalarBuffer::from(size), None),
573 delta_base: UInt64Array::new(ScalarBuffer::from(delta_base), None),
574 }
575}
576
577/// The oid column alone. Every arm stores it, and no arm packs it into the
578/// payload: the oid is the *key* the stree resolves against, not one of the
579/// facts a resolved lookup fetches, so putting it next to the payload would
580/// widen every payload read for a field nobody reads at lookup time.
581pub fn oid_column(entries: &[IndexEntry], order: &[u32], oid_len: usize) -> FixedSizeBinaryArray {
582 let mut bytes: Vec<u8> = Vec::with_capacity(order.len() * oid_len);
583 for &i in order {
584 bytes.extend_from_slice(&entries[i as usize].oid);
585 }
586 FixedSizeBinaryArray::new(oid_len as i32, Buffer::from_vec(bytes), None)
587}
588
589/// The five facts of one object, packed little-endian into `PACKED_LEN` bytes.
590///
591/// ```text
592/// 0 u64 LE offset 8
593/// 8 u64 LE len 8
594/// 16 u8 object type code 1
595/// 17 u64 LE uncompressed_size 8
596/// 25 u64 LE delta_base 8
597/// ══
598/// 33
599/// ```
600///
601/// Fixed order, fixed width, no padding, no nulls. The type byte sits between
602/// the extent and the sizes rather than after them so the record is 33 bytes
603/// instead of 40 — the whole point of the arm is how few bytes a full-row fetch
604/// drags through cache, and 33 against 40 is 18% of that budget.
605///
606/// **This was 25 bytes before `delta_base` (PLAN §13) joined the schema.** The
607/// column is appended rather than inserted so the first four fields keep the
608/// offsets every reader here and every hand-decode in the tests already uses;
609/// the width is asserted byte for byte by
610/// `the_packed_record_is_the_documented_33_bytes`.
611pub const PACKED_LEN: usize = 33;
612const P_OFFSET: usize = 0;
613const P_LEN: usize = 8;
614const P_TYPE: usize = 16;
615const P_SIZE: usize = 17;
616const P_DELTA_BASE: usize = 25;
617
618/// One `FixedSizeBinary(PACKED_LEN)` element per object, in `order`.
619pub fn packed_column(entries: &[IndexEntry], order: &[u32]) -> FixedSizeBinaryArray {
620 let mut bytes: Vec<u8> = Vec::with_capacity(order.len() * PACKED_LEN);
621 for &i in order {
622 let e = &entries[i as usize];
623 bytes.extend_from_slice(&e.offset.to_le_bytes());
624 bytes.extend_from_slice(&e.len.to_le_bytes());
625 bytes.push(e.obj_type.code());
626 bytes.extend_from_slice(&e.uncompressed_size.to_le_bytes());
627 bytes.extend_from_slice(&e.delta_base.to_le_bytes());
628 }
629 debug_assert_eq!(bytes.len(), order.len() * PACKED_LEN);
630 FixedSizeBinaryArray::new(PACKED_LEN as i32, Buffer::from_vec(bytes), None)
631}
632
633#[inline]
634fn le64(r: &[u8], at: usize) -> u64 {
635 u64::from_le_bytes(r[at..at + 8].try_into().unwrap())
636}
637
638fn oid_field(oid_len: usize) -> Field {
639 Field::new(COL_OID, DataType::FixedSizeBinary(oid_len as i32), false)
640}
641
642/// Serialise one batch as a self-contained Arrow IPC **stream**.
643fn to_ipc(batch: &RecordBatch) -> Result<Vec<u8>> {
644 let mut out = Vec::with_capacity(64 + batch.get_array_memory_size());
645 {
646 let mut w = StreamWriter::try_new(&mut out, batch.schema_ref())
647 .map_err(|e| anyhow!("ipc writer: {e}"))?;
648 w.write(batch).map_err(|e| anyhow!("ipc write: {e}"))?;
649 w.finish().map_err(|e| anyhow!("ipc finish: {e}"))?;
650 }
651 Ok(out)
652}
653
654/// Decode an IPC stream **zero-copy**, and return the owning [`Buffer`] with it.
655///
656/// The `Vec<u8>` a writer produces is only 1-byte aligned, so it is first copied
657/// once into a `MutableBuffer` (64-byte aligned). After that every array in the
658/// batch is a view into `buffer` — enforced by `with_require_alignment(true)`,
659/// which errors instead of quietly re-allocating.
660fn decode_ipc(bytes: &[u8]) -> Result<(Buffer, RecordBatch)> {
661 let mut mb = MutableBuffer::with_capacity(bytes.len());
662 mb.extend_from_slice(bytes);
663 decode_ipc_buffer(mb.into())
664}
665
666/// The half of [`decode_ipc`] that does not control the buffer's alignment,
667/// split out so a test can hand it a deliberately misaligned one and prove
668/// `with_require_alignment(true)` is load-bearing rather than decoration.
669fn decode_ipc_buffer(owner: Buffer) -> Result<(Buffer, RecordBatch)> {
670 let mut cursor = owner.clone();
671 let mut decoder = StreamDecoder::new().with_require_alignment(true);
672 let mut found: Option<RecordBatch> = None;
673 while !cursor.is_empty() {
674 match decoder.decode(&mut cursor).map_err(|e| anyhow!("ipc decode: {e}"))? {
675 Some(b) if found.is_none() => found = Some(b),
676 Some(_) => bail!("index section holds more than one record batch"),
677 None => {}
678 }
679 }
680 decoder.finish().map_err(|e| anyhow!("ipc unfinished: {e}"))?;
681 found.ok_or_else(|| anyhow!("index section holds no record batch"))
682 .map(|b| (owner, b))
683}
684
685fn col<T: Array + Clone + 'static>(batch: &RecordBatch, name: &str) -> Result<T> {
686 batch
687 .column_by_name(name)
688 .ok_or_else(|| anyhow!("no `{name}` column"))?
689 .as_any()
690 .downcast_ref::<T>()
691 .cloned()
692 .ok_or_else(|| anyhow!("`{name}` has an unexpected type"))
693}
694
695/// True when `array`'s value bytes lie inside `ipc` — i.e. the decode really was
696/// zero-copy and not an aligned re-allocation behind our back.
697fn inside(ipc: &Buffer, values: &[u8]) -> bool {
698 if values.is_empty() {
699 // Nothing to point at; a zero-length column cannot disprove anything.
700 return true;
701 }
702 let base = ipc.as_ptr() as usize;
703 let p = values.as_ptr() as usize;
704 p >= base && p + values.len() <= base + ipc.len()
705}
706
707// ── shared read paths for the two columnar arms ───────────────────────────────
708
709/// The six arrays and **every** read path over them.
710///
711/// Both columnar arms hold one of these and neither has a hot path of its own,
712/// so they cannot drift apart (LAW 5) and the only thing the bench can see
713/// between them is how many IPC streams the arrays were framed into. That the
714/// two then tie is a fact about Arrow, not about this struct: `FourTables` and
715/// `OneTableFourColumns` both have **five payload columns in five separate
716/// buffers**, and a full-row fetch touches five distant strides either way. The
717/// number of *tables* was never the variable. The number of *columns* is, which
718/// is what [`PackedPayload`] changes.
719struct ColumnarPayload {
720 oid: FixedSizeBinaryArray,
721 offset: UInt64Array,
722 len: UInt64Array,
723 obj_type: UInt8Array,
724 size: UInt64Array,
725 delta_base: UInt64Array,
726}
727
728impl ColumnarPayload {
729 /// Five separate buffer reads, five strides.
730 #[inline]
731 fn row_at(&self, ordinal: u32) -> IndexRow {
732 let i = ordinal as usize;
733 IndexRow {
734 ordinal,
735 offset: self.offset.value(i),
736 len: self.len.value(i),
737 // A code the writer cannot produce cannot appear here: the column is
738 // built from `ObjType`, so the round trip is total. `Blob` is the
739 // only defensible fallback and it is unreachable in a section this
740 // crate wrote.
741 obj_type: ObjType::from_code(self.obj_type.value(i)).unwrap_or(ObjType::Blob),
742 uncompressed_size: self.size.value(i),
743 delta_base: self.delta_base.value(i),
744 }
745 }
746
747 /// Two of the five buffers.
748 #[inline]
749 fn extent_at(&self, ordinal: u32) -> (u64, u64) {
750 let i = ordinal as usize;
751 (self.offset.value(i), self.len.value(i))
752 }
753
754 /// One contiguous `u64` run, start to end — the case columnar is for.
755 fn sum_uncompressed(&self) -> u64 {
756 self.size.values().iter().copied().fold(0u64, u64::wrapping_add)
757 }
758
759 /// One contiguous `u8` run: `n` bytes read to answer a question about `n`
760 /// rows, which is the least memory traffic any layout can do here.
761 fn count_type(&self, t: ObjType) -> usize {
762 let c = t.code();
763 self.obj_type.values().iter().filter(|&&x| x == c).count()
764 }
765
766 fn inside(&self, oid_ipc: &Buffer, extent_ipc: &Buffer, type_ipc: &Buffer, size_ipc: &Buffer) -> bool {
767 inside(oid_ipc, self.oid.value_data())
768 && inside(extent_ipc, self.offset.values().inner().as_slice())
769 && inside(extent_ipc, self.len.values().inner().as_slice())
770 && inside(extent_ipc, self.delta_base.values().inner().as_slice())
771 && inside(type_ipc, self.obj_type.values().inner().as_slice())
772 && inside(size_ipc, self.size.values().inner().as_slice())
773 }
774}
775
776/// The three schemas layout A frames its facts into, plus the oid schema.
777///
778/// `delta_base` rides in the **extent** section rather than in a fifth one, and
779/// the reason is what the section means: it is *where the bytes are*, and a
780/// delta base is an address in exactly the same coordinate space as `offset` —
781/// the two are compared against each other by every guard that proves the base
782/// resolves. Keeping it here also keeps layout A what the benchmark named it:
783/// **four IPC sections** against layout B's one. The section count is the
784/// variable under test, and adding a fifth section would have changed the
785/// experiment rather than the schema.
786fn extent_schema() -> SchemaRef {
787 Arc::new(Schema::new(vec![
788 Field::new(COL_OFFSET, DataType::UInt64, false),
789 Field::new(COL_LEN, DataType::UInt64, false),
790 Field::new(COL_DELTA_BASE, DataType::UInt64, false),
791 ]))
792}
793
794// ── Impl A — FourTables ───────────────────────────────────────────────────────
795
796/// Four Arrow IPC sections — oid, byte extent, type, size — joined by row
797/// ordinal.
798///
799/// This is git's own shape: `.idx`, `.rev` and the missing type/size files, each
800/// an independent artifact. A lookup resolves the oid to an ordinal and then
801/// indexes three further sections at that ordinal.
802///
803/// The name counts **sections**, which is this arm's whole difference from
804/// [`OneTableFourColumns`]. It carries five payload columns: `delta_base` joined
805/// the schema afterwards and shares the extent section, for the reason given on
806/// [`extent_schema`].
807pub struct FourTables {
808 oids: OidResolver,
809 /// Owning IPC buffers, kept alive because every array below is a view into
810 /// one of them. Four buffers, four allocations, four distinct page runs.
811 ipc: [Buffer; 4],
812 cols: ColumnarPayload,
813 rows: usize,
814}
815
816impl FourTables {
817 /// Section order: oid, extent, type, size.
818 pub fn ipc_section_lens(&self) -> [usize; 4] {
819 [self.ipc[0].len(), self.ipc[1].len(), self.ipc[2].len(), self.ipc[3].len()]
820 }
821
822 /// The oid column, straight out of its own section — proof that "four
823 /// tables" still gives a contiguous scannable column.
824 pub fn oid_column(&self) -> &FixedSizeBinaryArray {
825 &self.cols.oid
826 }
827
828 /// Every column's bytes lie inside the section they were decoded from.
829 pub fn column_is_inside_ipc(&self) -> bool {
830 self.cols.inside(&self.ipc[0], &self.ipc[1], &self.ipc[2], &self.ipc[3])
831 }
832}
833
834impl ObjectIndex for FourTables {
835 fn build(entries: &[IndexEntry]) -> Result<Self> {
836 let order = oid_order(entries);
837 let hash = validate(entries, &order)?;
838 let oid_len = hash.oid_len();
839 let c = columns(entries, &order, oid_len);
840 let oids = OidResolver::build(entries, &order, hash)?;
841
842 let s_oid = Arc::new(Schema::new(vec![oid_field(oid_len)]));
843 let s_type = Arc::new(Schema::new(vec![Field::new(COL_TYPE, DataType::UInt8, false)]));
844 let s_size = Arc::new(Schema::new(vec![Field::new(COL_SIZE, DataType::UInt64, false)]));
845
846 let b_oid = RecordBatch::try_new(s_oid, vec![Arc::new(c.oid)])?;
847 let b_extent = RecordBatch::try_new(
848 extent_schema(),
849 vec![Arc::new(c.offset), Arc::new(c.len), Arc::new(c.delta_base)],
850 )?;
851 let b_type = RecordBatch::try_new(s_type, vec![Arc::new(c.obj_type)])?;
852 let b_size = RecordBatch::try_new(s_size, vec![Arc::new(c.size)])?;
853
854 let (ipc_oid, r_oid) = decode_ipc(&to_ipc(&b_oid)?)?;
855 let (ipc_extent, r_extent) = decode_ipc(&to_ipc(&b_extent)?)?;
856 let (ipc_type, r_type) = decode_ipc(&to_ipc(&b_type)?)?;
857 let (ipc_size, r_size) = decode_ipc(&to_ipc(&b_size)?)?;
858
859 Ok(Self {
860 oids,
861 ipc: [ipc_oid, ipc_extent, ipc_type, ipc_size],
862 cols: ColumnarPayload {
863 oid: col(&r_oid, COL_OID)?,
864 offset: col(&r_extent, COL_OFFSET)?,
865 len: col(&r_extent, COL_LEN)?,
866 obj_type: col(&r_type, COL_TYPE)?,
867 size: col(&r_size, COL_SIZE)?,
868 delta_base: col(&r_extent, COL_DELTA_BASE)?,
869 },
870 rows: order.len(),
871 })
872 }
873
874 fn lookup(&self, oid: &[u8]) -> Option<IndexRow> {
875 self.oids.ordinal(oid).map(|o| self.cols.row_at(o))
876 }
877
878 fn lookup_batch(&self, oids: &[&[u8]]) -> Vec<Option<IndexRow>> {
879 self.oids.ordinals(oids).into_iter().map(|o| o.map(|o| self.cols.row_at(o))).collect()
880 }
881
882 fn ordinals_batch(&self, oids: &[&[u8]]) -> Vec<Option<u32>> {
883 self.oids.ordinals(oids)
884 }
885
886 fn extents_batch(&self, oids: &[&[u8]]) -> Vec<Option<(u64, u64)>> {
887 self.oids.ordinals(oids).into_iter().map(|o| o.map(|o| self.cols.extent_at(o))).collect()
888 }
889
890 fn sum_uncompressed(&self) -> u64 {
891 self.cols.sum_uncompressed()
892 }
893
894 fn count_type(&self, t: ObjType) -> usize {
895 self.cols.count_type(t)
896 }
897
898 fn name(&self) -> &'static str {
899 "FourTables"
900 }
901
902 fn len(&self) -> usize {
903 self.rows
904 }
905
906 fn ipc_bytes(&self) -> usize {
907 self.ipc.iter().map(|b| b.len()).sum()
908 }
909
910 fn resident_bytes(&self) -> usize {
911 self.ipc_bytes() + self.oids.section_bytes
912 }
913}
914
915// ── Impl B — OneTableFourColumns ──────────────────────────────────────────────
916
917/// One Arrow IPC section, one table, the facts one column each.
918///
919/// Arrow is columnar, so this is **not** row-contiguous: `offset` is its own
920/// buffer, `len` is its own buffer, and a full-row fetch still touches five
921/// strides that are megabytes apart. What it saves over [`FourTables`] is the
922/// framing of three IPC streams and nothing else — which is exactly what the
923/// measurement found.
924///
925/// The name counts the columns it had when it was named and measured; since
926/// `delta_base` (PLAN §13) there are five payload columns here and in
927/// [`FourTables`] alike, so the two are still separated by section count and
928/// nothing else.
929pub struct OneTableFourColumns {
930 oids: OidResolver,
931 ipc: Buffer,
932 cols: ColumnarPayload,
933 rows: usize,
934}
935
936impl OneTableFourColumns {
937 pub fn oid_column(&self) -> &FixedSizeBinaryArray {
938 &self.cols.oid
939 }
940
941 /// All five arrays are views into the one IPC buffer.
942 pub fn column_is_inside_ipc(&self) -> bool {
943 self.cols.inside(&self.ipc, &self.ipc, &self.ipc, &self.ipc)
944 }
945
946 /// **The bytes this index would be persisted as** — the single Arrow IPC
947 /// stream every column is a view into, exactly as [`to_ipc`] framed it.
948 ///
949 /// [`ObjectIndex::ipc_bytes`] reports this buffer's *length*, which is
950 /// enough to compare two layouts' footprints and not enough to write one
951 /// down. `examples/tail_write_bench.rs` needs the bytes themselves: its
952 /// no-tail arm has to rewrite the whole index on every push, and a
953 /// measurement of that write is only honest if the bytes going to the file
954 /// are the index's own and not a stand-in of the same size.
955 ///
956 /// A borrowed slice and not a `Vec`: the buffer is already resident and
957 /// aligned, and handing out a copy would put an allocation inside the very
958 /// write this exists to measure.
959 pub fn ipc_slice(&self) -> &[u8] {
960 self.ipc.as_slice()
961 }
962}
963
964impl ObjectIndex for OneTableFourColumns {
965 fn build(entries: &[IndexEntry]) -> Result<Self> {
966 let order = oid_order(entries);
967 let hash = validate(entries, &order)?;
968 let oid_len = hash.oid_len();
969 let c = columns(entries, &order, oid_len);
970 let oids = OidResolver::build(entries, &order, hash)?;
971
972 let schema: SchemaRef = Arc::new(Schema::new(vec![
973 oid_field(oid_len),
974 Field::new(COL_OFFSET, DataType::UInt64, false),
975 Field::new(COL_LEN, DataType::UInt64, false),
976 Field::new(COL_TYPE, DataType::UInt8, false),
977 Field::new(COL_SIZE, DataType::UInt64, false),
978 Field::new(COL_DELTA_BASE, DataType::UInt64, false),
979 ]));
980 let batch = RecordBatch::try_new(
981 schema,
982 vec![
983 Arc::new(c.oid),
984 Arc::new(c.offset),
985 Arc::new(c.len),
986 Arc::new(c.obj_type),
987 Arc::new(c.size),
988 Arc::new(c.delta_base),
989 ],
990 )?;
991 let (ipc, r) = decode_ipc(&to_ipc(&batch)?)?;
992
993 Ok(Self {
994 oids,
995 ipc,
996 cols: ColumnarPayload {
997 oid: col(&r, COL_OID)?,
998 offset: col(&r, COL_OFFSET)?,
999 len: col(&r, COL_LEN)?,
1000 obj_type: col(&r, COL_TYPE)?,
1001 size: col(&r, COL_SIZE)?,
1002 delta_base: col(&r, COL_DELTA_BASE)?,
1003 },
1004 rows: order.len(),
1005 })
1006 }
1007
1008 fn lookup(&self, oid: &[u8]) -> Option<IndexRow> {
1009 self.oids.ordinal(oid).map(|o| self.cols.row_at(o))
1010 }
1011
1012 fn lookup_batch(&self, oids: &[&[u8]]) -> Vec<Option<IndexRow>> {
1013 self.oids.ordinals(oids).into_iter().map(|o| o.map(|o| self.cols.row_at(o))).collect()
1014 }
1015
1016 fn ordinals_batch(&self, oids: &[&[u8]]) -> Vec<Option<u32>> {
1017 self.oids.ordinals(oids)
1018 }
1019
1020 fn extents_batch(&self, oids: &[&[u8]]) -> Vec<Option<(u64, u64)>> {
1021 self.oids.ordinals(oids).into_iter().map(|o| o.map(|o| self.cols.extent_at(o))).collect()
1022 }
1023
1024 fn sum_uncompressed(&self) -> u64 {
1025 self.cols.sum_uncompressed()
1026 }
1027
1028 fn count_type(&self, t: ObjType) -> usize {
1029 self.cols.count_type(t)
1030 }
1031
1032 fn name(&self) -> &'static str {
1033 "OneTableFourColumns"
1034 }
1035
1036 fn len(&self) -> usize {
1037 self.rows
1038 }
1039
1040 fn ipc_bytes(&self) -> usize {
1041 self.ipc.len()
1042 }
1043
1044 fn resident_bytes(&self) -> usize {
1045 self.ipc_bytes() + self.oids.section_bytes
1046 }
1047}
1048
1049// ── Impl C — PackedPayload ────────────────────────────────────────────────────
1050
1051/// **One** payload column: all five facts of one object packed adjacently into
1052/// a single `FixedSizeBinary(33)` element.
1053///
1054/// This is the arm the first two were both missing. `FourTables` and
1055/// `OneTableFourColumns` differ in how many *tables* they use and agree in
1056/// having **five payload columns**, so a full-row fetch costs five buffer reads
1057/// at five unrelated addresses in both. Here it costs one:
1058///
1059/// ```text
1060/// per row, byte for byte (little-endian, no padding, no nulls):
1061/// 0 u64 offset
1062/// 8 u64 len
1063/// 16 u8 object type code (1 commit, 2 tree, 3 blob, 4 tag, 6 ofs-delta, 7 ref-delta)
1064/// 17 u64 uncompressed_size
1065/// 25 u64 delta_base — archive offset of the base entry, 0 for none
1066/// 33 ── next row
1067/// ```
1068///
1069/// **It was 24 bytes narrower before `delta_base` (PLAN §13).** A 33-byte record
1070/// spans one 64-byte cache line 49% of the time and two the rest, so a full-row
1071/// fetch is ~1.5 lines against the five the columnar arms touch — where at 25
1072/// bytes it was ~1.4 against four. The trade moved slightly, in both directions
1073/// at once, which is why the numbers below were re-taken rather than scaled.
1074///
1075/// The oid stays in its own column. It is the key the `stree` resolves
1076/// *against*, not one of the facts a resolved lookup fetches, so packing it in
1077/// would grow every payload read by 20 bytes nobody reads at lookup time.
1078///
1079/// ## The trade, stated before it is measured
1080///
1081/// * **Full-row access should win** — one stride instead of four.
1082/// * **Column scans should lose, and lose badly.** `count_type` reads one byte
1083/// per row; the columnar arms stream `n` bytes to answer it, this arm drags
1084/// `33n` through cache to use `n`. `sum_uncompressed` reads 8 of every 33
1085/// instead of 8 of every 8.
1086/// * It is **no longer typed Arrow columns**. A `FixedSizeBinary(33)` is
1087/// opaque to DuckDB / Polars / DataFusion, which can query the other two arms
1088/// directly off the IPC bytes. That is a real cost and it is not a
1089/// performance one.
1090pub struct PackedPayload {
1091 oids: OidResolver,
1092 ipc: Buffer,
1093 oid: FixedSizeBinaryArray,
1094 payload: FixedSizeBinaryArray,
1095 rows: usize,
1096}
1097
1098/// Column name of the single packed payload column.
1099pub const COL_PACKED: &str = "packed";
1100
1101impl PackedPayload {
1102 /// [`ObjectIndex::build`] with the `stree` section's [`OidLayout`] chosen
1103 /// explicitly — the whole apparatus of the alignment experiment
1104 /// (`examples/oid_align_bench.rs`).
1105 ///
1106 /// It lives on this arm alone rather than on the trait because
1107 /// `ordinals_batch` is **the same code in all three arms** (they share one
1108 /// [`OidResolver`]), so a second arm would add a second Arrow payload to
1109 /// keep resident and would measure nothing new. This is the arm the payload
1110 /// sweep picked.
1111 pub fn build_with_oid_layout(entries: &[IndexEntry], layout: OidLayout) -> Result<Self> {
1112 let order = oid_order(entries);
1113 let hash = validate(entries, &order)?;
1114 let oid_len = hash.oid_len();
1115 let oid_arr = oid_column(entries, &order, oid_len);
1116 let packed = packed_column(entries, &order);
1117 let oids = OidResolver::build_with(entries, &order, hash, layout)?;
1118 Self::assemble(oids, oid_arr, packed, oid_len, order.len())
1119 }
1120
1121 /// The cache-line phase of this index's `stree` keyspace — 0 for
1122 /// [`OidLayout::Aligned64`]. The bench asserts on it before quoting a
1123 /// number, because two arms that landed on the same phase would be one arm
1124 /// measured twice.
1125 pub fn keyspace_phase(&self) -> usize {
1126 self.oids.tree.keyspace_phase()
1127 }
1128
1129 /// Everything after the oid resolver: framing the two columns into one IPC
1130 /// stream and decoding it back zero-copy. Shared with `build` so the two
1131 /// cannot drift (LAW 5) — the only difference between them must be the
1132 /// `stree` layout, or the experiment is measuring two indexes.
1133 fn assemble(
1134 oids: OidResolver,
1135 oid_arr: FixedSizeBinaryArray,
1136 packed: FixedSizeBinaryArray,
1137 oid_len: usize,
1138 rows: usize,
1139 ) -> Result<Self> {
1140 let schema: SchemaRef = Arc::new(Schema::new(vec![
1141 oid_field(oid_len),
1142 Field::new(COL_PACKED, DataType::FixedSizeBinary(PACKED_LEN as i32), false),
1143 ]));
1144 let batch = RecordBatch::try_new(schema, vec![Arc::new(oid_arr), Arc::new(packed)])?;
1145 let (ipc, r) = decode_ipc(&to_ipc(&batch)?)?;
1146 Ok(Self { oids, ipc, oid: col(&r, COL_OID)?, payload: col(&r, COL_PACKED)?, rows })
1147 }
1148
1149 pub fn oid_column(&self) -> &FixedSizeBinaryArray {
1150 &self.oid
1151 }
1152
1153 pub fn column_is_inside_ipc(&self) -> bool {
1154 inside(&self.ipc, self.oid.value_data()) && inside(&self.ipc, self.payload.value_data())
1155 }
1156
1157 /// One buffer read, one stride.
1158 #[inline]
1159 fn row_at(&self, ordinal: u32) -> IndexRow {
1160 let r = self.payload.value(ordinal as usize);
1161 IndexRow {
1162 ordinal,
1163 offset: le64(r, P_OFFSET),
1164 len: le64(r, P_LEN),
1165 obj_type: ObjType::from_code(r[P_TYPE]).unwrap_or(ObjType::Blob),
1166 uncompressed_size: le64(r, P_SIZE),
1167 delta_base: le64(r, P_DELTA_BASE),
1168 }
1169 }
1170
1171 /// The same one buffer read — a partial row costs a packed layout exactly
1172 /// what a full row costs, which is half the point of the trade.
1173 #[inline]
1174 fn extent_at(&self, ordinal: u32) -> (u64, u64) {
1175 let r = self.payload.value(ordinal as usize);
1176 (le64(r, P_OFFSET), le64(r, P_LEN))
1177 }
1178}
1179
1180impl ObjectIndex for PackedPayload {
1181 fn build(entries: &[IndexEntry]) -> Result<Self> {
1182 let order = oid_order(entries);
1183 let hash = validate(entries, &order)?;
1184 let oid_len = hash.oid_len();
1185 let oid_arr = oid_column(entries, &order, oid_len);
1186 let packed = packed_column(entries, &order);
1187 let oids = OidResolver::build(entries, &order, hash)?;
1188 Self::assemble(oids, oid_arr, packed, oid_len, order.len())
1189 }
1190
1191 fn lookup(&self, oid: &[u8]) -> Option<IndexRow> {
1192 self.oids.ordinal(oid).map(|o| self.row_at(o))
1193 }
1194
1195 fn lookup_batch(&self, oids: &[&[u8]]) -> Vec<Option<IndexRow>> {
1196 self.oids.ordinals(oids).into_iter().map(|o| o.map(|o| self.row_at(o))).collect()
1197 }
1198
1199 fn ordinals_batch(&self, oids: &[&[u8]]) -> Vec<Option<u32>> {
1200 self.oids.ordinals(oids)
1201 }
1202
1203 fn extents_batch(&self, oids: &[&[u8]]) -> Vec<Option<(u64, u64)>> {
1204 self.oids.ordinals(oids).into_iter().map(|o| o.map(|o| self.extent_at(o))).collect()
1205 }
1206
1207 /// Strided: 8 useful bytes out of every 25 touched.
1208 fn sum_uncompressed(&self) -> u64 {
1209 let d = self.payload.value_data();
1210 let mut acc = 0u64;
1211 let mut i = P_SIZE;
1212 while i + 8 <= d.len() {
1213 acc = acc.wrapping_add(le64(d, i));
1214 i += PACKED_LEN;
1215 }
1216 acc
1217 }
1218
1219 /// Strided: 1 useful byte out of every 25 touched.
1220 fn count_type(&self, t: ObjType) -> usize {
1221 let c = t.code();
1222 let d = self.payload.value_data();
1223 let mut n = 0usize;
1224 let mut i = P_TYPE;
1225 while i < d.len() {
1226 if d[i] == c {
1227 n += 1;
1228 }
1229 i += PACKED_LEN;
1230 }
1231 n
1232 }
1233
1234 fn name(&self) -> &'static str {
1235 "PackedPayload"
1236 }
1237
1238 fn len(&self) -> usize {
1239 self.rows
1240 }
1241
1242 fn ipc_bytes(&self) -> usize {
1243 self.ipc.len()
1244 }
1245
1246 fn resident_bytes(&self) -> usize {
1247 self.ipc_bytes() + self.oids.section_bytes
1248 }
1249}
1250
1251// ── deterministic workload generation, shared by tests and the bench ──────────
1252
1253/// splitmix64. Seeded, so a bench run is reproducible and a historized series is
1254/// comparable at all.
1255pub struct Rng(pub u64);
1256
1257impl Rng {
1258 pub fn next_u64(&mut self) -> u64 {
1259 self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
1260 let mut z = self.0;
1261 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
1262 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
1263 z ^ (z >> 31)
1264 }
1265
1266 pub fn fill(&mut self, out: &mut [u8]) {
1267 for c in out.chunks_mut(8) {
1268 let w = self.next_u64().to_le_bytes();
1269 let n = c.len();
1270 c.copy_from_slice(&w[..n]);
1271 }
1272 }
1273}
1274
1275/// `n` distinct entries with uniformly random oids.
1276///
1277/// Uniform randomness is the property under test, not a convenience: real oids
1278/// are hashes and share no prefixes, so a generator with structure would give
1279/// the stree an unrepresentative keyspace.
1280///
1281/// **Every `OfsDelta` entry carries a non-zero `delta_base`** — the offset of
1282/// the entry immediately before it, which is a real row of the same workload —
1283/// and every other entry carries `0`. LAW 2's identity-value trap is the whole
1284/// reason: a generator that left `delta_base` at `0` everywhere would let a
1285/// layout that never wrote the column, or read it from the wrong stride, pass
1286/// every comparison in this module. It is derived from `out.last()` rather than
1287/// from `rng`, so oids, offsets, lengths and types are bit-identical to what
1288/// this generator produced before the column existed and no earlier figure is
1289/// invalidated by the workload changing under it.
1290pub fn synthetic_entries(n: usize, oid_len: usize, seed: u64) -> Vec<IndexEntry> {
1291 let mut rng = Rng(seed);
1292 let mut seen = std::collections::HashSet::with_capacity(n * 2);
1293 let mut out: Vec<IndexEntry> = Vec::with_capacity(n);
1294 let mut off = 12u64; // past a pack header
1295 while out.len() < n {
1296 let mut oid = vec![0u8; oid_len];
1297 rng.fill(&mut oid);
1298 if !seen.insert(oid.clone()) {
1299 continue;
1300 }
1301 // Length distribution roughly like a real pack: mostly small, a long
1302 // tail. The exact shape does not affect a point lookup, but it keeps
1303 // the u64 columns from being all-identical, which would let a compressor
1304 // or a branch predictor flatter one arm over the other.
1305 let len = 32 + (rng.next_u64() % 4096);
1306 let ty = ObjType::ALL[(rng.next_u64() % 6) as usize];
1307 // An ofs-delta's base is the entry before it: always an offset that some
1308 // row of this same workload really starts at, never 0, and never a
1309 // forward reference. A ref-delta's base is named by oid and has no
1310 // offset until it is resolved, so it records the 0 sentinel — as does
1311 // every whole object.
1312 let delta_base = match (ty, out.last()) {
1313 (ObjType::OfsDelta, Some(prev)) => prev.offset,
1314 _ => 0,
1315 };
1316 out.push(IndexEntry {
1317 oid,
1318 offset: off,
1319 len,
1320 obj_type: ty,
1321 uncompressed_size: len * (1 + rng.next_u64() % 5),
1322 delta_base,
1323 });
1324 off += len;
1325 }
1326 out
1327}
1328
1329
1330#[cfg(test)]
1331mod tests {
1332 use super::*;
1333
1334 /// All three arms over the same entries. Every semantic test runs against
1335 /// the triple, because "the three layouts are one index" is the claim the
1336 /// whole comparison rests on.
1337 fn arms(entries: &[IndexEntry]) -> (FourTables, OneTableFourColumns, PackedPayload) {
1338 (
1339 FourTables::build(entries).expect("A builds"),
1340 OneTableFourColumns::build(entries).expect("B builds"),
1341 PackedPayload::build(entries).expect("C builds"),
1342 )
1343 }
1344
1345 /// The core correctness claim: **the three layouts are the same index**.
1346 ///
1347 /// Asserted on applied output — the five facts of every row, plus the
1348 /// ordinal — for every present oid, for absent oids, and through the
1349 /// serial, batch, extent-only and ordinal-only paths. A row-count or an
1350 /// `is_some()` check would pass for three indexes that disagreed on every
1351 /// value.
1352 ///
1353 /// Seen RED by changing `ColumnarPayload::row_at` to read `self.len.value(i)`
1354 /// for `offset`: "layouts disagree on 80313d462e6994e9e819193e6fdbd5f8390e92e3
1355 /// left: IndexRow { ordinal: 259, offset: 344, len: 344, .. }
1356 /// right: IndexRow { ordinal: 259, offset: 12, len: 344, .. }".
1357 /// Restored.
1358 ///
1359 /// Seen RED a second time, for the packed arm specifically, by swapping the
1360 /// `len` and `uncompressed_size` writes in `packed_column` only, so the
1361 /// writer and the reader disagree about the record layout:
1362 /// "C disagrees with A on 80313d462e6994e9e819193e6fdbd5f8390e92e3
1363 /// left: IndexRow { offset: 12, len: 344, uncompressed_size: 1720 }
1364 /// right: IndexRow { offset: 12, len: 1720, uncompressed_size: 344 }".
1365 /// Restored. Note that A and B stayed green throughout — only a guard that
1366 /// compares the packed arm against them can see this class of bug.
1367 ///
1368 /// Seen RED a third time, when `delta_base` was added, by dropping
1369 /// [`FourTables`] read `COL_LEN` into `ColumnarPayload::delta_base` — the
1370 /// single most plausible way to wire a new column in wrong, since both are
1371 /// `u64` columns of the same section: "A and B disagree on
1372 /// 80313d462e6994e9e819193e6fdbd5f8390e92e3 / left: IndexRow { ordinal: 259,
1373 /// offset: 12, len: 344, obj_type: Tree, uncompressed_size: 1720,
1374 /// **delta_base: 344** } / right: IndexRow { … **delta_base: 0** }". B and C
1375 /// were right and A was wrong, and only the row-for-row comparison said so.
1376 /// Restored.
1377 #[test]
1378 fn the_three_layouts_return_identical_rows() {
1379 for &oid_len in &[20usize, 32] {
1380 let entries = synthetic_entries(500, oid_len, 0xA11CE);
1381 let (a, b, c) = arms(&entries);
1382 assert_eq!(a.len(), 500);
1383 assert_eq!(b.len(), 500);
1384 assert_eq!(c.len(), 500);
1385
1386 // Not a blind guard: the workload has to carry the column at
1387 // something other than its identity value, or every arm agreeing on
1388 // `delta_base: 0` would prove nothing about `delta_base` at all.
1389 let with_base = entries.iter().filter(|e| e.delta_base != 0).count();
1390 assert!(
1391 with_base >= 50,
1392 "only {with_base} of 500 entries carry a non-zero delta_base — this guard would \
1393 sit on the identity value and could not see a column that was never written"
1394 );
1395
1396 let mut hits = 0usize;
1397 for e in &entries {
1398 let ra = a.lookup(&e.oid).unwrap_or_else(|| {
1399 panic!("{} missed {}", a.name(), hex::encode(&e.oid))
1400 });
1401 let rb = b.lookup(&e.oid).unwrap_or_else(|| {
1402 panic!("{} missed {}", b.name(), hex::encode(&e.oid))
1403 });
1404 let rc = c.lookup(&e.oid).unwrap_or_else(|| {
1405 panic!("{} missed {}", c.name(), hex::encode(&e.oid))
1406 });
1407 assert_eq!(ra, rb, "A and B disagree on {}", hex::encode(&e.oid));
1408 assert_eq!(
1409 ra,
1410 rc,
1411 "C disagrees with A on {}",
1412 hex::encode(&e.oid)
1413 );
1414 // …and all three agree with the input, not just with each other.
1415 assert_eq!(rc.offset, e.offset);
1416 assert_eq!(rc.len, e.len);
1417 assert_eq!(rc.obj_type, e.obj_type);
1418 assert_eq!(rc.uncompressed_size, e.uncompressed_size);
1419 assert_eq!(
1420 rc.delta_base,
1421 e.delta_base,
1422 "delta_base did not survive C for {}",
1423 hex::encode(&e.oid)
1424 );
1425 assert_eq!(ra.delta_base, e.delta_base, "delta_base did not survive A");
1426 assert_eq!(rb.delta_base, e.delta_base, "delta_base did not survive B");
1427 hits += 1;
1428 }
1429 assert_eq!(hits, 500, "every entry must resolve");
1430
1431 // Absent oids: same answer everywhere, and that answer is None.
1432 let absent = synthetic_entries(200, oid_len, 0xBEEF_0000);
1433 for e in &absent {
1434 assert_eq!(a.lookup(&e.oid), None);
1435 assert_eq!(b.lookup(&e.oid), None);
1436 assert_eq!(c.lookup(&e.oid), None);
1437 }
1438
1439 // Every batch path, on a mix, positionally.
1440 let mut q: Vec<&[u8]> = Vec::new();
1441 for (i, e) in entries.iter().enumerate() {
1442 q.push(&e.oid);
1443 if i < absent.len() {
1444 q.push(&absent[i].oid);
1445 }
1446 }
1447 let ba = a.lookup_batch(&q);
1448 let bb = b.lookup_batch(&q);
1449 let bc = c.lookup_batch(&q);
1450 assert_eq!(ba.len(), q.len());
1451 assert_eq!(ba, bb, "A/B batch paths disagree at oid_len {oid_len}");
1452 assert_eq!(ba, bc, "A/C batch paths disagree at oid_len {oid_len}");
1453 let n_hits = ba.iter().filter(|r| r.is_some()).count();
1454 assert_eq!(n_hits, 500, "expected exactly the 500 present oids to hit");
1455 for (i, r) in ba.iter().enumerate() {
1456 assert_eq!(*r, c.lookup(q[i]), "C batch/serial disagree at {i}");
1457 }
1458
1459 // The partial-row and ordinal-only paths agree with the full row.
1460 let ea = a.extents_batch(&q);
1461 let ec = c.extents_batch(&q);
1462 assert_eq!(ea, ec, "extent paths disagree");
1463 let oa = a.ordinals_batch(&q);
1464 let oc = c.ordinals_batch(&q);
1465 assert_eq!(oa, oc, "ordinal paths disagree");
1466 for i in 0..q.len() {
1467 assert_eq!(ea[i], ba[i].map(|r| (r.offset, r.len)), "extent != row at {i}");
1468 assert_eq!(oa[i], ba[i].map(|r| r.ordinal), "ordinal != row at {i}");
1469 }
1470 }
1471 }
1472
1473 /// **`delta_base` is an offset that locates a row of this very table**, in
1474 /// all three arms — which is the property an ordinal could not have.
1475 ///
1476 /// Read back through the index (never from the input entries), every
1477 /// non-zero `delta_base` is looked up against the set of `offset`s the index
1478 /// itself reports, and it has to land on one, earlier in the archive than
1479 /// the delta that names it. `offset` and `delta_base` are the same
1480 /// coordinate space, and this is the assertion that says so.
1481 ///
1482 /// Seen RED by making `synthetic_entries` write `prev.offset + 1` as the
1483 /// delta base — a value one byte off a real entry boundary, which is
1484 /// precisely how an off-by-one in a rebase or in a varint would look:
1485 /// "A: delta_base 4601 of ordinal 1256 lands on no entry offset in this
1486 /// index". Restored to `prev.offset`.
1487 ///
1488 /// Seen RED a second time, on the ordinal question itself, by writing the
1489 /// base's *row index* into the column instead of its offset:
1490 /// "A: delta_base 2 of ordinal 1256 lands on no entry offset in this index"
1491 /// — a small number that is a perfectly valid row address and an invalid
1492 /// archive address, which is §13's decision failing loudly rather than
1493 /// silently. Restored.
1494 #[test]
1495 fn delta_base_locates_a_real_entry_in_every_arm() {
1496 let entries = synthetic_entries(2000, 20, 0xDE17A);
1497 let (a, b, c) = arms(&entries);
1498
1499 // The offsets this index reports, taken from the index and not from the
1500 // input: `lookup` of every stored oid.
1501 let offsets: std::collections::HashSet<u64> =
1502 entries.iter().filter_map(|e| a.lookup(&e.oid)).map(|r| r.offset).collect();
1503 assert_eq!(offsets.len(), 2000, "every row must report a distinct offset");
1504
1505 let arms: [(&str, &dyn ObjectIndex); 3] = [("A", &a), ("B", &b), ("C", &c)];
1506 let mut checked = 0usize;
1507 for (name, idx) in arms {
1508 let mut with_base = 0usize;
1509 for e in &entries {
1510 let row = idx.lookup(&e.oid).expect("stored oid resolves");
1511 if row.delta_base == 0 {
1512 assert_ne!(
1513 row.obj_type,
1514 ObjType::OfsDelta,
1515 "{name}: an ofs-delta with no recorded base is a row that cannot be \
1516 resolved at all"
1517 );
1518 continue;
1519 }
1520 with_base += 1;
1521 assert!(
1522 offsets.contains(&row.delta_base),
1523 "{name}: delta_base {} of ordinal {} lands on no entry offset in this index",
1524 row.delta_base,
1525 row.ordinal
1526 );
1527 assert!(
1528 row.delta_base < row.offset,
1529 "{name}: delta_base {} is not earlier in the archive than the delta at {}",
1530 row.delta_base,
1531 row.offset
1532 );
1533 }
1534 assert!(
1535 with_base > 100,
1536 "{name}: only {with_base} of 2000 rows carried a base — nothing was proven"
1537 );
1538 checked += with_base;
1539 }
1540 assert!(checked > 300, "three arms must each have checked real bases");
1541 }
1542
1543 /// The two column scans return the same answer from all three arms, and
1544 /// that answer is the one computed straight from the input entries.
1545 ///
1546 /// This is the guard that makes the scan half of the benchmark meaningful:
1547 /// a strided reader that skipped rows would be very fast and very wrong.
1548 ///
1549 /// Seen RED by advancing `PackedPayload::sum_uncompressed` by `PACKED_LEN + 8`
1550 /// instead of `PACKED_LEN`: "C sum_uncompressed: left 8826373087920709042,
1551 /// right 12349770". The stride slipped out of phase, so it summed bytes
1552 /// straddling field boundaries — a fast, wrong scan that no timing
1553 /// assertion would ever have noticed. Restored.
1554 #[test]
1555 fn column_scans_agree_across_arms_and_with_the_input() {
1556 let entries = synthetic_entries(2000, 20, 0x5CA7);
1557 let (a, b, c) = arms(&entries);
1558
1559 let want: u64 = entries.iter().map(|e| e.uncompressed_size).sum();
1560 assert_eq!(a.sum_uncompressed(), want, "A sum_uncompressed");
1561 assert_eq!(b.sum_uncompressed(), want, "B sum_uncompressed");
1562 assert_eq!(c.sum_uncompressed(), want, "C sum_uncompressed");
1563 assert!(want > 0, "the workload must actually carry sizes");
1564
1565 let mut total = 0usize;
1566 for t in ObjType::ALL {
1567 let want = entries.iter().filter(|e| e.obj_type == t).count();
1568 assert_eq!(a.count_type(t), want, "A count_type({})", t.as_str());
1569 assert_eq!(b.count_type(t), want, "B count_type({})", t.as_str());
1570 assert_eq!(c.count_type(t), want, "C count_type({})", t.as_str());
1571 assert!(want > 0, "{} must appear in the workload", t.as_str());
1572 total += want;
1573 }
1574 assert_eq!(total, entries.len(), "the six types must partition the index");
1575 }
1576
1577 /// The packed record is 33 bytes laid out exactly as documented, read
1578 /// straight out of the IPC buffer rather than through the accessor that is
1579 /// under test. A layout that changed silently would still round-trip
1580 /// through its own reader; this pins it to the bytes.
1581 ///
1582 /// Seen RED by moving the type byte from offset 16 to offset 24 in
1583 /// `packed_column`: "row 0 byte 16 is 0 but the type code is 6". Restored.
1584 ///
1585 /// Seen RED again for the fifth field, by writing `e.offset` where
1586 /// `packed_column` writes `e.delta_base`: "row 0 bytes 25..33 must be the
1587 /// delta base / left: 368 / right: 12". Restored. Writing the *offset*
1588 /// there is the failure mode worth catching: it is a plausible archive
1589 /// offset, it is even a real entry boundary, so nothing downstream would
1590 /// look odd — only a comparison against the input entry tells the two
1591 /// apart.
1592 #[test]
1593 fn the_packed_record_is_the_documented_33_bytes() {
1594 let entries = synthetic_entries(64, 20, 0x9F);
1595 let c = PackedPayload::build(&entries).unwrap();
1596 assert_eq!(PACKED_LEN, 33);
1597 assert_eq!(PACKED_LEN, 8 + 8 + 1 + 8 + 8, "offset+len+type+size+delta_base");
1598
1599 let mut sorted: Vec<&IndexEntry> = entries.iter().collect();
1600 sorted.sort_by(|x, y| x.oid.cmp(&y.oid));
1601 let d = c.payload.value_data();
1602 assert_eq!(d.len(), 64 * PACKED_LEN, "payload column is not 33 bytes per row");
1603 assert!(
1604 sorted.iter().filter(|e| e.delta_base != 0).count() >= 4,
1605 "the fixture must carry real delta bases or bytes 25..33 are all zero"
1606 );
1607
1608 for (i, e) in sorted.iter().enumerate() {
1609 let r = &d[i * PACKED_LEN..(i + 1) * PACKED_LEN];
1610 assert_eq!(
1611 u64::from_le_bytes(r[0..8].try_into().unwrap()),
1612 e.offset,
1613 "row {i} bytes 0..8 must be the offset"
1614 );
1615 assert_eq!(
1616 u64::from_le_bytes(r[8..16].try_into().unwrap()),
1617 e.len,
1618 "row {i} bytes 8..16 must be the len"
1619 );
1620 assert_eq!(
1621 r[16],
1622 e.obj_type.code(),
1623 "row {i} byte 16 is {} but the type code is {}",
1624 r[16],
1625 e.obj_type.code()
1626 );
1627 assert_eq!(
1628 u64::from_le_bytes(r[17..25].try_into().unwrap()),
1629 e.uncompressed_size,
1630 "row {i} bytes 17..25 must be the uncompressed size"
1631 );
1632 assert_eq!(
1633 u64::from_le_bytes(r[25..33].try_into().unwrap()),
1634 e.delta_base,
1635 "row {i} bytes 25..33 must be the delta base"
1636 );
1637 }
1638 }
1639
1640 /// The whole premise of the third arm, asserted as a byte count rather than
1641 /// as an argument: a full-row fetch touches **one** payload buffer of 33
1642 /// bytes per row, where the columnar arms touch five buffers whose bases are
1643 /// megabytes apart.
1644 ///
1645 /// Seen RED by asserting the columnar arm's payload buffers were within 25
1646 /// bytes of each other: "offset and size buffers are 1737664 bytes apart,
1647 /// not adjacent" at 100 000 rows. That distance is the fact the packed arm
1648 /// exists to change. Restored to assert the true distances.
1649 #[test]
1650 fn a_packed_row_is_one_stride_and_a_columnar_row_is_five() {
1651 let entries = synthetic_entries(100_000, 20, 0x0FF5);
1652 let (_, b, c) = arms(&entries);
1653
1654 // Columnar: five payload buffers, and consecutive facts of ONE row are
1655 // ~800 kB apart because each column is 100000 × 8 bytes long.
1656 let base = |s: &[u8]| s.as_ptr() as usize;
1657 let off = base(b.cols.offset.values().inner().as_slice());
1658 let len = base(b.cols.len.values().inner().as_slice());
1659 let size = base(b.cols.size.values().inner().as_slice());
1660 let dbase = base(b.cols.delta_base.values().inner().as_slice());
1661 assert!(
1662 len.abs_diff(off) >= 800_000,
1663 "offset and len columns are only {} bytes apart — this arm is supposed to be \
1664 columnar",
1665 len.abs_diff(off)
1666 );
1667 assert!(size.abs_diff(off) >= 800_000);
1668 assert!(
1669 dbase.abs_diff(off) >= 800_000 && dbase.abs_diff(size) >= 800_000,
1670 "delta_base is {} bytes from offset and {} from size — the fifth fact must be its \
1671 own stride, not a field inside another column",
1672 dbase.abs_diff(off),
1673 dbase.abs_diff(size)
1674 );
1675
1676 // Packed: the five facts of one row are inside 33 consecutive bytes.
1677 let d = c.payload.value_data();
1678 assert_eq!(d.len(), 100_000 * PACKED_LEN);
1679 let row7 = &d[7 * PACKED_LEN..8 * PACKED_LEN];
1680 let r = c.lookup(&entries.iter().min_by_key(|e| e.oid.clone()).unwrap().oid);
1681 assert!(r.is_some(), "the lexicographically first oid must resolve");
1682 // Every fact of row 7 is readable from those 33 bytes alone.
1683 let from_bytes = IndexRow {
1684 ordinal: 7,
1685 offset: u64::from_le_bytes(row7[0..8].try_into().unwrap()),
1686 len: u64::from_le_bytes(row7[8..16].try_into().unwrap()),
1687 obj_type: ObjType::from_code(row7[16]).unwrap(),
1688 uncompressed_size: u64::from_le_bytes(row7[17..25].try_into().unwrap()),
1689 delta_base: u64::from_le_bytes(row7[25..33].try_into().unwrap()),
1690 };
1691 assert_eq!(
1692 from_bytes,
1693 c.row_at(7),
1694 "one 33-byte slice must carry the whole row"
1695 );
1696 }
1697
1698 /// The ordinal is the oid-lexicographic rank in **all three** arms, and it
1699 /// is the join key `FourTables` relies on. Asserted against an
1700 /// independently sorted copy of the input rather than against another arm.
1701 ///
1702 /// Seen RED by making `oid_order` sort by `offset` instead of by `oid`:
1703 /// "A ordinal is not the rank — left: 206, right: 0" on the first row.
1704 /// Restored.
1705 #[test]
1706 fn ordinals_are_the_oid_lexicographic_rank_in_every_arm() {
1707 let entries = synthetic_entries(300, 20, 7);
1708 let (a, b, c) = arms(&entries);
1709 let mut sorted: Vec<&IndexEntry> = entries.iter().collect();
1710 sorted.sort_by(|x, y| x.oid.cmp(&y.oid));
1711 for (rank, e) in sorted.iter().enumerate() {
1712 let ra = a.lookup(&e.oid).unwrap();
1713 let rb = b.lookup(&e.oid).unwrap();
1714 let rc = c.lookup(&e.oid).unwrap();
1715 assert_eq!(ra.ordinal as usize, rank, "A ordinal is not the rank");
1716 assert_eq!(rb.ordinal as usize, rank, "B ordinal is not the rank");
1717 assert_eq!(rc.ordinal as usize, rank, "C ordinal is not the rank");
1718 // The oid column of each arm, read at that ordinal, is that oid.
1719 assert_eq!(a.oid_column().value(rank), e.oid.as_slice());
1720 assert_eq!(b.oid_column().value(rank), e.oid.as_slice());
1721 assert_eq!(c.oid_column().value(rank), e.oid.as_slice());
1722 }
1723 }
1724
1725 /// Zero-copy, asserted by pointer containment rather than by hope, in all
1726 /// three arms.
1727 ///
1728 /// `decode_ipc` uses `with_require_alignment(true)`, so a misaligned buffer
1729 /// is an error, not a silent re-allocation. This proves the positive side:
1730 /// each array's bytes are *inside* the IPC buffer it came from.
1731 ///
1732 /// Seen RED by swapping `decode_ipc_buffer`'s `StreamDecoder` for the
1733 /// high-level `StreamReader` over a `Cursor` (which owns its own
1734 /// allocations): "FourTables columns were copied out of IPC". Restored.
1735 ///
1736 /// A weaker edit did **not** turn it red and is worth recording: replacing
1737 /// the `MutableBuffer` copy with `Buffer::from_vec(bytes.to_vec())` left the
1738 /// test green, because glibc happened to hand back an 8-aligned allocation
1739 /// for a ~57 kB `Vec`. Alignment by luck is not alignment, which is what
1740 /// [`require_alignment_is_load_bearing`] pins down separately.
1741 #[test]
1742 fn every_column_is_a_zero_copy_view_into_its_ipc_section() {
1743 let entries = synthetic_entries(1000, 32, 11);
1744 let (a, b, c) = arms(&entries);
1745 assert!(a.column_is_inside_ipc(), "FourTables columns were copied out of IPC");
1746 assert!(b.column_is_inside_ipc(), "OneTable columns were copied out of IPC");
1747 assert!(c.column_is_inside_ipc(), "PackedPayload columns were copied out of IPC");
1748
1749 // And the payload really is there: 1000 × 32 oid bytes + 1000 × 8 for
1750 // each of offset/len/size/delta_base + 1000 × 1 type = 65000 bytes
1751 // minimum.
1752 assert!(
1753 b.ipc_bytes() >= 65_000,
1754 "one-table section is {} bytes, too small to hold the payload",
1755 b.ipc_bytes()
1756 );
1757 assert!(a.ipc_bytes() >= 65_000);
1758 assert!(c.ipc_bytes() >= 65_000);
1759 }
1760
1761 /// `with_require_alignment(true)` is the thing that makes "zero-copy" a
1762 /// contract instead of a hope: with it off, arrow silently allocates a fresh
1763 /// aligned buffer and copies, and the only symptom is that opening a large
1764 /// index got slower and doubled its peak memory.
1765 ///
1766 /// The same IPC bytes are decoded twice — once from a 64-byte-aligned
1767 /// buffer, once from the identical bytes sitting at offset 4 of the same
1768 /// allocation. The first must succeed and be a view; the second must be
1769 /// **refused**.
1770 ///
1771 /// Seen RED by dropping `.with_require_alignment(true)` from
1772 /// `decode_ipc_buffer`: the misaligned decode returned `Ok` and the test
1773 /// panicked with "a misaligned buffer must be refused, not silently
1774 /// copied". Restored.
1775 #[test]
1776 fn require_alignment_is_load_bearing() {
1777 let entries = synthetic_entries(64, 20, 77);
1778 let order = oid_order(&entries);
1779 let c = columns(&entries, &order, 20);
1780 let batch = RecordBatch::try_new(
1781 extent_schema(),
1782 vec![Arc::new(c.offset), Arc::new(c.len), Arc::new(c.delta_base)],
1783 )
1784 .unwrap();
1785 let ipc = to_ipc(&batch).unwrap();
1786
1787 // Aligned: 64 bytes of padding then the stream, sliced back to the
1788 // stream's start — the pointer is 64-aligned.
1789 let mut mb = MutableBuffer::with_capacity(64 + ipc.len());
1790 mb.extend_from_slice(&[0u8; 64]);
1791 mb.extend_from_slice(&ipc);
1792 let padded: Buffer = mb.into();
1793 let (owner, ok) = decode_ipc_buffer(padded.slice(64)).expect("aligned decode must work");
1794 assert_eq!(ok.num_rows(), 64, "the aligned decode must yield all 64 rows");
1795 assert!(inside(&owner, ok.column(0).to_data().buffers()[0].as_slice()));
1796
1797 // Misaligned by 4: byte-identical stream, 4-byte-offset pointer.
1798 let mut mb = MutableBuffer::with_capacity(4 + ipc.len());
1799 mb.extend_from_slice(&[0u8; 4]);
1800 mb.extend_from_slice(&ipc);
1801 let skewed: Buffer = mb.into();
1802 let err = match decode_ipc_buffer(skewed.slice(4)) {
1803 Ok(_) => panic!("a misaligned buffer must be refused, not silently copied"),
1804 Err(e) => e.to_string(),
1805 };
1806 assert!(
1807 err.contains("Misaligned"),
1808 "the refusal must name the misalignment, got: {err}"
1809 );
1810 }
1811
1812 /// Four sections cost strictly more IPC framing than one, and the amount is
1813 /// asserted as a byte count, not as "greater than".
1814 ///
1815 /// Each Arrow IPC stream carries a schema message, a record-batch message
1816 /// header and an end-of-stream marker. Three extra copies of that is the
1817 /// entire structural overhead of layout A, and on a tiny index it dominates.
1818 ///
1819 /// Seen RED by asserting `>= 900`: "expected ≥900 bytes of extra framing
1820 /// for three extra sections, got 728 (A=4704 B=3976)". The bound below is
1821 /// the one the measurement supports — 728 bytes, ~243 per extra section,
1822 /// which is the schema + batch-header + EOS framing and not payload.
1823 #[test]
1824 fn four_sections_pay_three_extra_ipc_frames() {
1825 let entries = synthetic_entries(64, 20, 3);
1826 let (a, b, _) = arms(&entries);
1827 let extra = a.ipc_bytes() as i64 - b.ipc_bytes() as i64;
1828 assert!(
1829 (600..1200).contains(&extra),
1830 "expected 600..1200 bytes of extra framing for three extra sections, got {extra} \
1831 (A={} B={})",
1832 a.ipc_bytes(),
1833 b.ipc_bytes()
1834 );
1835 // The four sections are separately sized and the oid one is the biggest.
1836 let lens = a.ipc_section_lens();
1837 assert_eq!(lens.len(), 4);
1838 assert!(lens[0] > lens[2], "oid section {} must exceed type section {}", lens[0], lens[2]);
1839 }
1840
1841 /// The packed arm stores the same *payload* bytes — 33 per row against
1842 /// 8 + 8 + 1 + 8 + 8 — so nothing in the timing comparison is a
1843 /// memory-footprint effect in disguise. Its IPC **section** is nonetheless
1844 /// smaller, and the amount is asserted as a scaling law rather than as a
1845 /// constant, at two sizes, so it is attributed rather than hand-waved.
1846 ///
1847 /// Four fewer columns is four fewer per-column IPC buffers, and the
1848 /// saving grows linearly with row count at about `4 · n/8` bytes. It was
1849 /// `3 · n/8` — 38 016 B at 100 000 rows — before `delta_base` gave the
1850 /// columnar arm a fifth payload column. That is the only footprint
1851 /// difference between the three arms.
1852 ///
1853 /// Seen RED by asserting the two sections were within 4096 bytes of each
1854 /// other: "packed payload is 4525512 bytes against 4563528 columnar", which
1855 /// is what sent me to count buffers instead of guessing. Seen RED a second
1856 /// time by asserting the saving was *constant* across the two sizes:
1857 /// "saving did not scale: 38016 at 100000 rows, 75456 at 200000". Seen RED
1858 /// a third time by leaving the `3 · n/8` bound in place after the fifth
1859 /// column landed: "at 100000 rows the saving is 50560 B, not the ~37500 B
1860 /// that four fewer columns accounts for" — 50 560 B is `4 · n/8` plus
1861 /// framing, so the bound is counting real buffers rather than tracking a
1862 /// moving target.
1863 #[test]
1864 fn the_packed_arm_holds_the_same_payload_but_a_smaller_section() {
1865 let mut savings = Vec::new();
1866 for &n in &[100_000usize, 200_000] {
1867 let entries = synthetic_entries(n, 20, 0xBEE5);
1868 let (_, b, c) = arms(&entries);
1869
1870 // The payload itself is byte-for-byte the same size.
1871 let payload_bytes = n * (8 + 8 + 1 + 8 + 8);
1872 assert_eq!(c.payload.value_data().len(), payload_bytes);
1873 assert_eq!(c.payload.value_data().len(), n * PACKED_LEN);
1874
1875 let saving = b.ipc_bytes() as i64 - c.ipc_bytes() as i64;
1876 assert!(
1877 saving > 0,
1878 "the two-column section ({}) must not be larger than the six-column one ({})",
1879 c.ipc_bytes(),
1880 b.ipc_bytes()
1881 );
1882 // Four fewer columns, at roughly n/8 bytes of per-column buffer each.
1883 let expect = 4 * (n as i64) / 8;
1884 assert!(
1885 (expect..expect + 4096).contains(&saving),
1886 "at {n} rows the saving is {saving} B, not the ~{expect} B that four fewer \
1887 columns accounts for"
1888 );
1889 savings.push(saving);
1890 }
1891 assert!(
1892 savings[1] > savings[0] * 3 / 2,
1893 "saving did not scale: {} at 100000 rows, {} at 200000",
1894 savings[0],
1895 savings[1]
1896 );
1897 }
1898
1899 /// LAW 2 — the 8-byte prefix collision, carried through all three arms.
1900 ///
1901 /// Two oids sharing their first eight bytes share one stree key, so the tree
1902 /// alone cannot tell them apart. Every arm must still return each oid's own
1903 /// four facts, and a third oid on the same prefix that was never inserted
1904 /// must miss.
1905 ///
1906 /// Seen RED by replacing `OidResolver::ordinal`'s verified `tree.lookup`
1907 /// with the unverified `tree.candidate_run(key_for_oid(oid)).start` — i.e.
1908 /// trusting the 8-byte prefix: "collision resolved to the wrong row —
1909 /// left: 1000, right: 2000". Both colliding oids came back as the first
1910 /// candidate. Restored.
1911 #[test]
1912 fn a_prefix_collision_resolves_to_the_right_row_in_every_arm() {
1913 let prefix = [0xde, 0xad, 0xbe, 0xef, 0x01, 0x02, 0x03, 0x04];
1914 // The two colliding entries carry *different* delta bases, so a column
1915 // read at the wrong ordinal shows up here too and not only in `offset`.
1916 let mk = |last: u8, off: u64, ty: ObjType| {
1917 let mut oid = vec![0u8; 20];
1918 oid[..8].copy_from_slice(&prefix);
1919 oid[8] = last;
1920 IndexEntry {
1921 oid,
1922 offset: off,
1923 len: 10,
1924 obj_type: ty,
1925 uncompressed_size: off * 2,
1926 delta_base: off / 2,
1927 }
1928 };
1929 let mut entries = vec![mk(0xaa, 1000, ObjType::Commit), mk(0xbb, 2000, ObjType::OfsDelta)];
1930 entries.extend(synthetic_entries(200, 20, 99));
1931 let (a, b, c) = arms(&entries);
1932
1933 for (last, off, ty) in [(0xaau8, 1000u64, ObjType::Commit), (0xbb, 2000, ObjType::OfsDelta)]
1934 {
1935 let oid = mk(last, off, ty).oid;
1936 let ra = a.lookup(&oid).expect("colliding oid must resolve in A");
1937 let rb = b.lookup(&oid).expect("colliding oid must resolve in B");
1938 let rc = c.lookup(&oid).expect("colliding oid must resolve in C");
1939 assert_eq!(ra, rb);
1940 assert_eq!(ra, rc);
1941 assert_eq!(ra.offset, off, "collision resolved to the wrong row");
1942 assert_eq!(ra.obj_type, ty);
1943 assert_eq!(ra.delta_base, off / 2, "collision resolved to the wrong delta base");
1944 }
1945 let never = mk(0xcc, 0, ObjType::Blob).oid;
1946 assert_eq!(a.lookup(&never), None, "unstored oid on a colliding prefix must miss");
1947 assert_eq!(b.lookup(&never), None);
1948 assert_eq!(c.lookup(&never), None);
1949 }
1950
1951 /// All six pack type codes survive the round trip in every arm, including
1952 /// the two delta kinds that are the reason this fact is stored at all.
1953 ///
1954 /// Seen RED by mapping `ObjType::RefDelta` to code 6 in `code()`, colliding
1955 /// with `OfsDelta`: "type did not survive the column — left: OfsDelta,
1956 /// right: RefDelta". Restored.
1957 #[test]
1958 fn all_six_pack_types_round_trip_including_the_deltas() {
1959 let entries: Vec<IndexEntry> = ObjType::ALL
1960 .iter()
1961 .enumerate()
1962 .map(|(i, &t)| {
1963 let mut oid = vec![0u8; 32];
1964 oid[0] = i as u8 * 17;
1965 oid[31] = i as u8;
1966 IndexEntry {
1967 oid,
1968 offset: 100 + i as u64,
1969 len: 5,
1970 obj_type: t,
1971 uncompressed_size: 900 + i as u64,
1972 // Only the two delta codes carry a base, which is the
1973 // relationship the type column exists to express.
1974 delta_base: match t {
1975 ObjType::OfsDelta => 100,
1976 _ => 0,
1977 },
1978 }
1979 })
1980 .collect();
1981 let (a, b, c) = arms(&entries);
1982 let mut seen: Vec<ObjType> = Vec::new();
1983 for e in &entries {
1984 let ra = a.lookup(&e.oid).unwrap();
1985 assert_eq!(ra, b.lookup(&e.oid).unwrap());
1986 assert_eq!(ra, c.lookup(&e.oid).unwrap());
1987 assert_eq!(ra.obj_type, e.obj_type, "type did not survive the column");
1988 seen.push(ra.obj_type);
1989 }
1990 assert_eq!(seen, ObjType::ALL.to_vec(), "all six codes must be distinct");
1991 assert_eq!(ObjType::from_code(0), None);
1992 assert_eq!(ObjType::from_code(5), None, "git leaves 5 unused; it must not be mapped");
1993 assert_eq!(ObjType::from_code(8), None);
1994 }
1995
1996 /// An empty index and a one-row index are clean, not panics, in every arm.
1997 ///
1998 /// Seen RED by replacing `validate`'s empty-input `Ok(GitHashKind::Sha1)`
1999 /// with `bail!("an empty index")`: "A builds: an empty index" — every arm
2000 /// failed to construct at all. Restored.
2001 #[test]
2002 fn degenerate_sizes_are_clean_in_every_arm() {
2003 let (a, b, c) = arms(&[]);
2004 assert!(a.is_empty() && b.is_empty() && c.is_empty());
2005 let probe = vec![7u8; 20];
2006 assert_eq!(a.lookup(&probe), None);
2007 assert_eq!(b.lookup(&probe), None);
2008 assert_eq!(c.lookup(&probe), None);
2009 assert_eq!(c.lookup_batch(&[&probe[..]]), vec![None]);
2010 assert_eq!(c.extents_batch(&[&probe[..]]), vec![None]);
2011 // A scan over an empty index is 0, not a panic or a wrap.
2012 assert_eq!(c.sum_uncompressed(), 0);
2013 assert_eq!(c.count_type(ObjType::Blob), 0);
2014
2015 let one = synthetic_entries(1, 20, 5);
2016 let (a, b, c) = arms(&one);
2017 assert_eq!(a.lookup(&one[0].oid).unwrap(), b.lookup(&one[0].oid).unwrap());
2018 assert_eq!(a.lookup(&one[0].oid).unwrap(), c.lookup(&one[0].oid).unwrap());
2019 assert_eq!(c.lookup(&one[0].oid).unwrap().offset, one[0].offset);
2020 assert_eq!(c.sum_uncompressed(), one[0].uncompressed_size);
2021 }
2022
2023 /// A wrong-width oid is a miss, never a panic and never a wrong row —
2024 /// the query side of P-4.
2025 ///
2026 /// The width check inside `oid_index::lookup` is only a fast path; what
2027 /// actually makes this true is the **full-oid compare**, because
2028 /// `key_for_oid` zero-pads and an 8-byte truncation of a stored oid
2029 /// therefore lands on that oid's key. Seen RED by the same
2030 /// unverified-`candidate_run` edit as
2031 /// [`a_prefix_collision_resolves_to_the_right_row_in_every_arm`]:
2032 /// "a 8-byte oid must miss — left: Some(IndexRow { ordinal: 47, offset: 12,
2033 /// len: 1505, obj_type: RefDelta, uncompressed_size: 3010 }), right: None".
2034 /// Restored.
2035 #[test]
2036 fn a_wrong_width_oid_misses_in_every_arm() {
2037 let entries = synthetic_entries(64, 20, 21);
2038 let (a, b, c) = arms(&entries);
2039 let short = &entries[0].oid[..8];
2040 let mut long = entries[0].oid.clone();
2041 long.extend_from_slice(&[0u8; 12]);
2042 for q in [short, &long[..]] {
2043 assert_eq!(a.lookup(q), None, "a {}-byte oid must miss", q.len());
2044 assert_eq!(b.lookup(q), None);
2045 assert_eq!(c.lookup(q), None);
2046 }
2047 assert_eq!(a.lookup_batch(&[short, &long]), vec![None, None]);
2048 assert_eq!(b.lookup_batch(&[short, &long]), vec![None, None]);
2049 assert_eq!(c.lookup_batch(&[short, &long]), vec![None, None]);
2050 }
2051
2052 /// A duplicate oid, or a mix of sha1 and sha256, is refused at build.
2053 /// Silently keeping one of two identical oids would give the arms different
2054 /// ordinals for the same object and make every later comparison a lie.
2055 ///
2056 /// Seen RED by short-circuiting the duplicate scan in `validate` with
2057 /// `if false && …`: the build succeeded and the test panicked with
2058 /// "a duplicate oid must be refused at build". Restored.
2059 #[test]
2060 fn build_refuses_duplicates_and_mixed_widths() {
2061 fn why<T>(r: Result<T>, what: &str) -> String {
2062 match r {
2063 Ok(_) => panic!("{what} must be refused at build"),
2064 Err(e) => e.to_string(),
2065 }
2066 }
2067 let mut dup = synthetic_entries(4, 20, 1);
2068 dup.push(dup[0].clone());
2069 let err = why(FourTables::build(&dup), "a duplicate oid");
2070 assert!(err.contains("duplicate oid"), "{err}");
2071 assert!(OneTableFourColumns::build(&dup).is_err());
2072 assert!(PackedPayload::build(&dup).is_err());
2073
2074 let mut mixed = synthetic_entries(4, 20, 2);
2075 mixed.push(synthetic_entries(1, 32, 3).pop().unwrap());
2076 let err = why(PackedPayload::build(&mixed), "a mixed-width index");
2077 assert!(err.contains("mixed oid widths"), "{err}");
2078 assert!(FourTables::build(&mixed).is_err());
2079 assert!(OneTableFourColumns::build(&mixed).is_err());
2080 }
2081
2082 /// Every arm is `Send + Sync`, which is what lets a server share one index
2083 /// across connection handlers. A compile-time assertion, plus an actual
2084 /// cross-thread lookup so it is not only a type-level claim.
2085 ///
2086 /// Seen RED by dropping `Send + Sync` from the `ObjectIndex` supertrait
2087 /// list: "error[E0277]: `dyn index_layout::ObjectIndex` cannot be shared
2088 /// between threads safely" and the same for `Send` — the crate stopped
2089 /// compiling. Restored.
2090 #[test]
2091 fn an_index_can_be_shared_across_threads() {
2092 fn assert_send_sync<T: Send + Sync>() {}
2093 assert_send_sync::<FourTables>();
2094 assert_send_sync::<OneTableFourColumns>();
2095 assert_send_sync::<PackedPayload>();
2096
2097 let entries = synthetic_entries(256, 20, 42);
2098 let a: Arc<dyn ObjectIndex> = Arc::new(FourTables::build(&entries).unwrap());
2099 let b: Arc<dyn ObjectIndex> = Arc::new(OneTableFourColumns::build(&entries).unwrap());
2100 let c: Arc<dyn ObjectIndex> = Arc::new(PackedPayload::build(&entries).unwrap());
2101 let oids: Vec<Vec<u8>> = entries.iter().map(|e| e.oid.clone()).collect();
2102 let mut handles = Vec::new();
2103 for idx in [a, b, c] {
2104 let oids = oids.clone();
2105 handles.push(std::thread::spawn(move || {
2106 let refs: Vec<&[u8]> = oids.iter().map(|o| o.as_slice()).collect();
2107 idx.lookup_batch(&refs).iter().filter(|r| r.is_some()).count()
2108 }));
2109 }
2110 for h in handles {
2111 assert_eq!(h.join().unwrap(), 256, "every oid must resolve off-thread");
2112 }
2113 }
2114}