Skip to main content

znippy_plugin_git/
exploded_cache.rs

1//! **The exploded tier is a CACHE, not a tier — and this is the bound.**
2//!
3//! Rickard, 2026-08-30, on being shown the lazy-explode design: *"does lazy
4//! explode mean it eventually takes the disk anyway?"* — and the honest answer
5//! is **yes, unless the tier is capped**, because a client that browses a whole
6//! history reads every object once and a write-back-on-first-read tier would
7//! then hold exactly what the eager one held. MEASURED on the rig 2026-08-30:
8//! the 8.12 GiB `torvalds/linux` pack drove the eager tier to **141.7 GiB**
9//! into `/data`, ~17× the pack. *"We cannot have one repo take all 300 GB
10//! disk."*
11//!
12//! So the tier has a **byte budget** and evicts. Nothing here is data: every
13//! row is re-derivable from the verbatim pack bytes by
14//! [`crate::resolve::materialize_at`], so an eviction is never a loss and never
15//! an error a client can see — it is a later read paying ~0.5–2 ms to inflate
16//! its own delta chain again.
17//!
18//! # Two pools, and the split is the whole design
19//!
20//! ```text
21//!   objects.exploded         the EAGER pool — what the indexer writes at push
22//!                            time. Under the shipped policy that is commits
23//!                            and tags: what `graph`/`reach`/tag-peel need, so
24//!                            visibility and pull checks never stall.
25//!                            NEVER evicted — it is the "commits last" rule,
26//!                            held by construction rather than by a comparator.
27//!
28//!   objects.exploded.c1      the LAZY pool — first-read write-backs, appended
29//!   objects.exploded.c2      in read order, one file per segment.
30//!   …                        EVICTION IS ONE `unlink` of the oldest segment.
31//! ```
32//!
33//! Both pools are counted against the budget and both are named on the
34//! dashboard; only the lazy one is evictable. If the eager pool alone exceeds
35//! the budget the lazy pool is evicted to nothing and the eager pool is still
36//! kept — a store that cannot answer `reach` is broken, and a store that reads
37//! slowly is not.
38//!
39//! # Why segments, and why eviction is an `unlink`
40//!
41//! [`ExplodedArchive`] is one append-only Arrow IPC stream: `[schema][batch]…`,
42//! nothing ever rewritten. That is what makes it 1.0× its payload instead of
43//! redb's 12×, and it is also what makes *deleting a row in the middle* cost a
44//! whole-file rewrite — up to 17 GB, which the module docs already refuse to
45//! smuggle into `gc`. Cutting the pool into segment files turns "reclaim the
46//! coldest bytes" into `remove_file`: O(1), no rewrite, no read amplification,
47//! and a crash during it leaves a pool that is merely shorter.
48//!
49//! # The recency argument, stated honestly
50//!
51//! Segments are appended in **first-read order**, so dropping the oldest drops
52//! the objects least recently *admitted*. That is not the same as least
53//! recently *used* — an object read at minute 1 and again at minute 90 sits in
54//! an old segment. It is not promoted, and it does not need to be: when its
55//! segment is dropped, the next read of it misses, re-inflates its chain, and
56//! **writes it back into the newest segment**. Re-entry-on-miss is what makes
57//! this LRU-shaped, at the cost of one chain inflate per hot object per eviction
58//! cycle rather than a copy per hit. So it is FIFO over segments with
59//! re-entry-on-miss, and the thing an LRU is wanted for — a working set that
60//! stays resident under a scan of everything else — holds, because the working
61//! set is what keeps re-entering.
62//!
63//! # What a full-history read now costs on disk
64//!
65//! The plateau, not the climb. A reader that walks every object of a
66//! Linux-sized repository writes back every object it inflates; the pool grows
67//! to the budget and then stops, because each rotation past it drops the oldest
68//! segment. That is the number lane Q reports as its headline, and
69//! `the_tier_plateaus_at_its_budget_under_a_full_scan` is the test that asserts
70//! it rather than the sentence.
71
72use std::path::{Path, PathBuf};
73use std::sync::Mutex;
74use std::sync::atomic::{AtomicU64, Ordering};
75
76use anyhow::Result;
77
78use crate::exploded::ExplodedStats;
79use crate::exploded_arrow::{ExplodePolicy, ExplodedArchive};
80use crate::object::GitObjectKind;
81
82/// One lazy segment is closed and a new one started once it passes this many
83/// bytes. Eviction granularity is one segment, so this is the quantum a budget
84/// is spent and reclaimed in: 1/16 of the budget, floored so a small budget
85/// still gets whole batches and ceilinged so a huge one does not accumulate
86/// thousands of open indexes.
87const MIN_SEGMENT: u64 = 16 << 20;
88const MAX_SEGMENT: u64 = 1 << 30;
89const SEGMENTS_PER_BUDGET: u64 = 16;
90
91/// The lazy pool buffers this much before it writes. Far under
92/// [`crate::exploded_arrow::FLUSH_BYTES`] on purpose: that 64 MiB buffer is
93/// sized for an indexer draining a pack, and a **reader's** write-back holding
94/// 64 MiB per store is memory the box did not agree to spend.
95pub const CACHE_FLUSH_BYTES: u64 = 4 << 20;
96
97// ════════════════════════════════════════════════════════════════════════════
98// A VALIDATION READ IS NOT A READER
99// ════════════════════════════════════════════════════════════════════════════
100
101thread_local! {
102    /// Depth, not a flag: guards nest, and the innermost one ending must not
103    /// re-open the cache for an outer scope that is still validating.
104    static SUPPRESS_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
105}
106
107/// **Declare that reads on this thread are validation, not a reader's.**
108///
109/// `receive-pack` reads every commit and tree it was sent — once — to prove the
110/// push closes, and then never reads them again. Those reads look identical to
111/// a client's from inside the store, so the store cannot tell them apart and
112/// the caller must say.
113///
114/// MEASURED on `torvalds/linux`, oden 2026-09-03: the lazy pool is **empty
115/// until the instant indexing completes** and then grows to
116/// **6 778 047 872 B** (13 segments) before the push returns — 31 % of the
117/// whole store and the largest non-pack thing in it, written for a reader that
118/// does not exist. Full table in
119/// `gunnar/.nornir/storage-levers-2026-09-03.md`.
120///
121/// # Scope
122///
123/// **Thread-local, and that is the point.** A `receive-pack` connection does
124/// its ingest, its index and its connectivity walk on one thread and serves
125/// nobody; the background absorber runs elsewhere and is untouched, and so is
126/// every serving connection. Nothing global is switched off, so a store that is
127/// simultaneously answering a clone still warms its cache from that clone.
128///
129/// The eager pool is not affected either: the indexer writes that one directly,
130/// not through [`ExplodedCache::write_back`].
131///
132/// # It is a guard, not a pair of calls
133///
134/// Restored on drop, including on unwind — a panic inside a connectivity walk
135/// must not leave a thread that never caches again.
136#[must_use = "the suppression lasts only as long as the guard is held"]
137pub fn suppress_write_back() -> SuppressWriteBack {
138    SUPPRESS_DEPTH.with(|d| d.set(d.get().saturating_add(1)));
139    SuppressWriteBack { _private: () }
140}
141
142/// Whether [`suppress_write_back`] is in force on this thread.
143pub fn write_back_suppressed() -> bool {
144    SUPPRESS_DEPTH.with(|d| d.get()) > 0
145}
146
147/// The guard [`suppress_write_back`] returns. See it for what this is for.
148pub struct SuppressWriteBack {
149    _private: (),
150}
151
152impl Drop for SuppressWriteBack {
153    fn drop(&mut self) {
154        SUPPRESS_DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
155    }
156}
157
158// ════════════════════════════════════════════════════════════════════════════
159// The admission policy: DO NOT EXPLODE UNIFORMLY
160// ════════════════════════════════════════════════════════════════════════════
161
162/// **The cheapest thing a cache can do is not cache.**
163///
164/// Rickard, 2026-08-30: *"can the index point at the original git object and
165/// decompress it directly instead of materialising everything?"* — and it can,
166/// because a packfile is not one stream. Every object is its own zlib stream at
167/// its own offset, so `oid → (offset, type, base, inflated size)` is enough to
168/// inflate exactly one object ([`crate::resolve::materialize_at`]). A **whole**
169/// object is then one `inflate` of a mapped byte range: microseconds, no chain,
170/// no delta application. Writing that into a cache costs a copy, a flush, an
171/// fsync and a slice of somebody's quota — to save microseconds it did not
172/// need saving.
173///
174/// So the cache admits on **rebuild cost**, not on being read:
175///
176/// # It admits on cost DENSITY, not on cost
177///
178/// The first cut admitted anything over 16 KiB "because the inflate itself is
179/// the cost". That is true and it is the wrong rule, because the budget is
180/// **shared**: what a cache should hold is what saves the most time *per byte
181/// held*. A 3 MiB whole blob costs one linear inflate — bandwidth-bound,
182/// microseconds a kilobyte — and would occupy the same 3 MiB as ~250 deep tree
183/// chains that each cost a chain walk. Admitting it evicts all of them.
184///
185/// | what the read paid | admitted? |
186/// |---|---|
187/// | over [`MAX_CACHED_BYTES`] inflated | **no** — a bad tenant of a shared budget whatever its depth; its direct read is bandwidth-bound anyway |
188/// | depth 0–[`CHEAP_DEPTH`] | **no** — one inflate of one mapped zlib stream, plus at most two delta applications. Caching it spends quota to save microseconds |
189/// | deeper than [`CHEAP_DEPTH`] | yes — every extra link is another inflate plus a delta application, and git allows chains to 50 |
190/// | a base outside this archive | yes — it went through a [`BaseSource`](crate::resolve::BaseSource), which is never the cheap path |
191///
192/// The thresholds are named, not tuned: `CHEAP_DEPTH` is 2 because git's own
193/// default `pack.depth` is 50 and a 0–2 chain is at most two delta applications
194/// over a mapped buffer; `MAX_CACHED_BYTES` is 1 MiB because that is where one
195/// object starts costing what hundreds of chain-heavy ones do.
196///
197/// **This is also the zero-copy rule.** A declined object is declined *before*
198/// anything is copied, so the commonest reads — and every large one — cost the
199/// cache exactly zero bytes. MEASURED by lane AA 2026-08-30: one 3 145 728 B
200/// object read through `gunnar-cli` allocated 6 340 693 B, exactly two copies,
201/// and the second was the cache taking a blob it should never have wanted.
202pub const CHEAP_DEPTH: u32 = 2;
203pub const MAX_CACHED_BYTES: u64 = 1 << 20;
204
205/// What it cost to produce an object, as the cache scores it.
206///
207/// `depth + 1` inflates and `depth` delta applications over `inflated` bytes.
208/// Deliberately a coarse integer and not a timing: a duration measured on the
209/// reader's thread carries that thread's scheduling, and two identical objects
210/// would then score differently depending on how busy the box was.
211pub fn rebuild_cost(depth: u32, inflated: u64, external_base: bool) -> u64 {
212    // Bytes inflated across the whole chain, roughly: every link inflates
213    // something of about the object's order, plus one delta application each.
214    let links = depth as u64 + 1;
215    let base = links * inflated.max(1);
216    if external_base { base.saturating_mul(4) } else { base }
217}
218
219/// Is this object worth a slice of the quota?
220pub fn worth_caching(depth: u32, inflated: u64, external_base: bool) -> bool {
221    inflated <= MAX_CACHED_BYTES && (external_base || depth > CHEAP_DEPTH)
222}
223
224/// Environment door for the budget. Named in [`crate::arms::ENV_EXPLODE_BUDGET`]
225/// and read through that crate's one counted door, so
226/// `every_environment_read_in_this_crate_is_named_in_all_env` can see it —
227/// a key spelled locally is a key that roster cannot check.
228pub use crate::arms::ENV_EXPLODE_BUDGET as ENV_BUDGET;
229
230/// **The default budget, and the arithmetic that makes it safe.**
231///
232/// `min(10 % of the filesystem holding the store, 8 GiB)` per repository.
233///
234/// On the shipped appliance — 300 GB `/data`, the shape Rickard named — 10 %
235/// is 30 GB, so the 8 GiB ceiling binds and every repository is capped at
236/// 8 GiB. **Twenty** repositories of any size therefore cost at most 160 GB of
237/// exploded cache against 300 GB, leaving the packs themselves (the truth,
238/// which is never evictable) room; and a repository only reaches its cap if
239/// somebody actually reads all of it. The same appliance with the eager tier
240/// took 141.7 GB for **one** repository.
241///
242/// On a small box the percentage binds instead: a 64 GiB `/data` gives 6.4 GiB,
243/// a 20 GiB one gives 2 GiB. The floor is [`MIN_BUDGET`] so a tiny volume still
244/// gets a cache rather than thrashing at zero.
245pub const BUDGET_FRACTION_PERCENT: u64 = 10;
246pub const BUDGET_CEILING: u64 = 8 << 30;
247pub const MIN_BUDGET: u64 = 64 << 20;
248
249/// The default budget for a store rooted at `dir`, from that filesystem's size.
250pub fn default_budget(dir: &Path) -> u64 {
251    let total = filesystem_bytes(dir).unwrap_or(0);
252    if total == 0 {
253        return BUDGET_CEILING;
254    }
255    (total / 100 * BUDGET_FRACTION_PERCENT)
256        .min(BUDGET_CEILING)
257        .max(MIN_BUDGET)
258}
259
260/// The process-wide line for a store rooted at `dir`: the same tenth of the
261/// filesystem as [`default_budget`], **uncapped** — the cap is per store, the
262/// tenth is per box. Every cache on one filesystem computes the same figure;
263/// caches on different filesystems each hold the sum to their own, which
264/// over-counts across mounts and is the conservative direction. `0` (no
265/// filesystem figure) turns the global check off rather than inventing one.
266pub fn default_global_line(dir: &Path) -> u64 {
267    filesystem_bytes(dir).unwrap_or(0) / 100 * BUDGET_FRACTION_PERCENT
268}
269
270/// Total bytes of the filesystem holding `dir`, via `statvfs`.
271fn filesystem_bytes(dir: &Path) -> Option<u64> {
272    use std::os::unix::ffi::OsStrExt;
273    let mut c = Vec::with_capacity(dir.as_os_str().len() + 1);
274    c.extend_from_slice(dir.as_os_str().as_bytes());
275    c.push(0);
276    let mut s: libc::statvfs = unsafe { std::mem::zeroed() };
277    let rc = unsafe { libc::statvfs(c.as_ptr().cast(), &mut s) };
278    (rc == 0).then(|| s.f_blocks as u64 * s.f_frsize as u64)
279}
280
281/// The budget a store opens with: the environment door if it names one, the
282/// filesystem-derived default otherwise.
283pub fn budget_from_env(dir: &Path) -> Result<u64> {
284    match crate::arms::read_env(crate::arms::ENV_EXPLODE_BUDGET) {
285        Some(v) => parse_budget(&v),
286        None => Ok(default_budget(dir)),
287    }
288}
289
290/// `12G`, `512M`, `1048576`, `0`, `unlimited`. An unparseable value is an
291/// ERROR and never a silent default — a typo in a quota is a bill that is
292/// wrong, and nobody notices until it is.
293pub fn parse_budget(s: &str) -> Result<u64> {
294    let t = s.trim().to_ascii_lowercase();
295    if t == "unlimited" || t == "none" || t == "off" {
296        return Ok(0);
297    }
298    let (digits, mult) = match t.as_bytes().last() {
299        Some(b'k') => (&t[..t.len() - 1], 1u64 << 10),
300        Some(b'm') => (&t[..t.len() - 1], 1u64 << 20),
301        Some(b'g') => (&t[..t.len() - 1], 1u64 << 30),
302        Some(b't') => (&t[..t.len() - 1], 1u64 << 40),
303        _ => (t.as_str(), 1),
304    };
305    let n: u64 = digits
306        .trim()
307        .parse()
308        .map_err(|_| anyhow::anyhow!("unreadable explode budget {s:?}; expected 0, 512M, 8G, …"))?;
309    n.checked_mul(mult)
310        .ok_or_else(|| anyhow::anyhow!("explode budget {s:?} overflows"))
311}
312
313/// What the tier is holding and what it is allowed to hold — the row a
314/// dashboard prints and `Admin.StorageInfo` carries.
315#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
316pub struct CacheUse {
317    /// Bytes in the eager pool (commits and tags under the shipped policy).
318    pub eager_bytes: u64,
319    /// Bytes in the lazy pool, across every live segment.
320    pub lazy_bytes: u64,
321    /// The cap. `0` is unlimited.
322    pub budget: u64,
323    /// Live lazy segments.
324    pub segments: u64,
325    /// Segments unlinked since this store was opened.
326    pub evicted_segments: u64,
327    /// Bytes those segments held. **Applied output**: what actually left the
328    /// filesystem, measured before the unlink, not a projection.
329    pub evicted_bytes: u64,
330    /// Rows those segments held.
331    pub evicted_rows: u64,
332    /// Objects written back by a first read.
333    pub written_back: u64,
334    /// **Reads served by inflating the object directly out of the pack and
335    /// caching NOTHING** — the cheap ones the admission policy declined.
336    /// Applied output: the counter says the policy ran, which a size alone
337    /// could not.
338    pub direct_reads: u64,
339    /// **Write-backs declined because the caller declared the read a
340    /// validation read** ([`suppress_write_back`]) — a `receive-pack`'s
341    /// connectivity walk, not a reader.
342    ///
343    /// Applied output, and the only way to tell the suppression ran from a
344    /// store that simply had nothing to cache: a pool that stays empty proves
345    /// nothing on its own, and this counter moving proves the gate fired.
346    pub suppressed_write_backs: u64,
347}
348
349impl CacheUse {
350    pub fn used(&self) -> u64 {
351        self.eager_bytes + self.lazy_bytes
352    }
353    /// `3.1G/8G` — what the dashboard cell prints.
354    pub fn band(&self) -> String {
355        if self.budget == 0 {
356            format!("{}/unlimited", human(self.used()))
357        } else {
358            format!("{}/{}", human(self.used()), human(self.budget))
359        }
360    }
361    /// Over budget right now — true only while the eager pool alone exceeds it,
362    /// because the lazy pool is evicted back under after every rotation.
363    pub fn over(&self) -> bool {
364        self.budget != 0 && self.used() > self.budget
365    }
366}
367
368/// `3.1G`, `812M`, `40K` — one significant fraction, the same shape the
369/// dashboard's other byte cells use.
370pub fn human(bytes: u64) -> String {
371    const UNITS: [(u64, &str); 4] = [(1 << 40, "T"), (1 << 30, "G"), (1 << 20, "M"), (1 << 10, "K")];
372    for (scale, suffix) in UNITS {
373        if bytes >= scale {
374            let v = bytes as f64 / scale as f64;
375            return if v < 10.0 {
376                format!("{v:.1}{suffix}")
377            } else {
378                format!("{v:.0}{suffix}")
379            };
380        }
381    }
382    format!("{bytes}B")
383}
384
385/// What one live lazy segment is holding, for cost-weighted eviction.
386#[derive(Debug, Clone, Copy, Default)]
387struct SegStat {
388    rows: u64,
389    /// Summed [`rebuild_cost`] of the rows written into it.
390    cost: u64,
391    /// Monotonic tick of the last write into it — the recency half of the rank.
392    touched: u64,
393}
394
395/// **The two pools, one door.** Everything that used to call an
396/// [`ExplodedArchive`] calls this instead; the eager pool *is* an
397/// `ExplodedArchive` and behaves exactly as it did.
398pub struct ExplodedCache {
399    eager: ExplodedArchive,
400    /// Oldest first. `Mutex` and not `RwLock`: it is touched once per rotation
401    /// and once per read miss, never per object.
402    lazy: Mutex<Vec<std::sync::Arc<ExplodedArchive>>>,
403    base: PathBuf,
404    policy: ExplodePolicy,
405    budget: AtomicU64,
406    /// **The process-wide line**, in bytes, that the SUM of every registered
407    /// cache's disk use is held under; `0` = no global line. `budget` above is
408    /// per store — 10 % of the filesystem, capped at 8 GiB — and MEASURED on
409    /// 2026-09-05 that meant N repositories read hard could hold N × 8 GiB:
410    /// ten busy tenants on a 1 TB appliance, 80 GB of cache. This is the same
411    /// 10 % of the filesystem, uncapped, applied once to the box: a cache whose
412    /// own use is above its fair share of it (`line / live caches`) evicts its
413    /// cheapest segment on its tick even while under its own budget, so the
414    /// biggest pools shrink first and the sum converges under the line.
415    global_line: AtomicU64,
416    segment_bytes: AtomicU64,
417    next_seg: AtomicU64,
418    written_back: AtomicU64,
419    direct_reads: AtomicU64,
420    /// See [`CacheUse::suppressed_write_backs`].
421    suppressed_write_backs: AtomicU64,
422    /// Per live segment, parallel to `lazy`: rows, and the summed rebuild cost
423    /// of what is in it. What cost-weighted eviction ranks on.
424    seg_cost: Mutex<Vec<SegStat>>,
425    evicted_segments: AtomicU64,
426    evicted_bytes: AtomicU64,
427    evicted_rows: AtomicU64,
428    /// Bytes buffered in the newest lazy segment since its last flush. The
429    /// flusher reads it; a reader adds to it and never blocks on it.
430    dirty: AtomicU64,
431    /// Where this cache's store lives, for the registry's rows.
432    root: String,
433    /// A maintenance thread is running. **The whole of "nobody waits"**: the
434    /// reader that fills the buffer starts one and walks away, and a second
435    /// reader that arrives while it runs does nothing at all.
436    maintaining: std::sync::atomic::AtomicBool,
437}
438
439impl ExplodedCache {
440    /// Open both pools at `base` (`…/objects.exploded`), adopting whatever
441    /// lazy segments a previous process left beside it.
442    pub fn open(base: &Path, policy: ExplodePolicy, budget: u64) -> Result<Self> {
443        let eager = ExplodedArchive::open_with_policy(base, policy)?;
444        let mut found: Vec<(u64, PathBuf)> = Vec::new();
445        if let Some(dir) = base.parent()
446            && let Ok(rd) = std::fs::read_dir(dir)
447        {
448            let stem = base
449                .file_name()
450                .map(|s| s.to_string_lossy().into_owned())
451                .unwrap_or_default();
452            let prefix = format!("{stem}.c");
453            for e in rd.flatten() {
454                let name = e.file_name().to_string_lossy().into_owned();
455                if let Some(n) = name.strip_prefix(&prefix)
456                    && let Ok(n) = n.parse::<u64>()
457                {
458                    found.push((n, e.path()));
459                }
460            }
461        }
462        found.sort_unstable_by_key(|(n, _)| *n);
463        let next = found.last().map(|(n, _)| n + 1).unwrap_or(1);
464        // A segment adopted from a previous process has no cost history — the
465        // scores are per-process and are not written down. It is scored by its
466        // position instead, oldest first, which is what plain FIFO would do
467        // and is the honest reading of "we do not know".
468        let seg_stats: Vec<SegStat> = (0..found.len())
469            .map(|i| SegStat { rows: 0, cost: 0, touched: i as u64 })
470            .collect();
471        let mut lazy = Vec::with_capacity(found.len());
472        for (_, p) in found {
473            // The lazy pool takes EVERY kind: it is where an object the eager
474            // policy declined comes to rest, so its own policy is `Full`.
475            lazy.push(std::sync::Arc::new(ExplodedArchive::open_with_policy(
476                &p,
477                ExplodePolicy::Full,
478            )?));
479        }
480        Ok(Self {
481            eager,
482            lazy: Mutex::new(lazy),
483            base: base.to_path_buf(),
484            policy,
485            budget: AtomicU64::new(budget),
486            global_line: AtomicU64::new(default_global_line(base)),
487            segment_bytes: AtomicU64::new(segment_for(budget)),
488            next_seg: AtomicU64::new(next),
489            written_back: AtomicU64::new(0),
490            direct_reads: AtomicU64::new(0),
491            suppressed_write_backs: AtomicU64::new(0),
492            seg_cost: Mutex::new(seg_stats),
493            evicted_segments: AtomicU64::new(0),
494            evicted_bytes: AtomicU64::new(0),
495            evicted_rows: AtomicU64::new(0),
496            dirty: AtomicU64::new(0),
497            root: base.parent().unwrap_or(base).display().to_string(),
498            maintaining: std::sync::atomic::AtomicBool::new(false),
499        })
500    }
501
502    /// Register this cache so a dashboard tick can read every open store's
503    /// band without holding a store lock — the same `Weak` registry
504    /// [`crate::progress`] keeps, for the same reason and with the same sweep.
505    pub fn registered(self: std::sync::Arc<Self>) -> std::sync::Arc<Self> {
506        registry()
507            .lock()
508            .unwrap_or_else(|e| e.into_inner())
509            .push(std::sync::Arc::downgrade(&self));
510        self
511    }
512
513    pub fn root(&self) -> &str {
514        &self.root
515    }
516
517    /// The quota, changed live — what the control plane sets when an account's
518    /// plan changes. Takes effect at the next rotation; it never refuses a
519    /// write and never deletes on the caller's thread.
520    pub fn set_budget(&self, bytes: u64) {
521        self.budget.store(bytes, Ordering::Release);
522        self.segment_bytes.store(segment_for(bytes), Ordering::Release);
523    }
524
525    /// The process-wide line this cache holds itself to its fair share of.
526    /// `0` turns the global check off. Tests set it small; production takes
527    /// [`default_global_line`] at open.
528    pub fn set_global_line(&self, bytes: u64) {
529        self.global_line.store(bytes, Ordering::Release);
530    }
531
532    /// True when the registered caches together exceed the global line AND this
533    /// cache holds more than its fair share of it — the condition under which
534    /// this cache evicts for the box rather than for itself. Computed without
535    /// holding this cache's own lock, so the registry sweep can lock the others.
536    fn over_global_share(&self) -> bool {
537        let line = self.global_line.load(Ordering::Acquire);
538        if line == 0 {
539            return false;
540        }
541        let all = use_all();
542        // The share is among caches that HOLD something: an idle repository's
543        // empty pool must not dilute the line for the ones actually using it.
544        let live = all
545            .iter()
546            .filter(|(_, u)| u.eager_bytes + u.lazy_bytes > 0)
547            .count()
548            .max(1) as u64;
549        let sum: u64 = all.iter().map(|(_, u)| u.eager_bytes + u.lazy_bytes).sum();
550        if sum <= line {
551            return false;
552        }
553        let mine = self.use_now();
554        mine.eager_bytes + mine.lazy_bytes > line / live
555    }
556
557    pub fn budget(&self) -> u64 {
558        self.budget.load(Ordering::Acquire)
559    }
560
561    pub fn policy(&self) -> ExplodePolicy {
562        self.policy
563    }
564
565    pub fn path(&self) -> &Path {
566        &self.base
567    }
568
569    /// **The eager write** — the indexer's sink, at push time. Unchanged
570    /// behaviour: the policy decides, and what it declines is counted as
571    /// skipped rather than silently dropped.
572    pub fn explode(&self, oid: &[u8], kind: GitObjectKind, payload: &[u8]) -> Result<()> {
573        self.eager.explode(oid, kind, payload)
574    }
575
576    pub fn explode_at(
577        &self,
578        oid: &[u8],
579        kind: GitObjectKind,
580        mode: Option<u32>,
581        path: Option<&str>,
582        payload: &[u8],
583    ) -> Result<()> {
584        self.eager.explode_at(oid, kind, mode, path, payload)
585    }
586
587    /// **The lazy write-back** — one object a reader has just inflated from the
588    /// pack, kept for the next reader.
589    ///
590    /// Buffers only: it appends to the newest segment's in-memory rows and
591    /// returns. Nothing is written, nothing is fsynced, no eviction runs. The
592    /// reader that called it has its bytes already and is not made to wait for
593    /// anybody — [`Self::maintain`] does the I/O on the store's own thread.
594    /// Two readers racing on one oid is benign: the same bytes are buffered
595    /// twice and the newest row wins, which is what
596    /// [`ExplodedArchive::explode_at`] already promises.
597    pub fn write_back(
598        &self,
599        oid: &[u8],
600        kind: GitObjectKind,
601        payload: &[u8],
602        cost: crate::resolve::ReadCost,
603    ) -> Result<bool> {
604        // **A validation read is not a reader.** A `receive-pack` reads every
605        // commit and tree it was sent, once, to prove the push closes — and
606        // then never reads them again. Caching those is writing a read-cache
607        // for a reader that does not exist. MEASURED on torvalds/linux
608        // (2026-09-03, oden): the lazy pool is EMPTY until the instant indexing
609        // completes and then grows to **6 778 047 872 B** before the push
610        // returns, which is 31 % of the whole store and the largest non-pack
611        // thing in it. See `gunnar/.nornir/storage-levers-2026-09-03.md`.
612        //
613        // The caller declares the window ([`suppress_write_back`]) because the
614        // caller is the only thing that knows what kind of read this is: the
615        // store sees the same `read` either way.
616        if write_back_suppressed() {
617            self.suppressed_write_backs.fetch_add(1, Ordering::Relaxed);
618            return Ok(false);
619        }
620        // **The admission gate.** A shallow, small object is cheaper to inflate
621        // again than to keep: caching it would spend somebody's quota to save
622        // microseconds, and evict something that costs milliseconds.
623        if !worth_caching(cost.depth, cost.inflated, cost.external_base) {
624            self.direct_reads.fetch_add(1, Ordering::Relaxed);
625            return Ok(false);
626        }
627        let seg = {
628            let mut l = self
629                .lazy
630                .lock()
631                .map_err(|_| anyhow::anyhow!("exploded cache poisoned"))?;
632            match l.last() {
633                Some(s) => s.clone(),
634                None => {
635                    let s = self.new_segment()?;
636                    l.push(s.clone());
637                    s
638                }
639            }
640        };
641        seg.explode(oid, kind, payload)?;
642        {
643            let tick = self.written_back.load(Ordering::Relaxed);
644            let mut st = self
645                .seg_cost
646                .lock()
647                .map_err(|_| anyhow::anyhow!("exploded cache poisoned"))?;
648            if st.is_empty() {
649                st.push(SegStat::default());
650            }
651            if let Some(last) = st.last_mut() {
652                last.rows += 1;
653                last.cost += rebuild_cost(cost.depth, cost.inflated, cost.external_base);
654                last.touched = tick;
655            }
656        }
657        self.written_back.fetch_add(1, Ordering::Relaxed);
658        let n = self
659            .dirty
660            .fetch_add(payload.len() as u64, Ordering::AcqRel)
661            + payload.len() as u64;
662        Ok(n >= CACHE_FLUSH_BYTES)
663    }
664
665    /// **Write down what is buffered, rotate if the newest segment is full, and
666    /// evict until the pools fit the budget.** The whole of the tier's I/O, on
667    /// one thread that is nobody's reader.
668    ///
669    /// Returns the bytes reclaimed, so a caller can log applied output rather
670    /// than an intention.
671    pub fn maintain(&self) -> Result<u64> {
672        let newest = {
673            let l = self
674                .lazy
675                .lock()
676                .map_err(|_| anyhow::anyhow!("exploded cache poisoned"))?;
677            l.last().cloned()
678        };
679        if let Some(seg) = newest {
680            seg.flush()?;
681            self.dirty.store(0, Ordering::Release);
682            if seg.disk_bytes() >= self.segment_bytes.load(Ordering::Acquire) {
683                let fresh = self.new_segment()?;
684                let mut l = self
685                    .lazy
686                    .lock()
687                    .map_err(|_| anyhow::anyhow!("exploded cache poisoned"))?;
688                l.push(fresh);
689                if let Ok(mut st) = self.seg_cost.lock() {
690                    st.push(SegStat {
691                        rows: 0,
692                        cost: 0,
693                        touched: self.written_back.load(Ordering::Relaxed),
694                    });
695                }
696            }
697        }
698        self.evict_to_budget()
699    }
700
701    /// Drop segments until the two pools fit, **cheapest-to-rebuild first**.
702    ///
703    /// Not plain FIFO. A segment is ranked by
704    /// `mean rebuild cost × recency`, and the lowest score goes: a segment of
705    /// shallow 20 KiB blobs is worth less than one of depth-40 chains even if
706    /// it was written more recently, because re-reading the first costs
707    /// microseconds an object and the second costs milliseconds. Recency is
708    /// still half the rank, so a cold segment of expensive objects does
709    /// eventually go rather than pinning the pool.
710    ///
711    /// **The eager pool is never touched**: commits are what `graph`, `reach`
712    /// and a tag peel read, and a store that answers those slowly is worse than
713    /// one that reads a blob slowly. If the eager pool alone is over budget the
714    /// lazy pool goes to nothing and the store is reported `over`.
715    fn evict_to_budget(&self) -> Result<u64> {
716        let budget = self.budget.load(Ordering::Acquire);
717        if budget == 0 && self.global_line.load(Ordering::Acquire) == 0 {
718            return Ok(0);
719        }
720        let eager = self.eager.disk_bytes();
721        let mut freed = 0u64;
722        loop {
723            // Re-read per iteration: each eviction moves this cache's share.
724            let over_share = self.over_global_share();
725            let (used, victim, at) = {
726                let l = self
727                    .lazy
728                    .lock()
729                    .map_err(|_| anyhow::anyhow!("exploded cache poisoned"))?;
730                let lazy: u64 = l.iter().map(|s| s.disk_bytes()).sum();
731                // The newest segment is the one being written into; evicting it
732                // would drop rows a reader just paid for and start the same
733                // segment again. There is always at least one live segment.
734                // Within its own budget (`0` = unlimited) AND not over its
735                // share of the box: nothing to do. Otherwise the cheapest
736                // segment goes, for whichever reason applies.
737                let within_own = budget == 0 || eager + lazy <= budget;
738                if (within_own && !over_share) || l.len() < 2 {
739                    (eager + lazy, None, 0)
740                } else {
741                    let at = self.cheapest_segment(l.len() - 1);
742                    (eager + lazy, Some(l[at].clone()), at)
743                }
744            };
745            let Some(victim) = victim else {
746                let _ = used;
747                break;
748            };
749            let bytes = victim.disk_bytes();
750            let rows = victim.rows().unwrap_or(0);
751            let path = victim.path().to_path_buf();
752            {
753                let mut l = self
754                    .lazy
755                    .lock()
756                    .map_err(|_| anyhow::anyhow!("exploded cache poisoned"))?;
757                if at < l.len() {
758                    l.remove(at);
759                }
760                if let Ok(mut st) = self.seg_cost.lock()
761                    && at < st.len()
762                {
763                    st.remove(at);
764                }
765            }
766            drop(victim);
767            // The file goes even if some reader still holds an `Arc` on the
768            // segment: an unlinked file keeps answering the handles that are
769            // open, and the blocks come back when the last one closes. So the
770            // budget is honoured immediately and no read in flight fails.
771            std::fs::remove_file(&path).ok();
772            self.evicted_segments.fetch_add(1, Ordering::Relaxed);
773            self.evicted_bytes.fetch_add(bytes, Ordering::Relaxed);
774            self.evicted_rows.fetch_add(rows, Ordering::Relaxed);
775            freed += bytes;
776        }
777        Ok(freed)
778    }
779
780    /// The index of the segment with the lowest `mean rebuild cost × recency`,
781    /// searched over `[0, exclusive)` so the segment being written into is
782    /// never a candidate. Ties and unknown costs (a segment adopted from a
783    /// previous process, which carries no history) fall back to the oldest,
784    /// which is what plain FIFO would have chosen.
785    fn cheapest_segment(&self, exclusive: usize) -> usize {
786        let Ok(st) = self.seg_cost.lock() else {
787            return 0;
788        };
789        let newest = st.last().map(|s| s.touched).unwrap_or(0).max(1);
790        let mut best = 0usize;
791        let mut best_score = u128::MAX;
792        for i in 0..exclusive.min(st.len()) {
793            let s = st[i];
794            let mean = if s.rows == 0 { 0 } else { s.cost / s.rows };
795            // Recency in [1, 1024]: a segment written at the very start scores
796            // 1, the newest scores 1024. Multiplying rather than adding keeps
797            // the two halves on one scale without a weight nobody can justify.
798            let recency = 1 + (s.touched as u128 * 1023) / newest as u128;
799            let score = (mean as u128 + 1) * recency;
800            if score < best_score {
801                best_score = score;
802                best = i;
803            }
804        }
805        best
806    }
807
808    fn new_segment(&self) -> Result<std::sync::Arc<ExplodedArchive>> {
809        let n = self.next_seg.fetch_add(1, Ordering::AcqRel);
810        let name = format!(
811            "{}.c{n}",
812            self.base.file_name().unwrap_or_default().to_string_lossy()
813        );
814        let path = self.base.with_file_name(name);
815        Ok(std::sync::Arc::new(ExplodedArchive::open_with_policy(
816            &path,
817            ExplodePolicy::Full,
818        )?))
819    }
820
821    /// The object's kind and bytes from either pool, or `None` — *fall back and
822    /// re-derive*, never *wrong*.
823    ///
824    /// Eager first: it is the smaller table, its index is the one already warm,
825    /// and under the shipped policy it holds exactly the objects a graph walk
826    /// asks for. Then the lazy segments **newest first**, so a re-entered
827    /// object is found before the stale copy an older segment may still hold.
828    pub fn content(&self, oid: &[u8]) -> Result<Option<(GitObjectKind, Vec<u8>)>> {
829        if let Some(hit) = self.eager.content(oid)? {
830            return Ok(Some(hit));
831        }
832        let segs = self.segments()?;
833        for s in segs.iter().rev() {
834            if let Some(hit) = s.content(oid)? {
835                return Ok(Some(hit));
836            }
837        }
838        Ok(None)
839    }
840
841    pub fn has(&self, oid: &[u8]) -> Result<bool> {
842        if self.eager.has(oid)? {
843            return Ok(true);
844        }
845        for s in self.segments()?.iter().rev() {
846            if s.has(oid)? {
847                return Ok(true);
848            }
849        }
850        Ok(false)
851    }
852
853    pub fn name(&self, oid: &[u8]) -> Result<Option<(Option<u32>, Option<String>)>> {
854        if let Some(n) = self.eager.name(oid)? {
855            return Ok(Some(n));
856        }
857        for s in self.segments()?.iter().rev() {
858            if let Some(n) = s.name(oid)? {
859                return Ok(Some(n));
860            }
861        }
862        Ok(None)
863    }
864
865    /// Every oid of one kind, across both pools, newest spelling winning.
866    ///
867    /// The graph fold's input. Under the shipped policy every commit is in the
868    /// eager pool, so this is one table's scan and the lazy segments add
869    /// nothing — but it unions rather than assuming that, because a store
870    /// opened under a different policy must still fold a whole graph.
871    pub fn of_kind(&self, kind: GitObjectKind) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
872        let mut out = self.eager.of_kind(kind)?;
873        let segs = self.segments()?;
874        if segs.is_empty() {
875            return Ok(out);
876        }
877        let mut seen: std::collections::HashSet<Vec<u8>> =
878            out.iter().map(|(o, _)| o.clone()).collect();
879        for s in segs.iter().rev() {
880            for (oid, payload) in s.of_kind(kind)? {
881                if seen.insert(oid.clone()) {
882                    out.push((oid, payload));
883                }
884            }
885        }
886        Ok(out)
887    }
888
889    /// Retire every oid `live` rejects — in **both** pools.
890    ///
891    /// Both, and that is not defensive: a tombstone written only into the eager
892    /// pool would leave the lazy pool's row live, `content` would fall through
893    /// to it, and a `gc`'d object would come back by the second door. That is
894    /// the same defect
895    /// `a_wholly_dead_pack_does_not_come_back_when_the_store_is_reopened` found
896    /// the first time, one pool along.
897    pub fn retain(&self, live: &dyn Fn(&[u8]) -> bool) -> Result<u64> {
898        let mut n = self.eager.retain(live)?;
899        for s in self.segments()? {
900            n += s.retain(live)?;
901        }
902        Ok(n)
903    }
904
905    /// **`repo gc` reclaims the cache.** Every lazy segment is unlinked; the
906    /// eager pool keeps its rows, because they are the graph. Returns the bytes
907    /// that left the filesystem.
908    pub fn drop_cache(&self) -> Result<u64> {
909        let victims = {
910            let mut l = self
911                .lazy
912                .lock()
913                .map_err(|_| anyhow::anyhow!("exploded cache poisoned"))?;
914            if let Ok(mut st) = self.seg_cost.lock() {
915                st.clear();
916            }
917            std::mem::take(&mut *l)
918        };
919        let mut freed = 0;
920        for s in victims {
921            let bytes = s.disk_bytes();
922            let rows = s.rows().unwrap_or(0);
923            let path = s.path().to_path_buf();
924            drop(s);
925            std::fs::remove_file(&path).ok();
926            self.evicted_segments.fetch_add(1, Ordering::Relaxed);
927            self.evicted_bytes.fetch_add(bytes, Ordering::Relaxed);
928            self.evicted_rows.fetch_add(rows, Ordering::Relaxed);
929            freed += bytes;
930        }
931        self.dirty.store(0, Ordering::Release);
932        Ok(freed)
933    }
934
935    pub fn flush(&self) -> Result<()> {
936        self.eager.flush()?;
937        for s in self.segments()? {
938            s.flush()?;
939        }
940        self.dirty.store(0, Ordering::Release);
941        Ok(())
942    }
943
944    /// What the memory watchdog reaches for: every derived, rebuildable
945    /// structure in every pool.
946    pub fn drop_caches(&self) {
947        self.eager.drop_caches();
948        if let Ok(l) = self.lazy.lock() {
949            for s in l.iter() {
950                s.drop_caches();
951            }
952        }
953    }
954
955    pub fn rows(&self) -> Result<u64> {
956        let mut n = self.eager.rows()?;
957        for s in self.segments()? {
958            n += s.rows()?;
959        }
960        Ok(n)
961    }
962
963    /// Rows in the EAGER pool only — what `adopt_journal` compares against the
964    /// index, because the lazy pool's size is a function of what has been read
965    /// and says nothing about whether a pack was absorbed.
966    pub fn eager_rows(&self) -> Result<u64> {
967        self.eager.rows()
968    }
969
970    pub fn disk_bytes(&self) -> u64 {
971        self.use_now().used()
972    }
973
974    pub fn use_now(&self) -> CacheUse {
975        let (lazy_bytes, segments) = match self.lazy.lock() {
976            Ok(l) => (l.iter().map(|s| s.disk_bytes()).sum(), l.len() as u64),
977            Err(_) => (0, 0),
978        };
979        CacheUse {
980            eager_bytes: self.eager.disk_bytes(),
981            lazy_bytes,
982            budget: self.budget.load(Ordering::Acquire),
983            segments,
984            evicted_segments: self.evicted_segments.load(Ordering::Relaxed),
985            evicted_bytes: self.evicted_bytes.load(Ordering::Relaxed),
986            evicted_rows: self.evicted_rows.load(Ordering::Relaxed),
987            written_back: self.written_back.load(Ordering::Relaxed),
988            direct_reads: self.direct_reads.load(Ordering::Relaxed),
989            suppressed_write_backs: self.suppressed_write_backs.load(Ordering::Relaxed),
990        }
991    }
992
993    pub fn note_rederived(&self) {
994        self.eager.note_rederived();
995    }
996
997    pub fn pread_served(&self) -> u64 {
998        self.eager.pread_served()
999            + self
1000                .segments()
1001                .map(|s| s.iter().map(|x| x.pread_served()).sum::<u64>())
1002                .unwrap_or(0)
1003    }
1004
1005    pub fn skipped(&self) -> u64 {
1006        self.eager.skipped()
1007    }
1008
1009    /// The engine-wide counters, summed over both pools, so no caller can tell
1010    /// the two apart by its instruments.
1011    pub fn engine_stats(&self) -> ExplodedStats {
1012        let mut s = self.eager.engine_stats();
1013        if let Ok(segs) = self.segments() {
1014            for x in segs {
1015                let e = x.engine_stats();
1016                s.rows += e.rows;
1017                s.written += e.written;
1018                s.served += e.served;
1019                s.absent += e.absent;
1020            }
1021        }
1022        s
1023    }
1024
1025    /// **Start the write-back thread if one is not already running — and
1026    /// return to the reader immediately either way.**
1027    ///
1028    /// Rickard's law, from the design note: *nobody waits*. The reader already
1029    /// has its bytes; the append, the fsync, the rotation and the eviction all
1030    /// happen here, on a thread that is nobody's request. A thread per 4 MiB of
1031    /// write-back rather than a parked thread per store, because a box holding
1032    /// 1 200 open repositories (lane V) cannot afford 1 200 idle threads and
1033    /// can easily afford one spawn per few thousand objects read.
1034    ///
1035    /// The flag is the whole of the mutual exclusion: a second reader finding
1036    /// it set does nothing, and the running thread loops until the buffer is
1037    /// empty before clearing it, so no work is dropped between the two.
1038    pub fn kick(self: &std::sync::Arc<Self>) {
1039        if self
1040            .maintaining
1041            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
1042            .is_err()
1043        {
1044            return;
1045        }
1046        let me = self.clone();
1047        let spawned = std::thread::Builder::new()
1048            .name("explode-writeback".into())
1049            .stack_size(256 << 10)
1050            .spawn(move || {
1051                loop {
1052                    if let Err(e) = me.maintain() {
1053                        tracing::warn!(target: "znippy.git", error = %e, "explode cache maintenance");
1054                        break;
1055                    }
1056                    if me.dirty.load(Ordering::Acquire) < CACHE_FLUSH_BYTES {
1057                        break;
1058                    }
1059                }
1060                me.maintaining.store(false, Ordering::Release);
1061            });
1062        if spawned.is_err() {
1063            // No thread to be had. Clearing the flag is what makes the next
1064            // reader try again rather than the cache silently stopping.
1065            self.maintaining.store(false, Ordering::Release);
1066        }
1067    }
1068
1069    fn segments(&self) -> Result<Vec<std::sync::Arc<ExplodedArchive>>> {
1070        Ok(self
1071            .lazy
1072            .lock()
1073            .map_err(|_| anyhow::anyhow!("exploded cache poisoned"))?
1074            .clone())
1075    }
1076}
1077
1078impl crate::exploded::PayloadSink for ExplodedCache {
1079    fn wants(&self, kind: GitObjectKind) -> bool {
1080        crate::exploded::PayloadSink::wants(&self.eager, kind)
1081    }
1082    fn explode(&self, oid: &[u8], kind: GitObjectKind, payload: &[u8]) -> Result<()> {
1083        ExplodedCache::explode(self, oid, kind, payload)
1084    }
1085    fn flush(&self) -> Result<()> {
1086        self.eager.flush().map(|_| ())
1087    }
1088}
1089
1090fn registry() -> &'static Mutex<Vec<std::sync::Weak<ExplodedCache>>> {
1091    static R: std::sync::OnceLock<Mutex<Vec<std::sync::Weak<ExplodedCache>>>> =
1092        std::sync::OnceLock::new();
1093    R.get_or_init(|| Mutex::new(Vec::new()))
1094}
1095
1096/// **Every open store's explode band**, as `(store root, use)`. What the
1097/// dashboard tick and `Admin.StorageInfo` read; a `metadata` call per pool and
1098/// no store lock. Dead entries are swept on the way past.
1099pub fn use_all() -> Vec<(String, CacheUse)> {
1100    let mut r = registry().lock().unwrap_or_else(|e| e.into_inner());
1101    r.retain(|w| w.strong_count() > 0);
1102    r.iter()
1103        .filter_map(|w| w.upgrade())
1104        .map(|c| (c.root.clone(), c.use_now()))
1105        .collect()
1106}
1107
1108/// Set the budget of every open store under `root` (a prefix match, so an
1109/// account's whole tree is one call). Returns how many were changed — applied
1110/// output, so a control plane that set nothing can say so.
1111pub fn set_budget_under(root: &str, bytes: u64) -> usize {
1112    let mut n = 0;
1113    let mut r = registry().lock().unwrap_or_else(|e| e.into_inner());
1114    r.retain(|w| w.strong_count() > 0);
1115    for c in r.iter().filter_map(|w| w.upgrade()) {
1116        if c.root.starts_with(root) {
1117            c.set_budget(bytes);
1118            n += 1;
1119        }
1120    }
1121    n
1122}
1123
1124/// One segment is 1/16 of the budget, clamped. An unlimited budget still
1125/// rotates, so a pool that is later given a budget can be evicted without a
1126/// rewrite.
1127fn segment_for(budget: u64) -> u64 {
1128    if budget == 0 {
1129        return MAX_SEGMENT.min(1 << 28);
1130    }
1131    // The floor yields to the budget rather than overriding it: a 16 MiB
1132    // minimum against a 1 MiB quota would mean the pool never rotates and
1133    // therefore never evicts — a cap that silently is not one, which is the
1134    // exact shape of bug LAW 2 is about. So the floor is `min(MIN_SEGMENT,
1135    // budget/4)`: a real budget gets 16 MiB segments, a tiny one gets tiny ones.
1136    let floor = MIN_SEGMENT.min(budget / 4).max(64 << 10);
1137    (budget / SEGMENTS_PER_BUDGET).clamp(floor, MAX_SEGMENT)
1138}
1139
1140#[cfg(test)]
1141mod tests {
1142    use super::*;
1143
1144    fn tmp(name: &str) -> PathBuf {
1145        let d = std::env::temp_dir().join(format!("explode-cache-{}-{name}", std::process::id()));
1146        let _ = std::fs::remove_dir_all(&d);
1147        std::fs::create_dir_all(&d).unwrap();
1148        d.join("objects.exploded")
1149    }
1150
1151    /// A cost the admission gate admits: deep enough and big enough that the
1152    /// cache is the cheaper place for it. Tests that are about eviction must
1153    /// not accidentally be about admission.
1154    /// An INCOMPRESSIBLE payload of `len` bytes (a tiny LCG seeded by `seed`).
1155    /// The eviction tests reason about bytes on disk against a budget, and since
1156    /// lever 3 (2026-09-04) a row is stored zlib-compressed when that is smaller
1157    /// — a `vec![3u8; 64 << 10]` lands as ~80 bytes and the pool never reaches
1158    /// the budget those tests were sized for ("nothing was evicted" ×3). Noise
1159    /// does not compress, so the budget arithmetic means what it did.
1160    fn noise(len: usize, seed: u8) -> Vec<u8> {
1161        let mut x: u32 = 0x9E37_79B9 ^ (seed as u32).wrapping_mul(0x0101_0101);
1162        (0..len)
1163            .map(|_| {
1164                x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1165                (x >> 24) as u8
1166            })
1167            .collect()
1168    }
1169
1170    fn dear(payload: &[u8]) -> crate::resolve::ReadCost {
1171        crate::resolve::ReadCost {
1172            depth: CHEAP_DEPTH + 8,
1173            inflated: payload.len() as u64,
1174            external_base: false,
1175        }
1176    }
1177
1178    /// Assert at compile time that the eviction fixtures below stay under the
1179    /// size cap — a fixture that grew past it would be silently DECLINED and
1180    /// the test would then be asserting nothing.
1181    const _: () = assert!((64 << 10) < MAX_CACHED_BYTES as usize);
1182
1183    fn oid(n: u32) -> Vec<u8> {
1184        let mut o = vec![0u8; 20];
1185        o[..4].copy_from_slice(&n.to_be_bytes());
1186        o
1187    }
1188
1189    /// ★ **THE ANSWER TO "does it take the disk anyway?"**
1190    ///
1191    /// Every object of a repository is read once, each one written back — the
1192    /// full-history browse that would otherwise reproduce the eager tier. The
1193    /// tier must **plateau at its budget**, not climb.
1194    ///
1195    /// Seen RED by returning `Ok(0)` from `evict_to_budget`: the pool climbs to
1196    /// 9.4 MiB against a 2 MiB budget and the assertion names the number.
1197    #[test]
1198    fn the_tier_plateaus_at_its_budget_under_a_full_scan() {
1199        let base = tmp("plateau");
1200        let budget = 2 << 20;
1201        let c = ExplodedCache::open(&base, ExplodePolicy::Commits, budget).unwrap();
1202        let payload = vec![7u8; 8 << 10];
1203        let mut peak = 0u64;
1204        for i in 0..2000u32 {
1205            c.write_back(&oid(i), GitObjectKind::Blob, &payload, dear(&payload)).unwrap();
1206            // The store's own thread, doing what it does between reads.
1207            c.maintain().unwrap();
1208            peak = peak.max(c.use_now().used());
1209        }
1210        let end = c.use_now();
1211        let written = 2000u64 * payload.len() as u64;
1212        assert!(
1213            peak <= budget as u64 + segment_for(budget) + (1 << 20),
1214            "the tier climbed to {peak} B against a {budget} B budget after {written} B of \
1215             write-backs — it is a tier, not a cache"
1216        );
1217        assert!(
1218            end.evicted_bytes > 0 && end.evicted_segments > 0,
1219            "nothing was evicted, so the plateau is an accident of size: {end:?}"
1220        );
1221    }
1222
1223    /// An account at its budget still serves **every** read correctly — only
1224    /// slower. Eviction is never an error a client sees.
1225    #[test]
1226    fn an_evicted_object_is_absent_and_never_wrong() {
1227        let base = tmp("absent");
1228        let c = ExplodedCache::open(&base, ExplodePolicy::Commits, 1 << 20).unwrap();
1229        let payload = noise(64 << 10, 3);
1230        for i in 0..200u32 {
1231            c.write_back(&oid(i), GitObjectKind::Blob, &payload, dear(&payload)).unwrap();
1232            c.maintain().unwrap();
1233        }
1234        // Whatever survived comes back byte-identical; whatever did not comes
1235        // back `None`, which is the caller's cue to re-inflate the chain.
1236        let mut hits = 0;
1237        for i in 0..200u32 {
1238            match c.content(&oid(i)).unwrap() {
1239                Some((k, b)) => {
1240                    assert_eq!(k, GitObjectKind::Blob);
1241                    assert_eq!(b, payload, "an evicting cache returned the wrong bytes");
1242                    hits += 1;
1243                }
1244                None => {}
1245            }
1246        }
1247        assert!(hits > 0, "the cache evicted everything, including the newest segment");
1248        assert!(hits < 200, "nothing was evicted, so this proves nothing");
1249    }
1250
1251    /// Commits are the last thing standing: the eager pool is never unlinked,
1252    /// whatever the lazy pool does.
1253    /// **The box has one line, and the biggest pool pays for it.** Two caches,
1254    /// each far under its own per-store budget, share a small global line: the
1255    /// one holding most of the box's cache evicts on its tick; the one under
1256    /// its fair share does not, however far over the line the box is.
1257    ///
1258    /// Robust to whatever else is registered in this process: the fairness
1259    /// claim is made with B holding ONE 8 KiB row (over its share only if more
1260    /// than ~128 caches held bytes at once), and the convergence claim is made
1261    /// on A's own bytes, not on a sum that other tests' pools can move.
1262    ///
1263    /// Seen RED by making `over_global_share` return `false` always: A evicted
1264    /// nothing ("the big pool must evict for the box") and stayed at 3 MiB
1265    /// over a 1 MiB line. Restored.
1266    #[test]
1267    fn the_global_line_is_paid_by_the_cache_over_its_share() {
1268        let base_a = tmp("global-a");
1269        let base_b = tmp("global-b");
1270        // 4 MiB per store → 1 MiB segments (the budget/4 floor), so 3 MiB rotates into four and
1271        // the per-store budget itself never evicts anything here.
1272        let a = std::sync::Arc::new(ExplodedCache::open(&base_a, ExplodePolicy::Commits, 4 << 20).unwrap())
1273            .registered();
1274        let b = std::sync::Arc::new(ExplodedCache::open(&base_b, ExplodePolicy::Commits, 4 << 20).unwrap())
1275            .registered();
1276        // Fill with the global check OFF, so the shape under test is set up
1277        // before it is asked about.
1278        a.set_global_line(0);
1279        b.set_global_line(0);
1280        let big = noise(64 << 10, 5);
1281        for i in 0..48u32 {
1282            a.write_back(&oid(i), GitObjectKind::Blob, &big, dear(&big)).unwrap();
1283            a.maintain().unwrap();
1284        }
1285        let small = noise(8 << 10, 6);
1286        b.write_back(&oid(100), GitObjectKind::Blob, &small, dear(&small)).unwrap();
1287        b.maintain().unwrap();
1288        let a0 = a.use_now();
1289        let b0 = b.use_now();
1290        let line = 1u64 << 20;
1291        assert!(a0.lazy_bytes > line, "precondition: A alone is over the line, has {}", a0.lazy_bytes);
1292        assert!(a0.segments >= 3, "precondition: A rotated into segments, has {}", a0.segments);
1293        assert_eq!(a0.evicted_segments + b0.evicted_segments, 0, "precondition: nothing evicted yet");
1294
1295        a.set_global_line(line);
1296        b.set_global_line(line);
1297
1298        // B ticks first: under its share, it must not pay for A.
1299        b.maintain().unwrap();
1300        assert_eq!(b.use_now().evicted_segments, 0, "a cache under its fair share must not evict for the box");
1301
1302        // A ticks: over its share, it evicts for the box until it is under the
1303        // line on its own (it cannot stop above it: then the box is over and
1304        // it is over any share of it).
1305        a.maintain().unwrap();
1306        let a1 = a.use_now();
1307        assert!(a1.evicted_segments > 0, "the big pool must evict for the box");
1308        assert!(
1309            a1.lazy_bytes + a1.eager_bytes <= line,
1310            "A must have shrunk under the line on its own: {} > {line}",
1311            a1.lazy_bytes + a1.eager_bytes
1312        );
1313        assert!(a1.lazy_bytes < 4 << 20, "its own budget was never the reason");
1314        assert_eq!(b.use_now().evicted_segments, 0, "B still untouched");
1315    }
1316    #[test]
1317    fn eviction_never_takes_a_commit() {
1318        let base = tmp("commits");
1319        let c = ExplodedCache::open(&base, ExplodePolicy::Commits, 1 << 20).unwrap();
1320        for i in 0..50u32 {
1321            c.explode(&oid(1_000_000 + i), GitObjectKind::Commit, b"tree x\n")
1322                .unwrap();
1323        }
1324        c.flush().unwrap();
1325        let blob = noise(64 << 10, 1);
1326        for i in 0..200u32 {
1327            c.write_back(&oid(i), GitObjectKind::Blob, &blob, dear(&blob)).unwrap();
1328            c.maintain().unwrap();
1329        }
1330        assert!(c.use_now().evicted_segments > 0, "nothing was evicted");
1331        for i in 0..50u32 {
1332            assert!(
1333                c.content(&oid(1_000_000 + i)).unwrap().is_some(),
1334                "a commit was evicted — graph and reach are now blind"
1335            );
1336        }
1337    }
1338
1339    /// `repo gc` reclaims the cache and keeps the graph.
1340    #[test]
1341    fn dropping_the_cache_reclaims_the_lazy_pool_only() {
1342        let base = tmp("gc");
1343        let c = ExplodedCache::open(&base, ExplodePolicy::Commits, 0).unwrap();
1344        c.explode(&oid(9), GitObjectKind::Commit, b"tree y\n").unwrap();
1345        let blob = vec![2u8; 32 << 10];
1346        for i in 0..100u32 {
1347            c.write_back(&oid(i), GitObjectKind::Blob, &blob, dear(&blob)).unwrap();
1348        }
1349        c.maintain().unwrap();
1350        let before = c.use_now();
1351        assert!(before.lazy_bytes > 0);
1352        let freed = c.drop_cache().unwrap();
1353        assert!(freed > 0, "gc reclaimed nothing");
1354        let after = c.use_now();
1355        assert_eq!(after.lazy_bytes, 0, "the lazy pool survived gc");
1356        assert_eq!(after.eager_bytes, before.eager_bytes, "gc took the graph too");
1357        assert!(c.content(&oid(9)).unwrap().is_some());
1358    }
1359
1360    /// The segments a previous process wrote are adopted, so a restart does not
1361    /// lose the cache and does not lose track of its size either.
1362    #[test]
1363    fn a_reopen_adopts_the_segments_it_left() {
1364        let base = tmp("reopen");
1365        let blob = vec![5u8; 32 << 10];
1366        let bytes = {
1367            let c = ExplodedCache::open(&base, ExplodePolicy::Commits, 0).unwrap();
1368            for i in 0..40u32 {
1369                c.write_back(&oid(i), GitObjectKind::Blob, &blob, dear(&blob)).unwrap();
1370            }
1371            c.maintain().unwrap();
1372            c.use_now().lazy_bytes
1373        };
1374        assert!(bytes > 0);
1375        let again = ExplodedCache::open(&base, ExplodePolicy::Commits, 0).unwrap();
1376        assert_eq!(again.use_now().lazy_bytes, bytes, "the segments were not adopted");
1377        assert_eq!(
1378            again.content(&oid(7)).unwrap().map(|(_, b)| b),
1379            Some(blob),
1380            "an adopted segment does not answer"
1381        );
1382    }
1383
1384    /// ★ **DO NOT EXPLODE UNIFORMLY: a cheap object is never cached.**
1385    ///
1386    /// Rickard, 2026-08-30: the index points at the object's own zlib stream at
1387    /// its own offset, so a whole object is one direct inflate. Caching that
1388    /// spends quota to save microseconds — and evicts something that costs
1389    /// milliseconds. So the gate is rebuild cost, not "was read".
1390    ///
1391    /// Seen RED by making `write_back` admit everything: 400 shallow 1 KiB
1392    /// objects land in the pool, `direct_reads` stays 0, and the assertion
1393    /// names both.
1394    #[test]
1395    fn a_shallow_small_object_is_read_directly_and_never_cached() {
1396        let base = tmp("cheap");
1397        let c = ExplodedCache::open(&base, ExplodePolicy::Commits, 0).unwrap();
1398        let small = vec![1u8; 1 << 10];
1399        let big = vec![2u8; 64 << 10];
1400
1401        // Cheap: shallow and small. Not worth a byte of anybody's quota.
1402        for i in 0..400u32 {
1403            let took = c
1404                .write_back(
1405                    &oid(i),
1406                    GitObjectKind::Blob,
1407                    &small,
1408                    crate::resolve::ReadCost {
1409                        depth: CHEAP_DEPTH,
1410                        inflated: small.len() as u64,
1411                        external_base: false,
1412                    },
1413                )
1414                .unwrap();
1415            assert!(!took, "a cheap object asked for a flush");
1416        }
1417        c.maintain().unwrap();
1418        let after_cheap = c.use_now();
1419        assert_eq!(
1420            after_cheap.lazy_bytes, 0,
1421            "400 shallow 1 KiB objects put {} B in the cache; a direct read is \
1422             microseconds and this is quota spent to save them",
1423            after_cheap.lazy_bytes
1424        );
1425        assert_eq!(
1426            after_cheap.direct_reads, 400,
1427            "the policy declined {} of 400 cheap objects — it is not running",
1428            after_cheap.direct_reads
1429        );
1430        assert_eq!(after_cheap.written_back, 0);
1431
1432        // Expensive by DEPTH, and by an external base. Each on its own admits.
1433        c.write_back(
1434            &oid(1000),
1435            GitObjectKind::Blob,
1436            &small,
1437            crate::resolve::ReadCost { depth: CHEAP_DEPTH + 1, inflated: small.len() as u64, external_base: false },
1438        )
1439        .unwrap();
1440        c.write_back(
1441            &oid(1002),
1442            GitObjectKind::Blob,
1443            &small,
1444            crate::resolve::ReadCost { depth: 0, inflated: small.len() as u64, external_base: true },
1445        )
1446        .unwrap();
1447        // **Big is NOT a reason to cache.** A 64 KiB — or a 3 MiB — whole blob
1448        // is one linear inflate and a bad tenant of a shared budget, and it is
1449        // declined however deep it is. This is lane AA's second copy.
1450        c.write_back(
1451            &oid(1001),
1452            GitObjectKind::Blob,
1453            &big,
1454            crate::resolve::ReadCost { depth: 40, inflated: (MAX_CACHED_BYTES + 1) as u64, external_base: true },
1455        )
1456        .unwrap();
1457        c.maintain().unwrap();
1458        let end = c.use_now();
1459        assert_eq!(end.written_back, 2, "an expensive object was declined");
1460        assert_eq!(
1461            end.direct_reads, 401,
1462            "an object over the size cap was cached instead of read directly"
1463        );
1464        for n in [1000u32, 1002] {
1465            assert!(
1466                c.content(&oid(n)).unwrap().is_some(),
1467                "the expensive object {n} is not in the cache"
1468            );
1469        }
1470        assert!(
1471            c.content(&oid(1001)).unwrap().is_none(),
1472            "an object over the size cap is in the cache"
1473        );
1474        assert!(
1475            c.content(&oid(7)).unwrap().is_none(),
1476            "a declined object is in the cache after all"
1477        );
1478    }
1479
1480    /// ★ **Eviction ranks by rebuild cost, not by age alone.**
1481    ///
1482    /// Two segments, the older one full of expensive objects and the newer one
1483    /// full of barely-admitted ones. Plain FIFO takes the expensive segment
1484    /// because it is older; ranking by `mean rebuild cost × recency` takes the
1485    /// cheap one, which is the whole point — evict what is cheap to recompute.
1486    ///
1487    /// Seen RED by restoring `Some(l[0].clone())`: the depth-40 objects go and
1488    /// the barely-admitted ones stay.
1489    #[test]
1490    fn eviction_takes_the_cheap_segment_before_the_old_expensive_one() {
1491        let base = tmp("costrank");
1492        // Small budget, small segments: three segments fit and the fourth
1493        // forces one out.
1494        let c = ExplodedCache::open(&base, ExplodePolicy::Commits, 1 << 20).unwrap();
1495        let payload = noise(32 << 10, 9);
1496        let dear = crate::resolve::ReadCost { depth: 40, inflated: payload.len() as u64, external_base: false };
1497        // Barely admitted: one link past the cheap depth.
1498        let cheapish = crate::resolve::ReadCost {
1499            depth: CHEAP_DEPTH + 1,
1500            inflated: payload.len() as u64,
1501            external_base: false,
1502        };
1503
1504        // Segment 0: expensive. Rotate it out by filling past the segment size.
1505        for i in 0..16u32 {
1506            c.write_back(&oid(i), GitObjectKind::Blob, &payload, dear).unwrap();
1507        }
1508        c.maintain().unwrap();
1509        // Segment 1+: cheapish.
1510        for i in 100..160u32 {
1511            c.write_back(&oid(i), GitObjectKind::Blob, &payload, cheapish).unwrap();
1512            c.maintain().unwrap();
1513        }
1514        let end = c.use_now();
1515        assert!(end.evicted_segments > 0, "nothing was evicted; this proves nothing");
1516        // The expensive objects are the ones still there.
1517        let expensive_left = (0..16u32).filter(|i| c.content(&oid(*i)).unwrap().is_some()).count();
1518        let cheap_left = (100..160u32).filter(|i| c.content(&oid(*i)).unwrap().is_some()).count();
1519        assert!(
1520            expensive_left > 0,
1521            "every depth-40 object was evicted while {cheap_left} barely-admitted ones \
1522             survived — eviction is ranking by age alone: {end:?}"
1523        );
1524    }
1525
1526    /// A budget is parsed, and a typo is refused rather than silently taking a
1527    /// default nobody is billed for.
1528    #[test]
1529    fn a_budget_is_read_and_a_typo_is_refused() {
1530        assert_eq!(parse_budget("8G").unwrap(), 8 << 30);
1531        assert_eq!(parse_budget(" 512m ").unwrap(), 512 << 20);
1532        assert_eq!(parse_budget("1048576").unwrap(), 1 << 20);
1533        assert_eq!(parse_budget("unlimited").unwrap(), 0);
1534        assert!(parse_budget("8 gigs").is_err());
1535        assert!(parse_budget("").is_err());
1536    }
1537
1538    /// The default is derived from the filesystem, and the appliance arithmetic
1539    /// in the module docs is the one the code does.
1540    #[test]
1541    fn the_default_budget_is_the_smaller_of_a_tenth_and_the_ceiling() {
1542        let d = default_budget(&std::env::temp_dir());
1543        assert!(d >= MIN_BUDGET && d <= BUDGET_CEILING, "{d}");
1544    }
1545
1546    /// **A validation read caches nothing, and the same reads without the guard
1547    /// fill the pool** — both halves, because either alone proves nothing.
1548    ///
1549    /// The RED half is the first loop: these are objects the admission policy
1550    /// WANTS (deep chains), so a pool that stays empty under the guard cannot be
1551    /// explained by `worth_caching` declining them. The counter is asserted too,
1552    /// because "the pool is empty" is also what a cache that was handed nothing
1553    /// looks like.
1554    #[test]
1555    fn a_suppressed_thread_caches_nothing_and_an_unsuppressed_one_fills_the_pool() {
1556        let payload = vec![7u8; 64 << 10];
1557        let costly = crate::resolve::ReadCost {
1558            depth: CHEAP_DEPTH + 8,
1559            inflated: payload.len() as u64,
1560            external_base: false,
1561        };
1562
1563        // ── RED: no guard. The same objects, admitted. ──────────────────────
1564        let hot = ExplodedCache::open(&tmp("nosuppress"), ExplodePolicy::Commits, 0).unwrap();
1565        for i in 0..200u32 {
1566            hot.write_back(&oid(i), GitObjectKind::Tree, &payload, costly).unwrap();
1567        }
1568        hot.maintain().unwrap();
1569        let hot_use = hot.use_now();
1570        assert!(
1571            hot_use.lazy_bytes > 0,
1572            "without the guard these objects must be cached, or the GREEN half \
1573             below is proving that `worth_caching` declined them and nothing else"
1574        );
1575        assert_eq!(hot_use.written_back, 200);
1576        assert_eq!(hot_use.suppressed_write_backs, 0);
1577
1578        // ── GREEN: the identical loop inside the guard. ─────────────────────
1579        let cold = ExplodedCache::open(&tmp("suppress"), ExplodePolicy::Commits, 0).unwrap();
1580        {
1581            let _guard = suppress_write_back();
1582            assert!(write_back_suppressed());
1583            for i in 0..200u32 {
1584                let took = cold.write_back(&oid(i), GitObjectKind::Tree, &payload, costly).unwrap();
1585                assert!(!took, "a validation read asked for a flush");
1586            }
1587        }
1588        cold.maintain().unwrap();
1589        let cold_use = cold.use_now();
1590        assert_eq!(
1591            cold_use.lazy_bytes, 0,
1592            "a receive-pack's connectivity walk put {} B in the cache",
1593            cold_use.lazy_bytes
1594        );
1595        assert_eq!(cold_use.written_back, 0);
1596        assert_eq!(
1597            cold_use.suppressed_write_backs, 200,
1598            "the gate must be what declined them — {} suppressed, not 200",
1599            cold_use.suppressed_write_backs
1600        );
1601        // The policy was never consulted: a suppressed read is declined BEFORE
1602        // the admission gate, so it is not a `direct_read` either.
1603        assert_eq!(cold_use.direct_reads, 0);
1604    }
1605
1606    /// The guard is released on drop, including out of a panic — a thread that
1607    /// panicked mid-walk must not stop caching for the rest of its life.
1608    #[test]
1609    fn the_guard_is_released_on_drop_and_on_unwind_and_it_nests() {
1610        assert!(!write_back_suppressed(), "a fresh thread starts unsuppressed");
1611        {
1612            let _a = suppress_write_back();
1613            {
1614                let _b = suppress_write_back();
1615                assert!(write_back_suppressed());
1616            }
1617            assert!(
1618                write_back_suppressed(),
1619                "the inner guard ending reopened the cache while the outer scope \
1620                 is still validating"
1621            );
1622        }
1623        assert!(!write_back_suppressed());
1624
1625        let unwound = std::panic::catch_unwind(|| {
1626            let _g = suppress_write_back();
1627            assert!(write_back_suppressed());
1628            panic!("a connectivity walk died");
1629        });
1630        assert!(unwound.is_err());
1631        assert!(
1632            !write_back_suppressed(),
1633            "a panic inside the guard left this thread never caching again"
1634        );
1635    }
1636}