Skip to main content

gunnar_server/
stores.rs

1//! Where the server's state lives on this box, and the one place a repository
2//! is turned into a pair of stores.
3//!
4//! ```text
5//!   <data-root>/
6//!     control.redb            the catalog, the identity table, the issuer
7//!                             certificate AND the sealed secrets (the certificate-identity plan)
8//!     secrets.kek             the key-encrypting key — a file, not a row
9//!     control.git/            LEGACY. The Arrow secret log, left where it is.
10//!     repos/<ns>/<name>.git/  one bare repository per catalog entry
11//! ```
12//!
13//! # One control store, and the migration that made it one
14//!
15//! The catalog and the identity table used to be two JSON blobs behind two
16//! references *inside* `control.git`. They moved to redb because the storage
17//! engine takes objects as packs and refuses a single-object write, which is
18//! exactly what a control document is — `gunnar_core::control` has the argument.
19//!
20//! What did **not** move then was `RepoStore::secrets()`, the Arrow log the
21//! sealed SSH host key lived in, and this header used to say why: *"folding it
22//! in then would have been a second migration riding on the first"*. It
23//! also named what deferring it cost — the control **repository** was still
24//! opened, so a `gunnar-server` still needed a storage engine to read its own
25//! host key, and the only mitigation was to open it **lazily** so that at least
26//! the catalog and the identity table stayed reachable without one.
27//!
28//! **That second migration happened on 2026-08-10.** Secrets are rows in
29//! `control.redb` ([`gunnar_core::secrets`]), the lazy `OnceLock` is gone, and
30//! so is [`RepoStore::secrets`] and the per-repository Arrow log every
31//! `open_repo` used to create beside a repository nobody read secrets from.
32//! `ServerStores` no longer opens a repository for any reason except serving
33//! one.
34//!
35//! # 🚨 The live SSH host key crosses this, and it is not a flag day
36//!
37//! `serve.rs` calls `ensure_host_key` on every boot. A migration that lost the
38//! key would mint a fresh one and hand every existing client
39//! `REMOTE HOST IDENTIFICATION HAS CHANGED`, which is what an attack looks like.
40//! So [`ServerStores::secrets`] is a **read-old / write-new** store
41//! ([`gunnar_core::MigratingSecretStore`]): redb first, the Arrow log as the
42//! fallback, the adopted value written back into redb, and **the Arrow log left
43//! on disk byte for byte**. An appliance that boots the new binary keeps its
44//! fingerprint; one that is rolled back to the old binary still finds its key
45//! where it left it. Nothing here deletes old data.
46//!
47//! The legacy log is opened only if `secrets.arrow` is already there
48//! ([`gunnar_core::legacy_secret_log`]), so a fresh installation never creates
49//! one, and it is opened as a **plain file through `gunnar_core::arrow_log`** —
50//! no engine is involved, and never needed to be.
51//!
52//! # One handle per repository, and a bound on how many
53//!
54//! An engine's store takes a writer lock on its own directory — the znippy arm
55//! caches one `GitStore` per path *under* the lock and says why (*"two
56//! instances over one directory would be two writers with two tails"*) — so two
57//! handles on the same git directory must not exist at once. Opening one per
58//! request would therefore fail the moment two clones of the same repository
59//! overlapped. Handles are cached instead, which is also what the
60//! single-writer requirement of the Arrow-IPC ref log wants.
61//!
62//! **Correction, 2026-08-10.** This paragraph used to make that argument about
63//! `FsStore`'s `O_EXCL` lock on **its Arrow secret log**. That lock is gone with
64//! the log: a repository no longer has a secret store, so nothing about
65//! *secrets* constrains how many handles it can have. The constraint is real and
66//! it is the engine's own writer lock; only the citation was stale.
67//!
68//! Until 2026-08-03 that cache had no bound and no eviction, so a server that
69//! touched a million repositories accumulated a million open handles: a lock
70//! file, an object store with its mmapped packs, and its logs, each. File
71//! descriptors run out long before memory does, and when they do *every* open
72//! fails while the cache holds descriptors for repositories nobody has touched
73//! in weeks.
74//!
75//! It is now a bounded LRU, and the two halves of that are equally load-bearing:
76//!
77//! * **the bound**: [`DEFAULT_OPEN_REPOS`] handles, evicting the least recently
78//!   used on insert; and
79//! * **liveness**: the value is an `Arc<OpenRepo>`, and an entry whose
80//!   handle somebody else still holds is **skipped by the evictor**. Dropping it
81//!   from the map would not close the in-flight transfer (the `Arc` keeps it
82//!   alive), but it would let the *next* request for that repository try to open
83//!   a second store on a git directory whose writer lock is still held, turning
84//!   a capacity policy into a spurious "the store is locked" failure in the
85//!   middle of a clone.
86//!
87//! The map is behind one mutex, which is still the server's one global
88//! serialisation point. The critical section holds no I/O (opening a store
89//! happens outside it), but a sharded map is the next thing to do here if
90//! contention ever shows up in a profile. It has not been measured, so it has
91//! not been built.
92
93use std::collections::HashMap;
94use std::path::{Path, PathBuf};
95use std::sync::atomic::AtomicBool;
96use std::sync::atomic::AtomicU64;
97use std::sync::{Arc, Mutex, MutexGuard};
98
99use anyhow::{Context, Result};
100use gunnar_core::{AuthTable, ControlStore, HashKind, NewRepo, Repo, RepoCatalog, RepoRef};
101use gunnar_ssh::Control;
102
103use crate::storage::OpenRepo;
104
105/// **Legacy, and kept.** The bare repository that held the catalog and the
106/// identity table until the certificate-identity plan moved them to [`CONTROL_DB`], and the sealed
107/// SSH host key until 2026-08-10 moved that there too.
108///
109/// It is still named, and still created, for two reasons that have nothing to
110/// do with git: [`gunnar_core::Kek::for_control_dir`] keeps `secrets.kek` in it
111/// — a file beside the data, deliberately not a row inside it — and
112/// [`gunnar_core::legacy_secret_log`] looks under it for the Arrow log an
113/// existing appliance's host key is in. **No storage engine opens it any more.**
114pub const CONTROL_DIR: &str = "control.git";
115
116/// **The control database**: the catalog, the identity table, the issuer
117/// certificate and the sealed secrets (the certificate-identity plan).
118pub const CONTROL_DB: &str = "control.redb";
119
120/// The directory every served repository lives under.
121pub const REPOS_DIR: &str = "repos";
122/// Where the transaction log lives under the data root.
123pub const TXLOG_DIR: &str = "txlog";
124
125/// **The identity half of the metadata mirror**, under
126/// `<slow>/metadata/` — principals and enrolled public keys, and nothing
127/// secret.
128///
129/// A mirror and never a source: nothing reads it back into the control store.
130/// It is there for the morning after the stripe is gone, when the question is
131/// *who had access to this box, and with which keys* — and `control.redb` is on
132/// the four disks that just died together.
133pub const IDENTITY_MIRROR: &str = "identity.json";
134
135/// The hash kind the **legacy** Arrow secret log under [`CONTROL_DIR`] was
136/// opened with, and therefore the one it must be reopened with to be read.
137///
138/// Nothing git-shaped was ever stored in that log — `ArrowLogStore` records a
139/// hash kind and refuses a reopen that disagrees with it (`Error::
140/// HashKindMismatch`), so this is a compatibility constant and not a choice
141/// being made afresh. sha256 because that is gunnar's default and what
142/// every control repository was opened with.
143pub const CONTROL_HASH_KIND: gix_hash::Kind = gix_hash::Kind::Sha256;
144
145/// How many repository handles are kept open at once.
146///
147/// Each one costs several file descriptors: the engine's writer lock and
148/// whatever its object store has open — mmapped packs and a redb tail on the
149/// znippy arm, loose objects and packs on the gix one. (It was "ten, including
150/// the two Arrow logs" until 2026-08-10; a repository has no Arrow logs any
151/// more.) So this is a descriptor budget in disguise. 256 sits an order of magnitude
152/// under a default 1024-descriptor `RLIMIT_NOFILE` while still keeping every
153/// repository an ordinary server touches in a minute resident.
154///
155/// It is a *cache* bound, not a concurrency limit: a repository whose handle is
156/// in use is never evicted, so exceeding it costs a re-open, never a failure.
157///
158/// **It is the CEILING, not the number** (2026-08-29). "256 sits an order of
159/// magnitude under a default 1024-descriptor `RLIMIT_NOFILE`" was arithmetic
160/// on handles, and a handle is five descriptors on the znippy engine — 256
161/// handles are 1280 descriptors, over the 1024 the appliance's PID 1 ran with.
162/// The rig hit `EMFILE` on the 202nd repository. [`ServerStores::open`] now
163/// takes [`crate::limits::open_repo_budget`] of the limit the process actually
164/// has: this value under a comfortable limit, 153 under 1024.
165pub const DEFAULT_OPEN_REPOS: usize = 256;
166
167/// Below this share of `MemTotal` still available, the handle cache gives
168/// handles back ([`ServerStores::reclaim_under_pressure`]).
169///
170/// Twenty-five percent, one step **above** the indexer watchdog's 20 % floor
171/// (`ZNIPPY_GIT_MEM_BUDGET_PCT`, the memory limit) and
172/// deliberately so: the cache is the cheaper thing to give up, and it should
173/// have given some back before the watchdog starts pausing pushes. The 2 GB box's
174/// 2 GB box reached the watchdog's floor with 256 handles still held and no way
175/// to reach them.
176pub const RECLAIM_FLOOR_PERCENT: u64 = 25;
177
178/// How often the memory behind the handle cache is probed, at most.
179///
180/// A quarter second: fast enough that a box falling into pressure gives handles
181/// back within a few opens, slow enough that a `/proc/meminfo` read is never on
182/// a hot path. It is taken only on a cache miss, which already costs a store
183/// open.
184pub const RECLAIM_PROBE_INTERVAL: std::time::Duration = std::time::Duration::from_millis(250);
185
186/// **How long a soft-deleted repository's bytes are kept before a sweep
187/// reclaims them.** Thirty days, which is the ordinary expectation of a paid
188/// forge and the number the drill states.
189///
190/// It is a DEFAULT and not a rule: every delete carries its own
191/// `purge_after_unix_ms`, written into the tombstone at the moment of the
192/// delete, so changing this constant never moves the deadline of a repository
193/// that is already deleted. A promise made to a customer on the day they
194/// deleted something must not be shortened by a later deploy.
195pub const DEFAULT_DELETE_RETENTION_DAYS: u32 = 30;
196
197/// How often [`ServerStores::sweep_expired_tombstones`] runs on a serving box.
198///
199/// Hourly. The window is measured in days, so the sweep's own period is noise
200/// against it, and an hour is short enough that an operator who set a
201/// `--retention-days 0` to reclaim space sees it happen while they are still
202/// watching.
203pub const TOMBSTONE_SWEEP_INTERVAL: std::time::Duration = std::time::Duration::from_secs(3600);
204
205/// **How often the flow ledger's live counters are copied into the control
206/// store: every 60 seconds.**
207///
208/// The window this bounds is *how much of today is lost to a hard power cut*,
209/// and a minute of one namespace's byte counts is the right size of loss for
210/// the write it costs — one redb commit per minute for the whole box, however
211/// many namespaces moved bytes, because the flush batches every row into one
212/// document update. A one-second flush would buy a minute of accuracy on a
213/// meter nobody bills to the minute and pay for it sixty times over; an hourly
214/// one would make a reboot look like a quiet hour.
215pub const FLOW_FLUSH_INTERVAL: std::time::Duration = std::time::Duration::from_secs(60);
216
217/// Why a name is tombstoned. The two cases are NOT the same and must never be
218/// collapsed.
219#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
220#[serde(rename_all = "snake_case")]
221pub enum TombstoneReason {
222    /// **A soft delete.** The bytes are being HELD, on purpose, until
223    /// `purge_after_unix_ms`. `repo undelete` puts the repository back.
224    Deleted,
225    /// **A reclaim that FAILED** (2026-08-30). The bytes are OWED, not
226    /// held: a `remove_dir_all` did not work and the name is fenced off until
227    /// `repo delete` is run again and succeeds. There is nothing to undelete —
228    /// the operator asked for the bytes to go.
229    ReclaimFailed,
230}
231
232impl TombstoneReason {
233    /// The word a message uses.
234    pub fn as_str(self) -> &'static str {
235        match self {
236            TombstoneReason::Deleted => "soft-deleted",
237            TombstoneReason::ReclaimFailed => "reclaim failed",
238        }
239    }
240}
241
242/// **A dated tombstone: the record beside a repository whose catalog row is
243/// gone and whose bytes are not.**
244///
245/// Written by [`ServerStores::soft_delete`] and by a failed
246/// [`ServerStores::purge_repo`], read by [`ServerStores::refuse_stale_store`]
247/// (which is what makes the NAME unusable), by
248/// [`ServerStores::undelete`] and by the sweep.
249///
250/// # Why the catalog row is copied in here
251///
252/// `undelete` has to restore what was there — the hash kind above all. A
253/// repository recreated `--hash sha256` over a sha1 store serves sha1 refs to a
254/// client that asked for sha256 and answers `fatal: protocol error`; that is
255/// the 2026-08-30 resurrection this closed, and an undelete that guessed the
256/// defaults would re-open it from the other side. The store's own
257/// `OBJECT_FORMAT` marker is the second opinion, and
258/// [`ServerStores::create_repo`]'s adopt path checks them against each other.
259///
260/// # It is JSON, and it is read leniently
261///
262/// An earlier build wrote a free-text note here. A file that does not parse as JSON is
263/// therefore read as one of those: reason `ReclaimFailed`, no deadline, the
264/// text kept as the note. An old appliance's tombstone keeps working, and a
265/// new one is never mistaken for a soft delete it was not.
266#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
267pub struct Tombstone {
268    /// When the delete was asked for.
269    pub deleted_at_unix_ms: i64,
270    /// When a sweep may reclaim the bytes.
271    ///
272    /// `None` means **never on its own**: a failed reclaim is owed to an
273    /// operator, not scheduled, and a sweep that purged it would be doing the
274    /// thing that already failed, unattended.
275    pub purge_after_unix_ms: Option<i64>,
276    /// Who asked. Empty when a local CLI did it with no principal.
277    #[serde(default)]
278    pub principal_id: String,
279    /// Held, or owed.
280    pub reason: TombstoneReason,
281    /// The catalog row as it was, so `undelete` restores it rather than a
282    /// default. `None` on a tombstone written before this existed.
283    #[serde(default)]
284    pub repo: Option<Repo>,
285    /// A sentence a human reads.
286    #[serde(default)]
287    pub note: String,
288}
289
290impl Tombstone {
291    /// Read one, leniently. See the type docs on the free-text form.
292    pub fn parse(text: &str) -> Tombstone {
293        if let Ok(parsed) = serde_json::from_str::<Tombstone>(text) {
294            return parsed;
295        }
296        Tombstone {
297            deleted_at_unix_ms: 0,
298            purge_after_unix_ms: None,
299            principal_id: String::new(),
300            reason: TombstoneReason::ReclaimFailed,
301            repo: None,
302            note: text.trim().to_owned(),
303        }
304    }
305
306    /// Is the retention window over at `now`?
307    ///
308    /// A tombstone with no deadline is **never** expired, whatever `now` is.
309    pub fn is_expired_at(&self, now_unix_ms: i64) -> bool {
310        match self.purge_after_unix_ms {
311            Some(at) => now_unix_ms >= at,
312            None => false,
313        }
314    }
315
316    /// How long is left, in whole seconds, or `None` when there is no deadline.
317    pub fn seconds_left(&self, now_unix_ms: i64) -> Option<i64> {
318        self.purge_after_unix_ms
319            .map(|at| (at - now_unix_ms).max(0) / 1000)
320    }
321}
322
323/// One soft-deleted repository, as `repo list-deleted` and `Admin.StorageInfo`
324/// report it.
325#[derive(Debug, Clone)]
326pub struct DeletedRepo {
327    /// Where it was.
328    pub path: RepoRef,
329    /// The record beside it.
330    pub tombstone: Tombstone,
331    /// Bytes its directory still holds. **This is the number a bill is made
332    /// of**: a tombstone is storage the account is still using.
333    pub bytes: u64,
334}
335
336/// **A store directory with no catalog row and no soft-delete tombstone: an
337/// ORPHAN**, as `repo list-orphans` reports it.
338///
339/// This is the class of bytes nothing on the box could see before 2026-08-30.
340/// `repo list` reads the catalog and an orphan is not in it; `repo
341/// list-deleted`, `repo purge`, `repo undelete` and the expiry sweep all key
342/// off a `Deleted` tombstone and an orphan has none. Every reclaim path was
343/// keyed off a record that had gone.
344///
345/// The listing invariant this type exists to make true: **every `<name>.git`
346/// directory under `repos/` appears in exactly one of `repo list`, `repo
347/// list-deleted` and `repo list-orphans`** — so no directory on the disk is
348/// invisible to every door.
349#[derive(Debug, Clone)]
350pub struct OrphanStore {
351    /// The name the directory stands at.
352    pub path: RepoRef,
353    /// Where it is, for an operator with a shell — and there is none on the
354    /// appliance, which is why the other fields exist.
355    pub dir: PathBuf,
356    /// What it is holding.
357    pub bytes: u64,
358    /// The `OBJECT_FORMAT` marker, when it has one. `None` is a store written
359    /// before the marker existed, and it is what `create --adopt --hash` takes
360    /// the caller's word about.
361    pub hash_marker: Option<String>,
362    /// Newest mtime under the directory, so an operator can tell Friday's
363    /// wreckage from something still being written to.
364    pub modified_unix_ms: i64,
365    /// A tombstone that is **not** a soft delete — a reclaim that FAILED and
366    /// is owed to an operator. Those are orphans too: `tombstones()` filters
367    /// them out of `list-deleted` on purpose, so without this they would be in
368    /// no listing at all.
369    pub failed_reclaim: Option<String>,
370}
371
372/// The bounded LRU of open repository handles.
373struct HandleCache {
374    capacity: usize,
375    /// Repository key → its handle and the tick it was last handed out at.
376    entries: HashMap<String, (Arc<OpenRepo>, u64)>,
377    /// Monotonic, so "least recently used" is a comparison and not a list.
378    clock: u64,
379}
380
381impl HandleCache {
382    fn new(capacity: usize) -> Self {
383        HandleCache {
384            capacity: capacity.max(1),
385            entries: HashMap::new(),
386            clock: 0,
387        }
388    }
389
390    /// Lower (or raise) the bound and evict down to it.
391    ///
392    /// Returns how many handles were dropped, so the caller can say it once
393    /// rather than have this file guess at a log line's wording.
394    fn set_capacity(&mut self, capacity: usize) -> usize {
395        let before = self.entries.len();
396        self.capacity = capacity.max(1);
397        self.evict();
398        before.saturating_sub(self.entries.len())
399    }
400
401    fn touch(&mut self, key: &str) -> Option<Arc<OpenRepo>> {
402        self.clock += 1;
403        let clock = self.clock;
404        let (store, used) = self.entries.get_mut(key)?;
405        *used = clock;
406        Some(Arc::clone(store))
407    }
408
409    /// Insert `store` under `key` unless another thread already won that race,
410    /// and return whichever handle is now the cached one.
411    fn insert(&mut self, key: String, store: Arc<OpenRepo>) -> Arc<OpenRepo> {
412        if let Some(existing) = self.touch(&key) {
413            // The loser's handle is dropped by the caller, releasing its lock.
414            return existing;
415        }
416        self.clock += 1;
417        let clock = self.clock;
418        self.entries.insert(key, (Arc::clone(&store), clock));
419        self.evict();
420        store
421    }
422
423    /// Drop least-recently-used entries until the bound holds again, skipping
424    /// any handle somebody else is still holding.
425    ///
426    /// A cache that cannot get under its bound because every handle is in use
427    /// says so once per eviction pass rather than growing silently: over the
428    /// bound is a real state, and an operator whose descriptors are about to run
429    /// out needs to hear about it before `accept` starts failing.
430    fn evict(&mut self) {
431        while self.entries.len() > self.capacity {
432            let victim = self
433                .entries
434                .iter()
435                // The iterator borrows rather than clones, so `1` is the
436                // cache's own reference and nothing else. Anything above it is
437                // a caller holding the handle through an operation.
438                .filter(|(_, (store, _))| Arc::strong_count(store) == 1)
439                .min_by_key(|(_, (_, used))| *used)
440                .map(|(key, _)| key.clone());
441            match victim {
442                Some(key) => {
443                    self.entries.remove(&key);
444                }
445                None => {
446                    tracing::warn!(
447                        open = self.entries.len(),
448                        capacity = self.capacity,
449                        "every open repository handle is in use; the cache is over its bound \
450                         until one of them is released"
451                    );
452                    return;
453                }
454            }
455        }
456    }
457}
458
459/// Every store the server needs, opened once.
460pub struct ServerStores {
461    /// **The identity core of this box** (IDENTITY-HOST, 2026-10-27), set once
462    /// by the server when it builds it ([`crate::identity::build`]): the paths
463    /// outside a gRPC context (a pulled `sign_in_again` or `add_users` order)
464    /// mint their first-login links through it. `None` before the server is up.
465    /// **Weak, on purpose**: the core holds the control plane, which holds
466    /// these stores; a strong handle here is a cycle that keeps the redb files
467    /// open after the server stops (an in-process restart met "Database already
468    /// open"). The server's context owns the core.
469    identity: std::sync::OnceLock<std::sync::Weak<gunnar_grpc::identity::GunnarIdentity>>,
470    root: PathBuf,
471    repos_root: PathBuf,
472    control_dir: PathBuf,
473    /// **Which storage engine this process runs.**
474    ///
475    /// Resolved once, at [`ServerStores::open`], from `GUNNAR_ENGINE` or the
476    /// build's default. A field and not a global: the `OnceLock` that used to
477    /// hold an installed engine is gone with the crate that installed into it,
478    /// and "which engine" is now ordinary configuration that arrives with the
479    /// data root rather than a plugin registered from a `main` somewhere else.
480    ///
481    /// It is resolved *before* the first repository is opened, so a build asked
482    /// for an engine it does not carry fails at startup with a message naming
483    /// what it does carry — never by quietly serving from the other one.
484    engine: crate::storage::Engine,
485    /// **The raw secret store**, opened eagerly with everything else.
486    ///
487    /// It used to be a `OnceLock<Arc<dyn RepoStore>>` holding the control
488    /// *repository*, opened lazily because opening it needed a storage engine
489    /// and the catalog and the identity table had stopped needing one. There is
490    /// nothing left to defer: this is a table in the database that is already
491    /// open, plus — on an appliance that predates 2026-08-10 — a read-only
492    /// handle on the legacy Arrow log, which is a plain file.
493    ///
494    /// Raw, not sealed. [`Self::secrets`] is the only supported way to reach it
495    /// and it puts the seal on; nothing on the boot path may write a private key
496    /// through this handle. It is private for exactly that reason.
497    secrets: Arc<dyn gunnar_store::SecretStore>,
498    /// **Whether a pre-sealing secret log is on this disk at all.**
499    ///
500    /// The one fact that decides whether an unsealed value read back out of
501    /// [`Self::secrets`] is gunnar's own history or somebody else's writing.
502    /// `legacy_secret_log` answered it once, at open, out of `secrets.arrow`'s
503    /// existence; [`Self::secrets`] hands that answer to the seal as a
504    /// `gunnar_core::PlaintextPolicy` rather than letting the decorator guess it
505    /// from bytes that cannot carry it. `false` on every installation made after
506    /// the 2026-08-10 redb migration, which is every installation that was not
507    /// upgraded across it.
508    legacy_secrets: bool,
509    /// The key-encrypting key the control store's secrets are sealed under
510    /// Resolved at open, so a KEK that cannot be read fails the boot
511    /// loudly rather than at whatever moment first touches a secret. It is a
512    /// file beside the database, not a row in it — which is what makes a copied
513    /// `control.redb` useless — so it costs no engine either.
514    ///
515    /// Behind a lock (S9, 2026-10-10): a twin opens under a KEK of its own and is handed its
516    /// primary's as the log's first frame ([`Self::adopt_kek`]); from that frame on it opens the
517    /// rows it holds — a sold front's `Sealed.Get` on the twin — without a restart.
518    kek: std::sync::RwLock<gunnar_core::Kek>,
519    /// The catalog, the identity table and the issuer certificate (the certificate-identity plan).
520    control_store: Arc<dyn ControlStore>,
521    /// **The one redb handle** under `control_store` and `secrets` — what the
522    /// runtime data-set growth takes off the stripe and puts back
523    /// (`gunnar_core::ControlDb::suspend` / `resume`, `crate::grow`).
524    control_db: Arc<gunnar_core::ControlDb>,
525    /// **The repository stores are CLOSED for a growth** (`crate::grow`):
526    /// `repo_store` refuses to open anything while this is set, so a
527    /// background worker meets an error and retries rather than pinning the
528    /// mount that is about to go. Never set outside a growth.
529    suspended: AtomicBool,
530    /// **The transaction log** every durable mutation on this box is a frame
531    /// in, before it lands (`gunnar_core::txlog`). The twin's source.
532    txlog: Arc<gunnar_core::txlog::Log>,
533    /// This box is a twin (`<root>/twin.json`, `crate::twin`). Runtime, not decided once at open:
534    /// a fresh box becomes a twin through `Bootstrap.BecomeTwin` while it runs, and from that
535    /// moment it writes no per-box mirror (the KVM drill found the fresh box's own mirror left
536    /// on the twin's disk).
537    ///
538    /// **An `Arc` since 2026-09-21 (lane T4)**, so the SSH/HTTP front door can
539    /// hold the SAME flag rather than a copy taken at start-up: a box conferred
540    /// the twin role over the wire must stop serving git the instant the role
541    /// lands, not at the next restart.
542    twin: Arc<AtomicBool>,
543    /// **Snapshots being streamed from a cut** (R5.1-A, 2026-10-07; [`ServerStores::snapshot_pin`]):
544    /// while any is, a gc waits, and so does the removal of a repository store or an LFS object —
545    /// what the cut names must still be there when the stream reaches it.
546    snapshot_pins: SnapshotPins,
547    /// The control store UNDER the tee — the twin's apply path.
548    raw_control_store: Arc<dyn ControlStore>,
549    /// The secret store UNDER the tee — the twin's apply path.
550    raw_secrets: Arc<dyn gunnar_store::SecretStore>,
551    auth: AuthTable,
552    catalog: RepoCatalog,
553    /// Per-repository policy documents (`refs/gunnar/policy`).
554    ///
555    /// Opened with the other two and not lazily: it is read on the **push
556    /// path**, and a store opened on first push would make the first push of
557    /// every restart pay for it.
558    policies: gunnar_core::PolicyStore,
559    /// Pull-mirror registrations (`refs/gunnar/mirrors`).
560    mirrors: gunnar_core::MirrorStore,
561    /// **The flow ledger** (`refs/gunnar/flow`): what MOVED, per namespace, per
562    /// UTC day.
563    ///
564    /// An `Arc` and not a plain field because it is the one store here that is
565    /// written from the TRANSFER paths as well as read from the control plane —
566    /// `transport::serve_blocking` and `gunnar_ssh::Admission` each hold a
567    /// clone — and because its live half is a set of atomics that must be the
568    /// same set for every holder. Two ledgers over one control store would each
569    /// hold half the day and each overwrite the other's half on flush.
570    ///
571    /// Opened with the other documents rather than lazily, for
572    /// [`ServerStores::policies`]'s reason: it is read and written on the push
573    /// path, and a store opened on first push would make the first push of
574    /// every restart pay for it.
575    flow: Arc<gunnar_core::FlowLedger>,
576    /// **When each principal last signed in and last changed something**
577    /// (2026-10-21): in memory, minute-grained, flushed by its own thread in a
578    /// batch — one redb transaction and one `Activity` frame per flush that
579    /// moved something — never on the request path, never in the identity
580    /// document. See `gunnar_core::activity`.
581    activity: Arc<gunnar_core::PrincipalActivity>,
582    /// **The usage ledger** (2026-10-06): every namespace's stock meters, kept
583    /// current by re-measuring only what changed — `UsageBatch.ReadMany`'s
584    /// source, so a billing poll is not one disk walk per tenant. Marked from
585    /// this type's own mutation points (a store opening, a tombstone, a
586    /// growth's resume) and from the flow ledger's observer.
587    usage: Arc<crate::usage_ledger::UsageLedger>,
588    /// **The server's ONE set of counters** (`gunnar_core::observe::ServerMetrics`), minted
589    /// with the stores so the tasks that start before `Server::start` (the flow flush and its
590    /// usage-ledger reconcile pass, A28 M17) write to the same counters the listeners do and
591    /// `/metrics` publishes. `Server::start` takes this one; it mints no second set.
592    metrics: Arc<gunnar_core::observe::ServerMetrics>,
593    /// **Every account's audit log** (`refs/gunnar/account-audit/<account>`,
594    /// 2026-10-05): the account admin's, never the operator's.
595    account_audit: Arc<gunnar_core::account_audit::AccountAuditLog>,
596    /// **The name filter's lists and the accounts' review queues**
597    /// (`refs/gunnar/name-filter`, 2026-10-05).
598    names: gunnar_core::name_filter::NameFilterStore,
599    /// **The generic server settings** (`refs/gunnar/settings`, owner 2026-10-26): bytes under
600    /// names the clients choose; the server knows none of them.
601    settings: gunnar_core::settings::SettingsStore,
602    /// **People's encryption keys** (`refs/gunnar/encryption-keys`, CRYPT-YUBI 2026-10-26): the
603    /// public half of each person's one encryption key and its unlock methods' wraps, which are
604    /// ciphertext to this server.
605    encryption_keys: gunnar_core::encryption_key::EncryptionKeys,
606    open: Mutex<HandleCache>,
607    /// When the memory probe behind [`ServerStores::reclaim_under_pressure`]
608    /// last ran. `None` until the first cache miss.
609    last_reclaim_probe: Mutex<Option<std::time::Instant>>,
610    /// **Is this box refusing client writes because it is a STANDBY?**
611    ///
612    /// One `Arc<AtomicBool>`, shared by clone into every [`Control`] this
613    /// `ssh_control` hands out AND read/written by the replication slot's
614    /// role changes — one value, so the SSH front door and the control plane
615    /// can never disagree about whether a `git push` should be refused (one implementation).
616    /// `true` = STANDBY (freeze non-`Machine` writes), `false` = PRIMARY.
617    ///
618    /// Initialised from the persisted role in `replication.json` at open, so a
619    /// box that abdicated and then rebooted comes back still frozen — the same
620    /// durability `demote`'s roster already has. Always present, even in a build
621    /// without the `replication` feature, where it simply never turns `true`.
622    writes_frozen: Arc<AtomicBool>,
623    /// **Is this box a browse replica**? Sibling of
624    /// `writes_frozen`, same lifecycle: set from `replication.json` at open,
625    /// flipped by the replication slot on a role change, READ by the control
626    /// plane's mutator refusal and by the front door's wording. A browse box is
627    /// also frozen; this flag is what distinguishes it from a promotable
628    /// standby.
629    browse: Arc<AtomicBool>,
630    /// **How many repository stores this process has opened**, cumulative and
631    /// monotonic.
632    ///
633    /// One counter, bumped at the single site an engine store is actually
634    /// opened (a [`HandleCache`] miss in [`Self::repo_store`]) — not on a cache
635    /// hit, which pays nothing. Each open pays the refold cost, so a
636    /// path that opens every repository on a cold box is a cost measured in
637    /// this number, and it is the number a status call must not run up: see
638    /// Exposed for exactly that assertion — a test proves a plain
639    /// `replication list` adds ZERO to it, and `--refs` adds one per repository.
640    store_opens: Arc<AtomicU64>,
641    /// **Where each kind of data goes** (`crate::slow`), resolved once at open
642    /// out of the layout config's `dir.<name>.path`.
643    ///
644    /// A field and not a global for the reason the engine is a field: which
645    /// directories this server writes to is configuration that arrives with the
646    /// data root, and a process-global would make two `ServerStores` in one
647    /// process (the bench opens the same data root twice) share one answer.
648    ///
649    /// It ALWAYS resolves — to the configured paths, or to the documented
650    /// default under the data root — so nothing downstream branches on whether
651    /// the machine has a second spindle. What the branch is on is the CLAIM:
652    /// see `crate::slow::Claim`.
653    slow: crate::slow::SlowRoot,
654    /// **What the installer decided**, read once at open and never re-read.
655    ///
656    /// Static and historical by nature: it is the only place the *reasoning*
657    /// survives — which disk booted and why, which devices became `/data`,
658    /// what was rejected and on what grounds. Re-reading it would not make it
659    /// fresher, and an absent one stays absent with the sentence that says so.
660    install: crate::layout_config::Load,
661    /// **The front doors' plan-gate chain, where a mirror's worker can read
662    /// it** (2026-10-02). `serve::front_control` builds the chain a push is held
663    /// to — disk headroom, then the entitlement on a metered build — and
664    /// installs it here, so a mirror sync is held to the SAME namespace room a
665    /// push is, by the same gates, rather than being the one write on the box
666    /// no ceiling holds. Empty until something installs it (a store opened by
667    /// a test or a tool), which is "no ceiling", exactly the answer a chain
668    /// with no gates gives.
669    plan_gates: std::sync::RwLock<Vec<Arc<dyn gunnar_ssh::PlanGate>>>,
670    /// **The data set's space ledger** (`gunnar_ssh::space`), installed with
671    /// the plan gates by `serve::front_control` — the disk gate's own. Every
672    /// door that writes a pack or an object asks it before each chunk. `None`
673    /// (a test, a tool): no admission beyond the gates.
674    space: std::sync::RwLock<Option<Arc<gunnar_ssh::SpaceLedger>>>,
675    /// **The keys this primary was FED to enrol and has not enrolled yet**
676    /// (fingerprint → OpenSSH line; `crate::fed_principals::note_fed`), read
677    /// by the gRPC gate through `Identity::awaiting_enrolment`: the holder of
678    /// one is told `Unavailable [key-enrolling]`, ask again, not that it is
679    /// unknown (cov-E r3 2026-10-06). In memory only: the feed on disk is the
680    /// authority, and every feed and every install pass recomputes it.
681    fed_keys: std::sync::RwLock<std::collections::BTreeMap<String, String>>,
682}
683
684/// The longest a gc or a removal waits for a snapshot streaming from its cut
685/// ([`ServerStores::wait_unpinned`]).
686pub const SNAPSHOT_PIN_WAIT: std::time::Duration = std::time::Duration::from_secs(600);
687
688/// The pin count and its condvar ([`ServerStores::snapshot_pin`]).
689#[derive(Default)]
690struct SnapshotPins {
691    count: Mutex<usize>,
692    cv: std::sync::Condvar,
693}
694
695/// Held while a snapshot streams from its cut. See [`ServerStores::snapshot_pin`].
696#[must_use = "the pin holds only while the guard lives"]
697pub struct SnapshotPin<'a> {
698    pins: &'a SnapshotPins,
699}
700
701impl Drop for SnapshotPin<'_> {
702    fn drop(&mut self) {
703        let mut n = self.pins.count.lock().unwrap_or_else(|p| p.into_inner());
704        *n = n.saturating_sub(1);
705        self.pins.cv.notify_all();
706    }
707}
708
709impl std::fmt::Debug for ServerStores {
710    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
711        f.debug_struct("ServerStores")
712            .field("root", &self.root)
713            .finish_non_exhaustive()
714    }
715}
716
717impl ServerStores {
718    /// Open everything under `root`, creating whatever is not there yet.
719    ///
720    /// The handle cache is sized to the descriptor limit this process has —
721    /// after [`crate::limits::nofile`] has raised it as far as it may — so the
722    /// cache can never by itself put the process over `RLIMIT_NOFILE`.
723    pub fn open(root: impl AsRef<Path>) -> Result<Self> {
724        // `crate::budget`, not `limits::open_repo_budget` alone: the descriptor
725        // term is still the descriptor one and still binds first on a small `ulimit -n`,
726        // but it is now the MINIMUM of that and a memory term. The 2 GB box measured
727        // why: on a 2 GB appliance the descriptor term said 256 handles, 256
728        // handles held the whole box, and the indexer's watchdog then spent
729        // every push failing to reclaim memory that was in the OTHER 255.
730        Self::open_with_capacity(root, crate::budget::budgets().open_repos)
731    }
732
733    /// [`ServerStores::open`], with an explicit handle-cache bound.
734    ///
735    /// Exists so the eviction path can be tested at a capacity a test can
736    /// actually exceed. A bound that is only ever exercised at 256 is a bound
737    /// nothing has ever seen fire.
738    pub fn open_with_capacity(root: impl AsRef<Path>, capacity: usize) -> Result<Self> {
739        Self::open_with_engine(root, capacity, crate::storage::Engine::selected()?)
740    }
741
742    /// [`ServerStores::open_with_capacity`], with the engine named rather than
743    /// resolved from the environment.
744    ///
745    /// The one seam a head-to-head bench needs: the same data root opened twice,
746    /// once per engine, from one process — which is what makes an Arrow-vs-gix
747    /// row a comparison rather than two anecdotes.
748    pub fn open_with_engine(
749        root: impl AsRef<Path>,
750        capacity: usize,
751        engine: crate::storage::Engine,
752    ) -> Result<Self> {
753        let root = root.as_ref().to_path_buf();
754        let repos_root = root.join(REPOS_DIR);
755        std::fs::create_dir_all(&repos_root)
756            .with_context(|| format!("creating the repository root {}", repos_root.display()))?;
757
758        let control_dir = root.join(CONTROL_DIR);
759        std::fs::create_dir_all(&control_dir)
760            .with_context(|| format!("creating the control directory {}", control_dir.display()))?;
761
762        // **Where the storage is, read once — and gunnar is TOLD, never
763        // discovers.** `/boot/korp/layout.conf` is what the installer wrote and
764        // sealed while it still knew WHY it chose what it chose; `crate::slow`
765        // obeys its `dir.<name>.path` verbatim and nothing here probes a mount
766        // table to second-guess it. An appliance installed before the config
767        // existed has none, which is a first-class answer carrying the sentence
768        // that says so — never a refusal to start, and never an inference.
769        let install = crate::layout_config::load();
770        let slow = crate::slow::SlowRoot::resolve(&root, install.config());
771        slow.announce(
772            &crate::layout_config::config_path().display().to_string(),
773            install
774                .config()
775                .map(|c| c.authenticity().word())
776                .unwrap_or_default(),
777        );
778        if let Some(why) = install.absent_reason() {
779            tracing::info!(
780                target: crate::slow::TARGET_SLOW,
781                event = "layout.absent",
782                "{why}"
783            );
784        }
785        // The panic hook in `main` has no data root; this is where it learns
786        // where a crash record goes. Best effort — a crash directory that
787        // cannot be made means no crash file, never a refusal to start.
788        match slow.crash_dir() {
789            Ok(dir) => crate::slow::register_crash_dir(dir),
790            Err(err) => tracing::warn!(
791                target: crate::slow::TARGET_SLOW,
792                %err,
793                "no crash directory on the slow disk; a panic will reach the console but \
794                 will not be written down"
795            ),
796        }
797
798        // The KEK for the control store's secrets. Read (or minted) here
799        // so `secrets()` cannot fail on the key, and so a missing one is a
800        // boot-time error with a path in it. It is a file, not a git object, so
801        // this does not need an engine.
802        let kek = gunnar_core::Kek::for_control_dir(&control_dir).with_context(|| {
803            format!(
804                "resolving the key-encrypting key for {}; secrets are sealed at rest",
805                control_dir.display()
806            )
807        })?;
808
809        // The certificate-identity plan. This is the whole control plane's storage, and it opens
810        // whether or not this binary carries a storage engine.
811        //
812        // The documents and the secrets come out of ONE call because they share
813        // one `redb::Database`: redb takes an exclusive file lock, so opening
814        // `control.redb` twice in this process would fail rather than give two
815        // views. One file, one lock, one handle.
816        let db = root.join(CONTROL_DB);
817        let (raw_control_store, redb_secrets, control_db) = gunnar_core::open_control_with_db(&db)
818            .with_context(|| format!("opening the control store {}", db.display()))?;
819        // **The transaction log**, before either store: a primary that cannot
820        // write its log has no twin, and that is loud here rather than found
821        // at the restore (`.nornir/twin-transaction-log.md`).
822        let txlog_dir = root.join(TXLOG_DIR);
823        let txlog = Arc::new(
824            gunnar_core::txlog::Log::open(&txlog_dir)
825                .with_context(|| format!("opening the transaction log {}", txlog_dir.display()))?,
826        );
827        // **Twin or primary** (`crate::twin`). A twin holds the primary's
828        // numbers and originates none: its log is follower-only, nothing under
829        // its root is framed, and its control plane refuses mutators (the
830        // browse flag). A box mid-restore is follower-only too. A primary
831        // frames its KEK FIRST — seq 1 — so a restore can open every sealed
832        // secret that follows, and registers its root with the sink so the
833        // signed logs and documents under it are frames before they are bytes.
834        let twin = crate::twin::is_twin_root(&root);
835        let restoring = crate::twin::is_restoring(&root);
836        if restoring && !twin {
837            // Said at every open, because the state is silent otherwise: the box serves git,
838            // answers reads, and refuses every write with a message about twins.
839            tracing::warn!(
840                target: gunnar_core::observe::TARGET_TWIN,
841                event = "twin.restoring_at_open",
842                "THIS BOX IS MID-RESTORE (`txlog-restoring` is present): it originates no \
843                 transactions, so every control-plane write is refused, until a restore finishes. \
844                 Resend the twin's log with `gunnar control twin replay`; a finished restore that \
845                 still says this lost its marker's removal to a power cut"
846            );
847        }
848        // **An old generation of its log** (stinky row 18, the main's half): a twin
849        // showed this box a newer generation signed by its own host key, so the
850        // box was fenced (`crate::twin::LOG_FENCED`). A restart must not undo
851        // that: it comes up follower-only, writes nothing, and says why.
852        let fenced = !twin && !restoring && crate::twin::is_fenced(&root);
853        if fenced {
854            tracing::error!(
855                target: gunnar_core::observe::TARGET_TWIN,
856                event = "twin.fenced_by_generation",
857                "THIS BOX IS FENCED: {}. Every write is refused and no twin is served its log.",
858                crate::twin::fenced_why(&root).unwrap_or_default()
859            );
860        }
861        if twin || restoring || fenced {
862            txlog.set_follower(true);
863        } else {
864            // **This history's name** (2026-09-21, lane T4). A primary mints it
865            // once, from the CSPRNG and from nothing on the box, and answers
866            // `Mirror.LogHead` with it from then on. It is what lets a twin ask
867            // "is this the same log?" instead of only "is this number bigger?"
868            // — the question that catches a re-imaged main which has already
869            // written PAST the twin's head, where every number still looks
870            // right. A twin does not mint one: it is told its primary's, and a
871            // box taking a restore is told the stream's. See `twin::LOG_ID`.
872            crate::twin::mint_log_id(&root).context("minting this log's identity")?;
873            if txlog.head_seq() == 0 {
874                let bytes = hex::decode(kek.to_hex()).context("the KEK as bytes")?;
875                txlog
876                    .append(
877                        gunnar_core::txlog::Kind::Kek,
878                        &gunnar_core::txlog::Meta::Kek {},
879                        &bytes,
880                    )
881                    .context("framing the KEK as the log's first transaction")?;
882            }
883            gunnar_core::txlog::sink::register(&root, &txlog);
884            // **And the site's WireGuard hub declaration becomes a transaction**
885            // (lane T11, 2026-09-21). Nothing in gunnar ever WRITES `wg/hub.conf` —
886            // `korp-installer` lays it through the ESP data stage before gunnar's
887            // first boot — so it has no sink call site of its own and the twin
888            // never held it. A restored main with no hub declaration is a box
889            // nobody can reach, which is the worst thing to find on the day the
890            // twin is used.
891            //
892            // Framed on open, once per CHANGE and not once per boot: the digest of
893            // what was last framed sits beside it in a per-box file, so a box that
894            // reboots a thousand times adds one frame, not a thousand.
895            //
896            // **After the re-seal, not here** — see the call site below. A restored
897            // box's FIRST frame after the restore must be its new KEK, and framing a
898            // document before it would put the KEK second in its own log.
899        }
900        let control_store: Arc<dyn ControlStore> =
901            Arc::new(gunnar_core::txlog::tee::LoggedControlStore::new(
902                Arc::clone(&raw_control_store),
903                Arc::clone(&txlog),
904            ));
905
906        // 🚨 THE LIVE SSH HOST KEY CROSSES HERE. Read-old / write-new: the
907        // legacy Arrow log is consulted only for a key redb has never seen, and
908        // whatever it answers is written into redb and returned unchanged. The
909        // log itself is never written and never removed — an appliance rolled
910        // back to a pre-migration binary still finds its host key. `None` is the
911        // normal answer on any installation made after this change, and on that
912        // path no Arrow log is created.
913        let legacy =
914            gunnar_core::legacy_secret_log(&control_dir, CONTROL_HASH_KIND).with_context(|| {
915                format!(
916                    "checking {} for a legacy Arrow secret log to carry the SSH host key \
917                     forward from",
918                    control_dir.display()
919                )
920            })?;
921        // Recorded before the handle is type-erased: once `legacy` is inside an
922        // `Arc<dyn SecretStore>` nothing downstream can ask whether there was
923        // one, and `secrets()` is the caller that has to know.
924        let legacy_secrets = legacy.is_some();
925        let raw_secrets: Arc<dyn gunnar_store::SecretStore> =
926            Arc::new(gunnar_core::MigratingSecretStore::new(redb_secrets, legacy));
927        // **A restored box re-seals under a KEK of its own** before any sealed store is built
928        // (`crate::twin::reseal_after_restore`). Its log is a primary's again by now.
929        // Captured before the re-seal clears its marker: it names this start in what the audit
930        // trail check says (`crate::twin::rematerialise_audit_trail`, below).
931        let just_restored = !twin && !restoring && crate::twin::reseal_pending(&root);
932        let kek = if just_restored {
933            let rows = control_db
934                .export()
935                .context("reading the secrets to re-seal")?
936                .secrets;
937            crate::twin::reseal_after_restore(
938                &root,
939                &control_dir,
940                &txlog,
941                &rows,
942                raw_secrets.as_ref(),
943            )
944            .context("re-sealing a restored box's secrets under its own KEK")?
945        } else {
946            kek
947        };
948        // **And now the site's hub declaration** (lane T11) — deliberately AFTER the re-seal.
949        // A restored box's first frame after the restore is its own KEK (`reseal_after_restore`
950        // frames it first so the twin following the restored box can open everything that comes
951        // after), and a document framed before it would take that place. Measured: it did, and
952        // `a_restored_box_reseals_every_secret_under_a_kek_of_its_own…` said so by name.
953        if !twin && !restoring && !fenced {
954            adopt_hub_conf(&root, &txlog);
955        }
956        let secrets: Arc<dyn gunnar_store::SecretStore> =
957            Arc::new(gunnar_core::txlog::tee::LoggedSecretStore::new(
958                Arc::clone(&raw_secrets),
959                Arc::clone(&txlog),
960            ));
961
962        let auth =
963            AuthTable::new(Arc::clone(&control_store)).context("opening the identity table")?;
964        let catalog = RepoCatalog::new(Arc::clone(&control_store))
965            .context("opening the repository catalog")?;
966        let policies = gunnar_core::PolicyStore::new(Arc::clone(&control_store))
967            .context("opening the policy store")?;
968        let mirrors = gunnar_core::MirrorStore::new(Arc::clone(&control_store))
969            .context("opening the mirror registry")?;
970        let account_audit = Arc::new(
971            gunnar_core::account_audit::AccountAuditLog::new(Arc::clone(&control_store))
972                .context("opening the account audit logs")?,
973        );
974        let names = gunnar_core::name_filter::NameFilterStore::new(Arc::clone(&control_store))
975            .context("opening the name filter")?;
976        let settings = gunnar_core::settings::SettingsStore::new(Arc::clone(&control_store))
977            .context("opening the server settings")?;
978        let encryption_keys =
979            gunnar_core::encryption_key::EncryptionKeys::new(Arc::clone(&control_store))
980                .context("opening people's encryption keys")?;
981        let flow = Arc::new(gunnar_core::FlowLedger::new(
982            gunnar_core::FlowStore::new(Arc::clone(&control_store))
983                .context("opening the flow ledger")?,
984        ));
985
986        tracing::info!(
987            target: "gunnar::store",
988            event = "store.engine_selected",
989            engine = engine.name(),
990            compiled = %crate::storage::Engine::compiled_list(),
991            "the storage engine for this process"
992        );
993
994        // The persisted role decides whether this box comes up frozen. A
995        // standby that rebooted is still a standby; a plain box (no
996        // `replication.json`, or the `replication` feature off) is a writable
997        // primary, which is every deployment before failover was built.
998        let role_at_open = replication_role_at_open(&root);
999        let frozen_at_open = role_at_open.refuses_client_writes();
1000        if frozen_at_open {
1001            tracing::warn!(
1002                target: "gunnar::store",
1003                event = "store.role_standby",
1004                "this box is a STANDBY (replication.json) — direct client pushes are refused; \
1005                 only the replication push from its primary writes. `gunnar control replication \
1006                 promote` makes it a writable primary."
1007            );
1008        }
1009
1010        if twin {
1011            // Before any repository of the twin opens: the engine keeps no derived memo (C2)
1012            // and no exploded read cache, and resolves a pack narrow enough for the box (C1 +
1013            // the twin memory bound). Both are process-wide, and both used to be cmdline
1014            // tokens on a medium that no longer exists.
1015            engine.hold_no_graph_memo();
1016            engine.hold_twin_memory_bound();
1017        }
1018        // In the control database's own table; each flush that moved something is
1019        // ONE `Activity` frame on a box that originates its log (the twin's copy),
1020        // nothing framed on a follower. The old JSON file is read once and left.
1021        let activity = Arc::new(gunnar_core::PrincipalActivity::open(
1022            Arc::clone(&control_db),
1023            Some(control_dir.join(gunnar_core::ACTIVITY_FILE)),
1024            Some(Arc::clone(&txlog)),
1025        ));
1026        // Flushed every FLUSH_EVERY by a jera job that ends with the record (A32-14); one that
1027        // cannot start is said, and the record's drop still writes the last stamps.
1028        if let Err(e) = start_activity_flush(&activity, gunnar_core::activity::FLUSH_EVERY) {
1029            tracing::error!("ALERT {ACTIVITY_FLUSH} no flush ({e}): the last-seen stamps are written when the record is dropped only");
1030        }
1031        let stores = ServerStores {
1032            identity: std::sync::OnceLock::new(),
1033            root,
1034            repos_root,
1035            control_dir,
1036            activity,
1037            engine,
1038            secrets,
1039            legacy_secrets,
1040            kek: std::sync::RwLock::new(kek),
1041            control_store,
1042            control_db,
1043            suspended: AtomicBool::new(false),
1044            raw_control_store,
1045            raw_secrets,
1046            txlog,
1047            twin: Arc::new(AtomicBool::new(twin)),
1048            auth,
1049            catalog,
1050            policies,
1051            mirrors,
1052            flow,
1053            usage: Arc::new(crate::usage_ledger::UsageLedger::new()),
1054            metrics: Arc::new(gunnar_core::observe::ServerMetrics::new()),
1055            account_audit,
1056            names,
1057            settings,
1058            encryption_keys,
1059            open: Mutex::new(HandleCache::new(capacity)),
1060            last_reclaim_probe: Mutex::new(None),
1061            writes_frozen: Arc::new(AtomicBool::new(frozen_at_open || twin)),
1062            browse: Arc::new(AtomicBool::new(role_at_open.is_browse() || twin)),
1063            store_opens: Arc::new(AtomicU64::new(0)),
1064            slow,
1065            install,
1066            plan_gates: std::sync::RwLock::new(Vec::new()),
1067            space: std::sync::RwLock::new(None),
1068            fed_keys: std::sync::RwLock::new(std::collections::BTreeMap::new()),
1069            snapshot_pins: SnapshotPins::default(),
1070        };
1071        // **The flow tells the usage ledger** which namespaces moved: their
1072        // `*_today` meters changed, and a transfer is what grows a repository.
1073        {
1074            let usage = Arc::clone(&stores.usage);
1075            stores
1076                .flow
1077                .observe(gunnar_core::FlowObserver(Arc::new(move |ns: &str| {
1078                    usage.mark_flow(ns)
1079                })));
1080        }
1081        // The identity half of the metadata mirror, taken once at open so a box
1082        // that has not enrolled anybody since its last boot still has a current
1083        // copy off the stripe. The mutating verbs refresh it; see
1084        // `ServerStores::mirror_identity`.
1085        stores.mirror_identity();
1086        // **The audit trail, checked against the log it came from** — on EVERY open of a box
1087        // that originates its log, before `serve` opens it for the gate (lane T11; every start
1088        // since T17). The window it closes: `AuditChain::append` syncs the frame, then writes the
1089        // line; a primary that crashes between the two comes back with the log one entry ahead,
1090        // and the gate would frame a second entry at an existing seq. See
1091        // `crate::twin::rematerialise_audit_trail`.
1092        if !twin && !restoring {
1093            crate::twin::rematerialise_audit_trail(&stores, just_restored);
1094        }
1095        // A twin keeps no per-box mirror, including one a fresh box wrote before it became a twin.
1096        if stores.is_twin() {
1097            crate::twin::forget_mirrors(&stores);
1098            crate::twin::say_if_stores_were_applied(&stores);
1099        }
1100        Ok(stores)
1101    }
1102
1103    /// **Say which fed keys this box will enrol and has not yet** — the whole
1104    /// set, replacing the last (`crate::fed_principals::note_fed`).
1105    pub fn await_enrolment(&self, keys: std::collections::BTreeMap<String, String>) {
1106        *self.fed_keys.write().unwrap_or_else(|p| p.into_inner()) = keys;
1107    }
1108
1109    /// The fed key under `fingerprint` this box will enrol and has not yet, if
1110    /// any ([`ServerStores::await_enrolment`]).
1111    pub fn awaiting_enrolment(&self, fingerprint: &str) -> Option<String> {
1112        self.fed_keys
1113            .read()
1114            .unwrap_or_else(|p| p.into_inner())
1115            .get(fingerprint)
1116            .cloned()
1117    }
1118
1119    pub fn root(&self) -> &Path {
1120        &self.root
1121    }
1122
1123    /// The identity core of this box, once the server built it.
1124    pub fn identity(&self) -> Option<std::sync::Arc<gunnar_grpc::identity::GunnarIdentity>> {
1125        self.identity.get().and_then(std::sync::Weak::upgrade)
1126    }
1127
1128    /// Hand the box's identity core to the paths outside a gRPC context (once;
1129    /// a second hand-over is ignored: one core per box). Held weakly: the
1130    /// caller keeps the core alive (the server's context does).
1131    pub fn set_identity(&self, identity: &std::sync::Arc<gunnar_grpc::identity::GunnarIdentity>) {
1132        let _ = self.identity.set(std::sync::Arc::downgrade(identity));
1133    }
1134
1135    /// **The slow disk** this server writes its off-stripe copies to.
1136    ///
1137    /// Always present. See `crate::slow` for what goes there and for the
1138    /// three-valued claim over it.
1139    pub fn slow(&self) -> &crate::slow::SlowRoot {
1140        &self.slow
1141    }
1142
1143    /// **What the installer decided**, or the sentence saying there is no
1144    /// config. Read once at open; see the field's documentation.
1145    pub fn layout_config(&self) -> &crate::layout_config::Load {
1146        &self.install
1147    }
1148
1149    /// **Where the control-plane audit trail lives**: `<slow>/audit/` — one of
1150    /// the three copies that must be on another failure domain.
1151    ///
1152    /// It used to be `<control dir>/audit-chain.jsonl`, on the stripe with the
1153    /// repositories whose history it records. An existing chain is ADOPTED into
1154    /// the new place once, on the first boot of a build that knows about the
1155    /// slow disk (`slow::adopt_file`: copy, fsync, unlink — `rename` answers
1156    /// `EXDEV` across devices, which is exactly the case that matters). If the
1157    /// move cannot be made the old path is returned unchanged and the server
1158    /// keeps writing the trail where it already is.
1159    ///
1160    /// **On a twin, or on a box mid-restore, it is a DIFFERENT file**
1161    /// (`audit-chain.local.jsonl`, [`gunnar_core::txlog::AUDIT_LOCAL_REL`]).
1162    /// Such a box holds the primary's trail as replicated state and must
1163    /// originate nothing into it: its own gate decisions — who browsed it, who
1164    /// was refused — are its own, and interleaving them into a hash chain that
1165    /// has exactly one writer would break every `prev` after the splice. The
1166    /// twin's own trail stays on the twin and is never sent anywhere.
1167    pub fn audit_path(&self) -> std::path::PathBuf {
1168        // The name is decided by the same two facts that decide whether the log originates at
1169        // all (`ServerStores::open`: a twin or a restoring box is a follower and registers no
1170        // sink), so the trail and the log can never disagree about which box this is.
1171        if self.is_twin() || crate::twin::is_restoring(&self.root) {
1172            let local = std::path::Path::new(gunnar_core::txlog::AUDIT_LOCAL_REL)
1173                .file_name()
1174                .expect("a file name")
1175                .to_owned();
1176            return match self.slow.log_dir() {
1177                Ok(dir) => dir.join(local),
1178                Err(_) => self.control_dir.join(local),
1179            };
1180        }
1181        let old = self.control_dir.join(gunnar_core::AUDIT_FILE);
1182        match self.slow.log_dir() {
1183            Ok(dir) => crate::slow::adopt_file(&old, &dir.join(gunnar_core::AUDIT_FILE)),
1184            Err(err) => {
1185                tracing::warn!(
1186                    target: crate::slow::TARGET_SLOW,
1187                    %err,
1188                    path = %old.display(),
1189                    "no audit directory on the slow disk; the audit trail stays on /data, where \
1190                     it shares a failure domain with the repositories it records"
1191                );
1192                old
1193            }
1194        }
1195    }
1196
1197    /// **The identity half of the metadata mirror**: every principal and every
1198    /// enrolled public key, as one JSON document off the stripe.
1199    ///
1200    /// Public material only — a fingerprint, an `authorized_keys` line, a
1201    /// principal's id and name. No secret in this file, ever: the secrets are
1202    /// sealed in `control.redb` under a KEK that is a separate file, and a
1203    /// mirror that carried them would make the slow disk a second place to
1204    /// steal them from.
1205    ///
1206    /// Best effort, and deliberately so at every call site: this runs after a
1207    /// principal or a key has ALREADY been written to the control store, and
1208    /// failing the verb because the mirror could not be refreshed would turn a
1209    /// full slow disk into an outage of the identity system. A failure is one
1210    /// WARN naming the path.
1211    pub fn mirror_identity(&self) {
1212        // A twin keeps no mirror of its own: its identity table is a replica,
1213        // and a derived per-box copy on its disk is exactly the cache the twin
1214        // must not hold.
1215        if self.is_twin() {
1216            return;
1217        }
1218        if let Err(err) = self.try_mirror_identity() {
1219            tracing::warn!(
1220                target: crate::slow::TARGET_SLOW,
1221                %err,
1222                "the identity metadata mirror could not be refreshed; the control store itself \
1223                 is unaffected"
1224            );
1225        }
1226    }
1227
1228    /// **The storage reality of this machine**, for `Admin.StorageInfo`.
1229    ///
1230    /// Three layers that are kept apart because they age differently: what the
1231    /// installer DECIDED (historical, from the record), what is TRUE NOW (the
1232    /// configured filesystems, read here), and what gunnar is CONFIGURED to do
1233    /// (the placement table as built). One artifact behind the first and third
1234    /// — `crate::layout_config` and `crate::slow` — so the console and the
1235    /// placement code cannot drift into two views of the same facts.
1236    ///
1237    /// **Nothing here surveys the machine.** The only paths measured are the
1238    /// two gunnar was told to use; no mount table is walked, no device is
1239    /// enumerated, and the installer's decisions are never inferred from what
1240    /// happens to be mounted now. A record that is missing is reported as
1241    /// missing.
1242    pub fn storage_reality(&self) -> gunnar_proto::StorageReality {
1243        let mut out = gunnar_proto::StorageReality {
1244            data_root: self.root.display().to_string(),
1245            slow_root: self.slow.serialdat().to_owned(),
1246            slow_root_source: self.slow.source().word().to_owned(),
1247            backing_device: self.slow.device().to_owned(),
1248            backing_class: self.slow.class().to_owned(),
1249            off_stripe: self.slow.claim().word().to_owned(),
1250            off_stripe_health: self.slow.health(),
1251            ..Default::default()
1252        };
1253        // ── 1. what the installer decided ──────────────────────────────────
1254        match self.install.config() {
1255            Some(config) => {
1256                out.record_present = true;
1257                out.record_path = config.path().display().to_string();
1258                out.record_version = config.version();
1259                // **The third state, said in the installer's own two words.**
1260                // `INTEGRITY ONLY` is what every appliance built today is, and
1261                // it is never rendered as verified.
1262                out.record_signature = config.authenticity().word().to_owned();
1263                out.record_signature_verified = config.authenticity().is_verified();
1264                out.record_signature_note = config.note().to_owned();
1265                out.record_fields = config
1266                    .fields()
1267                    .map(|(key, value)| gunnar_proto::InstallRecordField {
1268                        key: key.to_owned(),
1269                        value: value.to_owned(),
1270                    })
1271                    .collect();
1272            }
1273            None => {
1274                out.record_absent_reason = self
1275                    .install
1276                    .absent_reason()
1277                    .unwrap_or("there is no layout config")
1278                    .to_owned();
1279            }
1280        }
1281        // ── 2. what is true now ────────────────────────────────────────────
1282        //
1283        // Only the paths gunnar was TOLD to use, measured at the moment of the
1284        // call. No mount table is walked and no device is enumerated: a
1285        // filesystem gunnar was not configured with is not this call's to
1286        // report on.
1287        let mut measured: Vec<(&str, PathBuf)> = vec![("data root", self.root.clone())];
1288        for p in crate::slow::PLACEMENT
1289            .iter()
1290            .filter(|p| p.requires_off_stripe)
1291        {
1292            let path = self.slow.path_of(p.dir);
1293            if !measured.iter().any(|(_, seen)| *seen == path) {
1294                measured.push(("configured directory", path));
1295            }
1296        }
1297        out.filesystems = measured
1298            .iter()
1299            .map(|(what, path)| filesystem_use(what, path))
1300            .collect();
1301        // ── 3. what gunnar is configured to do ─────────────────────────────
1302        out.placement = crate::slow::PLACEMENT
1303            .iter()
1304            .map(|p| gunnar_proto::PlacementRow {
1305                what: p.what.to_owned(),
1306                path: self.slow.path_of(p.dir).display().to_string(),
1307                requires_off_stripe: p.requires_off_stripe,
1308                // The verdict is carried ONLY on the rows that need it, and it
1309                // is the config's per-directory answer rather than one summary
1310                // painted across every row. An empty string on a row that does
1311                // not require it is the honest shape; painting "off-stripe" on
1312                // git's own objects would suggest a guarantee nobody made.
1313                off_stripe: if p.requires_off_stripe {
1314                    self.slow.claim_of(p.dir).word().to_owned()
1315                } else {
1316                    String::new()
1317                },
1318                wired: p.wired,
1319                note: p.note.to_owned(),
1320            })
1321            .collect();
1322        // ── /data's own shape, and the machine at a glance (2026-10-04) ────
1323        //
1324        // `/data`'s devices come from the installer's `data.*` keys and from
1325        // nothing else; `backing_*` above are `/serialdat`'s and stay so.
1326        let config = self.install.config();
1327        if let Some(config) = config {
1328            out.data_shape = config.get("data.shape").unwrap_or_default().to_owned();
1329            out.data_devices = (0..config.count("data"))
1330                .filter_map(|i| config.get(&format!("data.{i}.dev")).map(str::to_owned))
1331                .collect();
1332        }
1333        let data_label = config
1334            .and_then(|c| c.get("data.mountpoint"))
1335            .map(str::to_owned)
1336            .unwrap_or_else(|| out.data_root.clone());
1337        let serialdat_label = config
1338            .and_then(|c| c.get("serialdat.mountpoint"))
1339            .map(str::to_owned)
1340            .unwrap_or_else(|| out.slow_root.clone());
1341        let disk = crate::disktest::last();
1342        let data_fs = out
1343            .filesystems
1344            .iter()
1345            .find(|f| f.what == "data root")
1346            .cloned();
1347        out.glance = crate::glance::lines(&crate::glance::Facts {
1348            record_present: out.record_present,
1349            data_label: &data_label,
1350            data_shape: &out.data_shape,
1351            data_devices: &out.data_devices,
1352            serialdat_label: &serialdat_label,
1353            serialdat_class: &out.backing_class,
1354            serialdat_device: &out.backing_device,
1355            off_stripe: &out.off_stripe,
1356            off_stripe_health: &out.off_stripe_health,
1357            data_fs: data_fs.as_ref(),
1358            disk: disk.as_ref(),
1359        });
1360        out
1361    }
1362
1363    fn try_mirror_identity(&self) -> Result<()> {
1364        let principals = self.auth.principals().context("listing principals")?;
1365        let keys = self.auth.keys().context("listing enrolled keys")?;
1366        let written_unix_ms = std::time::SystemTime::now()
1367            .duration_since(std::time::UNIX_EPOCH)
1368            .map(|d| d.as_millis() as i64)
1369            .unwrap_or_default();
1370        let doc = serde_json::json!({
1371            "written_unix_ms": written_unix_ms,
1372            "principals": principals,
1373            "keys": keys,
1374        });
1375        let bytes = serde_json::to_vec_pretty(&doc).context("encoding the identity mirror")?;
1376        let dir = self.slow.meta_dir()?;
1377        crate::durable::write_atomic_unframed(&dir, IDENTITY_MIRROR, &bytes)
1378    }
1379
1380    /// The storage engine this process is running.
1381    pub fn engine(&self) -> crate::storage::Engine {
1382        self.engine
1383    }
1384
1385    /// Where served repositories live.
1386    pub fn repos_root(&self) -> &Path {
1387        &self.repos_root
1388    }
1389
1390    /// The identity table (the ACL model).
1391    /// **Who signed in and who changed something, and when** (2026-10-21) —
1392    /// the stamps `Access.ListPrincipals` answers beside each principal.
1393    pub fn activity(&self) -> &Arc<gunnar_core::PrincipalActivity> {
1394        &self.activity
1395    }
1396
1397    pub fn auth(&self) -> &AuthTable {
1398        &self.auth
1399    }
1400
1401    /// The repository catalog.
1402    pub fn catalog(&self) -> &RepoCatalog {
1403        &self.catalog
1404    }
1405
1406    /// Per-repository policy documents (`refs/gunnar/policy`).
1407    ///
1408    /// The **one** home for branch protection and ref-name policy since
1409    /// `Policy.*` stopped answering `Unimplemented`. `gunnar-policy.json`
1410    /// beside a repository is still read as a fallback, and
1411    /// `transport::load_policy` says why and for how long.
1412    pub fn policies(&self) -> &gunnar_core::PolicyStore {
1413        &self.policies
1414    }
1415
1416    /// Pull-mirror registrations (`refs/gunnar/mirrors`).
1417    ///
1418    /// The server's own registry, reachable over `Mirror.*`. Not the same thing
1419    /// as `gunnar-client`'s `mirrors.json`, which is the pull-mirror *client's*
1420    /// state on a host running `gunnar mirror`.
1421    pub fn mirrors(&self) -> &gunnar_core::MirrorStore {
1422        &self.mirrors
1423    }
1424
1425    /// **The flow ledger**: what moved, per namespace, per UTC day.
1426    ///
1427    /// Handed out as an `Arc` because its holders outlive any one borrow — the
1428    /// transfer path keeps a clone for the length of a transfer, the flush tick
1429    /// keeps one for the length of the process — and because every holder must
1430    /// share the one set of live atomics. See the field.
1431    /// **Every account's audit log** — read only by each account's admins
1432    /// (`Enterprise.AuditLog`), written by the control plane's handlers.
1433    pub fn account_audit(&self) -> &Arc<gunnar_core::account_audit::AccountAuditLog> {
1434        &self.account_audit
1435    }
1436
1437    /// **The name filter** — its lists and the accounts' review queues.
1438    pub fn names(&self) -> &gunnar_core::name_filter::NameFilterStore {
1439        &self.names
1440    }
1441
1442    /// **People's encryption keys** (`Access.GetEncryptionKey` and friends, `Repos.RecipientKeys`).
1443    pub fn encryption_keys(&self) -> &gunnar_core::encryption_key::EncryptionKeys {
1444        &self.encryption_keys
1445    }
1446
1447    /// **The generic server settings** (`Admin.GetSetting` / `Admin.SetSetting`).
1448    pub fn settings(&self) -> &gunnar_core::settings::SettingsStore {
1449        &self.settings
1450    }
1451
1452    pub fn usage_ledger(&self) -> &Arc<crate::usage_ledger::UsageLedger> {
1453        &self.usage
1454    }
1455
1456    /// The server's one set of counters (see the field).
1457    pub fn metrics(&self) -> &Arc<gunnar_core::observe::ServerMetrics> {
1458        &self.metrics
1459    }
1460
1461    pub fn flow(&self) -> &Arc<gunnar_core::FlowLedger> {
1462        &self.flow
1463    }
1464
1465    /// **Pin the stores for a snapshot streamed from a cut** (R5.1-A, 2026-10-07): until the
1466    /// guard drops, [`ServerStores::wait_unpinned`] holds back a gc, a repository store's removal
1467    /// and an LFS object's removal — the objects reachable from the cut's tips, the stores it
1468    /// names and the LFS objects it lists stay where the stream will read them. Take it BEFORE the
1469    /// log's freeze; the ones who wait take it before their own mutation guard, so a freeze can
1470    /// never wait on a thread that waits on a pin.
1471    pub fn snapshot_pin(&self) -> SnapshotPin<'_> {
1472        *self
1473            .snapshot_pins
1474            .count
1475            .lock()
1476            .unwrap_or_else(|p| p.into_inner()) += 1;
1477        SnapshotPin {
1478            pins: &self.snapshot_pins,
1479        }
1480    }
1481
1482    /// **Wait while a snapshot streams from a cut** ([`ServerStores::snapshot_pin`]) — at most
1483    /// [`SNAPSHOT_PIN_WAIT`], after which the caller goes on and that snapshot fails at the piece
1484    /// that needed what was removed (the twin asks again; it never installs half). `what` names the
1485    /// caller in the line said while it waits. Called BEFORE any mutation guard.
1486    pub fn wait_unpinned(&self, what: &str) {
1487        let pins = &self.snapshot_pins;
1488        let mut n = pins.count.lock().unwrap_or_else(|p| p.into_inner());
1489        if *n == 0 {
1490            return;
1491        }
1492        tracing::info!(target: "gunnar::store", what, snapshots = *n, "a snapshot is streaming from its cut: {what} waits for it");
1493        let deadline = std::time::Instant::now() + SNAPSHOT_PIN_WAIT;
1494        while *n > 0 {
1495            let left = deadline.saturating_duration_since(std::time::Instant::now());
1496            if left.is_zero() {
1497                tracing::warn!(target: "gunnar::store", what, "a snapshot still streams after {} s: {what} goes on; that snapshot fails and is asked for again", SNAPSHOT_PIN_WAIT.as_secs());
1498                return;
1499            }
1500            n = pins
1501                .cv
1502                .wait_timeout(n, left)
1503                .unwrap_or_else(|p| p.into_inner())
1504                .0;
1505        }
1506    }
1507
1508    /// The catalog and the identity table, as one store (the certificate-identity plan).
1509    /// The transaction log — what the twin fetches and what a restore replays.
1510    pub fn txlog(&self) -> &Arc<gunnar_core::txlog::Log> {
1511        &self.txlog
1512    }
1513
1514    /// **Is this box a twin right now?** Set at open from `twin.json`, and by
1515    /// [`ServerStores::mark_twin`] the moment `Bootstrap.BecomeTwin` confers
1516    /// the role on a running box. NOT decided once, whatever this comment used
1517    /// to say.
1518    pub fn is_twin(&self) -> bool {
1519        self.twin.load(std::sync::atomic::Ordering::SeqCst)
1520    }
1521
1522    /// **The shared twin flag**, for the front door — the same `Arc`
1523    /// [`ServerStores::mark_twin`] writes, so a box conferred the twin role
1524    /// over the wire refuses git from that instant instead of from the next
1525    /// restart. See `gunnar_ssh::Control::with_twin_flag`.
1526    pub fn twin_flag(&self) -> Arc<AtomicBool> {
1527        Arc::clone(&self.twin)
1528    }
1529
1530    /// From now on this box is a twin (`crate::twin::become_twin`).
1531    pub fn mark_twin(&self) {
1532        self.twin.store(true, std::sync::atomic::Ordering::SeqCst);
1533        // No derived memo on a twin's disk from the next store open on (C2), no exploded read
1534        // cache and a resolver narrow enough for the box (C1 + the twin memory bound). This is
1535        // the runtime half that made the five `korp.env.ZNIPPY_*` tokens retirable, so a twin
1536        // needs nothing on its command line.
1537        self.engine.hold_no_graph_memo();
1538        self.engine.hold_twin_memory_bound();
1539        // A setter governs the NEXT open, so the stores this box already holds — it came up a
1540        // primary, which is what one medium means — are swept by hand.
1541        let freed = self.engine.bound_open_stores_to_twin();
1542        if freed > 0 {
1543            tracing::info!(
1544                target: gunnar_core::observe::TARGET_TWIN,
1545                bytes = freed,
1546                "unlinked the exploded read cache of the repositories this box already held: a twin holds none"
1547            );
1548        }
1549    }
1550
1551    /// The sealed secret store over the UNLOGGED half: what a twin reads its
1552    /// replicated host key through (a twin frames nothing).
1553    pub fn secrets_unframed(
1554        &self,
1555    ) -> Result<gunnar_core::SealedSecretStore<std::sync::Arc<dyn gunnar_store::SecretStore>>> {
1556        Ok(gunnar_core::SealedSecretStore::new(
1557            Arc::clone(&self.raw_secrets),
1558            self.kek(),
1559        ))
1560    }
1561
1562    fn kek(&self) -> gunnar_core::Kek {
1563        self.kek
1564            .read()
1565            .unwrap_or_else(std::sync::PoisonError::into_inner)
1566            .clone()
1567    }
1568
1569    /// **Hold `bytes` as this process's KEK** (S9): what a follower does with a `Kek` frame
1570    /// once the key file is durable, so the sealed rows it holds open from now on.
1571    pub fn adopt_kek(&self, bytes: &[u8]) -> Result<()> {
1572        let key: [u8; 32] = bytes
1573            .try_into()
1574            .map_err(|_| anyhow::anyhow!("a KEK carries {} bytes, not 32", bytes.len()))?;
1575        *self
1576            .kek
1577            .write()
1578            .unwrap_or_else(std::sync::PoisonError::into_inner) = gunnar_core::Kek::from_bytes(key);
1579        Ok(())
1580    }
1581
1582    /// The KEK this process holds, as bytes — a snapshot's `Kek` item when no key file exists
1583    /// (the key was handed in by the environment).
1584    pub fn kek_bytes(&self) -> Vec<u8> {
1585        hex::decode(self.kek().to_hex()).expect("a KEK's hex decodes")
1586    }
1587
1588    /// **The control store with no log in front of it** — the twin applies
1589    /// the primary's `ControlBlob` / `ControlDoc` frames here, and nothing
1590    /// else writes here.
1591    pub fn raw_control_store(&self) -> &Arc<dyn ControlStore> {
1592        &self.raw_control_store
1593    }
1594
1595    /// **The secret store with no log in front of it** — the twin's
1596    /// `Secret` frames land here as the sealed bytes they are.
1597    pub fn raw_secrets(&self) -> &Arc<dyn gunnar_store::SecretStore> {
1598        &self.raw_secrets
1599    }
1600
1601    pub fn control_store(&self) -> &Arc<dyn ControlStore> {
1602        &self.control_store
1603    }
1604
1605    /// The redb handle under the control store — see the field.
1606    pub fn control_db(&self) -> Arc<gunnar_core::ControlDb> {
1607        Arc::clone(&self.control_db)
1608    }
1609
1610    /// Are the repository stores closed for a growth?
1611    pub fn suspended(&self) -> bool {
1612        self.suspended.load(std::sync::atomic::Ordering::SeqCst)
1613    }
1614
1615    /// **Close every repository store for the runtime growth** (`crate::grow`,
1616    /// `DATA-SET-GROWTH-FLOW.md` G6): from here until [`Self::resume_repos`]
1617    /// `repo_store` refuses with `why`, the handle cache is emptied and the
1618    /// engines release what they cached — the packs' mmaps, the redb tails,
1619    /// the descriptors that would otherwise pin `/data`. A store still held
1620    /// by an in-flight request (there are none: the drain finished first)
1621    /// drops when that request returns.
1622    pub fn suspend_repos(&self, why: &str) {
1623        self.suspended
1624            .store(true, std::sync::atomic::Ordering::SeqCst);
1625        let dropped = {
1626            let mut cache = self.cache();
1627            let n = cache.entries.len();
1628            cache.entries.clear();
1629            n
1630        };
1631        crate::storage::shutdown();
1632        tracing::warn!(
1633            target: "gunnar::store",
1634            event = "store.suspended",
1635            dropped,
1636            why,
1637            "every repository store is closed and opens are refused: {why}"
1638        );
1639    }
1640
1641    /// The stores may open again (lazily, on the next request), after the
1642    /// growth mounted `/data` back.
1643    pub fn resume_repos(&self) {
1644        // The data set was unmounted and is back, perhaps grown: every reading
1645        // the usage ledger holds is re-taken.
1646        self.usage.mark_all();
1647        if self
1648            .suspended
1649            .swap(false, std::sync::atomic::Ordering::SeqCst)
1650        {
1651            tracing::info!(target: "gunnar::store", event = "store.resumed", "repository stores open again on demand");
1652        }
1653    }
1654
1655    /// Where the KEK and the legacy Arrow secret log live. See [`CONTROL_DIR`].
1656    ///
1657    /// `control()` used to be here — the one accessor on this type that opened
1658    /// a repository, and the reason the server needed a storage engine to boot.
1659    /// There is no control repository any more, so there is no accessor for one.
1660    pub fn control_dir(&self) -> &Path {
1661        &self.control_dir
1662    }
1663
1664    /// **The server's secret store, sealed.**
1665    ///
1666    /// Everything on the boot path must go through this rather than through the
1667    /// raw handle: the raw handle writes plaintext, and the SSH host key is the
1668    /// one secret whose whole purpose is to be persisted. The decorator is the
1669    /// only thing standing between a private key and a file designed to be
1670    /// copied off the machine — and now that the store is a table in
1671    /// `control.redb`, "the file designed to be copied off the machine" is the
1672    /// same file the catalog is in.
1673    ///
1674    /// Still `Result`, and deliberately: the signature is what every caller on
1675    /// the boot path is written against, and the store behind it may yet be one
1676    /// that can fail to open (`VaultSecretStore` is still noted-not-built). It
1677    /// no longer opens anything.
1678    /// # And what it does with a value that is not sealed
1679    ///
1680    /// It refuses it, unless [`Self::legacy_secrets`] says a pre-sealing
1681    /// `secrets.arrow` is on this disk. That is not belt-and-braces: reading an
1682    /// unsealed value through is a way past the seal that needs no KEK at all,
1683    /// so anything that can write `control.redb` — a restored backup, a tampered
1684    /// cold-tier archive, a replica's copied file — could put its own SSH host
1685    /// key in the slot and gunnar would serve it. Only the machine that has the
1686    /// old log has a legitimate unsealed value to read, and only that machine
1687    /// gets the policy that reads one.
1688    ///
1689    /// [`Self::legacy_secrets`]: ServerStores::legacy_secrets
1690    pub fn secrets(
1691        &self,
1692    ) -> Result<gunnar_core::SealedSecretStore<std::sync::Arc<dyn gunnar_store::SecretStore>>> {
1693        let inner = Arc::clone(&self.secrets);
1694        Ok(if self.legacy_secrets {
1695            gunnar_core::SealedSecretStore::migrating(inner, self.kek())
1696        } else {
1697            gunnar_core::SealedSecretStore::new(inner, self.kek())
1698        })
1699    }
1700
1701    /// **The transparency log's signing key**, minting one on first use.
1702    ///
1703    /// Its own key and not the issuer's: the issuer says who somebody *is*, and
1704    /// this says what the log *held*. One key for both would mean compromising
1705    /// the log's signer also mints administrators, and would make revoking one
1706    /// job impossible without revoking the other.
1707    ///
1708    /// Atomic across racing callers, exactly as the issuer key and the host key
1709    /// are: two heads issued at once produce one key, not two.
1710    pub fn transparency_key(&self) -> Result<gunnar_core::ssh_key::PrivateKey> {
1711        use gunnar_store::SecretStoreExt as _;
1712        let secrets = self.secrets()?;
1713        let bytes = secrets
1714            .get_or_create_with(gunnar_store::TRANSPARENCY_LOG_KEY, || {
1715                tracing::info!(
1716                    key = gunnar_store::TRANSPARENCY_LOG_KEY,
1717                    "no transparency-log signing key stored; minting one. It is sealed under the \
1718                     KEK, and its public half is what a verifier pins to check a signed tree head"
1719                );
1720                gunnar_core::mint_ed25519()
1721                    .map_err(|err| gunnar_store::Error::backend(format!("{err}")))
1722            })
1723            .context("reading the transparency log's signing key")?;
1724        let pem = String::from_utf8(bytes)
1725            .context("the stored transparency-log key is not utf-8 OpenSSH PEM")?;
1726        gunnar_core::ssh_key::PrivateKey::from_openssh(&pem)
1727            .context("parsing the transparency log's signing key")
1728    }
1729
1730    /// The transparency log over this server's push attestations.
1731    pub fn transparency(&self) -> crate::attest::TransparencyLog {
1732        crate::attest::TransparencyLog::under(&self.root)
1733    }
1734
1735    /// The transparency log over this server's **build** records.
1736    ///
1737    /// The same machinery over a different file: a build record and a push
1738    /// attestation are different shapes with different readers, and mixing them
1739    /// into one file would break every reader of the other.
1740    pub fn build_log(&self) -> crate::attest::TransparencyLog {
1741        crate::attest::TransparencyLog::over(
1742            self.root.join(crate::attest::BUILD_LOG),
1743            self.root.join(crate::attest::BUILD_HEADS),
1744        )
1745    }
1746
1747    /// The transparency log over this server's **forge** events.
1748    ///
1749    /// Issues, reviews and merges, each a row signed by the principal that did
1750    /// it — so an approval is evidence in the same sense a signed commit is,
1751    /// and not the server's word for it.
1752    pub fn forge_log(&self) -> crate::attest::TransparencyLog {
1753        crate::attest::TransparencyLog::over(
1754            self.root.join(crate::attest::FORGE_LOG),
1755            self.root.join(crate::attest::FORGE_HEADS),
1756        )
1757    }
1758
1759    /// The transparency log over this server's **group-membership** changes.
1760    ///
1761    /// The same machinery over a different file: each line is an add or remove
1762    /// signed by the acting admin's own key, so who was in a group at any time
1763    /// is evidence a third party can check and not the server's word. The live
1764    /// membership table ([`gunnar_core::AuthTable`]) stays the authority the SSH
1765    /// listener resolves grants through; this is the durable, signed record of
1766    /// how it came to say what it says.
1767    pub fn membership_log(&self) -> crate::attest::TransparencyLog {
1768        crate::attest::TransparencyLog::over(
1769            self.root.join(crate::attest::MEMBERSHIP_LOG),
1770            self.root.join(crate::attest::MEMBERSHIP_HEADS),
1771        )
1772    }
1773
1774    /// **The builder's provenance signing key**, minting one on first use.
1775    ///
1776    /// A third key beside the issuer's and the log's, because it is a third
1777    /// job — and because a runner on its own host needs a key of its own that
1778    /// revoking the log's signer does not take with it.
1779    pub fn provenance_key(&self) -> Result<gunnar_core::ssh_key::PrivateKey> {
1780        use gunnar_store::SecretStoreExt as _;
1781        let secrets = self.secrets()?;
1782        let bytes = secrets
1783            .get_or_create_with(gunnar_store::PROVENANCE_KEY, || {
1784                tracing::info!(
1785                    key = gunnar_store::PROVENANCE_KEY,
1786                    "no provenance signing key stored; minting one. Its public half is what a \
1787                     verifier pins to check a build record"
1788                );
1789                gunnar_core::mint_ed25519()
1790                    .map_err(|err| gunnar_store::Error::backend(format!("{err}")))
1791            })
1792            .context("reading the provenance signing key")?;
1793        let pem = String::from_utf8(bytes)
1794            .context("the stored provenance key is not utf-8 OpenSSH PEM")?;
1795        gunnar_core::ssh_key::PrivateKey::from_openssh(&pem)
1796            .context("parsing the provenance signing key")
1797    }
1798
1799    /// **The outbound webhook signing key**, minting one on first use.
1800    ///
1801    /// A fourth key beside the issuer's, the log's and the builder's, because a
1802    /// delivery signature is a fourth job: it says "this event body came from
1803    /// this server". Its PUBLIC half is what a webhook receiver pins and checks
1804    /// each delivery against with `ssh-keygen -Y verify` — no shared secret, so
1805    /// a leaked delivery URL is not a leaked signing key. Sealed under the KEK
1806    /// and atomic across racing callers, exactly as the keys above are.
1807    pub fn webhook_key(&self) -> Result<gunnar_core::ssh_key::PrivateKey> {
1808        use gunnar_store::SecretStoreExt as _;
1809        let secrets = self.secrets()?;
1810        let bytes = secrets
1811            .get_or_create_with(gunnar_store::WEBHOOK_KEY, || {
1812                tracing::info!(
1813                    key = gunnar_store::WEBHOOK_KEY,
1814                    "no webhook signing key stored; minting one. Its public half is what a \
1815                     receiver pins to verify a delivery"
1816                );
1817                gunnar_core::mint_ed25519()
1818                    .map_err(|err| gunnar_store::Error::backend(format!("{err}")))
1819            })
1820            .context("reading the webhook signing key")?;
1821        let pem =
1822            String::from_utf8(bytes).context("the stored webhook key is not utf-8 OpenSSH PEM")?;
1823        gunnar_core::ssh_key::PrivateKey::from_openssh(&pem)
1824            .context("parsing the webhook signing key")
1825    }
1826
1827    /// **The forge-attestation key**, minting one on first use (GHUNT-19):
1828    /// what gunnar signs a person's forge event with when it came from their
1829    /// stepped-up session ([`gunnar_store::FORGE_ATTEST_KEY`]). Sealed under the
1830    /// KEK and atomic across racing callers, exactly as the keys above are.
1831    pub fn forge_attest_key(&self) -> Result<gunnar_core::ssh_key::PrivateKey> {
1832        use gunnar_store::SecretStoreExt as _;
1833        let secrets = self.secrets()?;
1834        let bytes = secrets
1835            .get_or_create_with(gunnar_store::FORGE_ATTEST_KEY, || {
1836                tracing::info!(
1837                    key = gunnar_store::FORGE_ATTEST_KEY,
1838                    "no forge-attestation key stored; minting one. It signs a person's forge \
1839                     event made from a session that stepped up"
1840                );
1841                gunnar_core::mint_ed25519()
1842                    .map_err(|err| gunnar_store::Error::backend(format!("{err}")))
1843            })
1844            .context("reading the forge-attestation key")?;
1845        let pem = String::from_utf8(bytes)
1846            .context("the stored forge-attestation key is not utf-8 OpenSSH PEM")?;
1847        gunnar_core::ssh_key::PrivateKey::from_openssh(&pem)
1848            .context("parsing the forge-attestation key")
1849    }
1850
1851    /// The forge-attestation key's PUBLIC half, if one was ever minted — read
1852    /// without minting, so a reader (a twin included) never writes a secret.
1853    pub fn forge_attest_public(&self) -> Result<Option<gunnar_core::ssh_key::PublicKey>> {
1854        use gunnar_store::SecretStore as _;
1855        let secrets = self.secrets()?;
1856        let Some(bytes) = secrets
1857            .get(gunnar_store::FORGE_ATTEST_KEY)
1858            .context("reading the forge-attestation key")?
1859        else {
1860            return Ok(None);
1861        };
1862        let pem = String::from_utf8(bytes)
1863            .context("the stored forge-attestation key is not utf-8 OpenSSH PEM")?;
1864        Ok(Some(
1865            gunnar_core::ssh_key::PrivateKey::from_openssh(&pem)
1866                .context("parsing the forge-attestation key")?
1867                .public_key()
1868                .clone(),
1869        ))
1870    }
1871
1872    /// **The actor-ticket signing key**, minting one on first use.
1873    ///
1874    /// A fifth key beside the issuer's, the log's, the builder's and the
1875    /// webhook's, and a fifth job: it signs the appliance's word that one
1876    /// human may act for one tenant. Sealed under the KEK and atomic across
1877    /// racing callers, exactly as the four above are.
1878    ///
1879    /// # Why not the SSH host key, which is right there
1880    ///
1881    /// Because the host key's signatures always travel inside something that
1882    /// separates domains for them — the SSH transport's own framing, or the
1883    /// `sshsig` envelope with its namespace — and a raw Ed25519 signature over
1884    /// a JSON document travels inside nothing. One key signing in two formats,
1885    /// one of which has no domain separator at the signature layer, is a
1886    /// cross-protocol confusion that costs nothing today and is not
1887    /// recoverable on the day somebody finds bytes that parse as both. A key
1888    /// per job also keeps a compromise of one a compromise of one, which is
1889    /// the sentence the other four are each here for.
1890    ///
1891    /// # Why this costs no installer pin, which was the alternative
1892    ///
1893    /// It is minted AT RUNTIME into the secret store this box already has.
1894    /// The design that was weighed against it — ship the key, or a
1895    /// configuration naming it, in the image — would have put a new value into
1896    /// the two manifests that pin the installer, and `gunnar-cli`'s own note
1897    /// on that pin is the reason it was not taken: a key that can only be
1898    /// rolled by re-cutting an ISO is a key nobody rolls. Nothing here reaches
1899    /// the image; the first `Billing.MintActorTicket` on a fresh appliance
1900    /// mints it, and `Billing.ApplianceIdentity` hands the operator the public
1901    /// half to paste into their configuration.
1902    ///
1903    /// # Why it is raw Ed25519 and not `sshsig`
1904    ///
1905    /// Because the VERIFIER is `monetize_embed::ticket::verify_ticket`, which
1906    /// holds an `ed25519_dalek::VerifyingKey` and checks the canonical bytes
1907    /// that crate defines. gunnar writes no second canonical form and no
1908    /// second envelope — the stored key is still an ordinary OpenSSH ed25519
1909    /// private key, minted by the same [`gunnar_core::mint_ed25519`] as its
1910    /// four siblings, and only the SIGNATURE format differs.
1911    /// **The named sealed slot `name`** (2026-10-09): `(owner principal id,
1912    /// value)`, or `None`. Stored as the secret `slot/<name>` through
1913    /// [`Self::secrets`] — sealed under the KEK with the key as its AAD, one
1914    /// `Secret` frame — so the twin copies it, a snapshot carries it and a
1915    /// recharge restores it with no code of its own. The ACL is the gRPC
1916    /// service's; this reads and writes.
1917    #[cfg(feature = "metered")]
1918    pub fn sealed_slot_get(&self, name: &str) -> Result<Option<(String, Vec<u8>)>> {
1919        use gunnar_store::SecretStore as _;
1920        let raw = self
1921            .secrets()?
1922            .get(&sealed_slot::key(name))
1923            .context("reading a sealed slot")?;
1924        raw.map(|b| sealed_slot::decode(&b)).transpose()
1925    }
1926
1927    /// **Store `value` in the slot `name`, owned by `owner`.** Answers whether
1928    /// it was created (it did not exist).
1929    #[cfg(feature = "metered")]
1930    pub fn sealed_slot_put(&self, name: &str, owner: &str, value: &[u8]) -> Result<bool> {
1931        use gunnar_store::SecretStore as _;
1932        let secrets = self.secrets()?;
1933        let key = sealed_slot::key(name);
1934        let created = secrets
1935            .get(&key)
1936            .context("reading a sealed slot")?
1937            .is_none();
1938        secrets
1939            .put(&key, &sealed_slot::encode(owner, value))
1940            .context("writing a sealed slot")?;
1941        Ok(created)
1942    }
1943
1944    #[cfg(feature = "metered")]
1945    pub fn actor_ticket_key(&self) -> Result<crate::actor_ticket::ActorTicketKey> {
1946        use gunnar_store::{SecretStore as _, SecretStoreExt as _};
1947        let secrets = self.secrets()?;
1948        // RCH-TK: a re-laid main that awaits its twin, or is being restored, gets the DEAD
1949        // main's key back with the twin's sealed secrets — the key the ONE box still holds for
1950        // this site. Minting one first would sign tickets nobody accepts.
1951        let root = self.root();
1952        if (root.join(crate::twin::RECHARGE_REL).exists() || crate::twin::is_restoring(root))
1953            && secrets
1954                .get(gunnar_store::ACTOR_TICKET_KEY)
1955                .context("reading the actor-ticket signing key")?
1956                .is_none()
1957        {
1958            anyhow::bail!("this box awaits its twin's restore (a re-laid main): the actor-ticket key comes back with it, none is minted here");
1959        }
1960        let bytes = secrets
1961            .get_or_create_with(gunnar_store::ACTOR_TICKET_KEY, || {
1962                tracing::info!(
1963                    key = gunnar_store::ACTOR_TICKET_KEY,
1964                    "no actor-ticket signing key stored; minting one. Its public half is what \
1965                     the other side of the seam pins to check what this appliance signed"
1966                );
1967                gunnar_core::mint_ed25519()
1968                    .map_err(|err| gunnar_store::Error::backend(format!("{err}")))
1969            })
1970            .context("reading the actor-ticket signing key")?;
1971        let pem = String::from_utf8(bytes)
1972            .context("the stored actor-ticket key is not utf-8 OpenSSH PEM")?;
1973        let private = gunnar_core::ssh_key::PrivateKey::from_openssh(&pem)
1974            .context("parsing the actor-ticket signing key")?;
1975        crate::actor_ticket::ActorTicketKey::from_openssh(&private)
1976    }
1977
1978    /// **The server's certificate issuer** (the certificate-identity plan).
1979    ///
1980    /// Built from the two halves that must never be one: the control store,
1981    /// which holds the issuer *certificate* and the trusted-CA list, and the
1982    /// **sealed** secret store, which holds the private key. It is
1983    /// [`Self::secrets`] that is handed over and never the raw handle — the raw
1984    /// handle writes plaintext, and this is the one key on the machine whose
1985    /// loss means an attacker issues themselves an administrator rather than
1986    /// having to break anything.
1987    ///
1988    /// The two halves are now two **tables** rather than two files, and the
1989    /// boundary that protects the key is the seal rather than the file: the KEK
1990    /// is in `secrets.kek` beside the database and not in it, so a copied
1991    /// `control.redb` carries a certificate it cannot sign with.
1992    ///
1993    /// It no longer needs a storage engine. Neither does
1994    /// [`Self::pki_readonly`], which is why both are here and only the
1995    /// difference between them is about what they may write.
1996    pub fn pki(&self) -> Result<gunnar_core::Pki> {
1997        let secrets: std::sync::Arc<dyn gunnar_store::SecretStore> =
1998            std::sync::Arc::new(self.secrets()?);
1999        Ok(gunnar_core::Pki::new(
2000            Arc::clone(&self.control_store),
2001            secrets,
2002        )?)
2003    }
2004
2005    /// **The issuer certificate and the trusted-CA list, and nothing that can
2006    /// sign.**
2007    ///
2008    /// `gunnar issuer show` is a control-plane read. The returned handle refuses
2009    /// every secret-store call **by construction**, so it cannot mint, import or
2010    /// issue — see [`gunnar_core::Pki::read_only`]. That is now the only thing
2011    /// separating it from [`Self::pki`]: since the secrets moved into
2012    /// `control.redb`, "without an engine" describes both, and the distinction
2013    /// this method carries is a capability one rather than a dependency one.
2014    pub fn pki_readonly(&self) -> Result<gunnar_core::Pki> {
2015        Ok(gunnar_core::Pki::read_only(Arc::clone(
2016            &self.control_store,
2017        ))?)
2018    }
2019
2020    /// The identity table and catalog together, as `gunnar-ssh` wants them.
2021    ///
2022    /// Handed the shared write-gate so the front door refuses a client push on
2023    /// a standby. Every `Control` this returns clones the SAME gate, so SSH and
2024    /// smart-HTTP freeze together the instant a role change flips it.
2025    /// **Install the plan-gate chain** a mirror sync is held to — the front
2026    /// doors' own, in their order. Replaces whatever was installed: the chain
2027    /// is built once per serve, and the newest build is the one in force.
2028    pub fn install_plan_gates(&self, gates: Vec<Arc<dyn gunnar_ssh::PlanGate>>) {
2029        *self
2030            .plan_gates
2031            .write()
2032            .unwrap_or_else(|poisoned| poisoned.into_inner()) = gates;
2033    }
2034
2035    /// **Install the data set's space ledger** — the disk gate's
2036    /// ([`gunnar_ssh::DiskHeadroomGate::ledger`]). Replaces any earlier one.
2037    pub fn install_space_ledger(&self, ledger: Arc<gunnar_ssh::SpaceLedger>) {
2038        *self
2039            .space
2040            .write()
2041            .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(ledger);
2042    }
2043
2044    /// The installed space ledger, if any.
2045    pub fn space_ledger(&self) -> Option<Arc<gunnar_ssh::SpaceLedger>> {
2046        self.space
2047            .read()
2048            .unwrap_or_else(|poisoned| poisoned.into_inner())
2049            .clone()
2050    }
2051
2052    /// The installed chain, in the order it is asked. Empty: no ceiling.
2053    pub fn plan_gates(&self) -> Vec<Arc<dyn gunnar_ssh::PlanGate>> {
2054        self.plan_gates
2055            .read()
2056            .unwrap_or_else(|poisoned| poisoned.into_inner())
2057            .clone()
2058    }
2059
2060    pub fn ssh_control(&self) -> Control {
2061        Control::new(self.auth.clone(), self.catalog.clone())
2062            .with_encryption_keys(self.encryption_keys.clone())
2063            .with_write_gate(Arc::clone(&self.writes_frozen))
2064            .with_browse_flag(Arc::clone(&self.browse))
2065            // **And the twin flag** (2026-09-21, lane T4): a twin serves no git
2066            // at all, and the role now arrives over the wire on a box that is
2067            // already listening. One `Arc`, so the door cannot be a restart
2068            // behind the role.
2069            .with_twin_flag(Arc::clone(&self.twin))
2070            // The owner's enterprise list (2026-10-05): a first push's
2071            // repository name meets the name filter, and its creation is in
2072            // its account's audit log.
2073            .with_enterprise(self.names.clone(), Arc::clone(&self.account_audit))
2074    }
2075
2076    /// **The shared browse flag.** `true` = this box is a browse replica: a
2077    /// frozen standby that serves anonymous reads and refuses every
2078    /// control-plane mutator and its own promotion. Same one value as
2079    /// [`Self::writes_frozen`]'s sibling (one implementation).
2080    pub fn browse(&self) -> Arc<AtomicBool> {
2081        Arc::clone(&self.browse)
2082    }
2083
2084    /// **The shared write-gate.** `true` = this box is a frozen standby.
2085    ///
2086    /// The replication slot writes it on a role change; the SSH/HTTP front
2087    /// doors read it on every push. One value (one implementation).
2088    pub fn writes_frozen(&self) -> Arc<AtomicBool> {
2089        Arc::clone(&self.writes_frozen)
2090    }
2091
2092    /// **How many repository stores this process has opened so far** — see the
2093    /// `store_opens` field. Monotonic, so a caller measures a delta across the
2094    /// operation it is pricing. The measurement behind the red: a plain
2095    /// `Mirror.ReplicationStatus` must leave this unchanged.
2096    pub fn store_opens(&self) -> u64 {
2097        self.store_opens.load(std::sync::atomic::Ordering::Relaxed)
2098    }
2099
2100    /// Where a repository's git directory is, checked against symlink escapes.
2101    ///
2102    /// The string sandbox in [`gunnar_core::resolve_repo_path`] cannot see a
2103    /// symlink; that check lives in [`RepoRef::path_under`], and this is the
2104    /// one place gunnar calls it.
2105    pub fn repo_dir(&self, path: &RepoRef) -> Result<PathBuf> {
2106        path.path_under(&self.repos_root)
2107            .with_context(|| format!("resolving the directory for {path}"))
2108    }
2109
2110    /// The handle cache, recovering from a poisoned lock.
2111    ///
2112    /// This lock is taken on every repository lookup on every request, and it
2113    /// used to be three `.expect()`s. One panic anywhere under it poisoned the
2114    /// mutex and every subsequent request panicked: a whole server lost to one
2115    /// bad repository. What the lock protects is a *cache*: every entry in it is
2116    /// a complete, already-opened handle, so a panicking thread cannot leave it
2117    /// half-written, and recovering is strictly better than propagating.
2118    fn cache(&self) -> MutexGuard<'_, HandleCache> {
2119        self.open
2120            .lock()
2121            .unwrap_or_else(|poison| poison.into_inner())
2122    }
2123
2124    /// **The bound the handle cache is currently holding itself to.**
2125    ///
2126    /// The companion to [`Self::open_handles`], which answers how many are held
2127    /// but not what against. `reclaim_under_pressure` MOVES this number, so a
2128    /// caller — or a test — that reads only the count cannot tell a cache that
2129    /// evicted from a cache that was cut.
2130    pub fn open_repo_capacity(&self) -> usize {
2131        self.cache().capacity
2132    }
2133
2134    /// **Lower (or raise) the handle bound and evict down to it now.** Returns
2135    /// how many handles were dropped.
2136    ///
2137    /// The same call [`Self::reclaim_under_pressure`] makes, exposed because
2138    /// that one is reachable only from a `/proc/meminfo` reading below
2139    /// [`RECLAIM_FLOOR_PERCENT`] — a state a test cannot put a shared build box
2140    /// into, and the reason the reclaim path is the one half of the bound that
2141    /// `gunnar-cli/tests/handle_cache.rs` could not reach. Eviction on *insert*
2142    /// is covered there and is not duplicated here (one implementation); eviction on
2143    /// *pressure* had never run outside the appliance it was written for.
2144    pub fn set_open_repo_capacity(&self, capacity: usize) -> usize {
2145        self.cache().set_capacity(capacity)
2146    }
2147
2148    /// The stores for one catalogued repository, opening it if this is the
2149    /// first request for it.
2150    ///
2151    /// The returned `Arc` is what keeps the handle alive: while a caller holds
2152    /// one, the evictor will not drop that repository from the cache, so an
2153    /// in-flight clone cannot have its store lock pulled out from under it.
2154    pub fn repo_store(&self, repo: &Repo) -> Result<Arc<OpenRepo>> {
2155        let path = repo.path();
2156        let key = path.key();
2157        if self.suspended() {
2158            anyhow::bail!(
2159                "the data set is off-line while it is being grown; the repository {} cannot be \
2160                 opened until /data is mounted again — retry in a few minutes",
2161                key
2162            );
2163        }
2164        if let Some(store) = self.cache().touch(&key) {
2165            return Ok(store);
2166        }
2167        // A miss is about to open a store, which is the one moment the cache
2168        // grows. Check the box before it does; see `reclaim_under_pressure`.
2169        self.reclaim_under_pressure();
2170
2171        let dir = self.repo_dir(&path)?;
2172        if let Some(parent) = dir.parent() {
2173            std::fs::create_dir_all(parent).with_context(|| {
2174                format!("creating the namespace directory {}", parent.display())
2175            })?;
2176        }
2177        // The engine opens it. Which engine that is, is a fact about startup
2178        // rather than about this file.
2179        // The one site a store is actually opened. Count it here — after the
2180        // cache miss and before anything can early-return — so `store_opens`
2181        // measures engine opens (the refold cost) and nothing a cache
2182        // hit avoided. See the field.
2183        self.store_opens
2184            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2185        // An open store is one whose bytes may move: the usage ledger
2186        // re-measures it while it is open and once after it closes.
2187        self.usage.mark_repo(&repo.namespace, &repo.name);
2188        let store = self
2189            .engine
2190            .open_repo(&dir, repo.hash_kind.into())
2191            .with_context(|| format!("opening the repository at {}", dir.display()))?
2192            .logged(
2193                Arc::clone(&self.txlog),
2194                &repo.key(),
2195                &repo.hash_kind.to_string(),
2196            );
2197        Self::point_head(&store, repo)?;
2198        // The hash marker, written once. `--adopt` is the only reader; a
2199        // store from before 2026-08-30 gets its marker on its first open
2200        // after the upgrade, from the catalog row it has always been served
2201        // under.
2202        let marker = dir.join(Self::HASH_MARKER);
2203        if !marker.exists() {
2204            if let Err(err) = std::fs::write(&marker, format!("{}\n", repo.hash_kind)) {
2205                tracing::warn!(
2206                    target: "gunnar::store",
2207                    repo = %repo.key(),
2208                    marker = %marker.display(),
2209                    error = %err,
2210                    "the hash marker could not be written; --adopt will refuse this store"
2211                );
2212            }
2213        }
2214
2215        // **The account's quota, applied at the one moment it can be.** The
2216        // store opens on the server's default and is moved onto the plan here,
2217        // so an admin who set a quota while the repository was closed does not
2218        // have to set it again. A namespace with no quota keeps the default,
2219        // which is what `None` means and why the call is skipped rather than
2220        // passed a zero.
2221        self.apply_explode_quota(&repo.namespace, &dir);
2222
2223        // Another thread may have won the race while this one was on disk. Its
2224        // handle holds the lock; ours is about to be dropped, releasing it. So
2225        // keep the winner rather than overwriting it.
2226        Ok(self.cache().insert(key, store))
2227    }
2228
2229    /// Move every open store under `dir` onto the namespace's quota.
2230    ///
2231    /// Called when a store opens and when an admin changes the plan. A failure
2232    /// to read the catalog is logged and the default stands: a quota that
2233    /// cannot be read must not stop a repository serving, because the worst it
2234    /// costs is a cache that is the wrong size and the best it costs is an
2235    /// outage.
2236    pub fn apply_explode_quota(&self, namespace: &str, dir: &Path) {
2237        match self.catalog().namespace_explode_budget(namespace) {
2238            Ok(Some(bytes)) => {
2239                let n = self.engine.set_explode_budget(dir, bytes);
2240                tracing::debug!(
2241                    target: "gunnar::store",
2242                    namespace,
2243                    bytes,
2244                    stores = n,
2245                    "the account's explode budget was applied"
2246                );
2247            }
2248            Ok(None) => {}
2249            Err(err) => tracing::warn!(
2250                target: "gunnar::store",
2251                namespace,
2252                error = %err,
2253                "the account's explode budget could not be read; the server default stands"
2254            ),
2255        }
2256    }
2257
2258    /// **Shrink the handle cache when the box is short of memory.**
2259    ///
2260    /// # The hole this closes — MEASURED on the 2 GB appliance, 2026-08-30
2261    ///
2262    /// On a 2 GB appliance the box collapsed at ~1200 repositories:
2263    /// `MemAvailable` fell under the indexer watchdog's floor (399 MB) and
2264    /// every store then spilled caches it did not hold — `scanned_rows_dropped=0`
2265    /// on every push — because the memory was in the **other 255 handles in the
2266    /// LRU**, which the watchdog cannot reach. Before the console fix that
2267    /// ended in a hard wedge: eight transfers in flight, no progress for 41
2268    /// minutes, the control plane still answering. The handle cache was bounded
2269    /// by descriptors and nothing else, so it never gave anything back.
2270    ///
2271    /// [`crate::budget`] sizes the cache against memory at start. This is the
2272    /// same rule applied *again*, from the memory the box actually has now:
2273    /// below [`RECLAIM_FLOOR_PERCENT`] of `MemTotal` available, the bound is
2274    /// halved and the least recently used handles are dropped, freeing their
2275    /// redb page caches and their five descriptors each. It is the eviction the
2276    /// watchdog could not do, done by the only thing that owns the handles.
2277    ///
2278    /// **Rate-limited to one probe per [`RECLAIM_PROBE_INTERVAL`]**, and taken
2279    /// only on a cache *miss*, which is the one moment the cache grows. A
2280    /// `/proc/meminfo` read on every request would be a syscall on the hot
2281    /// path; on a miss it is noise beside opening a store.
2282    ///
2283    /// It never shrinks below [`crate::limits::MIN_OPEN_REPOS`]: a server that
2284    /// can keep no repository open re-opens on every request, and a box that
2285    /// low is the WARN row's job, not the cache's.
2286    fn reclaim_under_pressure(&self) {
2287        let now = std::time::Instant::now();
2288        {
2289            let mut probed = self
2290                .last_reclaim_probe
2291                .lock()
2292                .unwrap_or_else(|poison| poison.into_inner());
2293            match *probed {
2294                Some(last) if now.duration_since(last) < RECLAIM_PROBE_INTERVAL => return,
2295                _ => *probed = Some(now),
2296            }
2297        }
2298        let Some((total, available)) = crate::dashboard::probe::memory() else {
2299            return;
2300        };
2301        if total == 0 || available >= total / 100 * RECLAIM_FLOOR_PERCENT {
2302            return;
2303        }
2304        let mut cache = self.cache();
2305        let before = cache.capacity;
2306        let want = (before / 2).max(crate::limits::MIN_OPEN_REPOS);
2307        if want >= before {
2308            return;
2309        }
2310        let dropped = cache.set_capacity(want);
2311        let held = cache.entries.len();
2312        drop(cache);
2313        tracing::warn!(
2314            target: "gunnar::limits",
2315            event = "limits.handles.reclaimed",
2316            mem_available = available,
2317            mem_total = total,
2318            was = before,
2319            now = want,
2320            dropped,
2321            open = held,
2322            "memory is short ({} of {} available): the open-repository cache is cut from {} to \
2323             {} handles and {} were dropped. Each one held five descriptors and its page caches; \
2324             a repository touched again simply re-opens.",
2325            crate::budget::human(available),
2326            crate::budget::human(total),
2327            before,
2328            want,
2329            dropped
2330        );
2331    }
2332
2333    /// Make an open repository's `HEAD` name the default branch its catalog
2334    /// entry carries.
2335    ///
2336    /// **The only place the server projects the catalog onto a repository's
2337    /// `HEAD`** (one implementation), and it is called from exactly two: [`Self::repo_store`]
2338    /// on the open path, so create and every transfer after a restart carry it,
2339    /// and `ControlPlane::set_default_branch`, which has to re-run it because
2340    /// the handle it needs is already in the cache and `repo_store` returns
2341    /// early for those.
2342    ///
2343    /// A move is logged at info. It is a change to what a clone checks out and
2344    /// it happens without anyone asking on the open path, so it must be visible
2345    /// in the log of the repository that had it done to it.
2346    pub fn point_head(store: &OpenRepo, repo: &Repo) -> Result<()> {
2347        // Through the UNLOGGED store: HEAD's default is derived from the
2348        // catalog row, which is itself a logged document, and every box —
2349        // primary, twin, a restore — derives it the same way on open. Logging
2350        // it here would put a frame in a twin's log that the primary never
2351        // numbered, and `append_at` would refuse the primary's next one.
2352        let moved = gunnar_core::point_head_at(store.unlogged(), &repo.default_branch)
2353            .with_context(|| format!("pointing {}'s HEAD at its default branch", repo.key()))?;
2354        if moved {
2355            tracing::info!(
2356                repo = %repo.key(),
2357                default_branch = %repo.default_branch,
2358                "HEAD now names the repository's default branch; it did not before, so this \
2359                 repository was not clonable if that branch was the only one with commits"
2360            );
2361        }
2362        Ok(())
2363    }
2364
2365    /// [`Self::point_head`] for a repository this server has catalogued,
2366    /// opening its store first. Used after the catalog's default branch moves.
2367    pub fn repoint_head(&self, repo: &Repo) -> Result<()> {
2368        let store = self.repo_store(repo)?;
2369        Self::point_head(&store, repo)
2370    }
2371
2372    /// Adopt a pushed branch as the default branch of a repository whose `HEAD`
2373    /// still resolves to nothing, and report the name if one was adopted.
2374    ///
2375    /// # Why a push is allowed to change this
2376    ///
2377    /// `repo create` gives every repository `refs/heads/main`, and a donor
2378    /// whose branch is `master` therefore lands in a repository whose `HEAD`
2379    /// names a branch that does not exist and never will. That repository
2380    /// **cannot be cloned**: `HEAD` has no object, so it is not advertised, and
2381    /// stock `git clone` writes an empty worktree, prints *"remote HEAD refers
2382    /// to nonexistent ref"* and exits **0**. Nothing between the successful push
2383    /// and the empty checkout says a word about the default branch, which is
2384    /// what cost the roundtrip harness a day on 2026-08-06.
2385    ///
2386    /// So the first branch to arrive in a repository with an unborn `HEAD` is
2387    /// adopted, which is what every hosted forge does and what makes `push`
2388    /// alone produce something clonable. It is deliberately narrow:
2389    ///
2390    /// * it fires **only** when `HEAD` resolves to nothing *after* the push, so
2391    ///   the only repositories it can touch are the ones that are unclonable as
2392    ///   they stand — if the configured default branch was among the ones just
2393    ///   pushed, `HEAD` resolves and this does nothing;
2394    /// * it considers only `refs/heads/…` that the push **created or moved**,
2395    ///   never a delete and never a tag; and
2396    /// * the choice goes through the catalog and then through
2397    ///   [`Self::point_head`], so the authority and its projection still move
2398    ///   together and there is still one writer of `HEAD`.
2399    ///
2400    /// It is logged at `warn`, not `info`: the server chose a default branch
2401    /// nobody asked for, and the operator has to be able to find that decision
2402    /// later. `set-default-branch` overrides it.
2403    pub fn adopt_default_branch_if_unborn(
2404        &self,
2405        path: &RepoRef,
2406        pushed: &[String],
2407    ) -> Result<Option<String>> {
2408        let Some(repo) = self.catalog().get(path)? else {
2409            // The repository was deleted between the push and here. Not an
2410            // error, and not something to invent a default branch for.
2411            return Ok(None);
2412        };
2413        let store = self.repo_store(&repo)?;
2414        // `HEAD` is not a row in `refs()` (the `GitServe` HEAD ruling), so this is the accessor
2415        // pair plus one resolution against the same snapshot the resolution
2416        // reads — see [`gunnar_wire::RefSnapshot::head`].
2417        // `FullName::new(HEAD_REF)` died with `RefStore`; there is nothing to
2418        // validate here, because the name is not a caller's.
2419        let git = store.serve();
2420        if gunnar_wire::RefSnapshot::read(git)?.head(git)?.is_some() {
2421            return Ok(None);
2422        }
2423        let Some(adopted) = pushed
2424            .iter()
2425            .find(|name| name.starts_with("refs/heads/"))
2426            .cloned()
2427        else {
2428            return Ok(None);
2429        };
2430        let repo = self.catalog().set_default_branch(path, &adopted)?;
2431        Self::point_head(&store, &repo)?;
2432        tracing::warn!(
2433            repo = %repo.key(),
2434            default_branch = %adopted,
2435            "this repository's default branch did not exist, so nothing could clone it; the \
2436             first branch pushed has been adopted as the default. `gunnar control repo \
2437             set-default-branch` overrides this"
2438        );
2439        Ok(Some(adopted))
2440    }
2441
2442    /// **`repo create` is transactional, and it never adopts a store it did
2443    /// not make.** The one verb every create routes through: the gRPC
2444    /// `Repos.Create`, the local `gunnar repo create`, and the
2445    /// first-repository door once a push has passed the hash check.
2446    ///
2447    /// Order, and why each step is where it is:
2448    ///
2449    /// 1. **Look at the disk first.** If a directory already stands at the
2450    ///    name — or a [tombstone](Self::tombstone_path) says a delete could not
2451    ///    reclaim it — the create is refused **by name**, before the catalog is
2452    ///    touched. This is the 2026-08-30 resurrection: on v1.1.3-166 `repo
2453    ///    delete` dropped the catalog row and left the store, and the next
2454    ///    `repo create` of the same name opened it — `ls-remote` right after
2455    ///    the create listed all 59 refs of the deleted skade, and recreated
2456    ///    `--hash sha256` the name served sha1 refs (`fatal: protocol
2457    ///    error`). `adopt` is the opt-in for the one legitimate case (a
2458    ///    catalog restored from backup over a surviving data disk), and only
2459    ///    for a store whose [hash marker](Self::HASH_MARKER) matches.
2460    /// 2. The catalog row.
2461    /// 3. The store. If the engine cannot make it, step 2 is **rolled back**
2462    ///    and whatever the engine left is removed: a create that failed
2463    ///    leaves no directory, no row, nothing for `repo get` to find.
2464    ///
2465    /// Returns the catalogued repository; the handle is in the cache.
2466    pub fn create_repo(&self, spec: NewRepo, adopt: bool) -> Result<Repo> {
2467        let path = spec.path.clone();
2468        // TRUE when the directory was already there and was taken over. The
2469        // rollback below must not remove such a directory: "a create that
2470        // failed leaves no directory" is a promise about a directory THIS
2471        // create made, and applying it to an adopted store would answer a
2472        // transient engine failure by destroying the very bytes the operator
2473        // ran `--adopt` to keep. On the appliance that is 25-39 GB.
2474        let adopted = self.refuse_stale_store(&path, adopt, spec.hash_kind)?;
2475        let repo = self.catalog().create(spec)?;
2476        match self.repo_store(&repo) {
2477            Ok(_) => Ok(repo),
2478            Err(err) => {
2479                // Roll back: the row, the handle, the directory. A failure
2480                // inside the rollback is logged and the original error is the
2481                // one the caller sees, because that is the one they can act on.
2482                self.close_repo(&path);
2483                if let Err(undo) = self.catalog().delete(&path) {
2484                    tracing::error!(
2485                        target: "gunnar::store",
2486                        repo = %path,
2487                        error = format!("{undo:#}"),
2488                        "rolling back the catalog row of a create whose store failed"
2489                    );
2490                }
2491                if adopted {
2492                    tracing::error!(
2493                        target: "gunnar::store",
2494                        event = "repo.adopt_failed",
2495                        repo = %path,
2496                        "the create that ADOPTED this store failed to open it; the catalog row is \
2497                         rolled back and the DIRECTORY IS LEFT WHERE IT IS — it was not made by \
2498                         this create and is not this create's to remove"
2499                    );
2500                } else if let Ok(dir) = self.repo_dir(&path) {
2501                    if let Err(undo) = std::fs::remove_dir_all(&dir) {
2502                        if undo.kind() != std::io::ErrorKind::NotFound {
2503                            tracing::error!(
2504                                target: "gunnar::store",
2505                                repo = %path,
2506                                dir = %dir.display(),
2507                                error = %undo,
2508                                "rolling back the directory of a create whose store failed"
2509                            );
2510                        }
2511                    }
2512                }
2513                Err(err.context(if adopted {
2514                    format!(
2515                        "creating the stores of {path} over an ADOPTED directory; the row was \
2516                         rolled back and the store's bytes were left untouched"
2517                    )
2518                } else {
2519                    format!("creating the stores of {path}; nothing was kept")
2520                }))
2521            }
2522        }
2523    }
2524
2525    /// The file that says which hash a store's objects are: `sha1` or
2526    /// `sha256`, one line, written when the store is first opened. Not the
2527    /// engine's — a store carries no marker of its own, and opening a sha1
2528    /// archive as sha256 does not fail, it decodes garbage. `--adopt` reads
2529    /// it; nothing else does.
2530    pub const HASH_MARKER: &'static str = "OBJECT_FORMAT";
2531
2532    /// Step 1 of [`Self::create_repo`]: nothing may stand at `path` on disk.
2533    ///
2534    /// Returns **true when an existing store was ADOPTED** — the one case in
2535    /// which the directory was not made by this create, and therefore the one
2536    /// case in which [`Self::create_repo`]'s rollback must not remove it.
2537    ///
2538    /// ## `--adopt` means "take it as it is", including a store from before
2539    /// the marker existed
2540    ///
2541    /// MEASURED on the appliance 2026-08-30, `v1.1.3-227-g6a2367a`, request
2542    /// `175daccc0000000d`:
2543    ///
2544    /// ```text
2545    /// repo create alice/linux --hash sha1 --public --adopt
2546    ///   -> failed precondition: cannot adopt the store at
2547    ///      /data/repos/alice/linux.git: it carries unmarked objects, the
2548    ///      create asked for sha1
2549    /// ```
2550    ///
2551    /// The marker is a 2026-08-30 file. **Every store written before that day
2552    /// has none**, so an `--adopt` that requires one refuses precisely the
2553    /// stores adoption exists for — a catalog restored over a surviving data
2554    /// disk, or the orphan an old catalog-only delete left. Composed with a
2555    /// `create` that refuses the name and a `delete` that cannot authorise it,
2556    /// that is a store with no way out at all.
2557    ///
2558    /// The honest rule, and the one implemented here:
2559    ///
2560    /// * **unmarked** — there is no second opinion to check, so the caller's
2561    ///   `--hash` is taken at their word AND WRITTEN into the marker. The
2562    ///   store is marked from then on, so the *next* adopt is checked; the
2563    ///   caller's word is recorded rather than merely trusted.
2564    /// * **marked and equal** — adopted, as before.
2565    /// * **marked and different** — refused, as before. This is the arm that
2566    ///   stops a sha256 row over a sha1 store from serving refs no client can
2567    ///   read, and it is not weakened: a store that carries a marker is
2568    ///   checked against it.
2569    pub fn refuse_stale_store(
2570        &self,
2571        path: &RepoRef,
2572        adopt: bool,
2573        hash_kind: HashKind,
2574    ) -> Result<bool> {
2575        let dir = self.repo_dir(path)?;
2576        let tombstone = Self::tombstone_path(&dir);
2577        let tombstoned = tombstone.exists();
2578        if !dir.exists() && !tombstoned {
2579            return Ok(false);
2580        }
2581        if !adopt {
2582            let why = if tombstoned {
2583                let record =
2584                    Tombstone::parse(&std::fs::read_to_string(&tombstone).unwrap_or_default());
2585                match record.reason {
2586                    // **The soft-delete window.** The name is unusable because
2587                    // the repository is still there, being kept — and the
2588                    // sentence has to say `undelete`, because a create is
2589                    // exactly what somebody reaches for when they mean it.
2590                    TombstoneReason::Deleted => {
2591                        let left = record
2592                            .seconds_left(gunnar_core::now_ms())
2593                            .map(|s| format!("{} day(s) left", s / 86_400))
2594                            .unwrap_or_else(|| "no expiry set".to_owned());
2595                        format!(
2596                            "{path} is DELETED but not purged: its bytes are being kept ({left}). \
2597                             `repo undelete {path}` puts it back as it was, `repo purge {path}` \
2598                             reclaims it now, or pass --adopt to take the store as a new \
2599                             repository and lose the old row"
2600                        )
2601                    }
2602                    TombstoneReason::ReclaimFailed => format!(
2603                        "a delete of this name could not reclaim its store ({}); `repo delete \
2604                         {path} --purge` retries the reclaim, or pass --adopt to take the store \
2605                         as it is",
2606                        record.note.trim()
2607                    ),
2608                }
2609            } else {
2610                format!(
2611                    "a store already exists at {}; `repo delete {path}` reclaims it, or pass \
2612                     --adopt to take it as it is",
2613                    dir.display()
2614                )
2615            };
2616            anyhow::bail!("{why}");
2617        }
2618        let marker = dir.join(Self::HASH_MARKER);
2619        let on_disk = std::fs::read_to_string(&marker)
2620            .map(|text| text.trim().to_owned())
2621            .unwrap_or_default();
2622        if on_disk.is_empty() {
2623            // Unmarked: a store from before the marker existed. There is
2624            // nothing to disagree with, so the caller's word is taken — and
2625            // WRITTEN, so it is a fact from here on rather than a decision
2626            // taken again on every adopt.
2627            std::fs::write(&marker, format!("{hash_kind}\n")).with_context(|| {
2628                format!(
2629                    "marking the adopted store at {} as {hash_kind}; the adopt is refused rather \
2630                     than leaving a store whose hash nothing records",
2631                    dir.display()
2632                )
2633            })?;
2634            tracing::warn!(
2635                target: "gunnar::store",
2636                event = "repo.adopted_unmarked",
2637                repo = %path,
2638                dir = %dir.display(),
2639                hash = %hash_kind,
2640                marker = %marker.display(),
2641                "an UNMARKED store (written before the OBJECT_FORMAT marker existed) was adopted \
2642                 at the caller's word; it is marked {} from now on and the next adopt is CHECKED",
2643                hash_kind
2644            );
2645        } else {
2646            anyhow::ensure!(
2647                on_disk == hash_kind.to_string(),
2648                "cannot adopt the store at {}: its objects are {} (marker {} says so), the \
2649                 create asked for {hash_kind}. Adopt it as {} or leave it alone; a {hash_kind} \
2650                 row over a {} store serves refs no client can read.",
2651                dir.display(),
2652                on_disk,
2653                marker.display(),
2654                on_disk,
2655                on_disk
2656            );
2657        }
2658        if tombstoned {
2659            // Framed, as every tombstone change is (`frame_tombstone`): an adopt over a
2660            // soft-deleted name (and `repo undelete`, which adopts) must not leave a box
2661            // restored from the twin with the name still fenced off.
2662            let _framed = self.frame_tombstone(&tombstone, None)?;
2663            std::fs::remove_file(&tombstone)
2664                .with_context(|| format!("removing the tombstone {}", tombstone.display()))?;
2665        }
2666        tracing::warn!(
2667            target: "gunnar::store",
2668            event = "repo.adopted",
2669            repo = %path,
2670            dir = %dir.display(),
2671            hash = %hash_kind,
2672            "an existing store was ADOPTED by a create with --adopt; its objects are served as they are"
2673        );
2674        Ok(true)
2675    }
2676
2677    /// Where a name's tombstone lives: beside its directory, so a store that
2678    /// could not be removed and its marker are removed together by the retry.
2679    pub fn tombstone_path(dir: &Path) -> PathBuf {
2680        let mut name = dir
2681            .file_name()
2682            .map(|n| n.to_os_string())
2683            .unwrap_or_default();
2684        name.push(".tombstone");
2685        dir.with_file_name(name)
2686    }
2687
2688    /// Is `path` tombstoned — deleted from the catalog, store not reclaimed?
2689    pub fn is_tombstoned(&self, path: &RepoRef) -> Result<bool> {
2690        Ok(Self::tombstone_path(&self.repo_dir(path)?).exists())
2691    }
2692
2693    /// How many repository handles are open. For tests and `Admin.Stats`.
2694    pub fn open_handles(&self) -> usize {
2695        self.cache().entries.len()
2696    }
2697
2698    /// Forget a repository's handle, releasing its store lock. Used by
2699    /// `repo delete --purge` before the directory is removed.
2700    pub fn close_repo(&self, path: &RepoRef) {
2701        self.usage.mark_repo(path.namespace(), path.name());
2702        self.cache().entries.remove(&path.key());
2703    }
2704
2705    /// **`repo delete` reclaims the disk.** Stop the repository's index work,
2706    /// release its handle, remove its directory — pack, journal, tail,
2707    /// exploded tier and index tables — and report the bytes that went.
2708    ///
2709    /// MEASURED 2026-08-29 on the appliance: a `repo delete` after the linux
2710    /// push left **25 GB** of `gunnar-git.znippy/` behind, because the catalog
2711    /// row was removed and the directory was not. Order here is the point:
2712    ///
2713    /// 1. the engine cancels the index worker (an in-flight pack is **aborted**
2714    ///    at its next checkpoint, milliseconds, never finished — its rows are
2715    ///    keyed by oid and the directory is about to go);
2716    /// 2. the handle cache forgets the repository, so the store drops as soon as
2717    ///    the last request holding it returns (the worker is cancelled, so the
2718    ///    drop does not join hours of work);
2719    /// 3. `remove_dir_all`. A store still held by an in-flight request keeps
2720    ///    its open fds on unlinked files until it returns; the bytes are
2721    ///    reclaimed when it does, and the directory entry is gone now.
2722    ///
2723    /// Returns `(bytes_before, bytes_after)` measured by walking the directory,
2724    /// so the log line and the caller report applied output.
2725    ///
2726    /// **A reclaim that fails leaves the name TOMBSTONED** (2026-08-30): a
2727    /// file beside the directory saying when and why, so
2728    /// [`Self::create_repo`] refuses the name until `repo delete` is run again
2729    /// and succeeds. Without it a failed `remove_dir_all` (a store held open
2730    /// on a read-only mount, a permissions slip) left a directory the next
2731    /// create would refuse by name anyway — but with no sentence saying that
2732    /// a delete had been asked for and had not finished.
2733    pub fn purge_repo(&self, path: &RepoRef) -> Result<(u64, u64)> {
2734        // A snapshot streaming from its cut may still read this store (R5.1-A).
2735        self.wait_unpinned("removing a repository store");
2736        let _usage = UsageMark::namespace(&self.usage, path.namespace());
2737        // **A `RepoStore` purge frame before the directory goes** (twin note, M9): the twin
2738        // removes the same store at the same point of the sequence, and a restore replays the
2739        // removal, so a purged repository is never resurrected from the log's earlier packs.
2740        // A twin applying the frame reaches `reclaim_repo` directly and frames nothing.
2741        if !self.txlog.is_follower() {
2742            let dir = self.repo_dir(path)?;
2743            let hash = std::fs::read_to_string(dir.join(Self::HASH_MARKER))
2744                .map(|s| s.trim().to_string())
2745                .unwrap_or_default();
2746            let meta = gunnar_core::txlog::Meta::RepoStore {
2747                repo: path.key(),
2748                op: "purged".into(),
2749                hash,
2750            };
2751            let _framed = self.txlog.mutation();
2752            self.txlog
2753                .append(gunnar_core::txlog::Kind::RepoStore, &meta, &[])
2754                .with_context(|| format!("framing the purge of {path}"))?;
2755            return self.reclaim_repo(path);
2756        }
2757        self.reclaim_repo(path)
2758    }
2759
2760    /// The removal half of [`Self::purge_repo`], unframed: what the twin's apply of a
2761    /// `RepoStore` purge frame runs.
2762    pub fn reclaim_repo(&self, path: &RepoRef) -> Result<(u64, u64)> {
2763        let _usage = UsageMark::namespace(&self.usage, path.namespace());
2764        let dir = self.repo_dir(path)?;
2765        let tombstone = Self::tombstone_path(&dir);
2766        let before = dir_bytes(&dir);
2767        self.engine.cancel_index(&dir);
2768        self.close_repo(path);
2769        match std::fs::remove_dir_all(&dir) {
2770            Ok(()) => {}
2771            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
2772            Err(e) => {
2773                let now = gunnar_core::now_ms();
2774                let record = Tombstone {
2775                    deleted_at_unix_ms: now,
2776                    // No deadline: a reclaim that failed is OWED to an
2777                    // operator, and a sweep that retried it unattended would
2778                    // be repeating the thing that just did not work.
2779                    purge_after_unix_ms: None,
2780                    principal_id: String::new(),
2781                    reason: TombstoneReason::ReclaimFailed,
2782                    repo: None,
2783                    note: format!("delete asked at unix_ms {now}, reclaim failed: {e}"),
2784                };
2785                let note = record.note.clone();
2786                let text = serde_json::to_string_pretty(&record)
2787                    .unwrap_or_else(|_| format!("{{\"note\":\"{note}\"}}"));
2788                if let Err(write) = std::fs::write(&tombstone, format!("{text}\n")) {
2789                    tracing::error!(
2790                        target: "gunnar::store",
2791                        repo = %path,
2792                        tombstone = %tombstone.display(),
2793                        error = %write,
2794                        "the reclaim failed AND the tombstone could not be written"
2795                    );
2796                }
2797                tracing::error!(
2798                    target: "gunnar::store",
2799                    event = "repo.purge_failed",
2800                    repo = %path,
2801                    dir = %dir.display(),
2802                    error = %e,
2803                    "repo delete could not reclaim the store; the name is tombstoned and a create \
2804                     refuses it until `repo delete` is run again and succeeds"
2805                );
2806                return Err(anyhow::anyhow!(
2807                    "the catalog row is gone but the store at {} could not be reclaimed ({e}); \
2808                     the name is tombstoned — `repo delete {path}` retries, `repo create` refuses \
2809                     it until then",
2810                    dir.display()
2811                ));
2812            }
2813        }
2814        if tombstone.exists() {
2815            std::fs::remove_file(&tombstone)
2816                .with_context(|| format!("removing the tombstone {}", tombstone.display()))?;
2817        }
2818        let after = dir_bytes(&dir);
2819        tracing::info!(
2820            target: "gunnar::store",
2821            event = "repo.purged",
2822            repo = %path,
2823            dir = %dir.display(),
2824            bytes_before = before,
2825            bytes_after = after,
2826            "repo delete reclaimed {} bytes",
2827            before.saturating_sub(after)
2828        );
2829        Ok((before, after))
2830    }
2831
2832    // ── the soft-delete window (2026-08-30) ────────────────────────────────
2833
2834    /// **`repo delete` without `--purge`: a DATED TOMBSTONE, not a reclaim.**
2835    ///
2836    /// The catalog row is the caller's to remove; this is everything else. The
2837    /// bytes stay exactly where they are, the name becomes unusable
2838    /// ([`Self::refuse_stale_store`] refuses a create over a tombstone), and a
2839    /// deadline is written into the tombstone at this instant.
2840    ///
2841    /// Why this exists at all, in one measured line from
2842    /// MEASURED: `repo delete --purge` returns the bytes in
2843    /// ~2 seconds — **181 GiB to 33 MiB** — and a live mirror does not help
2844    /// because the delete replicates. The failure a first paying customer is
2845    /// most likely to cause is deleting their own repository, and the only
2846    /// thing that answers it is a window.
2847    ///
2848    /// What it does NOT do, and deliberately:
2849    ///
2850    /// * it does not touch the bytes, so it cannot fail on a full disk;
2851    /// * it cancels the index worker and drops the handle, because a
2852    ///   repository nobody may reach should not be spending CPU or file
2853    ///   descriptors on being resolved;
2854    /// * it does not delete the tombstone of a *failed reclaim* — that record
2855    ///   is owed to an operator. Soft-deleting a name already tombstoned that
2856    ///   way is refused by name.
2857    ///
2858    /// `retention` of zero is legal and means *purge at the next sweep*: an
2859    /// operator reclaiming space said so, and a zero that silently became
2860    /// thirty days would be the server overruling them.
2861    pub fn soft_delete(
2862        &self,
2863        path: &RepoRef,
2864        repo: Option<&Repo>,
2865        principal_id: &str,
2866        retention: std::time::Duration,
2867    ) -> Result<Tombstone> {
2868        let _usage = UsageMark::namespace(&self.usage, path.namespace());
2869        let dir = self.repo_dir(path)?;
2870        let marker = Self::tombstone_path(&dir);
2871        if let Some(existing) = Self::read_tombstone(&marker) {
2872            if existing.reason == TombstoneReason::ReclaimFailed {
2873                anyhow::bail!(
2874                    "{path} is already tombstoned because a reclaim FAILED ({}). That is bytes \
2875                     owed, not bytes held: run `repo delete {path} --purge` to finish it. \
2876                     Soft-deleting it again would hide the failure behind a deadline.",
2877                    existing.note.trim()
2878                );
2879            }
2880        }
2881        anyhow::ensure!(
2882            dir.is_dir(),
2883            "{path} has nothing on disk at {}; there is nothing to keep, and a tombstone over \
2884             no bytes would promise a restore that cannot happen",
2885            dir.display()
2886        );
2887        let now = gunnar_core::now_ms();
2888        let record = Tombstone {
2889            deleted_at_unix_ms: now,
2890            purge_after_unix_ms: Some(now + retention.as_millis() as i64),
2891            principal_id: principal_id.to_owned(),
2892            reason: TombstoneReason::Deleted,
2893            repo: repo.cloned(),
2894            note: format!(
2895                "soft-deleted at unix_ms {now}; the bytes are kept until the deadline, `repo \
2896                 undelete {path}` restores it"
2897            ),
2898        };
2899        // The engine first: a repository nobody may reach must not keep
2900        // resolving a pack. The handle after it, so the store drops as soon as
2901        // the last in-flight request returns.
2902        self.engine.cancel_index(&dir);
2903        self.close_repo(path);
2904        let text = serde_json::to_string_pretty(&record).context("serialising the tombstone")?;
2905        let text = format!("{text}\n");
2906        // **The twin hears of it FIRST** (GHUNT-SOFTDEL, gunnar.rs 2026-10-28): a `File` frame
2907        // before the file, as `durable::write_atomic` does for every document under the data
2908        // root. Unframed, the twin held the catalog row's removal and not the tombstone, so a
2909        // box restored from it (the recharge, a main rebuilt from its twin) held the bytes as
2910        // an ORPHAN: not listed by `repo list-deleted`, and no `repo undelete`.
2911        let _framed = self.frame_tombstone(&marker, Some(text.as_bytes()))?;
2912        std::fs::write(&marker, &text)
2913            .with_context(|| format!("writing the tombstone {}", marker.display()))?;
2914        let bytes = dir_bytes(&dir);
2915        tracing::warn!(
2916            target: "gunnar::store",
2917            event = "repo.soft_deleted",
2918            repo = %path,
2919            dir = %dir.display(),
2920            bytes,
2921            principal = %principal_id,
2922            purge_after_unix_ms = record.purge_after_unix_ms.unwrap_or_default(),
2923            "repo delete tombstoned this repository; {bytes} bytes are KEPT until the retention \
2924             window ends, and they still count against the account"
2925        );
2926        Ok(record)
2927    }
2928
2929    /// **`repo undelete`: put a soft-deleted repository back.**
2930    ///
2931    /// Returns the [`NewRepo`] the caller must re-insert into the catalog, and
2932    /// removes the tombstone. The two halves are split because the catalog is
2933    /// the caller's — the gRPC path and the local CLI reach it differently —
2934    /// and because the row must go in *before* the tombstone comes off: a
2935    /// crash between them leaves a repository that is still fenced off, which
2936    /// is recoverable, rather than a name a create would adopt, which is the
2937    /// resurrection the reclaim rules closed.
2938    ///
2939    /// The recorded hash kind is the one that comes back, never a default. A
2940    /// tombstone that does not carry a row (one written before this existed)
2941    /// is refused BY NAME rather than restored as sha256 over a sha1 store.
2942    pub fn undelete_spec(&self, path: &RepoRef) -> Result<NewRepo> {
2943        let dir = self.repo_dir(path)?;
2944        let marker = Self::tombstone_path(&dir);
2945        let record = Self::read_tombstone(&marker).ok_or_else(|| {
2946            anyhow::anyhow!(
2947                "{path} is not deleted: there is no tombstone at {}. `repo list-deleted` shows \
2948                 what can be undeleted.",
2949                marker.display()
2950            )
2951        })?;
2952        anyhow::ensure!(
2953            record.reason == TombstoneReason::Deleted,
2954            "{path} is tombstoned because a RECLAIM FAILED, not because it was deleted with a \
2955             window ({}). There is nothing to undelete: the operator asked for these bytes to \
2956             go. `repo delete {path} --purge` finishes it.",
2957            record.note.trim()
2958        );
2959        anyhow::ensure!(
2960            dir.is_dir(),
2961            "{path} is tombstoned but its bytes are gone from {}; there is nothing to restore",
2962            dir.display()
2963        );
2964        let repo = record.repo.ok_or_else(|| {
2965            anyhow::anyhow!(
2966                "the tombstone at {} does not record what {path} was — no hash kind, no default \
2967                 branch. Restoring it would be a GUESS, and a sha256 row over a sha1 store \
2968                 serves refs no client can read. Recreate it with `repo create --adopt --hash \
2969                 <the store's OBJECT_FORMAT>` instead.",
2970                marker.display()
2971            )
2972        })?;
2973        Ok(NewRepo {
2974            path: path.clone(),
2975            hash_kind: repo.hash_kind,
2976            default_branch: Some(repo.default_branch),
2977            visibility: repo.visibility,
2978            description: repo.description,
2979        })
2980    }
2981
2982    /// Take the tombstone off, once the catalog row is back.
2983    pub fn clear_tombstone(&self, path: &RepoRef) -> Result<()> {
2984        let _usage = UsageMark::namespace(&self.usage, path.namespace());
2985        let marker = Self::tombstone_path(&self.repo_dir(path)?);
2986        // Framed before it goes, for the reason `soft_delete` frames its write: a box restored
2987        // from the twin must not find the undeleted repository still fenced off.
2988        let _framed = if marker.exists() {
2989            self.frame_tombstone(&marker, None)?
2990        } else {
2991            None
2992        };
2993        match std::fs::remove_file(&marker) {
2994            Ok(()) => {}
2995            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
2996            Err(e) => {
2997                return Err(e)
2998                    .with_context(|| format!("removing the tombstone {}", marker.display()))
2999            }
3000        }
3001        tracing::warn!(
3002            target: "gunnar::store",
3003            event = "repo.undeleted",
3004            repo = %path,
3005            "repo undelete put this repository back; its bytes were never reclaimed"
3006        );
3007        Ok(())
3008    }
3009
3010    /// **A tombstone's write (`Some(bytes)`) or removal (`None`) as a `File` frame** in this
3011    /// box's log, before the file changes; the guard holds the log's mutation lock until the
3012    /// caller has changed it. Nothing on a follower (a twin or a box being restored: it applies
3013    /// frames, it originates none).
3014    fn frame_tombstone(
3015        &self,
3016        marker: &Path,
3017        bytes: Option<&[u8]>,
3018    ) -> Result<Option<gunnar_core::txlog::MutationGuard>> {
3019        if self.txlog.is_follower() {
3020            return Ok(None);
3021        }
3022        let rel = marker
3023            .strip_prefix(&self.root)
3024            .with_context(|| {
3025                format!(
3026                    "the tombstone {} is not under the data root",
3027                    marker.display()
3028                )
3029            })?
3030            .to_string_lossy()
3031            .into_owned();
3032        let guard = self.txlog.mutation();
3033        self.txlog
3034            .append(
3035                gunnar_core::txlog::Kind::File,
3036                &gunnar_core::txlog::Meta::File {
3037                    path: rel.clone(),
3038                    deleted: bytes.is_none(),
3039                },
3040                bytes.unwrap_or_default(),
3041            )
3042            .with_context(|| format!("framing the tombstone {rel}"))?;
3043        Ok(Some(guard))
3044    }
3045
3046    /// Read a tombstone file, or `None` when there is not one.
3047    pub fn read_tombstone(marker: &Path) -> Option<Tombstone> {
3048        std::fs::read_to_string(marker)
3049            .ok()
3050            .map(|text| Tombstone::parse(&text))
3051    }
3052
3053    /// The tombstone beside `path`, if any.
3054    pub fn tombstone_of(&self, path: &RepoRef) -> Result<Option<Tombstone>> {
3055        Ok(Self::read_tombstone(&Self::tombstone_path(
3056            &self.repo_dir(path)?,
3057        )))
3058    }
3059
3060    /// **Every soft-deleted repository, with the bytes it is still holding.**
3061    ///
3062    /// This is what makes a tombstone visible on a bill: the bytes are real,
3063    /// the account is still using them, and a customer who deleted a
3064    /// repository and saw no change in their usage would rightly call that a
3065    /// bug. `Admin.StorageInfo` reports the total and `repo list-deleted`
3066    /// prints the rows.
3067    ///
3068    /// It walks `repos/` rather than asking the catalog, because the whole
3069    /// point of a tombstone is that the catalog does not know about it.
3070    pub fn tombstones(&self) -> Result<Vec<DeletedRepo>> {
3071        let root = self.repos_root().to_path_buf();
3072        let mut found = Vec::new();
3073        Self::walk_tombstones(&root, &root, &mut found);
3074        found.sort_by_key(|a| a.path.key());
3075        Ok(found)
3076    }
3077
3078    /// The recursion behind [`Self::tombstones`]. Namespaces nest, so
3079    /// this cannot be one `read_dir`.
3080    fn walk_tombstones(root: &Path, dir: &Path, out: &mut Vec<DeletedRepo>) {
3081        let Ok(entries) = std::fs::read_dir(dir) else {
3082            return;
3083        };
3084        for entry in entries.flatten() {
3085            let path = entry.path();
3086            let name = entry.file_name().to_string_lossy().into_owned();
3087            if name.ends_with(".git.tombstone") {
3088                let Some(record) = Self::read_tombstone(&path) else {
3089                    continue;
3090                };
3091                if record.reason != TombstoneReason::Deleted {
3092                    continue;
3093                }
3094                let store = path.with_file_name(name.trim_end_matches(".tombstone"));
3095                let Some(repo_ref) = Self::repo_ref_of_dir(root, &store) else {
3096                    continue;
3097                };
3098                out.push(DeletedRepo {
3099                    path: repo_ref,
3100                    tombstone: record,
3101                    bytes: dir_bytes(&store),
3102                });
3103                continue;
3104            }
3105            if path.is_dir() && !name.ends_with(".git") {
3106                Self::walk_tombstones(root, &path, out);
3107            }
3108        }
3109    }
3110
3111    /// `<repos-root>/<ns…>/<name>.git` back to a [`RepoRef`].
3112    fn repo_ref_of_dir(root: &Path, dir: &Path) -> Option<RepoRef> {
3113        let rel = dir.strip_prefix(root).ok()?;
3114        let mut parts: Vec<String> = rel
3115            .components()
3116            .map(|c| c.as_os_str().to_string_lossy().into_owned())
3117            .collect();
3118        let name = parts.pop()?;
3119        let name = name.strip_suffix(".git").unwrap_or(&name).to_owned();
3120        if parts.is_empty() {
3121            return None;
3122        }
3123        RepoRef::new(&parts.join("/"), &name).ok()
3124    }
3125
3126    // ── orphan stores: the directory nothing can see (2026-08-30) ──────────
3127
3128    /// **Every store directory with no catalog row and no soft-delete
3129    /// tombstone.**
3130    ///
3131    /// MEASURED on the appliance 2026-08-30 (`v1.1.3-227-g6a2367a`), the
3132    /// wreckage of Friday's kernel-mirror incident: `/data/repos/alice/linux.git`
3133    /// stood on the disk with ~25-39 GB in it, no catalog row and no
3134    /// tombstone. Three guards, each right on its own, composed into a state
3135    /// with no exit — `create` refused the name because the directory was
3136    /// there (`175daccc0000000c`), `create --adopt` refused it because the
3137    /// store predated the `OBJECT_FORMAT` marker (`…0d`), and `delete
3138    /// --purge` refused it because the access check was `Access::repo` on a
3139    /// repository not in the catalog, which no principal can ever hold a grant
3140    /// on (`…0b`/`…0e`). The bytes were stranded and the NAME was permanently
3141    /// unusable.
3142    ///
3143    /// This is the door that was missing. It walks `repos/` rather than
3144    /// asking the catalog, exactly as [`Self::tombstones`] does and for the
3145    /// same reason: the whole point of an orphan is that no record of it
3146    /// exists.
3147    ///
3148    /// What counts as an orphan, and why it is drawn here:
3149    ///
3150    /// * **no catalog row** — a catalogued directory is `repo list`'s;
3151    /// * **no `Deleted` tombstone** — one of those is `repo list-deleted`'s,
3152    ///   and it has `undelete` and `purge` as its exits;
3153    /// * a `ReclaimFailed` tombstone IS an orphan. `tombstones()` filters that
3154    ///   reason out of `list-deleted` deliberately (bytes owed, not bytes
3155    ///   held), which left it in no listing whatsoever; the row carries the
3156    ///   note so an operator sees why.
3157    pub fn orphans(&self) -> Result<Vec<OrphanStore>> {
3158        let root = self.repos_root().to_path_buf();
3159        let mut found = Vec::new();
3160        self.walk_orphans(&root, &root, &mut found)?;
3161        found.sort_by_key(|a| a.path.key());
3162        Ok(found)
3163    }
3164
3165    /// The recursion behind [`Self::orphans`]. Namespaces nest, so this
3166    /// cannot be one `read_dir` — the same shape as
3167    /// [`Self::walk_tombstones`].
3168    fn walk_orphans(&self, root: &Path, dir: &Path, out: &mut Vec<OrphanStore>) -> Result<()> {
3169        let Ok(entries) = std::fs::read_dir(dir) else {
3170            return Ok(());
3171        };
3172        for entry in entries.flatten() {
3173            let path = entry.path();
3174            let name = entry.file_name().to_string_lossy().into_owned();
3175            if !path.is_dir() {
3176                continue;
3177            }
3178            if !name.ends_with(".git") {
3179                self.walk_orphans(root, &path, out)?;
3180                continue;
3181            }
3182            let Some(repo_ref) = Self::repo_ref_of_dir(root, &path) else {
3183                continue;
3184            };
3185            if self.catalog().get(&repo_ref)?.is_some() {
3186                continue;
3187            }
3188            let record = Self::read_tombstone(&Self::tombstone_path(&path));
3189            let failed_reclaim = match &record {
3190                // `repo list-deleted` owns this one; it is not an orphan.
3191                Some(t) if t.reason == TombstoneReason::Deleted => continue,
3192                Some(t) => Some(t.note.trim().to_owned()),
3193                None => None,
3194            };
3195            let hash_marker = std::fs::read_to_string(path.join(Self::HASH_MARKER))
3196                .ok()
3197                .map(|text| text.trim().to_owned())
3198                .filter(|text| !text.is_empty());
3199            out.push(OrphanStore {
3200                path: repo_ref,
3201                bytes: dir_bytes(&path),
3202                modified_unix_ms: newest_mtime_unix_ms(&path),
3203                hash_marker,
3204                failed_reclaim,
3205                dir: path,
3206            });
3207        }
3208        Ok(())
3209    }
3210
3211    /// **Is there a store at `path` that no record accounts for?**
3212    ///
3213    /// The one question both delete doors ask, so they cannot answer it
3214    /// differently (one implementation): a directory on disk, no catalog row, and no
3215    /// `Deleted` tombstone. A `ReclaimFailed` tombstone still counts as an
3216    /// orphan — those bytes are owed to an operator and no listing but
3217    /// [`Self::orphans`] shows them.
3218    pub fn is_orphan(&self, path: &RepoRef) -> Result<bool> {
3219        if self.catalog().get(path)?.is_some() {
3220            return Ok(false);
3221        }
3222        let dir = self.repo_dir(path)?;
3223        if !dir.is_dir() {
3224            return Ok(false);
3225        }
3226        Ok(!matches!(
3227            Self::read_tombstone(&Self::tombstone_path(&dir)),
3228            Some(record) if record.reason == TombstoneReason::Deleted
3229        ))
3230    }
3231
3232    /// **What a delete of an orphan may and may not do**, as one sentence both
3233    /// doors print.
3234    ///
3235    /// `--purge` on an orphan is legitimate and is exactly what `repo reclaim`
3236    /// does: the operator said "the bytes go", the row is already gone, the
3237    /// bytes are there. A *soft* delete of one is not, and the reason is the
3238    /// soft delete's own contract — it promises `repo undelete` puts the
3239    /// repository back **as it was**, and for an orphan the server does not
3240    /// know what it was: no hash kind, no default branch, no visibility. Lane
3241    /// AC already refuses to restore a tombstone that carries no row; refusing
3242    /// to WRITE one is that same rule, one step earlier, before a deadline has
3243    /// been put on bytes nobody can bring back.
3244    pub fn orphan_soft_delete_refusal(path: &RepoRef) -> String {
3245        format!(
3246            "{path} is an ORPHAN store: bytes on disk with no catalog row and no tombstone, so \
3247             the server does not know what it was and a tombstone would promise an undelete it \
3248             cannot honour. Three exits, and they are all one command: `repo delete {path} \
3249             --purge` reclaims the bytes now, `repo reclaim {path}` is the same thing said \
3250             plainly, and `repo create {path} --adopt --hash <its OBJECT_FORMAT>` takes the \
3251             store over as a repository instead. `repo list-orphans` reports that hash."
3252        )
3253    }
3254
3255    /// **Reclaim an orphan's bytes.** The exit that did not exist.
3256    ///
3257    /// It refuses anything that is not an orphan BY NAME, because both of the
3258    /// other two states have their own verb and reaching them through this one
3259    /// would be a second way to destroy a repository:
3260    ///
3261    /// * catalogued -> `repo delete --purge`;
3262    /// * soft-deleted -> `repo undelete` or `repo purge`.
3263    ///
3264    /// The reclaim itself is [`Self::purge_repo`] — the same verb `--purge`
3265    /// and the sweep use, so an orphan's bytes go the way every other
3266    /// repository's bytes go (one implementation), including the index worker being
3267    /// cancelled first and a `ReclaimFailed` tombstone if it cannot.
3268    pub fn reclaim_orphan(&self, path: &RepoRef) -> Result<u64> {
3269        let _usage = UsageMark::namespace(&self.usage, path.namespace());
3270        anyhow::ensure!(
3271            self.catalog().get(path)?.is_none(),
3272            "{path} is a LIVE repository, not an orphan: it is in the catalog. `repo delete \
3273             {path} --purge` is the verb that deletes it."
3274        );
3275        let dir = self.repo_dir(path)?;
3276        if let Some(record) = Self::read_tombstone(&Self::tombstone_path(&dir)) {
3277            anyhow::ensure!(
3278                record.reason != TombstoneReason::Deleted,
3279                "{path} is SOFT-DELETED, not an orphan: its bytes are being kept on purpose and \
3280                 `repo undelete {path}` still puts it back. `repo purge {path}` ends the window."
3281            );
3282        }
3283        anyhow::ensure!(
3284            dir.is_dir(),
3285            "there is no store at {}; `repo list-orphans` shows what there is to reclaim",
3286            dir.display()
3287        );
3288        let (before, after) = self.purge_repo(path)?;
3289        let bytes = before.saturating_sub(after);
3290        tracing::warn!(
3291            target: "gunnar::store",
3292            event = "repo.orphan_reclaimed",
3293            repo = %path,
3294            dir = %dir.display(),
3295            bytes,
3296            "an ORPHAN store — no catalog row, no tombstone — was reclaimed; {bytes} bytes back \
3297             and the name is usable again"
3298        );
3299        Ok(bytes)
3300    }
3301
3302    /// **The sweep: reclaim every tombstone whose window has closed.**
3303    ///
3304    /// Returns what it reclaimed, `(path, bytes)`. A failure on one repository
3305    /// is logged and the sweep continues — one undeletable directory must not
3306    /// stop the other nineteen from being reclaimed, and `purge_repo` leaves
3307    /// its own `ReclaimFailed` tombstone behind so the failure is not lost.
3308    pub fn sweep_expired_tombstones(&self, now_unix_ms: i64) -> Vec<(RepoRef, u64)> {
3309        let deleted = match self.tombstones() {
3310            Ok(deleted) => deleted,
3311            Err(err) => {
3312                tracing::error!(
3313                    target: "gunnar::store",
3314                    error = format!("{err:#}"),
3315                    "the tombstone sweep could not list what is deleted; nothing was reclaimed"
3316                );
3317                return Vec::new();
3318            }
3319        };
3320        let mut reclaimed = Vec::new();
3321        for row in deleted {
3322            if !row.tombstone.is_expired_at(now_unix_ms) {
3323                continue;
3324            }
3325            match self.purge_repo(&row.path) {
3326                Ok((before, after)) => {
3327                    let bytes = before.saturating_sub(after);
3328                    tracing::warn!(
3329                        target: "gunnar::store",
3330                        event = "repo.tombstone_swept",
3331                        repo = %row.path,
3332                        bytes,
3333                        deleted_at_unix_ms = row.tombstone.deleted_at_unix_ms,
3334                        "the retention window closed; a soft-deleted repository was reclaimed \
3335                         and cannot be undeleted any more"
3336                    );
3337                    reclaimed.push((row.path, bytes));
3338                }
3339                Err(err) => {
3340                    tracing::error!(
3341                        target: "gunnar::store",
3342                        event = "repo.tombstone_sweep_failed",
3343                        repo = %row.path,
3344                        error = format!("{err:#}"),
3345                        "an expired tombstone could not be reclaimed; the name stays fenced off \
3346                         and the sweep continues"
3347                    );
3348                }
3349            }
3350        }
3351        reclaimed
3352    }
3353
3354    /// Which catalogued repository the git directory `dir` belongs to, as
3355    /// `namespace/name` — the inverse of [`Self::repo_dir`], for a progress
3356    /// row that knows only a store root.
3357    pub fn repo_of_dir(&self, dir: &Path) -> Option<(String, String)> {
3358        let rel = dir.strip_prefix(&self.repos_root).ok()?;
3359        let mut parts = rel.components().filter_map(|c| match c {
3360            std::path::Component::Normal(s) => Some(s.to_string_lossy().into_owned()),
3361            _ => None,
3362        });
3363        let ns = parts.next()?;
3364        let name = parts.next()?;
3365        Some((ns, name.strip_suffix(".git").unwrap_or(&name).to_owned()))
3366    }
3367}
3368
3369/// **Start the soft-delete sweep**: hourly, and once immediately.
3370///
3371/// The other half of a soft delete. Without it "deleted" would mean "kept
3372/// forever" and a `/data` would fill with repositories nobody can see — which
3373/// is the invisible 25 GB again, only with a promise attached.
3374///
3375/// It runs once at start on purpose: a box that was powered off when a
3376/// retention window closed must not wait an hour to notice, and an operator who
3377/// set `--retention-days 0` to free space should see it happen while they are
3378/// still watching.
3379///
3380/// Fire and forget, exactly like `disktest::spawn`. It holds no lock the server
3381/// needs, its work is on the blocking pool, and a failure on one repository is
3382/// logged and skipped rather than stopping the sweep — `purge_repo` leaves its
3383/// own tombstone behind, so nothing is lost by carrying on.
3384pub fn spawn_tombstone_sweep(stores: Arc<ServerStores>) -> tokio::task::JoinHandle<()> {
3385    // A32-14, stays a task: its handle is kept by serve and aborted at the server's stop.
3386    tokio::spawn(async move {
3387        loop {
3388            let stores = Arc::clone(&stores);
3389            let reclaimed = tokio::task::spawn_blocking(move || {
3390                stores.sweep_expired_tombstones(gunnar_core::now_ms())
3391            })
3392            .await
3393            .unwrap_or_default();
3394            if !reclaimed.is_empty() {
3395                let bytes: u64 = reclaimed.iter().map(|(_, b)| b).sum();
3396                tracing::warn!(
3397                    target: "gunnar::store",
3398                    event = "repo.sweep",
3399                    repos = reclaimed.len(),
3400                    bytes,
3401                    "the retention window closed on {} repository(ies); {bytes} bytes were \
3402                     reclaimed and they can no longer be undeleted",
3403                    reclaimed.len()
3404                );
3405            }
3406            tokio::time::sleep(TOMBSTONE_SWEEP_INTERVAL).await;
3407        }
3408    })
3409}
3410
3411/// What one flow-flush tick did.
3412#[derive(Debug, Clone, PartialEq, Eq)]
3413pub enum FlowFlush {
3414    /// This many namespace-day rows written.
3415    Wrote(usize),
3416    /// Not attempted: the transaction log is RELEASED (a runtime data-set growth has given its
3417    /// files up and `/data` is unmounted). Nothing is lost — the live counters are in RAM and a
3418    /// refused write re-parks its completed days — and nothing is logged above trace.
3419    Held,
3420    /// The write failed for any other reason.
3421    Failed(String),
3422}
3423
3424/// **One flow-flush tick.** Found by the lifecycle lane 2026-09-15: every minute of a runtime
3425/// growth logged `flow.flush_failed`, because the flush wrote through a transaction log that
3426/// had been released for the unmount. The release window is now a quiet hold, and a write
3427/// the release overtook mid-flush is read as the same hold rather than as a failure.
3428pub fn flow_flush_tick(stores: &ServerStores) -> FlowFlush {
3429    if stores.txlog().is_released() {
3430        return FlowFlush::Held;
3431    }
3432    match stores.flow().flush(gunnar_core::now_ms()) {
3433        Ok(rows) => FlowFlush::Wrote(rows),
3434        Err(_) if stores.txlog().is_released() => FlowFlush::Held,
3435        Err(err) => FlowFlush::Failed(err.to_string()),
3436    }
3437}
3438
3439/// **Start the flow flush**: every [`FLOW_FLUSH_INTERVAL`], forever.
3440///
3441/// The live half of the flow ledger is a set of atomics in this process; this
3442/// is what makes it survive a restart. It COPIES the live slots into the
3443/// control store rather than adding to them (`gunnar_core::FlowLedger::flush`),
3444/// so running it twice writes the same rows twice instead of doubling them —
3445/// which is what lets it run on a tick without any coordination, and what lets
3446/// a slot opened after a restart be seeded from the stored row rather than from
3447/// zero.
3448///
3449/// It is a task of its own and NOT a line in the dashboard's two-second tick,
3450/// deliberately: that tick is documented as reading a few atomics and nothing
3451/// else, and this writes redb. A flush on the dashboard's thread would put a
3452/// database commit between the operator and the screen.
3453///
3454/// It also carries the day boundary on an IDLE server. A namespace that was
3455/// pushed to at 23:59 and then left alone has a live slot still holding
3456/// yesterday; nothing on the transfer path will notice, because there is no
3457/// transfer. The flush rolls it and writes the completed day.
3458///
3459/// Fire and forget, like [`spawn_tombstone_sweep`]: it holds no lock the server
3460/// needs, its work is on the blocking pool, and a failed write is logged and
3461/// retried on the next tick — the counters are still in RAM, so nothing is lost
3462/// by carrying on.
3463pub fn spawn_flow_flush(
3464    stores: Arc<ServerStores>,
3465    band: Arc<Mutex<Option<gunnar_core::Fleet>>>,
3466) -> tokio::task::JoinHandle<()> {
3467    // A32-14, stays a task: its handle is kept by serve and aborted at the server's stop.
3468    tokio::spawn(async move {
3469        loop {
3470            tokio::time::sleep(FLOW_FLUSH_INTERVAL).await;
3471            let tick = Arc::clone(&stores);
3472            let band = Arc::clone(&band);
3473            let written = tokio::task::spawn_blocking(move || {
3474                let written = flow_flush_tick(&tick);
3475                if written == FlowFlush::Held {
3476                    // The fold reads the control document, which is under the unmounted
3477                    // data set too: the band keeps its last answer through the window.
3478                    return written;
3479                }
3480                // **The usage ledger's reconcile pass** (2026-10-06): one slice of
3481                // namespaces re-measured per tick, the whole set every
3482                // `RECONCILE_CYCLE`, so bytes that moved without a mark are
3483                // corrected and counted rather than billed stale. Low priority by
3484                // PACING: on this tick — already off the request path, once a
3485                // minute — and a thirtieth of the namespaces at a time (~330
3486                // one-repository walks a minute at 10,000 tenants).
3487                reconcile_tick(&tick, FLOW_FLUSH_INTERVAL);
3488                // **The dashboard's fold, taken HERE and not on the band's own
3489                // tick.** It walks every namespace and reads the control
3490                // document; the band re-samples every two seconds and is
3491                // documented as reading a few atomics and nothing else. Once a
3492                // minute is also the right rate for a row a human reads.
3493                *band.lock().expect("the flow band") = Some(
3494                    tick.flow()
3495                        .fleet(gunnar_core::now_ms(), crate::dashboard::SILENT_AFTER_DAYS),
3496                );
3497                written
3498            })
3499            .await
3500            .unwrap_or_else(|err| FlowFlush::Failed(err.to_string()));
3501            match written {
3502                FlowFlush::Wrote(0) => {}
3503                // The release window of a runtime growth: nothing lost, nothing to say above
3504                // trace. The counters stay in RAM and the first tick after the remount writes.
3505                FlowFlush::Held => tracing::trace!(
3506                    target: "gunnar::store",
3507                    event = "flow.flush_held",
3508                    "the transaction log is released for a data-set growth; the flow ledger waits for the remount"
3509                ),
3510                FlowFlush::Wrote(rows) => tracing::debug!(
3511                    target: "gunnar::store",
3512                    event = "flow.flushed",
3513                    rows,
3514                    "wrote {rows} namespace-day flow row(s)"
3515                ),
3516                FlowFlush::Failed(err) => tracing::warn!(
3517                    target: "gunnar::store",
3518                    event = "flow.flush_failed",
3519                    %err,
3520                    "the flow ledger could not be written; the counters are still in memory and \
3521                     the next tick will try again"
3522                ),
3523            }
3524        }
3525    })
3526}
3527
3528/// **One tick of the usage ledger's reconcile pass, a miss counted** (A28 M17): the pass
3529/// that could not run is counted on the server's counters (`usage_reconcile_missed`, on
3530/// `/metrics` and in the heartbeat) and warned, never dropped; the next tick tries again.
3531pub fn reconcile_tick(stores: &ServerStores, tick: std::time::Duration) -> Option<(usize, usize)> {
3532    count_reconcile(
3533        stores.usage_ledger().reconcile_step(stores, tick),
3534        stores.metrics(),
3535    )
3536}
3537
3538/// Pure but for the counter: **the reconcile pass's outcome, a miss counted and warned**.
3539pub fn count_reconcile(
3540    outcome: gunnar_core::Result<(usize, usize)>,
3541    metrics: &gunnar_core::observe::ServerMetrics,
3542) -> Option<(usize, usize)> {
3543    match outcome {
3544        Ok(done) => Some(done),
3545        Err(err) => {
3546            metrics.add_usage_reconcile_missed(1);
3547            tracing::warn!(
3548                target: "gunnar::store",
3549                event = "usage.reconcile_missed",
3550                %err,
3551                missed = metrics.snapshot().usage_reconcile_missed,
3552                "the usage ledger's reconcile pass could not run ({err}): nothing was re-measured \
3553                 this tick; counted as usage_reconcile_missed, and the next tick tries again"
3554            );
3555            None
3556        }
3557    }
3558}
3559
3560/// Bytes under `dir`, walked (not `du`, not estimated). `0` for a missing dir.
3561pub fn dir_bytes(dir: &Path) -> u64 {
3562    fn walk(p: &Path, acc: &mut u64) {
3563        let Ok(rd) = std::fs::read_dir(p) else { return };
3564        for e in rd.flatten() {
3565            let Ok(m) = e.metadata() else { continue };
3566            if m.is_dir() {
3567                walk(&e.path(), acc);
3568            } else {
3569                *acc += m.len();
3570            }
3571        }
3572    }
3573    let mut n = 0;
3574    walk(dir, &mut n);
3575    n
3576}
3577
3578/// **The newest mtime anywhere under `dir`, as unix milliseconds.**
3579///
3580/// The directory's own mtime is not enough: a store is a tree, and writing a
3581/// pack inside `objects/` does not touch the top. This is what tells an
3582/// operator on a shell-less appliance whether an orphan is Friday's wreckage
3583/// or something a push is still writing to — which is the difference between
3584/// `repo reclaim` and leaving it alone.
3585///
3586/// `0` when nothing can be read, which is a fact ("no timestamp") rather than
3587/// a guess at one.
3588pub fn newest_mtime_unix_ms(dir: &Path) -> i64 {
3589    fn walk(p: &Path, acc: &mut i64) {
3590        let Ok(rd) = std::fs::read_dir(p) else { return };
3591        for e in rd.flatten() {
3592            let Ok(m) = e.metadata() else { continue };
3593            if let Ok(at) = m.modified() {
3594                if let Ok(since) = at.duration_since(std::time::UNIX_EPOCH) {
3595                    *acc = (*acc).max(since.as_millis() as i64);
3596                }
3597            }
3598            if m.is_dir() {
3599                walk(&e.path(), acc);
3600            }
3601        }
3602    }
3603    let mut newest = std::fs::metadata(dir)
3604        .and_then(|m| m.modified())
3605        .ok()
3606        .and_then(|at| at.duration_since(std::time::UNIX_EPOCH).ok())
3607        .map(|d| d.as_millis() as i64)
3608        .unwrap_or(0);
3609    walk(dir, &mut newest);
3610    newest
3611}
3612
3613/// **Is the persisted role a STANDBY?** Read from `replication.json` once, at
3614/// open, to decide whether the box comes up frozen.
3615///
3616/// Behind the `replication` feature because the role lives in the replication
3617/// config; a build without it has no way to become a standby and is always a
3618/// writable primary. A missing or malformed file reads as PRIMARY — the same
3619/// fail-open chosen for a torn `replication.json`, because a box that
3620/// refused every push over a config it could not read would be a worse outage
3621/// than one that served.
3622#[cfg(feature = "replication")]
3623fn replication_role_at_open(root: &Path) -> crate::mirror::Role {
3624    crate::mirror::ReplicationConfig::load(root)
3625        .map(|c| c.role)
3626        .unwrap_or_default()
3627}
3628
3629/// The role a build without replication always has: a writable primary. The
3630/// type is a private stand-in with the two questions the open path asks.
3631#[cfg(not(feature = "replication"))]
3632fn replication_role_at_open(_root: &Path) -> PrimaryOnly {
3633    PrimaryOnly
3634}
3635
3636#[cfg(not(feature = "replication"))]
3637struct PrimaryOnly;
3638
3639#[cfg(not(feature = "replication"))]
3640impl PrimaryOnly {
3641    fn refuses_client_writes(&self) -> bool {
3642        false
3643    }
3644    fn is_browse(&self) -> bool {
3645        false
3646    }
3647}
3648
3649#[cfg(test)]
3650mod tombstone_tests {
3651    use super::*;
3652
3653    /// **The old free-text tombstone must not read as a soft delete.**
3654    ///
3655    /// An appliance upgraded in place has files on disk that this code did not
3656    /// write. Reading one of those as `Deleted` would put a *deadline* on bytes
3657    /// that are OWED to an operator, and the sweep would then quietly do the
3658    /// `remove_dir_all` that already failed once — unattended, at 3 a.m.
3659    ///
3660    /// Seen red by making `parse` fall back to `Deleted`: this goes red on the
3661    /// reason and on `is_expired_at`.
3662    #[test]
3663    fn a_free_text_tombstone_reads_as_a_failed_reclaim_and_never_expires() {
3664        let old = "delete asked at unix_ms 1756500000000, reclaim failed: Permission denied\n";
3665        let record = Tombstone::parse(old);
3666        assert_eq!(record.reason, TombstoneReason::ReclaimFailed);
3667        assert_eq!(record.purge_after_unix_ms, None);
3668        assert!(record.note.contains("Permission denied"));
3669        // The load-bearing half: no deadline means the sweep never touches it,
3670        // whatever "now" is.
3671        assert!(!record.is_expired_at(i64::MAX));
3672        assert_eq!(record.seconds_left(0), None);
3673    }
3674
3675    /// A soft delete round-trips through JSON with its deadline and its row.
3676    #[test]
3677    fn a_soft_delete_round_trips_and_expires_exactly_at_its_deadline() {
3678        let record = Tombstone {
3679            deleted_at_unix_ms: 1_000,
3680            purge_after_unix_ms: Some(3_000),
3681            principal_id: "alice".into(),
3682            reason: TombstoneReason::Deleted,
3683            repo: None,
3684            note: "soft-deleted".into(),
3685        };
3686        let text = serde_json::to_string(&record).unwrap();
3687        let back = Tombstone::parse(&text);
3688        assert_eq!(back, record);
3689        assert!(!back.is_expired_at(2_999), "one ms early is not expired");
3690        assert!(back.is_expired_at(3_000), "the deadline itself expires");
3691        assert!(back.is_expired_at(3_001));
3692        assert_eq!(back.seconds_left(1_000), Some(2));
3693        assert_eq!(back.seconds_left(9_999), Some(0), "never negative");
3694    }
3695
3696    /// The two reasons print differently, because they mean different things
3697    /// and an operator acts on them differently.
3698    #[test]
3699    fn the_two_reasons_do_not_share_a_word() {
3700        assert_ne!(
3701            TombstoneReason::Deleted.as_str(),
3702            TombstoneReason::ReclaimFailed.as_str()
3703        );
3704    }
3705}
3706
3707/// One `statvfs` of a path gunnar was TOLD to use.
3708///
3709/// **Never a number that was not read.** A failed measurement leaves
3710/// `measured` false and both byte fields at zero with the OS's reason in
3711/// `error`; a renderer that prints `0 B free` for a filesystem nobody could
3712/// measure is how an operator is sent to look for a full disk that is not
3713/// full.
3714pub(crate) fn filesystem_use(what: &str, path: &Path) -> gunnar_proto::FilesystemUse {
3715    let mut row = gunnar_proto::FilesystemUse {
3716        what: what.to_owned(),
3717        path: path.display().to_string(),
3718        ..Default::default()
3719    };
3720    match rustix::fs::statvfs(path) {
3721        Ok(vfs) => {
3722            let frsize = if vfs.f_frsize == 0 {
3723                vfs.f_bsize
3724            } else {
3725                vfs.f_frsize
3726            };
3727            row.measured = true;
3728            row.total_bytes = vfs.f_blocks.saturating_mul(frsize);
3729            row.free_bytes = vfs.f_bavail.saturating_mul(frsize);
3730        }
3731        Err(err) => row.error = err.to_string(),
3732    }
3733    row
3734}
3735
3736#[cfg(test)]
3737mod flow_flush_tests {
3738    use super::*;
3739
3740    /// ★ **A reconcile pass that cannot run is counted, published and warned, never dropped**
3741    /// (A28 M17). Before, `reconcile_step` answered `(0, 0)` for a catalog it could not read,
3742    /// and the flush tick threw the answer away (`let _ =`): a ledger that stopped
3743    /// re-measuring looked exactly like one that found nothing to correct.
3744    #[test]
3745    fn a_reconcile_pass_that_cannot_run_is_counted_on_the_servers_counters() {
3746        let metrics = gunnar_core::observe::ServerMetrics::new();
3747        assert_eq!(count_reconcile(Ok((3, 1)), &metrics), Some((3, 1)));
3748        assert_eq!(
3749            metrics.snapshot().usage_reconcile_missed,
3750            0,
3751            "a pass that ran is no miss"
3752        );
3753        let miss = Err(gunnar_core::Error::NoSuchNamespace(
3754            "catalog unreadable".into(),
3755        ));
3756        assert_eq!(count_reconcile(miss, &metrics), None);
3757        assert_eq!(metrics.snapshot().usage_reconcile_missed, 1);
3758        assert!(
3759            metrics
3760                .snapshot()
3761                .render_prometheus()
3762                .contains("gunnar_usage_reconcile_missed 1\n"),
3763            "the miss is on /metrics: {}",
3764            metrics.snapshot().render_prometheus()
3765        );
3766    }
3767
3768    /// ★ The tick runs on the stores' OWN counters, the set `Server::start` takes: a healthy
3769    /// pass over a fresh box counts no miss.
3770    #[test]
3771    fn the_reconcile_tick_counts_on_the_stores_one_set_of_counters() {
3772        let dir = tempfile::tempdir().unwrap();
3773        let stores = ServerStores::open(dir.path()).unwrap();
3774        assert_eq!(reconcile_tick(&stores, FLOW_FLUSH_INTERVAL), Some((0, 0)));
3775        assert_eq!(stores.metrics().snapshot().usage_reconcile_missed, 0);
3776    }
3777
3778    /// **A runtime growth's release window is a quiet hold, and nothing is lost across it.**
3779    ///
3780    /// Found by the lifecycle lane 2026-09-15: `flow.flush_failed` every minute while the txlog
3781    /// was released. Yesterday's counters are the ones at risk — the roll moves them out of the
3782    /// live slot into `completed`, and a flush whose write was refused used to drop them there.
3783    #[test]
3784    fn a_released_txlog_holds_the_flush_and_the_rolled_day_lands_after_reacquire() {
3785        let dir = tempfile::tempdir().unwrap();
3786        let stores = ServerStores::open(dir.path()).unwrap();
3787        let now = gunnar_core::now_ms();
3788        let yesterday = now - 86_400_000;
3789        let push = gunnar_core::flow::Transfer {
3790            bytes_in: 42,
3791            pushed: true,
3792            principal: "p".into(),
3793            ..Default::default()
3794        };
3795        stores.flow().record("ns", yesterday, &push);
3796
3797        stores.txlog().release().unwrap();
3798        // The red the tick used to log: the write itself is refused while released.
3799        assert!(
3800            stores.flow().flush(now).is_err(),
3801            "a flush wrote through a released transaction log"
3802        );
3803        assert_eq!(flow_flush_tick(&stores), FlowFlush::Held);
3804        assert_eq!(
3805            flow_flush_tick(&stores),
3806            FlowFlush::Held,
3807            "still held, every tick of the window"
3808        );
3809
3810        stores.txlog().reacquire().unwrap();
3811        assert_eq!(
3812            flow_flush_tick(&stores),
3813            FlowFlush::Wrote(1),
3814            "yesterday's row, re-parked by the refused flush, is written after the remount"
3815        );
3816        assert_eq!(
3817            flow_flush_tick(&stores),
3818            FlowFlush::Wrote(0),
3819            "and written once"
3820        );
3821    }
3822}
3823
3824/// **Frame the site's WireGuard hub declaration into this primary's log, once per change.**
3825///
3826/// `wg/hub.conf` is public site data that `korp-installer` lays into `/data` through the ESP
3827/// data stage on a fresh install and that nothing in gunnar ever writes. It therefore had no
3828/// sink call site, the twin never held it, and `gunnar control twin replay` brought a main
3829/// back with no way of reaching the tunnel — the D6 failure again, in the one class where the
3830/// symptom is "nobody can reach the box at all".
3831///
3832/// **Best effort, and deliberately so.** This runs on the start-up path of a box whose tunnel
3833/// is already configured — the file on disk is the truth either way, and refusing to serve
3834/// because a 1 KiB document could not be framed would turn a replication gap into an outage.
3835/// A failure is one WARN naming the path, at the place an operator is already looking.
3836///
3837/// The machine's own `wg/identity.key` and `wg/identity.pub` are NOT touched here and are
3838/// refused by `gunnar_core::txlog::is_per_box_path`: a private key on the twin is a second
3839/// place to steal the site's network identity from, and a restored main carrying the dead
3840/// box's identity would claim a tunnel the hub registered to a key that no longer exists.
3841fn adopt_hub_conf(root: &Path, txlog: &Arc<gunnar_core::txlog::Log>) {
3842    use gunnar_core::txlog::{HUB_CONF_FRAMED_REL, HUB_CONF_REL};
3843    let path = root.join(HUB_CONF_REL);
3844    let bytes = match std::fs::read(&path) {
3845        Ok(b) => b,
3846        // No declaration is the ordinary case on every box that is not an appliance, and on
3847        // an appliance before the ceremony. Nothing to say.
3848        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
3849        Err(err) => {
3850            tracing::warn!(
3851                target: gunnar_core::observe::TARGET_TWIN,
3852                path = %path.display(),
3853                %err,
3854                "the hub declaration could not be read, so it is NOT in this box's log and a twin will not hold it"
3855            );
3856            return;
3857        }
3858    };
3859    // The ONE place that decides what a digest of something is.
3860    let digest = gunnar_core::provenance::digest_bytes(&bytes);
3861    let mark = root.join(HUB_CONF_FRAMED_REL);
3862    // Already framed, unchanged: the log carries these bytes. One `read_to_string` per boot.
3863    if std::fs::read_to_string(&mark)
3864        .map(|s| s.trim() == digest)
3865        .unwrap_or(false)
3866    {
3867        return;
3868    }
3869    let framed = txlog.append(
3870        gunnar_core::txlog::Kind::File,
3871        &gunnar_core::txlog::Meta::File {
3872            path: HUB_CONF_REL.to_string(),
3873            deleted: false,
3874        },
3875        &bytes,
3876    );
3877    match framed {
3878        Ok(seq) => {
3879            // The mark is written AFTER the frame is durable. The other order would let a
3880            // crash between them leave a box claiming to have framed what it had not — and
3881            // then never framing it, which is exactly the silent loss being fixed. This order
3882            // costs at worst one duplicate frame of the same bytes after a crash.
3883            if let Err(err) = crate::durable::write_atomic_unframed(
3884                mark.parent().unwrap_or(root),
3885                HUB_CONF_FRAMED_REL
3886                    .rsplit('/')
3887                    .next()
3888                    .unwrap_or(HUB_CONF_FRAMED_REL),
3889                format!("{digest}\n").as_bytes(),
3890            ) {
3891                tracing::warn!(target: gunnar_core::observe::TARGET_TWIN, %err, "the hub declaration is framed at seq {seq}; the note saying so was not written, so the next boot frames it again");
3892            }
3893            tracing::info!(
3894                target: gunnar_core::observe::TARGET_TWIN,
3895                seq,
3896                path = %path.display(),
3897                "the site's hub declaration is a transaction: the twin holds it and a restore brings it back"
3898            );
3899        }
3900        Err(err) => tracing::warn!(
3901            target: gunnar_core::observe::TARGET_TWIN,
3902            path = %path.display(),
3903            %err,
3904            "the hub declaration could not be framed, so a twin will not hold it and a restored main would come up with no way onto the tunnel"
3905        ),
3906    }
3907}
3908
3909/// **Mark a namespace in the usage ledger when the operation ENDS** — on
3910/// every path out, errors included. Marking at the start would let a settle
3911/// in the middle measure the half-done state and clear the mark; at the end, a
3912/// mid-way measurement is simply taken again.
3913struct UsageMark<'a> {
3914    ledger: &'a crate::usage_ledger::UsageLedger,
3915    namespace: String,
3916}
3917
3918impl<'a> UsageMark<'a> {
3919    fn namespace(ledger: &'a crate::usage_ledger::UsageLedger, namespace: &str) -> Self {
3920        UsageMark {
3921            ledger,
3922            namespace: namespace.to_owned(),
3923        }
3924    }
3925}
3926
3927impl Drop for UsageMark<'_> {
3928    fn drop(&mut self) {
3929        self.ledger.mark_namespace(&self.namespace);
3930    }
3931}
3932
3933/// **The named sealed slot's row** (2026-10-09): the secret `slot/<name>`,
3934/// holding `gsl1 | u16 owner length | owner | value` — sealed as one, so the
3935/// owner cannot be moved off its value.
3936#[cfg(feature = "metered")]
3937pub mod sealed_slot {
3938    use anyhow::{bail, Result};
3939
3940    /// Every slot's secret key starts so; no M5 secret does.
3941    pub const PREFIX: &str = "slot/";
3942    const MAGIC: &[u8; 4] = b"gsl1";
3943
3944    pub fn key(name: &str) -> String {
3945        format!("{PREFIX}{name}")
3946    }
3947
3948    pub fn encode(owner: &str, value: &[u8]) -> Vec<u8> {
3949        let mut out = Vec::with_capacity(6 + owner.len() + value.len());
3950        out.extend_from_slice(MAGIC);
3951        out.extend_from_slice(&(owner.len() as u16).to_be_bytes());
3952        out.extend_from_slice(owner.as_bytes());
3953        out.extend_from_slice(value);
3954        out
3955    }
3956
3957    pub fn decode(b: &[u8]) -> Result<(String, Vec<u8>)> {
3958        if b.len() < 6 || &b[..4] != MAGIC {
3959            bail!("a sealed slot's row is not gsl1");
3960        }
3961        let n = u16::from_be_bytes([b[4], b[5]]) as usize;
3962        if b.len() < 6 + n {
3963            bail!("a sealed slot's row is cut short");
3964        }
3965        Ok((
3966            String::from_utf8(b[6..6 + n].to_vec())?,
3967            b[6 + n..].to_vec(),
3968        ))
3969    }
3970}
3971
3972/// ★ **A re-laid main mints no ticket key of its own before its twin gives the old one back**
3973/// (gunnar.rs audit round 2, RCH-TK). After `estate recharge main` the ONE box keeps the
3974/// site's appliance key: the dead main's, which the twin's sealed secrets restore. A box that
3975/// awaits its twin (`pairing/recharge_from`, [`crate::pairing::Hold::Awaiting`]) or is being
3976/// restored and minted a key first — the installer's offer and self-registration both ask —
3977/// would sign every ticket with a key the ONE box refuses, and the write itself would end
3978/// the box's freshness before the restore.
3979#[cfg(all(test, feature = "metered"))]
3980mod ticket_key_recharge_tests {
3981    use super::*;
3982
3983    #[test]
3984    fn a_main_awaiting_its_twin_mints_no_ticket_key_and_reads_the_restored_one_after() {
3985        use gunnar_store::SecretStore as _;
3986        let dir = tempfile::tempdir().unwrap();
3987        let stores = ServerStores::open(dir.path()).unwrap();
3988        let marker = dir.path().join(crate::pairing::RECHARGE_REL);
3989        std::fs::create_dir_all(marker.parent().unwrap()).unwrap();
3990        std::fs::write(&marker, "10.13.8.3:50051\n").unwrap();
3991
3992        let e = stores
3993            .actor_ticket_key()
3994            .err()
3995            .expect("no key minted while the box awaits its twin");
3996        assert!(format!("{e:#}").contains("awaits its twin"), "{e:#}");
3997        assert!(
3998            stores
3999                .secrets()
4000                .unwrap()
4001                .get(gunnar_store::ACTOR_TICKET_KEY)
4002                .unwrap()
4003                .is_none(),
4004            "nothing was written"
4005        );
4006
4007        // The restore brought the dead main's key back and the marker went: it is read, not minted.
4008        std::fs::remove_file(&marker).unwrap();
4009        let k = stores
4010            .actor_ticket_key()
4011            .expect("restored (or never recharged): the key is there or minted");
4012        assert_eq!(
4013            stores.actor_ticket_key().unwrap().public_key_hex(),
4014            k.public_key_hex()
4015        );
4016    }
4017}
4018
4019/// The jera job that flushes the last-seen record (A32-14).
4020pub const ACTIVITY_FLUSH: &str = "principal-activity";
4021
4022/// **The last-seen record's flush, every `every`, as a jera job** (A32-14): the raw
4023/// `principal-activity` thread ended at a panic without a word and was never stopped. It holds the
4024/// record weakly and ends with it (the record's drop writes the last stamps); a flush that fails
4025/// keeps the rows in memory and is said.
4026pub fn start_activity_flush(
4027    activity: &Arc<gunnar_core::PrincipalActivity>,
4028    every: std::time::Duration,
4029) -> Result<Arc<gunnar_common::jobs::Job>, String> {
4030    let weak = Arc::downgrade(activity);
4031    let mut first = true;
4032    let say: gunnar_common::jobs::Say = Arc::new(|l: &str| tracing::error!("{l}"));
4033    gunnar_common::jobs::start(ACTIVITY_FLUSH, every, say, move || {
4034        // The first look only waits, as the thread's first sleep did.
4035        if std::mem::take(&mut first) {
4036            return gunnar_common::jobs::Round::Again;
4037        }
4038        let Some(activity) = weak.upgrade() else {
4039            return gunnar_common::jobs::Round::Done;
4040        };
4041        if let Err(err) = activity.flush() {
4042            tracing::warn!(error = %err, "the last-seen rows could not be written; they are kept in memory and tried again");
4043        }
4044        gunnar_common::jobs::Round::Again
4045    })
4046}
4047
4048#[cfg(test)]
4049mod activity_flush_tests {
4050    use super::*;
4051
4052    /// ★ **The last-seen flush is a jera job that writes while the record lives and ends with it.**
4053    #[test]
4054    fn the_activity_flush_is_a_jera_job_that_ends_with_the_record() {
4055        let dir = tempfile::tempdir().expect("tempdir");
4056        let path = dir.path().join("control.redb");
4057        let db = gunnar_core::control::open_control_with_db(&path)
4058            .expect("control store")
4059            .2;
4060        let a = Arc::new(gunnar_core::PrincipalActivity::open(
4061            Arc::clone(&db),
4062            None,
4063            None,
4064        ));
4065        let job = start_activity_flush(&a, std::time::Duration::from_millis(10))
4066            .expect("the flush starts as a jera job");
4067        assert_eq!(job.kind(), ACTIVITY_FLUSH);
4068        a.signed_in("kim", 7);
4069        let t = std::time::Instant::now();
4070        let flushed = || {
4071            gunnar_core::PrincipalActivity::open(Arc::clone(&db), None, None)
4072                .seen("kim")
4073                .signed_in
4074                == Some(7)
4075        };
4076        while !flushed() && t.elapsed() < std::time::Duration::from_secs(10) {
4077            std::thread::sleep(std::time::Duration::from_millis(10));
4078        }
4079        assert!(
4080            flushed(),
4081            "the job flushed the stamp while the record lives"
4082        );
4083        drop(a);
4084        let t = std::time::Instant::now();
4085        while !job.is_stopped() && t.elapsed() < std::time::Duration::from_secs(10) {
4086            std::thread::sleep(std::time::Duration::from_millis(10));
4087        }
4088        assert!(job.is_stopped(), "the job ended with the record");
4089    }
4090}