From da2afad95b7cfe6e50bfc3ec15f87b01c8ea84eb Mon Sep 17 00:00:00 2001 From: Tyler Smith <74526874+tylertms@users.noreply.github.com> Date: Thu, 12 Nov 2026 00:16:19 -0500 Subject: [PATCH] perf(engine): write a boot's pack segments when its entries reach half their bound, the first when translation goes quiet, and merge the newest two as they grow, from a writer tested on the host --- crates/stela-boot/src/engine/translations.rs | 599 ++++----------- crates/stela-engine/src/translations.rs | 1 + crates/stela-engine/src/translations/pack.rs | 11 + .../stela-engine/src/translations/writer.rs | 721 ++++++++++++++++++ .../src/translations/writer/tests.rs | 499 ++++++++++++ 5 files changed, 1384 insertions(+), 447 deletions(-) create mode 100644 crates/stela-engine/src/translations/writer.rs create mode 100644 crates/stela-engine/src/translations/writer/tests.rs diff --git a/crates/stela-boot/src/engine/translations.rs b/crates/stela-boot/src/engine/translations.rs index fed72bd1e5..ae4bb0a134 100644 --- a/crates/stela-boot/src/engine/translations.rs +++ b/crates/stela-boot/src/engine/translations.rs @@ -42,11 +42,9 @@ use stela_engine::translations; use stela_engine::translations::Digest; use stela_engine::translations::Record; use stela_engine::translations::pack; -use stela_engine::translations::pack::{ - DecodedRecord, Delta, Layout, MAX_SEGMENTS, MAX_USED_KEYS, MAX_USED_LISTS, Merge, Pack, - StagedOffer, Store, UsedKeys, -}; -use stela_formats::journal::{self, Blob, Change, Commit, DATA_START, Execution, SLOT_BYTES, Step}; +use stela_engine::translations::pack::{DecodedRecord, Pack, StagedOffer, Store, UsedKeys}; +use stela_engine::translations::writer::{self, Entries, Event, Writer}; +use stela_formats::journal::{self, Commit, DATA_START, SLOT_BYTES}; use stela_formats::payload::pieces::Extent; use stela_runtime::pc::fat32::Fat32; use stela_runtime::pc::gpt::Guid; @@ -895,25 +893,23 @@ pub fn install(contents: &'static [u8]) -> Option { used.len(), )); let readable = if segments.is_empty() { 0 } else { READ_PACK }; - let writer = Writer { + let file = writer::File { translator, limit, file_bytes: size, committed, - extents: None, segments: segments.clone(), used, partial, - merged: false, - added_keys: Vec::new(), - task: Task::Idle, - queued: Queued::default(), - next_delta: 0, - delta_interval: super::host::COUNTER_HZ * FIRST_DELTA_SECONDS, - failed: false, - stats: Stats::default(), }; - WRITER.holding(true, |slot| *slot = Some(writer)); + let held = PackWriter { + writer: Writer::new(file, super::host::COUNTER_HZ), + extents: None, + queued: Queued::default(), + steps: 0, + longest: 0, + }; + WRITER.holding(true, |slot| *slot = Some(held)); BOOT.with(|boot| { for lock in &STORES { let old = lock.with(Option::take); @@ -959,8 +955,8 @@ pub fn set_partition(partition: Box) { return; }; let extents = with_store_file(&pack_name(&translator), |_, extents| extents.to_vec()); - WRITER.with(|writer| match extents { - Ok(extents) => writer.extents = Some(extents), + WRITER.with(|held| match extents { + Ok(extents) => held.extents = Some(extents), Err(error) => { output::arguments(format_args!( "TRANSLATIONS written only at a stop: {error}\n" @@ -1062,348 +1058,94 @@ fn report(counters: &pack::Counters) { )); } -/// Segments or used-key lists at which a boot merges them. -const MERGE_AT: usize = 4; -/// The first new segment's delay, which doubles with each, up to the last: -/// a boot's compiling comes in bursts, mostly early, and the segments a -/// file holds are few ([`MAX_SEGMENTS`]). -const FIRST_DELTA_SECONDS: u64 = 60; -const LAST_DELTA_SECONDS: u64 = 32 * 60; -/// How long a step may take, in microseconds, and the work it does between -/// looks at the clock (records encoded, page keys merged, records indexed). +/// How long a step may take, in microseconds. const STEP_MICROS: u64 = 1000; -const STEP_WORK: usize = 32; -/// The bytes a step copies of a new segment, and the most a write step -/// queues. -const COPY_BYTES: u64 = 1 << 20; -const PIECE_BYTES: u64 = 512 << 10; -/// The writer of the pack file while the guest runs and at a stop. -struct Writer { - translator: Digest, - /// The bound a merged segment stays within: what this PC can read. - limit: u64, - file_bytes: u64, - committed: Option, - /// The file's device extents, found while the drivers may be called. +/// The pack file's writer (`translations::writer`) with what the boot adds: +/// the file's device extents, found while the drivers may be called, the +/// staged commands of the write in flight, and the steps it took. +struct PackWriter { + writer: Writer<'static>, extents: Option>, - /// The segments read and those this boot wrote, oldest first, and the - /// used-key lists read: a merge's input. - segments: Vec>, - used: Vec, - /// A segment was not read whole: no merge runs. - partial: bool, - /// This boot's merge ran or was tried: its segment is not in memory, so - /// no other follows. - merged: bool, - /// The keys of the entries this boot took for its segments: with those - /// it found, its used keys. More than a list names counts every key. - added_keys: Vec, - task: Task, - /// The staged commands of the write in flight. queued: Queued, - /// Host counter value before which no new segment starts, and the delay - /// after the next. - next_delta: u64, - delta_interval: u64, - /// A write failed: the file is not written again this boot. - failed: bool, - stats: Stats, -} - -/// What the writer did while the guest ran. -#[derive(Default)] -struct Stats { steps: u64, longest: u64, - deltas: u64, - delta_records: u64, - delta_bytes: u64, - merges: u64, - abandoned: u64, } -/// The writer's work in progress. -enum Task { - Idle, - /// A new segment of the entries taken, being laid out. - Delta(Box), - /// The new segment, being copied into memory the boot keeps for a - /// merge. - Copy { - layout: Layout<'static>, - bytes: Vec, - }, - Merge(Box>), - Write { - execution: Box>, - done: Done, - }, -} +static WRITER: Held = Held::new(); -/// What a finished write leaves. -enum Done { - Segment(Pack<'static>), - Merge, -} +/// The store's parts, as the writer sees them. +struct Parts; -static WRITER: Held = Held::new(); - -/// The keys found valid by every part of the store, with `added`: the -/// boot's used keys so far, as a list. -fn used_now(added: &[Digest]) -> Vec { - let translator = translations::translator_id(); - if added.len() > MAX_USED_KEYS { - return UsedKeys::encode_every(&translator); - } - let mut keys: Vec = added.to_vec(); - for lock in &STORES { - lock.with(|store| { - if let Some(store) = store { - keys.extend(store.used_keys().copied()); - } - }); - } - UsedKeys::encode(&translator, keys.iter()) -} - -impl Writer { - /// The committed blobs of `kind` of this translator. - fn count(&self, kind: u32) -> usize { - self.committed - .as_ref() - .filter(|commit| commit.key == self.translator.0) - .map_or(0, |commit| { - commit - .entries - .iter() - .filter(|entry| entry.kind == kind) - .count() - }) +impl Entries for Parts { + fn take_added(&mut self) -> BTreeMap { + let mut added = BTreeMap::new(); + for lock in &STORES { + let mut part = + lock.with(|store| store.as_mut().map(Store::take_added).unwrap_or_default()); + added.append(&mut part); + } + added } - /// Note the keys of entries taken for a segment. - fn note_added(&mut self, added: &BTreeMap) { - if self.added_keys.len() <= MAX_USED_KEYS { - self.added_keys.extend(added.keys().copied()); + fn found_keys(&mut self) -> Vec { + let mut keys = Vec::new(); + for lock in &STORES { + lock.with(|store| { + if let Some(store) = store { + keys.extend(store.used_keys().copied()); + } + }); } + keys } - /// Start a merge when the file holds enough segments or lists, else a - /// segment of the entries added when its time came. - fn begin(&mut self, now: u64) { - let segments = self.count(SEGMENT); - if !self.merged && !self.partial && (segments >= MERGE_AT || self.count(USED) >= MERGE_AT) { - self.merged = true; - // Beside the file's content, so its commit keeps that content - // until the merged segment is whole. - let free = journal::largest_free( - self.committed.as_ref(), - DOMAIN, - self.translator.0, - self.file_bytes, - ); - let protect = UsedKeys::parse(&used_now(&self.added_keys), &self.translator); - let mut merge = Merge::new( - self.translator, - self.segments.iter().copied().map(Into::into).collect(), - self.used.clone(), - self.limit.min(free), - ); - if let Some(protect) = protect { - merge = merge.protect(protect); - } - self.task = Task::Merge(Box::new(merge)); - return; - } - if self.next_delta == 0 { - self.next_delta = now + self.delta_interval; - } - // One segment stays free for the stop's. - if now < self.next_delta || segments + 1 >= MAX_SEGMENTS { - return; - } - let added = take_added(); - if added.is_empty() { - self.next_delta = now + super::host::COUNTER_HZ * 10; - return; - } - self.next_delta = now + self.delta_interval; - self.delta_interval = - (self.delta_interval * 2).min(super::host::COUNTER_HZ * LAST_DELTA_SECONDS); - self.note_added(&added); - self.stats.delta_records += added.len() as u64; - self.task = Task::Delta(Box::new(Delta::new(self.translator, added))); - } - - /// Plan writing `change`, which must commit once beside the file's - /// content: else it is left out. - fn plan(&mut self, change: Change<'static>, what: &str) -> Option>> { - let plan = journal::plan( - self.committed.as_ref(), - DOMAIN, - self.translator.0, - self.file_bytes, - change, - ); - let commits = plan - .steps + fn added(&mut self) -> u64 { + STORES .iter() - .filter(|step| matches!(step, Step::Commit(_))) - .count(); - if !plan.dropped.is_empty() || commits > 1 { - output::arguments(format_args!( - "TRANSLATIONS {what} not written: no room beside the content of a file of {} \ - bytes\n", - self.file_bytes - )); - self.stats.abandoned += 1; - return None; - } - Some(Box::new(Execution::new(plan))) + .map(|lock| lock.with(|store| store.as_ref().map_or(0, |store| store.counters.added))) + .sum() } - /// The task that writes `change` ([`Self::plan`]) and then leaves - /// `done`. - fn write(&mut self, change: Change<'static>, done: Done, what: &str) -> Task { - match self.plan(change, what) { - Some(execution) => Task::Write { execution, done }, - None => Task::Idle, - } - } - - /// A write finished: its commit is the file's newest. - fn finish(&mut self, execution: &Execution<'static>, done: Done) { - if let Some(last) = execution.last() { - self.committed = Some(last); - } - match done { - Done::Segment(pack) => { - self.stats.deltas += 1; - self.stats.delta_bytes += pack.bytes() as u64; - self.segments.push(pack); - } - Done::Merge => { - self.stats.merges += 1; - self.segments.clear(); - self.used.clear(); - } - } - } - - /// Carry the work forward until `deadline` (a host counter value), or - /// until a write queued its piece. - fn work(&mut self, now: u64, deadline: u64) -> Result<(), String> { - if matches!(self.task, Task::Idle) { - self.begin(now); - } - loop { - self.task = match core::mem::replace(&mut self.task, Task::Idle) { - Task::Idle => return Ok(()), - Task::Delta(mut delta) => { - if delta.step(STEP_WORK) { - match delta.finish() { - Some(layout) => Task::Copy { - bytes: Vec::with_capacity(layout.bytes() as usize), - layout, - }, - None => Task::Idle, - } - } else { - Task::Delta(delta) - } - } - Task::Copy { layout, mut bytes } => { - let at = bytes.len(); - let take = (layout.bytes() - at as u64).min(COPY_BYTES) as usize; - bytes.resize(at + take, 0); - layout.read_at(at as u64, &mut bytes[at..]); - if (bytes.len() as u64) < layout.bytes() { - Task::Copy { layout, bytes } - } else { - drop(layout); - // Kept for the boot: a merge reads it. - let bytes: &'static [u8] = Box::leak(bytes.into_boxed_slice()); - match Pack::parse(bytes, &self.translator) { - Ok(pack) => { - let change = Change { - replace: Vec::new(), - remove: Vec::new(), - blobs: vec![Blob::new(SEGMENT, bytes)], - }; - self.write(change, Done::Segment(pack), "segment") - } - Err(error) => return Err(format!("a new segment: {error:?}")), - } - } - } - Task::Merge(mut merge) => { - if merge.step(STEP_WORK) { - let merged = merge.finish(); - output::arguments(format_args!( - "TRANSLATIONS merged records={} bytes={} evicted={} expired={} \ - invalid={}\n", - merged.layout.records(), - merged.layout.bytes(), - merged.evicted, - merged.expired, - merged.invalid - )); - let change = Change { - replace: vec![SEGMENT, USED], - remove: Vec::new(), - blobs: vec![Blob::new(SEGMENT, merged.layout)], - }; - self.write(change, Done::Merge, "merge") - } else { - Task::Merge(merge) - } - } - Task::Write { - mut execution, - done, - } => { - let Some(extents) = self.extents.as_deref() else { - return Err(String::from("no extents")); - }; - let queued = &mut self.queued; - let advanced = lend_staged_partition(|device| { - let mut target = Staged { - device, - extents, - queued, - }; - execution.advance(&mut target, PIECE_BYTES) - }); - match advanced { - Some(Ok(true)) => self.finish(&execution, done), - Some(Err(error)) => return Err(error), - None | Some(Ok(false)) => self.task = Task::Write { execution, done }, - } - return Ok(()); - } - }; - if super::host::fresh_counter() >= deadline { - return Ok(()); - } - } - } - - fn fail(&mut self, error: &str) { - output::arguments(format_args!("TRANSLATIONS not written: {error}\n")); - self.task = Task::Idle; - self.failed = true; + fn pressed(&mut self) -> bool { + STORES + .iter() + .any(|lock| lock.with(|store| store.as_ref().is_some_and(Store::added_pressed))) } } -/// The entries every part of the store added since the last take. -fn take_added() -> BTreeMap { - let mut added = BTreeMap::new(); - for lock in &STORES { - let mut part = lock.with(|store| store.as_mut().map(Store::take_added).unwrap_or_default()); - added.append(&mut part); +/// Report what a writer step did. +fn report_event(event: &Event) { + match event { + Event::Segment { + records, + bytes, + trigger, + } => output::arguments(format_args!( + "TRANSLATIONS segment records={records} bytes={bytes} trigger={trigger:?}\n" + )), + Event::Merged { + full, + records, + bytes, + bound, + evicted, + expired, + invalid, + } => output::arguments(format_args!( + "TRANSLATIONS merged full={full} records={records} bytes={bytes} bound={bound} \ + evicted={evicted} expired={expired} invalid={invalid}\n" + )), + Event::MergeCommitted { full } => { + output::arguments(format_args!("TRANSLATIONS merge written full={full}\n")) + } + Event::Waiting { records } => output::arguments(format_args!( + "TRANSLATIONS segment of {records} records waits for a merge to make room\n" + )), + Event::Lost { records } => output::arguments(format_args!( + "TRANSLATIONS segment of {records} records left out: larger than the file holds\n" + )), } - added } /// While the guest runs, from a processor whose guest waits and that holds @@ -1414,133 +1156,96 @@ pub fn step() { return; } let started = super::host::fresh_counter(); - WRITER.try_with(|writer| { - if writer.failed || writer.extents.is_none() { + WRITER.try_with(|held| { + let Some(extents) = held.extents.as_deref() else { + return; + }; + if held.writer.failed() { return; } - let idle = matches!(writer.task, Task::Idle); + let idle = held.writer.idle(); let deadline = started + super::host::COUNTER_HZ * STEP_MICROS / 1_000_000; - if let Err(error) = writer.work(started, deadline) { - writer.fail(&error); + let queued = &mut held.queued; + let stepped = held.writer.step( + &mut super::host::fresh_counter, + deadline, + &mut Parts, + &mut |execution| { + lend_staged_partition(|device| { + let mut target = Staged { + device, + extents, + queued: &mut *queued, + }; + execution.advance(&mut target, writer::PIECE_BYTES) + }) + }, + ); + match stepped { + Ok(events) => events.iter().for_each(report_event), + Err(error) => output::arguments(format_args!("TRANSLATIONS not written: {error}\n")), } - if !idle || !matches!(writer.task, Task::Idle) { + if !idle || !held.writer.idle() { let took = super::host::fresh_counter().wrapping_sub(started); - writer.stats.steps += 1; - writer.stats.longest = writer.stats.longest.max(took); + held.steps += 1; + held.longest = held.longest.max(took); } }); } -/// At a quiescent point (the guest restarts or powers off): finish a new -/// segment's write in flight, then write a segment of the entries left and -/// this boot's used-key list. A merge not yet committed is left: its input -/// stays in the file. +/// At a quiescent point (the guest restarts or powers off): the writer's +/// stop ([`Writer::stop`]), carried out on the partition directly. pub fn write() { AVAILABLE.capabilities.store(0, Ordering::SeqCst); AVAILABLE.shared_bound.store(0, Ordering::Release); + let started = output::now(); + let held = WRITER.holding(true, Option::take).flatten(); + let writable = BOOT.with(|boot| boot.as_ref().is_some_and(|boot| boot.partition.is_some())); + if let Some(mut held) = held.filter(|_| writable) { + let stats = held.writer.stats(); + output::arguments(format_args!( + "TRANSLATIONS writer steps={} longest_us={} segments={} records={} bytes={} \ + pressed={} pairs={} merges={}\n", + held.steps, + held.longest * 1_000_000 / super::host::COUNTER_HZ, + stats.deltas, + stats.delta_records, + stats.delta_bytes, + stats.pressed, + stats.pairs, + stats.merges, + )); + let name = pack_name(&translations::translator_id()); + let stopped = held.writer.stop(&mut Parts, &mut |execution| { + with_store_file(&name, |device, extents| { + let mut target = Direct { device, extents }; + while !execution.advance(&mut target, writer::PIECE_BYTES)? {} + Ok::<(), String>(()) + }) + .and_then(|done| done) + }); + match stopped { + Ok(stopped) => output::arguments(format_args!( + "TRANSLATIONS written segments={} lists={} records={} lost={} bytes={} \ + merge_left={} ms={}\n", + stopped.segments, + stopped.lists, + stopped.records, + stopped.lost, + stopped.bytes, + stopped.merge_left, + output::millis_since(started) + )), + Err(error) => output::arguments(format_args!("TRANSLATIONS not written: {error}\n")), + } + } let mut parts = STORES.iter().filter_map(|lock| lock.with(Option::take)); - let store = parts.next().map(|mut store| { + if let Some(mut store) = parts.next() { for part in parts { store.absorb(part); } - store - }); - if let Some(store) = &store { report(&store.counters); } - let writer = WRITER.holding(true, Option::take).flatten(); - if let (Some(mut store), Some(mut writer)) = (store, writer) - && BOOT.with(|boot| boot.as_ref().is_some_and(|boot| boot.partition.is_some())) - && !writer.failed - { - write_last(&mut writer, &mut store); - } let boot = BOOT.with(Option::take); drop(boot); } - -/// The stop's writes ([`write`]). -fn write_last(writer: &mut Writer, store: &mut Store<'static>) { - let started = output::now(); - let name = pack_name(&writer.translator); - let run = |execution: &mut Execution<'static>| { - with_store_file(&name, |device, extents| { - let mut target = Direct { device, extents }; - while !execution.advance(&mut target, PIECE_BYTES)? {} - Ok::<(), String>(()) - }) - .and_then(|done| done) - }; - // What the run left: a segment's write is finished, one being made is - // written with the rest, a merge is left. - let mut pending: Vec> = Vec::new(); - match core::mem::replace(&mut writer.task, Task::Idle) { - Task::Write { - mut execution, - done: done @ Done::Segment(_), - } => match run(&mut execution) { - Ok(()) => writer.finish(&execution, done), - Err(error) => return writer.fail(&error), - }, - Task::Delta(delta) => pending.extend(delta.finish()), - Task::Copy { layout, .. } => pending.push(layout), - Task::Merge(_) | Task::Write { .. } => { - output::arguments(format_args!("TRANSLATIONS merge left for the next boot\n")); - writer.stats.abandoned += 1; - } - Task::Idle => {} - } - let stats = &writer.stats; - output::arguments(format_args!( - "TRANSLATIONS writer steps={} longest_us={} segments={} records={} bytes={} merges={} \ - abandoned={}\n", - stats.steps, - stats.longest * 1_000_000 / super::host::COUNTER_HZ, - stats.deltas, - stats.delta_records, - stats.delta_bytes, - stats.merges, - stats.abandoned - )); - let added = store.take_added(); - writer.note_added(&added); - let records = added.len(); - pending.extend(Delta::new(writer.translator, added).finish()); - let mut change = Change::default(); - let room = MAX_SEGMENTS.saturating_sub(writer.count(SEGMENT)); - let lost: usize = pending.iter().skip(room).map(Layout::records).sum(); - for layout in pending.into_iter().take(room) { - change.blobs.push(Blob::new(SEGMENT, layout)); - } - let lists = writer.count(USED) < MAX_USED_LISTS; - if lists { - let list = if writer.added_keys.len() > MAX_USED_KEYS { - UsedKeys::encode_every(&writer.translator) - } else { - UsedKeys::encode( - &writer.translator, - store.used_keys().chain(&writer.added_keys), - ) - }; - change.blobs.push(Blob::new(USED, list)); - } - let bytes: u64 = change.blobs.iter().map(Blob::length).sum(); - let Some(mut execution) = writer.plan(change, "stop") else { - return; - }; - match run(&mut execution) { - Ok(()) => { - if let Some(last) = execution.last() { - writer.committed = Some(last); - } - output::arguments(format_args!( - "TRANSLATIONS written segments={} lists={} records={records} lost={lost} \ - bytes={bytes} ms={}\n", - writer.count(SEGMENT), - writer.count(USED), - output::millis_since(started) - )); - } - Err(error) => writer.fail(&error), - } -} diff --git a/crates/stela-engine/src/translations.rs b/crates/stela-engine/src/translations.rs index 1a2cdeecac..a98513c0d3 100644 --- a/crates/stela-engine/src/translations.rs +++ b/crates/stela-engine/src/translations.rs @@ -9,6 +9,7 @@ //! and the pack `stela.efi` keeps //! ([`pack`]). pub mod pack; +pub mod writer; use alloc::{string::String, vec::Vec}; use stela_compiler::block::Features; diff --git a/crates/stela-engine/src/translations/pack.rs b/crates/stela-engine/src/translations/pack.rs index 720be76fb0..14f8f5cb90 100644 --- a/crates/stela-engine/src/translations/pack.rs +++ b/crates/stela-engine/src/translations/pack.rs @@ -828,6 +828,11 @@ impl<'a> Merge<'a> { } } + /// The bound its segment stays within. + pub fn bound(&self) -> u64 { + self.bound + } + /// Keep the records of `keys`, those the running boot used so far, /// whatever their age. pub fn protect(mut self, keys: UsedKeys) -> Self { @@ -1722,6 +1727,12 @@ impl<'a> Store<'a> { self.added_bytes } + /// Whether the entries added since the last take reached half the + /// bound past which new ones are not kept: time to take them. + pub fn added_pressed(&self) -> bool { + self.added_bytes != 0 && self.added_bytes.saturating_mul(2) >= self.added_bound + } + /// The page keys looked up whose records were found valid: with the /// keys of the entries it added ([`Self::take_added`]), this boot's used /// keys ([`UsedKeys`]). diff --git a/crates/stela-engine/src/translations/writer.rs b/crates/stela-engine/src/translations/writer.rs new file mode 100644 index 0000000000..1efa5d3b24 --- /dev/null +++ b/crates/stela-engine/src/translations/writer.rs @@ -0,0 +1,721 @@ +//! The order in which a boot writes its pack file, a journal of segments and +//! used-key lists ([`super::pack`]), independent of the device: the boot +//! drives [`Writer::step`] on processors whose guest waits and +//! [`Writer::stop`] when the guest restarts or powers off, and hands each a +//! way to carry a journal plan out ([`Execution`]). +//! +//! While the guest runs, the entries the boot added go to the file as new +//! segments: the first once translation goes quiet (fewer than +//! [`QUIET_RATE`] entries a second for [`QUIET_SECONDS`]) or at +//! [`FIRST_DELTA_SECONDS`], whichever comes first, then at doubling +//! intervals; and whenever the entries held reach half their bound +//! ([`Entries::pressed`]), so none is refused for want of room while the +//! writer keeps up. +//! +//! The newest two segments are merged, keeping every record and its age, +//! once the newer is at least half the older: segment sizes stay geometric, +//! so the slots ([`MAX_SEGMENTS`]) suffice for any amount and a record is +//! rewritten a logarithmic number of times. A full merge folds every +//! segment and used-key list into one, dropping records unused for too many +//! boots: once a boot when the file holds [`MERGE_AT`] of either (after the +//! boot's first segment came due, and while translation does not press), +//! when the segments fill half the file, when a new segment finds no room, +//! or when the slots run short. A merge reads segments from memory: those +//! the boot read and those it laid out, whose records it moves instead of +//! copying. Every merged segment lies beside the file's content, so it +//! commits once and a cut leaves the content before it whole; a full merge +//! stays within [`MERGED_SHARE`] of the file, so new segments find room +//! until the next. A new segment the file has no room for waits for a +//! merge; one that finds none even after it is too large for the file and +//! is left out. +//! +//! At a stop, a new segment's write in flight is finished, a merge not yet +//! committed is left, and what is left and the boot's used-key list are +//! written. +use super::pack::{ + Delta, JOURNAL_DOMAIN, Layout, MAX_SEGMENTS, MAX_USED_KEYS, MAX_USED_LISTS, Merge, Merged, + Pack, SEGMENT_BLOB, Segment, USED_BLOB, UsedKeys, +}; +use super::{Digest, Record}; +use alloc::{boxed::Box, collections::BTreeMap, string::String, sync::Arc, vec, vec::Vec}; +use stela_formats::journal::{self, Blob, Change, Commit, DATA_START, Entry, Execution, Step}; + +/// Segments or used-key lists at which a boot merges them in full, once. +pub const MERGE_AT: usize = 4; +/// Segments in the file at which a full merge runs whatever else: a new +/// segment and the stop's stay possible. +pub const MERGE_FULL: usize = MAX_SEGMENTS - 2; +/// A full merge runs once the segments take more than half the file's data +/// area, and its segment takes at most this share of it (in eighths): the +/// rest is room for the merge beside the content and for new segments. +pub const MERGED_SHARE: u64 = 3; +/// The first new segment comes at this many seconds, or earlier once fewer +/// than [`QUIET_RATE`] entries a second were added for [`QUIET_SECONDS`]. A +/// boot translates its kernel and first services in a burst of thousands of +/// entries a second; when that burst ends, the entries the next boot needs +/// first are all there, and a crash after it loses none of them. Twenty +/// seconds bounds the wait when a boot never goes quiet. The delay then +/// doubles with each segment, up to the last. +pub const FIRST_DELTA_SECONDS: u64 = 20; +pub const QUIET_RATE: u64 = 100; +pub const QUIET_SECONDS: u64 = 3; +pub const LAST_DELTA_SECONDS: u64 = 32 * 60; +/// How long the writer waits to look again when nothing was added. +const RECHECK_SECONDS: u64 = 10; +/// How often a second the writer asks the store how much it added: the +/// question takes every part's lock. +const LOOKS_PER_SECOND: u64 = 10; +/// The work a step does between looks at the clock: records encoded, page +/// keys merged, or records indexed. +pub const STEP_WORK: usize = 32; +/// The most bytes a write step queues. +pub const PIECE_BYTES: u64 = 512 << 10; + +/// What the writer asks of the boot's store. +pub trait Entries { + /// The entries added since the last take. + fn take_added(&mut self) -> BTreeMap; + /// The page keys looked up and found valid so far. + fn found_keys(&mut self) -> Vec; + /// The entries added since the boot began. + fn added(&mut self) -> u64; + /// Whether the entries held for the next segment reached half the + /// bound past which new ones are refused. + fn pressed(&mut self) -> bool; +} + +/// Why a new segment started. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Trigger { + /// Its delay passed. + Due, + /// Translation went quiet before the first delay passed. + Quiet, + /// The entries held reached half their bound. + Pressed, +} + +/// What a step did that the boot reports. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Event { + /// A new segment of `records` was committed, `bytes` long. + Segment { + records: usize, + bytes: u64, + trigger: Trigger, + }, + /// A merge laid out its segment within `bound`: in full, or of the + /// newest two segments. + Merged { + full: bool, + records: usize, + bytes: u64, + bound: u64, + evicted: u64, + expired: u64, + invalid: u64, + }, + /// A merge's segment was committed. + MergeCommitted { full: bool }, + /// A new segment found no room: it waits for a merge. + Waiting { records: usize }, + /// A waiting segment found no room after a merge either: it is larger + /// than the file holds beside the merged content, and left out. + Lost { records: usize }, +} + +/// What the writer did while the guest ran. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct Stats { + pub deltas: u64, + pub delta_records: u64, + pub delta_bytes: u64, + /// Segments started because the entries held pressed. + pub pressed: u64, + /// Merges of the newest two segments, and full merges. + pub pairs: u64, + pub merges: u64, +} + +/// What [`Writer::stop`] wrote: the segments in the file after it, the +/// used-key lists, the records of its new segments, those no slot was left +/// for, and its bytes. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct Stopped { + pub segments: usize, + pub lists: usize, + pub records: usize, + pub lost: usize, + pub bytes: u64, + /// A merge was in progress and left for the next boot. + pub merge_left: bool, +} + +/// A merge in progress: in full, or of the newest two segments, at these +/// offsets in the file. +enum Merging { + Full, + Pair([u64; 2]), +} + +/// The writer's work in progress. +enum Task<'a> { + Idle, + /// A new segment of the entries taken, being laid out. + Delta(Box, Trigger), + Merge(Box>, Merging), + Write { + execution: Box>, + done: Done<'a>, + }, +} + +/// What a finished write leaves in memory. +enum Done<'a> { + Segment(Arc>, Trigger), + Merge(Arc>, Merging), +} + +/// A boot's writer of its pack file. +pub struct Writer<'a> { + translator: Digest, + /// The bound a merged segment stays within: what this PC can read. + limit: u64, + file_bytes: u64, + committed: Option, + /// The file's segments as memory holds them, oldest first, and the + /// used-key lists read: a merge's input. + segments: Vec>, + used: Vec, + /// A segment was not read whole: only a full merge the file needs + /// runs, as a merge leaves out what was not read. + partial: bool, + /// This boot's first full merge ran; its first segment came due. + merged: bool, + settled: bool, + /// New segments laid out with no room yet in the file, and whether a + /// merge committed since the first began to wait. + waiting: Vec>>, + merged_since_wait: bool, + /// The keys of the entries this boot took for its segments: with those + /// it found, its used keys. More than a list names counts every key. + added_keys: Vec, + task: Task<'a>, + /// Counter ticks per second, the counter value before which no new + /// segment starts (0: not yet set), and the delay after the next. + hz: u64, + next_delta: u64, + delta_interval: u64, + /// The last look at the entries added: when, and how many since the + /// boot began; whether they pressed then, and since when they came + /// slower than [`QUIET_RATE`]. + looked: Option<(u64, u64)>, + pressed: bool, + quiet_since: Option, + failed: bool, + stats: Stats, +} + +/// A boot's view of its pack file as the loader read it. +pub struct File<'a> { + pub translator: Digest, + /// The bound a merged segment stays within. + pub limit: u64, + pub file_bytes: u64, + /// The file's newest commit, any translator's. + pub committed: Option, + /// The segments and used-key lists read, oldest first. + pub segments: Vec>, + pub used: Vec, + /// A segment was left out or cut. + pub partial: bool, +} + +impl<'a> Writer<'a> { + pub fn new(file: File<'a>, hz: u64) -> Self { + Self { + translator: file.translator, + limit: file.limit, + file_bytes: file.file_bytes, + committed: file.committed, + segments: file.segments.into_iter().map(Segment::from).collect(), + used: file.used, + partial: file.partial, + merged: false, + settled: false, + waiting: Vec::new(), + merged_since_wait: false, + added_keys: Vec::new(), + task: Task::Idle, + hz, + next_delta: 0, + delta_interval: hz * FIRST_DELTA_SECONDS, + looked: None, + pressed: false, + quiet_since: None, + failed: false, + stats: Stats::default(), + } + } + + pub fn stats(&self) -> Stats { + self.stats + } + + pub fn failed(&self) -> bool { + self.failed + } + + pub fn idle(&self) -> bool { + matches!(self.task, Task::Idle) + } + + /// The file's newest commit, as the writer last committed or read it. + pub fn committed(&self) -> Option<&Commit> { + self.committed.as_ref() + } + + /// The committed blobs of `kind` of this translator, in order. + fn entries(&self, kind: u32) -> impl Iterator + '_ { + self.committed + .iter() + .filter(|commit| commit.key == self.translator.0) + .flat_map(|commit| commit.entries.iter()) + .filter(move |entry| entry.kind == kind) + } + + /// The committed blobs of `kind` of this translator. + pub fn count(&self, kind: u32) -> usize { + self.entries(kind).count() + } + + /// The longest free run beside the file's content. + fn free(&self) -> u64 { + journal::largest_free( + self.committed.as_ref(), + JOURNAL_DOMAIN, + self.translator.0, + self.file_bytes, + ) + } + + /// The data area's bytes. + fn data_bytes(&self) -> u64 { + (self.file_bytes / journal::ALIGN * journal::ALIGN).saturating_sub(DATA_START) + } + + /// Note the keys of entries taken for a segment. + fn note_added(&mut self, added: &BTreeMap) { + if self.added_keys.len() <= MAX_USED_KEYS { + self.added_keys.extend(added.keys().copied()); + } + } + + /// This boot's used keys so far, as a list. + fn used_list(&self, found: Vec) -> Vec { + if self.added_keys.len() > MAX_USED_KEYS { + return UsedKeys::encode_every(&self.translator); + } + UsedKeys::encode(&self.translator, found.iter().chain(&self.added_keys)) + } + + /// Look at what the store added, at most [`LOOKS_PER_SECOND`] times a + /// second: whether it presses, and since when it comes slowly. + fn look(&mut self, now: u64, entries: &mut dyn Entries) { + let Some((at, total)) = self.looked else { + self.looked = Some((now, entries.added())); + return; + }; + if now < at + (self.hz / LOOKS_PER_SECOND).max(1) { + return; + } + let added = entries.added(); + self.pressed = entries.pressed(); + let rate = added.saturating_sub(total) * self.hz / (now - at); + if rate >= QUIET_RATE { + self.quiet_since = None; + } else if self.quiet_since.is_none() { + self.quiet_since = Some(at); + } + self.looked = Some((now, added)); + } + + /// Why a new segment starts now, if one does. + fn trigger(&self, now: u64) -> Option { + if self.pressed { + return Some(Trigger::Pressed); + } + if now >= self.next_delta { + return Some(Trigger::Due); + } + let quiet = self + .quiet_since + .is_some_and(|since| now >= since + self.hz * QUIET_SECONDS); + let added = self.looked.is_some_and(|(_, added)| added != 0); + (!self.settled && quiet && added).then_some(Trigger::Quiet) + } + + /// The bytes of the file's segments. + fn segment_bytes(&self) -> u64 { + self.entries(SEGMENT_BLOB).map(|entry| entry.length).sum() + } + + /// Whether a full merge is due: the slots run short, the segments fill + /// half the file, a new segment waits for room, or, once a boot when + /// every segment was read, after its first segment came due and while + /// translation does not press, enough segments or lists. + fn full_merge_due(&self) -> bool { + let segments = self.count(SEGMENT_BLOB); + segments >= MERGE_FULL + || self.segment_bytes() > self.data_bytes() / 2 + || !self.waiting.is_empty() + || (!self.merged + && !self.partial + && self.settled + && !self.pressed + && (segments >= MERGE_AT || self.count(USED_BLOB) >= MERGE_AT)) + } + + /// The offsets of the newest two segments when they are due to merge: + /// the newer at least half the older, memory holding both as the file + /// does, the two within what this PC reads, and room beside the content + /// for both. + fn pair_due(&self) -> Option<[u64; 2]> { + if self.partial || self.segments.len() != self.count(SEGMENT_BLOB) { + return None; + } + let segments: Vec<&Entry> = self.entries(SEGMENT_BLOB).collect(); + let [.., older, newer] = segments[..] else { + return None; + }; + let both = older.length + newer.length; + (newer.length * 2 >= older.length && both <= self.limit && both <= self.free()) + .then_some([older.offset, newer.offset]) + } + + /// Write a waiting segment when it fits, else start a merge when one is + /// due, else start a segment of the entries added when its time came. + fn begin(&mut self, now: u64, entries: &mut dyn Entries) -> Option { + if let Some(layout) = self.waiting.first().cloned() { + if let Some(task) = self.write_segment(layout.clone(), Trigger::Due) { + self.waiting.remove(0); + self.task = task; + return None; + } + if self.merged_since_wait { + self.waiting.remove(0); + self.merged_since_wait = false; + return Some(Event::Lost { + records: layout.records(), + }); + } + } + self.look(now, entries); + if self.full_merge_due() && !self.segments.is_empty() { + self.merged = true; + // Beside the file's content, so its commit keeps that content + // until the merged segment is whole; within its share of the + // file, so new segments find room until the next merge. + let share = self.data_bytes() / 8 * MERGED_SHARE; + let bound = self.limit.min(share).min(self.free()); + let protect = UsedKeys::parse(&self.used_list(entries.found_keys()), &self.translator); + let segments = core::mem::take(&mut self.segments); + let mut merge = Merge::new(self.translator, segments, self.used.clone(), bound); + if let Some(protect) = protect { + merge = merge.protect(protect); + } + self.task = Task::Merge(Box::new(merge), Merging::Full); + return None; + } + if !self.waiting.is_empty() { + return None; + } + if let Some(offsets) = self.pair_due() { + let pair = self.segments.split_off(self.segments.len() - 2); + let merge = Merge::new(self.translator, pair, Vec::new(), self.limit); + self.task = Task::Merge(Box::new(merge), Merging::Pair(offsets)); + return None; + } + if self.next_delta == 0 { + self.next_delta = now + self.delta_interval; + } + let trigger = self.trigger(now)?; + // One segment stays free for the stop's. + if self.count(SEGMENT_BLOB) + 1 >= MAX_SEGMENTS { + return None; + } + self.settled = true; + self.pressed = false; + let added = entries.take_added(); + if added.is_empty() { + self.next_delta = self.next_delta.max(now + self.hz * RECHECK_SECONDS); + return None; + } + if trigger == Trigger::Pressed { + self.stats.pressed += 1; + } else { + self.next_delta = now + self.delta_interval; + self.delta_interval = (self.delta_interval * 2).min(self.hz * LAST_DELTA_SECONDS); + } + self.note_added(&added); + self.stats.delta_records += added.len() as u64; + self.task = Task::Delta(Box::new(Delta::new(self.translator, added)), trigger); + None + } + + /// The plan that writes `change`, which commits once beside the file's + /// content: `None` when it does not fit so. + fn plan(&self, change: Change<'a>) -> Option>> { + let plan = journal::plan( + self.committed.as_ref(), + JOURNAL_DOMAIN, + self.translator.0, + self.file_bytes, + change, + ); + let commits = plan + .steps + .iter() + .filter(|step| matches!(step, Step::Commit(_))) + .count(); + (plan.dropped.is_empty() && commits <= 1).then(|| Box::new(Execution::new(plan))) + } + + /// The task that writes `layout` as a new segment, if it fits. + fn write_segment(&self, layout: Arc>, trigger: Trigger) -> Option> { + let change = Change { + replace: Vec::new(), + remove: Vec::new(), + blobs: vec![Blob { + kind: SEGMENT_BLOB, + source: layout.clone(), + }], + }; + let execution = self.plan(change)?; + Some(Task::Write { + execution, + done: Done::Segment(layout, trigger), + }) + } + + /// A write finished: its commit is the file's newest. + fn finish(&mut self, execution: Box>, done: Done<'a>) -> Event { + if let Some(last) = execution.last() { + self.committed = Some(last); + } + drop(execution); + match done { + Done::Segment(layout, trigger) => { + let (records, bytes) = (layout.records(), layout.bytes()); + self.stats.deltas += 1; + self.stats.delta_bytes += bytes; + self.segments.push(Segment::Laid(layout)); + Event::Segment { + records, + bytes, + trigger, + } + } + Done::Merge(layout, Merging::Pair(_)) => { + self.stats.pairs += 1; + self.segments.push(Segment::Laid(layout)); + Event::MergeCommitted { full: false } + } + Done::Merge(layout, Merging::Full) => { + self.stats.merges += 1; + self.merged_since_wait = !self.waiting.is_empty(); + self.segments = vec![Segment::Laid(layout)]; + self.used.clear(); + Event::MergeCommitted { full: true } + } + } + } + + /// Carry the work forward until `clock` passes `deadline`, or a write + /// queued its piece (`advance` carries a plan out a piece at a time on + /// the device, `None` while it cannot). Answers what it did to report. + pub fn step( + &mut self, + clock: &mut dyn FnMut() -> u64, + deadline: u64, + entries: &mut dyn Entries, + advance: &mut dyn FnMut(&mut Execution<'a>) -> Option>, + ) -> Result, String> { + let mut events = Vec::new(); + if self.failed { + return Ok(events); + } + if self.idle() { + events.extend(self.begin(clock(), entries)); + } + loop { + self.task = match core::mem::replace(&mut self.task, Task::Idle) { + Task::Idle => break, + Task::Delta(mut delta, trigger) => { + if !delta.step(STEP_WORK) { + Task::Delta(delta, trigger) + } else { + match delta.finish() { + Some(layout) => { + let layout = Arc::new(layout); + match self.write_segment(layout.clone(), trigger) { + Some(task) => task, + None => { + events.push(Event::Waiting { + records: layout.records(), + }); + self.waiting.push(layout); + Task::Idle + } + } + } + None => Task::Idle, + } + } + } + Task::Merge(mut merge, merging) => { + let merge_bound = merge.bound(); + if !merge.step(STEP_WORK) { + Task::Merge(merge, merging) + } else { + let Merged { + layout, + evicted, + expired, + invalid, + } = merge.finish(); + events.push(Event::Merged { + full: matches!(merging, Merging::Full), + records: layout.records(), + bytes: layout.bytes(), + bound: merge_bound, + evicted, + expired, + invalid, + }); + let layout = Arc::new(layout); + // A full merge replaces every segment and list; a + // pair, the two it merged. + let (replace, remove) = match merging { + Merging::Full => (vec![SEGMENT_BLOB, USED_BLOB], Vec::new()), + Merging::Pair(offsets) => (Vec::new(), offsets.to_vec()), + }; + let change = Change { + replace, + remove, + blobs: vec![Blob { + kind: SEGMENT_BLOB, + source: layout.clone(), + }], + }; + match self.plan(change) { + Some(execution) => Task::Write { + execution, + done: Done::Merge(layout, merging), + }, + // A pair's records grew past the room for both: + // memory holds them merged, the file as they + // were, and no pair merges again this boot. + None if matches!(merging, Merging::Pair(_)) => { + self.segments.push(Segment::Laid(layout)); + Task::Idle + } + None => { + self.failed = true; + return Err(String::from( + "a merged segment found no room beside the file's content", + )); + } + } + } + } + Task::Write { + mut execution, + done, + } => { + match advance(&mut execution) { + Some(Ok(true)) => events.push(self.finish(execution, done)), + Some(Err(error)) => { + self.failed = true; + return Err(error); + } + None | Some(Ok(false)) => self.task = Task::Write { execution, done }, + } + break; + } + }; + if clock() >= deadline { + break; + } + } + Ok(events) + } + + /// At a stop: finish a new segment's write in flight (`run` carries a + /// plan out whole), leave a merge not yet committed, then write a new + /// segment of what is left with the waiting ones, while slots last, and + /// this boot's used-key list. + pub fn stop( + &mut self, + entries: &mut dyn Entries, + run: &mut dyn FnMut(&mut Execution<'a>) -> Result<(), String>, + ) -> Result { + let mut stopped = Stopped::default(); + if self.failed { + return Err(String::from("the writer failed earlier")); + } + let mut layouts: Vec> = Vec::new(); + match core::mem::replace(&mut self.task, Task::Idle) { + Task::Write { + mut execution, + done: done @ Done::Segment(..), + } => { + run(&mut execution)?; + self.finish(execution, done); + } + Task::Delta(delta, _) => layouts.extend(delta.finish()), + Task::Merge(..) | Task::Write { .. } => stopped.merge_left = true, + Task::Idle => {} + } + let added = entries.take_added(); + self.note_added(&added); + layouts.extend(Delta::new(self.translator, added).finish()); + let mut change = Change::default(); + let room = MAX_SEGMENTS.saturating_sub(self.count(SEGMENT_BLOB)); + let waiting = core::mem::take(&mut self.waiting); + let mut segments = waiting + .iter() + .map(|layout| Blob { + kind: SEGMENT_BLOB, + source: layout.clone(), + }) + .chain( + layouts + .into_iter() + .map(|layout| Blob::new(SEGMENT_BLOB, layout)), + ); + for blob in segments.by_ref().take(room) { + change.blobs.push(blob); + } + stopped.lost = segments.count(); + stopped.records = self.added_keys.len().min(MAX_USED_KEYS + 1); + if self.count(USED_BLOB) < MAX_USED_LISTS { + let list = self.used_list(entries.found_keys()); + change.blobs.push(Blob::new(USED_BLOB, list)); + } + stopped.bytes = change.blobs.iter().map(Blob::length).sum(); + let mut execution = self + .plan(change) + .ok_or_else(|| String::from("the stop's blobs found no room in the file"))?; + run(&mut execution)?; + if let Some(last) = execution.last() { + self.committed = Some(last); + } + stopped.segments = self.count(SEGMENT_BLOB); + stopped.lists = self.count(USED_BLOB); + Ok(stopped) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/stela-engine/src/translations/writer/tests.rs b/crates/stela-engine/src/translations/writer/tests.rs new file mode 100644 index 0000000000..12228f735d --- /dev/null +++ b/crates/stela-engine/src/translations/writer/tests.rs @@ -0,0 +1,499 @@ +use super::*; +use crate::translations::translator_id; +use alloc::collections::BTreeSet; +use stela_formats::journal::Target; + +/// Counter ticks per second, and the steps a second of a boot gives. +const HZ: u64 = 1000; +const STEPS_PER_SECOND: u64 = 10; + +/// A pack file in memory whose writes may be cut after a number of bytes, +/// as a power loss cuts a disk's: the cut write lands only partly. +struct Disk { + bytes: Vec, + /// Bytes still written before the cut; `None` for no cut. + left: Option, + cut: bool, + written: u64, + /// A commit slot was written since the last flush, and the page keys + /// each commit left, once durable. + slot: bool, + contents: Vec>, +} + +impl Disk { + fn new(size: u64) -> Self { + Self { + bytes: vec![0; size as usize], + left: None, + cut: false, + written: 0, + slot: false, + contents: Vec::new(), + } + } +} + +impl Target for Disk { + type Error = String; + fn write_at(&mut self, offset: u64, bytes: &[u8]) -> Result { + let take = match self.left { + Some(left) => (left as usize).min(bytes.len()), + None => bytes.len(), + }; + let at = offset as usize; + self.bytes[at..at + take].copy_from_slice(&bytes[..take]); + self.written += take as u64; + self.slot |= offset < DATA_START; + if let Some(left) = &mut self.left { + *left -= take as u64; + if take < bytes.len() { + self.cut = true; + return Err(String::from("cut")); + } + } + Ok(true) + } + fn flush(&mut self) -> Result { + if self.cut { + return Err(String::from("cut")); + } + if core::mem::take(&mut self.slot) { + let found = keys(&self.bytes); + self.contents.push(found); + } + Ok(true) + } +} + +/// What a boot's store hands the writer: entries added, keys found. Like +/// the store, it keeps at most `bound` entries between takes and counts +/// those it refused. +struct Boot { + added: BTreeMap, + found: Vec, + next: u32, + total: u64, + bound: usize, + unkept: u64, +} + +impl Boot { + /// A boot whose pages are numbered from `seed` millions, that found + /// every record in `found`. + fn new(seed: u32, found: Vec) -> Self { + Self { + added: BTreeMap::new(), + found, + next: seed * 1_000_000, + total: 0, + bound: usize::MAX, + unkept: 0, + } + } + + /// Add `count` entries of new pages: the keys of those kept. + fn add(&mut self, count: u32) -> Vec { + let translator = translator_id(); + let mut kept = Vec::new(); + for _ in 0..count { + self.next += 1; + if self.added.len() >= self.bound { + self.unkept += 1; + continue; + } + let key = Digest::of(&self.next.to_le_bytes()); + self.added.insert(key, Record::new(translator, key)); + self.total += 1; + kept.push(key); + } + kept + } +} + +impl Entries for Boot { + fn take_added(&mut self) -> BTreeMap { + core::mem::take(&mut self.added) + } + fn found_keys(&mut self) -> Vec { + self.found.clone() + } + fn added(&mut self) -> u64 { + self.total + } + fn pressed(&mut self) -> bool { + !self.added.is_empty() && self.added.len().saturating_mul(2) >= self.bound + } +} + +/// The pack file as a boot's loader reads it: the newest commit, whose +/// blobs must read back whole, and its segments and lists. +fn load(disk: &[u8], limit: u64) -> File<'static> { + let translator = translator_id(); + let size = disk.len() as u64; + let committed = journal::candidates(&disk[..DATA_START as usize], JOURNAL_DOMAIN, size) + .into_iter() + .next(); + let mut segments = Vec::new(); + let mut used = Vec::new(); + if let Some(commit) = &committed { + let blobs = journal::read_entries(commit, |offset, into| { + let at = offset as usize; + into.copy_from_slice(disk.get(at..at + into.len())?); + Some(()) + }) + .expect("the newest commit's blobs read back whole"); + for (kind, bytes) in blobs { + let bytes: &'static [u8] = Vec::leak(bytes); + match kind { + SEGMENT_BLOB => segments.push(Pack::parse(bytes, &translator).unwrap()), + USED_BLOB => used.push(UsedKeys::parse(bytes, &translator).unwrap()), + _ => panic!("an unknown blob"), + } + } + } + File { + translator, + limit, + file_bytes: size, + committed, + segments, + used, + partial: false, + } +} + +/// The page keys the file's newest commit holds. +fn keys(disk: &[u8]) -> BTreeSet { + load(disk, u64::MAX) + .segments + .iter() + .flat_map(|pack| pack.iter().map(|(key, _)| key).collect::>()) + .collect() +} + +/// A writer's boot: its clock, the store and the disk. +struct Run<'a> { + writer: Writer<'a>, + boot: Boot, + now: u64, + events: Vec, +} + +impl<'a> Run<'a> { + /// A boot over `file` whose pages are numbered from `seed` millions, + /// that uses every record the file holds. + fn new(file: File<'a>, seed: u32) -> Self { + let found = file + .segments + .iter() + .flat_map(|pack| pack.iter().map(|(key, _)| key).collect::>()) + .collect(); + Self { + writer: Writer::new(file, HZ), + boot: Boot::new(seed, found), + now: 0, + events: Vec::new(), + } + } + + /// Step for `seconds` of the guest's time. + fn run(&mut self, disk: &mut Disk, seconds: u64) -> Result<(), String> { + for _ in 0..seconds * STEPS_PER_SECOND { + let now = self.now; + let events = + self.writer + .step(&mut || now, now + 1, &mut self.boot, &mut |execution| { + Some(execution.advance(disk, PIECE_BYTES)) + })?; + self.events.extend(events); + self.now += HZ / STEPS_PER_SECOND; + } + Ok(()) + } + + /// Step for `seconds` while the device takes no write. + fn stall(&mut self, seconds: u64) { + for _ in 0..seconds * STEPS_PER_SECOND { + let now = self.now; + let events = self + .writer + .step(&mut || now, now + 1, &mut self.boot, &mut |_| None) + .unwrap(); + self.events.extend(events); + self.now += HZ / STEPS_PER_SECOND; + } + } + + /// The triggers of the segments committed so far. + fn triggers(&self) -> Vec { + self.events + .iter() + .filter_map(|event| match event { + Event::Segment { trigger, .. } => Some(*trigger), + _ => None, + }) + .collect() + } + + fn stop(&mut self, disk: &mut Disk) -> Result { + self.writer.stop(&mut self.boot, &mut |execution| { + while !execution.advance(disk, PIECE_BYTES)? {} + Ok(()) + }) + } +} + +const FILE_BYTES: u64 = DATA_START + 4096 * journal::ALIGN; + +/// A boot `seed` of entries added in bursts, each followed by its +/// seconds, and stopped: the keys it added. +fn boot_of( + disk: &mut Disk, + seed: u32, + bursts: &[(u64, u32)], +) -> Result<(BTreeSet, Stopped), String> { + let file = load(&disk.bytes.clone(), u64::MAX); + let mut run = Run::new(file, seed); + let mut added = BTreeSet::new(); + for &(seconds, count) in bursts { + added.extend(run.boot.add(count)); + run.run(disk, seconds)?; + } + let stopped = run.stop(disk)?; + Ok((added, stopped)) +} + +#[test] +fn boots_commit_their_segments_and_lists_and_a_later_boot_merges_them() { + let mut disk = Disk::new(FILE_BYTES); + let mut all = BTreeSet::new(); + for boot in 0..5 { + let bursts = [(30, 200), (100, 50), (200, 10)]; + let (added, stopped) = boot_of(&mut disk, boot + 1, &bursts).unwrap(); + all.extend(added); + assert_eq!(keys(&disk.bytes), all, "boot {boot}"); + assert!(stopped.segments < MAX_SEGMENTS && stopped.lists <= MAX_USED_LISTS); + assert!(!stopped.merge_left); + } + // A merge ran once segments or lists reached MERGE_AT: the file holds + // fewer than five boots wrote. + let file = load(&disk.bytes, u64::MAX); + assert!(file.segments.len() < 5 * 3, "{}", file.segments.len()); + assert!(file.used.len() < 5); +} + +#[test] +fn a_long_session_keeps_a_free_slot_and_commits_every_entry_in_bounded_time() { + let mut disk = Disk::new(FILE_BYTES); + let mut run = Run::new(load(&disk.bytes.clone(), u64::MAX), 1); + let mut pending: Vec<(u64, Vec)> = Vec::new(); + // Three days of a burst every ten minutes. + for _ in 0..3 * 24 * 6 { + pending.push((run.now, run.boot.add(20))); + run.run(&mut disk, 600).unwrap(); + let committed = keys(&disk.bytes); + let file = load(&disk.bytes, u64::MAX); + assert!( + file.segments.len() < MAX_SEGMENTS, + "{}", + file.segments.len() + ); + // Whatever was added a last delay and a merge ago is in the file. + let bound = run.now.saturating_sub(HZ * (LAST_DELTA_SECONDS + 600)); + for (at, added) in &pending { + if *at < bound { + assert!( + added.iter().all(|key| committed.contains(key)), + "added at {at}" + ); + } + } + } + let stats = run.writer.stats(); + assert!(stats.pairs + stats.merges > 3, "{stats:?}"); + run.stop(&mut disk).unwrap(); + let committed = keys(&disk.bytes); + assert!( + pending + .iter() + .all(|(_, added)| added.iter().all(|key| committed.contains(key))) + ); +} + +#[test] +fn a_stop_finishes_a_segment_in_flight_and_leaves_a_merge() { + // A segment's write queued and not yet done: the stop finishes it. + let mut disk = Disk::new(FILE_BYTES); + let mut run = Run::new(load(&disk.bytes.clone(), u64::MAX), 1); + let added = run.boot.add(5000); + run.stall(FIRST_DELTA_SECONDS); + assert!(!run.writer.idle()); + assert!(keys(&disk.bytes).is_empty()); + let stopped = run.stop(&mut disk).unwrap(); + assert!(!stopped.merge_left); + assert_eq!(keys(&disk.bytes), added.into_iter().collect()); + assert_eq!(stopped.segments, 1); + + // A merge in progress at the stop: the file keeps its segments, and + // the stop adds its own beside them. + let mut disk = Disk::new(FILE_BYTES); + let mut all = BTreeSet::new(); + for seed in 0..MERGE_AT as u32 { + all.extend(boot_of(&mut disk, seed + 1, &[(1, 100)]).unwrap().0); + } + // The boot's merge waits for its first segment's delay; then its write + // never lands. + let mut run = Run::new(load(&disk.bytes.clone(), u64::MAX), 9); + run.stall(FIRST_DELTA_SECONDS + 1); + assert!(!run.writer.idle()); + assert!( + run.events + .iter() + .any(|event| matches!(event, Event::Merged { full: true, .. })), + "{:?}", + run.events + ); + all.extend(run.boot.add(30)); + let before = load(&disk.bytes, u64::MAX).segments.len(); + let stopped = run.stop(&mut disk).unwrap(); + assert!(stopped.merge_left); + assert_eq!(stopped.segments, before + 1); + assert_eq!(keys(&disk.bytes), all); +} + +/// Records whose segment takes about `blocks` journal blocks. +fn records_for(blocks: u64) -> u32 { + let translator = translator_id(); + let sample: Vec<(Digest, crate::translations::pack::Piece)> = (0u32..100) + .map(|n| { + let key = Digest::of(&n.to_le_bytes()); + let piece = + crate::translations::pack::Piece::New(Record::new(translator, key).encode()); + (key, piece) + }) + .collect(); + let per_record = Layout::new(&translator, sample).bytes() / 100; + (blocks * journal::ALIGN / per_record) as u32 +} + +#[test] +fn a_segment_without_room_waits_for_a_merge_and_one_larger_than_the_file_is_left_out() { + let mut disk = Disk::new(DATA_START + 64 * journal::ALIGN); + let mut run = Run::new(load(&disk.bytes.clone(), u64::MAX), 1); + let first: BTreeSet = run.boot.add(records_for(10)).into_iter().collect(); + run.run(&mut disk, FIRST_DELTA_SECONDS + 1).unwrap(); + assert_eq!(keys(&disk.bytes), first); + // More than the room beside the first, and than any room a merge + // leaves beside its segment. + let second = run.boot.add(records_for(60)); + run.run(&mut disk, 2 * FIRST_DELTA_SECONDS + 10).unwrap(); + let position = |wanted: fn(&Event) -> bool| run.events.iter().position(wanted); + let waiting = position(|event| matches!(event, Event::Waiting { .. })).unwrap(); + let merged = position(|event| *event == Event::MergeCommitted { full: true }).unwrap(); + let lost = position(|event| matches!(event, Event::Lost { .. })).unwrap(); + assert!(waiting < merged && merged < lost, "{:?}", run.events); + // The writer goes on: the next segment commits. + let third: BTreeSet = run.boot.add(20).into_iter().collect(); + run.run(&mut disk, 4 * FIRST_DELTA_SECONDS + 10).unwrap(); + let committed = keys(&disk.bytes); + assert!(committed.is_superset(&first) && committed.is_superset(&third)); + assert!(second.iter().all(|key| !committed.contains(key))); + run.stop(&mut disk).unwrap(); +} + +/// Boots of a writer, the same each run: a first with two segments, three +/// short ones whose lists bring a merge, and one more. +fn scenario(disk: &mut Disk) -> Result<(), String> { + let boots: [&[(u64, u32)]; 5] = [ + &[(70, 300), (130, 40)], + &[(5, 20)], + &[(5, 20)], + &[(5, 20)], + &[(90, 50)], + ]; + for (seed, bursts) in boots.into_iter().enumerate() { + boot_of(disk, seed as u32 + 1, bursts)?; + } + Ok(()) +} + +#[test] +fn a_cut_at_any_write_leaves_the_content_of_a_whole_commit() { + const SIZE: u64 = DATA_START + 512 * journal::ALIGN; + let mut disk = Disk::new(SIZE); + scenario(&mut disk).unwrap(); + let contents = core::mem::take(&mut disk.contents); + assert!(contents.len() > 8, "{}", contents.len()); + assert!( + contents + .iter() + .any(|content| content.len() < contents.last().unwrap().len()), + "commits before the last hold less" + ); + let total = disk.written; + let step = (total / 250).max(1); + let mut cut = 0; + while cut <= total { + let mut disk = Disk::new(SIZE); + disk.left = Some(cut); + let _ = scenario(&mut disk); + // The newest commit reads back whole (`load` checks it) and holds + // what one of the uncut run's commits held. + let found = keys(&disk.bytes); + assert!( + found.is_empty() || contents.contains(&found), + "a cut after {cut} of {total} bytes left content no commit held" + ); + cut += step; + } +} + +#[test] +fn entries_added_faster_than_their_bound_go_to_segments_before_any_is_refused() { + // A boot's kernel adds entries for its first seconds far faster than the + // bound the store keeps between segments: the writer takes them once + // they reach half of it, so the store refuses none, and the next boot + // finds all of them. + let mut disk = Disk::new(FILE_BYTES); + let mut run = Run::new(load(&disk.bytes.clone(), u64::MAX), 1); + run.boot.bound = 1000; + let mut added = BTreeSet::new(); + for _ in 0..FIRST_DELTA_SECONDS { + added.extend(run.boot.add(400)); + run.run(&mut disk, 1).unwrap(); + } + assert_eq!(run.boot.unkept, 0); + assert!(run.writer.stats().pressed >= 5, "{:?}", run.writer.stats()); + assert!(run.triggers().contains(&Trigger::Pressed)); + run.stop(&mut disk).unwrap(); + assert_eq!(keys(&disk.bytes), added); + assert_eq!(added.len() as u64, 400 * FIRST_DELTA_SECONDS); + // The pressed segments were merged as they came: fewer than the slots. + assert!(load(&disk.bytes, u64::MAX).segments.len() < MAX_SEGMENTS); +} + +#[test] +fn the_first_segment_comes_when_translation_goes_quiet_or_at_its_delay() { + // A burst, then quiet: the first segment commits a few seconds after. + let mut disk = Disk::new(FILE_BYTES); + let mut run = Run::new(load(&disk.bytes.clone(), u64::MAX), 1); + let burst: BTreeSet = run.boot.add(3000).into_iter().collect(); + run.run(&mut disk, QUIET_SECONDS + 2).unwrap(); + assert_eq!(run.triggers(), [Trigger::Quiet]); + assert_eq!(keys(&disk.bytes), burst); + run.stop(&mut disk).unwrap(); + + // Translation that never goes quiet: the first segment at its delay. + let mut disk = Disk::new(FILE_BYTES); + let mut run = Run::new(load(&disk.bytes.clone(), u64::MAX), 1); + for second in 0..FIRST_DELTA_SECONDS + 2 { + run.boot.add(2 * QUIET_RATE as u32); + run.run(&mut disk, 1).unwrap(); + if second + 1 < FIRST_DELTA_SECONDS { + assert!(run.triggers().is_empty(), "at {second} s"); + } + } + assert_eq!(run.triggers(), [Trigger::Due]); + run.stop(&mut disk).unwrap(); +}