Skip to main content

git_storage_trait/
lib.rs

1//! **The git-storage contract: `GitOps`, the backend-neutral eleven.**
2//!
3//! This is the contract written into `znippy-plugin-git`'s `store.rs`
4//! ("*The twelve functions. Nothing else is permitted here.*"), lifted out so it
5//! is no longer owned by one implementation. It defines *what a git object+ref
6//! store must be able to do*, and names no storage, no index, no durability
7//! mechanism and no codec — so both backends implement the **same** trait:
8//!
9//! | implementer | where | how it stores |
10//! |---|---|---|
11//! | `znippy-plugin-git` | `plugins/native/znippy-plugin-git` (this repo) | Arrow-IPC in a znippy archive (OpenZL) |
12//! | `storage-git-gix` | `edda/crates/storage-git-gix` | `gix-odb` / `gix-ref` on a filesystem |
13//!
14//! # Why this crate is tiny, and must stay that way
15//!
16//! It depends on `anyhow` and nothing else. That is load-bearing: the gix
17//! backend must be able to implement this contract **without** linking Arrow or
18//! OpenZL's C++ toolchain, and the znippy backend must not have to link `gix`.
19//! A dependency added here is a dependency forced on both.
20//!
21//! # "Eleven", not "twelve" — where `seal()` went
22//!
23//! The original `GitOps` in znippy had a twelfth method, `seal() ->
24//! Vec<ReservedSection>`, that folds the live logs into the reserved **Arrow**
25//! sections a znippy archive carries. `ReservedSection` is an Arrow type
26//! (`RecordBatch` payloads); a gix backend has no such sections and no analog.
27//! So `seal()` is an implementation detail of the znippy backend, not part of
28//! the neutral contract — it stays an inherent method on `GitStore`, which is
29//! how gunnar already calls it (on the concrete store, never through this
30//! trait). Keeping it here would have forced Arrow onto the gix backend for a
31//! method it can never implement.
32
33use std::path::PathBuf;
34
35use anyhow::Result;
36
37/// An object id, borrowed.
38pub type Oid<'a> = &'a [u8];
39
40/// A byte range inside the store: `(offset, len)`.
41///
42/// The unit is "wherever this backend keeps the bytes" — an extent in a znippy
43/// archive, or an offset into a packfile for a gix backend. The contract only
44/// promises the pair is stable for the life of the object.
45pub type Extent = (u64, u64);
46
47/// The type of a stored object, as it appears **in the pack** — so it may be a
48/// delta (`OfsDelta`/`RefDelta`) rather than a resolved type.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
50#[repr(u8)]
51pub enum ObjType {
52    Commit = 1,
53    Tree = 2,
54    Blob = 3,
55    Tag = 4,
56    OfsDelta = 6,
57    RefDelta = 7,
58}
59
60impl ObjType {
61    pub fn code(self) -> u8 {
62        self as u8
63    }
64
65    /// `None` for 0, 5 and anything above 7 — a wrong type in an index is worse
66    /// than an honest failure, because it is queried and believed.
67    pub fn from_code(c: u8) -> Option<Self> {
68        Some(match c {
69            1 => ObjType::Commit,
70            2 => ObjType::Tree,
71            3 => ObjType::Blob,
72            4 => ObjType::Tag,
73            6 => ObjType::OfsDelta,
74            7 => ObjType::RefDelta,
75            _ => return None,
76        })
77    }
78
79    pub fn as_str(self) -> &'static str {
80        match self {
81            ObjType::Commit => "commit",
82            ObjType::Tree => "tree",
83            ObjType::Blob => "blob",
84            ObjType::Tag => "tag",
85            ObjType::OfsDelta => "ofs-delta",
86            ObjType::RefDelta => "ref-delta",
87        }
88    }
89
90    /// The six codes, for exhaustive tests and for generators.
91    pub const ALL: [ObjType; 6] = [
92        ObjType::Commit,
93        ObjType::Tree,
94        ObjType::Blob,
95        ObjType::Tag,
96        ObjType::OfsDelta,
97        ObjType::RefDelta,
98    ];
99}
100
101/// The receipt for one durable transaction.
102///
103/// Not an opaque counter: a push spans **two** durable logs — the one that
104/// claims the pack's extent and the one whose frame *is* the ref transaction —
105/// and a caller that has to prove a push landed needs a coordinate in each.
106/// Every field is applied output, read back from what was written.
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
108pub struct TxId {
109    /// Dense id the push path assigned this pack, and the key the indexed bit is
110    /// kept under. `None` when the transaction carried no pack.
111    pub pack_id: Option<u64>,
112    /// Where the verbatim pack bytes are, as the journal row records them.
113    pub extent: Option<Extent>,
114    /// The ref log's ordering authority for the ref namespace. `None` when the
115    /// transaction carried no ref update.
116    pub push_seq: Option<u64>,
117}
118
119/// One row of the ref namespace: name, oid, peeled.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct RefRow {
122    pub name: String,
123    /// Raw oid. `None` for a purely symbolic ref such as `HEAD`.
124    pub oid: Option<Vec<u8>>,
125    /// For an annotated tag, the commit it peels to.
126    pub peeled: Option<Vec<u8>>,
127    /// For a symbolic ref, what it points at.
128    pub symref_target: Option<String>,
129}
130
131/// One ref update in a push.
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct RefUpdate {
134    pub name: String,
135    pub target: Option<String>,
136    pub peeled: Option<String>,
137    pub symref_target: Option<String>,
138}
139
140impl RefUpdate {
141    /// Set `name` to `target`.
142    pub fn set(name: impl Into<String>, target: impl Into<String>) -> Self {
143        Self {
144            name: name.into(),
145            target: Some(target.into()),
146            peeled: None,
147            symref_target: None,
148        }
149    }
150
151    /// Delete `name`.
152    pub fn delete(name: impl Into<String>) -> Self {
153        Self {
154            name: name.into(),
155            target: None,
156            peeled: None,
157            symref_target: None,
158        }
159    }
160
161    /// Point the symbolic ref `name` at `points_to`.
162    pub fn symbolic(name: impl Into<String>, points_to: impl Into<String>) -> Self {
163        Self {
164            name: name.into(),
165            target: None,
166            peeled: None,
167            symref_target: Some(points_to.into()),
168        }
169    }
170
171    /// Attach the peeled target of an annotated tag.
172    pub fn with_peeled(mut self, peeled: impl Into<String>) -> Self {
173        self.peeled = Some(peeled.into());
174        self
175    }
176}
177
178/// One ref edit **with the value the caller expects to find**.
179///
180/// This is the field [`RefUpdate`] lacks, and its absence is the whole reason
181/// `git push --atomic` could not be expressed: [`GitOps::put_refs`] is a batch
182/// *without* compare-and-swap and [`GitOps::update_ref`] is compare-and-swap
183/// *without* a batch, and `--atomic` is defined as both at once. Neither
184/// composes into the other — applying a batch one CAS at a time is exactly the
185/// partial application `--atomic` promises never to happen.
186///
187/// `old` and `new` are borrowed, like every other oid in this contract: a
188/// receive-pack command line is `<old> <new> <ref>` and both oids are already
189/// slices of the pkt-line the caller is holding. [`peeled`](RefCas::peeled) is
190/// the one that is **owned**, because it is not on the wire — it is derived by
191/// the server, once, at ingest.
192#[derive(Debug, Clone, PartialEq, Eq)]
193pub struct RefCas<'a> {
194    pub name: String,
195    /// What the caller believes is there. **`None` means *must not exist*** — a
196    /// create that must fail if anything is already at `name`.
197    ///
198    /// There is deliberately no third "don't care" state. receive-pack always
199    /// names an old value (all-zeroes for a create), so a caller that genuinely
200    /// does not care wants [`GitOps::put_refs`], which is the batch that makes no
201    /// claim about the previous value.
202    pub old: Option<Oid<'a>>,
203    /// The new value. **`None` deletes.**
204    pub new: Option<Oid<'a>>,
205    /// For an annotated tag, the commit `new` peels to — the terminal non-tag
206    /// object, following a tag-of-a-tag all the way down, exactly as git's
207    /// `packed-refs` stores its `^peeled` line.
208    ///
209    /// **Owned, and `None` for everything else.** A branch head, a lightweight
210    /// tag and a delete peel to nothing worth storing, so they carry `None`;
211    /// only a `new` that is itself a tag object carries `Some`. The backend
212    /// persists it in the ref row's peeled column so the advertisement
213    /// ([`GitServe`]) reads the peeled target straight out of the row and never
214    /// re-peels — the object read per tag that every clone, fetch and `ls-remote`
215    /// used to pay (gunnar stinky S-080) falls to zero.
216    ///
217    /// It is owned rather than an [`Oid`] because, unlike `old`/`new`, it is not
218    /// a slice of any pkt-line the caller holds: the peel is computed by the
219    /// server from the objects the push just delivered. A backend that keeps no
220    /// peel column, or a caller that does not compute one, leaves it `None` and
221    /// the advertisement falls back to peeling — correct, only not free.
222    pub peeled: Option<Vec<u8>>,
223}
224
225/// One ref target, backend-neutrally: an object, or another ref.
226///
227/// Named separately from [`RefRow`] because this is what was *observed* at one
228/// instant during a failed compare-and-swap, not a row of the namespace.
229#[derive(Debug, Clone, PartialEq, Eq)]
230pub enum RefTarget {
231    /// A raw oid.
232    Object(Vec<u8>),
233    /// A symbolic ref: the full name it points at.
234    Symbolic(String),
235}
236
237/// What was actually there — **including** the case where something was there
238/// and could not be decoded.
239///
240/// Restored from `gunnar-store`'s deleted `Error` type, and the three-state is
241/// the point. The two call sites that produce it in the gix arm used to write
242/// `from_gix_target(actual).ok()`, which turned a reference that existed and
243/// could not be read into `None` — reported to the pushing client as *"nothing
244/// was there"*. A backend that reports no observed value for a rejection
245/// answers [`Observed::Nothing`], which is *"the honest answer rather than a
246/// dropped one"*, and a backend that found bytes it could not parse answers
247/// [`Observed::Unreadable`]. Collapsing those two is the defect this enum
248/// exists to make impossible.
249#[derive(Debug, Clone, PartialEq, Eq)]
250pub enum Observed {
251    /// The ref did not exist.
252    Nothing,
253    /// It existed and held this.
254    Value(RefTarget),
255    /// It existed, and the backend could not decode what it held.
256    Unreadable(String),
257}
258
259impl Observed {
260    /// An expectation of "must not exist", as an [`Observed`].
261    pub fn absent() -> Self {
262        Observed::Nothing
263    }
264
265    /// An oid, as an [`Observed`].
266    pub fn oid(raw: &[u8]) -> Self {
267        Observed::Value(RefTarget::Object(raw.to_vec()))
268    }
269
270    pub fn is_unreadable(&self) -> bool {
271        matches!(self, Observed::Unreadable(_))
272    }
273}
274
275/// Lowercase hex, written out because this crate depends on `anyhow` and
276/// nothing else and a rejection has to be printable.
277fn hex_into(f: &mut std::fmt::Formatter<'_>, raw: &[u8]) -> std::fmt::Result {
278    for b in raw {
279        write!(f, "{b:02x}")?;
280    }
281    Ok(())
282}
283
284impl std::fmt::Display for Observed {
285    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
286        match self {
287            Observed::Nothing => f.write_str("nothing"),
288            Observed::Value(RefTarget::Object(raw)) => hex_into(f, raw),
289            Observed::Value(RefTarget::Symbolic(name)) => write!(f, "ref: {name}"),
290            Observed::Unreadable(why) => {
291                write!(f, "a value that could not be decoded: {why}")
292            }
293        }
294    }
295}
296
297/// **Why a ref write was refused, typed.**
298///
299/// # Why this exists at all
300///
301/// `Error::is_cas_failure()` / `is_lock_contention()` died with `RefStore`, and
302/// receive-pack has to tell a client *which* ref lost the race and what was
303/// there instead — **never by sniffing an error string**. `gunnar-store`'s
304/// `error.rs` records the loss verbatim: this type *"used to carry
305/// `RefCas { name, expected, actual }` and the `Observed` three-state beside
306/// it"*. This is that, restored, in the one crate both backends already share.
307///
308/// # How it travels, and why the crate is still `anyhow`-only
309///
310/// The trait methods keep returning `anyhow::Result`, so no signature in the
311/// frozen contract changes and no caller is forced to match on a storage error
312/// it does not care about. This type implements [`std::error::Error`] by hand —
313/// no `thiserror`, no new dependency — so a backend raises it with
314/// `anyhow::Error::new(rejection)` and a caller that *does* care recovers it
315/// with [`RefRejection::of`]. The tiny-crate property is about not forcing one
316/// backend's dependencies onto the other; it was never about refusing to name
317/// this crate's own errors.
318///
319/// # The two variants, and why `Locked` is one of them
320///
321/// From the gix arm's classifier, whose comment is the argument: a lock this
322/// writer could not take is *"**TYPED, not a `Backend`**: it is transient and
323/// the one control-document writer retries it. Left as an opaque backend error
324/// it read to a caller as a broken disk."*
325#[derive(Debug, Clone, PartialEq, Eq)]
326pub enum RefRejection {
327    /// A compare-and-swap lost: `name` did not hold what the caller expected,
328    /// and **nothing was written**.
329    ///
330    /// `expected` is the caller's claim ([`Observed::Nothing`] for a
331    /// must-not-exist create); `actual` is what the backend found.
332    Cas {
333        name: String,
334        expected: Observed,
335        actual: Observed,
336    },
337    /// A lock on `name` this writer could not take. Transient — the caller
338    /// retries. Not a fault, and specifically not a broken disk.
339    Locked { name: String },
340}
341
342impl RefRejection {
343    /// The ref this is about.
344    pub fn name(&self) -> &str {
345        match self {
346            RefRejection::Cas { name, .. } | RefRejection::Locked { name } => name,
347        }
348    }
349
350    /// *"Another push beat you to it"* — a lost race, not a fault.
351    pub fn is_cas_failure(&self) -> bool {
352        matches!(self, RefRejection::Cas { .. })
353    }
354
355    /// *"Try again"* — transient contention on the one writer.
356    pub fn is_lock_contention(&self) -> bool {
357        matches!(self, RefRejection::Locked { .. })
358    }
359
360    /// Recover a rejection from an [`anyhow::Error`] a backend raised.
361    ///
362    /// **This is the only sanctioned way to ask, and it is a named function so
363    /// that no caller ever spells `downcast_ref` — or, worse, matches on the
364    /// message text.** It walks the context chain, so a backend is free to add
365    /// `.context(..)` above the rejection without hiding it.
366    pub fn of(err: &anyhow::Error) -> Option<&RefRejection> {
367        err.chain().find_map(|e| e.downcast_ref::<RefRejection>())
368    }
369}
370
371impl std::fmt::Display for RefRejection {
372    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
373        match self {
374            RefRejection::Cas {
375                name,
376                expected,
377                actual,
378            } => write!(
379                f,
380                "compare-and-swap on {name} failed: it is {actual}, the caller expected \
381                 {expected} — nothing was written"
382            ),
383            RefRejection::Locked { name } => write!(
384                f,
385                "{name} is locked by another writer — transient, retry; this is not a \
386                 backend fault"
387            ),
388        }
389    }
390}
391
392impl std::error::Error for RefRejection {}
393
394/// What `get` hands back: the **stored** bytes and enough type information that
395/// they cannot be mistaken for something else.
396///
397/// `obj_type` is the entry's type *in the pack*, so it may be `OfsDelta` or
398/// `RefDelta`. That is deliberate and it is the whole reason this is a struct and
399/// not a `Vec<u8>`: the verbatim bytes are the truth and the resolved object a
400/// derived cache, and a caller handed delta bytes labelled "the object" would
401/// silently store garbage. Labelled a delta, it cannot.
402#[derive(Debug, Clone, PartialEq, Eq)]
403pub struct Stored {
404    pub obj_type: ObjType,
405    /// Post-resolution size — what the object inflates to once its chain is
406    /// applied, which is not `bytes.len()` for a delta.
407    pub uncompressed_size: u64,
408    /// Where these bytes live.
409    pub extent: Extent,
410    /// The bytes as stored: the pack entry, header and all, byte for byte as the
411    /// client sent them.
412    pub bytes: Vec<u8>,
413}
414
415/// What one GC run did. Every field is measured off the store after the fact —
416/// nothing here is an input echoed back.
417#[derive(Debug, Clone, PartialEq, Eq)]
418pub struct GcReport {
419    /// The name of the implementation that produced this.
420    pub strategy: &'static str,
421    /// The store that serves after the run.
422    pub archive: PathBuf,
423    /// The generation that was removed once the new one was proven. `None` for
424    /// an in-place compaction that has no distinct old file to remove.
425    pub retired: Option<PathBuf>,
426    pub bytes_before: u64,
427    pub bytes_after: u64,
428    /// Live entries carried across. A GC never changes this.
429    pub rows: u64,
430    /// Delta-map rows carried across. Also never changed.
431    pub delta_rows: u64,
432    /// Whether the result was read back and checked. `false` does not mean it
433    /// failed — an in-place compaction verifies *after* it has committed.
434    pub verified: bool,
435    /// Packs whose **every** object this run found dead, and whose rows it
436    /// therefore tombstoned.
437    pub retired_packs: u64,
438}
439
440/// **Where a store says how much of a pack it has taken in, while it is still
441/// taking it in.**
442///
443/// The one seam [`GitOps::put_pack_observed`] adds, and it is deliberately one
444/// method taking two plain integers. It is not `FnMut`, it is not a channel,
445/// and it carries no state of its own:
446///
447/// * **`&self`, not `&mut self`** — a store is shared across threads
448///   (`GitOps: Send + Sync`) and an implementer is free to publish from
449///   whichever one is doing the splitting. A sink that needs to mutate owns its
450///   own `Mutex`/atomic, which is the sink's business and not the store's.
451/// * **`Sync`** — same reason, and it is what lets a `&dyn PackProgress` cross
452///   into a store that is being shared.
453/// * **two `u64`s and no receipt** — publishing must not be able to fail the
454///   ingest. A store that gave up on a push because a progress bar was not
455///   listening would be trading correctness for cosmetics.
456///
457/// # The contract on the numbers
458///
459/// `done` is monotone non-decreasing across one call to
460/// [`GitOps::put_pack_observed`], `total` is constant, and the last publish of
461/// a successful call is `done == total`. A sink may therefore render
462/// `done/total` verbatim and never see it go backwards or overshoot.
463///
464/// **Per batch is allowed; per pack is not.** An implementer whose loop is
465/// genuinely batched may publish once per batch — a count that moves in steps
466/// of a thousand is a count that moves. What is forbidden is a single step from
467/// `0` to `total`, which is what a store that publishes nothing already looks
468/// like and is exactly the thing being fixed.
469pub trait PackProgress: Sync {
470    /// `done` of `total` objects of this pack are in.
471    fn indexed(&self, done: u64, total: u64);
472}
473
474/// **The eleven.** Typed, backend-neutral, and the only entry point a git server
475/// needs into storage.
476///
477/// Implemented by znippy's `GitStore` (Arrow-IPC) and by `storage-git-gix`
478/// (gix). No method invents storage, an index, a durability contract or a
479/// concurrency mechanism; if one looks like it does, that is the bug.
480/// `Send + Sync` is a supertrait because every consumer shares one store across
481/// threads and cannot do otherwise. gunnar's `RepoStore` is `Send + Sync` — the
482/// server holds one per repository and serves many connections from it at once —
483/// so a `RepoStore` holding an `Arc<dyn GitOps>` does not compile without this
484/// (`E0277` at every implementor). The traits `GitOps` replaced, `ObjectStore`
485/// and `RefStore`, both carried it; dropping it here was an oversight of the
486/// extraction, not a decision.
487///
488/// It costs the implementers nothing: both already satisfy it. The Arrow arm is
489/// built around a per-account indexer thread and declares `ArchiveWrite: Send +
490/// Sync` and `ObjectAbsorb: Send + Sync` itself; the gix arm shares a pooled odb
491/// handle across workers. The alternative — spelling `dyn GitOps + Send + Sync`
492/// at every use site — is viral, and a consumer who forgets it gets a different
493/// type rather than an error at the definition.
494pub trait GitOps: Send + Sync {
495    // ── STORE ───────────────────────────────────────────────────────────────
496
497    /// One push: pack bytes and ref updates, durable before this returns.
498    ///
499    /// The order inside it is the contract: the pack's bytes durable **first**,
500    /// then the refs that point into them. A crash between the two leaves
501    /// objects nobody points at (a GC reclaims them); the reverse order leaves a
502    /// ref pointing at objects that are not there, which no later pass repairs.
503    fn put(&self, pack: &[u8], refs: &[RefUpdate]) -> Result<TxId>;
504
505    /// The pack half of [`put`](GitOps::put), on its own.
506    fn put_pack(&self, bytes: &[u8]) -> Result<TxId>;
507
508    /// [`put_pack`](GitOps::put_pack), **saying how far it has got while it is
509    /// still getting there**.
510    ///
511    /// # Why this is a defaulted sibling and not a parameter on `put_pack`
512    ///
513    /// A caller that wants no progress must not have to say so, and — far more
514    /// importantly — **no existing implementer must have to change**. Every
515    /// backend, bench harness and test double in three repositories implements
516    /// `GitOps`; a new required method, or a new argument on an existing one,
517    /// would be a compile error in all of them for a feature none of them owes.
518    /// With a default they keep compiling and simply publish nothing, which is
519    /// the honest answer for a store that has no per-object loop to hang a
520    /// count on.
521    ///
522    /// # What "honest" means here, and what a store must not do
523    ///
524    /// The count is the **caller's numerator**, and the only thing on the
525    /// system that knows it is the code that is already splitting the pack.
526    /// Recovering it anywhere else means inflating every entry a second time —
527    /// a second pack decoder, which LAW 5 forbids and which would be a slower
528    /// and separately-wrong copy of the one that exists.
529    ///
530    /// So an implementer either has an entry loop and reports from inside it,
531    /// or it reports nothing. What it must **never** do is fabricate the shape:
532    /// publishing `(0, N)` and then `(N, N)` around a call that reports nothing
533    /// is indistinguishable, to a console, from a store that genuinely counts —
534    /// and that is precisely the defect this method exists to close.
535    ///
536    /// An implementer that overrides this must also answer
537    /// [`publishes_pack_progress`](GitOps::publishes_pack_progress) with
538    /// `true`, or the conformance suite will pass it vacuously and the override
539    /// will go unchecked for ever.
540    fn put_pack_observed(&self, bytes: &[u8], progress: &dyn PackProgress) -> Result<TxId> {
541        // Named, not `..`: the default is a *decision* — "this store cannot see
542        // its own entries go past" — and a reader should see the sink being
543        // deliberately dropped rather than an argument that looks forgotten.
544        let _unpublished = progress;
545        self.put_pack(bytes)
546    }
547
548    /// **Does [`put_pack_observed`](GitOps::put_pack_observed) actually
549    /// publish?** `false` for the default implementation.
550    ///
551    /// This exists for LAW 2, and only for LAW 2: a store that publishes
552    /// nothing and a store whose publishing is broken are the same store as far
553    /// as any assertion can tell, because both produce an empty series. The
554    /// conformance suite therefore asks first — a `true` is held to the
555    /// property, a `false` passes **by name**, and neither can be mistaken for
556    /// the other in a report.
557    fn publishes_pack_progress(&self) -> bool {
558        false
559    }
560
561    /// The ref half of [`put`](GitOps::put), on its own.
562    fn put_refs(&self, updates: &[RefUpdate]) -> Result<TxId>;
563
564    // ── READ ────────────────────────────────────────────────────────────────
565
566    /// The stored bytes of one object.
567    fn get(&self, oid: Oid<'_>) -> Result<Option<Stored>>;
568
569    /// Is this object here? The negotiation call, made a thousand at a time.
570    fn has(&self, oid: Oid<'_>) -> Result<bool>;
571
572    /// Post-resolution size.
573    fn size(&self, oid: Oid<'_>) -> Result<Option<u64>>;
574
575    /// Byte extents, in bulk — the wire path.
576    fn extents(&self, oids: &[Oid<'_>]) -> Result<Vec<Option<Extent>>>;
577
578    // ── REFS ────────────────────────────────────────────────────────────────
579
580    /// The current ref namespace.
581    fn refs(&self) -> Result<Vec<RefRow>>;
582
583    /// Compare-and-swap one ref.
584    fn update_ref(&self, name: &str, old: Option<Oid<'_>>, new: Option<Oid<'_>>) -> Result<TxId>;
585
586    /// **Apply every edit or none.** The `git push --atomic` primitive.
587    ///
588    /// The third shape, not a replacement: [`put_refs`](GitOps::put_refs) (batch,
589    /// no CAS) and [`update_ref`](GitOps::update_ref) (CAS, one ref) both stay,
590    /// and both have callers that want exactly what they are.
591    ///
592    /// Returns `Err` naming the **first** edit whose `old` did not match, and
593    /// applies **nothing**. That error carries a [`RefRejection`], recoverable
594    /// with [`RefRejection::of`] — receive-pack must be able to tell a client
595    /// which ref lost the race and what was there instead, and it must never do
596    /// that by reading a message.
597    ///
598    /// # Every expectation is checked BEFORE anything is applied — `S-023`
599    ///
600    /// Not a stylistic preference; it is the one implementation note this method
601    /// carries, and it is a real defect found in a real backend. gix's file ref
602    /// store **short-circuits an edit whose new value equals the value the
603    /// reference already holds**: it rewrites the expectation to
604    /// `MustExistAndMatch(current)` and never evaluates the one the caller
605    /// wrote. For an `old: None` — *must not exist* — that turns a create that
606    /// must fail into a **silent success**, so "exactly one creator wins", the
607    /// property receive-pack arbitrates two racing pushes with, was not true on
608    /// the only backend that survives a restart.
609    ///
610    /// So an implementation compares against **one snapshot of the namespace,
611    /// taken once, before the batch reaches the backend's own writer.**
612    ///
613    /// # There is no third state
614    ///
615    /// An empty batch is a no-op that succeeds, not an error: a deletions-free
616    /// push with nothing to apply calls this, and refusing it would make the
617    /// caller special-case the empty case at every site.
618    fn put_refs_cas(&self, edits: &[RefCas<'_>]) -> Result<TxId>;
619
620    // ── GRAPH ───────────────────────────────────────────────────────────────
621
622    /// `want` minus `have`, the object closure a fetch must send.
623    fn reachable(&self, want: &[Oid<'_>], have: &[Oid<'_>]) -> Result<Vec<Vec<u8>>>;
624
625    // ── MAINT ───────────────────────────────────────────────────────────────
626
627    /// Reachability, drop the dead index rows, then compact.
628    fn gc(&self) -> Result<GcReport>;
629}
630
631// ── the reading contract ─────────────────────────────────────────────────────
632
633/// What the client said it can parse, as far as **pack emission** is concerned.
634///
635/// Deliberately not "the capability line": a capability that does not change
636/// which bytes come out of [`GitServe::emit_pack`] does not belong here, and
637/// side-band, progress, agent strings and shallow negotiation all change the
638/// *transport*, which is the caller's.
639///
640/// **There is no `Default`, on purpose.** A caller that forgets a field would
641/// otherwise send a pack the client cannot parse, and it would look like a
642/// working server producing a corrupt clone — the failure nobody notices. Both
643/// fields are stated at every call site or the code does not compile. Use
644/// [`Caps::modern`] in a test that does not care.
645#[derive(Debug, Clone, Copy, PartialEq, Eq)]
646pub struct Caps {
647    /// The client accepts a **thin** pack: one whose deltas may name bases it
648    /// already holds and this pack does not carry.
649    ///
650    /// It is an *allowance*, never a requirement. A backend that always closes
651    /// its emission over every delta base is correct for `thin: true` as well —
652    /// it costs bytes, never correctness — so ignoring this flag is a
653    /// performance decision an implementation may take and should document.
654    pub thin: bool,
655    /// The client accepts `OFS_DELTA` entries (bases named by backwards
656    /// distance). Every git since 1.5.5 advertises it.
657    ///
658    /// When this is `false` a backend that stores entries verbatim **cannot
659    /// copy** an `OFS_DELTA` out: the distance means nothing to a reader that
660    /// will not parse it. The honest answers are to rewrite the entry as a
661    /// `REF_DELTA` or to refuse. Silently emitting one anyway is not an answer.
662    pub ofs_delta: bool,
663}
664
665impl Caps {
666    /// What every git client made this century advertises. For tests and for a
667    /// caller that has already validated the capability line.
668    pub fn modern() -> Self {
669        Caps {
670            thin: false,
671            ofs_delta: true,
672        }
673    }
674}
675
676/// The receipt for one [`GitServe::emit_pack`].
677///
678/// **`copied` and `recompressed` are the point** — the `P-001` applied-output
679/// assertion. A byte count and a wall clock cannot tell a pack-copy from a
680/// re-deflate: both produce a pack that passes `git index-pack --strict` and
681/// `git fsck`, and the slow one is only visible as a number nobody was
682/// recording. Both engines' `git-store-serve` already emit exactly this
683/// receipt, so a head-to-head stays a comparison rather than two anecdotes.
684#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
685pub struct PackStats {
686    /// Bytes written to `out`, trailer included.
687    pub bytes: u64,
688    /// Entries in the emitted pack.
689    pub objects: u64,
690    /// Entries whose stored payload went out **byte for byte**. Nothing was
691    /// inflated and nothing was deflated for these.
692    pub copied: u64,
693    /// Entries whose payload was re-deflated. On a store that keeps pack
694    /// entries verbatim this must be zero, and it is counted rather than
695    /// assumed for exactly that reason.
696    pub recompressed: u64,
697}
698
699/// **Many raw oids in ONE allocation.**
700///
701/// A `Vec<Vec<u8>>` of oids is one heap allocation *per object*, and the two
702/// things a store does with a repository-sized oid set — hand it across this
703/// contract, and ask it "do you hold this" — need neither. This is the flat
704/// form: `len × oid_len` bytes in a single buffer, iterated as slices.
705///
706/// # Why it is here and not in either engine
707///
708/// Because both engines cross this seam with one. MEASURED on oden 2026-08-15,
709/// the znippy engine serving a 69-object negotiated fetch out of the `nornir`
710/// mirror (12 303 objects, `have` closure 12 112): [`ReachSet::client_has`]
711/// alone was **12 112 `String`s and 12 112 `Vec<u8>`s per request** on the way
712/// through a hex round-trip, for a voucher whose only consumers ask its length
713/// and its membership. The gix engine pays the smaller half of the same bill —
714/// one `Vec<u8>` per `ObjectId` — and it pays it for the same reason: the
715/// contract's type demanded one. Fixing it in one engine and not the other
716/// would be the twinning LAW 5 forbids.
717///
718/// # What it is not
719///
720/// Not a set: [`contains`](OidList::contains) is a linear scan, stated rather
721/// than hidden, because this type's job is *carrying* oids cheaply. A consumer
722/// that asks membership per object builds its own index off
723/// [`iter`](OidList::iter) — a `HashSet` of fixed-size keys costs one
724/// allocation for the table and none per entry, which is the whole point.
725///
726/// Not sorted, and not deduplicated: it preserves exactly what was pushed.
727#[derive(Debug, Clone, PartialEq, Eq, Default)]
728pub struct OidList {
729    /// `len * oid_len` bytes, concatenated in push order.
730    bytes: Vec<u8>,
731    /// The width of one oid — 20 for SHA-1, 32 for SHA-256.
732    ///
733    /// **Zero exactly when the list is empty**, which is what keeps
734    /// [`Default`] equal to an empty list built by any engine at any width. A
735    /// list that has never been pushed to has no width to disagree about.
736    oid_len: usize,
737}
738
739impl OidList {
740    /// An empty list. Its width is decided by the first [`push`](Self::push).
741    pub fn new() -> Self {
742        Self::default()
743    }
744
745    /// An empty list with room for `oids` oids of `oid_len` bytes, in one
746    /// allocation. The width is still decided by the first push — this only
747    /// reserves.
748    pub fn with_capacity(oids: usize, oid_len: usize) -> Self {
749        OidList {
750            bytes: Vec::with_capacity(oids * oid_len),
751            oid_len: 0,
752        }
753    }
754
755    /// Append one raw oid.
756    ///
757    /// The first push fixes the width; a later one of a different width is an
758    /// error rather than a silently reinterpreted buffer, because every
759    /// accessor here is `len`-strided and a mixed list would hand back oids
760    /// that never existed.
761    pub fn push(&mut self, oid: &[u8]) -> Result<()> {
762        if self.bytes.is_empty() {
763            anyhow::ensure!(
764                !oid.is_empty(),
765                "an empty oid has no width, and a list of them would report a length of zero \
766                 objects while holding some"
767            );
768            self.oid_len = oid.len();
769        } else if oid.len() != self.oid_len {
770            anyhow::bail!(
771                "this oid list is {}-byte oids and was handed a {}-byte one; a mixed-width list \
772                 cannot be read back",
773                self.oid_len,
774                oid.len()
775            );
776        }
777        self.bytes.extend_from_slice(oid);
778        Ok(())
779    }
780
781    /// Every oid, in push order, borrowed out of the one buffer.
782    pub fn iter(&self) -> impl ExactSizeIterator<Item = &[u8]> + '_ {
783        self.bytes.chunks_exact(self.oid_len.max(1))
784    }
785
786    /// How many oids — **not** how many bytes.
787    pub fn len(&self) -> usize {
788        if self.oid_len == 0 {
789            0
790        } else {
791            self.bytes.len() / self.oid_len
792        }
793    }
794
795    /// Whether it names nothing. For a voucher this is the clone case.
796    pub fn is_empty(&self) -> bool {
797        self.bytes.is_empty()
798    }
799
800    /// The width of one oid, or 0 for an empty list.
801    pub fn oid_len(&self) -> usize {
802        self.oid_len
803    }
804
805    /// **A linear scan.** Fine for a guard and for a handful of probes; wrong
806    /// in a loop over a request. See the type's header.
807    pub fn contains(&self, oid: &[u8]) -> bool {
808        oid.len() == self.oid_len && self.iter().any(|o| o == oid)
809    }
810}
811
812impl<T: AsRef<[u8]>> FromIterator<T> for OidList {
813    /// Collect from anything oid-shaped — `Vec<u8>`, `&[u8]`, a gix
814    /// `ObjectId`'s bytes.
815    ///
816    /// A width disagreement **panics** here, because a `FromIterator` cannot
817    /// fail and an engine that mixes hash kinds inside one repository has a
818    /// bigger problem than this list. Use [`push`](OidList::push) where the
819    /// input is not the store's own index.
820    fn from_iter<I: IntoIterator<Item = T>>(items: I) -> Self {
821        let mut out = OidList::new();
822        for item in items {
823            out.push(item.as_ref())
824                .expect("one repository holds one hash kind");
825        }
826        out
827    }
828}
829
830/// One [`GitServe::select`] answer.
831#[derive(Debug, Clone, PartialEq, Eq, Default)]
832pub struct ReachSet {
833    /// Every object to send, as raw oids.
834    ///
835    /// **Order is not part of the contract.** Measured 2026-08-08 on a
836    /// 154-object fixture: sorted, unsorted and deliberately reversed all
837    /// produce `copied=154 recompressed=0` and the identical object graph,
838    /// because the emitter orders its own output.
839    pub objects: Vec<Vec<u8>>,
840    /// Which of `objects` are commits. Not derivable by the caller without a
841    /// header read per object; the store knows it for free.
842    pub commits: Vec<Vec<u8>>,
843    /// The closure of `have`: what the receiver held **before** this transfer,
844    /// never an object this transfer carries. The voucher a thin delta may name
845    /// a base from. Empty for a clone.
846    ///
847    /// **An [`OidList`] and not a `Vec<Vec<u8>>`, because this one is
848    /// repository-sized.** `objects` is what the transfer carries — small for a
849    /// fetch — but the voucher is the closure of what the client already had,
850    /// which on an incremental fetch is very nearly the whole repository: 12 112
851    /// oids to answer a 69-object request, measured on oden 2026-08-15. One
852    /// allocation per oid of that is a per-request cost that buys nothing, in
853    /// both engines. See [`OidList`].
854    pub client_has: OidList,
855}
856
857/// **The READING contract.**
858///
859/// Two consumers, not one: `gunnar-wire` serves from it, and `gunnar-policy`'s
860/// branch-protection ancestry walk and its signature gate read from it.
861/// [`emit_pack`](GitServe::emit_pack) and [`select`](GitServe::select) are only
862/// its *serving* half — this is not a wire trait, which is why it is not called
863/// one.
864///
865/// # Why it is a second trait and not eleven more methods on `GitOps`
866///
867/// [`GitOps`] provably cannot serve the wire: [`Stored::bytes`] is *"the pack
868/// entry, header and all, byte for byte as the client sent them"* — **possibly
869/// a delta** — and no method on the eleven returns an inflated object. Widening
870/// `GitOps` to cover that would stop it being a storage contract and make it a
871/// git-server API, and the second engine would carry serving methods it answers
872/// badly. So `GitOps` stays narrow and this rides above it.
873///
874/// `GitServe: GitOps`, so a `dyn GitServe` is also a `dyn GitOps` and a
875/// repo-resolution seam does not have to fork. `Send + Sync` comes with the
876/// supertrait and is required for the same reason.
877///
878/// # The ordering rule, and it is permanent
879///
880/// This trait is defined by what the **Arrow arm** needs to serve a clone well;
881/// the gix arm then implements it. **Never the reverse.** A method that only
882/// makes sense against a `.idx`, a `.bitmap` or an `objects/pack` directory is
883/// wrong by construction.
884///
885/// # Blocking
886///
887/// Every method blocks. Never call one from an async task without
888/// `tokio::task::spawn_blocking`, and size that pool deliberately.
889pub trait GitServe: GitOps {
890    /// The object, **INFLATED and delta-resolved** — what [`GitOps::get`]
891    /// deliberately is not.
892    ///
893    /// The returned [`ObjType`] is the **resolved** kind and is therefore never
894    /// `OfsDelta` or `RefDelta`. This is what `Graph::load` walks, and what
895    /// `gunnar-policy` parses a commit out of.
896    fn read(&self, oid: Oid<'_>) -> Result<Option<(ObjType, Vec<u8>)>>;
897
898    /// Kind and post-resolution size **without the payload**. The type probe.
899    ///
900    /// Kept apart from [`read`](GitServe::read) because an object ceiling and a
901    /// typed listing need this and nothing else, and a store that keeps the
902    /// header out of line answers it without touching a byte of content. Same
903    /// resolved-kind guarantee as `read`.
904    fn header(&self, oid: Oid<'_>) -> Result<Option<(ObjType, u64)>>;
905
906    /// Bulk post-resolution size. The negotiation path calls it a thousand at a
907    /// time.
908    ///
909    /// Positional: `out[i]` answers `oids[i]`, and `None` at a position means
910    /// **unknown — go ask [`header`](GitServe::header)**, never "fine". A caller
911    /// treating an unknown size as under a ceiling would skip the ceiling for
912    /// exactly the objects a push had just introduced.
913    ///
914    /// There is no `Ok(None)` "I have no bulk path" hatch, because the arm this
915    /// contract is designed for has one: `sizes` is a single index pass, and it
916    /// is what collapses a measured 34 124 per-object header walks on one clone.
917    /// A backend without a bulk path loops over `header` and says so in its own
918    /// docs.
919    fn sizes(&self, oids: &[Oid<'_>]) -> Result<Vec<Option<u64>>>;
920
921    /// **Make every object this store has accepted addressable by oid, now.**
922    ///
923    /// A backend may ack a push before its objects are indexed —
924    /// znippy's does, and it is what makes an 8.12 GiB mirror land in 4m29s
925    /// instead of an hour. The bytes are durable at that point; the *oids* are
926    /// not yet known, because a pack entry does not carry one and an entry's
927    /// oid exists only once its delta chain has been applied.
928    ///
929    /// `receive-pack` cannot check that a push closes until they are known, so
930    /// it calls this once, before the connectivity walk, and then reads through
931    /// point lookups. Returns how many units of deferred work were completed
932    /// (packs, for the znippy arm); `0` means there was nothing to do.
933    ///
934    /// # Why it is a method and not the reader's problem
935    ///
936    /// MEASURED on the oden rig 2026-08-30 (gunnar v1.1.3-180-g01ce6c58): with
937    /// no such call, the connectivity walk's first object read fell into the
938    /// znippy arm's read-time fallback, which resolves the whole pending pack
939    /// **on the reader's thread and throws the rows away** — a second resolver
940    /// beside the indexer's, over the same 13 948 244 objects, each holding its
941    /// own O(pack) tables on a four-vCPU box. `index.scanned … 13948244 objects
942    /// in 5792442 ms`. The client sat unacked for 2h14m30s and the push was
943    /// never reported. One explicit call before the walk is one resolve
944    /// instead of two.
945    ///
946    /// # The default is correct for a backend that has no deferred work
947    ///
948    /// A gix backend indexes inside `put_pack`, so there is nothing to finish
949    /// and `Ok(0)` is the whole implementation.
950    fn index_now(&self) -> Result<usize> {
951        Ok(0)
952    }
953
954    /// `HEAD`.
955    ///
956    /// **`HEAD` is NOT a row in [`GitOps::refs`]**, and that is the contract
957    /// rather than an accident: a ref stream walks `refs/` and *"deliberately
958    /// excludes the pseudo-refs such as `HEAD`"*. The reason is a type
959    /// constraint, not taste — a name type that admits `HEAD` also admits
960    /// `MERGE_HEAD` and `FETCH_HEAD`, so putting pseudo-refs in the row stream
961    /// means either widening the name type or filtering at every consumer.
962    ///
963    /// So it gets an accessor pair instead, and this is half of it. `None` means
964    /// the repository has no `HEAD` — an empty repository does not.
965    fn head(&self) -> Result<Option<RefRow>>;
966
967    /// Point `HEAD`. The other half of the pair; `point_head_at` is the live
968    /// consumer.
969    fn set_head(&self, target: &str) -> Result<TxId>;
970
971    /// Point `HEAD` **from an authority the caller keeps somewhere else**, and
972    /// re-applies on every open.
973    ///
974    /// Identical in effect to [`set_head`](GitServe::set_head) and identical in
975    /// visibility: after it returns, [`head`](GitServe::head) answers with the
976    /// new target, and so does a reader that opens the store fresh. The one
977    /// thing it gives up is the *barrier* — a backend may treat the write as
978    /// rebuildable state and let it reach the platter with whatever durable
979    /// write comes next.
980    ///
981    /// That is only sound because of what the caller promises by choosing this
982    /// method: **it holds the authoritative copy and projects it again on every
983    /// open**. gunnar does — the default branch is a column of the catalog row,
984    /// the catalog is durable, and `Stores::repo_store` runs `point_head_at` on
985    /// every open of every repository, so a `HEAD` frame lost to a power cut is
986    /// written again the next time anything touches the store. A caller with no
987    /// such second copy must use [`set_head`](GitServe::set_head), and so must
988    /// anything pointing `HEAD` at an oid (a detached `HEAD` is not derivable
989    /// from a default branch).
990    ///
991    /// The default is `set_head`: a backend that has no cheaper way to do this
992    /// is not obliged to invent one, and answering the same way is always
993    /// correct.
994    fn set_head_projected(&self, target: &str) -> Result<TxId> {
995        self.set_head(target)
996    }
997
998    /// **Emit a packfile containing exactly `objects`**, deduplicated,
999    /// honouring `caps`, onto `out`.
1000    ///
1001    /// # "exactly" means exactly. `stats.objects == objects.len()`, deduplicated
1002    ///
1003    /// # 🔴 This paragraph used to say the opposite, and both engines obeyed it
1004    ///
1005    /// It read: *"Do not assert `stats.objects == objects.len()`. Delta-base
1006    /// closure is a **format** requirement — an `OFS_DELTA` names its base by
1007    /// in-pack distance, so a pack containing a delta must contain its base —
1008    /// and the emitter adds those. `stats.objects` is therefore `objects.len()`
1009    /// plus whatever bases the format forced, and that is correct, not an
1010    /// over-send."*
1011    ///
1012    /// It is correct about the pack format and wrong about the clone, and every
1013    /// engine that implemented it shipped broken clones — the Arrow arm until
1014    /// 2026-08-11, the gix arm until 2026-08-14, and gunnar's own in-memory
1015    /// control until the same day. Two things go wrong and only the second is
1016    /// loud:
1017    ///
1018    /// * a base pulled in is **an object the client did not ask for**, so a
1019    ///   `--filter=blob:none` or `--depth=N` fetch is served back precisely what
1020    ///   it asked to be left out — the same over-send this method's `objects`
1021    ///   parameter was renamed to prevent, arriving by delta links instead of
1022    ///   graph links;
1023    /// * and if the base is a **tree**, it arrives owing children the pack does
1024    ///   not contain. `git index-pack --check-self-contained-and-connected` —
1025    ///   which is what `git clone` runs — walks every received object's links
1026    ///   and then demands each one exist, so the transfer dies with
1027    ///   `fatal: did not receive expected object <oid>` while the server logs a
1028    ///   success.
1029    ///
1030    /// MEASURED on gunnar's gix arm, 2026-08-14, over its real upload-pack: a
1031    /// repository of 208 objects with 202 reachable from its one ref served
1032    /// `selected=202 objects=203 copied=203 recompressed=0` and the clone was
1033    /// refused. Any store that has ever refused a ref update holds unreachable
1034    /// objects — a lost compare-and-swap, a reset branch, a `git fast-import` —
1035    /// and `pack-objects` stores the newest version of a path whole and the
1036    /// older ones as deltas against it, so after a reset the still-reachable
1037    /// object is routinely a delta against one that is not. This is an ordinary
1038    /// repository, not a corner.
1039    ///
1040    /// # The rule, which is stock `pack-objects`'
1041    ///
1042    /// **Reuse a stored delta only when its base is also being packed.** The
1043    /// base decides how an entry is *encoded*; it never decides what the pack
1044    /// *contains*:
1045    ///
1046    /// * base inside `objects` → copy the stored entry, re-heading it into
1047    ///   whichever spelling `caps` allows;
1048    /// * base outside `objects` → **rebuild the object whole** and count it in
1049    ///   [`PackStats::recompressed`], or — for a *fetch* whose `have` vouches
1050    ///   for the base — name it in a `REF_DELTA` the client can resolve.
1051    ///
1052    /// So `recompressed` is not a literal `0`. It is 0 for a whole-repository
1053    /// clone of a store with no unreachable history, because such a request
1054    /// contains every base, and non-zero exactly on the boundary a narrowed or
1055    /// unreachable-adjacent request cuts.
1056    ///
1057    /// The property this has always asserted, unchanged: **no object is added
1058    /// because the engine walked the graph.** Now nothing is added at all.
1059    ///
1060    /// # `objects` is a SET TO EMIT, not a set of tips to close over
1061    ///
1062    /// This parameter was called `want` until 2026-08-10 and the rename is the
1063    /// contract, not cosmetics. **The engine must not compute a closure here.**
1064    ///
1065    /// Upload-pack's caller holds `selection.objects`, which is already
1066    /// **post-filter, post-shallow and post-`include-tag`**, and is *deliberately
1067    /// not closed*. An engine that treats it as tips and closes over it **adds
1068    /// back exactly what `--filter=blob:none` or `--depth=N` excluded.**
1069    ///
1070    /// That bug is invisible to every guard we have: the over-sent pack passes
1071    /// `index-pack --strict` **and** `fsck`, the clone succeeds, and the client
1072    /// simply receives objects it asked not to have. It is `P-027`'s shape — a
1073    /// change no test can see — which is why the parameter is named for what it
1074    /// is. `select` owns the close-over-tips half; this does not.
1075    ///
1076    /// `have` is different in kind: those *are* the negotiated common **tips**,
1077    /// used for thin-pack base selection, never to derive membership.
1078    ///
1079    /// The engine owns this because the engine owns the format. The Arrow arm
1080    /// answers it as a **byte-range copy out of the archive**; a naive fallback
1081    /// that inflates every object in order to deflate it again produces a pack
1082    /// that passes `index-pack --strict` **and** `fsck` while sending a measured
1083    /// **18.4x** the wire bytes. That is why [`PackStats`] carries `copied` and
1084    /// `recompressed` and why they are counted rather than assumed.
1085    ///
1086    /// A backend that cannot honour `caps` **refuses**. It does not emit a pack
1087    /// the client cannot parse, and it does not silently fall back to a
1088    /// whole-object writer.
1089    fn emit_pack(
1090        &self,
1091        objects: &[Oid<'_>],
1092        have: &[Oid<'_>],
1093        caps: &Caps,
1094        out: &mut dyn std::io::Write,
1095    ) -> Result<PackStats>;
1096
1097    /// Negotiation: `want` minus `have`, with the two derived facts a caller
1098    /// cannot recompute cheaply.
1099    ///
1100    /// **`Ok(None)` means *"this engine cannot answer cheaply — walk it
1101    /// yourself"*, and it is load-bearing.** It is the escape hatch and it must
1102    /// stay: the Arrow arm returns `None` when its reachability projection is
1103    /// empty, which a clean restart currently produces. Without it a backend
1104    /// whose index does not cover a tip contributes only the tip, and the clone
1105    /// is short by everything beneath it **while exiting zero**.
1106    ///
1107    /// Do not "improve" this into always answering. An engine that always
1108    /// answers has to answer wrongly somewhere, and this is the shape of wrong
1109    /// that no exit code and no `fsck` can see.
1110    fn select(&self, want: &[Oid<'_>], have: &[Oid<'_>]) -> Result<Option<ReachSet>>;
1111}
1112
1113#[cfg(test)]
1114mod tests {
1115    use super::OidList;
1116
1117    /// The three properties the flat form has to have, each asserted on the
1118    /// **read-back**: what went in comes out, at the right width, in order.
1119    ///
1120    /// A length check alone is the hollow version of this test — a list that
1121    /// strided by the wrong width reports the same `len()` and hands back oids
1122    /// that never existed — so the slices themselves are compared.
1123    #[test]
1124    fn a_flat_list_reads_back_exactly_what_was_pushed() {
1125        let ids: Vec<Vec<u8>> = (0u8..5).map(|i| vec![i; 20]).collect();
1126        let list: OidList = ids.iter().collect();
1127        assert_eq!(list.len(), 5, "five 20-byte oids");
1128        assert_eq!(list.oid_len(), 20);
1129        let back: Vec<Vec<u8>> = list.iter().map(<[u8]>::to_vec).collect();
1130        assert_eq!(back, ids, "push order and bytes, both");
1131        assert!(list.contains(&[3u8; 20]));
1132        assert!(!list.contains(&[9u8; 20]), "an oid nobody pushed");
1133        // A 32-byte probe against a 20-byte list is not a truncated match.
1134        assert!(!list.contains(&[0u8; 32]));
1135    }
1136
1137    /// **The width guard, seen RED.** A mixed-width list cannot be read back at
1138    /// all, so the second push is refused rather than accepted.
1139    #[test]
1140    fn mixing_hash_widths_in_one_list_is_refused() {
1141        let mut list = OidList::new();
1142        list.push(&[1u8; 20])
1143            .expect("the first push sets the width");
1144        let err = list
1145            .push(&[2u8; 32])
1146            .expect_err("a 32-byte oid in a 20-byte list must not be accepted");
1147        assert!(
1148            err.to_string().contains("mixed-width"),
1149            "the refusal must say why: {err}"
1150        );
1151        assert_eq!(list.len(), 1, "the refused push must not have landed");
1152    }
1153
1154    /// `Default` is an empty list of no width, which is what an engine that
1155    /// vouched for nothing (a clone) produces — so the two must compare equal
1156    /// whichever built them.
1157    #[test]
1158    fn an_empty_voucher_equals_the_default_one() {
1159        let mut built = OidList::with_capacity(64, 20);
1160        assert_eq!(built, OidList::default(), "nothing pushed, no width yet");
1161        built.push(&[7u8; 20]).unwrap();
1162        assert_ne!(built, OidList::default());
1163        assert!(!built.is_empty());
1164    }
1165}