From 163af33b8e48f771b9efa1f034bb6632112f6e9b Mon Sep 17 00:00:00 2001 From: saket0187 Date: Fri, 4 Dec 2026 17:17:36 +0530 Subject: [PATCH 1/3] fix(admin): keep the admin audit log bounded across restarts and retry a failed compaction (cherry picked from commit d94a9077c2617c7b5627116c0242aca070fff17c) --- .changeset/admin-audit-compaction-bound.md | 6 + crates/nostream-admin/src/state.rs | 293 +++++++++++++----- crates/nostream-admin/tests/audit.rs | 233 ++++++++++++-- .../decisions/0014-admin-http-surface.md | 38 ++- 4 files changed, 456 insertions(+), 114 deletions(-) create mode 100644 .changeset/admin-audit-compaction-bound.md diff --git a/.changeset/admin-audit-compaction-bound.md b/.changeset/admin-audit-compaction-bound.md new file mode 100644 index 000000000..3bdbdd404 --- /dev/null +++ b/.changeset/admin-audit-compaction-bound.md @@ -0,0 +1,6 @@ +--- +--- + +fix(admin): keep the admin audit log bounded across restarts and retry a failed compaction + +`/admin-audit.jsonl` was compacted once every 2,000 appends by an in-process counter, so restarting the relay more often than that, or a compaction that kept failing (the counter was reset before the attempt), let the file grow without bound, and every compaction staged through one shared file name. An append now counts the file itself (once per process, and again when the file is not the length this process left it) and compacts at 4,000 entries to the newest 2,000; a failed compaction is logged and retried by the next append, which still reports its entry as written; each compaction stages through an exclusive per-process `.admin-audit...tmp`; and an append whose count finds the last line cut short by an interrupted write starts a new line, so that fragment no longer swallows the entry. Deliberate limits: while a compaction keeps failing the file keeps growing; a rewrite that leaves the file at exactly the length this process left is not noticed until the next compaction; and an entry another process appends during a compaction can still be lost, so one config directory keeps one writer. diff --git a/crates/nostream-admin/src/state.rs b/crates/nostream-admin/src/state.rs index c35668c54..f84044e20 100644 --- a/crates/nostream-admin/src/state.rs +++ b/crates/nostream-admin/src/state.rs @@ -8,6 +8,7 @@ use std::collections::{HashMap, VecDeque}; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -36,11 +37,14 @@ pub const HEARTBEAT_INTERVAL: Duration = Duration::from_millis(45_000); /// The stored admin audit entries (`MAX_ADMIN_AUDIT_ENTRIES`). pub const MAX_AUDIT_ENTRIES: usize = 2_000; -/// How many appends run between compactions, so the file holds at most -/// `MAX_AUDIT_ENTRIES + AUDIT_COMPACT_EVERY` lines. One append is one `write`; the read and -/// rewrite that keep the cap happen once per this many appends, not once per request. +/// How many entries the file gains between compactions: the append that brings it to 4,000 +/// compacts it to the newest `MAX_AUDIT_ENTRIES`, so with one writer, while compactions succeed, +/// the file never holds more than 4,000 entries. pub const AUDIT_COMPACT_EVERY: usize = 2_000; +/// How many staging file names one compaction tries before it fails. +pub const AUDIT_STAGING_ATTEMPTS: u64 = 5; + /// How many logins may hold a scrypt verification at once. The work runs on the blocking /// pool, so a burst queues here rather than taking every runtime worker. pub const MAX_CONCURRENT_LOGIN_VERIFICATIONS: usize = 4; @@ -115,8 +119,8 @@ pub struct AdminRuntime { /// The last purge this process ran, beside the heartbeats and the probe ring (D3). maintenance: Mutex>, probe: Mutex, - /// Appends since the last compaction. - audit: Mutex, + /// `None` until an append counts the file. + audit: Mutex>, /// The login verification permits (D15). login_verifications: Arc, /// The shared limiter (`nostream_relay::limits`), chosen by @@ -135,7 +139,7 @@ impl Default for AdminRuntime { heartbeats: Mutex::new(HashMap::new()), maintenance: Mutex::new(None), probe: Mutex::new(ProbeState::default()), - audit: Mutex::new(0), + audit: Mutex::new(None), login_verifications: Arc::new(tokio::sync::Semaphore::new( MAX_CONCURRENT_LOGIN_VERIFICATIONS, )), @@ -145,6 +149,13 @@ impl Default for AdminRuntime { } } +/// The audit file's entries and length as this process last left it. +#[derive(Debug, Clone, Copy)] +struct AuditFile { + entries: usize, + len: u64, +} + /// The shared limiter and the strategy it was built for, so a settings change swaps it. #[derive(Debug, Default)] struct LimiterSlot { @@ -574,8 +585,8 @@ impl AdminState { } } - /// Appends one admin audit entry: one `write` to the file, and a compaction once every - /// [`AUDIT_COMPACT_EVERY`] appends to keep [`MAX_AUDIT_ENTRIES`] (D9). + /// Appends one admin audit entry: one `write`, and a compaction at 4,000 entries (D9, D16). + /// An `Err` means the entry was not written; a failed compaction is logged and retried. /// /// The read-parse-rewrite the first cut did on every call was O(file) per request, and an /// unauthenticated `POST /logout` reaches it. @@ -585,7 +596,7 @@ impl AdminState { remote_address: Option<&str>, detail: Option, ) -> Result { - let mut appends = self + let mut known = self .runtime .audit .lock() @@ -621,23 +632,39 @@ impl AdminState { path: path.clone(), source, })?; + let metadata = file.metadata().map_err(|source| AdminError::Io { + path: path.clone(), + source, + })?; #[cfg(unix)] - owner_only(&file).map_err(|source| AdminError::Io { + owner_only(&file, &metadata).map_err(|source| AdminError::Io { path: path.clone(), source, })?; - let line = format!("{entry}\n"); + // Only a regular file is counted and compacted: reading a pipe would block on its writers. + let found = metadata + .is_file() + .then(|| count_audit(&path, *known, metadata.len())) + .flatten(); + let mut line = format!("{entry}\n"); + if found.is_some_and(|(_, cut_short)| cut_short) { + line.insert(0, '\n'); + } std::io::Write::write_all(&mut file, line.as_bytes()).map_err(|source| AdminError::Io { path: path.clone(), source, })?; drop(file); - *appends += 1; - if *appends >= AUDIT_COMPACT_EVERY { - *appends = 0; - compact_audit(&path)?; - } + *known = found.map(|(before, _)| { + settle_audit( + &path, + AuditFile { + entries: before.entries + 1, + len: before.len + line.len() as u64, + }, + ) + }); Ok(entry) } @@ -771,69 +798,178 @@ impl ProbeState { } fn read_audit_lines(path: &Path) -> Result, AdminError> { - let raw = match std::fs::read_to_string(path) { + read_audit_file(path).map(|raw| parse_audit_lines(&raw)) +} + +fn read_audit_file(path: &Path) -> Result, AdminError> { + match std::fs::read(path) { + Ok(raw) => Ok(raw), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()), + Err(source) => Err(AdminError::Io { + path: path.to_path_buf(), + source, + }), + } +} + +/// Byte lines, so a line cut mid-character is skipped rather than failing the whole read. +fn audit_lines(raw: &[u8]) -> impl DoubleEndedIterator { + raw.split(|byte| *byte == b'\n') + .filter(|line| !line.trim_ascii().is_empty()) +} + +fn parse_audit_lines(raw: &[u8]) -> Vec { + audit_lines(raw) + .filter_map(|line| serde_json::from_slice::(line).ok()) + .collect() +} + +/// This process's count while the file is the length it left, else a fresh count; the flag says +/// the file ends partway through a line. +fn count_audit(path: &Path, known: Option, len: u64) -> Option<(AuditFile, bool)> { + if let Some(file) = known.filter(|file| file.len == len) { + return Some((file, false)); + } + match read_audit_file(path) { + Ok(raw) => { + let entries = audit_lines(&raw) + .filter(|line| serde_json::from_slice::(line).is_ok()) + .count(); + let len = raw.len() as u64; + Some(( + AuditFile { entries, len }, + raw.last().is_some_and(|byte| *byte != b'\n'), + )) + } + Err(error) => { + tracing::warn!( + %error, + "the admin audit log was not counted; the next append counts it" + ); + None + } + } +} + +/// The entry is already written, so a failed compaction is logged, not returned, and the count it +/// leaves makes the next append retry. +fn settle_audit(path: &Path, appended: AuditFile) -> AuditFile { + if appended.entries < MAX_AUDIT_ENTRIES + AUDIT_COMPACT_EVERY { + return appended; + } + match compact_audit(path) { + Ok(compacted) => compacted, + Err(error) => { + tracing::warn!( + %error, + "the admin audit log was not compacted; the next append retries" + ); + appended + } + } +} + +/// The staging file is opened before the log is read, so a directory that refuses it costs no read. +fn compact_audit(path: &Path) -> Result { + let (staging, file) = open_staging(path)?; + let raw = match read_audit_file(path) { Ok(raw) => raw, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), - Err(source) => { - return Err(AdminError::Io { - path: path.to_path_buf(), - source, - }); + Err(error) => { + discard(&staging); + return Err(error); } }; - Ok(raw - .lines() - .filter(|line| !line.trim().is_empty()) - .filter_map(|line| serde_json::from_str::(line).ok()) - .collect()) -} - -/// Trims the file to its newest `MAX_AUDIT_ENTRIES` lines: read once, write a fresh file, -/// rename it into place. -fn compact_audit(path: &Path) -> Result<(), AdminError> { - let mut lines = read_audit_lines(path)?; - if lines.len() <= MAX_AUDIT_ENTRIES { - return Ok(()); - } - let excess = lines.len() - MAX_AUDIT_ENTRIES; - lines.drain(..excess); - let staging = path.with_extension("jsonl.compact"); - write_audit_lines(&staging, &lines)?; - std::fs::rename(&staging, path).map_err(|source| AdminError::Io { - path: path.to_path_buf(), - source, + // One past the cap says whether anything is cut. + let mut newest: Vec = audit_lines(&raw) + .rev() + .filter_map(|line| serde_json::from_slice::(line).ok()) + .take(MAX_AUDIT_ENTRIES + 1) + .collect(); + if newest.len() <= MAX_AUDIT_ENTRIES { + discard(&staging); + return Ok(AuditFile { + entries: newest.len(), + len: raw.len() as u64, + }); + } + newest.truncate(MAX_AUDIT_ENTRIES); + let body: String = newest + .iter() + .rev() + .map(|line| format!("{line}\n")) + .collect(); + if let Err(source) = write_staging(file, &body) { + discard(&staging); + return Err(AdminError::Io { + path: staging, + source, + }); + } + if let Err(source) = std::fs::rename(&staging, path) { + discard(&staging); + return Err(AdminError::Io { + path: path.to_path_buf(), + source, + }); + } + // The name earlier builds shared; a copy left there would stay readable at its old mode. + discard(&path.with_extension("jsonl.compact")); + Ok(AuditFile { + entries: newest.len(), + len: body.len() as u64, }) } -fn write_audit_lines(path: &Path, lines: &[Value]) -> Result<(), AdminError> { - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent).map_err(|source| AdminError::Io { - path: parent.to_path_buf(), - source, - })?; +/// A name already on disk may be another process's staging file, so it is skipped, never removed. +fn open_staging(path: &Path) -> Result<(PathBuf, std::fs::File), AdminError> { + let mut taken: Vec = Vec::new(); + for _ in 0..AUDIT_STAGING_ATTEMPTS { + let name = staging_name(); + let staging = path.with_file_name(&name); + match open_private( + std::fs::OpenOptions::new().write(true).create_new(true), + &staging, + ) { + Ok(file) => return Ok((staging, file)), + Err(source) if source.kind() == std::io::ErrorKind::AlreadyExists => taken.push(name), + Err(source) => { + return Err(AdminError::Io { + path: staging, + source, + }); + } + } } - let body: String = lines - .iter() - .map(|line| format!("{line}\n")) - .collect::>() - .concat(); - let io = |source| AdminError::Io { + Err(AdminError::Io { path: path.to_path_buf(), - source, - }; - // A leftover staging file would keep its mode, and any reader's descriptor, through a truncate. - match std::fs::remove_file(path) { - Err(source) if source.kind() != std::io::ErrorKind::NotFound => return Err(io(source)), - _ => {} - } - let mut file = open_private( - std::fs::OpenOptions::new().write(true).create_new(true), - path, - ) - .map_err(io)?; + source: std::io::Error::new( + std::io::ErrorKind::AlreadyExists, + format!( + "no free staging file name after {AUDIT_STAGING_ATTEMPTS} tries: {}", + taken.join(", ") + ), + ), + }) +} + +fn write_staging(mut file: std::fs::File, body: &str) -> std::io::Result<()> { #[cfg(unix)] - owner_only(&file).map_err(io)?; - std::io::Write::write_all(&mut file, body.as_bytes()).map_err(io) + owner_only(&file, &file.metadata()?)?; + std::io::Write::write_all(&mut file, body.as_bytes()) +} + +fn discard(path: &Path) { + let _ = std::fs::remove_file(path); +} + +/// `.admin-audit...tmp`, as `nostream_config::store` names the settings file's. +fn staging_name() -> String { + static STAGED: AtomicU64 = AtomicU64::new(0); + format!( + ".admin-audit.{}.{}.tmp", + std::process::id(), + STAGED.fetch_add(1, Ordering::Relaxed) + ) } /// Opens with `options`, asking for mode `0600` (less the umask) for a file the open creates, so it @@ -850,9 +986,8 @@ fn open_private(options: &mut std::fs::OpenOptions, path: &Path) -> std::io::Res /// Sets a regular audit file's permission bits to `0600` before anything is written to it, whatever /// the umask or an earlier build left; another target (a `/dev/null` link) is left alone. #[cfg(unix)] -fn owner_only(file: &std::fs::File) -> std::io::Result<()> { +fn owner_only(file: &std::fs::File, metadata: &std::fs::Metadata) -> std::io::Result<()> { use std::os::unix::fs::PermissionsExt; - let metadata = file.metadata()?; if metadata.is_file() && metadata.permissions().mode() & 0o777 != 0o600 { file.set_permissions(std::fs::Permissions::from_mode(0o600))?; } @@ -950,9 +1085,9 @@ mod tests { #[cfg(unix)] #[test] - fn a_compacted_log_is_0600_under_an_owner_stripping_umask() { + fn a_staging_file_is_0600_under_an_owner_stripping_umask() { if !is_child_under_umask( - "state::tests::a_compacted_log_is_0600_under_an_owner_stripping_umask", + "state::tests::a_staging_file_is_0600_under_an_owner_stripping_umask", "0400", ) { return; @@ -960,17 +1095,17 @@ mod tests { use std::os::unix::fs::PermissionsExt; let temp = tempfile::tempdir().unwrap(); std::fs::set_permissions(temp.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); - let path = temp.path().join("admin-audit.jsonl"); - write_audit_lines(&path, &[serde_json::json!({ "action": "admin.test" })]).unwrap(); + let (staging, file) = open_staging(&temp.path().join("admin-audit.jsonl")).unwrap(); + write_staging(file, "{\"action\":\"admin.test\"}\n").unwrap(); assert_eq!( - mode(&std::fs::metadata(&path).unwrap()), + mode(&std::fs::metadata(&staging).unwrap()), "600", - "the owner can read the log it wrote" + "the owner can read the staging file the rename makes the log" ); assert!( - std::fs::read_to_string(&path) + std::fs::read_to_string(&staging) .unwrap() .contains("admin.test") ); diff --git a/crates/nostream-admin/tests/audit.rs b/crates/nostream-admin/tests/audit.rs index 55e1a8670..64ea6df64 100644 --- a/crates/nostream-admin/tests/audit.rs +++ b/crates/nostream-admin/tests/audit.rs @@ -1,5 +1,6 @@ //! AC24's file, rewritten for cost: one append is one `write`, and the 2,000-entry cap is kept -//! by a compaction that runs once per `AUDIT_COMPACT_EVERY` appends (`state.rs`, D9). +//! by a compaction that runs when the file reaches `MAX_AUDIT_ENTRIES + AUDIT_COMPACT_EVERY` +//! entries (`state.rs`, D9, D16). //! //! | case | what it proves | //! |---|---| @@ -9,7 +10,13 @@ //! | `an_append_narrows_an_audit_file_left_at_another_mode` | a `0644` or `0200` file an earlier build left is exactly `0600` after the next append, which still lands | //! | `an_append_leaves_a_target_that_is_not_a_file_alone` | a target that is not a regular file (a drained pipe here) keeps its mode and still gets the entry | //! | `the_compaction_keeps_the_file_owner_only` | with a `022` umask a `0600` file is still `0600` after a compaction renames over it | -//! | `the_compaction_replaces_a_stale_staging_file` | a `0644` staging file an interrupted compaction left is replaced, not reused: a reader holding it sees none of the log, which is `0600` | +//! | `a_compaction_steps_over_a_taken_staging_name` | a `0644` file at the staging name the compaction reaches for first is another's: it is left as it was, and the log is compacted through the next name, `0600` | +//! | `a_restarted_writer_compacts_the_file_it_finds` | a process's first append counts the file an earlier process left, so a file at the bound is compacted | +//! | `an_append_counts_what_another_writer_added` | lines another writer appended are counted, so they cannot carry the file past the bound | +//! | `a_torn_line_is_skipped_by_the_count` | a line cut mid-character, or holding a byte that is not UTF-8, is not an entry: the count skips it rather than failing or counting it, and the compaction drops it | +//! | `an_entry_after_a_line_cut_short_is_a_line_of_its_own` | a file whose last line has no `\n` (a whole value, or a fragment) gets one before the entry, so the entry is read back | +//! | `a_compaction_removes_the_staging_file_earlier_builds_shared` | the `admin-audit.jsonl.compact` an interrupted compaction of an earlier build left is removed | +//! | `a_failed_compaction_is_retried_by_the_next_append` | the entry is written although the compaction fails, the next append compacts, and the taken staging files are left alone | #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] @@ -18,6 +25,7 @@ mod common; use std::os::unix::fs::PermissionsExt; use common::TestServer; +use nostream_admin::state::{AUDIT_COMPACT_EVERY, AUDIT_STAGING_ATTEMPTS, MAX_AUDIT_ENTRIES}; const UMASK_CHILD: &str = "NOSTREAM_ADMIN_AUDIT_MODE_CHILD"; @@ -39,19 +47,34 @@ fn mode(path: &std::path::Path) -> String { format!("{:o}", mode & 0o777) } -fn seed_at_cap(path: &std::path::Path) { - let seeded: String = (0..nostream_admin::state::MAX_AUDIT_ENTRIES) +fn seed_lines(count: usize) -> String { + (0..count) .map(|index| { format!( "{{\"id\":\"seed-{index}\",\"at\":\"2026-11-19T00:00:00Z\",\"action\":\"seed\"}}\n" ) }) - .collect(); - std::fs::write(path, seeded).unwrap(); + .collect() +} + +fn raw_line_count(path: &std::path::Path) -> usize { + std::fs::read(path) + .unwrap() + .split(|byte| *byte == b'\n') + .filter(|line| !line.is_empty()) + .count() +} + +fn seed_at_cap(path: &std::path::Path) { + std::fs::write(path, seed_lines(MAX_AUDIT_ENTRIES)).unwrap(); +} + +fn staging_name(n: u64) -> String { + format!(".admin-audit.{}.{n}.tmp", std::process::id()) } fn append_through_a_compaction(server: &TestServer) { - for index in 0..nostream_admin::state::AUDIT_COMPACT_EVERY { + for index in 0..AUDIT_COMPACT_EVERY { server .state .append_audit( @@ -113,13 +136,13 @@ async fn the_cap_survives_two_thousand_appends() { // A file already at the cap, as a long-running daemon leaves it. seed_at_cap(&path); - assert_eq!(line_count(&path), nostream_admin::state::MAX_AUDIT_ENTRIES); + assert_eq!(line_count(&path), MAX_AUDIT_ENTRIES); append_through_a_compaction(&server); assert_eq!( line_count(&path), - nostream_admin::state::MAX_AUDIT_ENTRIES, + MAX_AUDIT_ENTRIES, "the compaction kept the cap" ); let last = std::fs::read_to_string(&path) @@ -130,6 +153,11 @@ async fn the_cap_survives_two_thousand_appends() { .to_owned(); let last: serde_json::Value = serde_json::from_str(&last).unwrap(); assert_eq!(last["action"], "admin.test", "the newest entry is kept"); + assert_eq!( + last["detail"]["index"], + serde_json::json!(AUDIT_COMPACT_EVERY - 1), + "and is still the last line" + ); } #[tokio::test] @@ -205,41 +233,194 @@ async fn the_compaction_keeps_the_file_owner_only() { append_through_a_compaction(&server); - assert_eq!( - line_count(&path), - nostream_admin::state::MAX_AUDIT_ENTRIES, - "the compaction ran" - ); + assert_eq!(line_count(&path), MAX_AUDIT_ENTRIES, "the compaction ran"); assert_eq!(mode(&path), "600", "the compacted log is still private"); } #[tokio::test] -async fn the_compaction_replaces_a_stale_staging_file() { +async fn a_compaction_steps_over_a_taken_staging_name() { + // Alone in a child, so this compaction is the process's first and tries `.0` first. + if !is_umask_child("a_compaction_steps_over_a_taken_staging_name") { + return; + } let server = TestServer::start().await; let path = audit_path(&server); - let staging = server.config_dir.join("admin-audit.jsonl.compact"); + let taken = server.config_dir.join(staging_name(0)); seed_at_cap(&path); - std::fs::write(&staging, "stale\n").unwrap(); - std::fs::set_permissions(&staging, std::fs::Permissions::from_mode(0o644)).unwrap(); - let mut held = std::fs::File::open(&staging).unwrap(); + std::fs::write(&taken, "taken\n").unwrap(); + std::fs::set_permissions(&taken, std::fs::Permissions::from_mode(0o644)).unwrap(); append_through_a_compaction(&server); assert_eq!( line_count(&path), - nostream_admin::state::MAX_AUDIT_ENTRIES, - "the compaction ran" + MAX_AUDIT_ENTRIES, + "the compaction ran through the next name" ); - let mut seen = String::new(); - std::io::Read::read_to_string(&mut held, &mut seen).unwrap(); assert_eq!( - seen, "stale\n", - "a reader of the old staging file sees none of the log" + std::fs::read_to_string(&taken).unwrap(), + "taken\n", + "the file at the taken name is neither rewritten nor removed" ); assert_eq!( mode(&path), "600", - "the log does not take the stale file's mode" + "the log does not take the taken file's mode" + ); +} + +#[tokio::test] +async fn a_restarted_writer_compacts_the_file_it_finds() { + let server = TestServer::start().await; + let path = audit_path(&server); + std::fs::write( + &path, + seed_lines(MAX_AUDIT_ENTRIES + AUDIT_COMPACT_EVERY - 1), + ) + .unwrap(); + + server.state.append_audit("admin.test", None, None).unwrap(); + + assert_eq!( + line_count(&path), + MAX_AUDIT_ENTRIES, + "the first append of this process compacted the file an earlier one left at the bound" + ); +} + +#[tokio::test] +async fn an_append_counts_what_another_writer_added() { + let server = TestServer::start().await; + let path = audit_path(&server); + server.state.append_audit("admin.test", None, None).unwrap(); + + let mut other = std::fs::OpenOptions::new() + .append(true) + .open(&path) + .unwrap(); + std::io::Write::write_all( + &mut other, + seed_lines(MAX_AUDIT_ENTRIES + AUDIT_COMPACT_EVERY - 2).as_bytes(), + ) + .unwrap(); + + server.state.append_audit("admin.test", None, None).unwrap(); + + assert_eq!( + line_count(&path), + MAX_AUDIT_ENTRIES, + "the append counted the other writer's lines and compacted at the bound" + ); +} + +#[tokio::test] +async fn a_torn_line_is_skipped_by_the_count() { + let server = TestServer::start().await; + let path = audit_path(&server); + // A string cut mid-character, and a closed one holding a byte that is not UTF-8. + let mut seeded = b"{\"id\":\"torn\",\"action\":\"s\xc3\n".to_vec(); + seeded.extend(b"{\"id\":\"bad\",\"action\":\"s\xc3\"}\n"); + seeded.extend(seed_lines(MAX_AUDIT_ENTRIES + AUDIT_COMPACT_EVERY - 2).into_bytes()); + std::fs::write(&path, seeded).unwrap(); + + server.state.append_audit("admin.test", None, None).unwrap(); + assert_eq!( + raw_line_count(&path), + MAX_AUDIT_ENTRIES + AUDIT_COMPACT_EVERY + 1, + "one entry short of the bound: neither line that is not JSON was counted" ); + + server.state.append_audit("admin.test", None, None).unwrap(); + assert_eq!( + raw_line_count(&path), + MAX_AUDIT_ENTRIES, + "the bound was reached and the compaction dropped the torn line" + ); +} + +#[tokio::test] +async fn an_entry_after_a_line_cut_short_is_a_line_of_its_own() { + for tail in [ + "{\"id\":\"whole\",\"at\":\"2026-11-19T00:00:00Z\",\"action\":\"seed\"}", + "{\"id\":\"cut\",\"at\":\"2026-11-", + ] { + let server = TestServer::start().await; + let path = audit_path(&server); + std::fs::write(&path, format!("{}{tail}", seed_lines(1))).unwrap(); + + server.state.append_audit("admin.test", None, None).unwrap(); + + let newest = server.state.audit_entries(1).unwrap(); + assert_eq!( + newest[0]["action"], "admin.test", + "the entry after {tail:?} is read back" + ); + assert!( + std::fs::read_to_string(&path) + .unwrap() + .contains(&format!("{tail}\n")), + "the cut line keeps its own bytes" + ); + } +} + +#[tokio::test] +async fn a_compaction_removes_the_staging_file_earlier_builds_shared() { + let server = TestServer::start().await; + let path = audit_path(&server); + let legacy = server.config_dir.join("admin-audit.jsonl.compact"); + seed_at_cap(&path); + std::fs::write(&legacy, seed_lines(1)).unwrap(); + std::fs::set_permissions(&legacy, std::fs::Permissions::from_mode(0o644)).unwrap(); + + append_through_a_compaction(&server); + + assert_eq!(line_count(&path), MAX_AUDIT_ENTRIES, "the compaction ran"); + assert!(!legacy.exists(), "the earlier builds' staging copy is gone"); +} + +#[tokio::test] +async fn a_failed_compaction_is_retried_by_the_next_append() { + // Alone in a child, so the first compaction tries `.0` onwards. + if !is_umask_child("a_failed_compaction_is_retried_by_the_next_append") { + return; + } + let server = TestServer::start().await; + let path = audit_path(&server); + std::fs::write( + &path, + seed_lines(MAX_AUDIT_ENTRIES + AUDIT_COMPACT_EVERY - 1), + ) + .unwrap(); + let taken: Vec = (0..AUDIT_STAGING_ATTEMPTS) + .map(|n| server.config_dir.join(staging_name(n))) + .collect(); + for name in &taken { + std::fs::write(name, "taken\n").unwrap(); + } + + server + .state + .append_audit("admin.test", None, None) + .expect("the entry is written although the compaction fails"); + assert_eq!( + line_count(&path), + MAX_AUDIT_ENTRIES + AUDIT_COMPACT_EVERY, + "the failed compaction left the file whole" + ); + + server.state.append_audit("admin.test", None, None).unwrap(); + assert_eq!( + line_count(&path), + MAX_AUDIT_ENTRIES, + "the next append retried the compaction" + ); + for name in &taken { + assert_eq!( + std::fs::read_to_string(name).unwrap(), + "taken\n", + "another compaction's file is left alone" + ); + } } diff --git a/docs/rewrite/decisions/0014-admin-http-surface.md b/docs/rewrite/decisions/0014-admin-http-surface.md index f1ccd7513..7396b9fec 100644 --- a/docs/rewrite/decisions/0014-admin-http-surface.md +++ b/docs/rewrite/decisions/0014-admin-http-surface.md @@ -266,18 +266,37 @@ answers while a login verification is still in flight. ### D16 — The admin audit log appends, and compacts over the cap -`append_audit` is `OpenOptions::append` and one `write` per request; the 2,000-entry cap is kept -by a compaction that runs once per `AUDIT_COMPACT_EVERY` (2,000) appends, reading once and -renaming a fresh file into place. +`append_audit` is `OpenOptions::append` and one `write` per request; the 2,000-entry cap is kept by +a compaction that runs when an append brings the file to `MAX_AUDIT_ENTRIES + AUDIT_COMPACT_EVERY` +(4,000) entries, reading once and renaming a fresh file of the newest 2,000 into place, so while +compactions succeed the file holds at most 4,000 entries. The count is the file's, not the +process's: a process's first append reads the file to count it, and a later append trusts that count +only while the file is still the length this process left it, so the file an earlier process left +and the lines another writer appended are counted, not missed. A rewrite to exactly that length is +not noticed until the next compaction reads the file. A compaction that fails is logged and the next +append retries it, and the entry already written is still reported as written; while it keeps +failing the file keeps growing. The append counts and compacts only a regular file, so it never +reads a pipe at the path; the count and the compaction reopen the path, so they assume nothing +replaces the file while an append runs. A line that is not JSON, one cut mid-character included, is +skipped by the count and dropped by the compaction, and an append whose count reads a file ending +partway through a line writes a newline first, so the entry stays a line of its own. The file's permission bits are owner read and write only (`0600`), whatever the umask. The append opens it with that creation mode and, before writing, sets a regular file found with any other permission bits to `0600` through the descriptor it opened, so each append also costs one `fstat`. A file it cannot narrow (another account owns it) gets no entry, and the caller warns as for any other audit write error. Only a regular file is narrowed, so a link to `/dev/null` keeps its mode. The -compaction removes any staging file an interrupted compaction left and opens and narrows its own the -same way before writing, because the rename gives the log the staging file's mode, and a truncated -leftover would keep both its own mode and any reader that had it open. +compaction writes a staging file of its own, `.admin-audit...tmp` (the pid and a per-process +counter, as `nostream_config::store` names the settings file's), created exclusively and narrowed +the same way before writing, because the rename gives the log the staging file's mode. It opens that +file before it reads the log, so a retry in a directory that refuses the staging file skips the +compaction's read; a count after a restart or a change of length still reads the file once. The +compaction parses the file from its end and stops one entry past the cap, so it holds no more than +that many parsed entries in memory however long the file has grown. A name already on disk is +another compaction's, so it is stepped over, never truncated, rewritten or removed, and +`AUDIT_STAGING_ATTEMPTS` (5) taken names fail the compaction; any other error fails it at once. A +staging file an interrupted compaction left is not removed, except `admin-audit.jsonl.compact`, the +one name earlier builds shared, which a successful compaction removes. The first cut read, parsed and rewrote the whole file under a mutex on every call — and an unauthenticated `POST /logout` reaches it, so any caller could drive a full-file read and rewrite. @@ -354,9 +373,10 @@ composed independently of the relay path's at `crates/nostreamd/src/main.rs:187` same-`Arc` rule covers for the console and not for this mode. Wiring the store means wiring the two sites in one change; until then neither process opens an LMDB directory, so ADR 0012 D9's second-writer hazard cannot arise. The two modes are alternatives, and running both against one -directory is outside ADR 0012 D9 — `admin-audit.jsonl` (whose compaction is a read, a write and a -rename on a shared staging path, `crates/nostream-admin/src/state.rs:715-733`) and the settings -write both assume one writer per configuration. +directory is outside ADR 0012 D9 — `admin-audit.jsonl` (whose compaction reads the file and +renames a rewritten copy over it, so an entry another process appends in between is lost: +`compact_audit` in `crates/nostream-admin/src/state.rs`) and the settings write both assume one +writer per configuration. **The one artifact the two modes do share, and why it is not the hazard.** The MCP mode's `relay_status` reads `/relay-status.json`, which the daemon rewrites every 5 s From 3b1dffdf7a8ed1fefb291a7c5fddcc73bb4d6867 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 4 Dec 2026 09:43:16 -0500 Subject: [PATCH 2/3] fix(admin): give an audit entry its own line when the count fails The separator was keyed on the count alone, so a regular file whose tail could not be read (an append descriptor that consumed the last one) took the new entry onto the open line and both were lost. The tail is now treated as unknown for a regular file and separated: a blank line where it was already complete is dropped by the reader. --- crates/nostream-admin/src/state.rs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/nostream-admin/src/state.rs b/crates/nostream-admin/src/state.rs index f84044e20..fab874c19 100644 --- a/crates/nostream-admin/src/state.rs +++ b/crates/nostream-admin/src/state.rs @@ -647,7 +647,7 @@ impl AdminState { .then(|| count_audit(&path, *known, metadata.len())) .flatten(); let mut line = format!("{entry}\n"); - if found.is_some_and(|(_, cut_short)| cut_short) { + if needs_leading_newline(found, metadata.is_file()) { line.insert(0, '\n'); } std::io::Write::write_all(&mut file, line.as_bytes()).map_err(|source| AdminError::Io { @@ -801,6 +801,16 @@ fn read_audit_lines(path: &Path) -> Result, AdminError> { read_audit_file(path).map(|raw| parse_audit_lines(&raw)) } +/// Whether the entry needs a `\n` of its own before it: the file ends partway through a line, or +/// its count failed for a regular file, so the tail is unknown and must not be joined. Where the +/// tail was already complete, the blank line is dropped by the reader. +fn needs_leading_newline(found: Option<(AuditFile, bool)>, is_file: bool) -> bool { + match found { + Some((_, cut_short)) => cut_short, + None => is_file, + } +} + fn read_audit_file(path: &Path) -> Result, AdminError> { match std::fs::read(path) { Ok(raw) => Ok(raw), @@ -1028,6 +1038,19 @@ mod tests { use super::*; + #[test] + fn a_failed_count_still_separates_a_regular_file() { + let complete = (AuditFile { entries: 1, len: 8 }, false); + let cut = (AuditFile { entries: 1, len: 7 }, true); + assert!(!needs_leading_newline(Some(complete), true)); + assert!(needs_leading_newline(Some(cut), true)); + assert!( + needs_leading_newline(None, true), + "an uncounted regular file may end mid-line, so the entry gets its own" + ); + assert!(!needs_leading_newline(None, false), "a pipe keeps its framing"); + } + // `umask` is process-wide, so the case re-runs in a child under it; only the child asserts. #[cfg(unix)] fn is_child_under_umask(case: &str, umask: &str) -> bool { From bd31be6800a6445a18a4ab32e749158c146a1cc4 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Fri, 4 Dec 2026 09:51:30 -0500 Subject: [PATCH 3/3] style(admin): let rustfmt lay out the new assertion --- crates/nostream-admin/src/state.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/nostream-admin/src/state.rs b/crates/nostream-admin/src/state.rs index fab874c19..3f8e344d7 100644 --- a/crates/nostream-admin/src/state.rs +++ b/crates/nostream-admin/src/state.rs @@ -1048,7 +1048,10 @@ mod tests { needs_leading_newline(None, true), "an uncounted regular file may end mid-line, so the entry gets its own" ); - assert!(!needs_leading_newline(None, false), "a pipe keeps its framing"); + assert!( + !needs_leading_newline(None, false), + "a pipe keeps its framing" + ); } // `umask` is process-wide, so the case re-runs in a child under it; only the child asserts.