From 01ed597e5d8bcecceaab4d4c550930a08e12236c Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 29 Oct 2026 15:48:56 -0500 Subject: [PATCH 1/4] Residents' result bodies stay in RAM until the one memory owner sheds: RESULTS_RESIDENT_CHARS is gone RAM decides, not a number (Joel, 2026-10-29: no hand-rigged constants). The 1 << 20-char cap per mind evicted at receipt, settlement and restore; now nothing evicts there. - One MemoryReporter, `mind_results` (persona_workspace/mind_results_reporter.rs), accounts every resident mind's result bodies in BYTES (live cycles and private mind cycles; a memory reached twice counts once). Priority Background (a cache: every shed body is saved to its handle). min = what no shed may move; preferred = max = what it holds. - shed_load sheds the host's overrun past the monitor's own gate for that priority (used - pressure_gate * total, from the published PressureSnapshot), oldest received first across minds (new `received_ms` on each record), down to that allocation exactly. - Never moved: a mind's newest result, an unsaved one, or one whose saved output does not resolve or is missing (typed `LastCopy`, probed `wm.results.last_copy_kept`). - `evict_resident_results_over(bytes, saved)` (working_memory/residency.rs) is the one eviction verb; only the reporter calls it in production. No hysteresis: the owner decides when. - Registered once at boot beside the persona registry (persona_registry_modules.rs). Tests: never evicted at receipt however large the ring; restore keeps every body; the shed takes the oldest across two minds to the allocation and keeps newest, unsaved and unreloadable bodies, with stored_chars + handle kept; report sums bytes across minds; the shed target is the overrun past the monitor's gate. Tests that only asserted the constant's bursts were replaced. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/context_streams/tests.rs | 2 +- .../src/cognition/persona_workspace.rs | 2 + .../default_workspace_capacity.rs | 5 +- .../mind_results_reporter.rs | 256 ++++++++++++++++++ .../root_acting_workspace.rs | 10 +- .../src/cognition/persona_workspace/tests.rs | 1 + .../tests/mind_results_reporter.rs | 153 +++++++++++ ..._told_when_her_hands_move_and_only_then.rs | 3 +- .../src/cognition/working_memory.rs | 5 +- .../cognition/working_memory/action_log.rs | 69 +++-- .../cognition/working_memory/continuity.rs | 7 +- .../src/cognition/working_memory/ledger.rs | 19 +- .../cognition/working_memory/perception.rs | 46 +--- .../src/cognition/working_memory/residency.rs | 77 ++++++ .../working_memory/tests/action_log.rs | 9 +- .../cognition/working_memory/tests/custody.rs | 83 +++--- .../src/cognition/working_memory/tests/mod.rs | 10 + .../working_memory/tests/provenance.rs | 5 +- .../cognition/working_memory/tests/trail.rs | 32 +-- .../start_server/persona_registry_modules.rs | 6 + 20 files changed, 637 insertions(+), 163 deletions(-) create mode 100644 core/continuum-cognition/src/cognition/persona_workspace/mind_results_reporter.rs create mode 100644 core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs create mode 100644 core/continuum-cognition/src/cognition/working_memory/residency.rs diff --git a/core/continuum-cognition/src/cognition/context_streams/tests.rs b/core/continuum-cognition/src/cognition/context_streams/tests.rs index 5eabe5b129..c1953ce6b6 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tests.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tests.rs @@ -96,7 +96,7 @@ fn an_evicted_result_is_still_seen_whole_through_its_stored_level() { memory.record_receipt_typed(&[], "the newest stays resident", None, pin.retain(persona, "the newest stays resident")); let (before, _) = memory.action_renderings(); let resident_whole = before.first().map(|act| act.1.clone()).expect("test: the first act"); - memory.evict_resident_results_over(1); + memory.evict_resident_results_over(1, &|_| true); let (acts, _) = memory.action_renderings(); let (seq, full, _, pointer, stored) = acts.first().cloned().expect("test: the first act"); let (chars, _) = stored.expect("evicted to its handle and priced"); diff --git a/core/continuum-cognition/src/cognition/persona_workspace.rs b/core/continuum-cognition/src/cognition/persona_workspace.rs index 57658e32a1..ece912881f 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace.rs @@ -58,4 +58,6 @@ pub use acting_hands::*; mod root_acting_workspace; pub use root_acting_workspace::*; mod own_speech_persisted; +mod mind_results_reporter; +pub use mind_results_reporter::MindResultsReporter; pub(crate) use own_speech_persisted::*; diff --git a/core/continuum-cognition/src/cognition/persona_workspace/default_workspace_capacity.rs b/core/continuum-cognition/src/cognition/persona_workspace/default_workspace_capacity.rs index 6ed4d6b6c0..7da34b6291 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/default_workspace_capacity.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/default_workspace_capacity.rs @@ -653,8 +653,9 @@ pub struct PersonaWorkspaceRegistry { /// crosses between her public and private turns except what she publishes. It is never in /// `cycles`, so the volatile checkpoint never writes it to disk in plaintext (until her /// sealed store exists, a restart forgets her private scratchpad, which is the honest cost). - /// Lock order: `cycles`, then `templates`, then `mind_cycles`. - pub(super) mind_cycles: Mutex>>, + /// Lock order: `cycles`, then `templates`, then `mind_cycles`. Its working memory is held + /// beside it so the memory owner accounts and sheds her private results too. + pub(super) mind_cycles: Mutex>, } pub(super) struct ResidentWorkspace { diff --git a/core/continuum-cognition/src/cognition/persona_workspace/mind_results_reporter.rs b/core/continuum-cognition/src/cognition/persona_workspace/mind_results_reporter.rs new file mode 100644 index 0000000000..46f121a7a6 --- /dev/null +++ b/core/continuum-cognition/src/cognition/persona_workspace/mind_results_reporter.rs @@ -0,0 +1,256 @@ +//! The one memory owner's view of every mind's resident result bodies. +//! +//! A result's body stays in RAM until the memory pressure monitor says shed: RAM decides, not +//! a number (Joel, 2026-10-29; it replaced `RESULTS_RESIDENT_CHARS = 1 << 20`, a cap per mind +//! at receipt). This reporter is the only thing that moves a body to its handle in production +//! (`WorkingMemory::evict_resident_results_over`). It sheds oldest-first across every resident +//! mind, public and private, and never moves the newest result of a mind or a body whose saved +//! output is not there to reload (the last copy). +//! +//! Accounting is BYTES of resident bodies (`String::len`), never characters: characters are +//! the view's price (`stored_chars`). Each record owns its body (no shared backing), so the sum +//! over records is the RAM they hold; a working memory reached twice is counted once. + +use std::path::PathBuf; +use std::sync::Arc; + +use continuum_kernel::system_resources::{ + MemoryBudgetSpec, MemoryPriority, MemoryReporter, ModuleMemoryReport, PressureLevel, + PressureSnapshot, +}; +use tokio::sync::watch; +use uuid::Uuid; + +use super::PersonaWorkspaceRegistry; +use crate::cognition::working_memory::{Residency, WorkingMemory}; + +const NAME: &str = "mind_results"; + +/// A cache of state that can spill: every body it sheds is already saved whole to its handle +/// and reloads when her view grants it. That is `Background` ("caches, pre-computed data, idle +/// resources"), not `Interactive` (state a mind cannot work without: the newest result and the +/// last copies are that, and the shed never moves them). +const PRIORITY: MemoryPriority = MemoryPriority::Background; + +/// Why a body stays resident through a shed: it is the last copy of what she read. +#[derive(Debug)] +pub(crate) enum LastCopy { + /// The handle does not name an output this mind can resolve. + Unresolvable(std::io::Error), + /// The handle resolves, but its saved output is not there to reload. + Missing(PathBuf), +} + +impl std::fmt::Display for LastCopy { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Unresolvable(error) => write!(f, "handle does not resolve: {error}"), + Self::Missing(path) => write!(f, "saved output missing at {}", path.display()), + } + } +} + +/// Whether `persona`'s saved output for `handle` is there to reload, so its body may leave RAM. +pub(crate) fn saved_output(persona: Uuid, handle: &str) -> Result<(), LastCopy> { + let path = crate::cognition::tool_executor::spill::resolve(persona, handle) + .map_err(LastCopy::Unresolvable)?; + if path.is_file() { + Ok(()) + } else { + Err(LastCopy::Missing(path)) + } +} + +/// The resident minds the reporter accounts: `(persona, working memory)`, each memory once. +pub(crate) type Minds = Vec<(Uuid, Arc)>; + +impl PersonaWorkspaceRegistry { + /// Every resident mind's working memory: her live cycle's and her private mind cycle's. + /// Each lock is taken and released on its own, never nested. + pub(crate) fn resident_working_memories(&self) -> Minds { + let mut minds: Minds = self + .cycles + .lock() + .iter() + .map(|(id, entry)| (*id, Arc::clone(&entry.working_memory))) + .collect(); + minds.extend( + self.mind_cycles + .lock() + .iter() + .map(|(id, entry)| (*id, Arc::clone(&entry.working_memory))), + ); + let mut seen = std::collections::HashSet::new(); + minds.retain(|(_, memory)| seen.insert(Arc::as_ptr(memory))); + minds + } +} + +/// The bytes every mind's resident result bodies hold. +pub(crate) fn resident_bytes(minds: &Minds) -> u64 { + minds + .iter() + .map(|(_, memory)| memory.resident_result_bytes()) + .sum() +} + +/// What this consumer gives up: how far the host's used RAM stands past the line the monitor +/// declares this priority sheds at (`MemoryPriority::pressure_gate`). Both numbers are the +/// monitor's own; nothing here is a ratio of ours. `0` before the first poll (no total yet). +pub(crate) fn over_gate(snapshot: &PressureSnapshot) -> u64 { + let used = snapshot + .total_bytes + .saturating_sub(snapshot.available_bytes); + let gate = (snapshot.total_bytes as f64 * PRIORITY.pressure_gate()) as u64; + used.saturating_sub(gate) +} + +/// Per mind, the bytes to keep resident so the total comes down to `allocation`, moving the +/// oldest bodies across every mind first (`None`: leave that mind untouched). Within a mind +/// the oldest received are the lowest `seq`, so each budget moves exactly that mind's chosen +/// oldest bodies through `evict_resident_results_over`. +pub(crate) fn plan_shed(minds: &[Residency], allocation: u64) -> Vec> { + let total: u64 = minds.iter().map(|mind| mind.resident_bytes).sum(); + let mut freed = vec![0u64; minds.len()]; + if total > allocation { + let mut candidates: Vec<(Option, u64, usize, u64)> = minds + .iter() + .enumerate() + .flat_map(|(index, mind)| { + mind.evictable + .iter() + .map(move |r| (r.received_ms, r.seq, index, r.bytes)) + }) + .collect(); + candidates.sort_unstable(); + let mut need = total - allocation; + for (_, _, index, bytes) in candidates { + if need == 0 { + break; + } + freed[index] += bytes; + need = need.saturating_sub(bytes); + } + } + minds + .iter() + .zip(freed) + .map(|(mind, freed)| (freed > 0).then(|| mind.resident_bytes - freed)) + .collect() +} + +/// Shed every mind's resident bodies down to `allocation` bytes in total, oldest first. +/// `saved` vouches that a persona's handle has its output there to reload. +pub(crate) fn shed_to(minds: &Minds, allocation: u64, saved: &dyn Fn(Uuid, &str) -> bool) { + let residencies: Vec = minds + .iter() + .map(|(persona, memory)| memory.residency(&|handle| saved(*persona, handle))) + .collect(); + for ((persona, memory), budget) in minds.iter().zip(plan_shed(&residencies, allocation)) { + if let Some(budget) = budget { + memory.evict_resident_results_over(budget, &|handle| saved(*persona, handle)); + } + } +} + +/// `saved` for production: a body whose output is not there stays, and says why. +fn vouched(persona: Uuid, handle: &str) -> bool { + match saved_output(persona, handle) { + Ok(()) => true, + Err(last_copy) => { + continuum_base::probe!( + class = "wm.results.last_copy_kept", + persona_id = %persona, + handle = %handle, + reason = %last_copy, + "a resident result stays through a shed: its saved output is not there to reload" + ); + false + } + } +} + +/// The `MemoryReporter` for every mind's resident result bodies. Registered once at boot +/// beside the persona registry (`persona_registry_modules`). +pub struct MindResultsReporter { + registry: Arc, + /// The monitor's published snapshot: `shed_load` runs right after it is published, so this + /// is the poll that decided to shed. + pressure: watch::Receiver, +} + +impl MindResultsReporter { + pub fn new( + registry: Arc, + pressure: watch::Receiver, + ) -> Self { + Self { registry, pressure } + } +} + +impl MemoryReporter for MindResultsReporter { + fn name(&self) -> &'static str { + NAME + } + + /// It wants to keep everything it holds (`preferred = max = resident`); its floor is what + /// no shed may move (each mind's newest result and every last copy). + fn budget(&self) -> MemoryBudgetSpec { + let minds = self.registry.resident_working_memories(); + let (resident, pinned) = + minds + .iter() + .fold((0u64, 0u64), |(resident, pinned), (persona, memory)| { + let residency = + memory.residency(&|handle| saved_output(*persona, handle).is_ok()); + ( + resident + residency.resident_bytes, + pinned + residency.pinned_bytes, + ) + }); + MemoryBudgetSpec { + name: NAME.to_string(), + priority: PRIORITY, + min_bytes: pinned, + preferred_bytes: resident, + max_bytes: resident, + } + } + + fn report(&self) -> ModuleMemoryReport { + let minds = self.registry.resident_working_memories(); + let bytes = resident_bytes(&minds); + ModuleMemoryReport { + name: NAME.to_string(), + bytes, + detail: format!( + "{} minds, {} KiB of resident result bodies", + minds.len(), + bytes / 1024 + ), + can_shed: true, + } + } + + fn can_shed(&self) -> bool { + true + } + + fn shed_load(&self, level: PressureLevel) { + let over = over_gate(&self.pressure.borrow()); + if over == 0 { + return; + } + let minds = self.registry.resident_working_memories(); + let before = resident_bytes(&minds); + shed_to(&minds, before.saturating_sub(over), &vouched); + continuum_base::probe!( + class = "wm.results.shed", + level = %level, + over_gate = %over, + before = %before, + after = %resident_bytes(&minds), + "the memory owner moved the oldest resident results to their handles" + ); + } +} diff --git a/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs b/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs index 052b4479a7..a08a874fdd 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/root_acting_workspace.rs @@ -169,22 +169,24 @@ impl PersonaWorkspaceRegistry { /// private turns at the next turn boundary. `None` when she has no live cycle or template. pub fn mind_cycle(&self, persona_id: &Uuid) -> Option> { let live = self.get(persona_id)?; - let cached = self.mind_cycles.lock().get(persona_id).cloned(); + let cached = self.mind_cycles.lock().get(persona_id).map(|entry| Arc::clone(&entry.cycle)); let mind = match cached { Some(mind) => mind, None => { let _assembly = self.assembly.lock(); // Bound to its own statement: a guard in an `if let` scrutinee would live into // the `else` and deadlock on the insert below (non-reentrant lock). - let built_meanwhile = self.mind_cycles.lock().get(persona_id).cloned(); + let built_meanwhile = self.mind_cycles.lock().get(persona_id).map(|entry| Arc::clone(&entry.cycle)); if let Some(mind) = built_meanwhile { mind } else { let mut cfg = self.templates.lock().get(persona_id)?.clone(); cfg.defer_recall = false; - let (cycle, _working_memory) = assemble_workspace_cycle(cfg, None, Capture::Withheld); + let (cycle, working_memory) = assemble_workspace_cycle(cfg, None, Capture::Withheld); let cycle = Arc::new(cycle); - self.mind_cycles.lock().insert(*persona_id, Arc::clone(&cycle)); + self.mind_cycles + .lock() + .insert(*persona_id, ResidentWorkspace { cycle: Arc::clone(&cycle), working_memory }); cycle } } diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests.rs index 9e657b1452..2219479f21 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests.rs @@ -15,6 +15,7 @@ use crate::cognition::recall_metadata::{RecallMetadata, RecallMetadataRegistry}; mod she_is_told_when_her_hands_move_and_only_then; +mod mind_results_reporter; mod final_checkpoint_drains_admitted_periodic_writer_before_ack; use final_checkpoint_drains_admitted_periodic_writer_before_ack::*; mod gated_grounding; diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs new file mode 100644 index 0000000000..e75ab51071 --- /dev/null +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs @@ -0,0 +1,153 @@ +#![cfg(test)] +use std::sync::Arc; + +use uuid::Uuid; + +use crate::ai::types::ResultCustody; +use crate::cognition::persona_workspace::mind_results_reporter::{ + over_gate, resident_bytes, shed_to, Minds, +}; +use crate::cognition::working_memory::WorkingMemory; + +/// A test body's size in bytes; production has no such number (the memory owner sheds). +const BODY: usize = 1_000; + +fn receipt(memory: &WorkingMemory, name: &str, custody: ResultCustody) { + memory.record_receipt_typed( + &[], + &format!("{name}{}", "b".repeat(BODY - name.len())), + None, + custody, + ); + // Distinct receipt times, so "oldest across minds" is the order they were received in. + std::thread::sleep(std::time::Duration::from_millis(2)); +} + +fn saved(handle: &str) -> ResultCustody { + ResultCustody::Whole { + handle: handle.into(), + } +} + +/// Which of a mind's results are resident, by handle (`unsaved` for none). +fn resident(memory: &WorkingMemory) -> Vec { + memory + .snapshot() + .actions + .iter() + .filter(|r| r.result.is_some()) + .map(|r| r.handle.clone().unwrap_or_else(|| "unsaved".into())) + .collect() +} + +// what this catches: a shed that moves the wrong bodies. It must take the OLDEST received +// across every mind (not each mind's oldest in turn), stop at the allocation, and never move a +// mind's newest result, an unsaved one, or one whose saved output is missing (the last copy). +// A moved body keeps its handle and its measured length, so her view still reloads its whole. +#[test] +fn the_shed_moves_the_oldest_across_minds_down_to_the_allocation_and_keeps_last_copies() { + let (a, b) = ( + Arc::new(WorkingMemory::new(8)), + Arc::new(WorkingMemory::new(8)), + ); + receipt(&a, "a1", saved("a1")); + receipt(&b, "b1", ResultCustody::Unsaved); + receipt(&b, "b2", saved("b2")); + receipt(&b, "b3", saved("missing")); + receipt(&a, "a2", saved("a2")); + receipt(&b, "b4", saved("b4")); + receipt(&a, "a3", saved("a3")); + let minds: Minds = vec![ + (Uuid::new_v4(), Arc::clone(&a)), + (Uuid::new_v4(), Arc::clone(&b)), + ]; + let vouched = |_: Uuid, handle: &str| handle != "missing"; + let total = resident_bytes(&minds); + assert_eq!(total, 7 * BODY as u64, "precondition: every body resident"); + + shed_to(&minds, total - 2 * BODY as u64, &vouched); + assert_eq!( + resident_bytes(&minds), + 5 * BODY as u64, + "exactly down to the allocation" + ); + assert_eq!(resident(&a), ["a2", "a3"], "a1 was the oldest received"); + assert_eq!( + resident(&b), + ["unsaved", "missing", "b4"], + "b2 was next, before a2, though a2 is a's oldest left" + ); + let moved = b + .snapshot() + .actions + .into_iter() + .find(|r| r.handle.as_deref() == Some("b2")) + .expect("test: b2 kept its record"); + assert_eq!( + moved.stored_chars, + Some(BODY), + "a moved body keeps its measured length" + ); + + shed_to(&minds, 0, &vouched); + assert_eq!(resident(&a), ["a3"], "a's newest stays"); + assert_eq!( + resident(&b), + ["unsaved", "missing", "b4"], + "unsaved, unreloadable and newest stay through any shed" + ); +} + +// what this catches: the memory owner reading a wrong total, so it sheds too little or too +// much. `report()` is the sum of resident body BYTES across every mind (not characters: a +// multi-byte body counts its bytes), and moves with every receipt and shed. +#[test] +fn report_sums_resident_bytes_across_minds() { + let (a, b) = ( + Arc::new(WorkingMemory::new(8)), + Arc::new(WorkingMemory::new(8)), + ); + let minds: Minds = vec![ + (Uuid::new_v4(), Arc::clone(&a)), + (Uuid::new_v4(), Arc::clone(&b)), + ]; + assert_eq!(resident_bytes(&minds), 0); + receipt(&a, "a1", saved("a1")); + receipt(&a, "a2", saved("a2")); + let wide = "é".repeat(BODY); + b.record_receipt_typed(&[], &wide, None, saved("b1")); + assert_eq!( + resident_bytes(&minds), + 2 * BODY as u64 + wide.len() as u64, + "bytes, not chars" + ); + assert_eq!( + resident_bytes(&minds), + a.resident_result_bytes() + b.resident_result_bytes() + ); +} + +// what this catches: a shed target of our own invention. The bytes shed are how far the host's +// used RAM stands past the monitor's own gate for this priority; nothing before the first poll. +#[test] +fn the_shed_target_is_the_hosts_overrun_past_the_monitors_gate() { + use continuum_kernel::system_resources::{MemoryPriority, PressureSnapshot}; + assert_eq!( + over_gate(&PressureSnapshot::default()), + 0, + "no poll yet: nothing to shed" + ); + let total = 100 * 1024 * 1024 * 1024u64; + let gate = (total as f64 * MemoryPriority::Background.pressure_gate()) as u64; + let snapshot = |used: u64| PressureSnapshot { + total_bytes: total, + available_bytes: total - used, + ..Default::default() + }; + assert_eq!(over_gate(&snapshot(gate)), 0, "at the gate: nothing"); + assert_eq!( + over_gate(&snapshot(gate + 5 * BODY as u64)), + 5 * BODY as u64, + "past it: exactly the overrun" + ); +} diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs index b778f624fc..9d9c47d8a2 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs @@ -191,13 +191,14 @@ use super::*; { let memory = WorkingMemory::new(8); memory.set_served_window(16_384); - let cap = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; + let cap = 8_192; // a test body size; a shed below it collapses the older ones let saved = |handle: &str| crate::ai::types::ResultCustody::Whole { handle: handle.into() }; memory.record_receipt_typed(&[], &"c".repeat(cap / 2), None, saved("c011a75ed0000001")); for _ in 0..4 { memory.record_receipt_typed(&[], &"s".repeat(cap / 2), None, saved("5000000000000002")); } memory.record_settlement("done", None); + memory.evict_resident_results_over(0, &|_| true); let persisted = PersistedVolatile { wm: memory.snapshot(), own_speech: OwnSpeechPersisted::ByRoom(Vec::new()), diff --git a/core/continuum-cognition/src/cognition/working_memory.rs b/core/continuum-cognition/src/cognition/working_memory.rs index 5f4601e048..08a81c9493 100644 --- a/core/continuum-cognition/src/cognition/working_memory.rs +++ b/core/continuum-cognition/src/cognition/working_memory.rs @@ -558,6 +558,7 @@ impl VolatileSnapshot { written_pointer: None, summary: None, stored_chars: None, + received_ms: None, }; let mut records: BTreeMap = BTreeMap::new(); let mut unkeyed = 0usize; @@ -713,12 +714,12 @@ mod continuity; mod faculty; mod ledger; mod perception; +mod residency; pub use faculty::WorkingMemoryFaculty; pub(crate) use faculty::render_dispatched; pub(crate) use ledger::operation_level; -#[cfg(test)] -pub(crate) use perception::RESULTS_RESIDENT_CHARS; +pub(crate) use residency::Residency; impl Drop for WorkingMemory { /// A mind that is gone points at nothing: its saved results may be evicted again. diff --git a/core/continuum-cognition/src/cognition/working_memory/action_log.rs b/core/continuum-cognition/src/cognition/working_memory/action_log.rs index 5e8990ac72..ad1ce0e84b 100644 --- a/core/continuum-cognition/src/cognition/working_memory/action_log.rs +++ b/core/continuum-cognition/src/cognition/working_memory/action_log.rs @@ -47,6 +47,12 @@ pub(crate) struct ActionRecord { /// before this was kept (their whole then has no price: they show at pointer level). #[serde(default, skip_serializing_if = "Option::is_none")] pub stored_chars: Option, + /// When the result was received (ms since the Unix epoch): the one clock that orders every + /// mind's resident results oldest-first when the memory owner sheds across minds. `None` + /// for a record from a build before this was kept, which sheds first (it is older than any + /// result received since). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub received_ms: Option, } impl ActionRecord { @@ -56,15 +62,17 @@ impl ActionRecord { super::receipt_key(self.seq, self.handle.as_deref()) } - fn result_chars(&self) -> usize { - self.result.as_ref().map_or(0, |result| result.chars().count() + 1) + /// The RAM its resident body holds, in bytes: what the memory owner accounts, never a + /// character count (that is `stored_chars`, the view's price). + pub fn resident_bytes(&self) -> u64 { + self.result.as_ref().map_or(0, |result| result.len() as u64) } } /// What a collapse left behind. pub(super) struct Collapsed { - /// Characters still retained in full. - pub total: usize, + /// Bytes still resident. + pub total: u64, } #[derive(Debug, Default)] @@ -137,24 +145,45 @@ impl ActionLog { self.retained().chain(self.indexed_pointers()).map(ActionRecord::receipt_key).collect() } - /// Collapse the oldest saved results to their handles once the retained results exceed - /// `cap`, down to half of it, so the head of what she reads stays byte-stable between two - /// bursts. The newest result always stays, and an unsaved one stays whole. - pub fn collapse_over(&mut self, cap: usize) -> Collapsed { - let mut total: usize = self.records.iter().map(ActionRecord::result_chars).sum(); - if total <= cap { + /// The RAM every resident body holds, in bytes. + pub fn resident_bytes(&self) -> u64 { + self.records.iter().map(ActionRecord::resident_bytes).sum() + } + + /// The records a shed may move to their handles, oldest first: resident, saved (`saved` + /// says the handle's output is there to reload), and not the newest result. Everything + /// else is the last copy of what she read, so it stays. + pub fn evictable<'a>(&'a self, saved: &'a dyn Fn(&str) -> bool) -> impl Iterator + 'a { + let newest = self.retained().last().map(|record| record.seq); + self.records.iter().filter(move |record| { + record.result.is_some() + && Some(record.seq) != newest + && record.handle.as_deref().is_some_and(|handle| saved(handle)) + }) + } + + /// Move the oldest evictable bodies to their handles until at most `budget` bytes stay + /// resident. Each keeps its measured length (`stored_chars`) and its handle, so her view + /// still prices and reloads its whole. Exactly to the budget: the memory owner decides + /// when, so there is no hysteresis here. + pub fn collapse_over(&mut self, budget: u64, saved: &dyn Fn(&str) -> bool) -> Collapsed { + let mut total = self.resident_bytes(); + if total <= budget { return Collapsed { total }; } - let target = cap / 2; - let newest = self.retained().last().map(|record| record.seq); - for record in self.records.iter_mut() { - if total <= target { - break; - } - if record.result.is_none() || record.handle.is_none() || Some(record.seq) == newest { - continue; - } - total -= record.result_chars(); + let chosen: HashSet = { + let mut over = total - budget; + self.evictable(saved) + .take_while(|record| { + let take = over > 0; + over = over.saturating_sub(record.resident_bytes()); + take + }) + .map(|record| record.seq) + .collect() + }; + for record in self.records.iter_mut().filter(|record| chosen.contains(&record.seq)) { + total -= record.resident_bytes(); record.stored_chars = record.result.as_ref().map(|result| result.chars().count()); record.result = None; } diff --git a/core/continuum-cognition/src/cognition/working_memory/continuity.rs b/core/continuum-cognition/src/cognition/working_memory/continuity.rs index a40b0abcde..1947e8cbea 100644 --- a/core/continuum-cognition/src/cognition/working_memory/continuity.rs +++ b/core/continuum-cognition/src/cognition/working_memory/continuity.rs @@ -307,10 +307,9 @@ impl WorkingMemory { *self.receipt_children.lock() = snap.receipt_children; *self.view.lock() = snap.context_view; *self.open_views.lock() = super::super::open_views::OpenViews::from_saved(snap.open_views); - // Restored bodies are bound by the storage budget, never the window: a floor here once - // folded results the served window held (cap 1,536 at restore on the 5090, card - // df0035bf), and now nothing about the window decides what she sees (FLOW §2d). - self.evict_resident_results(); + // Restored bodies stay resident until the memory owner sheds: neither the window (a + // floor here once folded what the served window held, card df0035bf; FLOW §2d) nor a + // size cap decides at restore. self.publish_live_handles(); { let mut f = self.action_fps.lock(); diff --git a/core/continuum-cognition/src/cognition/working_memory/ledger.rs b/core/continuum-cognition/src/cognition/working_memory/ledger.rs index 5bd6fe9dea..253e6b9c94 100644 --- a/core/continuum-cognition/src/cognition/working_memory/ledger.rs +++ b/core/continuum-cognition/src/cognition/working_memory/ledger.rs @@ -295,8 +295,8 @@ impl WorkingMemory { // wall_source.rs 25+ times in four hours and landed no edit because every earlier // read reached her next turn as its last ~2,100 chars (Joel: "the clipping I've // yelled about for months"). The producer already fitted it (whole, or its - // handle: `spill::LivePin::whole_or_handle`); the budget decides how many of these units - // fit (`recent_results_chars`) and the rest collapse to pointers at settlement. + // handle: `spill::LivePin::whole_or_handle`); her view decides how much of each she + // sees, and the memory owner's shed alone moves a body to its handle (`residency`). { let tail = a.to_string(); // A receipt can contain several operations. Retain their typed names @@ -335,21 +335,14 @@ impl WorkingMemory { handle, written_pointer: None, stored_chars: None, + received_ms: Some(continuum_base::time::EpochMs::now().millis()), }, budget.receipt_archive_chars(), ); } - // The ring's share is enforced HERE, at every receipt, with hysteresis: nothing - // moves until the share is exceeded, then the oldest collapse to pointers down to - // half of it, so the prefix ahead of the newest entries is byte-stable for the whole - // run between two bursts. History: eviction on every act past ~3 (2026-08-24) rotated - // the head each act, and on a KV that cannot shift (`kv_shiftable = Some(false)`, - // "cache_reuse is not supported by this context") re-prefilled everything after it; - // the cap was then moved to settlement only. A coding turn is 100+ acts between - // settlements: on the M5 (2026-10-16) the rings persisted at 213 results / 686k - // chars, 155 / 1.09M, 123 / 442k, 49 / 138k, and fit_messages was the only bound. - // Now a storage budget (FOCUS rule 7): bodies leave RAM, never her view. - self.evict_resident_results(); + // No size cap here: the body stays in RAM until the one memory owner sheds + // (`residency`). A cap at receipt was a hand-rigged number (`RESULTS_RESIDENT_CHARS`, + // 1 << 20 chars) deciding what RAM could hold; the pressure monitor measures it. // Head into the rolling recency trail: proprioception ("I did #n X") + the // repeat-break signal. Truncation lives HERE now (one place), so callers pass the // full result and never pre-truncate. Append-only + `#seq`-stamped keeps the diff --git a/core/continuum-cognition/src/cognition/working_memory/perception.rs b/core/continuum-cognition/src/cognition/working_memory/perception.rs index ccd313e9cd..8ea1ce91ce 100644 --- a/core/continuum-cognition/src/cognition/working_memory/perception.rs +++ b/core/continuum-cognition/src/cognition/working_memory/perception.rs @@ -2,14 +2,6 @@ use super::*; -/// The RAM her results' bodies may hold, in characters: a storage budget, not a view size -/// (FOCUS-CONTRACT rule 7). Past it the oldest saved bodies move to their handles on disk and -/// stay visible at every level. -// derived-or-floor: floor. Storage only: past it a body is one local file read away when her view -// grants it whole. About 2 MiB per mind at the 2-byte char upper bound, sized above the largest -// ring measured (1.09M chars on a coding turn, 2026-10-16), so eviction is rare. -pub(crate) const RESULTS_RESIDENT_CHARS: usize = 1 << 20; - /// One act as her view renders it: seq, full, summary, pointer, and its stored whole (rendered /// chars, handle) when its body is not resident. pub(crate) type ActRendering = (u64, String, Option, String, Option<(usize, String)>); @@ -233,8 +225,8 @@ impl WorkingMemory { /// rides whole as the newest message of the turn); the flag says whether there is one. /// Each act as her view's actions source renders it: (seq, full, summary, pointer, stored). /// `stored` is the whole's rendered length and handle once its body left RAM for its - /// handle (`evict_resident_results`): `full` is then the pointer, and the view prices and - /// loads the whole through the source (`continuum_context::StoredWhole`). + /// handle (`evict_resident_results_over`, the memory owner's shed): `full` is then the + /// pointer, and the view prices and loads the whole through the source (`continuum_context::StoredWhole`). pub(crate) fn action_renderings(&self) -> (Vec, bool) { let active = self.in_flight_action_seq(); let actions = self.actions.lock(); @@ -308,11 +300,11 @@ impl WorkingMemory { "Recent results of your own actions (oldest first; #n matches the action ledger):" .to_string(), None, )); - // Every eligible result rides as a message of its own: the ring's RAM is bounded at - // receipt by its storage budget (`evict_resident_results`), never by a count here. + // Every eligible result rides as a message of its own: the ring's RAM is bounded by the + // one memory owner's shed (`residency`), never by a count here. // A count fold ("newest 16 as messages, the rest as index lines", 2026-10-16) rotated // the head on EVERY act, which on a KV that cannot shift re-prefilled everything - // after it; the chars cap with hysteresis rotates once per burst. + // after it; a shed happens only when RAM is short, so between sheds the ring appends. out.extend(actions.retained().filter(eligible).filter_map(|record| { let result = record.result.as_deref()?; let attribution = ResultAttribution::of(record); @@ -418,31 +410,6 @@ impl WorkingMemory { crate::cognition::tool_executor::spill::publish_live_handles(self.instance, handles); } - /// Bound the RAM her results' bodies hold (FOCUS-CONTRACT rule 7: a storage budget, never - /// what she sees). Past [`RESULTS_RESIDENT_CHARS`] the oldest saved bodies leave RAM for their - /// handles, down to half of it (hysteresis: nothing moves until the budget is passed). Each - /// keeps its measured length, so her view still prices its whole level and loads it when - /// the allocation grants it (`continuum_context::StoredWhole`, the actions source's `load`). - /// The newest result always stays; an unsaved result stays whole (no handle could reload - /// it). The window plays no part: it once did (`recent_results_chars`), and then this - /// decided what she read before her view saw her claims (FLOW §2d). - pub(super) fn evict_resident_results(&self) { - self.evict_resident_results_over(RESULTS_RESIDENT_CHARS); - } - - pub(crate) fn evict_resident_results_over(&self, budget: usize) { - let total = self.actions.lock().collapse_over(budget).total; - self.publish_live_handles(); - if total > budget { - continuum_base::probe!( - class = "wm.results.unsaved_over_storage", - total = %total, - budget = %budget, - "results whose save failed stay resident over the storage budget" - ); - } - } - /// Record that the persona SETTLED — produced an utterance and closed the current /// concern. Pushes a [`WM_SETTLEMENT_PREFIX`]-marked boundary into the same rolling /// buffer (honest proprioception: "I already answered X", perceivable by the mind @@ -451,9 +418,6 @@ impl WorkingMemory { /// legitimate re-use of the same tool for a genuinely NEW concern after an answer. /// Blank is ignored. Oldest ages out past capacity, same rolling scratchpad. pub fn record_settlement(&self, answer_head: &str, room: Option) { - // Deferred ring hygiene: the settle just closed, the next prompt - // re-prefills regardless — collapse over-cap results NOW, never mid-settle. - self.evict_resident_results(); let a = answer_head.trim(); let scope = self.scope.lock().clone(); // Existing authored-settlement boundary, not proof the task was completed. diff --git a/core/continuum-cognition/src/cognition/working_memory/residency.rs b/core/continuum-cognition/src/cognition/working_memory/residency.rs new file mode 100644 index 0000000000..49ad0046d0 --- /dev/null +++ b/core/continuum-cognition/src/cognition/working_memory/residency.rs @@ -0,0 +1,77 @@ +//! What of her results' bodies stays in RAM: the one memory owner decides. +//! +//! A result's body stays resident until the memory pressure monitor asks the mind-results +//! reporter to shed (`persona_workspace::mind_results_reporter`), never by a size cap at +//! receipt or restore: RAM decides, not a number (Joel, 2026-10-29). A shed moves the oldest +//! saved bodies to their handles; each keeps its measured length, so her view still prices its +//! whole level and loads it when the allocation grants it (FOCUS-CONTRACT rule 7, +//! `continuum_context::StoredWhole`). The newest result always stays, and so does any body +//! whose saved output is not there to reload: it is the last copy. + +use super::*; + +/// One resident body a shed may move to its handle. +#[derive(Debug, Clone)] +pub(crate) struct EvictableResult { + /// When it was received; `None` (an older build's record) sheds first. + pub received_ms: Option, + pub seq: u64, + pub bytes: u64, +} + +/// One mind's resident result bodies, as the memory owner accounts them. +#[derive(Debug, Clone)] +pub(crate) struct Residency { + /// Bytes of every resident body. + pub resident_bytes: u64, + /// Bytes no shed may move: the newest result, and every body whose saved output is not + /// there to reload (unsaved, or its output missing). + pub pinned_bytes: u64, + /// What a shed may move, oldest first. + pub evictable: Vec, +} + +impl WorkingMemory { + /// The RAM her resident result bodies hold, in bytes. Cheap: one pass, no allocation. + pub(crate) fn resident_result_bytes(&self) -> u64 { + self.actions.lock().resident_bytes() + } + + /// Her resident bodies split into what a shed may move and what it may not. `saved` says a + /// handle's output is there to reload; the caller owns that check (it knows her persona). + pub(crate) fn residency(&self, saved: &dyn Fn(&str) -> bool) -> Residency { + let actions = self.actions.lock(); + let resident_bytes = actions.resident_bytes(); + let evictable: Vec = actions + .evictable(saved) + .map(|record| EvictableResult { + received_ms: record.received_ms, + seq: record.seq, + bytes: record.resident_bytes(), + }) + .collect(); + let movable: u64 = evictable.iter().map(|result| result.bytes).sum(); + Residency { + resident_bytes, + pinned_bytes: resident_bytes - movable, + evictable, + } + } + + /// THE eviction verb: move the oldest saved bodies to their handles until at most `budget` + /// bytes stay resident. Only the memory owner's shed calls it in production. A body whose + /// output `saved` cannot vouch for stays, and so does the newest; past the budget after + /// that, the overrun is reported, never forced. + pub(crate) fn evict_resident_results_over(&self, budget: u64, saved: &dyn Fn(&str) -> bool) { + let total = self.actions.lock().collapse_over(budget, saved).total; + self.publish_live_handles(); + if total > budget { + continuum_base::probe!( + class = "wm.results.last_copies_over_allocation", + total = %total, + budget = %budget, + "results with no saved output to reload stay resident over the shed's allocation" + ); + } + } +} diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs b/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs index 41f34d02b5..4521544006 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/action_log.rs @@ -10,13 +10,14 @@ use super::*; fn an_act_is_one_record_that_collapses_but_keeps_its_ledger_line() { let wm = WorkingMemory::new(8); wm.set_served_window(16_384); - let cap = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; + let cap = 2 * BODY; // A short first line per result: that line is the ledger's, the body the ring's. wm.record_receipt_typed(&[], &format!("first\n{}", "a".repeat(cap / 2)), None, saved("first-handle")); for act in 2..=5 { record_saved(&wm, &format!("act {act}\n{}", "s".repeat(cap / 2))); } wm.record_settlement("done", None); + shed(&wm, cap / 2); let ledger: Vec = wm.receipt_archive().into_iter().map(|(_, head)| head).collect(); assert!(ledger.first().is_some_and(|head| head.starts_with("[action #1]")), "{ledger:?}"); let ring = wm.recent_results_messages().join("\n"); @@ -58,12 +59,13 @@ fn a_restart_keeps_every_act_as_she_read_it() { wm.set_served_window(16_384); wm.set_scope(Some("/work/foo".into())); let room = Uuid::new_v4(); - let cap = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; + let cap = 2 * BODY; wm.record_receipt_typed(&[], &format!("first\n{}", "a".repeat(cap / 2)), Some(room), saved("first-handle")); for act in 2..=5 { wm.record_receipt_typed(&[], &format!("act {act}\n{}", "s".repeat(cap / 2)), Some(room), saved("ring-test")); } wm.record_settlement("done", None); + shed(&wm, cap / 2); // The pointer index and the ledger. (Which act counts as in flight after a restore is // the restore's own rule, unchanged here, so the retained results are not compared.) let pointers = |memory: &WorkingMemory| -> Vec { @@ -85,12 +87,13 @@ fn a_restart_keeps_every_act_as_she_read_it() { fn a_checkpoint_keeps_the_shape_the_previous_build_reads() { let wm = WorkingMemory::new(8); wm.set_served_window(16_384); - let cap = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; + let cap = 2 * BODY; wm.record_receipt_typed(&[], &format!("first\n{}", "a".repeat(cap / 2)), None, saved("first-handle")); for act in 2..=5 { record_saved(&wm, &format!("act {act}\n{}", "s".repeat(cap / 2))); } wm.record_settlement("done", None); + shed(&wm, cap / 2); let snap = wm.snapshot(); assert!(snap.receipt_heads.first().is_some_and(|head| head.starts_with("[action #1]"))); assert_eq!(snap.evicted_pointers.first().map(|(_, handle)| handle.as_str()), Some("first-handle")); diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs index bd9779eb92..8b7bdf6f49 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs @@ -53,11 +53,11 @@ fn a_step_is_scoped_to_its_root_and_every_result_is_perceived_labelled_with_its_ "{back:?}" ); // Result custody must obey the same scope even after entry-trail eviction, - // settlement collapse and checkpoint restoration. Storage remains intact. + // a shed's collapse and checkpoint restoration. Storage remains intact. let results = WorkingMemory::new(2); results.set_served_window(16_384); results.set_scope(Some("task-a".into())); - let body_a = format!("task-a-only {}", "a".repeat(crate::cognition::working_memory::RESULTS_RESIDENT_CHARS)); + let body_a = format!("task-a-only {}", "a".repeat(BODY)); results.record_receipt_typed(&[], &body_a, None, saved("scope-a-output")); let original = results.last_action_full(); results.set_scope(Some("task-b".into())); @@ -73,6 +73,7 @@ fn a_step_is_scoped_to_its_root_and_every_result_is_perceived_labelled_with_its_ assert!(results.active_action_full().is_none(), "B stays stored but inactive in A"); results.set_scope(Some("task-b".into())); results.record_settlement("reported", None); + shed(&results, 0); let snapshot = results.snapshot(); assert!(!snapshot.evicted_pointers.is_empty(), "fixture exercises the collapsed ring"); let mut encoded = serde_json::to_value(&snapshot).expect("snapshot serializes"); @@ -118,13 +119,14 @@ fn a_mind_s_saved_handles_are_live_until_it_drops() { let live = |p: &std::path::Path| crate::cognition::tool_executor::spill::is_live(p); let wm = WorkingMemory::new(8); wm.set_served_window(16_384); - let cap = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; + let cap = 2 * BODY; wm.record_receipt_typed(&[], &"a".repeat(cap / 2), None, saved(&handle)); assert!(live(&file), "referenced by the ring"); for _ in 0..4 { record_saved(&wm, &"s".repeat(cap / 2)); } wm.record_settlement("done", None); + shed(&wm, cap / 2); assert!( wm.recent_results_messages().join("\n").contains(&format!("{handle} — collapsed")), "it collapsed to a pointer" @@ -166,7 +168,7 @@ fn a_receipt_s_per_call_results_stay_reachable_as_long_as_the_receipt() { let (receipt, children) = (id(), [id(), id()]); let wm = WorkingMemory::new(2); // two entries: the third receipt rolls the first out wm.set_served_window(16_384); - let cap = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; + let cap = 2 * BODY; wm.record_receipt_typed(&[act(&children[0]), act(&children[1])], &"r".repeat(cap / 2), None, saved(&receipt)); for _ in 0..3 { record_saved(&wm, &"s".repeat(cap / 2)); @@ -175,6 +177,7 @@ fn a_receipt_s_per_call_results_stay_reachable_as_long_as_the_receipt() { assert!(children.iter().all(|c| live(c)), "the receipt still holds its children"); wm.record_settlement("done", None); + shed(&wm, cap / 2); assert!(wm.recent_results_messages().join("\n").contains(&format!("{receipt} — collapsed")), "collapsed to a pointer"); assert!(live(&receipt) && children.iter().all(|c| live(c)), "the pointer holds the receipt and its children"); @@ -274,22 +277,16 @@ fn each_call_s_saved_result_is_live_once_its_receipt_is_recorded() { } // what this catches (BigMama's live receipt of #4963 on the 5090, card df0035bf; FLOW §2d): -// restore folding what she sees by a window. Restore once collapsed against the floor budget -// before her window was known (a 1,536-char share), and later against the window itself. The -// ring's bound is now a storage budget (`RESULTS_RESIDENT_CHARS`): the window plays no part, so -// restoring with no window or a small one keeps exactly what the snapshot held. +// restore folding what she sees by a window or a size. Restore once collapsed against the floor +// budget before her window was known (a 1,536-char share), later against the window itself, and +// then against a size cap of ours (`RESULTS_RESIDENT_CHARS`). Only the memory owner sheds now, so +// restoring with no window or a small one keeps every body the snapshot held resident. #[test] -fn restore_bounds_results_by_storage_never_by_window() { - let budget = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; +fn restore_keeps_every_resident_body_whatever_the_window() { let source = WorkingMemory::new(8); source.set_served_window(65_536); for i in 0..4 { - source.record_receipt_typed( - &[], - &format!("r{i} {}", "w".repeat(budget / 3)), - None, - saved(&format!("restore-{i}")), - ); + source.record_receipt_typed(&[], &format!("r{i} {}", "w".repeat(64 * BODY)), None, saved(&format!("restore-{i}"))); } let snapshot = source.snapshot(); let entries = |wm: &WorkingMemory| { @@ -298,63 +295,53 @@ fn restore_bounds_results_by_storage_never_by_window() { let held = entries(&source); let unknown = WorkingMemory::new(8); unknown.restore(snapshot.clone()); - assert_eq!(entries(&unknown), held, "no window yet: the storage budget alone bounds it"); + assert_eq!(entries(&unknown), held, "no window yet: nothing moves at restore"); + assert_eq!(unknown.resident_result_bytes(), source.resident_result_bytes(), "every body restored resident"); let small = WorkingMemory::new(8); small.set_served_window(16_384); small.restore(snapshot); assert_eq!(entries(&small), held, "a small window changes nothing her view is offered"); } -// what this catches: the ring growing without bound between settlements. The share was -// enforced at settlement only, and a coding turn is 100+ acts between settlements (the M5, -// 2026-10-16: 1.09M chars of results persisted for one mind). At every receipt the ring is -// within its share, the newest result is whole, and eviction is a BURST with hysteresis: -// between bursts the ring only appends, so the prefix ahead of it stays byte-stable. +// what this catches: a size cap of ours deciding what RAM holds (`RESULTS_RESIDENT_CHARS = +// 1 << 20` evicted every mind's oldest bodies at receipt, settlement and restore; Joel +// 2026-10-29: no hand-rigged constants). However large the ring grows, receipts and +// settlements move nothing to its handle: only the memory owner's shed does. #[test] -fn the_ring_holds_its_share_at_every_receipt_and_evicts_in_bursts() { +fn results_are_never_evicted_at_receipt_however_large_the_ring() { let wm = WorkingMemory::new(8); wm.set_served_window(16_384); - let share = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; - let chunk = share / 5; - let rendered = |wm: &WorkingMemory| -> Vec { - wm.recent_results_messages().into_iter().filter(|m| m.starts_with("[result ")).collect() - }; - let mut bursts = 0; - let mut head: Option = None; + let chunk = 64 * BODY; for i in 0..40 { - wm.record_receipt_typed(&[], &format!("r{i} {}", "w".repeat(chunk)), None, saved(&format!("burst-{i}"))); - let ring = rendered(&wm); - let chars: usize = ring.iter().map(|m| m.chars().count()).sum(); - assert!(chars <= share + 2_048, "receipt {i}: {chars} rendered chars over the {share} share"); - let now = ring.first().cloned(); - if head.is_some() && now != head { - bursts += 1; + wm.record_receipt_typed(&[], &format!("r{i} {}", "w".repeat(chunk)), None, saved(&format!("ring-{i}"))); + if i % 10 == 9 { + wm.record_settlement("a burst done", None); } - head = now; } - assert!(bursts >= 1, "the share was exceeded, so at least one burst evicted"); - assert!(bursts < 20, "a burst with hysteresis, not a rotation on every act: {bursts} bursts in 40 receipts"); - let newest = wm.snapshot().recent_results.last().map(|r| r.2.clone()).unwrap_or_default(); - assert!(newest.starts_with("r39 ") && newest.len() > chunk, "the newest result is held whole"); + assert!(wm.resident_result_bytes() >= 40 * chunk as u64, "all 40 bodies resident: {}", wm.resident_result_bytes()); + let snapshot = wm.snapshot(); + assert!(snapshot.evicted_pointers.is_empty(), "nothing collapsed to a pointer"); + assert!(snapshot.actions.iter().all(|record| record.result.is_some()), "every record holds its body"); } // what this catches: an unsaved result dropped at collapse (Astra on #4963 at 4840af859: // a pointer saying "never saved" documents the loss instead of preventing it). Its save -// failed, so nothing else holds its bytes: it stays WHOLE through settlement and restore -// while the saved results around it collapse to pointers. +// failed, so nothing else holds its bytes: it stays WHOLE through a shed and restore while +// the saved results around it collapse to pointers. #[test] -fn an_unsaved_result_keeps_its_bytes_through_settlement_and_restore() { +fn an_unsaved_result_keeps_its_bytes_through_a_shed_and_restore() { let wm = WorkingMemory::new(8); wm.set_served_window(16_384); - let cap = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; + let cap = 2 * BODY; let unsaved = format!("UNSAVED {}", "u".repeat(cap / 2)); wm.record_receipt_typed(&[], &unsaved, None, crate::ai::types::ResultCustody::Unsaved); for _ in 0..4 { record_saved(&wm, &"s".repeat(cap / 2)); } wm.record_settlement("done", None); + shed(&wm, cap / 2); let whole = |m: &WorkingMemory| m.recent_results_messages().iter().any(|r| r.ends_with(&unsaved)); - assert!(whole(&wm), "kept whole through settlement"); + assert!(whole(&wm), "kept whole through the shed"); assert!( wm.recent_results_messages().join("\n").contains("ring-test — collapsed"), "the saved ones around it collapsed" @@ -378,7 +365,7 @@ fn a_restore_prices_a_legacy_evicted_result_from_its_saved_output() { wm.record_receipt_typed(&[], &body, None, pin.retain(persona, &body)); wm.record_receipt_typed(&[], "a result whose output is gone", None, pin.retain(persona, "a result whose output is gone")); wm.record_receipt_typed(&[], "the newest stays resident", None, pin.retain(persona, "the newest stays resident")); - wm.evict_resident_results_over(1); + shed(&wm, 1); let mut snapshot = wm.snapshot(); snapshot.actions = snapshot.action_records(); // the shape the old share left: body gone, handle kept, no stored size diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs b/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs index 6ddc61bcf7..66271ac0f2 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs @@ -21,3 +21,13 @@ fn saved(handle: &str) -> crate::ai::types::ResultCustody { fn record_saved(wm: &WorkingMemory, text: &str) { wm.record_receipt_typed(&[], text, None, saved("ring-test")); } + +/// A test body's size in bytes: big enough that a shed below a few of them is visible. The +/// size is the test's choice; production has no such number (the memory owner sheds). +const BODY: usize = 4_096; + +/// Shed `wm`'s resident bodies down to `budget` bytes, as the memory owner's reporter does, +/// with every handle's saved output vouched for. +fn shed(wm: &WorkingMemory, budget: usize) { + wm.evict_resident_results_over(budget as u64, &|_| true); +} diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs b/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs index 8e864490f9..536ceedf1d 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/provenance.rs @@ -202,12 +202,13 @@ fn result_provenance_survives_cross_activity_render_and_checkpoint() { wm.full_result_message(seq, &full) ); - // Actual settlement collapses old results; its pointers must still tell + // A shed collapses old results; its pointers must still tell // the mind which activity and operation the retained handle belongs to. for _ in 0..4 { - record_saved(&restored, &"x".repeat(crate::cognition::working_memory::RESULTS_RESIDENT_CHARS)); + record_saved(&restored, &"x".repeat(BODY)); } restored.record_settlement("reported", None); + shed(&restored, 0); assert!(restored.recent_results_messages().join("\n").contains( &format!("[result #1; room {room_a}; operation code/search, code/read; output handle: tool/output search-output — collapsed]") )); diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs index 266d941e3e..18128e6eb7 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/trail.rs @@ -11,8 +11,7 @@ use super::*; #[test] fn recent_results_survive_subsequent_acts_and_stay_bounded() { let wm = WorkingMemory::new(8); - // A known window: the receipt-time collapse folds nothing against an unknown one - // (the act→observe seam pins the served window before any receipt in production). + // A known window, as the act→observe seam pins it before any receipt in production. wm.set_served_window(16_384); record_saved(&wm, "[action] code/run(sol.rs) error[E0601]: `main` function not found"); record_saved(&wm, "[action] code/list() sol.rs sol2.rs"); @@ -22,17 +21,13 @@ fn recent_results_survive_subsequent_acts_and_stay_bounded() { block.contains("E0601"), "the compile error must survive later trivial acts: {block}" ); - // PREMISE (2026-10-16, the third premise): the share is enforced at EVERY receipt, - // in a BURST with hysteresis. 2026-08-24 moved it to settlement because per-act - // eviction rotated the head on every act; a coding turn then held 100+ results - // between settlements (the M5: 1.09M chars persisted for one mind). So: flooding - // past the share collapses the OLDEST to pointers once, down to half the share… - let cap = crate::cognition::working_memory::RESULTS_RESIDENT_CHARS; - // Whole results an eighth of the share each, so several fit and the collapse is visible. - let unit = (cap / 8).max(1); + // A shed (only the memory owner's, under pressure) collapses the OLDEST to pointers, + // and every result still shown is shown whole. + let unit = BODY; for _ in 0..8 { record_saved(&wm, &"x".repeat(unit)); } + shed(&wm, 4 * unit); let messages = wm.recent_results_messages(); let kept: Vec<&String> = messages.iter().filter(|m| m.starts_with("[result ")).collect(); assert!(!kept.is_empty(), "the newest results stay"); @@ -43,18 +38,11 @@ fn recent_results_survive_subsequent_acts_and_stay_bounded() { assert!(messages.iter().any(|m| m.contains("collapsed")), "the rest are pointers"); assert!( !messages.join("\n").contains("E0601"), - "the oldest collapse to pointers once the share is exceeded — bounded, not immortal" - ); - // …in ONE CHUNK: the collapse lands at half the cap so the surviving head - // stays byte-identical across the next receipts and settles (the KV divergence - // audit, 2026-09-13: the oldest surviving result was the first differing block in - // 28 of 55 consecutive turns under one-entry-per-settle eviction). - let total: usize = kept.len() * unit; - assert!( - total <= cap / 2 + unit, - "an over-cap collapse lands at half the cap, not at the cap: {total} > {}", - cap / 2 + "the oldest collapse to pointers once shed — bounded, not immortal" ); + assert!(wm.resident_result_bytes() <= 4 * unit as u64, "down to the allocation: {}", wm.resident_result_bytes()); + // Between sheds the ring only appends: receipts and settles move nothing, so the head + // stays byte-identical (the KV divergence audit, 2026-09-13). let head_after_collapse = wm.recent_results_messages().get(1).cloned(); record_saved(&wm, "[action] code/read(a.rs) fine"); wm.record_settlement("one", None); @@ -63,7 +51,7 @@ fn recent_results_survive_subsequent_acts_and_stay_bounded() { assert_eq!( wm.recent_results_messages().get(1).cloned(), head_after_collapse, - "the ledger head is byte-stable across receipts and settles that fit under the cap" + "the ledger head is byte-stable across receipts and settles between sheds" ); } diff --git a/core/continuum-core/src/ipc/start_server/persona_registry_modules.rs b/core/continuum-core/src/ipc/start_server/persona_registry_modules.rs index 46d9a6d29a..c741aedb7f 100644 --- a/core/continuum-core/src/ipc/start_server/persona_registry_modules.rs +++ b/core/continuum-core/src/ipc/start_server/persona_registry_modules.rs @@ -98,6 +98,12 @@ pub(super) fn register_persona_registry_modules( crate::cognition::channel_substrate::global_channel_digest_buffer(), ), ); + // Every mind's resident result bodies answer to the one memory owner: they stay in RAM + // until the monitor sheds, never a size cap of ours (Joel, 2026-10-29). + pressure_monitor.add_reporter(Arc::new(crate::cognition::persona_workspace::MindResultsReporter::new( + crate::cognition::persona_workspace::global(), + pressure_monitor.subscribe(), + ))); // The dream/consolidation region goes LIVE (#145 slice B): per live persona, // on a material-driven cadence (dreams only when undigested episodic // experience accrues, `CadenceHint::Sleep` otherwise), it distills episodic From b7a477def4191225c40306a2c0af610f393fba35 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 29 Oct 2026 15:52:03 -0500 Subject: [PATCH 2/4] Results shed as Interactive state, every moved body's handle stays live, and no stat under a mind's lock - Priority Interactive: her results are working state for her current task, not an idle cache, so a shed gives up only the host's overrun past 0.80 instead of every movable body at the first Warning. The swap-only limit is noted in the reporter's doc. - Last copy: every record naming a handle keeps it live (`receipt_keys`) and stays in the log (`prune` drops only records with neither a body nor a handle, past the ledger's share). The newest 12 pointers (`POINTER_INDEX`) are now a rendering count only. - No filesystem access under a mind's lock: `resident_results()` reads candidates under it, the reporter checks each saved output after it drops, and the eviction moves only `(seq, handle)` pairs it vouched for, re-checked under the lock. Tests: a moved body's handle stays live behind 60 newer pointers and its record stays priced; a shed moves only records still naming the vouched handle; the target test reads the Interactive gate. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/context_streams/tests.rs | 2 +- .../mind_results_reporter.rs | 77 +++++++++++++++---- .../tests/mind_results_reporter.rs | 2 +- ..._told_when_her_hands_move_and_only_then.rs | 2 +- .../src/cognition/working_memory.rs | 2 +- .../cognition/working_memory/action_log.rs | 45 ++++++----- .../src/cognition/working_memory/residency.rs | 61 ++++++++------- .../cognition/working_memory/tests/custody.rs | 48 ++++++++++++ .../src/cognition/working_memory/tests/mod.rs | 2 +- 9 files changed, 173 insertions(+), 68 deletions(-) diff --git a/core/continuum-cognition/src/cognition/context_streams/tests.rs b/core/continuum-cognition/src/cognition/context_streams/tests.rs index c1953ce6b6..62b64ce156 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tests.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tests.rs @@ -96,7 +96,7 @@ fn an_evicted_result_is_still_seen_whole_through_its_stored_level() { memory.record_receipt_typed(&[], "the newest stays resident", None, pin.retain(persona, "the newest stays resident")); let (before, _) = memory.action_renderings(); let resident_whole = before.first().map(|act| act.1.clone()).expect("test: the first act"); - memory.evict_resident_results_over(1, &|_| true); + memory.evict_resident_results_over(1, &|_, _| true); let (acts, _) = memory.action_renderings(); let (seq, full, _, pointer, stored) = acts.first().cloned().expect("test: the first act"); let (chars, _) = stored.expect("evicted to its handle and priced"); diff --git a/core/continuum-cognition/src/cognition/persona_workspace/mind_results_reporter.rs b/core/continuum-cognition/src/cognition/persona_workspace/mind_results_reporter.rs index 46f121a7a6..d550baa422 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/mind_results_reporter.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/mind_results_reporter.rs @@ -10,6 +10,13 @@ //! Accounting is BYTES of resident bodies (`String::len`), never characters: characters are //! the view's price (`stored_chars`). Each record owns its body (no shared backing), so the sum //! over records is the RAM they hold; a working memory reached twice is counted once. +//! +//! No filesystem access under a mind's lock: her candidates are read under it, each saved +//! output is checked after it drops, and the eviction moves only the `(seq, handle)` pairs that +//! check vouched for. +//! +//! Known limit: the shed target is the host's RAM overrun past this priority's gate, so a +//! level raised by swap activity alone, with RAM use under the gate, sheds nothing here. use std::path::PathBuf; use std::sync::Arc; @@ -22,15 +29,15 @@ use tokio::sync::watch; use uuid::Uuid; use super::PersonaWorkspaceRegistry; -use crate::cognition::working_memory::{Residency, WorkingMemory}; +use crate::cognition::working_memory::{ResidentResults, WorkingMemory}; const NAME: &str = "mind_results"; -/// A cache of state that can spill: every body it sheds is already saved whole to its handle -/// and reloads when her view grants it. That is `Background` ("caches, pre-computed data, idle -/// resources"), not `Interactive` (state a mind cannot work without: the newest result and the -/// last copies are that, and the shed never moves them). -const PRIORITY: MemoryPriority = MemoryPriority::Background; +/// Her results are working state for her current task ("active persona state"), not an idle +/// cache: `Interactive`. Its gate (0.80) is where the monitor's Warning starts, so a shed gives +/// up only the overrun past it, not every movable body at the first Warning as `Background`'s +/// 0.60 gate would. +const PRIORITY: MemoryPriority = MemoryPriority::Interactive; /// Why a body stays resident through a shed: it is the last copy of what she read. #[derive(Debug)] @@ -105,6 +112,39 @@ pub(crate) fn over_gate(snapshot: &PressureSnapshot) -> u64 { used.saturating_sub(gate) } +/// One mind's resident result bodies as the memory owner accounts them: what a shed may move +/// (its saved output vouched for, outside her lock) and what it may not. +#[derive(Debug, Clone)] +pub(crate) struct Residency { + pub resident_bytes: u64, + /// The newest result and every last copy: what no shed may move. + pub pinned_bytes: u64, + /// Vouched candidates, oldest first. + pub evictable: Vec, +} + +/// Read `memory`'s candidates under her lock, then vouch for each saved output after it drops. +pub(crate) fn residency( + persona: Uuid, + memory: &WorkingMemory, + saved: &dyn Fn(Uuid, &str) -> bool, +) -> Residency { + let ResidentResults { + resident_bytes, + candidates, + } = memory.resident_results(); + let evictable: Vec<_> = candidates + .into_iter() + .filter(|candidate| saved(persona, &candidate.handle)) + .collect(); + let movable: u64 = evictable.iter().map(|candidate| candidate.bytes).sum(); + Residency { + resident_bytes, + pinned_bytes: resident_bytes - movable, + evictable, + } +} + /// Per mind, the bytes to keep resident so the total comes down to `allocation`, moving the /// oldest bodies across every mind first (`None`: leave that mind untouched). Within a mind /// the oldest received are the lowest `seq`, so each budget moves exactly that mind's chosen @@ -144,11 +184,20 @@ pub(crate) fn plan_shed(minds: &[Residency], allocation: u64) -> Vec pub(crate) fn shed_to(minds: &Minds, allocation: u64, saved: &dyn Fn(Uuid, &str) -> bool) { let residencies: Vec = minds .iter() - .map(|(persona, memory)| memory.residency(&|handle| saved(*persona, handle))) + .map(|(persona, memory)| residency(*persona, memory, saved)) .collect(); - for ((persona, memory), budget) in minds.iter().zip(plan_shed(&residencies, allocation)) { + let budgets = plan_shed(&residencies, allocation); + for (((_, memory), mind), budget) in minds.iter().zip(&residencies).zip(budgets) { if let Some(budget) = budget { - memory.evict_resident_results_over(budget, &|handle| saved(*persona, handle)); + // Only what was vouched for, and only if the record still names that handle. + let vouched: std::collections::HashMap = mind + .evictable + .iter() + .map(|candidate| (candidate.seq, candidate.handle.as_str())) + .collect(); + memory.evict_resident_results_over(budget, &|seq, handle| { + vouched.get(&seq).is_some_and(|vouched| *vouched == handle) + }); } } } @@ -201,12 +250,10 @@ impl MemoryReporter for MindResultsReporter { minds .iter() .fold((0u64, 0u64), |(resident, pinned), (persona, memory)| { - let residency = - memory.residency(&|handle| saved_output(*persona, handle).is_ok()); - ( - resident + residency.resident_bytes, - pinned + residency.pinned_bytes, - ) + let mind = residency(*persona, memory, &|persona, handle| { + saved_output(persona, handle).is_ok() + }); + (resident + mind.resident_bytes, pinned + mind.pinned_bytes) }); MemoryBudgetSpec { name: NAME.to_string(), diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs index e75ab51071..52819a2d1b 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs @@ -138,7 +138,7 @@ fn the_shed_target_is_the_hosts_overrun_past_the_monitors_gate() { "no poll yet: nothing to shed" ); let total = 100 * 1024 * 1024 * 1024u64; - let gate = (total as f64 * MemoryPriority::Background.pressure_gate()) as u64; + let gate = (total as f64 * MemoryPriority::Interactive.pressure_gate()) as u64; let snapshot = |used: u64| PressureSnapshot { total_bytes: total, available_bytes: total - used, diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs index 9d9c47d8a2..7af2838e13 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs @@ -198,7 +198,7 @@ use super::*; memory.record_receipt_typed(&[], &"s".repeat(cap / 2), None, saved("5000000000000002")); } memory.record_settlement("done", None); - memory.evict_resident_results_over(0, &|_| true); + memory.evict_resident_results_over(0, &|_, _| true); let persisted = PersistedVolatile { wm: memory.snapshot(), own_speech: OwnSpeechPersisted::ByRoom(Vec::new()), diff --git a/core/continuum-cognition/src/cognition/working_memory.rs b/core/continuum-cognition/src/cognition/working_memory.rs index 08a81c9493..3aefa0de79 100644 --- a/core/continuum-cognition/src/cognition/working_memory.rs +++ b/core/continuum-cognition/src/cognition/working_memory.rs @@ -719,7 +719,7 @@ mod residency; pub use faculty::WorkingMemoryFaculty; pub(crate) use faculty::render_dispatched; pub(crate) use ledger::operation_level; -pub(crate) use residency::Residency; +pub(crate) use residency::{ResidentResults, ShedCandidate}; impl Drop for WorkingMemory { /// A mind that is gone points at nothing: its saved results may be evicted again. diff --git a/core/continuum-cognition/src/cognition/working_memory/action_log.rs b/core/continuum-cognition/src/cognition/working_memory/action_log.rs index ad1ce0e84b..ae20c819e2 100644 --- a/core/continuum-cognition/src/cognition/working_memory/action_log.rs +++ b/core/continuum-cognition/src/cognition/working_memory/action_log.rs @@ -11,8 +11,9 @@ use std::collections::{HashSet, VecDeque}; use uuid::Uuid; -/// How many collapsed results keep their pointer (and their saved whole) reachable. The -/// bound the collapsed-pointer index already had; the ledger line outlives it. +/// How many collapsed results the legacy results ring lists as pointer lines (and the +/// checkpoint's rollback shape carries). A rendering count only: every record that names a +/// handle keeps it live and stays in the log (`receipt_keys`, `prune`). const POINTER_INDEX: usize = 12; #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] @@ -140,9 +141,14 @@ impl ActionLog { } /// Every receipt whose dependencies must stay reachable: each retained result's key and - /// each indexed pointer's handle. + /// every handle a record names. A body moved to its handle exists only on disk, so its + /// handle is live for as long as its record is, however many pointers are newer. pub fn receipt_keys(&self) -> HashSet { - self.retained().chain(self.indexed_pointers()).map(ActionRecord::receipt_key).collect() + self.records + .iter() + .filter(|record| record.result.is_some() || record.handle.is_some()) + .map(ActionRecord::receipt_key) + .collect() } /// The RAM every resident body holds, in bytes. @@ -150,15 +156,18 @@ impl ActionLog { self.records.iter().map(ActionRecord::resident_bytes).sum() } - /// The records a shed may move to their handles, oldest first: resident, saved (`saved` - /// says the handle's output is there to reload), and not the newest result. Everything - /// else is the last copy of what she read, so it stays. - pub fn evictable<'a>(&'a self, saved: &'a dyn Fn(&str) -> bool) -> impl Iterator + 'a { + /// The records a shed may move to their handles, oldest first: resident, saved, not the + /// newest result, and vouched for by `saved(seq, handle)` (its output is there to reload). + /// Everything else is the last copy of what she read, so it stays. + pub fn evictable<'a>( + &'a self, + saved: &'a dyn Fn(u64, &str) -> bool, + ) -> impl Iterator + 'a { let newest = self.retained().last().map(|record| record.seq); self.records.iter().filter(move |record| { record.result.is_some() && Some(record.seq) != newest - && record.handle.as_deref().is_some_and(|handle| saved(handle)) + && record.handle.as_deref().is_some_and(|handle| saved(record.seq, handle)) }) } @@ -166,7 +175,7 @@ impl ActionLog { /// resident. Each keeps its measured length (`stored_chars`) and its handle, so her view /// still prices and reloads its whole. Exactly to the budget: the memory owner decides /// when, so there is no hysteresis here. - pub fn collapse_over(&mut self, budget: u64, saved: &dyn Fn(&str) -> bool) -> Collapsed { + pub fn collapse_over(&mut self, budget: u64, saved: &dyn Fn(u64, &str) -> bool) -> Collapsed { let mut total = self.resident_bytes(); if total <= budget { return Collapsed { total }; @@ -190,16 +199,12 @@ impl ActionLog { Collapsed { total } } - /// Drop the records nothing shows any more: past the ledger's share, collapsed, and - /// no longer indexed as a pointer. + /// Drop the records nothing can reach any more: past the ledger's share, no body in RAM, + /// and no handle to reload one from. A record naming a handle stays, since its whole is + /// reachable through her view (`StoredWhole`) for as long as the record is. fn prune(&mut self, archive_chars: usize) { - let keep: HashSet = self - .archive(archive_chars) - .into_iter() - .map(|(record, _)| record) - .chain(self.indexed_pointers()) - .map(|record| record.seq) - .collect(); - self.records.retain(|record| record.result.is_some() || keep.contains(&record.seq)); + let keep: HashSet = self.archive(archive_chars).into_iter().map(|(record, _)| record.seq).collect(); + self.records + .retain(|record| record.result.is_some() || record.handle.is_some() || keep.contains(&record.seq)); } } diff --git a/core/continuum-cognition/src/cognition/working_memory/residency.rs b/core/continuum-cognition/src/cognition/working_memory/residency.rs index 49ad0046d0..530f4f0561 100644 --- a/core/continuum-cognition/src/cognition/working_memory/residency.rs +++ b/core/continuum-cognition/src/cognition/working_memory/residency.rs @@ -10,25 +10,25 @@ use super::*; -/// One resident body a shed may move to its handle. +/// One resident body a shed may move to its handle, if its saved output is there to reload +/// (the caller checks that outside her lock). #[derive(Debug, Clone)] -pub(crate) struct EvictableResult { +pub(crate) struct ShedCandidate { /// When it was received; `None` (an older build's record) sheds first. pub received_ms: Option, pub seq: u64, + pub handle: String, pub bytes: u64, } -/// One mind's resident result bodies, as the memory owner accounts them. +/// One mind's resident result bodies, read under her lock with no filesystem access. #[derive(Debug, Clone)] -pub(crate) struct Residency { +pub(crate) struct ResidentResults { /// Bytes of every resident body. pub resident_bytes: u64, - /// Bytes no shed may move: the newest result, and every body whose saved output is not - /// there to reload (unsaved, or its output missing). - pub pinned_bytes: u64, - /// What a shed may move, oldest first. - pub evictable: Vec, + /// Saved bodies other than the newest, oldest first: what a shed may move once each + /// candidate's output is vouched for. + pub candidates: Vec, } impl WorkingMemory { @@ -37,32 +37,37 @@ impl WorkingMemory { self.actions.lock().resident_bytes() } - /// Her resident bodies split into what a shed may move and what it may not. `saved` says a - /// handle's output is there to reload; the caller owns that check (it knows her persona). - pub(crate) fn residency(&self, saved: &dyn Fn(&str) -> bool) -> Residency { + /// Her resident bodies and the saved ones a shed could move. Only memory is read under the + /// lock: whether each handle's output is there is the caller's check, made after it drops. + pub(crate) fn resident_results(&self) -> ResidentResults { let actions = self.actions.lock(); - let resident_bytes = actions.resident_bytes(); - let evictable: Vec = actions - .evictable(saved) - .map(|record| EvictableResult { - received_ms: record.received_ms, - seq: record.seq, - bytes: record.resident_bytes(), + let candidates = actions + .evictable(&|_, _| true) + .filter_map(|record| { + Some(ShedCandidate { + received_ms: record.received_ms, + seq: record.seq, + handle: record.handle.clone()?, + bytes: record.resident_bytes(), + }) }) .collect(); - let movable: u64 = evictable.iter().map(|result| result.bytes).sum(); - Residency { - resident_bytes, - pinned_bytes: resident_bytes - movable, - evictable, + ResidentResults { + resident_bytes: actions.resident_bytes(), + candidates, } } /// THE eviction verb: move the oldest saved bodies to their handles until at most `budget` - /// bytes stay resident. Only the memory owner's shed calls it in production. A body whose - /// output `saved` cannot vouch for stays, and so does the newest; past the budget after - /// that, the overrun is reported, never forced. - pub(crate) fn evict_resident_results_over(&self, budget: u64, saved: &dyn Fn(&str) -> bool) { + /// bytes stay resident. Only the memory owner's shed calls it in production, with `saved` + /// answering from the `(seq, handle)` pairs it vouched for outside the lock, so a record + /// that changed since (a different handle, or gone) is not moved. The newest stays, and + /// past the budget after that the overrun is reported, never forced. + pub(crate) fn evict_resident_results_over( + &self, + budget: u64, + saved: &dyn Fn(u64, &str) -> bool, + ) { let total = self.actions.lock().collapse_over(budget, saved).total; self.publish_live_handles(); if total > budget { diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs index 8b7bdf6f49..52f119b7ca 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs @@ -136,6 +136,54 @@ fn a_mind_s_saved_handles_are_live_until_it_drops() { assert!(!live(&file), "released when the mind drops"); } +// what this catches: a body moved to disk losing its last copy. Liveness (and the log itself) +// once covered only the newest 12 collapsed pointers (`POINTER_INDEX`), so a shed that moved +// many bodies left the older handles evictable under disk pressure while her view still priced +// their wholes. Every record that names a handle keeps it live, however many pointers are newer. +#[test] +fn a_moved_body_s_handle_stays_live_behind_any_number_of_newer_pointers() { + let handle = || format!("{:016x}", Uuid::new_v4().as_u128() as u64); + let live = |h: &str| crate::cognition::tool_executor::spill::is_live(&std::path::PathBuf::from(format!("/spill/p/{h}.log"))); + let wm = WorkingMemory::new(8); + wm.set_served_window(16_384); + let first = handle(); + wm.record_receipt_typed(&[], &"f".repeat(BODY), None, saved(&first)); + for _ in 0..30 { + record_receipt_with(&wm, &handle()); + } + shed(&wm, 0); + for _ in 0..30 { + record_receipt_with(&wm, &handle()); + } + shed(&wm, 0); + assert!(live(&first), "the oldest moved body's handle is still protected"); + let (acts, _) = wm.action_renderings(); + let oldest = acts.first().expect("test: the first act"); + assert_eq!(oldest.4.as_ref().map(|(_, h)| h.as_str()), Some(first.as_str()), "its record stays, priced and reloadable"); + drop(wm); + assert!(!live(&first), "released when the mind drops"); +} + +fn record_receipt_with(wm: &WorkingMemory, handle: &str) { + wm.record_receipt_typed(&[], &format!("{handle} {}", "s".repeat(BODY)), None, saved(handle)); +} + +// what this catches: a shed moving a record it never checked. The memory owner vouches for each +// saved output outside her lock, then evicts by `(seq, handle)`; a record that no longer names +// the vouched handle stays resident. +#[test] +fn a_shed_moves_only_the_records_it_vouched_for() { + let wm = WorkingMemory::new(8); + wm.record_receipt_typed(&[], &"a".repeat(BODY), None, saved("vouched-a")); + wm.record_receipt_typed(&[], &"b".repeat(BODY), None, saved("vouched-b")); + wm.record_receipt_typed(&[], "newest", None, saved("vouched-c")); + let seq_of = |h: &str| wm.snapshot().actions.iter().find(|r| r.handle.as_deref() == Some(h)).map(|r| r.seq).expect("test: seq"); + let (a, b) = (seq_of("vouched-a"), seq_of("vouched-b")); + wm.evict_resident_results_over(0, &|seq, handle| (seq == a && handle == "a-changed") || (seq == b && handle == "vouched-b")); + let resident: Vec<_> = wm.snapshot().actions.into_iter().filter(|r| r.result.is_some()).filter_map(|r| r.handle).collect(); + assert_eq!(resident, ["vouched-a", "vouched-c"], "a changed since it was vouched for; only b moved"); +} + // what this catches (Codex on #4987): per-call results reachable only while the ENTRY that // carried their acts survives. Entries roll over at capacity while the receipt that points // at those results stays in the ring, then collapses to a pointer, then is checkpointed and diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs b/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs index 66271ac0f2..b834ea390b 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs @@ -29,5 +29,5 @@ const BODY: usize = 4_096; /// Shed `wm`'s resident bodies down to `budget` bytes, as the memory owner's reporter does, /// with every handle's saved output vouched for. fn shed(wm: &WorkingMemory, budget: usize) { - wm.evict_resident_results_over(budget as u64, &|_| true); + wm.evict_resident_results_over(budget as u64, &|_, _| true); } From 6e7c6e5b1cdf179853728873fcd352cbaa6ef84b Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 29 Oct 2026 16:25:33 -0500 Subject: [PATCH 3/4] A shed moves a body only once its saved copy is proven to load back to it Codex on #5595: vouching with `path.is_file()` counted an existing but unreadable or corrupt file as a safe copy, so the body left RAM and her view's later load rendered a pointer: the last copy was lost. - The spill owner gains the one read of a saved result (`spill::saved_whole`, the text her view's `load` renders, which now reads through it) and its digest (`WholeDigest`, `saved_digest`). - The shed plans from memory only, then reads and digests each planned candidate's copy outside the mind's lock; under the lock a body moves only if its record still names that handle and its digest matches. An unreadable copy or a mismatch keeps the body resident with the typed `LastCopy` probe (reason unreadable / mismatch). No filesystem access under the lock; `budget()` reads memory only. - The reporter's doc states plainly: swap-only pressure sheds nothing (`over_gate` returns 0), so this is not full governor coverage. Tests use real spill files: a copy with wrong content and a deleted copy keep their bodies resident while a good one moves and loads back to exactly what she read. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/context_streams/actions.rs | 6 +- .../src/cognition/context_streams/tests.rs | 2 +- .../mind_results_reporter.rs | 205 +++++++++--------- .../tests/mind_results_reporter.rs | 99 ++++++--- ..._told_when_her_hands_move_and_only_then.rs | 2 +- .../src/cognition/tool_executor/spill.rs | 27 +++ .../cognition/working_memory/action_log.rs | 17 +- .../src/cognition/working_memory/residency.rs | 11 +- .../cognition/working_memory/tests/custody.rs | 2 +- .../src/cognition/working_memory/tests/mod.rs | 2 +- 10 files changed, 225 insertions(+), 148 deletions(-) diff --git a/core/continuum-cognition/src/cognition/context_streams/actions.rs b/core/continuum-cognition/src/cognition/context_streams/actions.rs index fcc6ece6ef..913e5d1cc5 100644 --- a/core/continuum-cognition/src/cognition/context_streams/actions.rs +++ b/core/continuum-cognition/src/cognition/context_streams/actions.rs @@ -83,10 +83,8 @@ impl Source for Actions<'_> { let stored = item.stored.as_ref()?; let seq: u64 = item.key.parse().ok()?; let label = self.memory.action_whole_label(seq)?; - let path = crate::cognition::tool_executor::spill::resolve(self.persona, &stored.handle).ok()?; - let body = std::fs::read_to_string(path).ok()?; - // the record keeps its result trimmed (`record_receipt_inner`); loaded back, it reads the same - Some(ContextMessage::user(format!("{label}{}", body.trim()))) + let body = crate::cognition::tool_executor::spill::saved_whole(self.persona, &stored.handle).ok()?; + Some(ContextMessage::user(format!("{label}{body}"))) } /// Once she has acted, the void said earlier in this epoch is superseded, never edited: diff --git a/core/continuum-cognition/src/cognition/context_streams/tests.rs b/core/continuum-cognition/src/cognition/context_streams/tests.rs index 62b64ce156..39d9b5788c 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tests.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tests.rs @@ -96,7 +96,7 @@ fn an_evicted_result_is_still_seen_whole_through_its_stored_level() { memory.record_receipt_typed(&[], "the newest stays resident", None, pin.retain(persona, "the newest stays resident")); let (before, _) = memory.action_renderings(); let resident_whole = before.first().map(|act| act.1.clone()).expect("test: the first act"); - memory.evict_resident_results_over(1, &|_, _| true); + memory.evict_resident_results_over(1, &|_, _, _| true); let (acts, _) = memory.action_renderings(); let (seq, full, _, pointer, stored) = acts.first().cloned().expect("test: the first act"); let (chars, _) = stored.expect("evicted to its handle and priced"); diff --git a/core/continuum-cognition/src/cognition/persona_workspace/mind_results_reporter.rs b/core/continuum-cognition/src/cognition/persona_workspace/mind_results_reporter.rs index d550baa422..c65568d6e1 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/mind_results_reporter.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/mind_results_reporter.rs @@ -4,21 +4,23 @@ //! a number (Joel, 2026-10-29; it replaced `RESULTS_RESIDENT_CHARS = 1 << 20`, a cap per mind //! at receipt). This reporter is the only thing that moves a body to its handle in production //! (`WorkingMemory::evict_resident_results_over`). It sheds oldest-first across every resident -//! mind, public and private, and never moves the newest result of a mind or a body whose saved -//! output is not there to reload (the last copy). +//! mind, public and private, and never moves a mind's newest result or a body whose saved copy +//! is not PROVEN to load back to it (the last copy). //! //! Accounting is BYTES of resident bodies (`String::len`), never characters: characters are //! the view's price (`stored_chars`). Each record owns its body (no shared backing), so the sum //! over records is the RAM they hold; a working memory reached twice is counted once. //! -//! No filesystem access under a mind's lock: her candidates are read under it, each saved -//! output is checked after it drops, and the eviction moves only the `(seq, handle)` pairs that -//! check vouched for. +//! Proof without a filesystem read under a mind's lock: the shed plans from memory only, reads +//! each planned candidate's saved copy through the spill owner's one read (`spill::saved_whole`, +//! the same text her view's `load` renders) and digests it after the lock drops; under the lock +//! a body moves only if its record still names that handle and its digest matches. //! -//! Known limit: the shed target is the host's RAM overrun past this priority's gate, so a -//! level raised by swap activity alone, with RAM use under the gate, sheds nothing here. +//! NOT FULL GOVERNOR COVERAGE: the shed target is the host's RAM overrun past this priority's +//! gate (`over_gate`). Pressure raised by swap activity alone, with RAM use under the gate, +//! makes `over_gate` return 0 and sheds nothing here. -use std::path::PathBuf; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use continuum_kernel::system_resources::{ @@ -29,7 +31,8 @@ use tokio::sync::watch; use uuid::Uuid; use super::PersonaWorkspaceRegistry; -use crate::cognition::working_memory::{ResidentResults, WorkingMemory}; +use crate::cognition::tool_executor::spill::{self, WholeDigest}; +use crate::cognition::working_memory::{ResidentResults, ShedCandidate, WorkingMemory}; const NAME: &str = "mind_results"; @@ -42,32 +45,42 @@ const PRIORITY: MemoryPriority = MemoryPriority::Interactive; /// Why a body stays resident through a shed: it is the last copy of what she read. #[derive(Debug)] pub(crate) enum LastCopy { - /// The handle does not name an output this mind can resolve. - Unresolvable(std::io::Error), - /// The handle resolves, but its saved output is not there to reload. - Missing(PathBuf), + /// Its saved copy could not be read back (no such handle, no file, no permission, not text). + Unreadable(std::io::Error), + /// Its saved copy reads back, but not to this body. + Mismatch, } -impl std::fmt::Display for LastCopy { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl LastCopy { + fn reason(&self) -> &'static str { match self { - Self::Unresolvable(error) => write!(f, "handle does not resolve: {error}"), - Self::Missing(path) => write!(f, "saved output missing at {}", path.display()), + Self::Unreadable(_) => "unreadable", + Self::Mismatch => "mismatch", } } -} -/// Whether `persona`'s saved output for `handle` is there to reload, so its body may leave RAM. -pub(crate) fn saved_output(persona: Uuid, handle: &str) -> Result<(), LastCopy> { - let path = crate::cognition::tool_executor::spill::resolve(persona, handle) - .map_err(LastCopy::Unresolvable)?; - if path.is_file() { - Ok(()) - } else { - Err(LastCopy::Missing(path)) + fn probe(&self, persona: Uuid, handle: &str) { + let detail = match self { + Self::Unreadable(error) => error.to_string(), + Self::Mismatch => "its saved copy does not load back to the resident body".to_owned(), + }; + continuum_base::probe!( + class = "wm.results.last_copy_kept", + persona_id = %persona, + handle = %handle, + reason = self.reason(), + detail = %detail, + "a resident result stays through a shed: its saved copy cannot reproduce it" + ); } } +/// What `persona`'s saved copy for `handle` loads back to, as a digest: read outside every +/// mind's lock, compared with the resident body under it. +fn saved_copy(persona: Uuid, handle: &str) -> Result { + spill::saved_digest(persona, handle).map_err(LastCopy::Unreadable) +} + /// The resident minds the reporter accounts: `(persona, working memory)`, each memory once. pub(crate) type Minds = Vec<(Uuid, Arc)>; @@ -112,46 +125,36 @@ pub(crate) fn over_gate(snapshot: &PressureSnapshot) -> u64 { used.saturating_sub(gate) } -/// One mind's resident result bodies as the memory owner accounts them: what a shed may move -/// (its saved output vouched for, outside her lock) and what it may not. +/// One mind's resident result bodies, read from memory alone: what a shed may plan to move +/// (saved, not the newest) and what it may not. #[derive(Debug, Clone)] pub(crate) struct Residency { pub resident_bytes: u64, - /// The newest result and every last copy: what no shed may move. + /// The newest result and every unsaved body. A saved copy that fails its proof at shed + /// time stays too; that is found only then, by reading it. pub pinned_bytes: u64, - /// Vouched candidates, oldest first. - pub evictable: Vec, + /// Saved candidates, oldest first. + pub evictable: Vec, } -/// Read `memory`'s candidates under her lock, then vouch for each saved output after it drops. -pub(crate) fn residency( - persona: Uuid, - memory: &WorkingMemory, - saved: &dyn Fn(Uuid, &str) -> bool, -) -> Residency { +pub(crate) fn residency(memory: &WorkingMemory) -> Residency { let ResidentResults { resident_bytes, candidates, } = memory.resident_results(); - let evictable: Vec<_> = candidates - .into_iter() - .filter(|candidate| saved(persona, &candidate.handle)) - .collect(); - let movable: u64 = evictable.iter().map(|candidate| candidate.bytes).sum(); + let movable: u64 = candidates.iter().map(|candidate| candidate.bytes).sum(); Residency { resident_bytes, pinned_bytes: resident_bytes - movable, - evictable, + evictable: candidates, } } -/// Per mind, the bytes to keep resident so the total comes down to `allocation`, moving the -/// oldest bodies across every mind first (`None`: leave that mind untouched). Within a mind -/// the oldest received are the lowest `seq`, so each budget moves exactly that mind's chosen -/// oldest bodies through `evict_resident_results_over`. -pub(crate) fn plan_shed(minds: &[Residency], allocation: u64) -> Vec> { +/// Per mind, the candidates to move so the total comes down to `allocation`, the oldest +/// received across every mind first. +pub(crate) fn plan_shed(minds: &[Residency], allocation: u64) -> Vec> { let total: u64 = minds.iter().map(|mind| mind.resident_bytes).sum(); - let mut freed = vec![0u64; minds.len()]; + let mut chosen = vec![HashSet::new(); minds.len()]; if total > allocation { let mut candidates: Vec<(Option, u64, usize, u64)> = minds .iter() @@ -159,63 +162,68 @@ pub(crate) fn plan_shed(minds: &[Residency], allocation: u64) -> Vec .flat_map(|(index, mind)| { mind.evictable .iter() - .map(move |r| (r.received_ms, r.seq, index, r.bytes)) + .map(move |c| (c.received_ms, c.seq, index, c.bytes)) }) .collect(); candidates.sort_unstable(); let mut need = total - allocation; - for (_, _, index, bytes) in candidates { + for (_, seq, index, bytes) in candidates { if need == 0 { break; } - freed[index] += bytes; + chosen[index].insert(seq); need = need.saturating_sub(bytes); } } - minds - .iter() - .zip(freed) - .map(|(mind, freed)| (freed > 0).then(|| mind.resident_bytes - freed)) - .collect() -} - -/// Shed every mind's resident bodies down to `allocation` bytes in total, oldest first. -/// `saved` vouches that a persona's handle has its output there to reload. -pub(crate) fn shed_to(minds: &Minds, allocation: u64, saved: &dyn Fn(Uuid, &str) -> bool) { - let residencies: Vec = minds - .iter() - .map(|(persona, memory)| residency(*persona, memory, saved)) - .collect(); - let budgets = plan_shed(&residencies, allocation); - for (((_, memory), mind), budget) in minds.iter().zip(&residencies).zip(budgets) { - if let Some(budget) = budget { - // Only what was vouched for, and only if the record still names that handle. - let vouched: std::collections::HashMap = mind - .evictable - .iter() - .map(|candidate| (candidate.seq, candidate.handle.as_str())) - .collect(); - memory.evict_resident_results_over(budget, &|seq, handle| { - vouched.get(&seq).is_some_and(|vouched| *vouched == handle) - }); - } - } + chosen } -/// `saved` for production: a body whose output is not there stays, and says why. -fn vouched(persona: Uuid, handle: &str) -> bool { - match saved_output(persona, handle) { - Ok(()) => true, - Err(last_copy) => { - continuum_base::probe!( - class = "wm.results.last_copy_kept", - persona_id = %persona, - handle = %handle, - reason = %last_copy, - "a resident result stays through a shed: its saved output is not there to reload" - ); - false +/// Shed every mind's resident bodies down to `allocation` bytes in total, oldest first. Each +/// planned body moves only once its saved copy is proven to load back to it; a copy that +/// cannot keeps the body resident and says why (`LastCopy`). +pub(crate) fn shed_to(minds: &Minds, allocation: u64) { + let residencies: Vec = minds.iter().map(|(_, memory)| residency(memory)).collect(); + let plans = plan_shed(&residencies, allocation); + for (((persona, memory), mind), chosen) in minds.iter().zip(&residencies).zip(plans) { + if chosen.is_empty() { + continue; } + // Outside her lock: read and digest each planned copy. + let proven: HashMap = mind + .evictable + .iter() + .filter(|candidate| chosen.contains(&candidate.seq)) + .filter_map(|candidate| match saved_copy(*persona, &candidate.handle) { + Ok(digest) => Some((candidate.seq, (candidate.handle.as_str(), digest))), + Err(last_copy) => { + last_copy.probe(*persona, &candidate.handle); + None + } + }) + .collect(); + let movable: u64 = mind + .evictable + .iter() + .filter(|c| proven.contains_key(&c.seq)) + .map(|c| c.bytes) + .sum(); + // Under her lock: only a record still naming the proven handle, whose body matches. + memory.evict_resident_results_over( + mind.resident_bytes.saturating_sub(movable), + &|seq, handle, body| { + let Some((proven_handle, digest)) = proven.get(&seq) else { + return false; + }; + if *proven_handle != handle { + return false; + } + let reproduces = WholeDigest::of(body) == *digest; + if !reproduces { + LastCopy::Mismatch.probe(*persona, handle); + } + reproduces + }, + ); } } @@ -243,16 +251,15 @@ impl MemoryReporter for MindResultsReporter { } /// It wants to keep everything it holds (`preferred = max = resident`); its floor is what - /// no shed may move (each mind's newest result and every last copy). + /// no shed may move (each mind's newest result and every unsaved body). Read from memory + /// alone: a saved copy that fails its proof is found only when a shed reads it. fn budget(&self) -> MemoryBudgetSpec { let minds = self.registry.resident_working_memories(); let (resident, pinned) = minds .iter() - .fold((0u64, 0u64), |(resident, pinned), (persona, memory)| { - let mind = residency(*persona, memory, &|persona, handle| { - saved_output(persona, handle).is_ok() - }); + .fold((0u64, 0u64), |(resident, pinned), (_, memory)| { + let mind = residency(memory); (resident + mind.resident_bytes, pinned + mind.pinned_bytes) }); MemoryBudgetSpec { @@ -290,7 +297,7 @@ impl MemoryReporter for MindResultsReporter { } let minds = self.registry.resident_working_memories(); let before = resident_bytes(&minds); - shed_to(&minds, before.saturating_sub(over), &vouched); + shed_to(&minds, before.saturating_sub(over)); continuum_base::probe!( class = "wm.results.shed", level = %level, diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs index 52819a2d1b..08354423e6 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs @@ -7,65 +7,70 @@ use crate::ai::types::ResultCustody; use crate::cognition::persona_workspace::mind_results_reporter::{ over_gate, resident_bytes, shed_to, Minds, }; +use crate::cognition::tool_executor::spill::{self, LivePin}; use crate::cognition::working_memory::WorkingMemory; /// A test body's size in bytes; production has no such number (the memory owner sheds). const BODY: usize = 1_000; +fn body(name: &str) -> String { + format!("{name}{}", "b".repeat(BODY - name.len())) +} + fn receipt(memory: &WorkingMemory, name: &str, custody: ResultCustody) { - memory.record_receipt_typed( - &[], - &format!("{name}{}", "b".repeat(BODY - name.len())), - None, - custody, - ); + memory.record_receipt_typed(&[], &body(name), None, custody); // Distinct receipt times, so "oldest across minds" is the order they were received in. std::thread::sleep(std::time::Duration::from_millis(2)); } +/// Record `name` saved for real through the spill owner; its handle. +fn kept(memory: &WorkingMemory, persona: Uuid, pin: &LivePin, name: &str) -> String { + let custody = pin.retain(persona, &body(name)); + let handle = custody.handle().expect("test: saved").to_owned(); + receipt(memory, name, custody); + handle +} + fn saved(handle: &str) -> ResultCustody { ResultCustody::Whole { handle: handle.into(), } } -/// Which of a mind's results are resident, by handle (`unsaved` for none). +/// Which of a mind's results are resident, by the name each body starts with. fn resident(memory: &WorkingMemory) -> Vec { memory .snapshot() .actions .iter() - .filter(|r| r.result.is_some()) - .map(|r| r.handle.clone().unwrap_or_else(|| "unsaved".into())) + .filter_map(|r| r.result.as_ref().map(|body| body[..2].to_owned())) .collect() } // what this catches: a shed that moves the wrong bodies. It must take the OLDEST received // across every mind (not each mind's oldest in turn), stop at the allocation, and never move a -// mind's newest result, an unsaved one, or one whose saved output is missing (the last copy). -// A moved body keeps its handle and its measured length, so her view still reloads its whole. +// mind's newest result or an unsaved one. A moved body keeps its handle and its measured +// length, and its saved copy loads back to exactly what she read. #[test] -fn the_shed_moves_the_oldest_across_minds_down_to_the_allocation_and_keeps_last_copies() { +fn the_shed_moves_the_oldest_across_minds_down_to_the_allocation() { + let (pa, pb) = (Uuid::new_v4(), Uuid::new_v4()); + let pin = LivePin::new(); let (a, b) = ( Arc::new(WorkingMemory::new(8)), Arc::new(WorkingMemory::new(8)), ); - receipt(&a, "a1", saved("a1")); + kept(&a, pa, &pin, "a1"); receipt(&b, "b1", ResultCustody::Unsaved); - receipt(&b, "b2", saved("b2")); - receipt(&b, "b3", saved("missing")); - receipt(&a, "a2", saved("a2")); - receipt(&b, "b4", saved("b4")); - receipt(&a, "a3", saved("a3")); - let minds: Minds = vec![ - (Uuid::new_v4(), Arc::clone(&a)), - (Uuid::new_v4(), Arc::clone(&b)), - ]; - let vouched = |_: Uuid, handle: &str| handle != "missing"; + let b2 = kept(&b, pb, &pin, "b2"); + kept(&b, pb, &pin, "b3"); + kept(&a, pa, &pin, "a2"); + kept(&b, pb, &pin, "b4"); + kept(&a, pa, &pin, "a3"); + let minds: Minds = vec![(pa, Arc::clone(&a)), (pb, Arc::clone(&b))]; let total = resident_bytes(&minds); assert_eq!(total, 7 * BODY as u64, "precondition: every body resident"); - shed_to(&minds, total - 2 * BODY as u64, &vouched); + shed_to(&minds, total - 2 * BODY as u64); assert_eq!( resident_bytes(&minds), 5 * BODY as u64, @@ -74,28 +79,64 @@ fn the_shed_moves_the_oldest_across_minds_down_to_the_allocation_and_keeps_last_ assert_eq!(resident(&a), ["a2", "a3"], "a1 was the oldest received"); assert_eq!( resident(&b), - ["unsaved", "missing", "b4"], + ["b1", "b3", "b4"], "b2 was next, before a2, though a2 is a's oldest left" ); let moved = b .snapshot() .actions .into_iter() - .find(|r| r.handle.as_deref() == Some("b2")) + .find(|r| r.handle.as_deref() == Some(b2.as_str())) .expect("test: b2 kept its record"); assert_eq!( moved.stored_chars, Some(BODY), "a moved body keeps its measured length" ); + assert_eq!( + spill::saved_whole(pb, &b2).expect("test: b2 loads"), + body("b2"), + "and loads back to what she read" + ); - shed_to(&minds, 0, &vouched); + shed_to(&minds, 0); assert_eq!(resident(&a), ["a3"], "a's newest stays"); assert_eq!( resident(&b), - ["unsaved", "missing", "b4"], - "unsaved, unreloadable and newest stay through any shed" + ["b1", "b4"], + "unsaved and newest stay through any shed" + ); +} + +// what this catches (Codex on #5595): a saved copy counted as safe because its FILE EXISTS. A +// file that is there but does not load back to the body (wrong content), or is gone, is not a +// copy: moving the body would lose the last one, and her view's load would render a pointer. +// Real files through the spill owner, never an injected verdict. +#[test] +fn a_copy_that_cannot_reproduce_the_body_keeps_it_resident() { + let persona = Uuid::new_v4(); + let pin = LivePin::new(); + let memory = Arc::new(WorkingMemory::new(8)); + let wrong = kept(&memory, persona, &pin, "c1"); + let gone = kept(&memory, persona, &pin, "c2"); + kept(&memory, persona, &pin, "c3"); + kept(&memory, persona, &pin, "c4"); + std::fs::write( + spill::resolve(persona, &wrong).expect("test: path"), + "not what she read", + ) + .expect("test: overwrite"); + std::fs::remove_file(spill::resolve(persona, &gone).expect("test: path")) + .expect("test: remove"); + let minds: Minds = vec![(persona, Arc::clone(&memory))]; + + shed_to(&minds, 0); + assert_eq!( + resident(&memory), + ["c1", "c2", "c4"], + "wrong content and a missing file keep their bodies; c3 moved" ); + assert_eq!(resident_bytes(&minds), 3 * BODY as u64); } // what this catches: the memory owner reading a wrong total, so it sheds too little or too diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs index 7af2838e13..67f8361ec6 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs @@ -198,7 +198,7 @@ use super::*; memory.record_receipt_typed(&[], &"s".repeat(cap / 2), None, saved("5000000000000002")); } memory.record_settlement("done", None); - memory.evict_resident_results_over(0, &|_, _| true); + memory.evict_resident_results_over(0, &|_, _, _| true); let persisted = PersistedVolatile { wm: memory.snapshot(), own_speech: OwnSpeechPersisted::ByRoom(Vec::new()), diff --git a/core/continuum-cognition/src/cognition/tool_executor/spill.rs b/core/continuum-cognition/src/cognition/tool_executor/spill.rs index d3fb04d9ad..731d4abf12 100644 --- a/core/continuum-cognition/src/cognition/tool_executor/spill.rs +++ b/core/continuum-cognition/src/cognition/tool_executor/spill.rs @@ -326,6 +326,33 @@ pub fn resolve(persona_id: Uuid, handle: &str) -> std::io::Result { resolve_in(&spill_root()?, persona_id, handle) } +/// THE read of a saved result as her view loads it back: the saved output, trimmed as the +/// record keeps its result (`record_receipt_inner`). Her view's `load` and the memory owner's +/// shed both read through here, so "verified" means "loads back to this text". +pub fn saved_whole(persona_id: Uuid, handle: &str) -> std::io::Result { + let text = fs::read_to_string(resolve(persona_id, handle)?)?; + Ok(text.trim().to_owned()) +} + +/// A whole's content address for comparing a resident body with its saved copy without +/// holding both in RAM (SHA-256 of the text). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct WholeDigest([u8; 32]); + +impl WholeDigest { + pub fn of(text: &str) -> Self { + let mut digest = [0u8; 32]; + digest.copy_from_slice(&Sha256::digest(text.as_bytes())); + Self(digest) + } +} + +/// The digest of what `persona_id`'s saved output for `handle` loads back to +/// ([`saved_whole`]). A resident body whose digest matches is reproduced by its copy. +pub fn saved_digest(persona_id: Uuid, handle: &str) -> std::io::Result { + Ok(WholeDigest::of(&saved_whole(persona_id, handle)?)) +} + // ── root-injected cores (the filesystem seam; unit-tested against a tempdir so // tests never pollute ~/.continuum — the isolation lesson of task #7) ────── diff --git a/core/continuum-cognition/src/cognition/working_memory/action_log.rs b/core/continuum-cognition/src/cognition/working_memory/action_log.rs index ae20c819e2..756de8fdac 100644 --- a/core/continuum-cognition/src/cognition/working_memory/action_log.rs +++ b/core/continuum-cognition/src/cognition/working_memory/action_log.rs @@ -157,17 +157,20 @@ impl ActionLog { } /// The records a shed may move to their handles, oldest first: resident, saved, not the - /// newest result, and vouched for by `saved(seq, handle)` (its output is there to reload). - /// Everything else is the last copy of what she read, so it stays. + /// newest result, and vouched for by `saved(seq, handle, body)` (its saved copy loads back + /// to this body). Everything else is the last copy of what she read, so it stays. Lazy: + /// `saved` runs only for the records a caller actually takes. pub fn evictable<'a>( &'a self, - saved: &'a dyn Fn(u64, &str) -> bool, + saved: &'a dyn Fn(u64, &str, &str) -> bool, ) -> impl Iterator + 'a { let newest = self.retained().last().map(|record| record.seq); self.records.iter().filter(move |record| { - record.result.is_some() - && Some(record.seq) != newest - && record.handle.as_deref().is_some_and(|handle| saved(record.seq, handle)) + Some(record.seq) != newest + && match (&record.result, &record.handle) { + (Some(body), Some(handle)) => saved(record.seq, handle, body), + _ => false, + } }) } @@ -175,7 +178,7 @@ impl ActionLog { /// resident. Each keeps its measured length (`stored_chars`) and its handle, so her view /// still prices and reloads its whole. Exactly to the budget: the memory owner decides /// when, so there is no hysteresis here. - pub fn collapse_over(&mut self, budget: u64, saved: &dyn Fn(u64, &str) -> bool) -> Collapsed { + pub fn collapse_over(&mut self, budget: u64, saved: &dyn Fn(u64, &str, &str) -> bool) -> Collapsed { let mut total = self.resident_bytes(); if total <= budget { return Collapsed { total }; diff --git a/core/continuum-cognition/src/cognition/working_memory/residency.rs b/core/continuum-cognition/src/cognition/working_memory/residency.rs index 530f4f0561..a3b62fd108 100644 --- a/core/continuum-cognition/src/cognition/working_memory/residency.rs +++ b/core/continuum-cognition/src/cognition/working_memory/residency.rs @@ -42,7 +42,7 @@ impl WorkingMemory { pub(crate) fn resident_results(&self) -> ResidentResults { let actions = self.actions.lock(); let candidates = actions - .evictable(&|_, _| true) + .evictable(&|_, _, _| true) .filter_map(|record| { Some(ShedCandidate { received_ms: record.received_ms, @@ -59,14 +59,15 @@ impl WorkingMemory { } /// THE eviction verb: move the oldest saved bodies to their handles until at most `budget` - /// bytes stay resident. Only the memory owner's shed calls it in production, with `saved` - /// answering from the `(seq, handle)` pairs it vouched for outside the lock, so a record - /// that changed since (a different handle, or gone) is not moved. The newest stays, and + /// bytes stay resident. Only the memory owner's shed calls it in production, with + /// `saved(seq, handle, body)` answering from what it read outside the lock (each saved copy's + /// digest), so a record that changed since, or whose copy does not reproduce its body, is + /// not moved. No filesystem access happens under the lock. The newest stays, and /// past the budget after that the overrun is reported, never forced. pub(crate) fn evict_resident_results_over( &self, budget: u64, - saved: &dyn Fn(u64, &str) -> bool, + saved: &dyn Fn(u64, &str, &str) -> bool, ) { let total = self.actions.lock().collapse_over(budget, saved).total; self.publish_live_handles(); diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs index 52f119b7ca..e9b66fdadd 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs @@ -179,7 +179,7 @@ fn a_shed_moves_only_the_records_it_vouched_for() { wm.record_receipt_typed(&[], "newest", None, saved("vouched-c")); let seq_of = |h: &str| wm.snapshot().actions.iter().find(|r| r.handle.as_deref() == Some(h)).map(|r| r.seq).expect("test: seq"); let (a, b) = (seq_of("vouched-a"), seq_of("vouched-b")); - wm.evict_resident_results_over(0, &|seq, handle| (seq == a && handle == "a-changed") || (seq == b && handle == "vouched-b")); + wm.evict_resident_results_over(0, &|seq, handle, _| (seq == a && handle == "a-changed") || (seq == b && handle == "vouched-b")); let resident: Vec<_> = wm.snapshot().actions.into_iter().filter(|r| r.result.is_some()).filter_map(|r| r.handle).collect(); assert_eq!(resident, ["vouched-a", "vouched-c"], "a changed since it was vouched for; only b moved"); } diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs b/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs index b834ea390b..eceeb98489 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs @@ -29,5 +29,5 @@ const BODY: usize = 4_096; /// Shed `wm`'s resident bodies down to `budget` bytes, as the memory owner's reporter does, /// with every handle's saved output vouched for. fn shed(wm: &WorkingMemory, budget: usize) { - wm.evict_resident_results_over(budget as u64, &|_, _| true); + wm.evict_resident_results_over(budget as u64, &|_, _, _| true); } From 1609fafa56db1b7bd60b9b362e63b4af114cbf4a Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 29 Oct 2026 16:28:00 -0500 Subject: [PATCH 4/4] Saved copies are proven once at shed time and cached; budget() never touches the filesystem Cormac on #5595: budget() stat'ed every resident record of every mind, and the monitor calls it under its reporters lock on every snapshot. - Proof at shed time only: each candidate's body is copied out (her lock held only for the copy) and compared with what its saved copy loads back to (`spill::reproduces`, through the one read her view's `load` uses). A proven (persona, handle) is cached in the reporter; the output is content-addressed and live-protected while a record names it. The cache is pruned at each shed to the handles still resident. - budget() reads only that cache: an unproven body counts as pinned in min_bytes. - Only proven bodies are planned and moved; the eviction re-checks (seq, handle) under the lock. Drops the digest from the previous commit (no hashing under the lock). Tests (real spill files): a truncated write and wrong content prove LastCopy::Mismatch (the probe's reason "mismatch"), a missing file LastCopy::Unreadable, and all three keep their bodies through a shed; with the spill dir deleted after a shed, budget() answers from the cache (min = only the newest pinned). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/context_streams/tests.rs | 2 +- .../mind_results_reporter.rs | 188 +++++++++++------- .../tests/mind_results_reporter.rs | 105 ++++++++-- ..._told_when_her_hands_move_and_only_then.rs | 2 +- .../src/cognition/tool_executor/spill.rs | 24 +-- .../cognition/working_memory/action_log.rs | 17 +- .../src/cognition/working_memory/residency.rs | 21 +- .../cognition/working_memory/tests/custody.rs | 2 +- .../src/cognition/working_memory/tests/mod.rs | 2 +- 9 files changed, 239 insertions(+), 124 deletions(-) diff --git a/core/continuum-cognition/src/cognition/context_streams/tests.rs b/core/continuum-cognition/src/cognition/context_streams/tests.rs index 39d9b5788c..62b64ce156 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tests.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tests.rs @@ -96,7 +96,7 @@ fn an_evicted_result_is_still_seen_whole_through_its_stored_level() { memory.record_receipt_typed(&[], "the newest stays resident", None, pin.retain(persona, "the newest stays resident")); let (before, _) = memory.action_renderings(); let resident_whole = before.first().map(|act| act.1.clone()).expect("test: the first act"); - memory.evict_resident_results_over(1, &|_, _, _| true); + memory.evict_resident_results_over(1, &|_, _| true); let (acts, _) = memory.action_renderings(); let (seq, full, _, pointer, stored) = acts.first().cloned().expect("test: the first act"); let (chars, _) = stored.expect("evicted to its handle and priced"); diff --git a/core/continuum-cognition/src/cognition/persona_workspace/mind_results_reporter.rs b/core/continuum-cognition/src/cognition/persona_workspace/mind_results_reporter.rs index c65568d6e1..e4409817f3 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/mind_results_reporter.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/mind_results_reporter.rs @@ -11,10 +11,12 @@ //! the view's price (`stored_chars`). Each record owns its body (no shared backing), so the sum //! over records is the RAM they hold; a working memory reached twice is counted once. //! -//! Proof without a filesystem read under a mind's lock: the shed plans from memory only, reads -//! each planned candidate's saved copy through the spill owner's one read (`spill::saved_whole`, -//! the same text her view's `load` renders) and digests it after the lock drops; under the lock -//! a body moves only if its record still names that handle and its digest matches. +//! Proof, once per saved copy, never under a mind's lock and never in `budget()`: at shed time +//! each candidate's body is copied out (the lock held only for the copy) and compared with what +//! its saved copy loads back to through the spill owner's one read (`spill::reproduces`, the +//! same text her view's `load` renders). A proven `(persona, handle)` is cached: the output is +//! content-addressed and live-protected while a record names it, so the proof holds. Only +//! proven bodies are planned and moved; an unproven one counts as pinned. //! //! NOT FULL GOVERNOR COVERAGE: the shed target is the host's RAM overrun past this priority's //! gate (`over_gate`). Pressure raised by swap activity alone, with RAM use under the gate, @@ -23,6 +25,8 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; +use parking_lot::Mutex; + use continuum_kernel::system_resources::{ MemoryBudgetSpec, MemoryPriority, MemoryReporter, ModuleMemoryReport, PressureLevel, PressureSnapshot, @@ -31,7 +35,7 @@ use tokio::sync::watch; use uuid::Uuid; use super::PersonaWorkspaceRegistry; -use crate::cognition::tool_executor::spill::{self, WholeDigest}; +use crate::cognition::tool_executor::spill; use crate::cognition::working_memory::{ResidentResults, ShedCandidate, WorkingMemory}; const NAME: &str = "mind_results"; @@ -52,7 +56,7 @@ pub(crate) enum LastCopy { } impl LastCopy { - fn reason(&self) -> &'static str { + pub(crate) fn reason(&self) -> &'static str { match self { Self::Unreadable(_) => "unreadable", Self::Mismatch => "mismatch", @@ -75,10 +79,30 @@ impl LastCopy { } } -/// What `persona`'s saved copy for `handle` loads back to, as a digest: read outside every -/// mind's lock, compared with the resident body under it. -fn saved_copy(persona: Uuid, handle: &str) -> Result { - spill::saved_digest(persona, handle).map_err(LastCopy::Unreadable) +/// Prove `candidate`'s saved copy loads back to exactly its resident body. `None` when the +/// record moved on since it was read (nothing to prove). Reads the file with no lock held. +pub(crate) fn prove( + persona: Uuid, + memory: &WorkingMemory, + candidate: &ShedCandidate, +) -> Option> { + let body = memory.resident_body(candidate.seq, &candidate.handle)?; + Some(match spill::reproduces(persona, &candidate.handle, &body) { + Ok(true) => Ok(()), + Ok(false) => Err(LastCopy::Mismatch), + Err(error) => Err(LastCopy::Unreadable(error)), + }) +} + +/// The saved copies proven to reproduce their resident bodies, per `(persona, handle)`. Pruned +/// at every shed to the candidates that still exist, so it never outgrows what is resident. +#[derive(Debug, Default)] +pub(crate) struct ProvenCopies(HashSet<(Uuid, String)>); + +impl ProvenCopies { + pub(crate) fn contains(&self, persona: Uuid, handle: &str) -> bool { + self.0.contains(&(persona, handle.to_owned())) + } } /// The resident minds the reporter accounts: `(persona, working memory)`, each memory once. @@ -125,28 +149,52 @@ pub(crate) fn over_gate(snapshot: &PressureSnapshot) -> u64 { used.saturating_sub(gate) } -/// One mind's resident result bodies, read from memory alone: what a shed may plan to move -/// (saved, not the newest) and what it may not. +/// One mind's resident result bodies: what a shed may move (saved, not the newest, and its +/// copy proven) and what it may not. #[derive(Debug, Clone)] pub(crate) struct Residency { pub resident_bytes: u64, - /// The newest result and every unsaved body. A saved copy that fails its proof at shed - /// time stays too; that is found only then, by reading it. + /// The newest result, every unsaved body, and every body whose copy is not proven yet. pub pinned_bytes: u64, - /// Saved candidates, oldest first. + /// Proven candidates, oldest first. pub evictable: Vec, } -pub(crate) fn residency(memory: &WorkingMemory) -> Residency { +/// `memory`'s residency against the proofs in hand: memory only, no filesystem access. +pub(crate) fn residency(persona: Uuid, memory: &WorkingMemory, proven: &ProvenCopies) -> Residency { let ResidentResults { resident_bytes, candidates, } = memory.resident_results(); - let movable: u64 = candidates.iter().map(|candidate| candidate.bytes).sum(); + let evictable: Vec = candidates + .into_iter() + .filter(|candidate| proven.contains(persona, &candidate.handle)) + .collect(); + let movable: u64 = evictable.iter().map(|candidate| candidate.bytes).sum(); Residency { resident_bytes, pinned_bytes: resident_bytes - movable, - evictable: candidates, + evictable, + } +} + +/// What the reporter declares: everything resident preferred, the unprovable floor as minimum. +/// Reads the proof cache only: the monitor calls this under its reporters lock. +pub(crate) fn budget_of(minds: &Minds, proven: &Mutex) -> MemoryBudgetSpec { + let proven = proven.lock(); + let (resident, pinned) = + minds + .iter() + .fold((0u64, 0u64), |(resident, pinned), (persona, memory)| { + let mind = residency(*persona, memory, &proven); + (resident + mind.resident_bytes, pinned + mind.pinned_bytes) + }); + MemoryBudgetSpec { + name: NAME.to_string(), + priority: PRIORITY, + min_bytes: pinned, + preferred_bytes: resident, + max_bytes: resident, } } @@ -178,50 +226,64 @@ pub(crate) fn plan_shed(minds: &[Residency], allocation: u64) -> Vec = minds.iter().map(|(_, memory)| residency(memory)).collect(); +/// Prove every saved candidate not proven yet, each with no lock held across its read; a copy +/// that cannot reproduce its body stays unproven and says why (`LastCopy`). Then forget proofs +/// for handles no longer resident anywhere. +fn prove_candidates(minds: &Minds, proven: &Mutex) { + let mut resident: HashSet<(Uuid, String)> = HashSet::new(); + for (persona, memory) in minds { + for candidate in memory.resident_results().candidates { + let key = (*persona, candidate.handle.clone()); + if !proven.lock().0.contains(&key) { + match prove(*persona, memory, &candidate) { + Some(Ok(())) => { + proven.lock().0.insert(key.clone()); + } + Some(Err(last_copy)) => last_copy.probe(*persona, &candidate.handle), + None => {} + } + } + resident.insert(key); + } + } + proven.lock().0.retain(|key| resident.contains(key)); +} + +/// Shed every mind's resident bodies down to `allocation` bytes in total, oldest first, moving +/// only bodies whose saved copy is proven to load back to them. +pub(crate) fn shed_to(minds: &Minds, allocation: u64, proven: &Mutex) { + prove_candidates(minds, proven); + let residencies: Vec = { + let proven = proven.lock(); + minds + .iter() + .map(|(persona, memory)| residency(*persona, memory, &proven)) + .collect() + }; let plans = plan_shed(&residencies, allocation); - for (((persona, memory), mind), chosen) in minds.iter().zip(&residencies).zip(plans) { + for (((_, memory), mind), chosen) in minds.iter().zip(&residencies).zip(plans) { if chosen.is_empty() { continue; } - // Outside her lock: read and digest each planned copy. - let proven: HashMap = mind + let handles: HashMap = mind .evictable .iter() .filter(|candidate| chosen.contains(&candidate.seq)) - .filter_map(|candidate| match saved_copy(*persona, &candidate.handle) { - Ok(digest) => Some((candidate.seq, (candidate.handle.as_str(), digest))), - Err(last_copy) => { - last_copy.probe(*persona, &candidate.handle); - None - } - }) + .map(|candidate| (candidate.seq, candidate.handle.as_str())) .collect(); let movable: u64 = mind .evictable .iter() - .filter(|c| proven.contains_key(&c.seq)) + .filter(|c| handles.contains_key(&c.seq)) .map(|c| c.bytes) .sum(); - // Under her lock: only a record still naming the proven handle, whose body matches. + // Under her lock: only a planned record still naming its proven handle. memory.evict_resident_results_over( mind.resident_bytes.saturating_sub(movable), - &|seq, handle, body| { - let Some((proven_handle, digest)) = proven.get(&seq) else { - return false; - }; - if *proven_handle != handle { - return false; - } - let reproduces = WholeDigest::of(body) == *digest; - if !reproduces { - LastCopy::Mismatch.probe(*persona, handle); - } - reproduces + &|seq, handle| { + handles + .get(&seq) + .is_some_and(|proven_handle| *proven_handle == handle) }, ); } @@ -234,6 +296,8 @@ pub struct MindResultsReporter { /// The monitor's published snapshot: `shed_load` runs right after it is published, so this /// is the poll that decided to shed. pressure: watch::Receiver, + /// Saved copies proven at shed time; `budget()` reads only this. + proven: Mutex, } impl MindResultsReporter { @@ -241,7 +305,11 @@ impl MindResultsReporter { registry: Arc, pressure: watch::Receiver, ) -> Self { - Self { registry, pressure } + Self { + registry, + pressure, + proven: Mutex::new(ProvenCopies::default()), + } } } @@ -250,25 +318,11 @@ impl MemoryReporter for MindResultsReporter { NAME } - /// It wants to keep everything it holds (`preferred = max = resident`); its floor is what - /// no shed may move (each mind's newest result and every unsaved body). Read from memory - /// alone: a saved copy that fails its proof is found only when a shed reads it. + /// It wants to keep everything it holds (`preferred = max = resident`); its floor is what no + /// shed may move yet: each mind's newest result, every unsaved body, and every body whose + /// copy is not proven. No filesystem access: proofs are made at shed time and cached. fn budget(&self) -> MemoryBudgetSpec { - let minds = self.registry.resident_working_memories(); - let (resident, pinned) = - minds - .iter() - .fold((0u64, 0u64), |(resident, pinned), (_, memory)| { - let mind = residency(memory); - (resident + mind.resident_bytes, pinned + mind.pinned_bytes) - }); - MemoryBudgetSpec { - name: NAME.to_string(), - priority: PRIORITY, - min_bytes: pinned, - preferred_bytes: resident, - max_bytes: resident, - } + budget_of(&self.registry.resident_working_memories(), &self.proven) } fn report(&self) -> ModuleMemoryReport { @@ -297,7 +351,7 @@ impl MemoryReporter for MindResultsReporter { } let minds = self.registry.resident_working_memories(); let before = resident_bytes(&minds); - shed_to(&minds, before.saturating_sub(over)); + shed_to(&minds, before.saturating_sub(over), &self.proven); continuum_base::probe!( class = "wm.results.shed", level = %level, diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs index 08354423e6..7b783fcea1 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/mind_results_reporter.rs @@ -5,10 +5,11 @@ use uuid::Uuid; use crate::ai::types::ResultCustody; use crate::cognition::persona_workspace::mind_results_reporter::{ - over_gate, resident_bytes, shed_to, Minds, + budget_of, over_gate, prove, resident_bytes, shed_to, LastCopy, Minds, ProvenCopies, }; use crate::cognition::tool_executor::spill::{self, LivePin}; use crate::cognition::working_memory::WorkingMemory; +use parking_lot::Mutex; /// A test body's size in bytes; production has no such number (the memory owner sheds). const BODY: usize = 1_000; @@ -67,10 +68,11 @@ fn the_shed_moves_the_oldest_across_minds_down_to_the_allocation() { kept(&b, pb, &pin, "b4"); kept(&a, pa, &pin, "a3"); let minds: Minds = vec![(pa, Arc::clone(&a)), (pb, Arc::clone(&b))]; + let proven = Mutex::new(ProvenCopies::default()); let total = resident_bytes(&minds); assert_eq!(total, 7 * BODY as u64, "precondition: every body resident"); - shed_to(&minds, total - 2 * BODY as u64); + shed_to(&minds, total - 2 * BODY as u64, &proven); assert_eq!( resident_bytes(&minds), 5 * BODY as u64, @@ -99,7 +101,7 @@ fn the_shed_moves_the_oldest_across_minds_down_to_the_allocation() { "and loads back to what she read" ); - shed_to(&minds, 0); + shed_to(&minds, 0, &proven); assert_eq!(resident(&a), ["a3"], "a's newest stays"); assert_eq!( resident(&b), @@ -108,35 +110,98 @@ fn the_shed_moves_the_oldest_across_minds_down_to_the_allocation() { ); } -// what this catches (Codex on #5595): a saved copy counted as safe because its FILE EXISTS. A -// file that is there but does not load back to the body (wrong content), or is gone, is not a -// copy: moving the body would lose the last one, and her view's load would render a pointer. -// Real files through the spill owner, never an injected verdict. +// what this catches (Codex and Cormac on #5595): a saved copy counted as safe because its FILE +// EXISTS. A file that is there but does not load back to the body (wrong content, a truncated +// write), or is gone, is not a copy: moving the body would lose the last one, and her view's +// load would render a pointer. Real files through the spill owner, never an injected verdict. #[test] fn a_copy_that_cannot_reproduce_the_body_keeps_it_resident() { let persona = Uuid::new_v4(); let pin = LivePin::new(); let memory = Arc::new(WorkingMemory::new(8)); let wrong = kept(&memory, persona, &pin, "c1"); - let gone = kept(&memory, persona, &pin, "c2"); - kept(&memory, persona, &pin, "c3"); + let truncated = kept(&memory, persona, &pin, "c2"); + let gone = kept(&memory, persona, &pin, "c3"); kept(&memory, persona, &pin, "c4"); - std::fs::write( - spill::resolve(persona, &wrong).expect("test: path"), - "not what she read", - ) - .expect("test: overwrite"); - std::fs::remove_file(spill::resolve(persona, &gone).expect("test: path")) - .expect("test: remove"); + kept(&memory, persona, &pin, "c5"); + let path = |handle: &str| spill::resolve(persona, handle).expect("test: path"); + std::fs::write(path(&wrong), "not what she read").expect("test: overwrite"); + std::fs::write(path(&truncated), &body("c2")[..BODY / 2]).expect("test: truncated write"); + std::fs::remove_file(path(&gone)).expect("test: remove"); + + let candidates = memory.resident_results().candidates; + let verdict = |handle: &str| { + let candidate = candidates + .iter() + .find(|c| c.handle == handle) + .expect("test: a candidate"); + prove(persona, &memory, candidate).expect("test: still resident") + }; + assert!( + matches!(verdict(&truncated), Err(LastCopy::Mismatch)), + "a truncated copy is a mismatch" + ); + assert_eq!( + verdict(&truncated).err().map(|e| e.reason()), + Some("mismatch"), + "the wm.results.last_copy_kept probe's reason" + ); + assert!(matches!(verdict(&wrong), Err(LastCopy::Mismatch))); + assert!( + matches!(verdict(&gone), Err(LastCopy::Unreadable(_))), + "a missing copy is unreadable" + ); + + let minds: Minds = vec![(persona, Arc::clone(&memory))]; + shed_to(&minds, 0, &Mutex::new(ProvenCopies::default())); + assert_eq!( + resident(&memory), + ["c1", "c2", "c3", "c5"], + "unprovable copies keep their bodies; c4 moved" + ); + assert_eq!(resident_bytes(&minds), 4 * BODY as u64); +} + +// what this catches (Cormac on #5595): `budget()` touching the filesystem. The monitor calls it +// under its reporters lock on every snapshot, so a stat per resident record ran inside the +// monitor. Proofs are made at shed time and cached; with the spill directory gone, budget() +// answers the same from the cache, and an unproven body counts as pinned. +#[test] +fn budget_answers_from_the_proof_cache_without_the_filesystem() { + let persona = Uuid::new_v4(); + let pin = LivePin::new(); + let memory = Arc::new(WorkingMemory::new(8)); + for name in ["d1", "d2", "d3", "d4"] { + kept(&memory, persona, &pin, name); + } let minds: Minds = vec![(persona, Arc::clone(&memory))]; + let proven = Mutex::new(ProvenCopies::default()); + let unproven = budget_of(&minds, &proven); + assert_eq!( + (unproven.min_bytes, unproven.max_bytes), + (4 * BODY as u64, 4 * BODY as u64), + "nothing proven: all pinned" + ); - shed_to(&minds, 0); + shed_to(&minds, 3 * BODY as u64, &proven); assert_eq!( resident(&memory), - ["c1", "c2", "c4"], - "wrong content and a missing file keep their bodies; c3 moved" + ["d2", "d3", "d4"], + "the oldest moved once proven" + ); + let handle = memory.resident_results().candidates[0].handle.clone(); + let dir = spill::resolve(persona, &handle) + .expect("test: path") + .parent() + .expect("test: dir") + .to_owned(); + std::fs::remove_dir_all(&dir).expect("test: remove the spill dir"); + let cached = budget_of(&minds, &proven); + assert_eq!(cached.max_bytes, 3 * BODY as u64); + assert_eq!( + cached.min_bytes, BODY as u64, + "d2 and d3 proven from the cache; only the newest pinned" ); - assert_eq!(resident_bytes(&minds), 3 * BODY as u64); } // what this catches: the memory owner reading a wrong total, so it sheds too little or too diff --git a/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs index 67f8361ec6..7af2838e13 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace/tests/she_is_told_when_her_hands_move_and_only_then.rs @@ -198,7 +198,7 @@ use super::*; memory.record_receipt_typed(&[], &"s".repeat(cap / 2), None, saved("5000000000000002")); } memory.record_settlement("done", None); - memory.evict_resident_results_over(0, &|_, _, _| true); + memory.evict_resident_results_over(0, &|_, _| true); let persisted = PersistedVolatile { wm: memory.snapshot(), own_speech: OwnSpeechPersisted::ByRoom(Vec::new()), diff --git a/core/continuum-cognition/src/cognition/tool_executor/spill.rs b/core/continuum-cognition/src/cognition/tool_executor/spill.rs index 731d4abf12..27fb521633 100644 --- a/core/continuum-cognition/src/cognition/tool_executor/spill.rs +++ b/core/continuum-cognition/src/cognition/tool_executor/spill.rs @@ -328,29 +328,17 @@ pub fn resolve(persona_id: Uuid, handle: &str) -> std::io::Result { /// THE read of a saved result as her view loads it back: the saved output, trimmed as the /// record keeps its result (`record_receipt_inner`). Her view's `load` and the memory owner's -/// shed both read through here, so "verified" means "loads back to this text". +/// proof ([`reproduces`]) both read through here, so "verified" means "loads back to this text". pub fn saved_whole(persona_id: Uuid, handle: &str) -> std::io::Result { let text = fs::read_to_string(resolve(persona_id, handle)?)?; Ok(text.trim().to_owned()) } -/// A whole's content address for comparing a resident body with its saved copy without -/// holding both in RAM (SHA-256 of the text). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct WholeDigest([u8; 32]); - -impl WholeDigest { - pub fn of(text: &str) -> Self { - let mut digest = [0u8; 32]; - digest.copy_from_slice(&Sha256::digest(text.as_bytes())); - Self(digest) - } -} - -/// The digest of what `persona_id`'s saved output for `handle` loads back to -/// ([`saved_whole`]). A resident body whose digest matches is reproduced by its copy. -pub fn saved_digest(persona_id: Uuid, handle: &str) -> std::io::Result { - Ok(WholeDigest::of(&saved_whole(persona_id, handle)?)) +/// Whether `persona_id`'s saved output for `handle` loads back ([`saved_whole`]) to exactly +/// `body`: the proof that the copy can stand in for a body leaving RAM. `Err` when it cannot be +/// read back at all. +pub fn reproduces(persona_id: Uuid, handle: &str, body: &str) -> std::io::Result { + Ok(saved_whole(persona_id, handle)? == body) } // ── root-injected cores (the filesystem seam; unit-tested against a tempdir so diff --git a/core/continuum-cognition/src/cognition/working_memory/action_log.rs b/core/continuum-cognition/src/cognition/working_memory/action_log.rs index 756de8fdac..e91fdf3793 100644 --- a/core/continuum-cognition/src/cognition/working_memory/action_log.rs +++ b/core/continuum-cognition/src/cognition/working_memory/action_log.rs @@ -157,20 +157,17 @@ impl ActionLog { } /// The records a shed may move to their handles, oldest first: resident, saved, not the - /// newest result, and vouched for by `saved(seq, handle, body)` (its saved copy loads back - /// to this body). Everything else is the last copy of what she read, so it stays. Lazy: - /// `saved` runs only for the records a caller actually takes. + /// newest result, and vouched for by `saved(seq, handle)` (its saved copy was proven to load + /// back to this body). Everything else is the last copy of what she read, so it stays. pub fn evictable<'a>( &'a self, - saved: &'a dyn Fn(u64, &str, &str) -> bool, + saved: &'a dyn Fn(u64, &str) -> bool, ) -> impl Iterator + 'a { let newest = self.retained().last().map(|record| record.seq); self.records.iter().filter(move |record| { - Some(record.seq) != newest - && match (&record.result, &record.handle) { - (Some(body), Some(handle)) => saved(record.seq, handle, body), - _ => false, - } + record.result.is_some() + && Some(record.seq) != newest + && record.handle.as_deref().is_some_and(|handle| saved(record.seq, handle)) }) } @@ -178,7 +175,7 @@ impl ActionLog { /// resident. Each keeps its measured length (`stored_chars`) and its handle, so her view /// still prices and reloads its whole. Exactly to the budget: the memory owner decides /// when, so there is no hysteresis here. - pub fn collapse_over(&mut self, budget: u64, saved: &dyn Fn(u64, &str, &str) -> bool) -> Collapsed { + pub fn collapse_over(&mut self, budget: u64, saved: &dyn Fn(u64, &str) -> bool) -> Collapsed { let mut total = self.resident_bytes(); if total <= budget { return Collapsed { total }; diff --git a/core/continuum-cognition/src/cognition/working_memory/residency.rs b/core/continuum-cognition/src/cognition/working_memory/residency.rs index a3b62fd108..80aa89067b 100644 --- a/core/continuum-cognition/src/cognition/working_memory/residency.rs +++ b/core/continuum-cognition/src/cognition/working_memory/residency.rs @@ -42,7 +42,7 @@ impl WorkingMemory { pub(crate) fn resident_results(&self) -> ResidentResults { let actions = self.actions.lock(); let candidates = actions - .evictable(&|_, _, _| true) + .evictable(&|_, _| true) .filter_map(|record| { Some(ShedCandidate { received_ms: record.received_ms, @@ -58,16 +58,27 @@ impl WorkingMemory { } } + /// A copy of one resident body, if its record still names `handle`: what the memory owner + /// proves its saved copy against, outside the lock (the lock is held only for the copy). + pub(crate) fn resident_body(&self, seq: u64, handle: &str) -> Option { + let actions = self.actions.lock(); + let record = actions.get(seq)?; + if record.handle.as_deref() != Some(handle) { + return None; + } + record.result.clone() + } + /// THE eviction verb: move the oldest saved bodies to their handles until at most `budget` /// bytes stay resident. Only the memory owner's shed calls it in production, with - /// `saved(seq, handle, body)` answering from what it read outside the lock (each saved copy's - /// digest), so a record that changed since, or whose copy does not reproduce its body, is - /// not moved. No filesystem access happens under the lock. The newest stays, and + /// `saved(seq, handle)` answering from the copies it proved outside the lock, so a record + /// that changed since (a different handle, or gone) is not moved. No filesystem access + /// happens under the lock. The newest stays, and /// past the budget after that the overrun is reported, never forced. pub(crate) fn evict_resident_results_over( &self, budget: u64, - saved: &dyn Fn(u64, &str, &str) -> bool, + saved: &dyn Fn(u64, &str) -> bool, ) { let total = self.actions.lock().collapse_over(budget, saved).total; self.publish_live_handles(); diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs index e9b66fdadd..52f119b7ca 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/custody.rs @@ -179,7 +179,7 @@ fn a_shed_moves_only_the_records_it_vouched_for() { wm.record_receipt_typed(&[], "newest", None, saved("vouched-c")); let seq_of = |h: &str| wm.snapshot().actions.iter().find(|r| r.handle.as_deref() == Some(h)).map(|r| r.seq).expect("test: seq"); let (a, b) = (seq_of("vouched-a"), seq_of("vouched-b")); - wm.evict_resident_results_over(0, &|seq, handle, _| (seq == a && handle == "a-changed") || (seq == b && handle == "vouched-b")); + wm.evict_resident_results_over(0, &|seq, handle| (seq == a && handle == "a-changed") || (seq == b && handle == "vouched-b")); let resident: Vec<_> = wm.snapshot().actions.into_iter().filter(|r| r.result.is_some()).filter_map(|r| r.handle).collect(); assert_eq!(resident, ["vouched-a", "vouched-c"], "a changed since it was vouched for; only b moved"); } diff --git a/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs b/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs index eceeb98489..b834ea390b 100644 --- a/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs +++ b/core/continuum-cognition/src/cognition/working_memory/tests/mod.rs @@ -29,5 +29,5 @@ const BODY: usize = 4_096; /// Shed `wm`'s resident bodies down to `budget` bytes, as the memory owner's reporter does, /// with every handle's saved output vouched for. fn shed(wm: &WorkingMemory, budget: usize) { - wm.evict_resident_results_over(budget as u64, &|_, _, _| true); + wm.evict_resident_results_over(budget as u64, &|_, _| true); }