From 3c81de2490d6c726753d9edef9c4b9b23254c0b3 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 20:07:59 -0600 Subject: [PATCH 1/7] Ids are typed UUIDs end to end, and the channel cache answers to RAM: one typed source header, an infallible replay cursor, and ShedLru for rebuildable caches (Joel: "assume we're using the UUIDs"; "consistency enables compression") - AircRealtimeEnvelope: event_id is a Uuid, source_id a PeerId, target_id an Option (ts: string). A non-id source cannot be built. AircReplayCursor, AircReceipt and AircRealtimePublishResult carry Uuid event ids. AircReplayCursor::to_airc is infallible: its parse and error disappear, and so does the daemon replay's .transpose()?. - One header: the dedicated continuum.sender_id header is gone. The claim is continuum.source_id, a peer id: equal to the transport is the author speaking for itself, anything else a claim the gate must prove. - The core's scope peer moves to persona::self_peer (register_scope/scope), the one owner of this process's ids. chat::publication::relay reads it; the grid capacity beacon publishes under it instead of the name "grid-capacity". - Contract verifier: typed event ids and source; the signed payload's text signer is compared as an id at the boundary (its own retype is a separate card). - ShedLru (kernel system_resources::memory_pressure): a rebuildable in-RAM cache that registers with the MemoryPressureMonitor, accounts bytes, and sheds least recently used first to the host's overrun past its priority's gate. PressureSnapshot::over_gate is the one copy of that computation (mind_results now calls it). The channel element cache moves onto it: CHANNEL_ELEMENT_CACHE_MAX and with_max are deleted; it registers beside mind_results. - Self-sized constants removed from touched files: the replay page bounds (a page is what the caller asks, bounded by what the store retains), the pubkey hex length (ed25519_dalek's). - Test fixtures converted to typed ids (string event ids to Uuid::from_u128, names to PeerId). Tests (M5, serving down 02:01-02:07Z): kernel shed_lru + airc_realtime 28; cognition channel_element/channel_digest/conversation/mind_results 80; core airc/contracts/grid_capacity 162; mind chat 51; core check --tests clean; ratchets exit 0. Follow-up: the embedding cache (EMBEDDING_CACHE_MAX, continuum-engine) moves onto ShedLru next. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/channel_element.rs | 89 +++---- .../mind_results_reporter.rs | 6 +- .../src/airc/daemon_transport.rs | 39 ++- .../src/airc/event_transport.rs | 6 +- .../src/airc/inbound_attach/tests.rs | 8 +- .../continuum-core/src/airc/realtime_store.rs | 12 +- .../src/airc/realtime_store/tests.rs | 118 ++++---- .../src/commands/airc/realtime_publish.rs | 6 +- .../src/commands/airc/realtime_replay.rs | 4 +- .../src/contracts/verification.rs | 44 +-- .../start_server/persona_registry_modules.rs | 3 + core/continuum-core/src/modules/airc.rs | 7 +- .../src/modules/airc_runtime_e2e_tests.rs | 7 +- .../src/modules/grid_capacity.rs | 7 +- .../src/routing/airc_realtime.rs | 54 ++-- .../src/routing/airc_realtime_wire.rs | 34 +-- .../src/system_resources/memory_pressure.rs | 2 + .../memory_pressure/shed_lru.rs | 252 ++++++++++++++++++ core/continuum-mind/src/chat/publication.rs | 12 +- core/continuum-mind/src/chat/tests/mod.rs | 2 +- core/continuum-mind/src/persona/self_peer.rs | 15 ++ .../typescript/airc/AircRealtimeEnvelope.ts | 10 +- 22 files changed, 497 insertions(+), 240 deletions(-) create mode 100644 core/continuum-kernel/src/system_resources/memory_pressure/shed_lru.rs diff --git a/core/continuum-cognition/src/cognition/channel_element.rs b/core/continuum-cognition/src/cognition/channel_element.rs index 02d9daf567..16ed0239c6 100644 --- a/core/continuum-cognition/src/cognition/channel_element.rs +++ b/core/continuum-cognition/src/cognition/channel_element.rs @@ -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`); one per airc message, handed to every persona. @@ -141,32 +134,43 @@ 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::()) as u64; + std::mem::size_of::() as u64 + 2 * text + embedding + } +} + /// The shared element working set: airc `EventId` → one `Arc`, /// 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>, + elements: Arc>, embedder: Arc, - max: usize, } impl ChannelElementCache { /// Build against an embedder (the `CachingEmbeddingProvider` in production). pub fn new(embedder: Arc) -> 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, 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 @@ -174,30 +178,8 @@ impl ChannelElementCache { /// shared, artifacts computed once. Keyed by airc's stable `EventId`. pub fn get_or_insert(&self, event: TranscriptEvent) -> Arc { 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 @@ -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)] @@ -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, @@ -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 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 e4409817f3..910ef38bf4 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 @@ -142,11 +142,7 @@ pub(crate) fn resident_bytes(minds: &Minds) -> u64 { /// 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) + snapshot.over_gate(PRIORITY) } /// One mind's resident result bodies: what a shed may move (saved, not the newest, and its diff --git a/core/continuum-core/src/airc/daemon_transport.rs b/core/continuum-core/src/airc/daemon_transport.rs index 338cc40fa8..42373b4a94 100644 --- a/core/continuum-core/src/airc/daemon_transport.rs +++ b/core/continuum-core/src/airc/daemon_transport.rs @@ -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, @@ -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!( @@ -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>` - // 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 @@ -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 @@ -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( @@ -377,7 +372,7 @@ mod tests { let result = transport .publish(AircRealtimePublishParams { - envelope: envelope("evt-1"), + envelope: envelope(1), }) .await .unwrap(); @@ -414,7 +409,7 @@ mod tests { transport .publish(AircRealtimePublishParams { - envelope: envelope("evt-1"), + envelope: envelope(1), }) .await .unwrap(); @@ -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 @@ -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), @@ -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()); } } diff --git a/core/continuum-core/src/airc/event_transport.rs b/core/continuum-core/src/airc/event_transport.rs index 6a55901ff3..c08e9c4522 100644 --- a/core/continuum-core/src/airc/event_transport.rs +++ b/core/continuum-core/src/airc/event_transport.rs @@ -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( @@ -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)); } } diff --git a/core/continuum-core/src/airc/inbound_attach/tests.rs b/core/continuum-core/src/airc/inbound_attach/tests.rs index 39c1a6fa0a..0de071412e 100644 --- a/core/continuum-core/src/airc/inbound_attach/tests.rs +++ b/core/continuum-core/src/airc/inbound_attach/tests.rs @@ -86,9 +86,11 @@ fn transcript_event(body: Option, headers: airc_core::Headers) -> Transcri fn event_bridge_envelope() -> AircRealtimeEnvelope { AircRealtimeEnvelope::new( - "evt-1".to_string(), + Uuid::from_u128(1), Uuid::from_u128(2), - "continuum-peer".to_string(), + // A frame a core publishes itself: its source is its own transport peer (PeerId 3 in + // `transcript_event`), so it speaks for itself and makes no claim. + PeerId::from_u128(3), 100, AircRealtimePayload::ExistingSchema { payload: AircRealtimePayloadRef::inline( @@ -551,7 +553,7 @@ async fn a_claim_to_speak_for_someone_needs_its_exact_publication() { // A present sender header that is not an id: refused, never read as no claim. let malformed = continuum_mind::chat::line_store::RecordingImporter::default(); let (mut garbled, _) = relayed_line(relay, joel, room, "hello", message); - garbled.headers.insert(crate::routing::airc_realtime_wire::HEADER_CONTINUUM_SENDER_ID.to_string(), "joel".to_string()); + garbled.headers.insert(crate::routing::airc_realtime_wire::HEADER_CONTINUUM_SOURCE_ID.to_string(), "joel".to_string()); publish_transcript_event(&Arc::new(garbled), &bus, &malformed).await.expect("a refusal is not an error"); assert!(malformed.0.lock().expect("test: lock").is_empty(), "a malformed claim is refused before any consumer"); // test: a fixture step that must succeed diff --git a/core/continuum-core/src/airc/realtime_store.rs b/core/continuum-core/src/airc/realtime_store.rs index 1ce667aaa6..7cd0168256 100644 --- a/core/continuum-core/src/airc/realtime_store.rs +++ b/core/continuum-core/src/airc/realtime_store.rs @@ -14,8 +14,6 @@ use std::collections::{HashMap, VecDeque}; use ts_rs::TS; use uuid::Uuid; -pub const DEFAULT_ROOM_REPLAY_LIMIT: usize = 100; -pub const MAX_ROOM_REPLAY_LIMIT: usize = 500; pub const DEFAULT_EVENTS_PER_ROOM: usize = 2_000; #[derive(Debug, Clone, Serialize, Deserialize, TS, schemars::JsonSchema)] @@ -36,7 +34,8 @@ pub struct AircRealtimePublishParams { )] pub struct AircRealtimePublishResult { pub ok: bool, - pub event_id: String, + #[ts(type = "string")] + pub event_id: Uuid, #[ts(type = "string")] pub room_id: Uuid, pub delivery: AircRealtimeDelivery, @@ -218,10 +217,9 @@ impl AircRealtimeStore for InMemoryAircRealtimeStore { fn replay(&self, params: AircRealtimeReplayParams) -> Result { validate_room_id(params.room_id)?; - let limit = params - .limit - .unwrap_or(DEFAULT_ROOM_REPLAY_LIMIT) - .clamp(1, MAX_ROOM_REPLAY_LIMIT); + // A page is what the caller asks for, bounded by what this store retains (it can return no + // more); with no ask, the whole retained window. No second number chosen here. + let limit = params.limit.unwrap_or(self.max_events_per_room).clamp(1, self.max_events_per_room); let mut state = self.inner.lock(); if let Some(now_ms) = params.now_ms { state.prune_expired_presence(now_ms); diff --git a/core/continuum-core/src/airc/realtime_store/tests.rs b/core/continuum-core/src/airc/realtime_store/tests.rs index 56969f76eb..a7a0573aa5 100644 --- a/core/continuum-core/src/airc/realtime_store/tests.rs +++ b/core/continuum-core/src/airc/realtime_store/tests.rs @@ -11,26 +11,26 @@ const CAMBRIANTECH: Uuid = Uuid::from_u128(0xA2); const OTHER: Uuid = Uuid::from_u128(0xA3); - fn durable_event(id: &str, room: Uuid, created_at_ms: u64) -> AircRealtimeEnvelope { + fn durable_event(id: u128, room: Uuid, created_at_ms: u64) -> AircRealtimeEnvelope { AircRealtimeEnvelope::new( - id.to_string(), + Uuid::from_u128(id), room, - "node-a".to_string(), + PeerId::from_u128(0xC1), created_at_ms, AircRealtimePayload::ExistingSchema { payload: AircRealtimePayloadRef::inline( AircRealtimeSchema::ChatTranscript, - json!({"text": id}), + json!({"text": format!("{id}")}), ), }, ) } - fn typing_event(id: &str, started_at_ms: u64, expires_at_ms: u64) -> AircRealtimeEnvelope { + fn typing_event(id: u128, started_at_ms: u64, expires_at_ms: u64) -> AircRealtimeEnvelope { AircRealtimeEnvelope::new( - id.to_string(), + Uuid::from_u128(id), GENERAL, - "persona-1".to_string(), + PeerId::from_u128(0xC2), started_at_ms, AircRealtimePayload::Presence { event: AircPresenceEvent { @@ -47,7 +47,7 @@ } fn peer_manifest_event( - id: &str, + id: u128, peer_id: &str, rooms: &[Uuid], capabilities: &[&str], @@ -55,9 +55,9 @@ expires_at_ms: Option, ) -> AircRealtimeEnvelope { AircRealtimeEnvelope::new( - id.to_string(), + Uuid::from_u128(id), GENERAL, - peer_id.to_string(), + PeerId::from_uuid(uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, peer_id.as_bytes())), advertised_at_ms, AircRealtimePayload::PeerManifest { manifest: AircPeerManifest { @@ -94,7 +94,7 @@ for idx in 1..=3 { store .publish(AircRealtimePublishParams { - envelope: durable_event(&format!("evt-{idx}"), GENERAL, idx), + envelope: durable_event(idx as u128, GENERAL, idx), }) .unwrap(); } @@ -105,7 +105,7 @@ after_cursor: Some(AircReplayCursor { room_id: GENERAL, lamport: 1, - event_id: "evt-1".to_string(), + event_id: Uuid::from_u128(1), observed_at_ms: Some(1), }), limit: Some(10), @@ -121,11 +121,11 @@ result .events .iter() - .map(|event| event.event_id.as_str()) + .map(|event| event.event_id) .collect::>(), - ["evt-2", "evt-3"] + [Uuid::from_u128(2), Uuid::from_u128(3)] ); - assert_eq!(result.cursor.unwrap().event_id, "evt-3".to_string()); + assert_eq!(result.cursor.unwrap().event_id, Uuid::from_u128(3)); } #[test] @@ -133,12 +133,12 @@ let store = InMemoryAircRealtimeStore::new(10); let first = store .publish(AircRealtimePublishParams { - envelope: typing_event("typing-1", 100, 200), + envelope: typing_event(0x71, 100, 200), }) .unwrap(); let second = store .publish(AircRealtimePublishParams { - envelope: typing_event("typing-2", 120, 240), + envelope: typing_event(0x72, 120, 240), }) .unwrap(); @@ -183,7 +183,7 @@ let first = store .publish(AircRealtimePublishParams { envelope: peer_manifest_event( - "manifest-1", + 0x91, "peer-a", &[GENERAL], &["continuum.lora.invoke"], @@ -195,7 +195,7 @@ let second = store .publish(AircRealtimePublishParams { envelope: peer_manifest_event( - "manifest-2", + 0x92, "peer-a", &[GENERAL, CAMBRIANTECH], &["continuum.lora.invoke", "continuum.chat.turn"], @@ -207,7 +207,7 @@ store .publish(AircRealtimePublishParams { envelope: peer_manifest_event( - "manifest-3", + 0x93, "peer-b", &[GENERAL], &["continuum.lora.invoke"], @@ -310,13 +310,13 @@ fn receipt_only_messages_are_not_replayed() { let store = InMemoryAircRealtimeStore::new(10); let mut receipt = AircRealtimeEnvelope::new( - "receipt-1".to_string(), + Uuid::from_u128(0xB1), GENERAL, - "peer-1".to_string(), + PeerId::from_u128(0xC3), 10, AircRealtimePayload::Receipt { receipt: crate::routing::airc_realtime::AircReceipt { - event_id: "evt-1".to_string(), + event_id: Uuid::from_u128(1), peer_id: PeerId::from_uuid(uuid::Uuid::new_v5( &uuid::Uuid::NAMESPACE_OID, b"peer-1", @@ -352,9 +352,9 @@ fn control_messages_are_replayable_for_reconnect() { let store = InMemoryAircRealtimeStore::new(10); let envelope = AircRealtimeEnvelope::new( - "sub-1".to_string(), + Uuid::from_u128(0x51), GENERAL, - "browser-1".to_string(), + PeerId::from_uuid(uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, b"browser-1")), 10, AircRealtimePayload::Subscription { event: AircSubscriptionEvent { @@ -378,9 +378,9 @@ fn subscription_events_project_active_room_subscribers() { let store = InMemoryAircRealtimeStore::new(10); for (id, room, subscriber, topic) in [ - ("sub-1", GENERAL, "browser-1", "presence"), - ("sub-2", GENERAL, "persona-1", "media"), - ("sub-3", OTHER, "browser-2", "presence"), + (0x51, GENERAL, "browser-1", "presence"), + (0x62, GENERAL, "persona-1", "media"), + (0x63, OTHER, "browser-2", "presence"), ] { store .publish(AircRealtimePublishParams { @@ -419,7 +419,7 @@ store .publish(AircRealtimePublishParams { envelope: subscription_event( - "sub-1", + 0x51, GENERAL, "browser-1", "presence", @@ -430,7 +430,7 @@ let unsubscribe = store .publish(AircRealtimePublishParams { envelope: subscription_event( - "unsub-1", + 0x52, GENERAL, "browser-1", "presence", @@ -459,9 +459,9 @@ result .events .iter() - .map(|event| event.event_id.as_str()) + .map(|event| event.event_id) .collect::>(), - ["sub-1", "unsub-1"] + [Uuid::from_u128(0x51), Uuid::from_u128(0x52)] ); } @@ -470,7 +470,7 @@ let store = InMemoryAircRealtimeStore::new(10); let error = store .publish(AircRealtimePublishParams { - envelope: durable_event("evt-1", Uuid::nil(), 1), + envelope: durable_event(1, Uuid::nil(), 1), }) .unwrap_err(); @@ -478,16 +478,16 @@ } fn subscription_event( - id: &str, + id: u128, room: Uuid, subscriber: &str, topic: &str, action: AircSubscriptionAction, ) -> AircRealtimeEnvelope { AircRealtimeEnvelope::new( - id.to_string(), + Uuid::from_u128(id), room, - subscriber.to_string(), + PeerId::from_uuid(uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, subscriber.as_bytes())), 10, AircRealtimePayload::Subscription { event: AircSubscriptionEvent { @@ -564,7 +564,7 @@ tasks.push(tokio::spawn(async move { store .publish(AircRealtimePublishParams { - envelope: durable_event(&format!("evt-{i:03}"), GENERAL, i as u64 + 1), + envelope: durable_event(i as u128, GENERAL, i as u64 + 1), }) .expect("publish must succeed") })); @@ -589,7 +589,7 @@ .replay(AircRealtimeReplayParams { room_id: GENERAL, after_cursor: None, - limit: Some(MAX_ROOM_REPLAY_LIMIT), + limit: None, include_presence: None, include_subscriptions: None, include_peer_manifests: None, @@ -606,14 +606,14 @@ PARALLEL ); - // The published event_ids ("evt-000".."evt-063") must all be + // The published event_ids (Uuid::from_u128(0..PARALLEL)) must all be // present exactly once. Order across event_ids is non- // deterministic (publishes raced); only completeness matters. - let mut observed_ids: Vec = - replay.events.iter().map(|e| e.event_id.clone()).collect(); + let mut observed_ids: Vec = + replay.events.iter().map(|e| e.event_id).collect(); observed_ids.sort(); - let mut expected_ids: Vec = - (0..PARALLEL).map(|i| format!("evt-{i:03}")).collect(); + let mut expected_ids: Vec = + (0..PARALLEL).map(|i| Uuid::from_u128(i as u128)).collect(); expected_ids.sort(); assert_eq!( observed_ids, expected_ids, @@ -672,7 +672,7 @@ store .publish(AircRealtimePublishParams { envelope: durable_event( - &format!("evt-{:?}-{i:03}", room.as_u128()), + (room.as_u128() << 32) | i as u128, room, i as u64 + 1, ), @@ -690,7 +690,7 @@ .replay(AircRealtimeReplayParams { room_id: room, after_cursor: None, - limit: Some(MAX_ROOM_REPLAY_LIMIT), + limit: None, include_presence: None, include_subscriptions: None, include_peer_manifests: None, @@ -732,7 +732,7 @@ publish_tasks.push(tokio::spawn(async move { store .publish(AircRealtimePublishParams { - envelope: durable_event(&format!("evt-{i:03}"), GENERAL, i as u64 + 1), + envelope: durable_event(i as u128, GENERAL, i as u64 + 1), }) .expect("publish must succeed"); })); @@ -745,7 +745,7 @@ .replay(AircRealtimeReplayParams { room_id: GENERAL, after_cursor: None, - limit: Some(MAX_ROOM_REPLAY_LIMIT), + limit: None, include_presence: None, include_subscriptions: None, include_peer_manifests: None, @@ -792,7 +792,7 @@ .replay(AircRealtimeReplayParams { room_id: GENERAL, after_cursor: None, - limit: Some(MAX_ROOM_REPLAY_LIMIT), + limit: None, include_presence: None, include_subscriptions: None, include_peer_manifests: None, @@ -833,7 +833,7 @@ } store .publish(AircRealtimePublishParams { - envelope: durable_event(&format!("evt-{i:03}"), GENERAL, i as u64 + 1), + envelope: durable_event(i as u128, GENERAL, i as u64 + 1), }) .expect("publish must succeed"); })); @@ -850,7 +850,7 @@ .replay(AircRealtimeReplayParams { room_id: GENERAL, after_cursor: cursor.clone(), - limit: Some(MAX_ROOM_REPLAY_LIMIT), + limit: None, include_presence: None, include_subscriptions: None, include_peer_manifests: None, @@ -859,7 +859,7 @@ }) .expect("replay must succeed"); for evt in &r.events { - observed_ids.push(evt.event_id.clone()); + observed_ids.push(evt.event_id); } if let Some(c) = r.cursor.clone() { cursor = Some(c); @@ -872,7 +872,7 @@ // Wait for all publishers to finish, THEN one more poll loop // to drain anything left. futures::future::join_all(publish_tasks).await; - let mut observed: Vec = poll_task.await.expect("poll task must not panic"); + let mut observed: Vec = poll_task.await.expect("poll task must not panic"); // One final drain in case the poll loop exited before // observing the very last publishes. @@ -897,7 +897,7 @@ .replay(AircRealtimeReplayParams { room_id: GENERAL, after_cursor: None, - limit: Some(MAX_ROOM_REPLAY_LIMIT), + limit: None, include_presence: None, include_subscriptions: None, include_peer_manifests: None, @@ -920,7 +920,7 @@ Some(AircReplayCursor { room_id: GENERAL, lamport: evt.created_at_ms, // == publish-time ts == approx Lamport - event_id: evt.event_id.clone(), + event_id: evt.event_id, observed_at_ms: Some(evt.created_at_ms), }) } else { @@ -933,7 +933,7 @@ .replay(AircRealtimeReplayParams { room_id: GENERAL, after_cursor: cursor, - limit: Some(MAX_ROOM_REPLAY_LIMIT), + limit: None, include_presence: None, include_subscriptions: None, include_peer_manifests: None, @@ -943,7 +943,7 @@ .unwrap(); for evt in &final_drain.events { if !observed.contains(&evt.event_id) { - observed.push(evt.event_id.clone()); + observed.push(evt.event_id); } } @@ -959,9 +959,9 @@ ); // Eventually we saw every published event. - let expected: std::collections::HashSet = - (0..PUBLISHERS).map(|i| format!("evt-{i:03}")).collect(); - let actual: std::collections::HashSet = observed.into_iter().collect(); + let expected: std::collections::HashSet = + (0..PUBLISHERS).map(|i| Uuid::from_u128(i as u128)).collect(); + let actual: std::collections::HashSet = observed.into_iter().collect(); assert_eq!( actual, expected, "cursor polling + final drain must observe every published event (no losses)" diff --git a/core/continuum-core/src/commands/airc/realtime_publish.rs b/core/continuum-core/src/commands/airc/realtime_publish.rs index e718a754b6..c36c64bc60 100644 --- a/core/continuum-core/src/commands/airc/realtime_publish.rs +++ b/core/continuum-core/src/commands/airc/realtime_publish.rs @@ -38,9 +38,9 @@ mod tests { fn typing_envelope() -> AircRealtimeEnvelope { AircRealtimeEnvelope::new( - "typing-1".to_string(), + Uuid::from_u128(0x71), TEST_ROOM_ID, - "persona-1".to_string(), + airc_core::PeerId::from_u128(0xC1), 100, AircRealtimePayload::Presence { event: AircPresenceEvent { @@ -89,7 +89,7 @@ mod tests { .await .expect("publish must succeed"); assert!(result.ok); - assert_eq!(result.event_id, "typing-1"); + assert_eq!(result.event_id, Uuid::from_u128(0x71)); assert!(!result.stored_for_replay, "typing presence is ephemeral"); assert_eq!(result.active_presence_count, 1); } diff --git a/core/continuum-core/src/commands/airc/realtime_replay.rs b/core/continuum-core/src/commands/airc/realtime_replay.rs index 0ca7df5b35..53b185b163 100644 --- a/core/continuum-core/src/commands/airc/realtime_replay.rs +++ b/core/continuum-core/src/commands/airc/realtime_replay.rs @@ -60,9 +60,9 @@ mod tests { transport .publish(AircRealtimePublishParams { envelope: AircRealtimeEnvelope::new( - "typing-1".to_string(), + Uuid::from_u128(0x71), TEST_ROOM_ID, - "persona-1".to_string(), + airc_core::PeerId::from_u128(0xC1), 100, AircRealtimePayload::Presence { event: AircPresenceEvent { diff --git a/core/continuum-core/src/contracts/verification.rs b/core/continuum-core/src/contracts/verification.rs index d13c151e52..fdbc3f486d 100644 --- a/core/continuum-core/src/contracts/verification.rs +++ b/core/continuum-core/src/contracts/verification.rs @@ -22,7 +22,7 @@ use crate::contracts::{ #[derive(Debug, Clone, PartialEq, Eq)] pub struct VerifiedContractEvent { - pub replay_event_id: String, + pub replay_event_id: uuid::Uuid, pub room_id: uuid::Uuid, pub contract_id: String, pub event_name: String, @@ -33,31 +33,31 @@ pub struct VerifiedContractEvent { #[derive(Debug, Clone, PartialEq, Eq)] pub enum ContractVerificationError { MalformedContractEvent { - event_id: String, + event_id: uuid::Uuid, event_name: String, reason: String, }, SignatureRejected { - event_id: String, + event_id: uuid::Uuid, event_name: String, reason: String, }, MissingPeerManifest { - event_id: String, + event_id: uuid::Uuid, event_name: String, signer_peer_id: String, }, ManifestPubkeyMismatch { - event_id: String, + event_id: uuid::Uuid, event_name: String, signer_peer_id: String, manifest_pubkey_hex: String, event_pubkey_hex: String, }, SourcePeerMismatch { - event_id: String, + event_id: uuid::Uuid, event_name: String, - source_id: String, + source_id: airc_core::PeerId, signer_peer_id: String, }, } @@ -226,7 +226,7 @@ where let signed = serde_json::from_value::>(value.clone()).map_err(|error| { ContractVerificationError::MalformedContractEvent { - event_id: event.event_id.clone(), + event_id: event.event_id, event_name: event_name.to_string(), reason: error.to_string(), } @@ -234,13 +234,13 @@ where signed .verify() .map_err(|error| ContractVerificationError::SignatureRejected { - event_id: event.event_id.clone(), + event_id: event.event_id, event_name: event_name.to_string(), reason: error.to_string(), })?; let (contract_id, signer_peer_id) = signer_fields(&signed.payload); Ok(VerifiedContractEvent { - replay_event_id: event.event_id.clone(), + replay_event_id: event.event_id, room_id: event.room_id, contract_id: contract_id.clone(), event_name: signed.event_name, @@ -256,7 +256,7 @@ fn verify_manifest_binding( ) -> Result<(), ContractVerificationError> { let manifest = manifests.get(&contract.signer_peer_id).ok_or_else(|| { ContractVerificationError::MissingPeerManifest { - event_id: envelope.event_id.clone(), + event_id: envelope.event_id, event_name: contract.event_name.clone(), signer_peer_id: contract.signer_peer_id.clone(), } @@ -267,7 +267,7 @@ fn verify_manifest_binding( .eq_ignore_ascii_case(&contract.signer_pubkey_hex) { return Err(ContractVerificationError::ManifestPubkeyMismatch { - event_id: envelope.event_id.clone(), + event_id: envelope.event_id, event_name: contract.event_name.clone(), signer_peer_id: contract.signer_peer_id.clone(), manifest_pubkey_hex: manifest.signing_pubkey_hex.clone(), @@ -275,11 +275,13 @@ fn verify_manifest_binding( }); } - if envelope.source_id != contract.signer_peer_id { + // The signed payload carries its signer as text (its own retype is a separate card); compare as + // ids at this boundary. + if uuid::Uuid::parse_str(&contract.signer_peer_id).ok() != Some(envelope.source_id.as_uuid()) { // wire boundary: the signed contract's signer id is text return Err(ContractVerificationError::SourcePeerMismatch { - event_id: envelope.event_id.clone(), + event_id: envelope.event_id, event_name: contract.event_name.clone(), - source_id: envelope.source_id.clone(), + source_id: envelope.source_id, signer_peer_id: contract.signer_peer_id.clone(), }); } @@ -354,9 +356,9 @@ mod tests { SignedContractEvent::sign(EVENT_CONTRACT_PROPOSED, proposed_payload(peer_id), key, 2) .unwrap(); AircRealtimeEnvelope { - event_id: "event-1".to_string(), + event_id: uuid::Uuid::from_u128(1), room_id: room(), - source_id: test_peer_str(peer_id), + source_id: test_peer_id(peer_id), target_id: None, created_at_ms: 2, delivery: AircRealtimeDelivery::Durable, @@ -380,7 +382,7 @@ mod tests { cursor: Some(AircReplayCursor { room_id: room(), lamport: 1, - event_id: "event-1".to_string(), + event_id: uuid::Uuid::from_u128(1), observed_at_ms: Some(2), }), active_presence: Vec::new(), @@ -441,7 +443,7 @@ mod tests { fn rejects_contract_event_when_source_id_is_not_signer() { let key = ContractSigningKey::generate(); let mut event = signed_contract_event("peer-a", &key); - event.source_id = "peer-b".to_string(); + event.source_id = test_peer_id("peer-b"); let error = verify_contract_replay(&replay(vec![event], vec![manifest("peer-a", &key)])) .unwrap_err(); @@ -454,9 +456,9 @@ mod tests { #[test] fn ignores_non_contract_event_bridge_payloads() { let event = AircRealtimeEnvelope::new( - "event-2".to_string(), + uuid::Uuid::from_u128(2), room(), - "peer-a".to_string(), + test_peer_id("peer-a"), 2, AircRealtimePayload::ExistingSchema { payload: AircRealtimePayloadRef::inline( 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 c741aedb7f..c790633548 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 @@ -100,6 +100,9 @@ pub(super) fn register_persona_registry_modules( ); // 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). + // The shared channel-element cache is rebuildable (airc is the record): RAM sizes it, it sheds + // least recently used first under pressure, never an entry cap of ours. + crate::cognition::channel_substrate::global_channel_element_cache().register(pressure_monitor); pressure_monitor.add_reporter(Arc::new(crate::cognition::persona_workspace::MindResultsReporter::new( crate::cognition::persona_workspace::global(), pressure_monitor.subscribe(), diff --git a/core/continuum-core/src/modules/airc.rs b/core/continuum-core/src/modules/airc.rs index 48f9c68cf0..bb778690da 100644 --- a/core/continuum-core/src/modules/airc.rs +++ b/core/continuum-core/src/modules/airc.rs @@ -94,10 +94,9 @@ impl AircModule { // construction, so it is in the self set before the first persona build // reads a durable override — not only after this node hears its own // beacon echo back. - crate::persona::self_peer::register(*peer_id); - // This scope peer is the relay `chat/send` publishes callers' lines as: its - // publication obligations name it, and only it may deliver them (#5696). - continuum_mind::chat::publication::register_relay(airc_core::PeerId::from_uuid(*peer_id)); + // This scope peer is the identity the core publishes as: realtime publishes, the + // capacity beacon, and the relay `chat/send` publishes callers' lines as (#5696). + crate::persona::self_peer::register_scope(*peer_id); Self { queue_client: Arc::new(CliAircQueueClient::new(TokioAircCommandRunner)), // #3849: the socket is re-resolved when the daemon diff --git a/core/continuum-core/src/modules/airc_runtime_e2e_tests.rs b/core/continuum-core/src/modules/airc_runtime_e2e_tests.rs index eb29e21a3b..a3f78e3b63 100644 --- a/core/continuum-core/src/modules/airc_runtime_e2e_tests.rs +++ b/core/continuum-core/src/modules/airc_runtime_e2e_tests.rs @@ -32,6 +32,7 @@ use crate::runtime::{ }; const TEST_ROOM_ID: Uuid = Uuid::from_u128(0xA1); +const TEST_ENVELOPE_EVENT_ID: Uuid = Uuid::from_u128(0xB2); const TEST_AIRC_EVENT_ID: EventId = EventId(Uuid::from_u128(0xB1)); #[tokio::test] @@ -54,9 +55,9 @@ async fn runtime_publish_attach_and_replay_use_daemon_ipc_path() { daemon.wait_for_attach().await; let envelope = AircRealtimeEnvelope::new( - "continuum-runtime-e2e".to_string(), + TEST_ENVELOPE_EVENT_ID, TEST_ROOM_ID, - "continuum-runtime-test".to_string(), + airc_core::PeerId::from_u128(0xC2), 1_000, AircRealtimePayload::ExistingSchema { payload: AircRealtimePayloadRef::inline( @@ -103,7 +104,7 @@ async fn runtime_publish_attach_and_replay_use_daemon_ipc_path() { assert_eq!(replay_value["events"].as_array().unwrap().len(), 1); assert_eq!( replay_value["events"][0]["eventId"], - "continuum-runtime-e2e" + TEST_ENVELOPE_EVENT_ID.to_string() ); assert_eq!(replay_value["cursor"]["lamport"], 1); assert_eq!( diff --git a/core/continuum-core/src/modules/grid_capacity.rs b/core/continuum-core/src/modules/grid_capacity.rs index 119e3cc542..0154f33d89 100644 --- a/core/continuum-core/src/modules/grid_capacity.rs +++ b/core/continuum-core/src/modules/grid_capacity.rs @@ -122,10 +122,15 @@ impl ServiceModule for GridCapacityModule { return Ok(()); }; + // Published as this core's own scope peer: the beacon's author speaking for itself (a typed + // id, never a name). No scope peer means the airc module never attached, so nothing to beacon on. + let Some(source) = crate::persona::self_peer::scope() else { + return Ok(()); + }; let envelope = json!({ "eventId": uuid::Uuid::new_v4().to_string(), "roomId": self.room.as_uuid().to_string(), - "sourceId": "grid-capacity", + "sourceId": source.to_string(), "createdAtMs": offer.at_ms, "delivery": "ephemeral_coalesced", "payload": { diff --git a/core/continuum-kernel/src/routing/airc_realtime.rs b/core/continuum-kernel/src/routing/airc_realtime.rs index a2b6db9d36..19c95d55ae 100644 --- a/core/continuum-kernel/src/routing/airc_realtime.rs +++ b/core/continuum-kernel/src/routing/airc_realtime.rs @@ -204,7 +204,8 @@ pub struct AircReplayCursor { #[ts(type = "string")] pub room_id: Uuid, pub lamport: u64, - pub event_id: String, + #[ts(type = "string")] + pub event_id: Uuid, #[ts(optional)] pub observed_at_ms: Option, } @@ -219,18 +220,13 @@ impl AircReplayCursor { Self { room_id, lamport: cursor.lamport, - event_id: cursor.event_id.to_string(), + event_id: cursor.event_id.as_uuid(), observed_at_ms: None, } } - pub fn to_airc(&self) -> Result { - let event_uuid = Uuid::parse_str(&self.event_id) - .map_err(|error| format!("invalid AIRC replay cursor event_id: {error}"))?; - Ok(airc_core::TranscriptCursor { - lamport: self.lamport, - event_id: airc_core::EventId::from_uuid(event_uuid), - }) + pub fn to_airc(&self) -> airc_core::TranscriptCursor { + airc_core::TranscriptCursor { lamport: self.lamport, event_id: airc_core::EventId::from_uuid(self.event_id) } } } @@ -413,10 +409,11 @@ impl std::error::Error for AircPeerManifestError {} /// validation is delegated to ed25519_dalek when a consumer parses; this /// check is the cheap structural gate at substrate ingress. fn validate_signing_pubkey_hex(hex: &str) -> Result<(), AircPeerManifestError> { - const EXPECTED_LEN: usize = 64; // 32 bytes * 2 hex chars - if hex.len() != EXPECTED_LEN { + // Two hex characters per key byte; the key length is ed25519's, not ours to restate. + let expected = 2 * ed25519_dalek::PUBLIC_KEY_LENGTH; + if hex.len() != expected { return Err(AircPeerManifestError::PubkeyWrongLength { - expected: EXPECTED_LEN, + expected, got: hex.len(), }); } @@ -433,7 +430,8 @@ fn validate_signing_pubkey_hex(hex: &str) -> Result<(), AircPeerManifestError> { #[serde(rename_all = "camelCase")] #[ts(export, export_to = "../../../protocol/typescript/airc/AircReceipt.ts")] pub struct AircReceipt { - pub event_id: String, + #[ts(type = "string")] + pub event_id: Uuid, #[ts(type = "string")] #[schemars(with = "String")] pub peer_id: crate::identity::PeerId, @@ -485,12 +483,18 @@ impl AircRealtimePayload { export_to = "../../../protocol/typescript/airc/AircRealtimeEnvelope.ts" )] pub struct AircRealtimeEnvelope { - pub event_id: String, + /// The envelope's id (for a chat line, its stored message id). Typed: never a free-form name. + #[ts(type = "string")] + pub event_id: Uuid, #[ts(type = "string")] pub room_id: Uuid, - pub source_id: String, - #[ts(optional)] - pub target_id: Option, + /// Who published it, or for a relayed person's line, who it speaks for: always a peer id. + #[ts(type = "string")] + #[schemars(with = "Uuid")] + pub source_id: airc_core::PeerId, + #[ts(optional, type = "string")] + #[schemars(with = "Option")] + pub target_id: Option, pub created_at_ms: u64, pub delivery: AircRealtimeDelivery, pub payload: AircRealtimePayload, @@ -500,9 +504,9 @@ pub struct AircRealtimeEnvelope { impl AircRealtimeEnvelope { pub fn new( - event_id: String, + event_id: Uuid, room_id: Uuid, - source_id: String, + source_id: airc_core::PeerId, created_at_ms: u64, payload: AircRealtimePayload, ) -> Self { @@ -588,19 +592,19 @@ mod tests { let earlier = AircReplayCursor { room_id, lamport: 4, - event_id: "00000000-0000-0000-0000-000000000001".to_string(), + event_id: Uuid::from_u128(1), observed_at_ms: None, }; let later_same_lamport = AircReplayCursor { room_id, lamport: 4, - event_id: "00000000-0000-0000-0000-000000000002".to_string(), + event_id: Uuid::from_u128(2), observed_at_ms: None, }; let later_lamport = AircReplayCursor { room_id, lamport: 5, - event_id: "00000000-0000-0000-0000-000000000000".to_string(), + event_id: Uuid::from_u128(0), observed_at_ms: None, }; @@ -673,7 +677,7 @@ mod tests { fn envelope_delivery_must_match_payload_semantics() { let payload = AircRealtimePayload::Receipt { receipt: AircReceipt { - event_id: "evt-1".to_string(), + event_id: Uuid::from_u128(1), peer_id: PeerId::from_uuid(uuid::Uuid::new_v5( &uuid::Uuid::NAMESPACE_OID, b"peer-1", @@ -684,9 +688,9 @@ mod tests { }; let mut envelope = AircRealtimeEnvelope::new( - "receipt-1".to_string(), + Uuid::from_u128(0xB1), Uuid::from_u128(0xA1), - "peer-1".to_string(), + PeerId::from_u128(0xC1), 11, payload, ); diff --git a/core/continuum-kernel/src/routing/airc_realtime_wire.rs b/core/continuum-kernel/src/routing/airc_realtime_wire.rs index 9f9b18cb05..a45efcc64e 100644 --- a/core/continuum-kernel/src/routing/airc_realtime_wire.rs +++ b/core/continuum-kernel/src/routing/airc_realtime_wire.rs @@ -14,15 +14,14 @@ use crate::runtime::message_bus::BusEvent; pub const CONTINUUM_BODY_HINT: &str = "continuum.airc.realtime.envelope.v1"; pub const HEADER_CONTINUUM_EVENT_ID: &str = "continuum.event_id"; +/// Who an envelope is from (its typed `source_id`, a peer id): the transport author's own id for a +/// frame it publishes itself, or the person a relayed line speaks for. pub const HEADER_CONTINUUM_SOURCE_ID: &str = "continuum.source_id"; -/// The person a `chat_transcript` line is said by: stamped only on a person's line, so a claim to -/// speak for someone is its own typed header, never inferred from free-form provenance. -pub const HEADER_CONTINUUM_SENDER_ID: &str = "continuum.sender_id"; pub const HEADER_CONTINUUM_DELIVERY: &str = "continuum.delivery"; pub const HEADER_CONTINUUM_TRACE_ID: &str = "continuum.trace_id"; -/// The line's logical sender, from the `continuum.sender_id` header a person's line carries (a relay -/// publishes a human's line for them); the transport peer when there is none. Only lines that passed +/// The line's logical sender, from its `continuum.source_id` header (a relay publishes a human's line +/// for them); the transport peer when there is none. Only lines that passed /// the inbound attribution gate reach a consumer, so a claim read here was proven. Read from the header alone: the body is never opened to /// attribute a line (Joel, 2026-11-01: routing on headers, never parsed bodies). /// @@ -31,12 +30,14 @@ pub const HEADER_CONTINUUM_TRACE_ID: &str = "continuum.trace_id"; pub fn logical_sender(event: &TranscriptEvent) -> uuid::Uuid { event .headers - .get(HEADER_CONTINUUM_SENDER_ID) + .get(HEADER_CONTINUUM_SOURCE_ID) .and_then(|value| uuid::Uuid::parse_str(value).ok()) // wire boundary: a header value is text; the gate refused a malformed one .unwrap_or_else(|| event.peer_id.as_uuid()) // the transport peer is the real author when no relay named one } -/// What a line's `continuum.sender_id` header claims about who it speaks for. +/// What a line's `continuum.source_id` header claims about who it speaks for. Every source is a peer +/// id, so a source equal to the transport is the author speaking for itself, and only a relayed +/// line names someone else. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SenderClaim { /// No claim: the transport peer is the author. @@ -49,7 +50,7 @@ pub enum SenderClaim { /// The sender a line's header claims it speaks for. pub fn claimed_sender(event: &TranscriptEvent) -> SenderClaim { - match event.headers.get(HEADER_CONTINUUM_SENDER_ID) { + match event.headers.get(HEADER_CONTINUUM_SOURCE_ID) { None => SenderClaim::Absent, Some(value) => match uuid::Uuid::parse_str(value) { // wire boundary: a header value is text Ok(id) => SenderClaim::Named(airc_core::PeerId::from_uuid(id)), @@ -79,11 +80,11 @@ pub fn headers_for_envelope(envelope: &AircRealtimeEnvelope) -> Headers { ); headers.insert( HEADER_CONTINUUM_EVENT_ID.to_string(), - envelope.event_id.clone(), + envelope.event_id.to_string(), ); headers.insert( HEADER_CONTINUUM_SOURCE_ID.to_string(), - envelope.source_id.clone(), + envelope.source_id.as_uuid().to_string(), ); headers.insert( HEADER_CONTINUUM_DELIVERY.to_string(), @@ -92,13 +93,6 @@ pub fn headers_for_envelope(envelope: &AircRealtimeEnvelope) -> Headers { if let Some(trace_id) = &envelope.trace_id { headers.insert(HEADER_CONTINUUM_TRACE_ID.to_string(), trace_id.clone()); } - // A person's line names its sender in its own header; other frames (an event bridge, a presence - // subject) carry free-form provenance in `continuum.source_id` and make no claim. - if let AircRealtimePayload::ExistingSchema { payload } = &envelope.payload { - if payload.schema == AircRealtimeSchema::ChatTranscript { - headers.insert(HEADER_CONTINUUM_SENDER_ID.to_string(), envelope.source_id.clone()); - } - } headers } @@ -211,14 +205,12 @@ mod tests { #[test] fn the_logical_sender_is_read_from_the_header() { let human = uuid::Uuid::from_u128(0x5e); - let relayed = event(Headers::from([(HEADER_CONTINUUM_SENDER_ID.to_string(), human.to_string())])); + let relayed = event(Headers::from([(HEADER_CONTINUUM_SOURCE_ID.to_string(), human.to_string())])); assert_eq!(logical_sender(&relayed), human); assert_eq!(claimed_sender(&relayed), SenderClaim::Named(airc_core::PeerId::from_uuid(human))); assert_eq!(logical_sender(&event(Headers::new())), uuid::Uuid::from_u128(0x4e)); assert_eq!(claimed_sender(&event(Headers::new())), SenderClaim::Absent); - let provenance = event(Headers::from([(HEADER_CONTINUUM_SOURCE_ID.to_string(), "continuum-peer".to_string())])); - assert_eq!(claimed_sender(&provenance), SenderClaim::Absent, "free-form provenance is no claim"); - let garbled = event(Headers::from([(HEADER_CONTINUUM_SENDER_ID.to_string(), "joel".to_string())])); + let garbled = event(Headers::from([(HEADER_CONTINUUM_SOURCE_ID.to_string(), "joel".to_string())])); assert_eq!(claimed_sender(&garbled), SenderClaim::Malformed, "a present sender header that is not an id"); } } diff --git a/core/continuum-kernel/src/system_resources/memory_pressure.rs b/core/continuum-kernel/src/system_resources/memory_pressure.rs index 12ba8f28e7..b8777ea4ec 100644 --- a/core/continuum-kernel/src/system_resources/memory_pressure.rs +++ b/core/continuum-kernel/src/system_resources/memory_pressure.rs @@ -76,6 +76,8 @@ use crate::{clog_info, clog_warn}; mod poll_interval; pub use poll_interval::*; +mod shed_lru; +pub use shed_lru::{ByteSized, ShedLru}; mod memory_pressure_monitor; // ============================================================================= diff --git a/core/continuum-kernel/src/system_resources/memory_pressure/shed_lru.rs b/core/continuum-kernel/src/system_resources/memory_pressure/shed_lru.rs new file mode 100644 index 0000000000..a266fb1eb2 --- /dev/null +++ b/core/continuum-kernel/src/system_resources/memory_pressure/shed_lru.rs @@ -0,0 +1,252 @@ +//! A rebuildable in-RAM cache that RAM sizes, never a number (Joel, 2026-10-29; Cormac on the +//! pattern): entries are kept in recency order and, when the memory pressure monitor sheds, the +//! least recently used are dropped until the cache gives back exactly the host's overrun past its +//! priority's gate. Everything in it can be rebuilt (airc, a recompute), so its floor is zero. +//! +//! One owner for the pattern: every in-process cache of rebuildable values registers one of these +//! with the monitor instead of carrying its own entry cap. + +use std::collections::{BTreeMap, HashMap}; +use std::hash::Hash; +use std::sync::Arc; + +use parking_lot::Mutex; +use tokio::sync::watch; + +use super::{ + MemoryBudgetSpec, MemoryPriority, MemoryReporter, ModuleMemoryReport, PressureLevel, + PressureSnapshot, +}; + +impl PressureSnapshot { + /// Bytes the host is over `priority`'s gate (used RAM past `gate x total`): what a consumer at + /// that priority gives back when it sheds. Zero at or under the gate. + pub fn over_gate(&self, priority: MemoryPriority) -> u64 { + let used = self.total_bytes.saturating_sub(self.available_bytes); + let gate = (self.total_bytes as f64 * priority.pressure_gate()) as u64; + used.saturating_sub(gate) + } +} + +/// How many bytes of RAM a cached value holds (what shedding it gives back). +pub trait ByteSized { + fn byte_size(&self) -> u64; +} + +struct Entry { + value: Arc, + used: u64, +} + +struct State { + entries: HashMap>, + /// Recency order: the tick an entry was last used, to its key. + by_use: BTreeMap, + tick: u64, +} + +impl State { + fn touch(&mut self, key: &K) -> Option> { + self.tick += 1; + let tick = self.tick; + let entry = self.entries.get_mut(key)?; + self.by_use.remove(&entry.used); + entry.used = tick; + self.by_use.insert(tick, key.clone()); + Some(Arc::clone(&entry.value)) + } +} + +/// A cache of rebuildable values that the memory monitor sheds, least recently used first. +pub struct ShedLru { + name: &'static str, + priority: MemoryPriority, + state: Mutex>, + /// The monitor's published snapshot, attached when the cache registers with it. + pressure: Mutex>>, +} + +impl ShedLru { + /// A cache named `name` at `priority`. It sheds once registered with the monitor + /// ([`Self::register`]); until then it only holds. + pub fn new(name: &'static str, priority: MemoryPriority) -> Self { + Self { + name, + priority, + state: Mutex::new(State { + entries: HashMap::new(), + by_use: BTreeMap::new(), + tick: 0, + }), + pressure: Mutex::new(None), + } + } + + /// Answer to `monitor` from now on: it reads this cache's bytes and asks it to shed. + pub fn register(self: &Arc, monitor: &super::MemoryPressureMonitor) + where + K: 'static, + V: 'static, + { + *self.pressure.lock() = Some(monitor.subscribe()); + monitor.add_reporter(Arc::clone(self) as Arc); + } + + /// The cached value for `key` (marking it used), or `None`. + pub fn get(&self, key: &K) -> Option> { + self.state.lock().touch(key) + } + + /// The cached value for `key`, or `make()`'s, cached. A value already present wins, so every + /// caller shares one. + pub fn get_or_insert_with(&self, key: K, make: impl FnOnce() -> V) -> Arc { + let mut state = self.state.lock(); + if let Some(value) = state.touch(&key) { + return value; + } + state.tick += 1; + let used = state.tick; + let value = Arc::new(make()); + state.by_use.insert(used, key.clone()); + state.entries.insert( + key, + Entry { + value: Arc::clone(&value), + used, + }, + ); + value + } + + pub fn len(&self) -> usize { + self.state.lock().entries.len() + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Bytes held now: what shedding everything would give back. + pub fn bytes(&self) -> u64 { + self.state + .lock() + .entries + .values() + .map(|entry| entry.value.byte_size()) + .sum() + } + + /// Drop least recently used entries until at least `want` bytes are given back (or nothing is + /// left). Returns the bytes given back. + pub fn shed(&self, want: u64) -> u64 { + let mut state = self.state.lock(); + let mut freed = 0; + while freed < want { + let Some((_, key)) = state.by_use.pop_first() else { + break; + }; + if let Some(entry) = state.entries.remove(&key) { + freed += entry.value.byte_size(); + } + } + freed + } +} + +impl MemoryReporter + for ShedLru +{ + fn name(&self) -> &'static str { + self.name + } + + fn budget(&self) -> MemoryBudgetSpec { + let held = self.bytes(); + MemoryBudgetSpec { + name: self.name.to_string(), + priority: self.priority, + min_bytes: 0, + preferred_bytes: held, + max_bytes: held, + } + } + + fn report(&self) -> ModuleMemoryReport { + ModuleMemoryReport { + name: self.name.to_string(), + bytes: self.bytes(), + detail: format!("{} rebuildable entries", self.len()), + can_shed: true, + } + } + + fn can_shed(&self) -> bool { + true + } + + /// Give back the host's overrun past this priority's gate, least recently used first. + fn shed_load(&self, _level: PressureLevel) { + let Some(overrun) = self + .pressure + .lock() + .as_ref() + .map(|pressure| pressure.borrow().over_gate(self.priority)) + else { + return; + }; + if overrun > 0 { + let freed = self.shed(overrun); + continuum_base::probe!( + class = "memory.shed_lru.shed", + cache = self.name, + overrun = overrun, + freed = freed, + "a rebuildable cache gave back RAM past its priority's gate" + ); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + struct Bytes(u64); + impl ByteSized for Bytes { + fn byte_size(&self) -> u64 { + self.0 + } + } + + fn cache() -> ShedLru { + ShedLru::new("test", MemoryPriority::Background) + } + + // what this catches: a cache sized by a count instead of RAM, or shedding the wrong entries: + // it holds what it is given, gives back the requested bytes least-recently-used first, keeps + // a value it was just asked for, and shares one value per key. + #[test] + fn it_sheds_least_recently_used_first_by_bytes() { + let lru = cache(); + for key in 0..4u32 { + lru.get_or_insert_with(key, || Bytes(10)); + } + assert_eq!((lru.len(), lru.bytes()), (4, 40)); + assert!(lru.get(&0).is_some(), "0 is now the most recently used"); + assert_eq!( + lru.shed(15), + 20, + "two oldest (1, 2) give back at least 15 bytes" + ); + assert!(lru.get(&1).is_none() && lru.get(&2).is_none()); + assert!( + lru.get(&0).is_some() && lru.get(&3).is_some(), + "the recently used stay" + ); + let first = lru.get_or_insert_with(7, || Bytes(1)); + let again = lru.get_or_insert_with(7, || Bytes(99)); + assert!(Arc::ptr_eq(&first, &again), "one shared value per key"); + assert_eq!(lru.shed(u64::MAX), 21, "shedding everything empties it"); + assert!(lru.is_empty()); + } +} diff --git a/core/continuum-mind/src/chat/publication.rs b/core/continuum-mind/src/chat/publication.rs index 7797648fa7..1c9287d839 100644 --- a/core/continuum-mind/src/chat/publication.rs +++ b/core/continuum-mind/src/chat/publication.rs @@ -89,16 +89,10 @@ pub struct PublicationObligation { pub state: PublicationState, } -/// The transport identity this core publishes relayed lines as (the airc module's scope peer), -/// registered once at its construction. -static RELAY: std::sync::OnceLock = std::sync::OnceLock::new(); - -pub fn register_relay(peer: PeerId) { - let _ = RELAY.set(peer); // first registration wins: the airc module constructs once per process -} - +/// The transport identity this core publishes relayed lines as: its project-scope peer +/// (`persona::self_peer::scope`). A relayed line is delegated only when it arrives from it. pub fn relay() -> Option { - RELAY.get().copied() + crate::persona::self_peer::scope().map(PeerId::from_uuid) } /// Who a received line is from. diff --git a/core/continuum-mind/src/chat/tests/mod.rs b/core/continuum-mind/src/chat/tests/mod.rs index e1dbd4798f..f4dda54c0d 100644 --- a/core/continuum-mind/src/chat/tests/mod.rs +++ b/core/continuum-mind/src/chat/tests/mod.rs @@ -28,7 +28,7 @@ let executor = Arc::new(CommandExecutor::new(registry)); // The relay this core publishes callers' lines as (the airc module registers it in // production); first registration wins process-wide. - crate::chat::publication::register_relay(airc_core::PeerId::from_u128(0x7e1a)); + crate::persona::self_peer::register_scope(uuid::Uuid::from_u128(0x7e1a)); ChatModule::with_executor(executor) } diff --git a/core/continuum-mind/src/persona/self_peer.rs b/core/continuum-mind/src/persona/self_peer.rs index b6f4d8a492..e7285fc1c8 100644 --- a/core/continuum-mind/src/persona/self_peer.rs +++ b/core/continuum-mind/src/persona/self_peer.rs @@ -33,6 +33,21 @@ pub fn register(peer: Uuid) { registered().lock().unwrap_or_else(|p| p.into_inner()).insert(peer); // JUSTIFIED unwrap_or_else: a poisoned set still holds the ids; membership is bookkeeping, never truth } +/// The core's own project-scope peer: the identity it publishes as (airc realtime publishes, relayed +/// callers' lines, the capacity beacon). One of the ids above, designated once by the airc module. +static SCOPE: OnceLock = OnceLock::new(); + +/// Designate the core's project-scope peer (and record it as one of this process's ids). +pub fn register_scope(peer: Uuid) { + register(peer); + let _ = SCOPE.set(peer); // first designation wins: the airc module constructs once per process +} + +/// The core's project-scope peer, once the airc module has attached. +pub fn scope() -> Option { + SCOPE.get().copied() +} + /// Is `peer` one of the ids this process wears? A peer that is this node is never a /// remote seat: not for an offload, not for a return, not for a reservation ask, and a /// durable override naming it is a record of the old confusion, not an assignment. diff --git a/protocol/typescript/airc/AircRealtimeEnvelope.ts b/protocol/typescript/airc/AircRealtimeEnvelope.ts index de1f2153aa..e61cac4187 100644 --- a/protocol/typescript/airc/AircRealtimeEnvelope.ts +++ b/protocol/typescript/airc/AircRealtimeEnvelope.ts @@ -5,4 +5,12 @@ import type { AircRealtimePayload } from "./AircRealtimePayload"; /** * Top-level realtime envelope persisted or transmitted by AIRC. */ -export type AircRealtimeEnvelope = { eventId: string, roomId: string, sourceId: string, targetId?: string, createdAtMs: bigint, delivery: AircRealtimeDelivery, payload: AircRealtimePayload, traceId?: string, }; +export type AircRealtimeEnvelope = { +/** + * The envelope's id (for a chat line, its stored message id). Typed: never a free-form name. + */ +eventId: string, roomId: string, +/** + * Who published it, or for a relayed person's line, who it speaks for: always a peer id. + */ +sourceId: string, targetId?: string, createdAtMs: bigint, delivery: AircRealtimeDelivery, payload: AircRealtimePayload, traceId?: string, }; From ecc97a02aabc15b710ce78343fe25e36a9417b33 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 20:22:27 -0600 Subject: [PATCH 2/7] ShedLru shares one overrun across a priority, skips entries a caller holds, and inserts computed values outside its lock (Cormac on #5697) - PressureSnapshot::share_of_overrun(priority, held): each shedder gives back the overrun past its gate in proportion to what it holds among the registered holders at that priority (Holder, register_holder, held weakly), so one pressure event frees the overrun once, not once per cache. ShedLru and mind_results both register and both use the share: one rule. - shed skips an entry a caller still holds (Arc::strong_count > 1): dropping the cache's copy frees nothing, and counting it would drain the cache while the RAM stays pinned elsewhere. - insert_if_absent: for values computed outside the lock (the embedding cache next); the first insert wins, so one value per key. Tests (M5, serving down 02:20-02:22Z): kernel shed_lru 3 (new: a held entry is never counted as freed; two holders' shares of one overrun add up to it once); cognition channel_element + mind_results 12; core check --tests clean; ratchets exit 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../mind_results_reporter.rs | 17 +- .../start_server/persona_registry_modules.rs | 8 +- .../src/system_resources/memory_pressure.rs | 2 +- .../memory_pressure/shed_lru.rs | 216 +++++++++++++++--- 4 files changed, 199 insertions(+), 44 deletions(-) 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 910ef38bf4..613a377b1f 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 @@ -145,6 +145,16 @@ pub(crate) fn over_gate(snapshot: &PressureSnapshot) -> u64 { snapshot.over_gate(PRIORITY) } +impl continuum_kernel::system_resources::memory_pressure::Holder for MindResultsReporter { + fn priority(&self) -> MemoryPriority { + PRIORITY + } + + fn held_bytes(&self) -> u64 { + resident_bytes(&self.registry.resident_working_memories()) + } +} + /// 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)] @@ -341,12 +351,13 @@ impl MemoryReporter for MindResultsReporter { } 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", 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 c790633548..5450eab2b9 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 @@ -103,10 +103,14 @@ pub(super) fn register_persona_registry_modules( // The shared channel-element cache is rebuildable (airc is the record): RAM sizes it, it sheds // least recently used first under pressure, never an entry cap of ours. crate::cognition::channel_substrate::global_channel_element_cache().register(pressure_monitor); - pressure_monitor.add_reporter(Arc::new(crate::cognition::persona_workspace::MindResultsReporter::new( + let mind_results = Arc::new(crate::cognition::persona_workspace::MindResultsReporter::new( crate::cognition::persona_workspace::global(), pressure_monitor.subscribe(), - ))); + )); + // One overrun is shared across its priority's holders (Cormac on #5697): it joins the group. + let holder: Arc = mind_results.clone(); + crate::system_resources::memory_pressure::register_holder(Arc::downgrade(&holder)); + pressure_monitor.add_reporter(mind_results); // 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 diff --git a/core/continuum-kernel/src/system_resources/memory_pressure.rs b/core/continuum-kernel/src/system_resources/memory_pressure.rs index b8777ea4ec..f59a18de13 100644 --- a/core/continuum-kernel/src/system_resources/memory_pressure.rs +++ b/core/continuum-kernel/src/system_resources/memory_pressure.rs @@ -77,7 +77,7 @@ use crate::{clog_info, clog_warn}; mod poll_interval; pub use poll_interval::*; mod shed_lru; -pub use shed_lru::{ByteSized, ShedLru}; +pub use shed_lru::{register_holder, ByteSized, Holder, ShedLru}; mod memory_pressure_monitor; // ============================================================================= diff --git a/core/continuum-kernel/src/system_resources/memory_pressure/shed_lru.rs b/core/continuum-kernel/src/system_resources/memory_pressure/shed_lru.rs index a266fb1eb2..57fb0eb8ac 100644 --- a/core/continuum-kernel/src/system_resources/memory_pressure/shed_lru.rs +++ b/core/continuum-kernel/src/system_resources/memory_pressure/shed_lru.rs @@ -1,14 +1,16 @@ //! A rebuildable in-RAM cache that RAM sizes, never a number (Joel, 2026-10-29; Cormac on the //! pattern): entries are kept in recency order and, when the memory pressure monitor sheds, the -//! least recently used are dropped until the cache gives back exactly the host's overrun past its -//! priority's gate. Everything in it can be rebuilt (airc, a recompute), so its floor is zero. +//! least recently used are dropped until the cache gives back its share of the host's overrun past +//! its priority's gate. Everything in it can be rebuilt (airc, a recompute), so its floor is zero. //! //! One owner for the pattern: every in-process cache of rebuildable values registers one of these -//! with the monitor instead of carrying its own entry cap. +//! with the monitor instead of carrying its own entry cap. The overrun at a priority is shared +//! across every holder at that priority in proportion to what each holds, so one pressure event +//! frees it once (Cormac on #5697). use std::collections::{BTreeMap, HashMap}; use std::hash::Hash; -use std::sync::Arc; +use std::sync::{Arc, Weak}; use parking_lot::Mutex; use tokio::sync::watch; @@ -19,13 +21,55 @@ use super::{ }; impl PressureSnapshot { - /// Bytes the host is over `priority`'s gate (used RAM past `gate x total`): what a consumer at - /// that priority gives back when it sheds. Zero at or under the gate. + /// Bytes the host is over `priority`'s gate (used RAM past `gate x total`): what every consumer + /// at that priority gives back between them when they shed. Zero at or under the gate. pub fn over_gate(&self, priority: MemoryPriority) -> u64 { let used = self.total_bytes.saturating_sub(self.available_bytes); let gate = (self.total_bytes as f64 * priority.pressure_gate()) as u64; used.saturating_sub(gate) } + + /// The part of `priority`'s overrun a consumer holding `held` bytes gives back: its share in + /// proportion to what it holds among every registered holder at that priority, so one pressure + /// event frees the overrun once, not once per consumer. + pub fn share_of_overrun(&self, priority: MemoryPriority, held: u64) -> u64 { + let total = held_at(priority).max(held); + if total == 0 { + return 0; + } + (u128::from(self.over_gate(priority)) * u128::from(held) / u128::from(total)) as u64 + } +} + +/// A consumer that holds RAM at a priority and sheds a share of that priority's overrun. +pub trait Holder: Send + Sync { + fn priority(&self) -> MemoryPriority; + fn held_bytes(&self) -> u64; +} + +/// Every shedding consumer, held weakly (a dropped one leaves the group): the population an +/// overrun is apportioned across. +fn holders() -> &'static Mutex>> { + static HOLDERS: std::sync::OnceLock>>> = std::sync::OnceLock::new(); + HOLDERS.get_or_init(|| Mutex::new(Vec::new())) +} + +/// Join the group an overrun is shared across. +pub fn register_holder(holder: Weak) { + let mut holders = holders().lock(); + holders.retain(|held| held.strong_count() > 0); + holders.push(holder); +} + +/// Bytes every live holder at `priority` holds now. +fn held_at(priority: MemoryPriority) -> u64 { + holders() + .lock() + .iter() + .filter_map(Weak::upgrade) + .filter(|holder| holder.priority() == priority) + .map(|holder| holder.held_bytes()) + .sum() } /// How many bytes of RAM a cached value holds (what shedding it gives back). @@ -55,6 +99,13 @@ impl State { self.by_use.insert(tick, key.clone()); Some(Arc::clone(&entry.value)) } + + fn insert(&mut self, key: K, value: Arc) { + self.tick += 1; + let used = self.tick; + self.by_use.insert(used, key.clone()); + self.entries.insert(key, Entry { value, used }); + } } /// A cache of rebuildable values that the memory monitor sheds, least recently used first. @@ -82,13 +133,15 @@ impl ShedLru, monitor: &super::MemoryPressureMonitor) where K: 'static, V: 'static, { *self.pressure.lock() = Some(monitor.subscribe()); + let holder: Arc = Arc::clone(self) as Arc; + register_holder(Arc::downgrade(&holder)); monitor.add_reporter(Arc::clone(self) as Arc); } @@ -98,23 +151,27 @@ impl ShedLru V) -> Arc { let mut state = self.state.lock(); if let Some(value) = state.touch(&key) { return value; } - state.tick += 1; - let used = state.tick; let value = Arc::new(make()); - state.by_use.insert(used, key.clone()); - state.entries.insert( - key, - Entry { - value: Arc::clone(&value), - used, - }, - ); + state.insert(key, Arc::clone(&value)); + value + } + + /// Cache `value` under `key` unless one is already there, which wins (so every caller shares + /// one): for a value computed outside the lock, where two racing computations keep the first. + pub fn insert_if_absent(&self, key: K, value: V) -> Arc { + let mut state = self.state.lock(); + if let Some(existing) = state.touch(&key) { + return existing; + } + let value = Arc::new(value); + state.insert(key, Arc::clone(&value)); value } @@ -126,7 +183,7 @@ impl ShedLru u64 { self.state .lock() @@ -136,23 +193,43 @@ impl ShedLru u64 { let mut state = self.state.lock(); let mut freed = 0; - while freed < want { - let Some((_, key)) = state.by_use.pop_first() else { + let mut dropped = Vec::new(); + for (tick, key) in &state.by_use { + if freed >= want { break; - }; - if let Some(entry) = state.entries.remove(&key) { - freed += entry.value.byte_size(); } + if let Some(entry) = state.entries.get(key) { + if Arc::strong_count(&entry.value) == 1 { + freed += entry.value.byte_size(); + dropped.push((*tick, key.clone())); + } + } + } + for (tick, key) in dropped { + state.by_use.remove(&tick); + state.entries.remove(&key); } freed } } +impl Holder for ShedLru { + fn priority(&self) -> MemoryPriority { + self.priority + } + + fn held_bytes(&self) -> u64 { + self.bytes() + } +} + impl MemoryReporter for ShedLru { @@ -184,24 +261,25 @@ impl MemoryRepor true } - /// Give back the host's overrun past this priority's gate, least recently used first. + /// Give back this cache's share of the overrun past its priority's gate, least recently used first. fn shed_load(&self, _level: PressureLevel) { - let Some(overrun) = self + let held = self.bytes(); + let Some(share) = self .pressure .lock() .as_ref() - .map(|pressure| pressure.borrow().over_gate(self.priority)) + .map(|pressure| pressure.borrow().share_of_overrun(self.priority, held)) else { return; }; - if overrun > 0 { - let freed = self.shed(overrun); + if share > 0 { + let freed = self.shed(share); continuum_base::probe!( class = "memory.shed_lru.shed", cache = self.name, - overrun = overrun, + share = share, freed = freed, - "a rebuildable cache gave back RAM past its priority's gate" + "a rebuildable cache gave back its share of RAM past its priority's gate" ); } } @@ -223,8 +301,8 @@ mod tests { } // what this catches: a cache sized by a count instead of RAM, or shedding the wrong entries: - // it holds what it is given, gives back the requested bytes least-recently-used first, keeps - // a value it was just asked for, and shares one value per key. + // it gives back the requested bytes least-recently-used first, keeps a value it was just asked + // for, and shares one value per key. #[test] fn it_sheds_least_recently_used_first_by_bytes() { let lru = cache(); @@ -243,10 +321,72 @@ mod tests { lru.get(&0).is_some() && lru.get(&3).is_some(), "the recently used stay" ); - let first = lru.get_or_insert_with(7, || Bytes(1)); - let again = lru.get_or_insert_with(7, || Bytes(99)); - assert!(Arc::ptr_eq(&first, &again), "one shared value per key"); + let first = lru.insert_if_absent(7, Bytes(1)); + let again = lru.insert_if_absent(7, Bytes(99)); + assert!( + Arc::ptr_eq(&first, &again), + "one shared value per key; the first insert wins" + ); + drop((first, again)); assert_eq!(lru.shed(u64::MAX), 21, "shedding everything empties it"); assert!(lru.is_empty()); } + + // what this catches: an entry a caller still holds counted as freed: the cache would drain + // itself while the RAM stays pinned elsewhere. A held entry is skipped. + #[test] + fn a_held_entry_is_never_counted_as_freed() { + let lru = cache(); + let held = lru.get_or_insert_with(1, || Bytes(10)); + lru.get_or_insert_with(2, || Bytes(10)); + assert_eq!(lru.shed(u64::MAX), 10, "only the unheld entry frees"); + assert!(lru.get(&1).is_some(), "the held one stays cached"); + drop(held); + } + + struct Fixed(MemoryPriority, u64); + impl Holder for Fixed { + fn priority(&self) -> MemoryPriority { + self.0 + } + fn held_bytes(&self) -> u64 { + self.1 + } + } + + // what this catches: every consumer at a priority shedding the WHOLE overrun, so N caches free N + // times what the host needed and rebuildable entries thrash: the shares of one overrun across a + // priority's holders add up to the overrun, in proportion to what each holds. + #[test] + fn one_overrun_is_shared_across_a_priority_not_repeated() { + let priority = MemoryPriority::Batch; // a priority no other test in this crate registers + let a: Arc = Arc::new(Fixed(priority, 300)); + let b: Arc = Arc::new(Fixed(priority, 100)); + register_holder(Arc::downgrade(&a)); + register_holder(Arc::downgrade(&b)); + let snapshot = PressureSnapshot { + total_bytes: 1000, + available_bytes: 300, + ..PressureSnapshot::default() + }; + assert_eq!( + snapshot.over_gate(priority), + 200, + "used 700 of 1000 is 200 past Batch's 0.50 gate" + ); + let (share_a, share_b) = ( + snapshot.share_of_overrun(priority, 300), + snapshot.share_of_overrun(priority, 100), + ); + assert_eq!( + (share_a, share_b), + (150, 50), + "in proportion to what each holds" + ); + assert_eq!( + share_a + share_b, + 200, + "the shares add up to the overrun once" + ); + } } From c0663088b648a9c50a1b7af1fccb45776401684f Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 20:27:10 -0600 Subject: [PATCH 3/7] The core's scope peer is designated once: the same peer is idempotent, a different one is refused before anything registers, and boot fails rather than run as two identities (Codex on #5697) - self_peer::ScopeRegistry (instance-owned; scopes() is the process's): designate(peer) is idempotent for the same peer and returns a typed ScopeConflict{existing, offered} for another, before the peer enters the self set. - AircModule::from_discovery(discovery, scopes) -> Result; boot propagates a conflict as a named io error (the module can never attach as B while the relay and beacon publish as A). Tests and the remote-lane fixture pass a fresh registry, so there is no global-test race. - airc_boot's peer short form uses airc's shown_form, not a .take(8) cut. Tests (M5, serving down 02:23-02:27Z): mind self_peer+chat 54 (new: same peer idempotent, a different one refused, the first stays); core modules::airc+inbound_attach+data_wiring+ remote_lane+grid_capacity 44; core check --tests clean; ratchets exit 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/ipc/start_server/airc_boot.rs | 8 ++- core/continuum-core/src/modules/airc.rs | 28 ++++++---- .../test_env/mind_integration/remote_lane.rs | 3 +- core/continuum-mind/src/chat/tests/mod.rs | 4 +- core/continuum-mind/src/persona/self_peer.rs | 54 ++++++++++++++++--- 5 files changed, 77 insertions(+), 20 deletions(-) diff --git a/core/continuum-core/src/ipc/start_server/airc_boot.rs b/core/continuum-core/src/ipc/start_server/airc_boot.rs index fd95f8cb5c..ba9c41dab6 100644 --- a/core/continuum-core/src/ipc/start_server/airc_boot.rs +++ b/core/continuum-core/src/ipc/start_server/airc_boot.rs @@ -81,7 +81,7 @@ pub(super) fn discover_and_register_airc( room_name, .. } => { - let peer_short: String = peer_id.to_string().chars().take(8).collect(); + let peer_short = airc_core::shown_id::shown_form(*peer_id); ( BootStatusKind::Ok, format!( @@ -101,7 +101,11 @@ pub(super) fn discover_and_register_airc( }; boot_status("airc", kind, &detail); } - let airc_module = Arc::new(AircModule::from_discovery(&discovery)); + // A second, different scope peer refuses boot rather than run as two identities (Codex on #5697). + let airc_module = Arc::new( + AircModule::from_discovery(&discovery, crate::persona::self_peer::scopes()) + .map_err(|conflict| std::io::Error::other(conflict.to_string()))?, + ); // #432 (was the vestigial gate): persona hosting needs the DAEMON SOCKET // only — #298 removed the operator room from birth deps, but the zip here // still required a discovered default room, so "no default room ⇒ no diff --git a/core/continuum-core/src/modules/airc.rs b/core/continuum-core/src/modules/airc.rs index bb778690da..fce57f4748 100644 --- a/core/continuum-core/src/modules/airc.rs +++ b/core/continuum-core/src/modules/airc.rs @@ -79,9 +79,12 @@ impl AircModule { /// (the boot banner / log output can show what was resolved /// before the failure), but the module construction does not /// pretend. - pub fn from_discovery(discovery: &crate::airc::AircDiscovery) -> Self { + pub fn from_discovery( + discovery: &crate::airc::AircDiscovery, + scopes: &crate::persona::self_peer::ScopeRegistry, + ) -> Result { use crate::airc::AircDiscovery; - match discovery { + Ok(match discovery { AircDiscovery::Healthy { socket, default_room, @@ -96,7 +99,9 @@ impl AircModule { // beacon echo back. // This scope peer is the identity the core publishes as: realtime publishes, the // capacity beacon, and the relay `chat/send` publishes callers' lines as (#5696). - crate::persona::self_peer::register_scope(*peer_id); + // A different scope peer is refused before anything is registered (Codex on #5697). + scopes.designate(*peer_id)?; + crate::persona::self_peer::register(*peer_id); Self { queue_client: Arc::new(CliAircQueueClient::new(TokioAircCommandRunner)), // #3849: the socket is re-resolved when the daemon @@ -123,7 +128,7 @@ impl AircModule { AircDiscovery::Degraded { .. } | AircDiscovery::Unreachable { .. } => { Self::with_queue_client(Arc::new(CliAircQueueClient::new(TokioAircCommandRunner))) } - } + }) } pub fn with_daemon_home(airc_home: impl Into) -> Self { @@ -286,7 +291,8 @@ mod from_discovery_tests { peer_id: peer, }; - let module = AircModule::from_discovery(&discovery); + let module = AircModule::from_discovery(&discovery, &crate::persona::self_peer::ScopeRegistry::default()) + .expect("test: a fresh scope registry takes any peer"); assert_eq!( module.daemon_socket(), @@ -331,7 +337,8 @@ mod from_discovery_tests { }, }; - let module = AircModule::from_discovery(&discovery); + let module = AircModule::from_discovery(&discovery, &crate::persona::self_peer::ScopeRegistry::default()) + .expect("test: a fresh scope registry takes any peer"); assert_eq!( module.daemon_socket(), @@ -362,7 +369,8 @@ mod from_discovery_tests { }, }; - let module = AircModule::from_discovery(&discovery); + let module = AircModule::from_discovery(&discovery, &crate::persona::self_peer::ScopeRegistry::default()) + .expect("test: a fresh scope registry takes any peer"); assert_eq!( module.daemon_socket(), @@ -383,7 +391,8 @@ mod from_discovery_tests { reason: DiscoveryFailure::AutoInstallDisabled, }; - let module = AircModule::from_discovery(&discovery); + let module = AircModule::from_discovery(&discovery, &crate::persona::self_peer::ScopeRegistry::default()) + .expect("test: a fresh scope registry takes any peer"); assert_eq!(module.daemon_socket(), None); assert_eq!(module.default_room(), None); @@ -425,7 +434,8 @@ mod from_discovery_tests { ), ]; for (discovery, expect_socket_some) in cases { - let module = AircModule::from_discovery(&discovery); + let module = AircModule::from_discovery(&discovery, &crate::persona::self_peer::ScopeRegistry::default()) + .expect("test: a fresh scope registry takes any peer"); assert_eq!( module.daemon_socket().is_some(), expect_socket_some, diff --git a/core/continuum-core/src/test_env/mind_integration/remote_lane.rs b/core/continuum-core/src/test_env/mind_integration/remote_lane.rs index 791db51f43..294c48a5a4 100644 --- a/core/continuum-core/src/test_env/mind_integration/remote_lane.rs +++ b/core/continuum-core/src/test_env/mind_integration/remote_lane.rs @@ -37,7 +37,8 @@ async fn an_override_naming_this_node_is_retired_at_build_and_she_is_born_home() default_room: airc_core::RoomId::from_uuid(uuid::Uuid::new_v4()), room_name: "general".to_string(), peer_id: me, - }); + }, &crate::persona::self_peer::ScopeRegistry::default()) + .expect("test: a fresh scope registry takes any peer"); PersonaModelOverride::new_remote("ggml-org/Qwen3.8-27B-GGUF", Some("placement:fleet".to_string()), 1, me.to_string()) .write(&home) .expect("write override"); diff --git a/core/continuum-mind/src/chat/tests/mod.rs b/core/continuum-mind/src/chat/tests/mod.rs index f4dda54c0d..fd3bc85e49 100644 --- a/core/continuum-mind/src/chat/tests/mod.rs +++ b/core/continuum-mind/src/chat/tests/mod.rs @@ -28,7 +28,9 @@ let executor = Arc::new(CommandExecutor::new(registry)); // The relay this core publishes callers' lines as (the airc module registers it in // production); first registration wins process-wide. - crate::persona::self_peer::register_scope(uuid::Uuid::from_u128(0x7e1a)); + crate::persona::self_peer::scopes() + .designate(uuid::Uuid::from_u128(0x7e1a)) + .expect("test: every chat test uses one relay"); ChatModule::with_executor(executor) } diff --git a/core/continuum-mind/src/persona/self_peer.rs b/core/continuum-mind/src/persona/self_peer.rs index e7285fc1c8..fe1fb78c6b 100644 --- a/core/continuum-mind/src/persona/self_peer.rs +++ b/core/continuum-mind/src/persona/self_peer.rs @@ -33,19 +33,46 @@ pub fn register(peer: Uuid) { registered().lock().unwrap_or_else(|p| p.into_inner()).insert(peer); // JUSTIFIED unwrap_or_else: a poisoned set still holds the ids; membership is bookkeeping, never truth } +/// A second, different scope peer offered to a registry that already holds one. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +#[error("this core's scope peer is {existing}; refusing to also attach as {offered}")] +pub struct ScopeConflict { + pub existing: Uuid, + pub offered: Uuid, +} + /// The core's own project-scope peer: the identity it publishes as (airc realtime publishes, relayed -/// callers' lines, the capacity beacon). One of the ids above, designated once by the airc module. -static SCOPE: OnceLock = OnceLock::new(); +/// callers' lines, the capacity beacon). Designated once; the same peer again is a no-op, and a +/// different one is refused, so the module can never attach as one peer while the relay and the +/// beacon publish as another (Codex on #5697). Instance-owned so a test holds its own. +#[derive(Debug, Default)] +pub struct ScopeRegistry(OnceLock); + +impl ScopeRegistry { + /// Designate `peer` as the scope peer: idempotent for the same peer, refused for another. + pub fn designate(&self, peer: Uuid) -> Result<(), ScopeConflict> { + let existing = *self.0.get_or_init(|| peer); + if existing == peer { + Ok(()) + } else { + Err(ScopeConflict { existing, offered: peer }) + } + } -/// Designate the core's project-scope peer (and record it as one of this process's ids). -pub fn register_scope(peer: Uuid) { - register(peer); - let _ = SCOPE.set(peer); // first designation wins: the airc module constructs once per process + pub fn scope(&self) -> Option { + self.0.get().copied() + } +} + +/// The process's scope registry. +pub fn scopes() -> &'static ScopeRegistry { + static SCOPES: OnceLock = OnceLock::new(); + SCOPES.get_or_init(ScopeRegistry::default) } /// The core's project-scope peer, once the airc module has attached. pub fn scope() -> Option { - SCOPE.get().copied() + scopes().scope() } /// Is `peer` one of the ids this process wears? A peer that is this node is never a @@ -65,6 +92,19 @@ pub fn is_this_node(peer: Uuid) -> bool { mod tests { use super::*; + // what this catches: a second, different scope peer silently ignored, so the airc module + // attaches as B while the relay and the beacon still publish as A (Codex on #5697): the same + // peer is idempotent, a different one is refused and leaves the first in place. + #[test] + fn a_scope_is_designated_once_and_a_different_one_is_refused() { + let scopes = ScopeRegistry::default(); + let (a, b) = (Uuid::new_v4(), Uuid::new_v4()); + assert_eq!(scopes.designate(a), Ok(())); + assert_eq!(scopes.designate(a), Ok(()), "the same peer again is a no-op"); + assert_eq!(scopes.designate(b), Err(ScopeConflict { existing: a, offered: b })); + assert_eq!(scopes.scope(), Some(a), "the first stays"); + } + // what this catches (card 2500d2f1): a node that wears N airc ids must answer "me" // for every one of them and for nobody else — the M5 knew one of its three and // seated minds on the other two. From 1320fbfe982c79906288adf0a5256c34e79f6842 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 20:43:43 -0600 Subject: [PATCH 4/7] The monitor publishes what each priority holds, and shares are computed from it: the second holder registry is gone (Cormac on #5697) - PressureSnapshot.held_by_priority (HeldAtPriority, ts-exported): the monitor's poll sums each live reporter's report().bytes by its priority, read off-lock beside report() (a quarantined reporter contributes nothing and sheds nothing; every monitor counts its own reporters). - MemoryReporter::priority() (cheap; defaults to the budget's), overridden by ShedLru and mind_results so a costly budget() never runs per poll. - share_of_overrun reads snapshot.held_at(priority); Holder, register_holder and the global group are deleted, with their wiring. - poll_interval: PRESSURE_FLOOR/PRESSURE_CEILING were the Interactive and Realtime gates restated; normalization now reads them from the gate table, as the explicit zones its doc describes. Tests (M5, serving down 02:41-02:44Z): kernel memory_pressure 26 (shares of one overrun across a priority's held bytes add up to it once); cognition channel_element + mind_results 12; core check --tests clean; ratchets exit 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../mind_results_reporter.rs | 14 +-- .../start_server/persona_registry_modules.rs | 3 - .../src/system_resources/memory_pressure.rs | 2 +- .../memory_pressure_monitor.rs | 12 ++- .../memory_pressure/poll_interval.rs | 44 ++++++-- .../memory_pressure/shed_lru.rs | 100 ++++++------------ protocol/typescript/system/HeldAtPriority.ts | 8 ++ .../typescript/system/PressureSnapshot.ts | 5 + 8 files changed, 91 insertions(+), 97 deletions(-) create mode 100644 protocol/typescript/system/HeldAtPriority.ts 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 613a377b1f..11ccc29c9d 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 @@ -145,16 +145,6 @@ pub(crate) fn over_gate(snapshot: &PressureSnapshot) -> u64 { snapshot.over_gate(PRIORITY) } -impl continuum_kernel::system_resources::memory_pressure::Holder for MindResultsReporter { - fn priority(&self) -> MemoryPriority { - PRIORITY - } - - fn held_bytes(&self) -> u64 { - resident_bytes(&self.registry.resident_working_memories()) - } -} - /// 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)] @@ -346,6 +336,10 @@ impl MemoryReporter for MindResultsReporter { } } + fn priority(&self) -> MemoryPriority { + PRIORITY + } + fn can_shed(&self) -> bool { true } 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 5450eab2b9..3c70f49c9e 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 @@ -107,9 +107,6 @@ pub(super) fn register_persona_registry_modules( crate::cognition::persona_workspace::global(), pressure_monitor.subscribe(), )); - // One overrun is shared across its priority's holders (Cormac on #5697): it joins the group. - let holder: Arc = mind_results.clone(); - crate::system_resources::memory_pressure::register_holder(Arc::downgrade(&holder)); pressure_monitor.add_reporter(mind_results); // The dream/consolidation region goes LIVE (#145 slice B): per live persona, // on a material-driven cadence (dreams only when undigested episodic diff --git a/core/continuum-kernel/src/system_resources/memory_pressure.rs b/core/continuum-kernel/src/system_resources/memory_pressure.rs index f59a18de13..b8777ea4ec 100644 --- a/core/continuum-kernel/src/system_resources/memory_pressure.rs +++ b/core/continuum-kernel/src/system_resources/memory_pressure.rs @@ -77,7 +77,7 @@ use crate::{clog_info, clog_warn}; mod poll_interval; pub use poll_interval::*; mod shed_lru; -pub use shed_lru::{register_holder, ByteSized, Holder, ShedLru}; +pub use shed_lru::{ByteSized, ShedLru}; mod memory_pressure_monitor; // ============================================================================= diff --git a/core/continuum-kernel/src/system_resources/memory_pressure/memory_pressure_monitor.rs b/core/continuum-kernel/src/system_resources/memory_pressure/memory_pressure_monitor.rs index cad5cef076..cfcadf5f15 100644 --- a/core/continuum-kernel/src/system_resources/memory_pressure/memory_pressure_monitor.rs +++ b/core/continuum-kernel/src/system_resources/memory_pressure/memory_pressure_monitor.rs @@ -387,10 +387,10 @@ impl MemoryPressureMonitor { let mut results: Vec<(usize, ReporterCallOutcome)> = Vec::with_capacity(live.len()); for (idx, reporter) in live { let handle = tokio::task::spawn_blocking(move || { - std::panic::catch_unwind(AssertUnwindSafe(|| reporter.report())) + std::panic::catch_unwind(AssertUnwindSafe(|| (reporter.report(), reporter.priority()))) }); let outcome = match tokio::time::timeout(REPORTER_TIMEOUT, handle).await { - Ok(Ok(Ok(report))) => ReporterCallOutcome::Report(report), + Ok(Ok(Ok((report, priority)))) => ReporterCallOutcome::Report(report, priority), Ok(Ok(Err(_panic))) => ReporterCallOutcome::Panicked, Ok(Err(join_err)) => ReporterCallOutcome::JoinError(format!("{join_err:?}")), Err(_elapsed) => ReporterCallOutcome::TimedOut, @@ -404,12 +404,17 @@ impl MemoryPressureMonitor { let mut st = self.state.lock(); let mut module_reports = Vec::with_capacity(results.len()); + let mut held_by_priority: Vec = Vec::new(); for (idx, outcome) in results { let entry = &mut st.reporters[idx]; let name = entry.reporter.name(); match outcome { - ReporterCallOutcome::Report(report) => { + ReporterCallOutcome::Report(report, priority) => { entry.consecutive_panics = 0; + match held_by_priority.iter_mut().find(|held| held.priority == priority) { + Some(held) => held.bytes += report.bytes, + None => held_by_priority.push(HeldAtPriority { priority, bytes: report.bytes }), + } module_reports.push(report); } ReporterCallOutcome::Panicked => { @@ -501,6 +506,7 @@ impl MemoryPressureMonitor { available_bytes: available, swap_used_bytes: swap_used, modules: module_reports, + held_by_priority, timestamp_ms: now_ms, consecutive_at_level, }; diff --git a/core/continuum-kernel/src/system_resources/memory_pressure/poll_interval.rs b/core/continuum-kernel/src/system_resources/memory_pressure/poll_interval.rs index 710d816b93..dc04fe4e30 100644 --- a/core/continuum-kernel/src/system_resources/memory_pressure/poll_interval.rs +++ b/core/continuum-kernel/src/system_resources/memory_pressure/poll_interval.rs @@ -204,12 +204,6 @@ pub enum PressureLevel { Critical, } -/// Threshold constants for pressure level boundaries. -/// Below FLOOR = Normal (0.0 normalized), above CEILING = Critical (1.0 normalized). -pub(super) const PRESSURE_FLOOR: f64 = 0.80; - -pub(super) const PRESSURE_CEILING: f64 = 0.95; - impl PressureLevel { pub(super) fn from_pressure(pressure: f64) -> Self { // Thresholds are SYSTEM-WIDE memory, not process-only. @@ -227,9 +221,9 @@ impl PressureLevel { } } - /// Normalize raw pressure (used/total) to 0.0-1.0 action range. - /// 0.0 = at or below floor (no concern), 1.0 = at or above ceiling (emergency). - /// Linear interpolation between PRESSURE_FLOOR and PRESSURE_CEILING. + /// Normalize raw pressure (used/total) to the 0.0-1.0 action zone: 0.0 at or below the + /// Interactive gate (no concern), 1.0 at or above the Realtime gate (emergency), linear between. + /// The zone's ends ARE those gates: one table of gates, never a second pair of thresholds. /// Swap is its own pressure axis. macOS counts swapped-out and compressible pages /// as "available", so `from_pressure` read NORMAL on 2026-09-08 while swap sat at /// 40 of 41 GB and the model server paged weights from disk at 1–9 t/s. Half the @@ -272,7 +266,15 @@ impl PressureLevel { } pub(super) fn normalize(pressure: f64) -> f64 { - ((pressure - PRESSURE_FLOOR) / (PRESSURE_CEILING - PRESSURE_FLOOR)).clamp(0.0, 1.0) + let floor = MemoryPriority::Interactive.pressure_gate(); + let ceiling = MemoryPriority::Realtime.pressure_gate(); + if pressure <= floor { + 0.0 + } else if pressure >= ceiling { + 1.0 + } else { + (pressure - floor) / (ceiling - floor) + } } pub(super) fn to_u8(self) -> u8 { @@ -491,6 +493,8 @@ pub struct PressureSnapshot { pub swap_used_bytes: u64, /// Per-module memory breakdown (empty if no reporters registered) pub modules: Vec, + /// Bytes held at each priority this poll (from every live reporter's report and priority). + pub held_by_priority: Vec, /// Timestamp (ms since epoch) #[ts(type = "number")] pub timestamp_ms: u64, @@ -509,12 +513,24 @@ impl Default for PressureSnapshot { available_bytes: 0, swap_used_bytes: 0, modules: Vec::new(), + held_by_priority: Vec::new(), timestamp_ms: 0, consecutive_at_level: 0, } } } +/// Bytes every reporter at one priority held at the snapshot's poll: what that priority's overrun +/// is shared across. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, TS)] +#[ts(export, export_to = "../../../protocol/typescript/system/HeldAtPriority.ts")] +#[serde(rename_all = "camelCase")] +pub struct HeldAtPriority { + pub priority: MemoryPriority, + #[ts(type = "number")] + pub bytes: u64, +} + // ============================================================================= // Memory Reporter Trait // ============================================================================= @@ -543,6 +559,12 @@ pub trait MemoryReporter: Send + Sync { /// Report current memory usage. Must be fast and non-blocking. fn report(&self) -> ModuleMemoryReport; + /// The priority this reporter sheds at: read every poll beside `report()`, so keep it cheap. + /// Defaults to the declared budget's; a reporter whose budget is costly to compute overrides it. + fn priority(&self) -> MemoryPriority { + self.budget().priority + } + /// Whether this reporter can shed load under pressure. fn can_shed(&self) -> bool { false @@ -577,7 +599,7 @@ pub(super) struct ReporterEntry { /// reporter's name + count are resolved during the fold (so the warning text /// reflects the post-increment count), keeping this enum data-only. pub(super) enum ReporterCallOutcome { - Report(ModuleMemoryReport), + Report(ModuleMemoryReport, MemoryPriority), /// Reporter body panicked (caught inside `spawn_blocking`). Panicked, /// `spawn_blocking` itself failed to join (runtime-level, not a body panic). diff --git a/core/continuum-kernel/src/system_resources/memory_pressure/shed_lru.rs b/core/continuum-kernel/src/system_resources/memory_pressure/shed_lru.rs index 57fb0eb8ac..230e1412d8 100644 --- a/core/continuum-kernel/src/system_resources/memory_pressure/shed_lru.rs +++ b/core/continuum-kernel/src/system_resources/memory_pressure/shed_lru.rs @@ -5,12 +5,12 @@ //! //! One owner for the pattern: every in-process cache of rebuildable values registers one of these //! with the monitor instead of carrying its own entry cap. The overrun at a priority is shared -//! across every holder at that priority in proportion to what each holds, so one pressure event -//! frees it once (Cormac on #5697). +//! across every reporter at that priority in proportion to what each holds (the monitor publishes +//! what each priority holds in its snapshot), so one pressure event frees it once (Cormac on #5697). use std::collections::{BTreeMap, HashMap}; use std::hash::Hash; -use std::sync::{Arc, Weak}; +use std::sync::Arc; use parking_lot::Mutex; use tokio::sync::watch; @@ -29,11 +29,20 @@ impl PressureSnapshot { used.saturating_sub(gate) } + /// Bytes every reporter at `priority` held at this snapshot's poll. + pub fn held_at(&self, priority: MemoryPriority) -> u64 { + self.held_by_priority + .iter() + .filter(|held| held.priority == priority) + .map(|held| held.bytes) + .sum() + } + /// The part of `priority`'s overrun a consumer holding `held` bytes gives back: its share in - /// proportion to what it holds among every registered holder at that priority, so one pressure - /// event frees the overrun once, not once per consumer. + /// proportion to what it holds among every reporter at that priority (the monitor's own count of + /// its reporters, published in the snapshot), so one pressure event frees the overrun once. pub fn share_of_overrun(&self, priority: MemoryPriority, held: u64) -> u64 { - let total = held_at(priority).max(held); + let total = self.held_at(priority).max(held); if total == 0 { return 0; } @@ -41,37 +50,6 @@ impl PressureSnapshot { } } -/// A consumer that holds RAM at a priority and sheds a share of that priority's overrun. -pub trait Holder: Send + Sync { - fn priority(&self) -> MemoryPriority; - fn held_bytes(&self) -> u64; -} - -/// Every shedding consumer, held weakly (a dropped one leaves the group): the population an -/// overrun is apportioned across. -fn holders() -> &'static Mutex>> { - static HOLDERS: std::sync::OnceLock>>> = std::sync::OnceLock::new(); - HOLDERS.get_or_init(|| Mutex::new(Vec::new())) -} - -/// Join the group an overrun is shared across. -pub fn register_holder(holder: Weak) { - let mut holders = holders().lock(); - holders.retain(|held| held.strong_count() > 0); - holders.push(holder); -} - -/// Bytes every live holder at `priority` holds now. -fn held_at(priority: MemoryPriority) -> u64 { - holders() - .lock() - .iter() - .filter_map(Weak::upgrade) - .filter(|holder| holder.priority() == priority) - .map(|holder| holder.held_bytes()) - .sum() -} - /// How many bytes of RAM a cached value holds (what shedding it gives back). pub trait ByteSized { fn byte_size(&self) -> u64; @@ -140,8 +118,6 @@ impl ShedLru = Arc::clone(self) as Arc; - register_holder(Arc::downgrade(&holder)); monitor.add_reporter(Arc::clone(self) as Arc); } @@ -220,16 +196,6 @@ impl ShedLru Holder for ShedLru { - fn priority(&self) -> MemoryPriority { - self.priority - } - - fn held_bytes(&self) -> u64 { - self.bytes() - } -} - impl MemoryReporter for ShedLru { @@ -257,6 +223,10 @@ impl MemoryRepor } } + fn priority(&self) -> MemoryPriority { + self.priority + } + fn can_shed(&self) -> bool { true } @@ -288,6 +258,7 @@ impl MemoryRepor #[cfg(test)] mod tests { use super::*; + use crate::system_resources::memory_pressure::HeldAtPriority; struct Bytes(u64); impl ByteSized for Bytes { @@ -344,35 +315,26 @@ mod tests { drop(held); } - struct Fixed(MemoryPriority, u64); - impl Holder for Fixed { - fn priority(&self) -> MemoryPriority { - self.0 - } - fn held_bytes(&self) -> u64 { - self.1 - } - } - // what this catches: every consumer at a priority shedding the WHOLE overrun, so N caches free N // times what the host needed and rebuildable entries thrash: the shares of one overrun across a - // priority's holders add up to the overrun, in proportion to what each holds. + // priority's reporters (as the monitor counted them) add up to the overrun, in proportion to what + // each holds. #[test] fn one_overrun_is_shared_across_a_priority_not_repeated() { - let priority = MemoryPriority::Batch; // a priority no other test in this crate registers - let a: Arc = Arc::new(Fixed(priority, 300)); - let b: Arc = Arc::new(Fixed(priority, 100)); - register_holder(Arc::downgrade(&a)); - register_holder(Arc::downgrade(&b)); + let priority = MemoryPriority::Background; let snapshot = PressureSnapshot { total_bytes: 1000, available_bytes: 300, + held_by_priority: vec![HeldAtPriority { + priority, + bytes: 400, + }], ..PressureSnapshot::default() }; assert_eq!( snapshot.over_gate(priority), - 200, - "used 700 of 1000 is 200 past Batch's 0.50 gate" + 100, + "used 700 of 1000 is 100 past Background's 0.60 gate" ); let (share_a, share_b) = ( snapshot.share_of_overrun(priority, 300), @@ -380,12 +342,12 @@ mod tests { ); assert_eq!( (share_a, share_b), - (150, 50), + (75, 25), "in proportion to what each holds" ); assert_eq!( share_a + share_b, - 200, + 100, "the shares add up to the overrun once" ); } diff --git a/protocol/typescript/system/HeldAtPriority.ts b/protocol/typescript/system/HeldAtPriority.ts new file mode 100644 index 0000000000..137949d9e7 --- /dev/null +++ b/protocol/typescript/system/HeldAtPriority.ts @@ -0,0 +1,8 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { MemoryPriority } from "./MemoryPriority"; + +/** + * Bytes every reporter at one priority held at the snapshot's poll: what that priority's overrun + * is shared across. + */ +export type HeldAtPriority = { priority: MemoryPriority, bytes: number, }; diff --git a/protocol/typescript/system/PressureSnapshot.ts b/protocol/typescript/system/PressureSnapshot.ts index 6394ffa4d8..be21d149b7 100644 --- a/protocol/typescript/system/PressureSnapshot.ts +++ b/protocol/typescript/system/PressureSnapshot.ts @@ -1,4 +1,5 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { HeldAtPriority } from "./HeldAtPriority"; import type { ModuleMemoryReport } from "./ModuleMemoryReport"; import type { PressureLevel } from "./PressureLevel"; @@ -39,6 +40,10 @@ swap_used_bytes: number, * Per-module memory breakdown (empty if no reporters registered) */ modules: Array, +/** + * Bytes held at each priority this poll (from every live reporter's report and priority). + */ +held_by_priority: Array, /** * Timestamp (ms since epoch) */ From b9c02de5db88c7eb22fc290cf2dc7835f24965e2 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 20:47:33 -0600 Subject: [PATCH 5/7] Only reports that can shed count toward a priority's held total (Cormac's note on #5697) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../memory_pressure/memory_pressure_monitor.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/core/continuum-kernel/src/system_resources/memory_pressure/memory_pressure_monitor.rs b/core/continuum-kernel/src/system_resources/memory_pressure/memory_pressure_monitor.rs index cfcadf5f15..4c725400a6 100644 --- a/core/continuum-kernel/src/system_resources/memory_pressure/memory_pressure_monitor.rs +++ b/core/continuum-kernel/src/system_resources/memory_pressure/memory_pressure_monitor.rs @@ -411,9 +411,13 @@ impl MemoryPressureMonitor { match outcome { ReporterCallOutcome::Report(report, priority) => { entry.consecutive_panics = 0; - match held_by_priority.iter_mut().find(|held| held.priority == priority) { - Some(held) => held.bytes += report.bytes, - None => held_by_priority.push(HeldAtPriority { priority, bytes: report.bytes }), + // Only what can shed shares an overrun: an unsheddable reporter would claim a + // share it never frees (Cormac on #5697). + if report.can_shed { + match held_by_priority.iter_mut().find(|held| held.priority == priority) { + Some(held) => held.bytes += report.bytes, + None => held_by_priority.push(HeldAtPriority { priority, bytes: report.bytes }), + } } module_reports.push(report); } From 9236b724143005e733e0db96503329c93d4c4810 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 21:16:56 -0600 Subject: [PATCH 6/7] The restart tests designate their relay through the scope registry (rebased onto #5696's door) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/continuum-mind/src/chat/tests/restart.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/continuum-mind/src/chat/tests/restart.rs b/core/continuum-mind/src/chat/tests/restart.rs index a76a7177e2..83d09b24ba 100644 --- a/core/continuum-mind/src/chat/tests/restart.rs +++ b/core/continuum-mind/src/chat/tests/restart.rs @@ -26,7 +26,9 @@ fn real_store_chat(airc: StubAircModule) -> ChatModule { registry.register(Arc::new(airc)); let executor = Arc::new(CommandExecutor::new(registry.clone())); registry.install_executor_on_all(executor.clone()); - crate::chat::publication::register_relay(airc_core::PeerId::from_u128(0x7e1a)); + crate::persona::self_peer::scopes() + .designate(Uuid::from_u128(0x7e1a)) + .expect("test: every chat test designates the same relay"); // test: a fixture step that must succeed ChatModule::with_executor(executor) } From c61895aa53470df615dbe7874b8525ffed22cf59 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 23:12:27 -0600 Subject: [PATCH 7/7] Fixture envelopes use peer uuids (typed source ids refuse a name); the dead over_gate wrapper and its duplicate test go (CI on #5697: warnings 13 -> 14, two mind fixtures) Tests (M5, serving down 05:07-05:12Z): mind full lib 1104; cognition mind_results + channel_element 11; ratchets exit 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../mind_results_reporter.rs | 11 ++------ .../tests/mind_results_reporter.rs | 26 +------------------ .../airc_persona_conversation/tests/mod.rs | 2 +- .../airc_persona_conversation/tests/part_2.rs | 2 +- 4 files changed, 5 insertions(+), 36 deletions(-) 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 11ccc29c9d..cf9dbd85ee 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 @@ -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; @@ -138,13 +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 { - snapshot.over_gate(PRIORITY) -} - /// 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)] 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 bc69d458b4..566cbfa19d 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,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; @@ -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" - ); -} diff --git a/core/continuum-mind/src/persona/airc_persona_conversation/tests/mod.rs b/core/continuum-mind/src/persona/airc_persona_conversation/tests/mod.rs index 861f884ed0..e4bc569583 100644 --- a/core/continuum-mind/src/persona/airc_persona_conversation/tests/mod.rs +++ b/core/continuum-mind/src/persona/airc_persona_conversation/tests/mod.rs @@ -53,7 +53,7 @@ telemetry.kind = airc_core::TranscriptKind::System; let envelope = serde_json::from_value(serde_json::json!({ "eventId": telemetry.event_id.to_string(), "roomId": room.to_string(), - "sourceId": "grid-capacity", "createdAtMs": 1, + "sourceId": Uuid::new_v4().to_string(), "createdAtMs": 1, "delivery": "ephemeral_coalesced", "payload": { "kind": "existing_schema", "payload": { "schema": "grid_capacity", "inline": {} } diff --git a/core/continuum-mind/src/persona/airc_persona_conversation/tests/part_2.rs b/core/continuum-mind/src/persona/airc_persona_conversation/tests/part_2.rs index 391aeb6ab9..87633ff21e 100644 --- a/core/continuum-mind/src/persona/airc_persona_conversation/tests/part_2.rs +++ b/core/continuum-mind/src/persona/airc_persona_conversation/tests/part_2.rs @@ -257,7 +257,7 @@ use super::*; json!({ "eventId": Uuid::from_u128(9).to_string(), "roomId": Uuid::from_u128(2).to_string(), - "sourceId": "continuum-peer", + "sourceId": PeerId::from_u128(5).as_uuid().to_string(), "createdAtMs": 100u64, "delivery": "durable", "payload": {