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