Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 94 additions & 2 deletions pkgs/id/src/world/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<usize> {
serde_json::to_vec(event).ok().map(|bytes| bytes.len())
}

fn admin_history_bytes<'a>(events: impl IntoIterator<Item = &'a WorldEvent>) -> 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<Option<usize>>,
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<usize>) {
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<Item = &'a WorldEvent>) -> Self {
let mut ledger = Self::default();
for event in events {
ledger.track(admin_history_event_bytes(event));
}
ledger
}
}

fn presence_after(events: &[WorldEvent]) -> BTreeSet<u64> {
let mut present = BTreeSet::new();
for event in events {
Expand Down Expand Up @@ -83,6 +166,10 @@ pub struct WorldCore {
pub(crate) admin_history: VecDeque<WorldEvent>,
/// 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.
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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;
}
}
Expand Down Expand Up @@ -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(())
Expand Down
1 change: 1 addition & 0 deletions pkgs/id/src/world/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down
160 changes: 160 additions & 0 deletions pkgs/id/src/world/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down