znippy_plugin_git/arms.rs
1//! **Which implementation of each trait a store is built on** — one selector,
2//! read once, never per operation.
3//!
4//! Three traits in this crate have more than one implementation, every one of
5//! them written and benchmarked (PLAN §7, §8):
6//!
7//! | trait | arms | what varies |
8//! |---|---|---|
9//! | [`ArchiveWrite`] | [`WriterArm::Fast`] / [`Safe`](WriterArm::Safe) / [`Uring`](WriterArm::Uring) | **the durability contract**, and nothing else |
10//! | [`ObjectIndex`](crate::index_layout::ObjectIndex) | [`IndexArm::OneTableFourColumns`] / [`FourTables`](IndexArm::FourTables) / [`PackedPayload`](IndexArm::PackedPayload) | the payload layout behind the same `stree` |
11//! | [`Gc`] | [`GcArm::NewGeneration`] / [`CompactInPlace`](GcArm::CompactInPlace) | whether the old generation survives until the new one is proven |
12//!
13//! Until this module existed, `GitStore` named one of each by hand, so none of
14//! them could be A/B'd through a server or a bench without editing the source.
15//! [`StoreConfig`] is that choice made data.
16//!
17//! # The default is the shipping combination and it did not move
18//!
19//! [`StoreConfig::DEFAULT`] is `SafeWriter` + `ObjectReadStack<OneTableFourColumns>`
20//! + `NewGeneration`, which is exactly what
21//! [`GitStore::open`](crate::git_ops::GitStore::open) built before this module
22//! and is exactly what it builds now.
23//! **`open` and `open_with` do not read the environment at all** — an operator
24//! who exports a variable cannot silently change the durability contract under a
25//! caller that never asked for a selector. Choosing an arm is something a caller
26//! does on purpose, through
27//! [`open_with_arms`](crate::git_ops::GitStore::open_with_arms) or
28//! [`open_from_env`](crate::git_ops::open_from_env).
29//!
30//! # Read once, at construction. Never per operation.
31//!
32//! Every `getenv` this crate performs goes through [`read_env`] and happens
33//! either inside [`StoreConfig::from_env`] (which a store calls **once**, while
34//! it is being opened — the three arms and, since 2026-08-21, the cache ceiling
35//! with them) or behind a process-wide `OnceLock` for the knobs that never vary
36//! between two stores in one process. A `std::env::var` in a copy loop would be
37//! one syscall per object served, and that exact defect was found and fixed in
38//! gunnar the day before this was written. It is not a style rule here, it is
39//! asserted: [`env_reads_here`] counts every read this module makes on the
40//! calling thread, and
41//! `the_selector_is_read_once_at_construction_and_never_per_operation` pushes
42//! and serves a whole pack across an unchanged counter.
43//!
44//! Five reads at construction — three arms, the cache ceiling and the explode
45//! policy — and zero per operation. [`env_reads`] is the same count
46//! process-wide; see [`env_reads_here`] for why the guard asserts on the
47//! thread-local one. The complete roster of keys is [`ALL_ENV`].
48//!
49//! # The names, so an operator can type them
50//!
51//! ```text
52//! ZNIPPY_GIT_WRITER = fast | safe | uring (default: safe)
53//! ZNIPPY_GIT_INDEX = one-table | four-tables | packed (default: one-table)
54//! ZNIPPY_GIT_GC = new-generation | in-place (default: new-generation)
55//!
56//! ZNIPPY_GIT_REDB_CACHE_BYTES = <bytes> (default: 67108864)
57//!
58//! ZNIPPY_GIT_EXPLODE = off | graph | full (default: see exploded_arrow.rs)
59//! ZNIPPY_GIT_BOUNDARY_DELTA = 0 | off | false to disable (default: on)
60//! ZNIPPY_GIT_REACH_COMMITS = <commits> (default: 512)
61//! ZNIPPY_GIT_EMIT_WORKERS = <workers>, 0 = all cores (default: 4)
62//! ```
63//!
64//! The first four are per store and are what [`StoreConfig`] holds and prints;
65//! the last four are per process. [`ALL_ENV`] is all thirteen (eight + the five memory/batch knobs of 2026-08-30), and a consumer that
66//! has to carry any of them across a boundary asserts its list against it.
67//!
68//! An unset variable takes the default. A variable set to something else is an
69//! **error**, named and listing what is accepted — a typo that silently fell
70//! back to the default would make an operator believe a measurement came from an
71//! arm that never ran, which is worse than a failed open.
72//!
73//! ⚠ The fourth one is **not an arm**, and it is the only variable here that
74//! [`GitStore::open`](crate::git_ops::GitStore::open) reads. It selects no
75//! implementation and changes no contract — it is a memory ceiling, and redb's
76//! own default for it is 1 GiB *per database*. See [`redb_cache_bytes`].
77
78use std::path::{Path, PathBuf};
79use std::sync::atomic::{AtomicU64, Ordering};
80
81use anyhow::{Result, bail};
82
83use crate::archive_write::{ArchiveWrite, FastWriter, SafeWriter};
84use crate::gc::{CompactInPlace, Gc, NewGeneration};
85
86/// `getenv` calls this module has made since the process started.
87///
88/// The counter behind the read-once law. Every path that reads the environment
89/// in this crate goes through [`read_env`], which bumps it; nothing else does.
90/// A caller — or a guard — can therefore prove that serving N objects cost zero
91/// environment reads, which is the only way to state the law as an assertion
92/// rather than as a comment.
93pub fn env_reads() -> u64 {
94 ENV_READS.load(Ordering::Relaxed)
95}
96
97/// The same count, **for the calling thread only**.
98///
99/// [`env_reads`] is process-wide, which makes it the right number to report and
100/// the wrong number to *assert on*: any other thread opening a store moves it,
101/// so a guard written against it is a race dressed as a test. It was only ever
102/// accidentally deterministic — until 2026-08-10 the sole reader was
103/// [`StoreConfig::from_env`], every caller of which took `ENV_LOCK`, so the
104/// tests that counted were the only tests that counted. That stopped being true
105/// when [`redb_cache_bytes`] joined it: **every** store open reads the
106/// environment now, including [`GitStore::open`](crate::git_ops::GitStore::open),
107/// and most of the suite opens stores without the lock.
108///
109/// So the law is asserted per thread, where a call path actually lives. It is
110/// also the stronger statement: "this thread served 2687 objects and touched the
111/// environment zero times" is what the law says, and it is now true regardless
112/// of what else the process is doing.
113pub fn env_reads_here() -> u64 {
114 ENV_READS_HERE.with(|c| c.get())
115}
116
117static ENV_READS: AtomicU64 = AtomicU64::new(0);
118
119thread_local! {
120 static ENV_READS_HERE: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
121}
122
123/// The one place this crate touches the environment.
124///
125/// `pub(crate)` so the per-process knobs in `delta.rs`, `exploded_arrow.rs`
126/// and `git_ops.rs` read through the same counted door rather than through
127/// their own `std::env::var` — every read this crate makes moves
128/// [`env_reads`], or the read-once law is a comment.
129pub(crate) fn read_env(key: &str) -> Option<String> {
130 ENV_READS.fetch_add(1, Ordering::Relaxed);
131 ENV_READS_HERE.with(|c| c.set(c.get() + 1));
132 match std::env::var(key) {
133 Ok(v) if !v.trim().is_empty() => Some(v.trim().to_string()),
134 _ => None,
135 }
136}
137
138// ── the writer arm ────────────────────────────────────────────────────────────
139
140/// Which [`ArchiveWrite`] the push path appends through.
141///
142/// **The arm changes what `append` promises and nothing else.** All three write
143/// the pushed pack's bytes verbatim, at the same offset, into the same file; a
144/// store built on any of them holds byte-identical payload. What differs is how
145/// much of the write is durable when `append` returns, and that is the whole
146/// axis.
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
148pub enum WriterArm {
149 /// [`FastWriter`] — **one `pwrite`, no fsync, no journal.**
150 ///
151 /// `append` returns as soon as the bytes are in the kernel's page cache.
152 /// Stated plainly, because an operator selecting this is choosing it:
153 ///
154 /// * **A machine crash (power loss, panic, a hard reset) after `append`
155 /// returns loses the bytes.** Not "may lose" — nothing has told the device
156 /// about them.
157 /// * There is **no journal**, so a store on this arm has no durable record
158 /// that a pack was ever acked. It therefore has **no crash recovery**: a
159 /// reopen cannot re-queue an interrupted pack because there is nothing to
160 /// diff the index against, and pack ordinals restart at 0
161 /// (`indexer::packs_already_acked`).
162 /// * A *process* crash alone keeps the bytes: page cache survives `exit`.
163 /// That is the only crash it survives.
164 ///
165 /// It is here because it is the **ceiling the other two are measured
166 /// against** — at 8 KiB it acks in 3.9 µs against `SafeWriter`'s 132 µs
167 /// (`examples/push_path_bench.rs`, oden 2026-08-07) — and because there are
168 /// real workloads whose durability contract is not git's: a rebuildable
169 /// mirror, a bulk import that is re-run on failure, a benchmark. Selecting
170 /// it is not refused and not warned about. It is the operator's call and
171 /// the contract above is what they are choosing.
172 Fast,
173 /// [`SafeWriter`] — blob `fsync`, **then** the journal row, then the
174 /// journal's `fsync`. **The default, and git's contract**: a push that was
175 /// acked survives a crash. Four syscalls per append.
176 #[default]
177 Safe,
178 /// [`UringWriter`](crate::uring_write::UringWriter) — the **same ordering**
179 /// as [`Safe`](WriterArm::Safe), enforced by the kernel through an
180 /// `IOSQE_IO_LINK` chain instead of by the caller blocking between four
181 /// syscalls. One `io_uring_enter` carrying four linked ops.
182 ///
183 /// MEASURED 2026-08-07 (PLAN §8.3): **it did not win** — within noise of
184 /// `SafeWriter` at every pack size, because the cost is the two device
185 /// flushes and not the syscall count. Kept as a selectable arm precisely so
186 /// that finding can be re-run rather than remembered. Linux only.
187 ///
188 /// **What this arm costs that the other two do not: pinned memory, and a
189 /// ceiling on how many stores a process can hold.** Its ring registers a
190 /// staging buffer, and `IORING_REGISTER_BUFFERS` pins pages against
191 /// `RLIMIT_MEMLOCK` — a limit the kernel counts on the `user_struct`, so it
192 /// is shared by every process the uid is running. One writer per store means
193 /// the number of repositories this arm can serve is
194 /// `RLIMIT_MEMLOCK / page`, and `Fast` and `Safe` have no such ceiling
195 /// because they register nothing. It was **~107 stores** on a stock 8 MiB
196 /// limit until 2026-08-14, when the registration was cut from 64 KiB to the
197 /// one page a journal row actually needs; see
198 /// [`uring_write`](crate::uring_write)'s module docs for the arithmetic, the
199 /// measurement and the failure it produced in gunnar's sweep.
200 ///
201 /// It used to differ from `Safe` in one more way, and that is now closed:
202 /// [`UringWriter::create`](crate::uring_write::UringWriter::create) opened
203 /// its journal with `File::create`, so a **reopen truncated the journal**
204 /// where `SafeWriter` appends to it — the durability of `Safe` within a
205 /// process and the crash recovery of `Fast` across one. Both durable arms
206 /// now open the same log the same way, which is what "one journal format,
207 /// two transports" (LAW 5) always claimed of them.
208 Uring,
209}
210
211impl WriterArm {
212 /// Every arm, for a bench that sweeps them.
213 pub const ALL: [WriterArm; 3] = [WriterArm::Fast, WriterArm::Safe, WriterArm::Uring];
214
215 /// The spelling an operator types.
216 pub fn as_str(self) -> &'static str {
217 match self {
218 WriterArm::Fast => "fast",
219 WriterArm::Safe => "safe",
220 WriterArm::Uring => "uring",
221 }
222 }
223
224 /// One line on what this arm's `append` promises. Same string the trait's
225 /// own [`ArchiveWrite::durability`] returns, so a bench row and a config
226 /// dump cannot disagree.
227 pub fn durability(self) -> &'static str {
228 match self {
229 WriterArm::Fast => {
230 "none — page cache only; a machine crash after return loses the bytes, and there \
231 is no journal, so no crash recovery and no stable pack ordinals"
232 }
233 WriterArm::Safe | WriterArm::Uring => {
234 "full — blob fsynced, then a journal row fsynced; crash after return keeps both"
235 }
236 }
237 }
238
239 /// Whether this arm keeps the durable extent log that
240 /// [`GitStore::open_with_arms`](crate::git_ops::GitStore::open_with_arms)
241 /// derives §13.12's `indexed` bit from.
242 ///
243 /// `None` is [`Fast`](WriterArm::Fast) and it is load-bearing rather than
244 /// cosmetic: with no journal there is no durable record of an ack, so the
245 /// crash-recovery diff has nothing to run against and a reopen re-queues
246 /// nothing. Returning the path of a journal this arm does not write would
247 /// make a reopened store diff against a **stale** log and re-absorb packs
248 /// that a different arm acked.
249 pub fn journal(self, blobs: &Path) -> Option<PathBuf> {
250 match self {
251 WriterArm::Fast => None,
252 WriterArm::Safe | WriterArm::Uring => Some(crate::archive_write::journal_path(blobs)),
253 }
254 }
255
256 /// Build the writer. `blobs` is the file the pushed packs are appended to.
257 pub fn create(self, blobs: &Path) -> Result<Box<dyn ArchiveWrite>> {
258 Ok(match self {
259 WriterArm::Fast => Box::new(FastWriter::create(blobs)?),
260 WriterArm::Safe => Box::new(SafeWriter::create(blobs)?),
261 #[cfg(target_os = "linux")]
262 WriterArm::Uring => Box::new(crate::uring_write::UringWriter::create(blobs)?),
263 #[cfg(not(target_os = "linux"))]
264 WriterArm::Uring => bail!(
265 "the `uring` writer arm is Linux-only — this target has no io_uring, and this \
266 crate does not substitute a pwrite path under an io_uring name"
267 ),
268 })
269 }
270
271 /// Parse the spelling an operator types. Errors name what is accepted.
272 pub fn parse(s: &str) -> Result<Self> {
273 Ok(match s.trim().to_ascii_lowercase().as_str() {
274 "fast" | "fastwriter" => WriterArm::Fast,
275 "safe" | "safewriter" => WriterArm::Safe,
276 "uring" | "uringwriter" | "io_uring" => WriterArm::Uring,
277 other => bail!(
278 "'{other}' is not a writer arm — expected one of fast, safe, uring \
279 ({}={other})",
280 ENV_WRITER
281 ),
282 })
283 }
284}
285
286// ── the index arm ─────────────────────────────────────────────────────────────
287
288/// Which payload layout sits behind the read stack's `stree`.
289///
290/// **This one is a *type*, not a value**, and that is deliberate: it is the hot
291/// path. `GitStore` is generic over it
292/// (`GitStore<S = OneTableFourColumns>`), so a caller that knows its arm at
293/// compile time — which includes every existing caller, through the default —
294/// pays no dispatch at all. This enum exists so a *runtime* selector can pick
295/// one; see [`crate::git_ops::open_from_env`], which monomorphises all three and
296/// hands back a `Box<dyn GitOps>`.
297///
298/// MEASURED 2026-08-07 (PLAN §13): a packed 25-byte column beats four columns by
299/// 19–76% on the payload gather but loses column scans by 3.3x–14.4x, and no git
300/// operation does a full-row fetch. That is why `OneTableFourColumns` is the
301/// default — and why the losing arms stay selectable, because that conclusion is
302/// a measurement and measurements get re-run.
303#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
304pub enum IndexArm {
305 /// [`OneTableFourColumns`](crate::index_layout::OneTableFourColumns) — the
306 /// default. One Arrow IPC section, four columns.
307 #[default]
308 OneTableFourColumns,
309 /// [`FourTables`](crate::index_layout::FourTables) — four independent IPC
310 /// sections joined on the ordinal.
311 FourTables,
312 /// [`PackedPayload`](crate::index_layout::PackedPayload) — one 25-byte
313 /// fixed-size-binary column holding the whole row.
314 PackedPayload,
315}
316
317impl IndexArm {
318 pub const ALL: [IndexArm; 3] = [
319 IndexArm::OneTableFourColumns,
320 IndexArm::FourTables,
321 IndexArm::PackedPayload,
322 ];
323
324 /// The spelling an operator types.
325 pub fn as_str(self) -> &'static str {
326 match self {
327 IndexArm::OneTableFourColumns => "one-table",
328 IndexArm::FourTables => "four-tables",
329 IndexArm::PackedPayload => "packed",
330 }
331 }
332
333 /// The name [`ObjectIndex::name`](crate::index_layout::ObjectIndex::name)
334 /// reports for the projection this arm builds. Distinct from
335 /// [`as_str`](IndexArm::as_str) on purpose: one is what an operator types,
336 /// the other is what the built object calls itself, and a guard that
337 /// compares them is comparing the selector against applied output.
338 pub fn projection_name(self) -> &'static str {
339 match self {
340 IndexArm::OneTableFourColumns => "OneTableFourColumns",
341 IndexArm::FourTables => "FourTables",
342 IndexArm::PackedPayload => "PackedPayload",
343 }
344 }
345
346 pub fn parse(s: &str) -> Result<Self> {
347 Ok(match s.trim().to_ascii_lowercase().as_str() {
348 "one-table" | "one_table" | "onetablefourcolumns" | "one" => {
349 IndexArm::OneTableFourColumns
350 }
351 "four-tables" | "four_tables" | "fourtables" | "four" => IndexArm::FourTables,
352 "packed" | "packedpayload" => IndexArm::PackedPayload,
353 other => bail!(
354 "'{other}' is not an index arm — expected one of one-table, four-tables, packed \
355 ({ENV_INDEX}={other})"
356 ),
357 })
358 }
359}
360
361// ── the gc arm ────────────────────────────────────────────────────────────────
362
363/// Which [`Gc`] [`GitOps::gc`](crate::git_ops::GitOps::gc) runs as its third
364/// step, after reachability and after the dead index rows are dropped.
365#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
366pub enum GcArm {
367 /// [`NewGeneration`] — the default. Hard-link, compact the link, **verify
368 /// the result by reading every entry back**, rename to `x.gN.znippy`,
369 /// unlink the old generation last. A death at any point leaves at least one
370 /// complete readable archive.
371 #[default]
372 NewGeneration,
373 /// [`CompactInPlace`] — base znippy's `compact_archive` against the archive
374 /// under its own name: stage beside it, rename over it. Verification is
375 /// **post-hoc**: by the time there is something to read back, the original
376 /// is already gone. One archive on disk instead of two, and no generation
377 /// suffix — which is the reason to pick it — at the price of that window.
378 CompactInPlace,
379}
380
381impl GcArm {
382 pub const ALL: [GcArm; 2] = [GcArm::NewGeneration, GcArm::CompactInPlace];
383
384 pub fn as_str(self) -> &'static str {
385 match self {
386 GcArm::NewGeneration => "new-generation",
387 GcArm::CompactInPlace => "in-place",
388 }
389 }
390
391 /// The name the built implementation reports through [`Gc::name`], which is
392 /// also what lands in [`GcReport::strategy`](crate::gc::GcReport::strategy)
393 /// — the applied output a guard reads.
394 pub fn strategy(self) -> &'static str {
395 match self {
396 GcArm::NewGeneration => "NewGeneration",
397 GcArm::CompactInPlace => "CompactInPlace",
398 }
399 }
400
401 /// Build it. `Send + Sync` because a `GitStore` is shared across the
402 /// indexer's threads.
403 pub fn create(self) -> Box<dyn Gc + Send + Sync> {
404 match self {
405 GcArm::NewGeneration => Box::new(NewGeneration::new()),
406 GcArm::CompactInPlace => Box::new(CompactInPlace::new()),
407 }
408 }
409
410 pub fn parse(s: &str) -> Result<Self> {
411 Ok(match s.trim().to_ascii_lowercase().as_str() {
412 "new-generation" | "new_generation" | "newgeneration" | "new" | "generation" => {
413 GcArm::NewGeneration
414 }
415 "in-place" | "in_place" | "inplace" | "compactinplace" | "compact" => {
416 GcArm::CompactInPlace
417 }
418 other => bail!(
419 "'{other}' is not a gc arm — expected one of new-generation, in-place \
420 ({ENV_GC}={other})"
421 ),
422 })
423 }
424}
425
426// ── the config ────────────────────────────────────────────────────────────────
427
428/// Environment variable naming the [`ArchiveWrite`] arm.
429pub const ENV_WRITER: &str = "ZNIPPY_GIT_WRITER";
430/// Environment variable naming the
431/// [`ObjectIndex`](crate::index_layout::ObjectIndex) arm.
432pub const ENV_INDEX: &str = "ZNIPPY_GIT_INDEX";
433/// Environment variable naming the [`Gc`] arm.
434pub const ENV_GC: &str = "ZNIPPY_GIT_GC";
435/// Environment variable bounding **redb's page cache**, in bytes. See
436/// [`redb_cache_bytes`].
437pub const ENV_REDB_CACHE: &str = "ZNIPPY_GIT_REDB_CACHE_BYTES";
438/// Environment variable switching the **boundary re-delta** off for an A/B
439/// (`0` / `off` / `false`; anything else, or unset, is on). Read once per
440/// process by [`crate::delta::enabled`].
441pub const ENV_BOUNDARY_DELTA: &str = "ZNIPPY_GIT_BOUNDARY_DELTA";
442/// Environment variable naming the **explode policy** of the
443/// `objects.exploded` table (`off` · `graph` · `full`). Read once per store
444/// open by `ExplodePolicy::from_env`.
445pub const ENV_EXPLODE: &str = "ZNIPPY_GIT_EXPLODE";
446/// Environment variable setting the **explode cache budget** — the byte cap on
447/// the `objects.exploded` pools, `0`/`unlimited` for none. Read once per store
448/// open by `crate::exploded_cache::budget_from_env`, which supplies the
449/// filesystem-derived default when it is unset. The tier it bounds MEASURED
450/// 141.7 GiB for an 8.12 GiB pack before the cap existed.
451pub const ENV_EXPLODE_BUDGET: &str = "ZNIPPY_GIT_EXPLODE_BUDGET";
452/// Environment variable capping the **live reachability walk** in commits. An
453/// operator knob, not an arm — see `live_reach_policy` in `git_ops.rs`. Read
454/// once per process.
455pub const ENV_REACH_COMMITS: &str = "ZNIPPY_GIT_REACH_COMMITS";
456/// Environment variable setting the **phase-1 emit workers per request**. An
457/// operator knob, not an arm — see `emit_workers` in `git_ops.rs`. Read once
458/// per process.
459pub const ENV_EMIT_WORKERS: &str = "ZNIPPY_GIT_EMIT_WORKERS";
460/// Environment variable setting the **memory watchdog's floor** as a percent
461/// of `MemTotal` (default 20): below it the indexer flushes and waits. See
462/// [`crate::memguard`]. Read once per process.
463pub const ENV_MEM_BUDGET_PCT: &str = "ZNIPPY_GIT_MEM_BUDGET_PCT";
464/// Environment variable setting the same floor in **absolute bytes**, which
465/// wins over the percent when both are set. Read once per process.
466pub const ENV_MEM_BUDGET_BYTES: &str = "ZNIPPY_GIT_MEM_BUDGET_BYTES";
467/// Environment variable naming the file the watchdog reads instead of
468/// `/proc/meminfo` — a test's fake. Read once per process.
469pub const ENV_MEMINFO: &str = "ZNIPPY_GIT_MEMINFO";
470/// Environment variable bounding the **held delta-base set** of the resolver in
471/// bytes (default 25 % of `MemTotal`): over it the base whose next use is
472/// farthest is dropped and re-inflated from the mmapped pack when needed. See
473/// [`crate::resolve`]. Read once per process.
474pub const ENV_BASE_BUDGET_BYTES: &str = "ZNIPPY_GIT_BASE_BUDGET_BYTES";
475/// Environment variable setting how many **index rows are flushed per batch**
476/// by the absorber (default 262 144) instead of the whole pack's rows at once.
477/// Read once per process.
478pub const ENV_INDEX_BATCH_ROWS: &str = "ZNIPPY_GIT_INDEX_BATCH_ROWS";
479/// Environment variable setting the **absolute resume margin** in bytes
480/// (default 64 MiB): a pause ends once `MemAvailable` is the floor plus this.
481/// It used to be `budget / 8`, which on a 16 GB box demanded 410 MB of headroom
482/// to leave a pause that a 75 MB shortfall opened — the livelock lane P2
483/// measured. See [`crate::memguard`]. Read once per process.
484pub const ENV_MEM_RESUME_MARGIN_BYTES: &str = "ZNIPPY_GIT_MEM_RESUME_MARGIN_BYTES";
485/// Environment variable setting **how many subtrees the resolver walks at
486/// once** (default: one per core). `1` is the serial resolver, and the stream
487/// out is the same at every value. See [`crate::resolve::workers_from_env`].
488/// Read once per process.
489pub const ENV_RESOLVE_WORKERS: &str = "ZNIPPY_GIT_RESOLVE_WORKERS";
490/// Environment variable bounding **how far the resolver's workers may run
491/// ahead of its ordered output**, in bytes (default 128 MiB). Read once per
492/// process.
493pub const ENV_RESOLVE_LOOKAHEAD_BYTES: &str = "ZNIPPY_GIT_RESOLVE_LOOKAHEAD_BYTES";
494/// Environment variable bounding **how long one pause may last**, in
495/// milliseconds (default 300 000 = 5 minutes). Past it the worker stops
496/// waiting and the pack is failed BY NAME rather than parked forever. See
497/// [`crate::memguard::PauseEnd`]. Read once per process.
498pub const ENV_MEM_PAUSE_MAX_MS: &str = "ZNIPPY_GIT_MEM_PAUSE_MAX_MS";
499
500/// **Every environment variable this crate reads outside its tests**, in one
501/// place, so a consumer that carries them across a process or container
502/// boundary can assert its list against this one instead of against a count
503/// it remembers.
504///
505/// # Why a list, and why here
506///
507/// gunnar's forge runs `gunnar serve` inside a podman container, and podman
508/// passes nothing implicitly: a variable set on the host reaches the server
509/// only if the forge names it in its crossing list. On 2026-08-11 five separate
510/// wrong conclusions were drawn on one box from knobs that were "set" and never
511/// arrived — the server ran on its default and the probe reported "no effect",
512/// a null result shaped exactly like a real one. The forge's own list was three
513/// entries long against a crate that read four keys, and **nothing went red
514/// when this crate grew a key**, because the only list that looked was the
515/// consumer's.
516///
517/// This is the producer's list. It is the one a consumer asserts against — "my
518/// crossing list plus my named exclusions equals `ALL_ENV`" — so the day this
519/// crate grows a ninth key, the consumer's guard is what says so, and the
520/// failure names the key rather than producing a quiet default.
521///
522/// # It is asserted complete, not trusted
523///
524/// `every_environment_read_in_this_crate_is_named_in_all_env` (in this module's
525/// tests) walks the crate's own source and checks that every `std::env::var`
526/// call outside a `#[cfg(test)]` region names a key on this list — by literal
527/// or by one of the `ENV_*` constants above. Grow a read without growing the
528/// list and that test is what goes red.
529///
530/// Three of the thirteen are **arms** (they select an implementation and change
531/// what the store promises); the other five are knobs and ceilings that select
532/// nothing. [`StoreConfig`] holds the arms and the cache ceiling, and its
533/// `Display` prints those four; the remaining four are per-process knobs that
534/// never vary between two stores in one process.
535pub const ALL_ENV: &[&str] = &[
536 ENV_WRITER,
537 ENV_INDEX,
538 ENV_GC,
539 ENV_REDB_CACHE,
540 ENV_BOUNDARY_DELTA,
541 ENV_EXPLODE,
542 ENV_EXPLODE_BUDGET,
543 ENV_REACH_COMMITS,
544 ENV_EMIT_WORKERS,
545 ENV_MEM_BUDGET_PCT,
546 ENV_MEM_BUDGET_BYTES,
547 ENV_MEMINFO,
548 ENV_BASE_BUDGET_BYTES,
549 ENV_INDEX_BATCH_ROWS,
550 ENV_MEM_RESUME_MARGIN_BYTES,
551 ENV_MEM_PAUSE_MAX_MS,
552 ENV_RESOLVE_WORKERS,
553 ENV_RESOLVE_LOOKAHEAD_BYTES,
554];
555
556/// **The page-cache ceiling for one repository's redb database**, in bytes.
557///
558/// # Why this exists at all
559///
560/// `redb::Database::create(path)` is `Builder::new().create(path)`, and
561/// `Builder::new` ends with `set_cache_size(1024 * 1024 * 1024)` — redb-2.6.3
562/// `db.rs:1140`. **One GiB, per database, by default**, split 90 % read /
563/// 10 % write by `set_cache_size` (`db.rs:1184`), so the stock ceiling is 1 GiB
564/// *per repository* and a long-lived server holding N repositories has N times
565/// that.
566///
567/// # "Two databases per repository" was stale, and it cost a wrong diagnosis
568///
569/// This paragraph said "a store opens two of them, so the stock ceiling is
570/// 2 GiB per repository" until 2026-08-31. **A store opens one.**
571/// [`GitStore::open_with_arms`](crate::git_ops::GitStore::open_with_arms)
572/// constructs exactly one [`ObjectReadStack`](crate::read_stack::ObjectReadStack)
573/// — `objects.tail` — and `tests/fd_per_store.rs` counts exactly one
574/// `objects.tail` descriptor per store and asserts the total is three. The
575/// second database was the exploded table's, and it stopped being a redb when
576/// §14 moved that tier to append-only Arrow IPC
577/// ([`crate::exploded_arrow`]); the sentence outlived it.
578///
579/// It is recorded rather than quietly deleted because a stale doc is a second
580/// truth and this one was believed: `gunnar/.nornir/stinky.md` S-079 doubled
581/// this figure to 128 MiB per store on the strength of it, and built an
582/// explanation of a live appliance's 10 G on top. See S-082 for the
583/// measurement that refuted it.
584///
585/// It is a ceiling and not a reservation, so a small repository never noticed.
586/// MEASURED 2026-08-10 (t14s, `h2h-linear-sha1-2048c-1024f-16k`, a 1 078 472 704-byte
587/// `objects.exploded`): a single clone parked **594 MB resident** and kept it for
588/// the life of the process, because the pages a full-file traversal touched all
589/// fit under the ceiling and nothing evicted them.
590///
591/// # How the default was chosen
592///
593/// A B-tree read cache earns its keep on the **interior** nodes, which every
594/// lookup re-touches, and earns nothing on a single sequential pass over the
595/// leaves, which is what a `refold` is. The interior levels of a 4 KiB-page
596/// B-tree over that 1.078 GB table are ~7 MB; 64 MiB holds all of them nine
597/// times over and leaves 6.4 MiB of write cache, which is more than one absorb
598/// batch dirties. Measured against the 1 GiB default on the clone path it costs
599/// nothing and returns most of the resident set — see the sweep in
600/// `agentAA-report.md`.
601///
602/// # This is the one environment read that is not an arm
603///
604/// Every other variable in this module selects an *implementation* and therefore
605/// changes what the store promises, which is why
606/// [`GitStore::open`](crate::git_ops::GitStore::open) deliberately reads none of
607/// them. This one selects nothing: it is a memory ceiling, every arm behaves
608/// identically under any value of it, and the bytes on disk are the same either
609/// way. So it *is* read on the `open` path — an operator who has to cap a
610/// server's footprint cannot be told to use a different constructor.
611///
612/// An unparseable or zero value is an **error**, for the same reason a
613/// misspelled arm is: a silent fallback would let an operator believe a
614/// measurement came from a ceiling that was never applied.
615pub fn redb_cache_bytes() -> Result<usize> {
616 let Some(raw) = read_env(ENV_REDB_CACHE) else {
617 return Ok(DEFAULT_REDB_CACHE_BYTES);
618 };
619 match raw.parse::<usize>() {
620 Ok(0) | Err(_) => bail!(
621 "{ENV_REDB_CACHE}={raw:?} is not a positive byte count; it bounds redb's page \
622 cache per database and the default is {DEFAULT_REDB_CACHE_BYTES}"
623 ),
624 Ok(n) => Ok(n),
625 }
626}
627
628/// 64 MiB. See [`redb_cache_bytes`] for how that number was arrived at.
629pub const DEFAULT_REDB_CACHE_BYTES: usize = 64 * 1024 * 1024;
630
631/// One implementation of each trait, chosen.
632///
633/// A plain `Copy` value with no interior state: it is *read* once, at
634/// construction, and from then on the store holds the built objects rather than
635/// this. Handing it around after that is a description of what was built, not a
636/// switch anything consults.
637#[derive(Debug, Clone, Copy, PartialEq, Eq)]
638pub struct StoreConfig {
639 pub writer: WriterArm,
640 pub index: IndexArm,
641 pub gc: GcArm,
642 /// The redb page-cache ceiling the store's `objects.tail` database is opened
643 /// under. One database per store — see [`redb_cache_bytes`].
644 /// **Not an arm** — it selects nothing — but it is part of what was built,
645 /// and a `Display` of the config that left it out would have hidden the
646 /// one key that was "falsified" on 2026-08-11 by never reaching the
647 /// container at all. [`StoreConfig::from_env`] fills it from
648 /// [`redb_cache_bytes`]; [`DEFAULT`](Self::DEFAULT) is
649 /// [`DEFAULT_REDB_CACHE_BYTES`].
650 pub redb_cache_bytes: usize,
651}
652
653impl Default for StoreConfig {
654 /// [`StoreConfig::DEFAULT`], spelled out. A derived `Default` would put a
655 /// zero-byte page cache on the shipping combination.
656 fn default() -> Self {
657 Self::DEFAULT
658 }
659}
660
661impl StoreConfig {
662 /// **What shipped before this module existed, and what still ships.**
663 ///
664 /// `SafeWriter` + `ObjectReadStack<OneTableFourColumns>` + `NewGeneration`.
665 /// [`GitStore::open`](crate::git_ops::GitStore::open) builds exactly this
666 /// and consults no environment to do it.
667 pub const DEFAULT: StoreConfig = StoreConfig {
668 writer: WriterArm::Safe,
669 index: IndexArm::OneTableFourColumns,
670 gc: GcArm::NewGeneration,
671 redb_cache_bytes: DEFAULT_REDB_CACHE_BYTES,
672 };
673
674 /// Read the three arms and the cache ceiling. **Four `getenv`s, once, here.**
675 ///
676 /// It is called from a store's constructor and from nowhere on a serving
677 /// path; [`env_reads`] is what makes that assertable rather than asserted-
678 /// by-comment. An unset or empty variable takes the default; a variable set
679 /// to an unknown value is an error rather than a silent fallback, so a typo
680 /// cannot make a measurement look like it came from an arm that never ran.
681 ///
682 /// The ceiling rides along because it is read on the same construction path
683 /// and printed by the same `Display`: a caller that logs `from_env()`'s
684 /// result once at store open has then logged **every** per-store variable
685 /// this crate consults, and `ZNIPPY_GIT_REDB_CACHE_BYTES` is no longer the
686 /// one that can be set on a host, stop at a container boundary, and leave
687 /// no trace of having done so.
688 pub fn from_env() -> Result<Self> {
689 let mut cfg = StoreConfig::DEFAULT;
690 if let Some(v) = read_env(ENV_WRITER) {
691 cfg.writer = WriterArm::parse(&v)?;
692 }
693 if let Some(v) = read_env(ENV_INDEX) {
694 cfg.index = IndexArm::parse(&v)?;
695 }
696 if let Some(v) = read_env(ENV_GC) {
697 cfg.gc = GcArm::parse(&v)?;
698 }
699 cfg.redb_cache_bytes = redb_cache_bytes()?;
700 Ok(cfg)
701 }
702
703 /// Same three arms with a different writer. For a bench that sweeps one axis.
704 pub fn with_writer(mut self, w: WriterArm) -> Self {
705 self.writer = w;
706 self
707 }
708
709 pub fn with_index(mut self, i: IndexArm) -> Self {
710 self.index = i;
711 self
712 }
713
714 pub fn with_gc(mut self, g: GcArm) -> Self {
715 self.gc = g;
716 self
717 }
718
719 /// Same arms, a different redb page-cache ceiling. What
720 /// [`GitStore::open`](crate::git_ops::GitStore::open) uses to put the
721 /// environment's ceiling on the default arms without reading any arm.
722 pub fn with_redb_cache_bytes(mut self, bytes: usize) -> Self {
723 self.redb_cache_bytes = bytes;
724 self
725 }
726}
727
728/// `KEY=value` for every per-store variable, in the spelling an operator
729/// would type — so one log line at store open is a complete, reproducible
730/// statement of what the environment selected, including the ceiling.
731impl std::fmt::Display for StoreConfig {
732 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
733 write!(
734 f,
735 "{}={} {}={} {}={} {}={}",
736 ENV_WRITER,
737 self.writer.as_str(),
738 ENV_INDEX,
739 self.index.as_str(),
740 ENV_GC,
741 self.gc.as_str(),
742 ENV_REDB_CACHE,
743 self.redb_cache_bytes
744 )
745 }
746}
747
748#[cfg(test)]
749mod tests {
750 use super::*;
751 use crate::archive_write::read_journal;
752 use crate::git_ops::{GitOps, GitStore, open_from_env, open_selected};
753 use crate::index_layout::{OneTableFourColumns, PackedPayload};
754 use crate::object::GitHashKind;
755 use crate::store::tests::{corpus_pack, tmpdir};
756 use std::sync::Mutex;
757
758 fn loadavg() -> String {
759 std::fs::read_to_string("/proc/loadavg")
760 .unwrap_or_default()
761 .split_whitespace()
762 .take(3)
763 .collect::<Vec<_>>()
764 .join(" ")
765 }
766
767 /// The environment is process-global and this crate's tests run in parallel
768 /// threads, so every guard that sets or counts an environment read takes
769 /// this first. Without it [`env_reads`] would be a shared counter two tests
770 /// moved at once, and the read-once guard below would be a coin toss.
771 static ENV_LOCK: Mutex<()> = Mutex::new(());
772
773 /// Run `f` with this module's variables set to `vars`, restoring whatever
774 /// was there before.
775 ///
776 /// `ENV_REDB_CACHE` is cleared along with the three arms even though no test
777 /// sets it: it is read on the same construction path, and a value inherited
778 /// from the surrounding shell would otherwise change the footprint a test
779 /// measures without appearing anywhere in the test.
780 fn with_env<R>(vars: &[(&str, &str)], f: impl FnOnce() -> R) -> R {
781 let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
782 let saved: Vec<(String, Option<String>)> = [ENV_WRITER, ENV_INDEX, ENV_GC, ENV_REDB_CACHE]
783 .iter()
784 .map(|k| (k.to_string(), std::env::var(k).ok()))
785 .collect();
786 // SAFETY (edition 2024): the process-wide environment is mutated only
787 // under ENV_LOCK, and no thread this crate spawns reads it.
788 unsafe {
789 for (k, _) in &saved {
790 std::env::remove_var(k);
791 }
792 for (k, v) in vars {
793 std::env::set_var(k, v);
794 }
795 }
796 let out = f();
797 unsafe {
798 for (k, v) in &saved {
799 match v {
800 Some(v) => std::env::set_var(k, v),
801 None => std::env::remove_var(k),
802 }
803 }
804 }
805 out
806 }
807
808 /// **The writer arm really is the writer that runs — asserted on the files
809 /// on disk, not on a name.**
810 ///
811 /// The two arms differ in exactly one observable thing and it is a file: a
812 /// durable arm writes an Arrow IPC journal row naming the extent before
813 /// `append` returns, and [`WriterArm::Fast`] writes no journal at all. So
814 /// the same pack is pushed into two stores that differ only in
815 /// [`StoreConfig::writer`], and what is asserted is the **payload byte for
816 /// byte in both** (the arm must not change what is stored) and the
817 /// **journal present in one and absent in the other** (the arm must change
818 /// what is promised).
819 ///
820 /// Seen RED by ignoring the selection in `GitStore::open_with_arms` —
821 /// `arms.writer.create(&blobs)?` → `WriterArm::Safe.create(&blobs)?`, which
822 /// is the hardcoded `SafeWriter::create(&blobs)?` this whole change removes:
823 /// "the fast arm left a journal at
824 /// /tmp/…-arm-writer-fast-…/objects.pack.journal — a writer that was not
825 /// selected ran". Restored.
826 ///
827 /// `writer_name()` is asserted **after** the two directory listings, on
828 /// purpose: with it first the same break failed on a `&'static str`
829 /// (`left: "SafeWriter", right: "FastWriter"`), which proves a label was
830 /// copied and not that a byte moved.
831 ///
832 /// **What it does NOT catch, found by trying.** Making `WriterArm::journal`
833 /// return `Some` for `Fast` as well leaves this guard **green**: no
834 /// `SafeWriter` runs, so no journal file is ever created, and
835 /// `!fast_journal.exists()` still holds. That break is caught one level down
836 /// by [`only_the_arms_that_write_a_journal_name_one`], which asserts on the
837 /// path itself rather than on a file — recorded here rather than quietly
838 /// claimed, because a guard's blind spots are the part worth writing down.
839 #[test]
840 fn each_writer_arm_leaves_its_own_durability_on_disk() {
841 let (pack, rows) = corpus_pack();
842
843 // ── the fast arm: bytes, and nothing that says they were acked ───────
844 let fast_dir = tmpdir("arm-writer-fast");
845 let fast = GitStore::<OneTableFourColumns>::open_with_arms(
846 &fast_dir,
847 "rickard",
848 GitHashKind::Sha1,
849 StoreConfig::DEFAULT.with_writer(WriterArm::Fast),
850 )
851 .unwrap();
852 let fast_tx = fast.put_pack(&pack).unwrap();
853 let (fo, fl) = fast_tx.extent.unwrap();
854 let fast_blobs = fast_dir.join("objects.pack");
855 let fast_journal = crate::archive_write::journal_path(&fast_blobs);
856 assert_eq!(
857 &std::fs::read(&fast_blobs).unwrap()[fo as usize..(fo + fl) as usize],
858 &pack[..],
859 "the fast arm did not store the pack verbatim — the arm may change the promise, \
860 never the payload"
861 );
862 assert!(
863 !fast_journal.exists(),
864 "the fast arm left a journal at {} — a writer that was not selected ran",
865 fast_journal.display()
866 );
867
868 // ── the safe arm: the same bytes, plus the durable row that claims them
869 let safe_dir = tmpdir("arm-writer-safe");
870 let safe = GitStore::<OneTableFourColumns>::open_with_arms(
871 &safe_dir,
872 "rickard",
873 GitHashKind::Sha1,
874 StoreConfig::DEFAULT.with_writer(WriterArm::Safe),
875 )
876 .unwrap();
877 let safe_tx = safe.put_pack(&pack).unwrap();
878 let (so, sl) = safe_tx.extent.unwrap();
879 let safe_blobs = safe_dir.join("objects.pack");
880 let safe_journal = crate::archive_write::journal_path(&safe_blobs);
881 assert_eq!(
882 &std::fs::read(&safe_blobs).unwrap()[so as usize..(so + sl) as usize],
883 &pack[..],
884 "the safe arm did not store the pack verbatim"
885 );
886 assert!(
887 safe_journal.exists(),
888 "the safe arm wrote no journal — the durable arm did not run"
889 );
890 assert_eq!(
891 read_journal(&safe_journal).unwrap(),
892 vec![(so, sl)],
893 "the journal does not name the extent that was acked"
894 );
895
896 // Both arms store the same bytes at the same offset: the selection
897 // moves the durability contract and nothing else.
898 assert_eq!((fo, fl), (so, sl), "the two arms disagree about the extent");
899 // The labels, asserted **after** the evidence — a name that agreed with
900 // a directory listing that did not would be the wrong thing to fail on.
901 assert_eq!(fast.writer_name(), "FastWriter");
902 assert_eq!(safe.writer_name(), "SafeWriter");
903 fast.wait_indexed();
904 safe.wait_indexed();
905 assert_eq!(fast.object_count(), rows.len());
906 assert_eq!(safe.object_count(), rows.len());
907 eprintln!(
908 "load {}; {} objects: fast arm {} journal row(s), safe arm {} — {}",
909 loadavg(),
910 rows.len(),
911 if fast_journal.exists() { 1 } else { 0 },
912 read_journal(&safe_journal).unwrap().len(),
913 WriterArm::Fast.durability(),
914 );
915 }
916
917 /// **The third writer arm is selectable through a store too, and it lands
918 /// the same durable journal.**
919 ///
920 /// The `fast`/`safe` guard above is the contrast; this one is the coverage.
921 /// It asserts on applied output — the pack verbatim on disk and one journal
922 /// row naming its extent — which is the same pair
923 /// [`each_writer_arm_leaves_its_own_durability_on_disk`] asserts for `safe`,
924 /// because the two durable arms write **one** journal format through two
925 /// transports (LAW 5) and a store must not be able to tell them apart.
926 ///
927 /// A kernel that cannot run the chain is a **failure, not a skip**: the same
928 /// policy `tests/archive_write.rs` already takes, because a silently skipped
929 /// arm is an arm nobody notices stopped working.
930 ///
931 /// Seen RED by pointing the arm at the wrong writer —
932 /// `WriterArm::Uring => Box::new(SafeWriter::create(blobs)?)` in
933 /// `WriterArm::create`: "the uring arm ran a different writer — left:
934 /// \"SafeWriter\", right: \"UringWriter\"". Restored.
935 ///
936 /// **That red lands on a name, and here that is the honest ceiling.** The
937 /// two durable arms are *required* to be indistinguishable on disk — one
938 /// journal format, one encoder, two transports — so there is no applied
939 /// output that separates them, and inventing one would mean breaking LAW 5
940 /// to make a guard feel better. The applied-output assertions above prove
941 /// the chain did the job; the name is the only thing that can say which
942 /// transport did it.
943 #[cfg(target_os = "linux")]
944 #[test]
945 fn the_uring_arm_is_selectable_through_a_store_and_lands_the_same_journal() {
946 let dir = tmpdir("arm-writer-uring");
947 let store = GitStore::<OneTableFourColumns>::open_with_arms(
948 &dir,
949 "rickard",
950 GitHashKind::Sha1,
951 StoreConfig::DEFAULT.with_writer(WriterArm::Uring),
952 )
953 .expect(
954 "the io_uring arm could not be built on this kernel — not skipped, this is a real \
955 failure",
956 );
957 let (pack, oid) = crate::store::tests::one_blob_pack(b"a push down the io_uring chain");
958 let tx = store.put_pack(&pack).unwrap();
959 let (o, l) = tx.extent.unwrap();
960
961 let blobs = dir.join("objects.pack");
962 assert_eq!(
963 &std::fs::read(&blobs).unwrap()[o as usize..(o + l) as usize],
964 &pack[..],
965 "the uring arm did not store the pack verbatim"
966 );
967 assert_eq!(
968 read_journal(&crate::archive_write::journal_path(&blobs)).unwrap(),
969 vec![(o, l)],
970 "the uring arm's journal does not name the extent it acked — the two durable arms \
971 must write one journal format"
972 );
973 assert_eq!(store.writer_name(), "UringWriter", "the uring arm ran a different writer");
974 store.wait_indexed();
975 assert!(store.has(&oid).unwrap(), "the pushed object never reached the index");
976 }
977
978 /// **The gc arm really is the gc that runs — asserted on which files exist
979 /// afterwards.**
980 ///
981 /// [`GcArm::NewGeneration`] renames the compacted archive to `x.g1.znippy`
982 /// and unlinks the original **last**; [`GcArm::CompactInPlace`] renames over
983 /// the original name and produces no generation. Those are two different
984 /// sets of files on disk for the same input, which is what is asserted —
985 /// `GcReport::strategy` is checked too, but it is a label and the
986 /// directory listing is the evidence.
987 ///
988 /// Seen RED by ignoring the selection in `GitStore::open_with_arms` —
989 /// `gc: arms.gc.create()` → `gc: GcArm::NewGeneration.create()`: "the
990 /// in-place arm produced a new generation at
991 /// /tmp/…-arm-gc-in-place-…/repository.g1.znippy — a gc that was not
992 /// selected ran". Restored.
993 ///
994 /// `report.strategy` is asserted **after** the directory listing, on
995 /// purpose: with the strategy check first the same break failed on a
996 /// `&'static str` (`left: "NewGeneration", right: "CompactInPlace"`), which
997 /// is a label agreeing with itself and says nothing about what happened to
998 /// the archive.
999 #[test]
1000 fn each_gc_arm_leaves_its_own_generation_on_disk() {
1001 for arm in GcArm::ALL {
1002 let dir = tmpdir(&format!("arm-gc-{}", arm.as_str()));
1003 let store = GitStore::<OneTableFourColumns>::open_with_arms(
1004 &dir,
1005 "rickard",
1006 GitHashKind::Sha1,
1007 StoreConfig::DEFAULT.with_gc(arm),
1008 )
1009 .unwrap();
1010 let (pack, _) = corpus_pack();
1011 store.put(&pack, &[]).unwrap();
1012 store.absorb_pending().unwrap();
1013
1014 let root = store
1015 .graph_snapshot()
1016 .into_iter()
1017 .find(|c| c.generation == 1)
1018 .expect("a root commit");
1019 let root_raw = hex::decode(&root.oid).unwrap();
1020 store
1021 .update_ref("refs/heads/root", None, Some(&root_raw))
1022 .unwrap();
1023
1024 // A real znippy archive for the compaction step to work on — the
1025 // same fixture `store::tests`' own gc guard builds.
1026 let files = vec![
1027 ("pack-0.pack".to_string(), pack.clone()),
1028 ("pack-1.pack".to_string(), pack.clone()),
1029 ];
1030 znippy_common::create_archive(store.archive_path(), &files, 3).unwrap();
1031 let original = store.archive_path().to_path_buf();
1032 let generation = crate::gc::next_generation(&original).unwrap();
1033
1034 let report = store.gc().unwrap();
1035 match arm {
1036 GcArm::NewGeneration => {
1037 assert_eq!(report.archive, generation);
1038 assert!(
1039 generation.exists(),
1040 "the new-generation arm produced no {}",
1041 generation.display()
1042 );
1043 assert!(
1044 !original.exists(),
1045 "the new-generation arm kept the old generation at {}",
1046 original.display()
1047 );
1048 assert_eq!(report.retired.as_deref(), Some(original.as_path()));
1049 assert!(report.verified, "the new generation was not read back");
1050 }
1051 GcArm::CompactInPlace => {
1052 assert!(
1053 !generation.exists(),
1054 "the in-place arm produced a new generation at {} — a gc that was not \
1055 selected ran",
1056 generation.display()
1057 );
1058 assert!(
1059 original.exists(),
1060 "the in-place arm removed the archive it compacts into"
1061 );
1062 assert_eq!(report.archive, original);
1063 assert_eq!(report.retired, None);
1064 }
1065 }
1066 // The label, after the evidence.
1067 assert_eq!(report.strategy, arm.strategy());
1068 assert!(
1069 report.bytes_after <= report.bytes_before,
1070 "{} grew the archive: {} → {}",
1071 arm.strategy(),
1072 report.bytes_before,
1073 report.bytes_after
1074 );
1075 eprintln!(
1076 "load {}; gc arm {}: {} → {} bytes, archive now {}",
1077 loadavg(),
1078 arm.strategy(),
1079 report.bytes_before,
1080 report.bytes_after,
1081 report.archive.display()
1082 );
1083 }
1084 }
1085
1086 /// **The index arm really is the layout that gets built — asserted on the
1087 /// Arrow bytes it materialised, and on all three agreeing about every
1088 /// object.**
1089 ///
1090 /// A type name would prove nothing here (all three stacks report
1091 /// `ObjectReadStack`, because that is what they are). What distinguishes the
1092 /// arms is the projection they actually built:
1093 /// [`ObjectIndex::ipc_bytes`] is the size of the Arrow IPC payload held
1094 /// resident, and one packed 25-byte column, four columns in one section and
1095 /// four independent sections are three different numbers for the same 1352
1096 /// objects. Pairwise-distinct is the assertion.
1097 ///
1098 /// The other half matters more: the arms are a **layout** choice, so all
1099 /// three must answer identically. Every oid's full row is compared across
1100 /// the three, so an arm that decoded its own payload wrongly fails here
1101 /// rather than in production.
1102 ///
1103 /// Driven through [`open_selected`] — the runtime door — so the guard fails
1104 /// when the *selector* stops selecting rather than only when a layout is
1105 /// broken.
1106 ///
1107 /// Seen RED by pinning the type in `open_selected`, every match arm building
1108 /// `SelectedStore::OneTableFourColumns(GitStore::<OneTableFourColumns>…)`,
1109 /// which is the state this change starts from: "one-table and four-tables
1110 /// materialised the same 145544 IPC bytes — the index arm was not
1111 /// selected". Restored.
1112 ///
1113 /// **`store.arms().index` stayed green under that break**, and that is the
1114 /// reason it is not the assertion: `arms` is the value that was *requested*,
1115 /// so it agrees with the caller no matter which type got built. The byte
1116 /// count is what the store actually did.
1117 #[test]
1118 fn each_index_arm_builds_its_own_projection_and_all_three_agree() {
1119 let (pack, rows) = corpus_pack();
1120
1121 let mut built = Vec::new();
1122 for arm in IndexArm::ALL {
1123 let store = open_selected(
1124 &tmpdir(&format!("arm-index-{}", arm.as_str())),
1125 "rickard",
1126 GitHashKind::Sha1,
1127 StoreConfig::DEFAULT.with_index(arm),
1128 )
1129 .unwrap();
1130 store.put_pack(&pack).unwrap();
1131 store.wait_indexed();
1132 // A rebuild, so the projection under test — not the redb tail — is
1133 // what answers below.
1134 store.rebuild_projection().unwrap();
1135 assert_eq!(store.arms().index, arm);
1136 // The name the BUILT projection reports, against the name this arm
1137 // says it builds. `arms().index` above is the request echoed back
1138 // and stays green when the selector selects nothing;
1139 // `index_name()` goes through `ObjectReadStack::projection_name`
1140 // to `S::name()`, so it can only answer what was monomorphised.
1141 //
1142 // It is what a server logs to say which layout it is running —
1143 // gunnar's `store.znippy_arms_selected` — and the reason
1144 // `ObjectIndex::name` on the stack itself is no use for that: the
1145 // stack answers "ObjectReadStack" for all three, because that is
1146 // what the stack is.
1147 assert_eq!(
1148 store.index_name(),
1149 arm.projection_name(),
1150 "the {} arm built a projection calling itself {}",
1151 arm.as_str(),
1152 store.index_name()
1153 );
1154 built.push((arm, store));
1155 }
1156
1157 // Applied output: three layouts, three different quantities of Arrow IPC
1158 // materialised for the same objects.
1159 for (i, (a, sa)) in built.iter().enumerate() {
1160 for (b, sb) in &built[i + 1..] {
1161 assert_ne!(
1162 sa.index_ipc_bytes(),
1163 sb.index_ipc_bytes(),
1164 "{} and {} materialised the same {} IPC bytes — the index arm was not selected",
1165 a.as_str(),
1166 b.as_str(),
1167 sa.index_ipc_bytes()
1168 );
1169 }
1170 }
1171
1172 // …and they are three spellings of one answer. `get` goes through the
1173 // whole stack — index row, extent, bytes off disk — so a layout that
1174 // decoded its own payload wrongly cannot agree here by accident.
1175 for r in rows.iter().take(512) {
1176 let first = built[0].1.get(&r.oid).unwrap();
1177 assert!(first.is_some(), "{} is missing from one-table", hex::encode(&r.oid));
1178 for (arm, store) in &built[1..] {
1179 assert_eq!(
1180 store.get(&r.oid).unwrap(),
1181 first,
1182 "{} disagrees with one-table about {}",
1183 arm.as_str(),
1184 hex::encode(&r.oid)
1185 );
1186 }
1187 }
1188 eprintln!(
1189 "load {}; {} objects: {}",
1190 loadavg(),
1191 rows.len(),
1192 built
1193 .iter()
1194 .map(|(a, s)| format!("{} {} B", a.as_str(), s.index_ipc_bytes()))
1195 .collect::<Vec<_>>()
1196 .join(", ")
1197 );
1198 }
1199
1200 /// **The default did not move, and no environment variable can move it.**
1201 ///
1202 /// The compatibility half of this change. `GitStore::open` built
1203 /// `SafeWriter` + `ObjectReadStack<OneTableFourColumns>` + `NewGeneration`
1204 /// before the selector existed and must build exactly that after it —
1205 /// including in a process whose environment names all three *other* arms,
1206 /// because a caller that never asked for a selector must not have its
1207 /// durability contract changed by somebody's shell.
1208 ///
1209 /// Asserted on applied output rather than on `arms()`: the journal row that
1210 /// only a durable writer produces, and the generation file that only
1211 /// `NewGeneration` produces.
1212 ///
1213 /// Seen RED by making the old constructor read the environment —
1214 /// `Self::open_with_arms(root, account, hash, StoreConfig::DEFAULT)` →
1215 /// `Self::open_with_arms(root, account, hash, StoreConfig::from_env()?)` in
1216 /// `GitStore::open_with`: "GitStore::open wrote no journal — an environment
1217 /// variable moved the default durability contract". Restored.
1218 ///
1219 /// `arms()` is asserted **after** the journal, for the third time in this
1220 /// module and for the same reason: with it first the break failed on
1221 /// `StoreConfig { writer: Fast, … }` vs `StoreConfig { writer: Safe, … }`,
1222 /// which is the request echoed back rather than the contract that was kept.
1223 #[test]
1224 fn the_default_is_unchanged_and_the_environment_cannot_move_it() {
1225 with_env(
1226 &[
1227 (ENV_WRITER, "fast"),
1228 (ENV_INDEX, "packed"),
1229 (ENV_GC, "in-place"),
1230 ],
1231 || {
1232 let dir = tmpdir("arm-default");
1233 let store = GitStore::open(&dir, "rickard").unwrap();
1234 let (pack, rows) = corpus_pack();
1235 let tx = store.put(&pack, &[]).unwrap();
1236 let journal = crate::archive_write::journal_path(&dir.join("objects.pack"));
1237 assert!(
1238 journal.exists(),
1239 "GitStore::open wrote no journal — an environment variable moved the default \
1240 durability contract"
1241 );
1242 assert_eq!(read_journal(&journal).unwrap(), vec![tx.extent.unwrap()]);
1243 store.wait_indexed();
1244 assert_eq!(store.object_count(), rows.len());
1245 // The labels, after the evidence.
1246 assert_eq!(
1247 store.arms(),
1248 StoreConfig::DEFAULT,
1249 "GitStore::open did not build the shipping arms"
1250 );
1251 assert_eq!(store.writer_name(), "SafeWriter");
1252
1253 // And the gc arm is still the one that keeps the old generation
1254 // until the new one is proven.
1255 let root = store
1256 .graph_snapshot()
1257 .into_iter()
1258 .find(|c| c.generation == 1)
1259 .expect("a root commit");
1260 let root_raw = hex::decode(&root.oid).unwrap();
1261 store
1262 .update_ref("refs/heads/root", None, Some(&root_raw))
1263 .unwrap();
1264 let files = vec![("pack-0.pack".to_string(), pack.clone())];
1265 znippy_common::create_archive(store.archive_path(), &files, 3).unwrap();
1266 let generation = crate::gc::next_generation(store.archive_path()).unwrap();
1267 let report = store.gc().unwrap();
1268 assert_eq!(report.strategy, "NewGeneration");
1269 assert!(
1270 generation.exists(),
1271 "GitStore::open's gc arm is not NewGeneration — the environment moved it"
1272 );
1273 },
1274 );
1275 }
1276
1277 /// **The selector is read once, at construction, and never per operation.**
1278 ///
1279 /// gunnar's own rule, stated in its source: *read once, here, and not per
1280 /// entry — a getenv inside the copy loop would be one syscall per object
1281 /// served*. A per-object `getenv` was a real defect found and fixed there,
1282 /// so this is asserted with a counter rather than trusted to review.
1283 ///
1284 /// [`env_reads`] counts every environment read this crate makes. The whole
1285 /// corpus pack is then pushed and served — one `put`, 1352 `has`, a batch
1286 /// `extents`, `get`, `size`, `refs` — across a **counter that does not
1287 /// move**.
1288 ///
1289 /// **Five reads at construction since 2026-08-21** (four since 2026-08-10,
1290 /// three before). Three are [`StoreConfig::from_env`]'s arms; the fourth is
1291 /// [`redb_cache_bytes`], which `from_env` now reads alongside them so the
1292 /// ceiling is part of the config a caller logs; the fifth is the explode
1293 /// policy `ExplodedArchive::open` reads through the same counted door.
1294 /// None of the extra two is an arm — they select no implementation — but
1295 /// each is an environment read, so each is counted, and each is read
1296 /// exactly once per store rather than once per database or once per lookup.
1297 ///
1298 /// Seen RED by re-reading the selector on the lookup path — adding
1299 /// `let _ = crate::arms::StoreConfig::from_env()?;` at the top of
1300 /// `GitStore::lookup_one`: "the selector was read **8070** times while
1301 /// serving 2692 operations — it must be read once, at construction; left:
1302 /// 8070, right: 3". Restored.
1303 ///
1304 /// Seen RED a second time, and this one is what keeps the guard from being
1305 /// vacuous: `StoreConfig::from_env` stubbed to `return
1306 /// Ok(StoreConfig::DEFAULT)` before it reads anything gives "opening a store
1307 /// read the environment **0** times, not once per variable". A selector that
1308 /// is never read at all also never moves the counter during serving, so
1309 /// without the construction-time line the guard would pass over a selector
1310 /// that does nothing. Restored.
1311 #[test]
1312 fn the_selector_is_read_once_at_construction_and_never_per_operation() {
1313 with_env(
1314 &[
1315 (ENV_WRITER, "safe"),
1316 (ENV_INDEX, "four-tables"),
1317 (ENV_GC, "in-place"),
1318 ],
1319 || {
1320 let dir = tmpdir("arm-read-once");
1321 let (pack, rows) = corpus_pack();
1322
1323 // `env_reads_here`, not `env_reads`: the process-wide counter
1324 // is moved by every other test thread that opens a store, and
1325 // since `redb_cache_bytes` joined the readers that is most of
1326 // them. Per thread it is exact.
1327 let before = env_reads_here();
1328 let store = open_from_env(&dir, "rickard", GitHashKind::Sha1).unwrap();
1329 let at_open = env_reads_here();
1330 // Three arms, the redb cache ceiling, the explode policy and
1331 // the explode budget. Once each — a store opens TWO redb
1332 // databases and still reads the ceiling once.
1333 assert_eq!(
1334 at_open - before,
1335 6,
1336 "opening a store read the environment {} times, not once per variable",
1337 at_open - before
1338 );
1339
1340 // Everything below this line is serving. Nothing here may read
1341 // the environment even once.
1342 let mut ops = 0u64;
1343 store.put(&pack, &[]).unwrap();
1344 ops += 1;
1345 let oids: Vec<&[u8]> = rows.iter().map(|r| r.oid.as_slice()).collect();
1346 for oid in &oids {
1347 assert!(store.has(oid).unwrap());
1348 ops += 1;
1349 }
1350 let ext = store.extents(&oids).unwrap();
1351 ops += 1;
1352 assert_eq!(ext.len(), oids.len());
1353 assert!(ext.iter().all(Option::is_some));
1354 assert!(store.get(oids[0]).unwrap().is_some());
1355 assert!(store.size(oids[0]).unwrap().is_some());
1356 store.refs().unwrap();
1357 ops += 3;
1358
1359 let after = env_reads_here();
1360 assert_eq!(
1361 after, at_open,
1362 "the selector was read {} times while serving {ops} operations — it must be \
1363 read once, at construction",
1364 after - before
1365 );
1366 eprintln!(
1367 "load {}; {ops} operations over {} objects: {} environment read(s), all of \
1368 them at construction",
1369 loadavg(),
1370 rows.len(),
1371 at_open - before,
1372 );
1373 },
1374 );
1375 }
1376
1377 /// **A bad value is an error, not a silent default** — through the real
1378 /// front door, so the refusal cannot be a parser test that nothing calls.
1379 #[test]
1380 fn an_unknown_arm_refuses_to_open_rather_than_falling_back() {
1381 with_env(&[(ENV_WRITER, "safest")], || {
1382 let dir = tmpdir("arm-typo");
1383 let e = match open_from_env(&dir, "rickard", GitHashKind::Sha1) {
1384 Ok(_) => panic!("a typo opened a store on the default arm"),
1385 Err(e) => e,
1386 };
1387 let msg = format!("{e:#}");
1388 assert!(
1389 msg.contains("'safest' is not a writer arm") && msg.contains(ENV_WRITER),
1390 "the refusal must name the bad value and the variable it came from: {msg}"
1391 );
1392 });
1393 // …and an empty environment is the shipping default, not an error.
1394 with_env(&[], || {
1395 assert_eq!(StoreConfig::from_env().unwrap(), StoreConfig::DEFAULT);
1396 });
1397 }
1398
1399 /// **The runtime door and the typed door build the same store.**
1400 ///
1401 /// [`open_selected`] exists so a value can choose the index arm, which is a
1402 /// type; the risk it carries is that the dispatched path drifts from the
1403 /// monomorphised one. Asserted on applied output: the same pack pushed
1404 /// through both answers the same for every oid.
1405 #[test]
1406 fn the_selected_store_and_the_typed_store_answer_alike() {
1407 let (pack, rows) = corpus_pack();
1408 let arms = StoreConfig::DEFAULT.with_index(IndexArm::PackedPayload);
1409
1410 let boxed = open_selected(
1411 &tmpdir("arm-selected"),
1412 "rickard",
1413 GitHashKind::Sha1,
1414 arms,
1415 )
1416 .unwrap();
1417 let typed = GitStore::<PackedPayload>::open_with_arms(
1418 &tmpdir("arm-typed"),
1419 "rickard",
1420 GitHashKind::Sha1,
1421 arms,
1422 )
1423 .unwrap();
1424
1425 boxed.put(&pack, &[]).unwrap();
1426 typed.put(&pack, &[]).unwrap();
1427 for r in rows.iter().take(512) {
1428 let a = boxed.get(&r.oid).unwrap();
1429 let b = typed.get(&r.oid).unwrap();
1430 assert_eq!(a, b, "the boxed and typed stores disagree about {}", hex::encode(&r.oid));
1431 assert!(a.is_some());
1432 }
1433 }
1434
1435 /// Round-trips through every spelling, and a typo is an error rather than a
1436 /// default.
1437 #[test]
1438 fn every_arm_parses_from_the_name_an_operator_types() {
1439 for a in WriterArm::ALL {
1440 assert_eq!(WriterArm::parse(a.as_str()).unwrap(), a);
1441 assert_eq!(WriterArm::parse(&a.as_str().to_uppercase()).unwrap(), a);
1442 }
1443 for a in IndexArm::ALL {
1444 assert_eq!(IndexArm::parse(a.as_str()).unwrap(), a);
1445 }
1446 for a in GcArm::ALL {
1447 assert_eq!(GcArm::parse(a.as_str()).unwrap(), a);
1448 }
1449 // A typo must not become the default: an operator who mistyped `safe`
1450 // and got a measurement labelled `safe` would be reading a lie.
1451 for bad in ["saef", "", "fastwriter2", "none"] {
1452 assert!(
1453 WriterArm::parse(bad).is_err(),
1454 "'{bad}' parsed as a writer arm"
1455 );
1456 }
1457 assert!(IndexArm::parse("one-tabel").is_err());
1458 assert!(GcArm::parse("newgen").is_err());
1459 }
1460
1461 /// **[`ALL_ENV`] is complete, checked against the crate's own source.**
1462 ///
1463 /// Walks every `.rs` under this crate's `src/`, cuts each file at its first
1464 /// `#[cfg(test)]` (the convention here: one tests module, at the bottom),
1465 /// and finds every environment read in what is left — `std::env::var(…)`,
1466 /// `env::var_os(…)` and [`read_env`]`(…)`. The key each one names, whether
1467 /// a string literal or one of the `ENV_*` constants declared in this file,
1468 /// must be on [`ALL_ENV`]. The only `std::env::var` allowed outside that
1469 /// rule is the one inside [`read_env`] itself, which takes its key as a
1470 /// parameter.
1471 ///
1472 /// This is what goes red the day the crate grows a key without naming it —
1473 /// the defect gunnar's forge could not see from its side (it asserted its
1474 /// crossing list against a count it remembered, and the count was wrong
1475 /// for four months of one day). A source scan is the honest shape for it:
1476 /// the keys are string literals and the reads are call sites, and no
1477 /// runtime counter can tell which *names* were read.
1478 ///
1479 /// Seen RED by adding `std::env::var("ZNIPPY_GIT_NEW_KNOB")` to
1480 /// `git_ops.rs` outside its tests: "git_ops.rs reads ZNIPPY_GIT_NEW_KNOB
1481 /// and ALL_ENV does not name it". Restored.
1482 #[test]
1483 fn every_environment_read_in_this_crate_is_named_in_all_env() {
1484 let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
1485 let this_file = std::fs::read_to_string(src.join("arms.rs")).unwrap();
1486
1487 // `pub const ENV_X: &str = "…";` → ENV_X ↦ "…", from this file only.
1488 let mut consts: std::collections::BTreeMap<String, String> = Default::default();
1489 for line in this_file.lines() {
1490 let t = line.trim();
1491 let Some(rest) = t.strip_prefix("pub const ENV_") else { continue };
1492 let Some((name, val)) = rest.split_once(": &str = \"") else { continue };
1493 let val = val.split('"').next().unwrap();
1494 consts.insert(format!("ENV_{name}"), val.to_string());
1495 }
1496 assert!(consts.len() >= 8, "fewer ENV_* constants than expected: {consts:?}");
1497
1498 let mut seen: Vec<(String, String)> = Vec::new();
1499 let mut files = std::fs::read_dir(&src)
1500 .unwrap()
1501 .map(|e| e.unwrap().path())
1502 .filter(|p| p.extension().is_some_and(|e| e == "rs"))
1503 .collect::<Vec<_>>();
1504 files.sort();
1505 assert!(!files.is_empty());
1506 for path in files {
1507 let file = path.file_name().unwrap().to_string_lossy().into_owned();
1508 let text = std::fs::read_to_string(&path).unwrap();
1509 let non_test = match text.find("\n#[cfg(test)]") {
1510 Some(at) => &text[..at],
1511 None => &text[..],
1512 };
1513 for needle in ["env::var(", "env::var_os(", "read_env("] {
1514 let mut from = 0;
1515 while let Some(at) = non_test[from..].find(needle) {
1516 let call_at = from + at;
1517 from = call_at + needle.len();
1518 // The definition of `read_env` itself, and doc/comment lines
1519 // that merely mention a call, are not reads.
1520 let line_start = non_test[..call_at].rfind('\n').map_or(0, |i| i + 1);
1521 let line = non_test[line_start..].lines().next().unwrap_or("").trim_start();
1522 if line.starts_with("//") || line.starts_with("pub(crate) fn read_env") {
1523 continue;
1524 }
1525 // The `env::var(key)` inside `read_env` — the one door.
1526 if file == "arms.rs" && needle == "env::var(" && line.contains("var(key)") {
1527 continue;
1528 }
1529 let arg = non_test[from..].trim_start();
1530 let key = if let Some(lit) = arg.strip_prefix('"') {
1531 lit.split('"').next().unwrap().to_string()
1532 } else {
1533 let ident: String = arg
1534 .chars()
1535 .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == ':')
1536 .collect();
1537 let short = ident.rsplit("::").next().unwrap_or(&ident).to_string();
1538 consts.get(&short).cloned().unwrap_or_else(|| {
1539 panic!(
1540 "{file} reads the environment through `{needle}{ident}…`, which \
1541 is neither a string literal nor an ENV_* constant this test \
1542 can resolve — name the key as a `pub const ENV_*` in arms.rs"
1543 )
1544 })
1545 };
1546 seen.push((file.clone(), key));
1547 }
1548 }
1549 }
1550 assert!(
1551 seen.len() >= 8,
1552 "the scan found only {} environment reads; it is supposed to find at least the \
1553 eight in ALL_ENV ({seen:?})",
1554 seen.len()
1555 );
1556 for (file, key) in &seen {
1557 assert!(
1558 ALL_ENV.contains(&key.as_str()),
1559 "{file} reads {key} and ALL_ENV does not name it"
1560 );
1561 }
1562 // And the other direction: a key on the list that nothing reads is a
1563 // stale entry a consumer would be carrying for nothing.
1564 for key in ALL_ENV {
1565 assert!(
1566 seen.iter().any(|(_, k)| k == key),
1567 "ALL_ENV names {key} but no non-test code in this crate reads it"
1568 );
1569 }
1570 }
1571
1572 /// The default is the shipping combination, spelled out rather than derived
1573 /// — a derived `Default` that drifted would move the durability contract.
1574 #[test]
1575 fn the_default_config_is_the_shipping_combination() {
1576 assert_eq!(StoreConfig::default(), StoreConfig::DEFAULT);
1577 assert_eq!(StoreConfig::DEFAULT.writer, WriterArm::Safe);
1578 assert_eq!(StoreConfig::DEFAULT.index, IndexArm::OneTableFourColumns);
1579 assert_eq!(StoreConfig::DEFAULT.gc, GcArm::NewGeneration);
1580 assert_eq!(
1581 StoreConfig::DEFAULT.to_string(),
1582 "ZNIPPY_GIT_WRITER=safe ZNIPPY_GIT_INDEX=one-table ZNIPPY_GIT_GC=new-generation \
1583 ZNIPPY_GIT_REDB_CACHE_BYTES=67108864"
1584 );
1585 }
1586
1587 /// **Only the durable arms name a journal**, and the fast one names none.
1588 ///
1589 /// Not cosmetic: the path returned here is what a reopen derives §13.12's
1590 /// `indexed` bit from, so an arm that writes no journal must not hand back
1591 /// the name of one — a store that ran on `SafeWriter` and is reopened on
1592 /// `FastWriter` would then diff against a log this writer is not appending
1593 /// to, and resume pack ordinals from it.
1594 ///
1595 /// Seen RED by `WriterArm::Fast => Some(journal_path(blobs))`: "left:
1596 /// Some(\"/nonexistent/objects.pack.journal\") right: None". Restored.
1597 /// This is the guard that catches that break — the disk-level one above
1598 /// stays green for it, which is why both exist.
1599 #[test]
1600 fn only_the_arms_that_write_a_journal_name_one() {
1601 let blobs = Path::new("/nonexistent/objects.pack");
1602 assert_eq!(WriterArm::Fast.journal(blobs), None);
1603 assert_eq!(
1604 WriterArm::Safe.journal(blobs),
1605 Some(PathBuf::from("/nonexistent/objects.pack.journal"))
1606 );
1607 assert_eq!(
1608 WriterArm::Uring.journal(blobs),
1609 WriterArm::Safe.journal(blobs),
1610 "the two durable arms share one journal format (LAW 5) and must share its name"
1611 );
1612 }
1613
1614 /// The arm's stated durability is the writer's own, not a second copy of it
1615 /// that could drift.
1616 #[test]
1617 fn the_arms_durability_line_matches_the_writer_it_builds() {
1618 let dir = crate::store::tests::tmpdir("arm-durability");
1619 for arm in [WriterArm::Fast, WriterArm::Safe] {
1620 let w = arm.create(&dir.join(format!("{}.pack", arm.as_str()))).unwrap();
1621 match arm {
1622 WriterArm::Fast => {
1623 assert_eq!(w.name(), "FastWriter");
1624 assert!(
1625 w.durability().starts_with("none"),
1626 "FastWriter must say plainly that it promises nothing: {}",
1627 w.durability()
1628 );
1629 assert!(arm.durability().starts_with("none"));
1630 }
1631 WriterArm::Safe => {
1632 assert_eq!(w.name(), "SafeWriter");
1633 assert_eq!(w.durability(), arm.durability());
1634 }
1635 WriterArm::Uring => unreachable!(),
1636 }
1637 }
1638 }
1639}