Skip to main content

gunnar_core/
audit.rs

1//! **The control plane's audit trail, made tamper-evident** — an append-only
2//! hash chain over the decisions the gRPC gate makes.
3//!
4//! # What was there, and why it was not evidence
5//!
6//! Every authorised RPC already emitted one `tracing` record on
7//! `gunnar::audit` — method, principal, key fingerprint, scope, level, decision.
8//! That is a good *log* and it is not a *trail*: it goes wherever the
9//! subscriber points it, usually a file or a journal that the same box's root
10//! can rewrite, and nothing in it says whether it has been rewritten. An
11//! operator reading it cannot tell a complete record from one a line was cut
12//! out of, which is exactly the question an audit trail exists to answer. The
13//! security review recorded it as GUN-044.
14//!
15//! # The shape: each entry names the one before it
16//!
17//! ```text
18//!   entry.hash = SHA-256( "gunnar-audit-v1" ‖ prev ‖ len‖field … )
19//! ```
20//!
21//! The first entry's `prev` is [`GENESIS`] (64 zeros). Every later entry's
22//! `prev` is the previous entry's `hash`. So the tip hash commits to the whole
23//! history: change one byte of one entry and that entry's hash changes, which
24//! breaks the `prev` of the one after it, and so on to the end. Removing an
25//! entry breaks the same link; so does reordering two. There is no way to edit
26//! the middle of the file without rewriting every line after it, and a
27//! recorded tip (an operator's note, a second box, a monitoring system that
28//! reads the tip once a day) makes even that detectable.
29//!
30//! **This is not the transparency log.** [`crate::transparency`] is a Merkle
31//! tree with signed heads and inclusion proofs, which is the right shape for a
32//! log a *third party* audits without trusting the server. This is a linear
33//! chain with no signature, which is the right shape for a trail an *operator*
34//! checks on their own box, and it costs one hash per RPC and no key
35//! management. Making the control-plane trail publicly verifiable is a
36//! different, larger decision; this one closes the finding that was actually
37//! reported — a trail that cannot say whether it is complete.
38//!
39//! # The fields are length-prefixed, and that is the load-bearing detail
40//!
41//! A chain whose fields were joined with a separator would let a value
42//! containing that separator move the boundary: a `reason` of `"x\nallow"`
43//! could hash identically to a different entry whose decision really was
44//! `allow`. So each field goes in as its byte length (8 bytes, little-endian)
45//! followed by its bytes, which is unambiguous whatever the field holds. The
46//! same reasoning as [`crate::transparency`]'s domain-separating prefixes, one
47//! layer down.
48//!
49//! # One file, appended, fsynced
50//!
51//! JSON Lines, one entry per line, beside the rest of the control state — the
52//! same choice push attestation already made, for the same reason: a record
53//! that outlives the process must be readable by something that is not gunnar.
54//! Each append is durable before it returns. On the primary's REPLICATED trail
55//! ([`AuditChain::open_framed`]) the durable copy is the `Append` frame in the
56//! transaction log — group-committed with every frame staged beside it
57//! (perf, 2026-10-06: concurrent decisions share one `fdatasync`, measured
58//! 2.0 → 0.26 flushes per decision on eight request threads) — and the line in
59//! this file follows it without an fsync of its own: the file is the view of the
60//! log's frames that every start checks and rebuilds
61//! (`gunnar_server::twin::rematerialise_audit_trail`). An unframed chain (a
62//! twin's own trail) `sync_all`s each line as before.
63//!
64//! How decisions reach the chain is the gate's ledger's call
65//! (`gunnar_server::grpc_gate`): every refusal, write, admin call, self-scope
66//! call and override is one entry at once; repeated plain READS are aggregated —
67//! the first of a 60 s window at once, then one entry with the count and the
68//! first and last time (P3 of the load test, 2026-10-06, `READ_WINDOW`).
69
70use std::io::Write as _;
71use std::path::{Path, PathBuf};
72use std::sync::Mutex;
73
74use sha2::Digest as _;
75
76/// The file the chain lives in, under the control directory.
77pub const AUDIT_FILE: &str = "audit-chain.jsonl";
78
79/// Domain separation, so a hash from this chain is not a hash from anything
80/// else in this repository that also runs SHA-256 over records.
81const DOMAIN: &str = "gunnar-audit-v1";
82
83/// What the first entry's `prev` is: 64 zeros. A literal rather than an empty
84/// string, so every entry in the file has the same shape and a truncated-to-
85/// nothing `prev` cannot be mistaken for the start of the chain.
86pub const GENESIS: &str = "0000000000000000000000000000000000000000000000000000000000000000";
87
88/// What went wrong with the chain.
89#[derive(Debug, thiserror::Error)]
90pub enum AuditError {
91    /// The file could not be read, created or written.
92    #[error("the audit chain at {path}: {source}")]
93    Io {
94        /// Which file.
95        path: String,
96        /// The underlying failure.
97        source: std::io::Error,
98    },
99    /// A line in the file is not an entry.
100    #[error("the audit chain entry on line {line} does not parse: {source}")]
101    Malformed {
102        /// 1-based line number.
103        line: usize,
104        /// What serde said.
105        source: serde_json::Error,
106    },
107    /// The line could not be framed into the transaction log, so it was not
108    /// written down at all. **Deliberately not best-effort**: a trail whose
109    /// file and whose log disagree is worse than one missing entry, because
110    /// the missing entry is announced and the disagreement is not.
111    #[error("the audit chain at {path} could not be framed as a transaction: {detail}")]
112    Frame {
113        /// Which file.
114        path: String,
115        /// What the log said.
116        detail: String,
117    },
118    /// This chain was asked to be the REPLICATED trail and cannot be
119    /// ([`AuditChain::open_framed`]). Never silent: the caller says so out
120    /// loud and opens an unframed chain instead.
121    #[error("the audit chain at {path} cannot be the replicated trail: {why}")]
122    Unframed {
123        /// Which file.
124        path: String,
125        /// Why not, in a sentence an operator can act on.
126        why: String,
127    },
128    /// The box FOLLOWS (a twin, or a box being restored): it originates nothing into the
129    /// replicated trail it holds for its primary, so nothing was written ([`Recorded::NotOriginated`]
130    /// through [`AuditChain::append`]). Not a fault: the caller's log line is the record.
131    #[error("the audit chain at {path} is the primary's trail and this box follows it (a twin, or restoring): it originates nothing into it")]
132    NotOriginated {
133        /// Which file.
134        path: String,
135    },
136    /// The chain does not hold. **This is the finding, not a fault.**
137    #[error("the audit chain is broken at entry {seq} (line {line}): {what}")]
138    Broken {
139        /// The `seq` the entry claims.
140        seq: u64,
141        /// 1-based line number.
142        line: usize,
143        /// Which invariant failed, in a sentence an operator can act on.
144        what: String,
145    },
146}
147
148/// One decision, as the control plane hands it over.
149///
150/// Borrowed, because every field of it is already a `&str` at the call site and
151/// an audit record must not make the decision path allocate.
152#[derive(Debug, Clone, Copy)]
153pub struct AuditEvent<'a> {
154    /// `Service.Method`, e.g. `Access.Grant`.
155    pub method: &'a str,
156    /// The ACL principal id the credential resolved to.
157    pub principal: &'a str,
158    /// `SHA256:…` of the key that was presented, empty under the development
159    /// escape hatch.
160    pub fingerprint: &'a str,
161    /// What was asked about: `server`, `namespace:x`, `repo:x/y`.
162    pub scope: &'a str,
163    /// The grant level the method needs.
164    pub level: &'a str,
165    /// `required` or `allow-all-insecure`.
166    pub auth_mode: &'a str,
167    /// `allow`, `deny` or `narrow` — the same three words the `tracing` record
168    /// carries, so the two can be read side by side.
169    pub decision: &'a str,
170    /// Why, for a decision that has a why. Empty otherwise.
171    pub reason: &'a str,
172}
173
174/// One entry, as it sits on disk.
175///
176/// Field order is the serialisation order and the hashing order. It is
177/// `deny_unknown_fields` so a file written by a newer gunnar is refused loudly
178/// rather than verified against fields this build cannot see.
179#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
180#[serde(deny_unknown_fields)]
181pub struct AuditEntry {
182    /// 0 for the first entry, then +1 each time. Redundant with the file's line
183    /// numbering on purpose: a chain whose only ordering was its line order
184    /// could be truncated to a shorter, still-valid chain without the entries
185    /// themselves saying anything was missing.
186    pub seq: u64,
187    /// When the decision was made.
188    pub at_unix_ms: i64,
189    /// `Service.Method`.
190    pub method: String,
191    /// The ACL principal id.
192    pub principal: String,
193    /// The key fingerprint.
194    pub fingerprint: String,
195    /// The scope asked about.
196    pub scope: String,
197    /// The grant level.
198    pub level: String,
199    /// The authentication mode the listener was in.
200    pub auth_mode: String,
201    /// `allow`, `deny`, `narrow`.
202    pub decision: String,
203    /// Why, or empty.
204    pub reason: String,
205    /// The previous entry's [`AuditEntry::hash`], or [`GENESIS`].
206    pub prev: String,
207    /// This entry's own hash. Not hashed into itself; see [`AuditEntry::compute_hash`].
208    pub hash: String,
209}
210
211impl AuditEntry {
212    /// The hash this entry **should** carry, computed from everything else in
213    /// it.
214    ///
215    /// Verification is `entry.hash == entry.compute_hash()` plus
216    /// `entry.prev == previous.hash`. Both halves are needed: the first catches
217    /// an edited field, the second catches a removed, reordered or inserted
218    /// entry.
219    pub fn compute_hash(&self) -> String {
220        let mut hasher = sha2::Sha256::new();
221        let mut field = |bytes: &[u8]| {
222            // Length-prefixed, so no value can move a field boundary. See the
223            // module docs.
224            hasher.update((bytes.len() as u64).to_le_bytes());
225            hasher.update(bytes);
226        };
227        field(DOMAIN.as_bytes());
228        field(self.prev.as_bytes());
229        field(&self.seq.to_le_bytes());
230        field(&self.at_unix_ms.to_le_bytes());
231        field(self.method.as_bytes());
232        field(self.principal.as_bytes());
233        field(self.fingerprint.as_bytes());
234        field(self.scope.as_bytes());
235        field(self.level.as_bytes());
236        field(self.auth_mode.as_bytes());
237        field(self.decision.as_bytes());
238        field(self.reason.as_bytes());
239        let digest = hasher.finalize();
240        let mut out = String::with_capacity(64);
241        for byte in digest {
242            use std::fmt::Write as _;
243            let _ = write!(out, "{byte:02x}");
244        }
245        out
246    }
247}
248
249/// **The chain itself.** Open it once and append to it; it is `Send + Sync` and
250/// holds its own lock, because one server writes one chain from many request
251/// threads and two appends that interleaved would each claim the same `prev`.
252#[derive(Debug)]
253pub struct AuditChain {
254    path: PathBuf,
255    tip: Mutex<Tip>,
256    /// **Is every entry also a transaction?** ([`AuditChain::open_framed`]).
257    ///
258    /// The primary's trail is: it goes into the box's transaction log as an
259    /// `Append` frame, so the twin holds it and a restore brings it back. The
260    /// twin's OWN trail is not, and neither is a test's — see
261    /// [`crate::txlog::AUDIT_LOCAL_REL`].
262    framed: bool,
263}
264
265/// What the next entry needs to know about the last one.
266#[derive(Debug)]
267struct Tip {
268    next_seq: u64,
269    hash: String,
270    /// Lines computed while the log was RELEASED (the data set being grown and unmounted),
271    /// oldest first, each already linked to the one before it: framed and written, in order,
272    /// once the log is taken back ([`AuditChain::flush`]).
273    queued: Vec<String>,
274    /// The box followed its primary since this tip was read: the file may hold the primary's
275    /// entries now, so the tip is read from the file again before the next write.
276    stale: bool,
277    /// **Lines framed and not yet in the file**, oldest first, each with its frame's sequence
278    /// number (perf, 2026-10-06): a framed chain stages its frame, waits for the group's fsync
279    /// with the tip unlocked — so concurrent decisions share one — and only then writes the line,
280    /// in chain order, every line whose frame is durable.
281    unfiled: Vec<(u64, String)>,
282}
283
284/// **What became of one decision** ([`AuditChain::record`]).
285#[derive(Debug, Clone)]
286pub enum Recorded {
287    /// In the file (and, for a framed chain, in the transaction log).
288    Written(AuditEntry),
289    /// The log is RELEASED (the data set is being grown): the entry is linked and held in
290    /// memory, in order, and is framed and written by the first [`AuditChain::record`] or
291    /// [`AuditChain::flush`] after the remount. `pending` counts the held entries.
292    Queued {
293        /// The entry, as it will be written.
294        entry: AuditEntry,
295        /// How many entries wait.
296        pending: usize,
297    },
298    /// The box FOLLOWS its primary (a twin, or restoring): a framed chain is the primary's
299    /// trail, and this box originates nothing into it. Written nowhere.
300    NotOriginated,
301}
302
303/// What one framed write came to.
304enum Wrote {
305    Yes,
306    /// The log is released: nothing framed, nothing written.
307    Released,
308    /// The log follows: nothing framed, nothing written.
309    Follower,
310}
311
312impl AuditChain {
313    /// Open — or start — the chain at `path`.
314    ///
315    /// The existing file is **read and verified** at open, not merely counted.
316    /// A server that appended to a chain it had not checked would extend
317    /// somebody's forgery with genuine entries and make the break look like it
318    /// happened later than it did.
319    pub fn open(path: impl Into<PathBuf>) -> Result<AuditChain, AuditError> {
320        let path = path.into();
321        if let Some(parent) = path.parent() {
322            std::fs::create_dir_all(parent).map_err(|source| AuditError::Io {
323                path: parent.display().to_string(),
324                source,
325            })?;
326        }
327        let entries = read_entries(&path)?;
328        verify_entries(&entries)?;
329        let tip = match entries.last() {
330            Some(last) => Tip {
331                next_seq: last.seq + 1,
332                hash: last.hash.clone(),
333                queued: Vec::new(),
334                stale: false,
335                unfiled: Vec::new(),
336            },
337            None => Tip {
338                next_seq: 0,
339                hash: GENESIS.to_owned(),
340                queued: Vec::new(),
341                stale: false,
342                unfiled: Vec::new(),
343            },
344        };
345        Ok(AuditChain {
346            path,
347            tip: Mutex::new(tip),
348            framed: false,
349        })
350    }
351
352    /// **Open the chain as the REPLICATED trail** — every append is an
353    /// `Append` transaction before it is a line in a file, so the twin holds
354    /// the trail and `gunnar control twin replay` brings it back.
355    ///
356    /// This is the D6 fix (lane T11, 2026-09-21). Before it, `log/` was a
357    /// per-box path: the twin never held the audit trail and a restore came up
358    /// with none, reporting success. The restore happens on the worst day,
359    /// which is the day somebody has to reconstruct what happened.
360    ///
361    /// **It refuses rather than falling back.** The chain must sit at
362    /// [`crate::txlog::AUDIT_REL`] under a data root the sink knows, or this
363    /// returns [`AuditError::Unframed`] naming why. A chain that quietly
364    /// wrote unframed lines would reproduce the exact bug — a trail the
365    /// restore drops without saying so. The caller's job is to say it out
366    /// loud and open an ordinary chain with [`AuditChain::open`].
367    pub fn open_framed(path: impl Into<PathBuf>) -> Result<AuditChain, AuditError> {
368        let path = path.into();
369        match crate::txlog::sink::log_for(&path) {
370            None => {
371                return Err(AuditError::Unframed {
372                    path: path.display().to_string(),
373                    why: "it is under no data root that has a transaction log — the layout put \
374                          the `log` directory outside the data root, or this box originates \
375                          nothing (a twin, a box being restored)"
376                        .to_owned(),
377                })
378            }
379            Some((_, rel)) if rel != crate::txlog::AUDIT_REL => {
380                return Err(AuditError::Unframed {
381                    path: path.display().to_string(),
382                    why: format!(
383                        "the log would name it {rel:?}, and a restore resolves only {:?}",
384                        crate::txlog::AUDIT_REL
385                    ),
386                })
387            }
388            Some(_) => {}
389        }
390        let mut chain = AuditChain::open(path)?;
391        chain.framed = true;
392        Ok(chain)
393    }
394
395    /// Does every append of this chain also become a transaction? See
396    /// [`AuditChain::open_framed`].
397    pub fn is_framed(&self) -> bool {
398        self.framed
399    }
400
401    /// Where the chain lives.
402    pub fn path(&self) -> &Path {
403        &self.path
404    }
405
406    /// **Append one decision.** Returns the entry that was written (or, while the log is
407    /// released, queued — [`Recorded::Queued`]), whose `hash` is the new tip an operator can
408    /// record. A box that follows its primary answers [`AuditError::NotOriginated`].
409    pub fn append(&self, event: AuditEvent<'_>, at_unix_ms: i64) -> Result<AuditEntry, AuditError> {
410        match self.record(event, at_unix_ms)? {
411            Recorded::Written(entry) | Recorded::Queued { entry, .. } => Ok(entry),
412            Recorded::NotOriginated => Err(AuditError::NotOriginated { path: self.path.display().to_string() }),
413        }
414    }
415
416    /// The log this chain frames into, when it is framed and the sink knows its root.
417    fn framing_log(&self) -> Option<std::sync::Arc<crate::txlog::Log>> {
418        if self.framed {
419            crate::txlog::sink::log_for(&self.path).map(|(log, _)| log)
420        } else {
421            None
422        }
423    }
424
425    /// **Record one decision** — [`Recorded`] says what became of it.
426    ///
427    /// G + G2 (release-3 test2 mock 2026-09-29): a chain opened framed on a box that was
428    /// then told `BecomeTwin` at runtime, and a primary whose log was released for its own
429    /// growth, answered every decision with an error (`txlog: this box is a twin …`, `txlog:
430    /// released …`) that the gate logged at ERROR — 13 and 4 lines per mock — and the grow's
431    /// decisions were lost. A follower now originates nothing and says so without an error; a
432    /// released log holds the trail in memory, in order, and writes it after the remount.
433    pub fn record(&self, event: AuditEvent<'_>, at_unix_ms: i64) -> Result<Recorded, AuditError> {
434        // A framed decision is a mutation of the replicated trail, and its guard is taken BEFORE
435        // the chain's own lock and held until the file has the line: a snapshot's freeze waits
436        // for every guard in flight, and a thread that held the chain while it waited on the
437        // freeze would stop the very thread the freeze waits for (that one files its line under
438        // the chain's lock after its frame's fsync). The guards the frame write takes inside are
439        // nested and count once.
440        let _mutation = self.framing_log().map(|log| log.mutation());
441        // Poisoning is not a reason to stop writing the audit trail: a panic in
442        // some other request's append leaves the tip behind, and refusing every
443        // later record would turn one bug into a gap in the evidence.
444        let mut tip = self
445            .tip
446            .lock()
447            .unwrap_or_else(|poisoned| poisoned.into_inner());
448        let log = self.framing_log();
449        if log.as_ref().is_some_and(|l| l.is_follower()) {
450            // The file is the PRIMARY's trail now (the twin applies its frames into it): a
451            // local line would splice a second writer into a one-writer chain. Anything held
452            // from before is the primary role's, which ended.
453            tip.queued.clear();
454            tip.unfiled.clear();
455            tip.stale = true;
456            return Ok(Recorded::NotOriginated);
457        }
458        if tip.stale {
459            // Promoted again: continue from what the file holds NOW, not from the tip this
460            // box remembered before it followed.
461            let entries = read_entries(&self.path)?;
462            match entries.last() {
463                Some(last) => {
464                    tip.next_seq = last.seq + 1;
465                    tip.hash.clone_from(&last.hash);
466                }
467                None => {
468                    tip.next_seq = 0;
469                    tip.hash = GENESIS.to_owned();
470                }
471            }
472            tip.stale = false;
473        }
474        let released = log.as_ref().is_some_and(|l| l.is_released());
475        if !released {
476            self.flush_locked(&mut tip)?;
477        }
478
479        let mut entry = AuditEntry {
480            seq: tip.next_seq,
481            at_unix_ms,
482            method: event.method.to_owned(),
483            principal: event.principal.to_owned(),
484            fingerprint: event.fingerprint.to_owned(),
485            scope: event.scope.to_owned(),
486            level: event.level.to_owned(),
487            auth_mode: event.auth_mode.to_owned(),
488            decision: event.decision.to_owned(),
489            reason: event.reason.to_owned(),
490            prev: tip.hash.clone(),
491            hash: String::new(),
492        };
493        entry.hash = entry.compute_hash();
494
495        let line = serde_json::to_string(&entry).expect("an audit entry serialises");
496        debug_assert!(!line.contains('\n'), "a JSONL record holds no newline");
497
498        if released || !tip.queued.is_empty() {
499            return Ok(Self::hold(&mut tip, entry, line));
500        }
501        if self.framed {
502            // ── the group-committed path (perf, 2026-10-06) ──
503            match crate::txlog::sink::stage_line(&self.path, &line) {
504                Ok(Some(staged)) => {
505                    tip.next_seq = entry.seq + 1;
506                    tip.hash.clone_from(&entry.hash);
507                    tip.unfiled.push((staged.seq(), line));
508                    // The fsync is waited for with the tip UNLOCKED: decisions made meanwhile
509                    // link onto this one and stage their frames behind it, and one leader's
510                    // fdatasync makes them all durable.
511                    drop(tip);
512                    staged.durable().map_err(|e| AuditError::Frame { path: self.path.display().to_string(), detail: e.to_string() })?;
513                    let mut tip = self.tip.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
514                    self.file_durable(&mut tip, staged.log())?;
515                    drop(tip);
516                    // The mutation guard goes only now: the file has the line.
517                    drop(staged);
518                    return Ok(Recorded::Written(entry));
519                }
520                Ok(None) => {} // under no registered root any more: the unframed write below
521                Err(crate::txlog::Error::Released(_)) => return Ok(Self::hold(&mut tip, entry, line)),
522                Err(crate::txlog::Error::Follower) => {
523                    tip.stale = true;
524                    return Ok(Recorded::NotOriginated);
525                }
526                Err(source) => {
527                    return Err(AuditError::Frame { path: self.path.display().to_string(), detail: source.to_string() });
528                }
529            }
530        }
531        match self.write_line(&line)? {
532            Wrote::Yes => {}
533            Wrote::Released => return Ok(Self::hold(&mut tip, entry, line)),
534            Wrote::Follower => {
535                tip.stale = true;
536                return Ok(Recorded::NotOriginated);
537            }
538        }
539        tip.next_seq = entry.seq + 1;
540        tip.hash.clone_from(&entry.hash);
541        Ok(Recorded::Written(entry))
542    }
543
544    /// Hold a linked entry until the log is taken back.
545    fn hold(tip: &mut Tip, entry: AuditEntry, line: String) -> Recorded {
546        tip.queued.push(line);
547        tip.next_seq = entry.seq + 1;
548        tip.hash.clone_from(&entry.hash);
549        Recorded::Queued { entry, pending: tip.queued.len() }
550    }
551
552    /// How many entries wait for the log to be taken back ([`Recorded::Queued`]).
553    pub fn queued(&self) -> usize {
554        self.tip.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).queued.len()
555    }
556
557    /// **Write what waits** — every held entry, in order, once the log is taken back (the
558    /// remount after a growth). Answers how many were written; a log still released writes
559    /// none and keeps them.
560    pub fn flush(&self) -> Result<usize, AuditError> {
561        let mut tip = self
562            .tip
563            .lock()
564            .unwrap_or_else(|poisoned| poisoned.into_inner());
565        if self.framing_log().is_some_and(|l| l.is_released() || l.is_follower()) {
566            return Ok(0);
567        }
568        self.flush_locked(&mut tip)
569    }
570
571    /// **Write every framed line whose frame is durable into the file**, oldest first, as ONE
572    /// write and WITHOUT an fsync: the frame is the durable copy, and the file is the view of the
573    /// log's frames that every start checks and rebuilds (`gunnar_server::twin::
574    /// rematerialise_audit_trail`, T17) — an fsync per line here bought nothing the log does not
575    /// already hold, at the cost of a second flush per decision. A line whose write fails stays
576    /// unfiled and goes with the next.
577    fn file_durable(&self, tip: &mut Tip, log: &crate::txlog::Log) -> Result<usize, AuditError> {
578        let head = log.head_seq();
579        let n = tip.unfiled.iter().take_while(|(seq, _)| *seq <= head).count();
580        if n == 0 {
581            return Ok(0);
582        }
583        let mut bytes = Vec::with_capacity(tip.unfiled[..n].iter().map(|(_, l)| l.len() + 1).sum());
584        for (_, l) in &tip.unfiled[..n] {
585            bytes.extend_from_slice(l.as_bytes());
586            bytes.push(b'\n');
587        }
588        let io = |source: std::io::Error| AuditError::Io { path: self.path.display().to_string(), source };
589        let mut file = std::fs::OpenOptions::new().create(true).append(true).open(&self.path).map_err(io)?;
590        file.write_all(&bytes).map_err(io)?;
591        tip.unfiled.drain(..n);
592        Ok(n)
593    }
594
595    fn flush_locked(&self, tip: &mut Tip) -> Result<usize, AuditError> {
596        // Framed lines whose frames are durable go into the file first — they precede anything
597        // held. Their fsync is NOT forced here (that would hold the tip across an fsync and undo
598        // the group commit): the thread that staged each one files it. Only held lines waiting
599        // behind them (a release just ended) are worth an fsync of their own.
600        if !tip.unfiled.is_empty() {
601            if let Some(log) = self.framing_log() {
602                if !tip.queued.is_empty() {
603                    let last = tip.unfiled.last().map(|(s, _)| *s).unwrap_or(0);
604                    log.sync_through(last).map_err(|e| AuditError::Frame { path: self.path.display().to_string(), detail: e.to_string() })?;
605                }
606                self.file_durable(tip, &log)?;
607            }
608            if !tip.unfiled.is_empty() && !tip.queued.is_empty() {
609                return Ok(0);
610            }
611        }
612        let mut n = 0;
613        while let Some(line) = tip.queued.first().cloned() {
614            match self.write_line(&line)? {
615                Wrote::Yes => {
616                    tip.queued.remove(0);
617                    n += 1;
618                }
619                Wrote::Released | Wrote::Follower => break,
620            }
621        }
622        Ok(n)
623    }
624
625    /// Frame `line` (a framed chain) and append it to the file, durable.
626    fn write_line(&self, line: &str) -> Result<Wrote, AuditError> {
627        // **The trail is a transaction before it is a line** (lane T11). Framed FIRST and held
628        // until the file has the write, exactly as `attest.rs` frames an attestation: the
629        // mutation gate keeps a snapshot from cutting between the frame and the byte, so the
630        // twin can never hold a trail that is ahead of the file or behind it.
631        //
632        // NOT best effort. The gate's contract is that a failure here is one `error!` and a
633        // served RPC, and that contract is kept by the CALLER — what must not happen is a line
634        // in the file with no frame behind it, because the restore would then bring back a
635        // chain with a hole in the middle and `verify` would report the break as the
636        // primary's, months later, to somebody who cannot know it was ours.
637        let _framed = if self.framed {
638            match crate::txlog::sink::append_line(&self.path, line) {
639                Ok(f) => Some(f),
640                Err(crate::txlog::Error::Released(_)) => return Ok(Wrote::Released),
641                Err(crate::txlog::Error::Follower) => return Ok(Wrote::Follower),
642                Err(source) => {
643                    return Err(AuditError::Frame {
644                        path: self.path.display().to_string(),
645                        detail: source.to_string(),
646                    })
647                }
648            }
649        } else {
650            None
651        };
652        // G3: an UNFRAMED chain (the twin's own trail) has no log to tell it the set is off;
653        // the directory it lives in is gone while a growth has /data unmounted. That is the
654        // same state as a released log: hold the line, write it after the remount — and never
655        // create the directory on the root filesystem under the empty mountpoint.
656        if _framed.is_none() && self.path.parent().is_some_and(|p| !p.exists()) {
657            return Ok(Wrote::Released);
658        }
659        let io = |source: std::io::Error| AuditError::Io {
660            path: self.path.display().to_string(),
661            source,
662        };
663        let mut file = std::fs::OpenOptions::new()
664            .create(true)
665            .append(true)
666            .open(&self.path)
667            .map_err(io)?;
668        file.write_all(format!("{line}\n").as_bytes()).map_err(io)?;
669        // Durable before the caller is told it landed; see the module docs.
670        file.sync_all().map_err(io)?;
671        Ok(Wrote::Yes)
672    }
673
674    /// Every entry, oldest first.
675    pub fn entries(&self) -> Result<Vec<AuditEntry>, AuditError> {
676        read_entries(&self.path)
677    }
678
679    /// **Check the chain end to end.** `Ok(n)` is "n entries, and they hold".
680    ///
681    /// This is the function the finding asks for: an operator (or
682    /// `cargo test`) can ask the file whether anything in it has been changed
683    /// or removed, and get an answer that names the entry rather than a
684    /// shrug.
685    pub fn verify(&self) -> Result<usize, AuditError> {
686        let entries = read_entries(&self.path)?;
687        verify_entries(&entries)?;
688        Ok(entries.len())
689    }
690
691    /// The current tip hash — what a whole history commits to.
692    ///
693    /// Worth writing down somewhere the box cannot reach: with a recorded tip,
694    /// even a rewrite of the entire file is detected.
695    pub fn tip(&self) -> String {
696        self.tip
697            .lock()
698            .unwrap_or_else(|poisoned| poisoned.into_inner())
699            .hash
700            .clone()
701    }
702}
703
704/// Read the file, or `[]` if it is not there yet.
705fn read_entries(path: &Path) -> Result<Vec<AuditEntry>, AuditError> {
706    let text = match std::fs::read_to_string(path) {
707        Ok(text) => text,
708        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
709        Err(source) => {
710            return Err(AuditError::Io {
711                path: path.display().to_string(),
712                source,
713            })
714        }
715    };
716    let mut out = Vec::new();
717    for (index, line) in text.lines().enumerate() {
718        if line.trim().is_empty() {
719            continue;
720        }
721        let entry = serde_json::from_str(line).map_err(|source| AuditError::Malformed {
722            line: index + 1,
723            source,
724        })?;
725        out.push(entry);
726    }
727    Ok(out)
728}
729
730/// The arithmetic, over entries already parsed.
731///
732/// Separate from the file so a caller with entries in hand — a test, a future
733/// reader that streams — checks them with the same code the server does (one
734/// implementation).
735pub fn verify_entries(entries: &[AuditEntry]) -> Result<(), AuditError> {
736    let mut expected_prev = GENESIS.to_owned();
737    for (index, entry) in entries.iter().enumerate() {
738        let line = index + 1;
739        let broken = |what: String| AuditError::Broken {
740            seq: entry.seq,
741            line,
742            what,
743        };
744        if entry.seq != index as u64 {
745            return Err(broken(format!(
746                "it is the {}th entry in the file and claims seq {}; an entry has been removed \
747                 or reordered",
748                index, entry.seq
749            )));
750        }
751        if entry.prev != expected_prev {
752            return Err(broken(format!(
753                "it names {} as the entry before it and the entry before it hashes to {}; \
754                 the chain has been cut",
755                short(&entry.prev),
756                short(&expected_prev)
757            )));
758        }
759        let computed = entry.compute_hash();
760        if entry.hash != computed {
761            return Err(broken(format!(
762                "its contents hash to {} and it carries {}; this entry has been edited",
763                short(&computed),
764                short(&entry.hash)
765            )));
766        }
767        expected_prev = entry.hash.clone();
768    }
769    Ok(())
770}
771
772/// A hash, shortened for a message a person reads. The full value is in the
773/// file.
774fn short(hash: &str) -> &str {
775    hash.get(..12).unwrap_or(hash)
776}
777
778#[cfg(test)]
779mod tests {
780    use super::*;
781
782    fn event<'a>(method: &'a str, decision: &'a str) -> AuditEvent<'a> {
783        AuditEvent {
784            method,
785            principal: "alice",
786            fingerprint: "SHA256:abc",
787            scope: "repo:team/app",
788            level: "admin",
789            auth_mode: "required",
790            decision,
791            reason: "",
792        }
793    }
794
795    fn chain_of(path: &Path, count: usize) -> AuditChain {
796        let chain = AuditChain::open(path).expect("open");
797        for index in 0..count {
798            chain
799                .append(
800                    event("Access.Grant", "allow"),
801                    1_700_000_000_000 + index as i64,
802                )
803                .expect("append");
804        }
805        chain
806    }
807
808    /// The accept side, and the shape. Without it every tamper assertion below
809    /// would pass against a `verify` that refused everything.
810    #[test]
811    fn a_chain_links_each_entry_to_the_one_before_it_and_verifies() {
812        let dir = tempfile::tempdir().expect("tempdir");
813        let path = dir.path().join(AUDIT_FILE);
814        let chain = chain_of(&path, 3);
815        assert_eq!(chain.verify().expect("a fresh chain verifies"), 3);
816
817        let entries = chain.entries().expect("read");
818        assert_eq!(entries[0].prev, GENESIS, "the first entry starts the chain");
819        assert_eq!(entries[1].prev, entries[0].hash);
820        assert_eq!(entries[2].prev, entries[1].hash);
821        assert_eq!(chain.tip(), entries[2].hash);
822        assert_eq!((entries[0].seq, entries[2].seq), (0, 2));
823
824        // Reopening continues the chain rather than starting a second one: the
825        // tip is read back off the file, which is what makes a restart
826        // invisible to a verifier.
827        let reopened = AuditChain::open(&path).expect("reopen");
828        assert_eq!(reopened.tip(), entries[2].hash);
829        reopened
830            .append(event("Repos.Delete", "deny"), 1_700_000_009_000)
831            .expect("append after reopen");
832        assert_eq!(reopened.verify().expect("still holds"), 4);
833        let entries = reopened.entries().expect("read");
834        assert_eq!(entries[3].prev, entries[2].hash);
835    }
836
837    /// **A modified entry is detected.** The whole point: `tracing` could not
838    /// say this, and this is the sentence the operator gets.
839    #[test]
840    fn an_edited_entry_is_named() {
841        let dir = tempfile::tempdir().expect("tempdir");
842        let path = dir.path().join(AUDIT_FILE);
843        let _chain = chain_of(&path, 3);
844
845        // Rewrite the middle record's decision, the edit somebody covering a
846        // refusal would make, leaving everything else — the hash included —
847        // exactly as gunnar wrote it.
848        let text = std::fs::read_to_string(&path).expect("read");
849        let mut lines: Vec<String> = text.lines().map(str::to_owned).collect();
850        lines[1] = lines[1].replace("\"decision\":\"allow\"", "\"decision\":\"deny\"");
851        std::fs::write(&path, lines.join("\n") + "\n").expect("rewrite");
852
853        let err = AuditChain::open(&path).expect_err("a rewritten chain must not open");
854        match err {
855            AuditError::Broken {
856                seq,
857                line,
858                ref what,
859            } => {
860                assert_eq!((seq, line), (1, 2), "the break must be named: {what}");
861                assert!(what.contains("edited"), "{what}");
862            }
863            other => panic!("the edit was not detected: {other}"),
864        }
865    }
866
867    /// **A removed entry is detected** — the tamper `tracing` is least able to
868    /// show, because a deleted line leaves nothing behind.
869    #[test]
870    fn a_removed_entry_is_named() {
871        let dir = tempfile::tempdir().expect("tempdir");
872        let path = dir.path().join(AUDIT_FILE);
873        let chain = chain_of(&path, 4);
874        assert_eq!(chain.verify().expect("green first"), 4);
875
876        let text = std::fs::read_to_string(&path).expect("read");
877        let lines: Vec<&str> = text.lines().collect();
878        // Drop the second of four.
879        let cut: Vec<&str> = lines
880            .iter()
881            .enumerate()
882            .filter(|(index, _)| *index != 1)
883            .map(|(_, line)| *line)
884            .collect();
885        std::fs::write(&path, cut.join("\n") + "\n").expect("rewrite");
886
887        let err = AuditChain::open(&path).expect_err("a cut chain must not open");
888        assert!(
889            matches!(
890                err,
891                AuditError::Broken {
892                    seq: 2,
893                    line: 2,
894                    ..
895                }
896            ),
897            "the removal was not detected where it happened: {err}"
898        );
899    }
900
901    /// **Truncating the tail is detected too — but only against a recorded
902    /// tip**, and the difference is stated rather than assumed.
903    ///
904    /// Cutting the LAST entries leaves a chain that is internally consistent:
905    /// that is what a hash chain is, and claiming otherwise would be the kind
906    /// of overclaim this file is here to replace. What catches it is the tip an
907    /// operator wrote down, so the test asserts exactly that — the shortened
908    /// file verifies, and its tip is not the one that was recorded.
909    #[test]
910    fn a_truncated_tail_verifies_but_does_not_match_the_recorded_tip() {
911        let dir = tempfile::tempdir().expect("tempdir");
912        let path = dir.path().join(AUDIT_FILE);
913        let chain = chain_of(&path, 4);
914        let recorded = chain.tip();
915
916        let text = std::fs::read_to_string(&path).expect("read");
917        let kept: Vec<&str> = text.lines().take(2).collect();
918        std::fs::write(&path, kept.join("\n") + "\n").expect("rewrite");
919
920        let shortened = AuditChain::open(&path).expect("a truncated chain is self-consistent");
921        assert_eq!(shortened.verify().expect("and verifies"), 2);
922        assert_ne!(
923            shortened.tip(),
924            recorded,
925            "a truncated chain reproduced the tip of the full one"
926        );
927    }
928
929    /// A field cannot be moved across a boundary into another field, because
930    /// each one is length-prefixed. Without the prefixes these two entries hash
931    /// the same.
932    #[test]
933    fn a_field_holding_a_separator_cannot_impersonate_two_fields() {
934        let base = AuditEntry {
935            seq: 0,
936            at_unix_ms: 1,
937            method: "Access.Grant".into(),
938            principal: "alice".into(),
939            fingerprint: "SHA256:abc".into(),
940            scope: "server".into(),
941            level: "admin".into(),
942            auth_mode: "required".into(),
943            decision: "deny".into(),
944            reason: String::new(),
945            prev: GENESIS.into(),
946            hash: String::new(),
947        };
948        // The pair that COLLIDES under a newline-joined concatenation: both
949        // sides render as `alice\nSHA256:abc\n`, and only the length prefixes
950        // tell them apart.
951        let mut shifted = base.clone();
952        shifted.principal = "alice\nSHA256:abc".into();
953        shifted.fingerprint = String::new();
954        // The naive concatenation of the two differs only in where the
955        // boundary is drawn.
956        assert_ne!(
957            base.compute_hash(),
958            shifted.compute_hash(),
959            "two entries with different field boundaries hash the same"
960        );
961    }
962
963    // ── the trail survives a restore (lane T11, 2026-09-21; the D6 finding) ──
964
965    /// A data root with a transaction log registered on it, and the audit chain where the
966    /// layout puts it: `<root>/log/audit-chain.jsonl`.
967    fn framed_root() -> (tempfile::TempDir, std::sync::Arc<crate::txlog::Log>, PathBuf) {
968        let dir = tempfile::tempdir().expect("tempdir");
969        let log =
970            std::sync::Arc::new(crate::txlog::Log::open(dir.path().join("txlog")).expect("a log"));
971        crate::txlog::sink::register(dir.path(), &log);
972        let path = dir.path().join(crate::txlog::AUDIT_REL);
973        (dir, log, path)
974    }
975
976    fn a_decision(method: &str) -> AuditEvent<'_> {
977        AuditEvent {
978            method,
979            principal: "alice",
980            fingerprint: "SHA256:abc",
981            scope: "server",
982            level: "admin",
983            auth_mode: "required",
984            decision: "allow",
985            reason: "",
986        }
987    }
988
989    /// **Every entry of a framed chain is a transaction**, so the twin holds the audit trail
990    /// and `gunnar control twin replay` brings it back. That is the whole D6 fix: before it,
991    /// `log/` was a per-box path and a restore came up with no audit history, silently.
992    ///
993    /// Proven the way a restore would see it: the frames are read back out of the log and the
994    /// file is rebuilt from them alone, then opened and verified.
995    ///
996    /// **Fails before the fix**: make `AuditChain::open_framed` return the chain that
997    /// `AuditChain::open` returns (drop the `chain.framed = true;` line) and the log holds
998    /// nothing — `head_seq()` is 0 and the rebuilt file is empty.
999    #[test]
1000    fn a_framed_chain_puts_every_entry_in_the_transaction_log() {
1001        let (_dir, log, path) = framed_root();
1002        let chain = AuditChain::open_framed(&path).expect("the trail is framable where it lives");
1003        assert!(chain.is_framed());
1004        for m in ["Repos.Create", "Access.Grant", "Policy.SetProtection"] {
1005            chain.append(a_decision(m), 1).expect("append");
1006        }
1007        assert_eq!(chain.verify().expect("verify"), 3);
1008
1009        // What the twin holds: three `Append` frames, all naming the ONE canonical path, in
1010        // the order the chain wrote them.
1011        assert_eq!(log.head_seq(), 3, "one frame per decision");
1012        let mut rebuilt = String::new();
1013        for seq in 1..=3 {
1014            let e = log.read(seq).expect("a frame");
1015            assert_eq!(e.kind(), Some(crate::txlog::Kind::Append));
1016            match e.meta().expect("meta") {
1017                crate::txlog::Meta::Append { log: rel } => assert_eq!(rel, crate::txlog::AUDIT_REL),
1018                other => panic!("seq {seq} is {other:?}, not an Append of the audit trail"),
1019            }
1020            rebuilt.push_str(std::str::from_utf8(&e.blob).expect("utf8"));
1021            rebuilt.push('\n');
1022        }
1023
1024        // A restored box rebuilds the file from the frames alone — and it verifies, with the
1025        // same tip. That is the property the owner asked for in one assertion.
1026        let elsewhere = tempfile::tempdir().expect("tempdir");
1027        let restored_path = elsewhere.path().join("audit-chain.jsonl");
1028        std::fs::write(&restored_path, rebuilt).expect("write");
1029        let restored = AuditChain::open(&restored_path).expect("a restored trail opens");
1030        assert_eq!(restored.verify().expect("verify"), 3);
1031        assert_eq!(restored.tip(), chain.tip());
1032
1033        // And the restored box CONTINUES the chain rather than starting a new one: its next
1034        // entry's `prev` is the dead primary's tip, so the history is unbroken across the
1035        // disaster.
1036        let next = restored.append(a_decision("Repos.List"), 2).expect("append");
1037        assert_eq!(next.prev, chain.tip());
1038        assert_eq!(next.seq, 3);
1039    }
1040
1041    /// **A chain that cannot be replicated REFUSES to pretend it is**, rather than quietly
1042    /// writing unframed lines — which is the exact shape of the bug being fixed: a record the
1043    /// restore drops without saying so.
1044    ///
1045    /// Two ways it can happen: the `log` directory resolved outside any data root (no sink),
1046    /// and the chain sitting somewhere other than the one path a restore resolves.
1047    ///
1048    /// **Fails before the fix**: delete the `match crate::txlog::sink::log_for(&path)` block
1049    /// from `AuditChain::open_framed` and both halves return `Ok`.
1050    #[test]
1051    fn an_unreplicable_chain_refuses_to_be_the_replicated_trail() {
1052        let outside = tempfile::tempdir().expect("tempdir");
1053        let err = AuditChain::open_framed(outside.path().join("audit-chain.jsonl"))
1054            .expect_err("a chain under no data root is not the replicated trail");
1055        assert!(matches!(err, AuditError::Unframed { .. }), "{err}");
1056        assert!(format!("{err}").contains("under no data root"), "{err}");
1057
1058        let (dir, _log, _path) = framed_root();
1059        let misplaced = dir.path().join("somewhere-else.jsonl");
1060        let err = AuditChain::open_framed(&misplaced).expect_err("a misplaced chain is refused");
1061        assert!(matches!(err, AuditError::Unframed { .. }), "{err}");
1062        assert!(format!("{err}").contains(crate::txlog::AUDIT_REL), "{err}");
1063    }
1064
1065    /// **An unframed chain frames nothing** — the twin's own trail
1066    /// ([`crate::txlog::AUDIT_LOCAL_REL`]) and every test harness. A twin originates nothing,
1067    /// and a twin that put its own decisions into the log it is holding for the primary would
1068    /// be forging the primary's trail.
1069    ///
1070    /// **Fails before the fix**: make `AuditChain::append` frame unconditionally (drop the
1071    /// `if self.framed`) and the log holds the twin's own decision at seq 1.
1072    #[test]
1073    fn a_twins_own_trail_is_never_a_transaction() {
1074        let (dir, log, _path) = framed_root();
1075        let local = dir.path().join(crate::txlog::AUDIT_LOCAL_REL);
1076        let chain = AuditChain::open(&local).expect("the twin's own trail opens");
1077        assert!(!chain.is_framed());
1078        chain.append(a_decision("Mirror.LogHead"), 1).expect("append");
1079        assert_eq!(log.head_seq(), 0, "a twin originates nothing into the primary's log");
1080        assert_eq!(chain.verify().expect("verify"), 1);
1081        let _ = log;
1082    }
1083
1084    /// **G (release-3 test2 mock 2026-09-29): a box that FOLLOWS originates nothing into the
1085    /// replicated trail, and says so without an error.** The twin opened its chain framed (it
1086    /// started as a primary) and was then told `Bootstrap.BecomeTwin` at runtime: its log turned
1087    /// follower, and every later decision (`Admin.GrowStatus` polls from monetize, 13 of them)
1088    /// was an `ERROR txlog: this box is a twin (or restoring); it originates no transactions`.
1089    ///
1090    /// A follower's decision is NOT written — not into the log (the primary's numbers), and not
1091    /// into the file (the primary's chain, which the twin holds) — and the answer is a
1092    /// [`Recorded::NotOriginated`], not an error. A box promoted again continues from the tip the
1093    /// file holds THEN, not from the one it remembered before it followed.
1094    #[test]
1095    fn a_framed_chain_on_a_box_that_follows_originates_nothing_and_is_no_error() {
1096        let (_dir, log, path) = framed_root();
1097        let chain = AuditChain::open_framed(&path).expect("framed");
1098        chain.append(a_decision("Repos.Create"), 1).expect("the primary's own decision");
1099        log.set_follower(true);
1100        match chain.record(a_decision("Admin.GrowStatus"), 2).expect("a follower's decision is not an error") {
1101            Recorded::NotOriginated => {}
1102            other => panic!("a follower originates nothing: {other:?}"),
1103        }
1104        assert!(matches!(chain.append(a_decision("Admin.GrowStatus"), 3), Err(AuditError::NotOriginated { .. })));
1105        assert_eq!(log.head_seq(), 1, "nothing framed into the primary's numbers");
1106        assert_eq!(chain.verify().expect("verify"), 1, "nothing written into the primary's chain");
1107
1108        // The primary's own frames reach the file while it follows (the twin applies them) …
1109        let other = AuditChain::open(&path).expect("the applier's view");
1110        let applied = other.append(a_decision("Access.Grant"), 4).expect("applied");
1111        // … and a promoted box continues from THAT tip.
1112        log.set_follower(false);
1113        let next = chain.append(a_decision("Repos.List"), 5).expect("originates again");
1114        assert_eq!((next.seq, next.prev.clone()), (applied.seq + 1, applied.hash.clone()));
1115        assert_eq!(chain.verify().expect("verify"), 3);
1116    }
1117
1118    /// **G2: while the data set is grown the trail WAITS, in order, and is written after the
1119    /// remount — never an error.** MEASURED main on the same mock: 4 `ERROR txlog: released — the
1120    /// files under /data/txlog are given up while the data set is grown` on `Admin.Capacity` /
1121    /// `Admin.GrowStatus` during its growth, and those decisions were never in the trail.
1122    #[test]
1123    fn a_released_log_queues_the_trail_and_the_first_append_after_the_remount_writes_it_in_order() {
1124        let (_dir, log, path) = framed_root();
1125        let chain = AuditChain::open_framed(&path).expect("framed");
1126        chain.append(a_decision("Repos.Create"), 1).expect("append");
1127        log.release().expect("the grow releases the log");
1128        for (i, m) in ["Admin.Capacity", "Admin.GrowStatus"].into_iter().enumerate() {
1129            match chain.record(a_decision(m), 2 + i as i64).expect("a decision during the grow is not an error") {
1130                Recorded::Queued { pending, .. } => assert_eq!(pending, i + 1),
1131                other => panic!("released: queued, not {other:?}"),
1132            }
1133        }
1134        assert_eq!(chain.queued(), 2);
1135        assert_eq!(log.head_seq(), 1, "nothing framed while the files are given up");
1136        assert_eq!(chain.verify().expect("verify"), 1, "nothing written under the unmounted set");
1137        log.reacquire().expect("the remount");
1138        match chain.record(a_decision("Admin.GrowStatus"), 9).expect("after the remount") {
1139            Recorded::Written(e) => assert_eq!(e.seq, 3),
1140            other => panic!("written after the remount: {other:?}"),
1141        }
1142        assert_eq!(chain.queued(), 0);
1143        assert_eq!(chain.verify().expect("the chain holds across the grow"), 4);
1144        assert_eq!(log.head_seq(), 4, "every decision framed, in order");
1145        let methods: Vec<String> = chain.entries().unwrap().into_iter().map(|e| e.method).collect();
1146        assert_eq!(methods, ["Repos.Create", "Admin.Capacity", "Admin.GrowStatus", "Admin.GrowStatus"]);
1147        // `flush` writes a queue without waiting for the next decision.
1148        log.release().unwrap();
1149        chain.record(a_decision("Admin.Capacity"), 10).unwrap();
1150        log.reacquire().unwrap();
1151        assert_eq!(chain.flush().expect("flush"), 1);
1152        assert_eq!((chain.queued(), chain.verify().unwrap(), log.head_seq()), (0, 5, 5));
1153    }
1154
1155    /// **G3 (d-upg3 2026-10-02, the KVM mock of the full release upgrade at ops fa23a53): an
1156    /// UNFRAMED chain whose set is unmounted for a growth WAITS too — never an error.** With
1157    /// `[machines.twin]` fed to vm1, monetize grows the TWIN; the twin's own trail
1158    /// ([`crate::txlog::AUDIT_LOCAL_REL`]) is not framed, so nothing told it the set was off, and
1159    /// monetize's own `Admin.GrowStatus` poll during the growth answered `ERROR … the audit chain
1160    /// at /data/log/audit-chain.local.jsonl: No such file or directory` — the log gate's FAIL.
1161    /// The directory the chain lives in is GONE while /data is unmounted: the line is held, in
1162    /// order, and written by the first decision after the remount (or `flush`).
1163    #[test]
1164    fn an_unframed_chain_whose_set_is_unmounted_queues_and_writes_after_the_remount() {
1165        let dir = tempfile::tempdir().unwrap();
1166        let data = dir.path().join("data");
1167        let local = data.join(crate::txlog::AUDIT_LOCAL_REL);
1168        let chain = AuditChain::open(&local).expect("the twin's own trail opens");
1169        chain.append(a_decision("Mirror.LogHead"), 1).expect("before the grow");
1170        // The growth unmounts /data: the directory the chain is in is not there.
1171        let off = dir.path().join("data-off");
1172        std::fs::rename(&data, &off).unwrap();
1173        match chain.record(a_decision("Admin.GrowStatus"), 2).expect("a decision while the set is off is not an error") {
1174            Recorded::Queued { pending, .. } => assert_eq!(pending, 1),
1175            other => panic!("the set is off: queued, not {other:?}"),
1176        }
1177        assert!(!data.exists(), "nothing is created where the set is not mounted");
1178        std::fs::rename(&off, &data).unwrap();
1179        match chain.record(a_decision("Admin.GrowStatus"), 3).expect("after the remount") {
1180            Recorded::Written(e) => assert_eq!(e.seq, 2),
1181            other => panic!("written after the remount: {other:?}"),
1182        }
1183        assert_eq!((chain.queued(), chain.verify().expect("the chain holds across the grow")), (0, 3));
1184    }
1185
1186
1187    /// **Decisions group-committed from many threads, with a snapshot's freeze cutting in,
1188    /// never deadlock and never fork the chain** (perf, 2026-10-06). Eight threads record while
1189    /// another freezes the log over and over: every decision lands once, the chain verifies, the
1190    /// file holds exactly the lines the log's frames carry, in the same order — and the whole run
1191    /// ends (a thread that held the chain's lock while it waited on the freeze would stop the
1192    /// thread the freeze waits for; the guard is taken before the lock).
1193    #[test]
1194    fn concurrent_framed_decisions_with_freezes_land_once_in_order_and_never_deadlock() {
1195        let (_dir, log, path) = framed_root();
1196        let chain = std::sync::Arc::new(AuditChain::open_framed(&path).expect("framed"));
1197        let (tx, rx) = std::sync::mpsc::channel();
1198        {
1199            let (chain, log) = (std::sync::Arc::clone(&chain), std::sync::Arc::clone(&log));
1200            std::thread::spawn(move || {
1201                let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1202                let freezer = {
1203                    let (log, stop) = (std::sync::Arc::clone(&log), std::sync::Arc::clone(&stop));
1204                    std::thread::spawn(move || {
1205                        let mut n = 0u64;
1206                        while !stop.load(std::sync::atomic::Ordering::SeqCst) {
1207                            let g = log.freeze();
1208                            std::thread::sleep(std::time::Duration::from_micros(200));
1209                            drop(g);
1210                            n += 1;
1211                        }
1212                        n
1213                    })
1214                };
1215                std::thread::scope(|s| {
1216                    for t in 0..8 {
1217                        let chain = std::sync::Arc::clone(&chain);
1218                        s.spawn(move || {
1219                            for i in 0..40 {
1220                                chain.append(a_decision(if (t + i) % 2 == 0 { "Repos.Create" } else { "Access.Grant" }), i).expect("a decision lands");
1221                            }
1222                        });
1223                    }
1224                });
1225                stop.store(true, std::sync::atomic::Ordering::SeqCst);
1226                let _ = tx.send(freezer.join().unwrap());
1227            });
1228        }
1229        let freezes = rx.recv_timeout(std::time::Duration::from_secs(120)).expect("320 decisions under freezes end — no deadlock");
1230        assert!(freezes > 0, "the freezer cut in");
1231        assert_eq!(chain.verify().expect("the chain holds"), 320);
1232        let file: Vec<String> = std::fs::read_to_string(&path).unwrap().lines().map(str::to_owned).collect();
1233        let framed: Vec<String> = (1..=log.head_seq()).map(|s| String::from_utf8(log.read(s).unwrap().blob).unwrap()).collect();
1234        assert_eq!(file, framed, "the file is exactly the log's frames, in the log's order");
1235    }
1236
1237}