From e9eae6ce0e39bb2a72a2d026c80eb25d80cff94f Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 2 Nov 2026 21:08:20 -0600 Subject: [PATCH] fix(id/world): track retained admin-history bytes incrementally (#4633) record_admin_history re-serialized every retained admin-history event on every accepted event (and after each trim pop). Cache each event's encoded size once in AdminHistoryByteLedger and maintain the running total on push/pop, so recording is amortized O(1) in retained history size. Unserializable events count as usize::MAX, matching the legacy rescan semantics, so they force a trim instead of occupying unaccounted space. Restore keeps its one-shot over-budget scan and rebuilds the ledger. Regression tests cover the unserializable case, count-trim sync, byte-cap trim of a single oversized event, and restore sync. --- pkgs/id/src/world/core.rs | 96 +++++++++++++++++++++- pkgs/id/src/world/mod.rs | 1 + pkgs/id/src/world/tests.rs | 160 +++++++++++++++++++++++++++++++++++++ 3 files changed, 255 insertions(+), 2 deletions(-) diff --git a/pkgs/id/src/world/core.rs b/pkgs/id/src/world/core.rs index b6220d7597..f622c2dcb2 100644 --- a/pkgs/id/src/world/core.rs +++ b/pkgs/id/src/world/core.rs @@ -13,13 +13,96 @@ use anyhow::{Context, Result, ensure}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque}; use std::sync::Arc; +/// Encoded byte size of one admin-history event, or `None` when the event +/// cannot be serialized at all. Serialization failure is deliberate in the +/// accounting below (#4633): an unserializable event counts as +/// `usize::MAX` bytes, exactly as the previous rescan-every-time helper +/// treated it, so it forces the retained history to trim rather than +/// silently occupying unaccounted space. +fn admin_history_event_bytes(event: &WorldEvent) -> Option { + serde_json::to_vec(event).ok().map(|bytes| bytes.len()) +} + fn admin_history_bytes<'a>(events: impl IntoIterator) -> usize { events .into_iter() - .map(|event| serde_json::to_vec(event).map_or(usize::MAX, |bytes| bytes.len())) + .map(|event| admin_history_event_bytes(event).unwrap_or(usize::MAX)) .fold(0usize, usize::saturating_add) } +/// Incrementally maintained byte accounting for the retained admin history +/// (#4633). `record_admin_history` used to re-serialize every retained +/// event on every accepted event; this ledger caches each event's encoded +/// size once, when the event is recorded (or once during restore, where a +/// one-shot scan is acceptable), and maintains the running total as events +/// are pushed and trimmed, so recording is amortized O(1) in the retained +/// history size. +/// +/// Invariant: `sizes` holds one entry per retained admin-history event, in +/// the same order as `WorldCore::admin_history`. A `None` entry is an event +/// that failed to serialize; while any `None` is retained, +/// [`AdminHistoryByteLedger::effective_bytes`] is `usize::MAX`, matching +/// the legacy rescan semantics. +#[derive(Debug, Default)] +pub(crate) struct AdminHistoryByteLedger { + sizes: VecDeque>, + serializable_bytes: usize, + unserializable: usize, +} + +impl AdminHistoryByteLedger { + /// Start tracking one newly retained event of the given encoded size. + pub(crate) fn track(&mut self, size: Option) { + self.sizes.push_back(size); + match size { + Some(bytes) => { + self.serializable_bytes = self.serializable_bytes.saturating_add(bytes); + } + None => { + self.unserializable = self.unserializable.saturating_add(1); + } + } + } + + /// Stop tracking the oldest retained event (it was trimmed). + pub(crate) fn untrack_front(&mut self) { + if let Some(size) = self.sizes.pop_front() { + match size { + Some(bytes) => { + self.serializable_bytes = self.serializable_bytes.saturating_sub(bytes); + } + None => { + self.unserializable = self.unserializable.saturating_sub(1); + } + } + } + } + + /// The byte total the trim loop compares against the cap: the running + /// total, or `usize::MAX` while an unserializable event is retained. + pub(crate) fn effective_bytes(&self) -> usize { + if self.unserializable > 0 { + usize::MAX + } else { + self.serializable_bytes + } + } + + /// Number of events currently tracked; equals the retained history len. + pub(crate) fn tracked(&self) -> usize { + self.sizes.len() + } + + /// Rebuild the ledger for a restored history with a one-shot scan. + fn rebuild<'a>(events: impl IntoIterator) -> Self { + let mut ledger = Self::default(); + for event in events { + ledger.track(admin_history_event_bytes(event)); + } + ledger + } +} + fn presence_after(events: &[WorldEvent]) -> BTreeSet { let mut present = BTreeSet::new(); for event in events { @@ -83,6 +166,10 @@ pub struct WorldCore { pub(crate) admin_history: VecDeque, /// False once the oldest part of the journal history has been trimmed. pub(crate) admin_history_complete: bool, + /// Cached encoded sizes + running byte total for `admin_history` + /// (#4633); kept in lockstep with it by `record_admin_history` and + /// `restore_admin_history`. + pub(crate) admin_history_ledger: AdminHistoryByteLedger, /// Participants whose join the program has seen without a later leave. /// Unlike the actor's live-session refcount, this survives compaction so /// restore can deliver one leave for sessions lost with the process. @@ -239,6 +326,7 @@ impl WorldCore { events: VecDeque::new(), admin_history: VecDeque::new(), admin_history_complete: true, + admin_history_ledger: AdminHistoryByteLedger::default(), open_presence: BTreeSet::new(), directory: crate::directory::Directory::new(), petnames: crate::petname::Petnames::new(), @@ -1705,13 +1793,16 @@ impl WorldCore { self.open_presence.remove(&participant); } } + self.admin_history_ledger + .track(admin_history_event_bytes(&event)); self.admin_history.push_back(event); while self.admin_history.len() > self.limits.retained_events.min(MAX_ADMIN_HISTORY_EVENTS) - || admin_history_bytes(&self.admin_history) > MAX_ADMIN_HISTORY_BYTES + || self.admin_history_ledger.effective_bytes() > MAX_ADMIN_HISTORY_BYTES { if self.admin_history.pop_front().is_none() { break; } + self.admin_history_ledger.untrack_front(); self.admin_history_complete = false; } } @@ -1771,6 +1862,7 @@ impl WorldCore { .is_some_and(|event| event.sequence == 1), "complete checkpoint admin history does not start at sequence 1" ); + self.admin_history_ledger = AdminHistoryByteLedger::rebuild(&events); self.admin_history = events.into(); self.admin_history_complete = complete; Ok(()) diff --git a/pkgs/id/src/world/mod.rs b/pkgs/id/src/world/mod.rs index f4a6ca80b7..a52971fb32 100644 --- a/pkgs/id/src/world/mod.rs +++ b/pkgs/id/src/world/mod.rs @@ -46,6 +46,7 @@ mod tests; pub(crate) use actor::{WorldActor, WorldCommand}; pub use clock::{Clock, ManualClock, SystemClock}; pub use core::WorldCore; +pub(crate) use core::AdminHistoryByteLedger; pub use handle::WorldHandle; pub use metrics::{HistogramSnapshot, MetricsSnapshot, WorldMetrics}; pub use replication::{ diff --git a/pkgs/id/src/world/tests.rs b/pkgs/id/src/world/tests.rs index 6b4822b2e2..1245a9b3f8 100644 --- a/pkgs/id/src/world/tests.rs +++ b/pkgs/id/src/world/tests.rs @@ -1933,6 +1933,166 @@ mod tests { assert_eq!(restored.core.admin_history.len(), 2); } + #[test] + fn admin_history_byte_ledger_counts_unserializable_as_max_until_trimmed() { + // Deliberate serialization-failure semantics (#4633): an event that + // cannot be serialized counts as usize::MAX bytes — exactly as the + // old rescan-every-time helper treated it — so it forces the + // retained history to trim rather than occupying unaccounted space. + let mut ledger = AdminHistoryByteLedger::default(); + ledger.track(Some(10)); + ledger.track(Some(20)); + assert_eq!(ledger.effective_bytes(), 30); + assert_eq!(ledger.tracked(), 2); + ledger.track(None); + assert_eq!(ledger.effective_bytes(), usize::MAX); + ledger.untrack_front(); + ledger.untrack_front(); + assert_eq!( + ledger.effective_bytes(), + usize::MAX, + "the unserializable event is still retained" + ); + ledger.untrack_front(); + assert_eq!(ledger.effective_bytes(), 0); + assert_eq!(ledger.tracked(), 0); + } + + #[test] + fn admin_history_byte_ledger_stays_in_sync_through_count_trim() { + let limits = WorldLimits { + retained_events: 2, + ..WorldLimits::default() + }; + let mut core = WorldCore::new("ledger-trim-sync", limits).unwrap(); + for n in 0..5 { + core.record_admin_history(WorldEvent { + sequence: 0, + participant_id: 0, + kind: WorldEventKind::System { + event: format!(r#"{{"cap":"host","event":"tick-{n}"}}"#), + }, + }); + } + assert_eq!(core.admin_history.len(), 2); + assert!(!core.admin_history_complete); + assert_eq!(core.admin_history_ledger.tracked(), core.admin_history.len()); + let rescanned: usize = core + .admin_history + .iter() + .map(|event| serde_json::to_vec(event).unwrap().len()) + .sum(); + assert_eq!(core.admin_history_ledger.effective_bytes(), rescanned); + } + + #[test] + fn admin_history_byte_cap_trims_even_a_single_oversized_event() { + let mut core = WorldCore::new("ledger-byte-cap", WorldLimits::default()).unwrap(); + core.record_admin_history(WorldEvent { + sequence: 0, + participant_id: 0, + kind: WorldEventKind::System { + event: "small".to_owned(), + }, + }); + assert_eq!(core.admin_history.len(), 1); + core.record_admin_history(WorldEvent { + sequence: 0, + participant_id: 0, + kind: WorldEventKind::System { + event: "x".repeat(MAX_ADMIN_HISTORY_BYTES + 1), + }, + }); + assert!( + core.admin_history.is_empty(), + "an event larger than the byte cap cannot be retained" + ); + assert!(!core.admin_history_complete); + assert_eq!(core.admin_history_ledger.tracked(), 0); + assert_eq!(core.admin_history_ledger.effective_bytes(), 0); + } + + #[test] + fn admin_history_byte_ledger_stays_in_sync_through_restore() { + let mut core = WorldCore::new("ledger-restore-sync", WorldLimits::default()).unwrap(); + core.active_module_hash = Some("h".to_owned()); + core.commit_prepared(WorldEvent { + sequence: 1, + participant_id: 0, + kind: WorldEventKind::ProgramInstalled { + module_hash: "h".to_owned(), + seed: 7, + provenance: None, + trust: None, + }, + }) + .unwrap(); + for event in ["tick", "schedule"] { + core.record_admin_history(WorldEvent { + sequence: 0, + participant_id: 0, + kind: WorldEventKind::System { + event: format!(r#"{{"cap":"host","event":"{event}"}}"#), + }, + }); + } + let checkpoint = core.checkpoint_entries("snapshot".to_owned()).unwrap(); + let restored = + WorldCore::restore("ledger-restore-sync", WorldLimits::default(), checkpoint).unwrap(); + assert!(restored.core.admin_history_complete); + assert_eq!( + restored.core.admin_history_ledger.tracked(), + restored.core.admin_history.len() + ); + let rescanned: usize = restored + .core + .admin_history + .iter() + .map(|event| serde_json::to_vec(event).unwrap().len()) + .sum(); + assert_eq!( + restored.core.admin_history_ledger.effective_bytes(), + rescanned + ); + } + + #[test] + fn restore_rejects_checkpoint_admin_history_over_the_byte_bound() { + let mut core = WorldCore::new("ledger-restore-bytes", WorldLimits::default()).unwrap(); + core.active_module_hash = Some("h".to_owned()); + core.commit_prepared(WorldEvent { + sequence: 1, + participant_id: 0, + kind: WorldEventKind::ProgramInstalled { + module_hash: "h".to_owned(), + seed: 7, + provenance: None, + trust: None, + }, + }) + .unwrap(); + let mut checkpoint = core.checkpoint_entries("snapshot".to_owned()).unwrap(); + if let Some(JournalEntry::Checkpoint { admin_history, .. }) = checkpoint.last_mut() { + *admin_history = Some(JournalAdminHistory { + events: vec![WorldEvent { + sequence: 0, + participant_id: 0, + kind: WorldEventKind::System { + event: "x".repeat(MAX_ADMIN_HISTORY_BYTES + 1), + }, + }], + complete: false, + }); + } else { + panic!("checkpoint entry missing"); + } + assert!( + WorldCore::restore("ledger-restore-bytes", WorldLimits::default(), checkpoint) + .is_err(), + "a checkpoint whose admin history exceeds the byte bound must be refused" + ); + } + #[tokio::test] async fn the_actor_journals_host_events_and_grants() { #[derive(Default, Clone)]