Skip to content
89 changes: 39 additions & 50 deletions core/continuum-cognition/src/cognition/channel_element.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,11 @@
use std::sync::Arc;

use airc_core::TranscriptEvent;
use dashmap::DashMap;
use tokio::sync::OnceCell;
use uuid::Uuid;

use crate::ai::embedding::EmbeddingProvider;

/// Soft bound on the shared element working set so a long-lived node servicing a
/// busy room can't grow it without limit (the substrate pressure doctrine — an
/// unbounded hot-path cache is a leak at scale). On overflow we evict one arbitrary
/// entry; airc remains the system of record, so an evicted element just re-resolves
/// on its next access. A proper LRU / `PagedResourcePool` tie-in is the follow-up.
const CHANNEL_ELEMENT_CACHE_MAX: usize = 20_000;

/// One room message + its lazily-computed, shared derived artifacts. Reference-
/// passed (`Arc<ChannelElement>`); one per airc message, handed to every persona.
Expand Down Expand Up @@ -141,63 +134,52 @@ impl ChannelElement {
}
}

/// What one element holds in RAM, in the ballpark the shed decision needs (no serialization):
/// the struct, its text (counted twice: the extracted copy and the event body it came from), and
/// its embedding once computed. Error bound: headers and a non-text body are not counted; they are
/// small next to the text and the vector.
impl continuum_kernel::system_resources::memory_pressure::ByteSized for ChannelElement {
fn byte_size(&self) -> u64 {
let text = self.text.as_ref().map_or(0, String::len) as u64;
let embedding = self.embedding.get().and_then(Option::as_ref).map_or(0, |v| v.len() * std::mem::size_of::<f32>()) as u64;
std::mem::size_of::<Self>() as u64 + 2 * text + embedding
}
}

/// The shared element working set: airc `EventId` → one `Arc<ChannelElement>`,
/// handed to every persona so artifacts are computed once and referenced by all.
/// Process-lifetime, bounded; not a durable store (airc is).
/// Process-lifetime and rebuildable (airc is the system of record), so RAM sizes it: it answers
/// to the memory pressure monitor as a background cache and sheds least recently used first,
/// never by an entry count (Cormac on the pattern; Joel, 2026-10-29).
pub struct ChannelElementCache {
elements: DashMap<Uuid, Arc<ChannelElement>>,
elements: Arc<continuum_kernel::system_resources::memory_pressure::ShedLru<Uuid, ChannelElement>>,
embedder: Arc<dyn EmbeddingProvider>,
max: usize,
}

impl ChannelElementCache {
/// Build against an embedder (the `CachingEmbeddingProvider` in production).
pub fn new(embedder: Arc<dyn EmbeddingProvider>) -> Self {
Self {
elements: DashMap::new(),
elements: Arc::new(continuum_kernel::system_resources::memory_pressure::ShedLru::new(
"channel_elements",
continuum_kernel::system_resources::MemoryPriority::Background,
)),
embedder,
max: CHANNEL_ELEMENT_CACHE_MAX,
}
}

/// Build with an explicit soft cap (tests / isolated benches).
pub fn with_max(embedder: Arc<dyn EmbeddingProvider>, max: usize) -> Self {
Self {
elements: DashMap::new(),
embedder,
max: max.max(1),
}
/// Answer to the memory pressure monitor: it reads this cache's bytes and asks it to shed.
pub fn register(&self, monitor: &continuum_kernel::system_resources::MemoryPressureMonitor) {
self.elements.register(monitor);
}

/// Resolve the shared element for an airc message. The FIRST caller constructs
/// it; every caller after (any persona) gets the SAME `Arc` — one element,
/// shared, artifacts computed once. Keyed by airc's stable `EventId`.
pub fn get_or_insert(&self, event: TranscriptEvent) -> Arc<ChannelElement> {
let id = event.event_id.as_uuid();
// Fast path: an already-shared element (lock-free read on a hit).
if let Some(existing) = self.elements.get(&id) {
return existing.clone();
}
// Bound memory before admitting a genuinely new key. Soft cap: a small
// TOCTOU against concurrent inserts is acceptable for a working-set bound.
if self.elements.len() >= self.max && !self.elements.contains_key(&id) {
// Pick the victim in its OWN statement so the DashMap iterator's shard
// read-guard is dropped at the `;` — BEFORE `remove()` takes a write
// lock. Holding the iterator alive across `remove` (e.g. inside an
// `if let` scrutinee, whose temporaries outlive the body) deadlocks:
// the write waits on a read the same expression still holds.
let victim = self.elements.iter().next().map(|e| *e.key());
if let Some(victim) = victim {
self.elements.remove(&victim);
}
}
let embedder = self.embedder.clone();
// entry() is atomic per key: if two personas race the same new message,
// exactly one element is kept and both receive that same shared `Arc`.
self.elements
.entry(id)
.or_insert_with(|| Arc::new(ChannelElement::new(event, embedder)))
.clone()
self.elements.get_or_insert_with(id, || ChannelElement::new(event, embedder))
}

/// Resolve a batch of messages to their shared elements at once — the
Expand All @@ -217,6 +199,12 @@ impl ChannelElementCache {
pub fn is_empty(&self) -> bool {
self.elements.is_empty()
}

/// Give back at least `bytes`, least recently used first (what the monitor's shed does).
#[cfg(test)]
fn shed(&self, bytes: u64) -> u64 {
self.elements.shed(bytes)
}
}

#[cfg(test)]
Expand Down Expand Up @@ -293,9 +281,9 @@ mod tests {

let human = Uuid::new_v4(); // the operator identity chat/send carries
let envelope = AircRealtimeEnvelope {
event_id: Uuid::new_v4().to_string(),
event_id: Uuid::new_v4(),
room_id: RoomId::new().as_uuid(),
source_id: human.to_string(),
source_id: airc_core::PeerId::from_uuid(human),
target_id: None,
created_at_ms: 1,
delivery: AircRealtimeDelivery::Durable,
Expand Down Expand Up @@ -403,16 +391,17 @@ mod tests {
assert_eq!(cache.len(), 2);
}

// what this catches: the working-set bound holds — past the soft cap, admitting
// a new element evicts one, so the cache never grows without limit. airc stays
// the system of record, so an evicted element just re-resolves later.
// what this catches: the working set answering to RAM, not a count: a shed gives back bytes
// least recently used first, so the cache never grows without limit under pressure. airc stays
// the system of record, so a shed element just re-resolves later.
#[tokio::test]
async fn cache_evicts_past_soft_cap() {
let cache = ChannelElementCache::with_max(Arc::new(CountingEmbedder::new()), 2);
async fn the_cache_sheds_its_oldest_elements_by_bytes() {
let cache = ChannelElementCache::new(Arc::new(CountingEmbedder::new()));
cache.get_or_insert(make_event(Some("a"), 1));
cache.get_or_insert(make_event(Some("b"), 2));
cache.get_or_insert(make_event(Some("c"), 3));
assert_eq!(cache.len(), 2, "soft cap bounds the working set");
assert!(cache.shed(1) > 0, "a shed gives back bytes");
assert_eq!(cache.len(), 2, "the least recently used element went first");
}

// what this catches: the batch consolidation read resolves a whole window of
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
//! 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,
//! makes `over_gate` return 0 and sheds nothing here.
//! gate (`PressureSnapshot::over_gate`). Pressure raised by swap activity alone, with RAM use
//! under the gate, makes that overrun 0 and sheds nothing here.

use std::collections::{HashMap, HashSet};
use std::sync::Arc;
Expand Down Expand Up @@ -138,17 +138,6 @@ pub(crate) fn resident_bytes(minds: &Minds) -> u64 {
.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)
}

/// 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)]
Expand Down Expand Up @@ -340,17 +329,22 @@ impl MemoryReporter for MindResultsReporter {
}
}

fn priority(&self) -> MemoryPriority {
PRIORITY
}

fn can_shed(&self) -> bool {
true
}

fn shed_load(&self, level: PressureLevel) {
let over = over_gate(&self.pressure.borrow());
let minds = self.registry.resident_working_memories();
let before = resident_bytes(&minds);
// Its share of its priority's overrun, as every shedder computes it (Cormac on #5697).
let over = self.pressure.borrow().share_of_overrun(PRIORITY, before);
if over == 0 {
return;
}
let minds = self.registry.resident_working_memories();
let before = resident_bytes(&minds);
shed_to(&minds, before.saturating_sub(over), &self.proven);
continuum_base::probe!(
class = "wm.results.shed",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use uuid::Uuid;

use crate::ai::types::ResultCustody;
use crate::cognition::persona_workspace::mind_results_reporter::{
budget_of, over_gate, prove, resident_bytes, shed_to, LastCopy, Minds, ProvenCopies,
budget_of, prove, resident_bytes, shed_to, LastCopy, Minds, ProvenCopies,
};
use crate::cognition::tool_executor::spill::{self, LivePin};
use crate::cognition::working_memory::WorkingMemory;
Expand Down Expand Up @@ -243,27 +243,3 @@ fn report_sums_resident_bytes_across_minds() {
);
}

// 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::Interactive.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"
);
}
39 changes: 17 additions & 22 deletions core/continuum-core/src/airc/daemon_transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ use crate::airc::event_transport::AircEventTransport;
use crate::routing::airc_realtime::AircRealtimeDelivery;
use crate::airc::realtime_store::{
AircRealtimePublishParams, AircRealtimePublishResult, AircRealtimeReplayParams,
AircRealtimeReplayResult, AircRealtimeStore, InMemoryAircRealtimeStore, MAX_ROOM_REPLAY_LIMIT,
AircRealtimeReplayResult, AircRealtimeStore, InMemoryAircRealtimeStore,
};
use crate::routing::airc_realtime_wire::{
body_for_envelope, envelope_from_event, frame_kind_for_delivery, headers_for_envelope,
Expand Down Expand Up @@ -200,7 +200,7 @@ impl AircEventTransport for DaemonAircEventTransport {

Ok(AircRealtimePublishResult {
ok: true,
event_id: publish.event_id.to_string(),
event_id: publish.event_id.as_uuid(),
room_id: publish.channel_id.as_uuid(),
delivery: envelope.delivery,
stored_for_replay: matches!(
Expand All @@ -222,18 +222,12 @@ impl AircEventTransport for DaemonAircEventTransport {
let response = self
.client
.inbox(InboxRequest {
// TranscriptCursor → IpcCursor via the airc#1096 From
// impl. `.transpose()?` keeps the `Option<Result<_,_>>`
// pattern of the old code; `.map(Into::into)` then
// does the type conversion.
since: params
.after_cursor
.as_ref()
.map(|cursor| cursor.to_airc())
.transpose()?
.map(Into::into),
// TranscriptCursor → IpcCursor via the airc#1096 From impl; the cursor's id is
// typed, so the conversion cannot fail.
since: params.after_cursor.as_ref().map(|cursor| cursor.to_airc().into()),
channel: Some(RoomId::from_uuid(params.room_id)),
limit: Some(params.limit.unwrap_or(MAX_ROOM_REPLAY_LIMIT)),
// The caller's page; with none, the daemon's own page.
limit: params.limit,
// Replay is a cursor-resume of the FULL wire (durable
// transcript hydration), not a perception page — no kinds
// filter here. Perception's message-only page lives in
Expand All @@ -251,7 +245,8 @@ impl AircEventTransport for DaemonAircEventTransport {
crate::routing::airc_realtime::AircReplayCursor::from_airc(params.room_id, cursor.into())
});

let projection = InMemoryAircRealtimeStore::new(MAX_ROOM_REPLAY_LIMIT);
// Holds exactly the page the daemon returned.
let projection = InMemoryAircRealtimeStore::new(response.envelopes.len().max(1));
for envelope_bytes in response.envelopes {
// Decode wire bytes → TranscriptEvent (airc_lib helper),
// then project to continuum envelope. Malformed bytes are
Expand Down Expand Up @@ -355,11 +350,11 @@ mod tests {
}
}

fn envelope(event_id: &str) -> AircRealtimeEnvelope {
fn envelope(event_id: u128) -> AircRealtimeEnvelope {
AircRealtimeEnvelope::new(
event_id.to_string(),
Uuid::from_u128(event_id),
Uuid::from_u128(0xA1),
"continuum".to_string(),
airc_core::PeerId::from_u128(0xC0),
100,
AircRealtimePayload::ExistingSchema {
payload: AircRealtimePayloadRef::inline(
Expand All @@ -377,7 +372,7 @@ mod tests {

let result = transport
.publish(AircRealtimePublishParams {
envelope: envelope("evt-1"),
envelope: envelope(1),
})
.await
.unwrap();
Expand Down Expand Up @@ -414,7 +409,7 @@ mod tests {

transport
.publish(AircRealtimePublishParams {
envelope: envelope("evt-1"),
envelope: envelope(1),
})
.await
.unwrap();
Expand All @@ -427,7 +422,7 @@ mod tests {
#[tokio::test]
async fn replay_passes_cursor_through_as_ipc_cursor() {
let fake = Arc::new(FakeDaemonClient::default());
let env = envelope("evt-1");
let env = envelope(1);
let since_event = EventId::from_u128(0x10);
let newest_event = EventId::from_u128(0x20);
// Daemon hands us an IpcCursor in `newest`; we convert it
Expand All @@ -446,7 +441,7 @@ mod tests {
after_cursor: Some(crate::routing::airc_realtime::AircReplayCursor {
room_id: env.room_id,
lamport: 4,
event_id: since_event.to_string(),
event_id: since_event.as_uuid(),
observed_at_ms: None,
}),
limit: Some(10),
Expand All @@ -470,6 +465,6 @@ mod tests {
assert_eq!(since.event_id, since_event);
let cursor = replay.cursor.unwrap();
assert_eq!(cursor.lamport, 9);
assert_eq!(cursor.event_id, newest_event.to_string());
assert_eq!(cursor.event_id, newest_event.as_uuid());
}
}
6 changes: 3 additions & 3 deletions core/continuum-core/src/airc/event_transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,9 @@ mod tests {
StoreAircEventTransport::new(Arc::new(InMemoryAircRealtimeStore::default()));
let room_id = Uuid::from_u128(0xA1);
let envelope = AircRealtimeEnvelope::new(
"evt-1".to_string(),
Uuid::from_u128(1),
room_id,
"continuum".to_string(),
airc_core::PeerId::from_u128(0xC0),
100,
AircRealtimePayload::ExistingSchema {
payload: AircRealtimePayloadRef::inline(
Expand Down Expand Up @@ -103,6 +103,6 @@ mod tests {
.unwrap();

assert_eq!(replay.events.len(), 1);
assert_eq!(replay.events[0].event_id, "evt-1");
assert_eq!(replay.events[0].event_id, Uuid::from_u128(1));
}
}
Loading
Loading