From ff5d34c7eaef08c8128caa1402b2c43c9ec5b577 Mon Sep 17 00:00:00 2001 From: Tyler Smith <74526874+tylertms@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:46:41 -0500 Subject: [PATCH] perf(engine): keep the lower halves of 32 recent contexts instead of 8 --- crates/stela-engine/src/machine/mmu/shadow.rs | 33 +++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/stela-engine/src/machine/mmu/shadow.rs b/crates/stela-engine/src/machine/mmu/shadow.rs index 99fd8f109f..c75acc3a7d 100644 --- a/crates/stela-engine/src/machine/mmu/shadow.rs +++ b/crates/stela-engine/src/machine/mmu/shadow.rs @@ -154,8 +154,12 @@ pub struct Kept { switches: u64, } -/// The contexts whose lower halves [`Kept`] holds at most. -pub const KEPT: usize = 8; +/// The contexts whose lower halves [`Kept`] holds at most. A replaced half +/// frees no frames (they return only when the lower half is emptied), and +/// refilling a context that comes back allocates its tables again, so a +/// replacement costs frames as well as fills: a desktop session rotates +/// among dozens of processes, which eight halves missed half the time. +pub const KEPT: usize = 32; /// One context's kept lower half. #[derive(Debug, Clone, PartialEq, Eq)] @@ -473,6 +477,31 @@ mod tests { assert!(kept.is_empty()); } + #[test] + fn a_rotation_of_many_contexts_finds_every_half() { + // Two dozen processes taking turns, as a desktop session's do, + // each find their half again after the first round. + let mut kept = Kept::new(); + let key = |n: u64| (n << 12, 0); + const CONTEXTS: u64 = 24; + const { assert!(CONTEXTS as usize <= KEPT) }; + let mut found = 0; + for turn in 0..CONTEXTS * 4 { + let (from, to) = (turn % CONTEXTS, (turn + 1) % CONTEXTS); + let half = kept.switch( + key(from), + alloc::vec![(0x1000, 0, from + 1)], + Extents::new(), + key(to), + ); + if let Some(half) = half { + assert_eq!(half.entries, [(0x1000, 0, to + 1)]); + found += 1; + } + } + assert_eq!(found, CONTEXTS * 4 - (CONTEXTS - 1)); + } + #[test] fn switching_to_the_oldest_kept_half_reuses_it_when_full() { let mut kept = Kept::new();