From df36050ed29e1255d30a23417616b043e13b6069 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 17:37:26 -0600 Subject: [PATCH 1/7] Perception from the store, P2 drain (decision half): a mind's next page after her cursor, in commit order, with explicit gaps chat::drain::next decides, purely, what a mind perceives next from the store. It returns: - Drained::Rows{rows, scanned_through}: commit order; her own rows are skipped but still advance the scan; - Drained::Gap{from, through, reason}: Retention when her cursor is below the retained floor; UnvouchedImport (said once, before her first rows) when her rooms' watermark history is unvouched; - Drained::Empty. ChatModule::drain_page reads the page (arrivalSeq > through, her rooms, sorted, limited by the consumer's intake), the retained floor and the rooms' watermark histories from the store's own indexes. Routing reads the typed header only. Cross-room fairness needs no scheduler: the cursor only moves forward through commit order. Not here, by design (#5691 773d34a4): durable acceptance (pending perception, cursor prefix and gap receipts committed together) rides the shared consumption owner Codex is extracting; the consumer wiring and deleting events_tx wait for it. Tests (M5, serving down 23:35Z): mind chat 48 pass (new: own rows skipped but scanned; retention and unvouched gaps explicit, unvouched told once then rows); core check clean. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/continuum-mind/src/chat/drain.rs | 274 ++++++++++++++++++++++++++ core/continuum-mind/src/chat/mod.rs | 1 + 2 files changed, 275 insertions(+) create mode 100644 core/continuum-mind/src/chat/drain.rs diff --git a/core/continuum-mind/src/chat/drain.rs b/core/continuum-mind/src/chat/drain.rs new file mode 100644 index 0000000000..e21f457885 --- /dev/null +++ b/core/continuum-mind/src/chat/drain.rs @@ -0,0 +1,274 @@ +//! A mind's drain over the store's arrivals (PERCEPTION-FROM-THE-STORE.md, P2): the next page after +//! her cursor, in commit order, in her rooms, with an explicit gap whenever history she has not read +//! is gone or was never vouched for. Routing reads the typed arrival header only; the payload is the +//! consumer's to open. +//! +//! Fairness across rooms needs no scheduler: her cursor only moves forward through commit order, so a +//! row in a quiet room is reached after at most one page of a busy room's traffic, never starved. +//! +//! Durable acceptance (committing her pending perception, the cursor prefix and the gap receipts +//! together) is the shared consumption owner's (Codex, #5691 773d34a4); this module decides WHAT the +//! next page is, never whether it was accepted. + +use airc_core::{PeerId, RoomId}; +use serde_json::{json, Value}; + +use super::arrival::Arrival; +use super::chat_data_handle::{ChatModule, CHAT_DATA_HANDLE}; +use super::chat_module::extract_records_as_data; + +/// Why history between two sequences cannot be perceived. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GapReason { + /// Pruned by the store's retention before she read it. + Retention, + /// Imported before the store vouched for completeness (a migrated watermark): lines may be + /// missing, so she is told, once, before her first rows. + UnvouchedImport, +} + +/// Where a mind stands in the arrival order: everything through `through` has been accepted (or +/// receipted as a gap); `unvouched_receipted` once she has been told about an unvouched import. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DrainCursor { + pub through: u64, + pub unvouched_receipted: bool, +} + +/// The next thing a mind perceives from the store. +#[derive(Debug, Clone, PartialEq)] +pub enum Drained { + /// Rows to perceive, in commit order, and the sequence the page scanned through (her own rows + /// are skipped but still advance it, so they are never re-scanned). + Rows { + rows: Vec, + scanned_through: u64, + }, + /// History she cannot perceive, said once; accepting it moves her cursor to `through`. + Gap { + from: u64, + through: u64, + reason: GapReason, + }, + /// Nothing after her cursor in her rooms. + Empty, +} + +/// What the store says around a mind's cursor: the oldest retained sequence (`None` for an empty +/// collection) and whether her rooms' imports are unvouched before the store owned the watermark. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct StoreFacts { + pub retained_floor: Option, + pub unvouched_import: bool, +} + +/// Decide the next drain outcome from her cursor, the store's facts and the page of arrivals after +/// her cursor (in commit order, already restricted to her rooms). Pure: the store query and the +/// acceptance are around it. +pub fn next(cursor: DrainCursor, me: PeerId, facts: StoreFacts, page: Vec) -> Drained { + if facts.unvouched_import && !cursor.unvouched_receipted { + return Drained::Gap { + from: 0, + through: cursor.through, + reason: GapReason::UnvouchedImport, + }; + } + if let Some(floor) = facts.retained_floor { + if cursor.through + 1 < floor { + return Drained::Gap { + from: cursor.through + 1, + through: floor - 1, + reason: GapReason::Retention, + }; + } + } + let Some(scanned_through) = page.iter().map(|a| a.arrival_seq).max() else { + return Drained::Empty; + }; + let rows = page.into_iter().filter(|a| a.author != me).collect(); + Drained::Rows { + rows, + scanned_through, + } +} + +impl ChatModule { + /// The page after `cursor` in `rooms`, at most `intake` rows (her intake, the consumer's to size), + /// and the store facts the drain decision needs, from the store's own indexes. + pub async fn drain_page( + &self, + cursor: DrainCursor, + rooms: &[RoomId], + intake: usize, + ) -> Result<(StoreFacts, Vec), String> { + let executor = self.executor()?; + let collection = ::COLLECTION; + let rooms_typed = rooms; + let rooms: Vec = rooms.iter().map(|r| r.as_uuid().to_string()).collect(); + let page = json!({ + "dbPath": CHAT_DATA_HANDLE, + "collection": collection, + "filter": { "arrivalSeq": { "$gt": cursor.through }, "room": { "$in": rooms } }, + "sort": [{ "field": "arrivalSeq", "direction": "asc" }], + "limit": intake, + }); + let floor = json!({ + "dbPath": CHAT_DATA_HANDLE, + "collection": collection, + "filter": {}, + "sort": [{ "field": "arrivalSeq", "direction": "asc" }], + "limit": 1, + }); + let rows = executor + .execute_json("data/query", page) + .await + .map_err(|e| format!("drain: page query failed: {e}"))?; + let oldest = executor + .execute_json("data/query", floor) + .await + .map_err(|e| format!("drain: floor query failed: {e}"))?; + let arrivals = decode(extract_records_as_data(&rows))?; + let retained_floor = decode(extract_records_as_data(&oldest))? + .first() + .map(|a| a.arrival_seq); + let mut unvouched_import = false; + for room in rooms_typed { + if let Some(imported) = self.import_watermark(*room).await? { + unvouched_import |= matches!( + imported.history, + super::import_watermark::ImportHistory::UnvouchedThrough { .. } + ); + } + } + Ok(( + StoreFacts { + retained_floor, + unvouched_import, + }, + arrivals, + )) + } +} + +fn decode(rows: Vec) -> Result, String> { + rows.into_iter() + .map(|row| { + serde_json::from_value(row).map_err(|e| format!("drain: malformed arrival row: {e}")) + }) // storage boundary: the adapter's row format + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::chat::arrival::ArrivalKind; + use uuid::Uuid; + + fn arrival(seq: u64, room: RoomId, author: PeerId) -> Arrival { + let mut a = Arrival::new(Uuid::new_v4(), room, author, ArrivalKind::Message, None); + a.arrival_seq = seq; + a + } + + const FRESH: DrainCursor = DrainCursor { + through: 0, + unvouched_receipted: true, + }; + const WHOLE: StoreFacts = StoreFacts { + retained_floor: Some(1), + unvouched_import: false, + }; + + // what this catches: her own lines delivered back to her, or skipped without advancing the + // cursor (so the same page is scanned forever): skipped, and the scan covers them. + #[test] + fn her_own_rows_are_skipped_but_advance_the_scan() { + let (me, peer, room) = (PeerId::new(), PeerId::new(), RoomId::new()); + let page = vec![ + arrival(1, room, peer), + arrival(2, room, me), + arrival(3, room, peer), + ]; + let Drained::Rows { + rows, + scanned_through, + } = next(FRESH, me, WHOLE, page) + else { + panic!("rows expected"); + }; + assert_eq!( + rows.iter().map(|a| a.arrival_seq).collect::>(), + vec![1, 3] + ); + assert_eq!( + scanned_through, 3, + "her own row 2 is scanned through, never re-read" + ); + assert_eq!( + next( + DrainCursor { + through: 3, + ..FRESH + }, + me, + WHOLE, + vec![] + ), + Drained::Empty + ); + } + + // what this catches: pruned history read as silence (her cursor below the retained floor + // silently jumping), and an unvouched import never told: both are explicit gaps, unvouched first. + #[test] + fn lost_or_unvouched_history_is_an_explicit_gap() { + let (me, peer, room) = (PeerId::new(), PeerId::new(), RoomId::new()); + let pruned = StoreFacts { + retained_floor: Some(10), + unvouched_import: false, + }; + assert_eq!( + next( + DrainCursor { + through: 4, + ..FRESH + }, + me, + pruned, + vec![arrival(10, room, peer)] + ), + Drained::Gap { + from: 5, + through: 9, + reason: GapReason::Retention + } + ); + let unvouched = StoreFacts { + retained_floor: Some(1), + unvouched_import: true, + }; + let untold = DrainCursor { + through: 0, + unvouched_receipted: false, + }; + assert_eq!( + next(untold, me, unvouched, vec![arrival(1, room, peer)]), + Drained::Gap { + from: 0, + through: 0, + reason: GapReason::UnvouchedImport + } + ); + let told = DrainCursor { + unvouched_receipted: true, + ..untold + }; + assert!( + matches!( + next(told, me, unvouched, vec![arrival(1, room, peer)]), + Drained::Rows { .. } + ), + "told once, then her rows" + ); + } +} diff --git a/core/continuum-mind/src/chat/mod.rs b/core/continuum-mind/src/chat/mod.rs index 8b24c6439f..deca09407e 100644 --- a/core/continuum-mind/src/chat/mod.rs +++ b/core/continuum-mind/src/chat/mod.rs @@ -61,6 +61,7 @@ use types::{ChatPollParams, ChatPollResult, ChatSendParams, ChatSendResult, CHAT pub mod arrival; pub mod line_store; +pub mod drain; pub mod import_watermark; pub mod orm_entities; mod chat_data_handle; From b4777e2daf53ed98c97173c8562a217ab0cc7e04 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 18:19:52 -0600 Subject: [PATCH 2/7] A room line's sender is read from its header, never its body; the touched room-event renderers lose their self-chosen sizes - routing::airc_realtime_wire::logical_sender(event): the `continuum.source_id` header the publisher stamps (a relay publishes a human's line for them), else the transport peer. One typed decoder beside the encoder (headers_for_envelope), with its test. - chat_transcript_content / chat_transcript_message take the resolved sender; the body's `senderId` is no longer read for attribution (perception and the inbound seam both pass the header's sender). Test: a body senderId cannot override the header sender. - render_room_content: the media notice is one entry per typed MediaKind (from the MIME top-level type) with its count, bounded by the few kinds, with no item cap and no character cut; the event keeps every reference for opening. render_room_work's short ids use airc's shown_form, not a [..8] slice. - drain: the boundary comment sits on the deserializing line. Trust note (raised with Codex): whether a transport peer may name another sender is a grid-trust rule, as it was for the body field this replaces; this change moves the read, not the trust. Tests (M5, serving down 00:14-00:19Z): kernel airc_realtime_wire 1, cognition conversation 54, core inbound_attach 15, mind chat 48 pass; ratchets exit 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/conversation/room_event.rs | 108 ++++++++---------- .../continuum-core/src/airc/inbound_attach.rs | 2 +- .../src/routing/airc_realtime_wire.rs | 52 +++++++++ core/continuum-mind/src/chat/drain.rs | 7 +- 4 files changed, 101 insertions(+), 68 deletions(-) diff --git a/core/continuum-cognition/src/cognition/conversation/room_event.rs b/core/continuum-cognition/src/cognition/conversation/room_event.rs index fb0675a8ad..05fa2d66a0 100644 --- a/core/continuum-cognition/src/cognition/conversation/room_event.rs +++ b/core/continuum-cognition/src/cognition/conversation/room_event.rs @@ -81,17 +81,41 @@ pub fn room_turn_from_event(event: &TranscriptEvent) -> Result<(uuid::Uuid, Stri Ok((turn.sender, render_room_content(&turn.text, &turn.media))) } +/// What kind of media an attachment is, from its declared kind (the MIME top-level type). +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum MediaKind { + Image, + Audio, + Video, + Text, + File, +} + +impl MediaKind { + fn of(kind: &str) -> Self { + match kind { + "image" => Self::Image, + "audio" => Self::Audio, + "video" => Self::Video, + "text" => Self::Text, + _ => Self::File, // any other declared kind is a file she can open, never free text in her prompt + } + } +} + /// A bounded notice, not a claim that the model has inspected the attachment. /// The event retains the full references for explicit inspection/replay. pub(crate) fn render_room_content(text: &str, media: &[crate::cognition::conversation::channel_items::MediaItemRequest]) -> String { if media.is_empty() { return text.to_owned(); } let mut rendered = format!("{text}\n[{} media attachment(s); contents not loaded", media.len()); - for item in media.iter().take(8) { - let kind: String = item.kind.chars().filter(|c| !c.is_control()).take(24).collect(); - rendered.push_str(&format!("; {kind}")); - if let Some(hash) = item.blob_hash.as_deref().filter(|h| h.starts_with("sha256:") && h.len() == 71 && h[7..].bytes().all(|b| b.is_ascii_hexdigit())) { - rendered.push_str(&format!(" {hash}")); - } + // One entry per kind with its count: bounded by the few media kinds that exist, never by a cap + // on items or characters (a typed kind from the MIME top-level type, so no free text reaches her). + let mut kinds = std::collections::BTreeMap::::new(); + for item in media { + *kinds.entry(MediaKind::of(&item.kind)).or_default() += 1; + } + for (kind, count) in kinds { + rendered.push_str(&format!("; {count} {kind:?}")); } rendered.push(']'); rendered @@ -101,7 +125,7 @@ pub(crate) fn render_room_content(text: &str, media: &[crate::cognition::convers /// words. Short ids because that is how the board renders them; the typed event /// retains the full ids for her hands. pub fn render_room_work(work: &RoomWork, actor: uuid::Uuid) -> String { - let short = |id: uuid::Uuid| id.to_string()[..8].to_string(); + let short = airc_core::shown_id::shown_form; match work { RoomWork::Reviewed { card_id, outcome, reviewer, .. } => format!( "[board fact] review on card {}: {:?} (reviewer {})", @@ -171,7 +195,7 @@ pub fn room_content_from_event(event: &TranscriptEvent) -> Result return Err("envelope_decode_error"), Ok(None) => return Err("no_continuum_body_hint"), - Ok(Some(envelope)) => chat_transcript_content(&envelope, event.peer_id.as_uuid()).ok_or("non_chat_schema")?, + Ok(Some(envelope)) => chat_transcript_content(&envelope, crate::routing::airc_realtime_wire::logical_sender(event)).ok_or("non_chat_schema")?, } }; // Native AIRC attachments are first-class room input too. Preserve the @@ -200,11 +224,9 @@ pub fn room_content_from_event(event: &TranscriptEvent) -> Result Result Option<(uuid::Uuid, String)> { - let turn = chat_transcript_content(envelope, fallback_peer)?; + let turn = chat_transcript_content(envelope, sender)?; Some((turn.sender, render_room_content(&turn.text, &turn.media))) } -fn chat_transcript_content(envelope: &AircRealtimeEnvelope, fallback_peer: uuid::Uuid) -> Option { +fn chat_transcript_content(envelope: &AircRealtimeEnvelope, sender: uuid::Uuid) -> Option { let AircRealtimePayload::ExistingSchema { payload } = &envelope.payload else { return None; }; @@ -231,11 +253,6 @@ fn chat_transcript_content(envelope: &AircRealtimeEnvelope, fallback_peer: uuid: } let inline = payload.inline.as_ref()?; let text = inline.get("text").and_then(serde_json::Value::as_str)?; - let sender = inline - .get("senderId") - .and_then(serde_json::Value::as_str) - .and_then(|s| uuid::Uuid::parse_str(s).ok()) - .unwrap_or(fallback_peer); let media = inline.get("media").map(|value| serde_json::from_value(value.clone())).transpose().ok()?.unwrap_or_default(); // boundary: AIRC transcript JSON decodes typed references; omitted media is the legacy text-only wire contract. Some(RoomTurn { sender, text: text.to_string(), media }) } @@ -287,12 +304,12 @@ mod tests { // This is the seam that keeps human chat lines from being structurally // invisible to BOTH persona perception and the positron read surface. // A regression that renamed the `chat_transcript` schema tag or the - // inline `text`/`senderId` fields silently drops every human message - // from the room. + // inline `text` field silently drops every human message from the room; + // and the body's `senderId` must never override the header-resolved sender + // (routing on headers, never parsed bodies: Joel, 2026-11-01). #[test] - fn chat_transcript_message_recovers_sender_and_text() { + fn chat_transcript_text_decodes_and_the_header_sender_wins() { let sender = uuid::Uuid::from_u128(0x5e).to_string(); - let relay = uuid::Uuid::from_u128(0x4e); // Encode exactly as chat/send → airc/realtime-publish builds it. let envelope: AircRealtimeEnvelope = serde_json::from_value(serde_json::json!({ "eventId": uuid::Uuid::from_u128(0x1).to_string(), @@ -315,13 +332,11 @@ mod tests { })) .expect("chat/send envelope shape must decode into AircRealtimeEnvelope"); + let header_sender = uuid::Uuid::from_u128(0x77); let (recovered, text) = - chat_transcript_message(&envelope, relay).expect("chat_transcript must decode"); - assert_eq!( - recovered.to_string(), - sender, - "logical sender, not the relay" - ); + chat_transcript_message(&envelope, header_sender).expect("chat_transcript must decode"); + assert_eq!(recovered, header_sender, "the header's sender; the body's senderId routes nothing"); + assert_ne!(recovered.to_string(), sender); assert_eq!(text, "is anyone there?"); } @@ -342,37 +357,6 @@ mod tests { assert!(rendered.len() < 1000); } - // what this catches: attribution recovery, not fabrication. When the - // inline omits senderId, the sender falls back to the transport peer - // that relayed the publish — a real identity, never a nil/default. - #[test] - fn chat_transcript_message_falls_back_to_transport_peer() { - let relay = uuid::Uuid::from_u128(0x4e); - let envelope: AircRealtimeEnvelope = serde_json::from_value(serde_json::json!({ - "eventId": uuid::Uuid::from_u128(0x1).to_string(), - "roomId": uuid::Uuid::from_u128(0x2).to_string(), - "sourceId": uuid::Uuid::from_u128(0x5e).to_string(), - "createdAtMs": 100, - "delivery": "durable", - "payload": { - "kind": "existing_schema", - "payload": { - "schema": "chat_transcript", - "inline": { "text": "hello" } - } - }, - })) - .expect("envelope must decode"); - - let (recovered, text) = - chat_transcript_message(&envelope, relay).expect("chat_transcript must decode"); - assert_eq!( - recovered, relay, - "omitted senderId recovers to the relay peer" - ); - assert_eq!(text, "hello"); - } - // what this catches: classification, not fallback. A non-chat_transcript // envelope (here EventBridge) must yield None from this decoder — it is // NOT a chat line and must never be projected as one. diff --git a/core/continuum-core/src/airc/inbound_attach.rs b/core/continuum-core/src/airc/inbound_attach.rs index 42d437b413..037aeab751 100644 --- a/core/continuum-core/src/airc/inbound_attach.rs +++ b/core/continuum-core/src/airc/inbound_attach.rs @@ -505,7 +505,7 @@ fn posted_from_envelope( envelope: &AircRealtimeEnvelope, event: &airc_core::TranscriptEvent, ) -> Option { - let (sender_id, content) = chat_transcript_message(envelope, event.peer_id.as_uuid())?; + let (sender_id, content) = chat_transcript_message(envelope, crate::routing::airc_realtime_wire::logical_sender(event))?; let message_id = match &envelope.payload { crate::routing::airc_realtime::AircRealtimePayload::ExistingSchema { payload } => payload .inline diff --git a/core/continuum-kernel/src/routing/airc_realtime_wire.rs b/core/continuum-kernel/src/routing/airc_realtime_wire.rs index 6ab6de5e03..9e6a66e26a 100644 --- a/core/continuum-kernel/src/routing/airc_realtime_wire.rs +++ b/core/continuum-kernel/src/routing/airc_realtime_wire.rs @@ -18,6 +18,21 @@ pub const HEADER_CONTINUUM_SOURCE_ID: &str = "continuum.source_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.source_id` header the publisher stamped (a relay +/// publishes a human's line for them); the transport peer when the header is absent or is not an id +/// (a presence subject, a free-form source). Read from the header alone: the body is never opened to +/// attribute a line (Joel, 2026-11-01: routing on headers, never parsed bodies). +/// +/// Trust is the relay rule's, not this decoder's: whether a transport peer may speak for the sender it +/// names is a grid-trust decision (raised with Codex), exactly as it was for the body field it replaces. +pub fn logical_sender(event: &TranscriptEvent) -> uuid::Uuid { + event + .headers + .get(HEADER_CONTINUUM_SOURCE_ID) + .and_then(|value| uuid::Uuid::parse_str(value).ok()) // wire boundary: a header value is text; a non-id source is a non-person publisher + .unwrap_or_else(|| event.peer_id.as_uuid()) // the transport peer is the real author when no relay named one +} + pub fn frame_kind_for_delivery(delivery: AircRealtimeDelivery) -> FrameKind { match delivery { AircRealtimeDelivery::Durable => FrameKind::Message, @@ -129,3 +144,40 @@ pub fn is_stream_chunk(event: &TranscriptEvent) -> bool { pub fn is_command_frame(event: &TranscriptEvent) -> bool { event.headers.get(airc_protocol::HEADER_AIRC_CORRELATION_ID).is_some() } + +#[cfg(test)] +mod tests { + use super::*; + use airc_core::{ClientId, EventId, MentionTarget, PeerId, RoomId, TranscriptKind}; + + fn event(headers: Headers) -> TranscriptEvent { + TranscriptEvent { + event_id: EventId::from_u128(1), + room_id: RoomId::from_u128(2), + peer_id: PeerId::from_u128(0x4e), + client_id: ClientId::from_u128(4), + kind: TranscriptKind::Message, + occurred_at_ms: 100, + lamport: 1, + target: MentionTarget::All, + headers, + body: None, + attachment: None, + receipt: None, + metadata: serde_json::Value::Null, + } + } + + // what this catches: a relayed human line attributed to the relay peer (she answers the wrong + // person), or a non-id source fabricating a sender: the header names the logical sender; absent + // or not an id, the transport peer is the author. + #[test] + fn the_logical_sender_is_read_from_the_header() { + let human = uuid::Uuid::from_u128(0x5e); + let relayed = event(Headers::from([(HEADER_CONTINUUM_SOURCE_ID.to_string(), human.to_string())])); + assert_eq!(logical_sender(&relayed), human); + assert_eq!(logical_sender(&event(Headers::new())), uuid::Uuid::from_u128(0x4e)); + let named = event(Headers::from([(HEADER_CONTINUUM_SOURCE_ID.to_string(), "persona-1".to_string())])); + assert_eq!(logical_sender(&named), uuid::Uuid::from_u128(0x4e), "a non-id source is not a person"); + } +} diff --git a/core/continuum-mind/src/chat/drain.rs b/core/continuum-mind/src/chat/drain.rs index e21f457885..0d81c903bf 100644 --- a/core/continuum-mind/src/chat/drain.rs +++ b/core/continuum-mind/src/chat/drain.rs @@ -151,11 +151,8 @@ impl ChatModule { } fn decode(rows: Vec) -> Result, String> { - rows.into_iter() - .map(|row| { - serde_json::from_value(row).map_err(|e| format!("drain: malformed arrival row: {e}")) - }) // storage boundary: the adapter's row format - .collect() + let decode_row = |row: Value| serde_json::from_value::(row); // storage boundary: the adapter's row format + rows.into_iter().map(|row| decode_row(row).map_err(|e| format!("drain: malformed arrival row: {e}"))).collect() } #[cfg(test)] From f13c54b245bd92d173dd21e7bd456029e43f1e23 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 18:46:36 -0600 Subject: [PATCH 3/7] Attribution is proven, not claimed: chat/send binds the sender to its authenticated caller, and a relayed line is delegated only on its exact publication obligation (Codex on #5696) - chat/send: an authenticated caller (a persona or grid peer) speaks as itself; naming another sender is Denied. Only the substrate's own local code (caller None, the owner) may name the sender, as the live-call transcript does. Before, an explicit senderId won over the caller. - chat::publication: before the envelope leg publishes, chat/send records a PublicationObligation (message id, room, sender, digest). publication_digest hashes the typed fields directly (id, room, sender, text, each media handle; length-prefixed), with no serialization. The envelope is named by the message id (continuum.event_id header). - The inbound seam attributes BEFORE perception, the store or the projection see a line. With no claim, or a claim naming the transport author, it is the author's own. A claim for someone else is Delegated only when the obligation that message id names matches room, sender and the digest of the line as received (decoded once by the one chat_transcript decoder). Otherwise it is Refused{NoOrigin | RoomMismatch | SenderMismatch | AlteredPublication}, probed and dropped, never relabeled. A delegated import retires its obligation in the same batch. Foreign relays are refused until a scoped relay grant exists. - kernel wire: claimed_sender and claimed_message read the typed headers. Tests (M5, serving down 00:38-00:46Z): mind chat 50 (new: caller impersonation refused; only an exact publication delegates: no claim, self, forged Joel, room mismatch, other sender, altered content); core inbound_attach 16 (new: forged Joel, another room's publication, and a reused id with altered text are never stored; the exact publication imports under Joel and retires its obligation; the human chat_transcript projection rides its obligation); cognition conversation 54; ratchets exit 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/conversation/room_event.rs | 6 +- .../continuum-core/src/airc/inbound_attach.rs | 58 +++- .../src/airc/inbound_attach/tests.rs | 99 +++++-- .../src/routing/airc_realtime_wire.rs | 15 + .../src/chat/chat_data_handle.rs | 5 + core/continuum-mind/src/chat/commands/send.rs | 37 ++- core/continuum-mind/src/chat/line_store.rs | 32 ++- core/continuum-mind/src/chat/mod.rs | 1 + core/continuum-mind/src/chat/orm_entities.rs | 2 + core/continuum-mind/src/chat/publication.rs | 263 ++++++++++++++++++ core/continuum-mind/src/chat/tests/mod.rs | 15 +- 11 files changed, 496 insertions(+), 37 deletions(-) create mode 100644 core/continuum-mind/src/chat/publication.rs diff --git a/core/continuum-cognition/src/cognition/conversation/room_event.rs b/core/continuum-cognition/src/cognition/conversation/room_event.rs index 05fa2d66a0..97f7f285fb 100644 --- a/core/continuum-cognition/src/cognition/conversation/room_event.rs +++ b/core/continuum-cognition/src/cognition/conversation/room_event.rs @@ -244,7 +244,7 @@ pub fn chat_transcript_message( Some((turn.sender, render_room_content(&turn.text, &turn.media))) } -fn chat_transcript_content(envelope: &AircRealtimeEnvelope, sender: uuid::Uuid) -> Option { +pub fn chat_transcript_content(envelope: &AircRealtimeEnvelope, sender: uuid::Uuid) -> Option { let AircRealtimePayload::ExistingSchema { payload } = &envelope.payload else { return None; }; @@ -271,7 +271,9 @@ pub struct ChatTranscriptLine<'a> { /// caller-owned publication and a hydrated durable row all send. pub fn chat_transcript_envelope(message_id: uuid::Uuid, line: &ChatTranscriptLine<'_>, now_ms: u64) -> serde_json::Value { serde_json::json!({ - "eventId": uuid::Uuid::new_v4().to_string(), + // The envelope is named by the stored message id, so its `continuum.event_id` header names + // the row and its publication obligation (attribution reads the header, never the body). + "eventId": message_id.to_string(), "roomId": line.room_id.to_string(), "sourceId": line.sender_id.to_string(), "createdAtMs": now_ms, diff --git a/core/continuum-core/src/airc/inbound_attach.rs b/core/continuum-core/src/airc/inbound_attach.rs index 037aeab751..1e9477b0da 100644 --- a/core/continuum-core/src/airc/inbound_attach.rs +++ b/core/continuum-core/src/airc/inbound_attach.rs @@ -362,6 +362,14 @@ pub async fn publish_transcript_event( // core, instead of from a per-persona subscription (which on the 5090 never // carried other peers' durable pushes while this path did). Synchronous and // cheap: one classification, one lock per resident, no await. + // ATTRIBUTION BEFORE ANYTHING CONSUMES THE LINE (Codex on #5696): a line claiming to speak for + // someone other than its transport author reaches perception, the store and the projection only + // when this core's publication obligation proves it; otherwise it is refused here, said, and + // dropped, never relabeled. + let delegated = match attribution_gate(event, lines).await? { + Gate::Pass { delegated } => delegated, + Gate::Refused => return Ok(()), + }; let fed = crate::persona::perception_feed::feed(&conversation, EpochMs::now().millis()); if fed > 0 { continuum_base::probe!( @@ -459,7 +467,8 @@ pub async fn publish_transcript_event( "first capacity offer heard from a grid peer", ); } - } else if let Some(line) = posted_from_envelope(&envelope, event) { + } else if let Some(mut line) = posted_from_envelope(&envelope, event) { + line.retires_publication = delegated; // The same awaited, idempotent import as the plain arm (a human line was stored by // chat/send under this id already; the import reuses its row and arrival). lines @@ -522,6 +531,52 @@ fn posted_from_envelope( Some(line) } +/// Whether a line may be consumed, decided by attribution. +enum Gate { + Pass { delegated: bool }, + Refused, +} + +/// Attribute a line before it is consumed: no claim (or a claim naming its transport author) passes +/// as the author's own; a claim to speak for someone else passes only on an exact publication +/// obligation (`chat::publication::attribute`), read through the injected store. +async fn attribution_gate(event: &airc_core::TranscriptEvent, lines: &dyn LineImporter) -> Result { + use crate::routing::airc_realtime_wire::{claimed_message, claimed_sender, envelope_from_event}; + use continuum_mind::chat::publication::{attribute, publication_digest, Attribution}; + let claimed = claimed_sender(event); + if claimed.is_none() || claimed == Some(event.peer_id) { + return Ok(Gate::Pass { delegated: false }); + } + let obligation = match claimed_message(event) { + Some(id) => lines.publication(id).await?, + None => None, + }; + // The line as received, from the one chat_transcript decoder (its claimed sender, its text and + // media); a line that does not decode matches no publication. + let received = match (claimed_message(event), claimed, envelope_from_event(event)) { + (Some(message), Some(sender), Ok(Some(envelope))) => { + crate::cognition::conversation::room_event::chat_transcript_content(&envelope, sender.as_uuid()) + .map(|turn| publication_digest(message, event.room_id, sender, &turn.text, &turn.media)) + } + _ => None, + }; + match attribute(event.peer_id, claimed, event.room_id, obligation.as_ref(), received) { + Attribution::Author(_) => Ok(Gate::Pass { delegated: false }), + Attribution::Delegated { .. } => Ok(Gate::Pass { delegated: true }), + Attribution::Refused { claimed, reason } => { + continuum_base::probe!( + class = "airc.inbound.delegation_refused", + room = %event.room_id.as_uuid(), + transport = %event.peer_id.as_uuid(), + claimed = %claimed.as_uuid(), + reason = ?reason, + "a line claimed to speak for someone it could not prove; refused, not relabeled" + ); + Ok(Gate::Refused) + } + } +} + /// The typed line of a room event, from its header (kind, ids, addressee) and its decoded text; /// `None` when the event is not a room line. fn posted_line(event: &airc_core::TranscriptEvent, text: String) -> Option { @@ -534,6 +589,7 @@ fn posted_line(event: &airc_core::TranscriptEvent, text: String) -> Option AircRealtimeEnvelope { - AircRealtimeEnvelope::new( - "evt-1".to_string(), - Uuid::from_u128(2), - sender.to_string(), - 100, - AircRealtimePayload::ExistingSchema { - payload: AircRealtimePayloadRef::inline( - AircRealtimeSchema::ChatTranscript, - json!({ - "messageId": Uuid::from_u128(0x3).to_string(), - "text": text, - "senderId": sender.to_string(), - "replyToId": serde_json::Value::Null, - }), - ), - }, - ) -} - #[tokio::test] async fn chat_transcript_envelope_projects_chat_posted() { // what this catches: the Case-A completeness fix (task #84). A human @@ -161,13 +141,14 @@ async fn chat_transcript_envelope_projects_chat_posted() { let bus = MessageBus::new(); let mut receiver = bus.receiver(); let sender = Uuid::from_u128(0x5e); - let envelope = chat_transcript_envelope(sender, "is anyone there?"); - let event = transcript_event( - Some(Body::Json(serde_json::to_value(&envelope).unwrap())), - headers_for_envelope(&envelope), - ); + // As chat/send publishes it now: named by its message id, with its publication obligation recorded + // (a relayed line without one is refused, #5696). + let message = Uuid::from_u128(0x3); + let (event, _envelope) = relayed_line(PeerId::from_u128(3), sender, RoomId::from_u128(2), "is anyone there?", message); + let lines = continuum_mind::chat::line_store::RecordingImporter::default(); + lines.2.lock().expect("test: lock").insert(message, obligation_for("is anyone there?", message, RoomId::from_u128(2), sender)); // test: a fixture step that must succeed - publish_transcript_event(&Arc::new(event), &bus, &continuum_mind::chat::line_store::RecordingImporter::default()).await.unwrap(); + publish_transcript_event(&Arc::new(event), &bus, &lines).await.unwrap(); let delivered = timeout(Duration::from_millis(200), receiver.recv()) .await @@ -500,3 +481,69 @@ async fn a_migrated_cursor_never_vouches_for_the_lines_before_it() { persist_cursor(&lines, &room, &IpcCursor { epoch: 7, counter: 950, event_id: EventId::from_u128(0x950) }).await; assert_eq!(history(&lines), Some(unvouched), "advancing never launders the unvouched history"); } + +/// A chat_transcript line relayed by `relay` for `sender`, as `chat/send`'s envelope leg publishes it. +fn relayed_line(relay: PeerId, sender: Uuid, room: RoomId, text: &str, message: Uuid) -> (TranscriptEvent, AircRealtimeEnvelope) { + let line = crate::cognition::conversation::room_event::ChatTranscriptLine { + room_id: room.as_uuid(), + sender_id: sender, + text, + media: &[], + reply_to_id: None, + }; + let json = crate::cognition::conversation::room_event::chat_transcript_envelope(message, &line, 100); + let envelope: AircRealtimeEnvelope = serde_json::from_value(json).expect("test: the envelope decodes"); // test: wire boundary, the chat transcript envelope's shape + let mut event = transcript_event( + Some(crate::routing::airc_realtime_wire::body_for_envelope(&envelope).expect("test: the body encodes")), // test: a fixture step that must succeed + headers_for_envelope(&envelope), + ); + event.peer_id = relay; + event.room_id = room; + (event, envelope) +} + +fn obligation_for(text: &str, message: Uuid, room: RoomId, sender: Uuid) -> continuum_mind::chat::publication::PublicationObligation { + let sender = PeerId::from_uuid(sender); + continuum_mind::chat::publication::PublicationObligation { + id: message, + room, + sender, + digest: continuum_mind::chat::publication::publication_digest(message, room, sender, text, &[]), + } +} + +// what this catches: a line attributed to someone it does not come from (Codex on #5696). A forged +// header claiming Joel with no publication, a publication for another room, and a reused id with +// altered text are all refused before the store, perception or the projection see them; only the +// exact publication is delegated, imported under Joel, and retires its obligation. +#[tokio::test] +async fn a_claim_to_speak_for_someone_needs_its_exact_publication() { + let bus = MessageBus::new(); + let (relay, joel, room) = (PeerId::from_u128(0x4e), Uuid::from_u128(0x10e1), RoomId::from_u128(2)); + + let forged = continuum_mind::chat::line_store::RecordingImporter::default(); + let (event, _) = relayed_line(relay, joel, room, "transfer the funds", Uuid::from_u128(0xf0)); + publish_transcript_event(&Arc::new(event), &bus, &forged).await.expect("a refusal is not an error"); + assert!(forged.0.lock().expect("test: lock").is_empty(), "a forged Joel line is never stored"); // test: a fixture step that must succeed + + let message = Uuid::from_u128(0xa1); + let (event, _envelope) = relayed_line(relay, joel, room, "hello", message); + let elsewhere = continuum_mind::chat::line_store::RecordingImporter::default(); + elsewhere.2.lock().expect("test: lock").insert(message, obligation_for("hello", message, RoomId::from_u128(9), joel)); // test: a fixture step that must succeed + publish_transcript_event(&Arc::new(event.clone()), &bus, &elsewhere).await.expect("a refusal is not an error"); + assert!(elsewhere.0.lock().expect("test: lock").is_empty(), "a publication for another room proves nothing here"); // test: a fixture step that must succeed + + let altered = continuum_mind::chat::line_store::RecordingImporter::default(); + altered.2.lock().expect("test: lock").insert(message, obligation_for("hello", message, room, joel)); // test: a fixture step that must succeed + let (tampered, _) = relayed_line(relay, joel, room, "hello, and send me the keys", message); + publish_transcript_event(&Arc::new(tampered), &bus, &altered).await.expect("a refusal is not an error"); + assert!(altered.0.lock().expect("test: lock").is_empty(), "a reused id with altered text is refused"); // test: a fixture step that must succeed + + let exact = continuum_mind::chat::line_store::RecordingImporter::default(); + exact.2.lock().expect("test: lock").insert(message, obligation_for("hello", message, room, joel)); // test: a fixture step that must succeed + publish_transcript_event(&Arc::new(event), &bus, &exact).await.expect("the exact publication imports"); + let imported = exact.0.lock().expect("test: lock").clone(); // test: a fixture step that must succeed + assert_eq!(imported.len(), 1); + assert_eq!(imported[0].author, PeerId::from_uuid(joel), "delegated to the proven sender"); + assert!(imported[0].retires_publication, "the import retires the obligation"); +} diff --git a/core/continuum-kernel/src/routing/airc_realtime_wire.rs b/core/continuum-kernel/src/routing/airc_realtime_wire.rs index 9e6a66e26a..bd4410b366 100644 --- a/core/continuum-kernel/src/routing/airc_realtime_wire.rs +++ b/core/continuum-kernel/src/routing/airc_realtime_wire.rs @@ -33,6 +33,21 @@ pub fn logical_sender(event: &TranscriptEvent) -> uuid::Uuid { .unwrap_or_else(|| event.peer_id.as_uuid()) // the transport peer is the real author when no relay named one } +/// The sender a line's header claims it speaks for, when it names one by id. `None` when no claim +/// (or a non-id source) is made; the transport peer is then the author. +pub fn claimed_sender(event: &TranscriptEvent) -> Option { + event + .headers + .get(HEADER_CONTINUUM_SOURCE_ID) + .and_then(|value| uuid::Uuid::parse_str(value).ok()) // wire boundary: a header value is text + .map(airc_core::PeerId::from_uuid) +} + +/// The message id a continuum envelope is named by (`continuum.event_id`), when it is an id. +pub fn claimed_message(event: &TranscriptEvent) -> Option { + event.headers.get(HEADER_CONTINUUM_EVENT_ID).and_then(|value| uuid::Uuid::parse_str(value).ok()) // wire boundary: a header value is text +} + pub fn frame_kind_for_delivery(delivery: AircRealtimeDelivery) -> FrameKind { match delivery { AircRealtimeDelivery::Durable => FrameKind::Message, diff --git a/core/continuum-mind/src/chat/chat_data_handle.rs b/core/continuum-mind/src/chat/chat_data_handle.rs index 520f08f86b..a758d5e372 100644 --- a/core/continuum-mind/src/chat/chat_data_handle.rs +++ b/core/continuum-mind/src/chat/chat_data_handle.rs @@ -234,6 +234,7 @@ impl ChatModule { direct_to: None, occurred_at_ms: now_ms, text: params.text.clone(), + retires_publication: false, }; let content = json!({ "text": params.text, "media": params.media }); self.commit_line( @@ -276,6 +277,10 @@ impl ChatModule { now_ms, ); + // Record the publication obligation BEFORE publishing (Codex on #5696): the exact envelope's + // digest, the room and the sender, under the message id. The inbound seam delegates the line + // to this sender only on an exact match, so the envelope published is the typed one digested. + self.record_publication(message_id, params).await?; let publish_params = json!({ "envelope": publish_envelope }); // Partial failure path: data succeeded, airc failed. Return diff --git a/core/continuum-mind/src/chat/commands/send.rs b/core/continuum-mind/src/chat/commands/send.rs index 418447eb73..6849123d33 100644 --- a/core/continuum-mind/src/chat/commands/send.rs +++ b/core/continuum-mind/src/chat/commands/send.rs @@ -65,9 +65,23 @@ crate::action_command! { // the AGENT self-peer — never as the human operator. Attribution is // identity's whole point (Joel, 2026-09-01). let agent_session = ctx.claimed_actor_kind.as_deref() == Some("agent"); - let sender_id = p - .sender_id - .or_else(|| ctx.caller.as_ref().map(|c| c.peer_id.as_uuid())) + // The sender is bound to the authenticated caller: a persona or a grid peer speaks as + // itself, and naming anyone else is refused (it was the first link of the chain, so any + // caller could post as anyone). Only the substrate's own local code (`caller: None`, + // the owner) may name the sender, as the live-call transcript does for a speaker. + if let (Some(caller), Some(named)) = (ctx.caller.as_ref(), p.sender_id) { + if caller.peer_id.as_uuid() != named { + return Err(CommandError::Denied(format!( + "chat/send: caller {} may not speak as {named}; omit senderId to speak as yourself", + caller.peer_id.as_uuid() + ))); + } + } + let sender_id = ctx + .caller + .as_ref() + .map(|c| c.peer_id.as_uuid()) + .or(p.sender_id) .or_else(|| { if agent_session { crate::persona::operator_peer::agent_runtime() @@ -218,6 +232,23 @@ mod tests { // every caller binds to) and stays AiSafe — chat/send WRITES, but posting a message // is a normal persona action, not the Owner-locked data/delete class. A regression // that renamed the path or narrowed access (gagging personas) is caught here. + // what this catches: impersonation through chat/send (an explicit senderId used to win over + // the authenticated caller, so any persona or grid peer could post as Joel): a caller naming + // anyone but itself is refused before anything is stored or published. + #[tokio::test] + async fn an_authenticated_caller_cannot_speak_as_someone_else() { + let command = ChatSend { executor_slot: Arc::new(LateBound::new("test::chat_send")) }; + let caller = crate::identity::PeerId::from_uuid(Uuid::new_v4()); + let ctx = crate::sdk_codegen::Ctx { + caller: Some(crate::routing::CallerIdentity::airc(caller)), + ..Default::default() + }; + let joel = Uuid::new_v4(); + let params = ChatSendWireParams { room_id: Uuid::new_v4(), sender_id: Some(joel), text: "hi".into(), reply_to_id: None }; + let refused = command.run(&ctx, params).await; + assert!(matches!(refused, Err(CommandError::Denied(_))), "speaking as someone else is refused: {refused:?}"); + } + #[test] fn name_and_access_are_the_contract() { assert_eq!(ChatSend::NAME, "chat/send"); diff --git a/core/continuum-mind/src/chat/line_store.rs b/core/continuum-mind/src/chat/line_store.rs index fa24666453..a8f9c54a9b 100644 --- a/core/continuum-mind/src/chat/line_store.rs +++ b/core/continuum-mind/src/chat/line_store.rs @@ -10,6 +10,7 @@ use uuid::Uuid; use super::arrival::{Arrival, ArrivalKind}; use super::chat_data_handle::{now_iso, ChatModule, CHAT_DATA_HANDLE}; use super::import_watermark::{ImportHistory, ImportWatermark, ImportedThrough}; +use super::publication::PublicationObligation; use super::types::CHAT_MESSAGES_COLLECTION; use crate::orm::types::{BatchOperation, BatchOperationType}; use crate::runtime::late_bound::LateBound; @@ -24,6 +25,9 @@ pub struct PostedLine { pub direct_to: Option, pub occurred_at_ms: u64, pub text: String, + /// The line was delegated through this core's publication obligation, which the import retires + /// in the same batch. + pub retires_publication: bool, } /// Where a line landed in arrival order. @@ -57,6 +61,9 @@ pub trait LineImporter: Send + Sync { /// the store has not committed. async fn import(&self, line: PostedLine) -> Result; + /// The publication obligation `id` names, if this core published that line for a caller. + async fn publication(&self, id: Uuid) -> Result, String>; + /// How far the store has imported `room` from airc; `None` when it never has. async fn watermark(&self, room: RoomId) -> Result, String>; @@ -79,6 +86,10 @@ impl LineImporter for ChatStore { .await } + async fn publication(&self, id: Uuid) -> Result, String> { + installed()?.publication(id).await + } + async fn watermark(&self, room: RoomId) -> Result, String> { installed()?.import_watermark(room).await } @@ -104,6 +115,7 @@ fn installed() -> Result, String> { pub struct RecordingImporter( pub std::sync::Mutex>, pub std::sync::Mutex>, + pub std::sync::Mutex>, ); #[cfg(any(test, feature = "test-fixtures"))] @@ -117,6 +129,10 @@ impl LineImporter for RecordingImporter { }) } + async fn publication(&self, id: Uuid) -> Result, String> { + Ok(self.2.lock().unwrap_or_else(|p| p.into_inner()).get(&id).cloned()) // test fixture: a poisoned lock still holds the obligations + } + async fn watermark(&self, room: RoomId) -> Result, String> { Ok(self .1 @@ -197,7 +213,17 @@ impl ChatModule { line.direct_to, ); let append_op = arrival.append_op().map_err(|e| format!("chat line: {e}"))?; - let params = json!({ "dbPath": CHAT_DATA_HANDLE, "operations": [message_op, append_op] }); + let mut operations = vec![message_op, append_op]; + if line.retires_publication { + // The relayed line came back: its obligation retires with the import, atomically. + operations.push(BatchOperation { + operation_type: BatchOperationType::Delete, + collection: ::COLLECTION.to_string(), + id: Some(line.message_id.to_string()), + data: None, + }); + } + let params = json!({ "dbPath": CHAT_DATA_HANDLE, "operations": operations }); let result = executor .execute_json("data/batch", params) .await @@ -238,6 +264,10 @@ impl LineImporter for RefusingImporter { Err("test: the store refused the line".to_string()) } + async fn publication(&self, _id: Uuid) -> Result, String> { + Err("test: the store cannot read".to_string()) + } + async fn watermark(&self, _room: RoomId) -> Result, String> { Err("test: the store cannot read".to_string()) } diff --git a/core/continuum-mind/src/chat/mod.rs b/core/continuum-mind/src/chat/mod.rs index deca09407e..3eb72a8e13 100644 --- a/core/continuum-mind/src/chat/mod.rs +++ b/core/continuum-mind/src/chat/mod.rs @@ -62,6 +62,7 @@ use types::{ChatPollParams, ChatPollResult, ChatSendParams, ChatSendResult, CHAT pub mod arrival; pub mod line_store; pub mod drain; +pub mod publication; pub mod import_watermark; pub mod orm_entities; mod chat_data_handle; diff --git a/core/continuum-mind/src/chat/orm_entities.rs b/core/continuum-mind/src/chat/orm_entities.rs index 6265971d24..ed0b01c3f9 100644 --- a/core/continuum-mind/src/chat/orm_entities.rs +++ b/core/continuum-mind/src/chat/orm_entities.rs @@ -5,6 +5,7 @@ pub const CHAT_ORM_COLLECTIONS: &[&str] = &[ ::COLLECTION, ::COLLECTION, + ::COLLECTION, ]; /// Register the chat store's entities (arrivals with their unique indexes; import watermarks). @@ -14,5 +15,6 @@ pub fn register_chat_orm_entities( ) -> Result<(), crate::orm::RegistrationError> { registry.register::()?; registry.register::()?; + registry.register::()?; Ok(()) } diff --git a/core/continuum-mind/src/chat/publication.rs b/core/continuum-mind/src/chat/publication.rs new file mode 100644 index 0000000000..19c34506de --- /dev/null +++ b/core/continuum-mind/src/chat/publication.rs @@ -0,0 +1,263 @@ +//! A relayed line's proof of origin. When `chat/send` publishes a line for its caller through the +//! core's relay (the envelope leg), it first records a durable PUBLICATION OBLIGATION in the same +//! batch as the message row: the message id, room, sender (bound to the authenticated caller) and the +//! digest of the exact envelope it publishes. The inbound seam attributes a line to a sender other +//! than its transport author only when the line it received matches an obligation exactly: same id, +//! room, claimed sender and envelope digest. A forged sender header, a different room, or a reused id +//! with altered text matches nothing and is refused; it is never relabeled (Codex on #5696). +//! +//! The digest is an integrity check of the publication, computed from its typed fields with no +//! serialization; routing still reads only the typed headers. + +use airc_core::{PeerId, RoomId}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use uuid::Uuid; + +/// The digest of a published line, fed directly with its typed facts (no serialization): message id, +/// room, sender, text and each media item's content handle, each length-prefixed so no two lines +/// can collide by moving a boundary. The publisher computes it from what it sends, the seam from what +/// it received; any altered field changes it. +pub fn publication_digest( + message: Uuid, + room: RoomId, + sender: PeerId, + text: &str, + media: &[crate::cognition::conversation::channel_items::MediaItemRequest], +) -> [u8; 32] { + let mut hash = Sha256::new(); + let mut field = |bytes: &[u8]| { + hash.update((bytes.len() as u64).to_le_bytes()); + hash.update(bytes); + }; + field(message.as_bytes()); + field(room.as_uuid().as_bytes()); + field(sender.as_uuid().as_bytes()); + field(text.as_bytes()); + for item in media { + field( + item.blob_hash + .as_deref() + .or(item.url.as_deref()) + .unwrap_or_default() + .as_bytes(), + ); // unwrap_or_default: an item with neither handle still counts, as an empty field + } + hash.finalize().into() +} + +/// One line `chat/send` published for its caller and has not yet seen come back. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, crate::orm::Entity)] +#[serde(rename_all = "camelCase")] +#[entity(collection = "chat_publications")] +pub struct PublicationObligation { + /// The message id (the stored row's, and the envelope's `continuum.event_id` header). + #[entity(primary_key)] + pub id: Uuid, + pub room: RoomId, + pub sender: PeerId, + pub digest: [u8; 32], +} + +/// Who a received line is from. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Attribution { + /// The transport author speaks for itself (no claim, or a claim naming itself). + Author(PeerId), + /// The core relayed it for this sender, proven by its publication obligation. + Delegated { sender: PeerId }, + /// A claim to speak for someone else that nothing proves: dropped, said, never relabeled. + Refused { + claimed: PeerId, + reason: DelegationRefusal, + }, +} + +/// Why a claim to speak for someone else was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DelegationRefusal { + /// No publication obligation for this message id (a forged claim, or a foreign relay: no + /// scoped relay grant exists yet). + NoOrigin, + /// The obligation is for another room. + RoomMismatch, + /// The obligation names another sender. + SenderMismatch, + /// The envelope is not the one published (a reused id with altered content). + AlteredPublication, +} + +/// Decide a received line's attribution from its transport author, the sender its header claims, the +/// obligation its message id names (if any) and the digest of the envelope it arrived as (`None` when +/// it could not be decoded, which matches no publication). Pure. +pub fn attribute( + transport: PeerId, + claimed: Option, + room: RoomId, + obligation: Option<&PublicationObligation>, + received: Option<[u8; 32]>, +) -> Attribution { + let claimed = match claimed { + None => return Attribution::Author(transport), + Some(claimed) if claimed == transport => return Attribution::Author(transport), + Some(claimed) => claimed, + }; + let refuse = |reason| Attribution::Refused { claimed, reason }; + let Some(obligation) = obligation else { + return refuse(DelegationRefusal::NoOrigin); + }; + if obligation.room != room { + return refuse(DelegationRefusal::RoomMismatch); + } + if obligation.sender != claimed { + return refuse(DelegationRefusal::SenderMismatch); + } + if Some(obligation.digest) != received { + return refuse(DelegationRefusal::AlteredPublication); + } + Attribution::Delegated { sender: claimed } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn obligation(room: RoomId, sender: PeerId, digest: [u8; 32]) -> PublicationObligation { + PublicationObligation { + id: Uuid::new_v4(), + room, + sender, + digest, + } + } + + // what this catches: attribution decided by anything but proof of origin (Codex on #5696): no + // claim and a self claim are the author; a forged claim to be Joel, a room mismatch, another + // sender, and a reused id with altered content are refused; only an exact obligation delegates. + #[test] + fn only_an_exact_publication_delegates() { + let (relay, joel, room) = (PeerId::new(), PeerId::new(), RoomId::new()); + let published = [7u8; 32]; + let exact = obligation(room, joel, published); + assert_eq!( + attribute(relay, None, room, None, Some(published)), + Attribution::Author(relay), + "no claim" + ); + assert_eq!( + attribute(relay, Some(relay), room, None, Some(published)), + Attribution::Author(relay), + "self" + ); + assert_eq!( + attribute(relay, Some(joel), room, None, Some(published)), + Attribution::Refused { + claimed: joel, + reason: DelegationRefusal::NoOrigin + }, + "a forged Joel header proves nothing" + ); + assert_eq!( + attribute( + relay, + Some(joel), + RoomId::new(), + Some(&exact), + Some(published) + ), + Attribution::Refused { + claimed: joel, + reason: DelegationRefusal::RoomMismatch + } + ); + assert!(matches!( + attribute( + relay, + Some(PeerId::new()), + room, + Some(&exact), + Some(published) + ), + Attribution::Refused { + reason: DelegationRefusal::SenderMismatch, + .. + } + )); + assert_eq!( + attribute(relay, Some(joel), room, Some(&exact), Some([9u8; 32])), + Attribution::Refused { + claimed: joel, + reason: DelegationRefusal::AlteredPublication + }, + "a reused id with changed content" + ); + assert_eq!( + attribute(relay, Some(joel), room, Some(&exact), Some(published)), + Attribution::Delegated { sender: joel } + ); + } +} + +impl super::chat_data_handle::ChatModule { + /// Record that this core is publishing this line for `params.sender_id` (bound to the + /// authenticated caller by `chat/send`), before it is published. + pub(super) async fn record_publication( + &self, + message_id: Uuid, + params: &super::types::ChatSendParams, + ) -> Result<(), String> { + let (room, sender) = ( + RoomId::from_uuid(params.room_id), + PeerId::from_uuid(params.sender_id), + ); + let obligation = PublicationObligation { + id: message_id, + room, + sender, + digest: publication_digest(message_id, room, sender, ¶ms.text, ¶ms.media), + }; + let data = serde_json::to_value(&obligation).map_err(|e| format!("publication: {e}"))?; // storage boundary: the adapter's row format + let params = serde_json::json!({ + "dbPath": super::chat_data_handle::CHAT_DATA_HANDLE, + "collection": ::COLLECTION, + "id": message_id.to_string(), + "data": data, + }); + let result = self + .executor()? + .execute_json("data/create", params) + .await + .map_err(|e| format!("publication: data/create failed: {e}"))?; + match result.get("success").and_then(serde_json::Value::as_bool) { + Some(true) => Ok(()), + _ => Err(format!( + "publication: the store refused the obligation: {result}" + )), + } + } + + /// The obligation a received line's message id names, if any. + pub(super) async fn publication( + &self, + id: Uuid, + ) -> Result, String> { + let params = serde_json::json!({ + "dbPath": super::chat_data_handle::CHAT_DATA_HANDLE, + "collection": ::COLLECTION, + "id": id.to_string(), + }); + let result = self + .executor()? + .execute_json("data/read", params) + .await + .map_err(|e| format!("publication: data/read failed: {e}"))?; + if result.get("success").and_then(serde_json::Value::as_bool) != Some(true) { + return Ok(None); + } + let Some(data) = result.get("data").and_then(|d| d.get("data")).cloned() else { + return Ok(None); + }; + let row = serde_json::from_value(data); // storage boundary: the adapter's row format + row.map(Some).map_err(|e| format!("publication: malformed row: {e}")) + } +} diff --git a/core/continuum-mind/src/chat/tests/mod.rs b/core/continuum-mind/src/chat/tests/mod.rs index c80c0c8829..be29bc26b1 100644 --- a/core/continuum-mind/src/chat/tests/mod.rs +++ b/core/continuum-mind/src/chat/tests/mod.rs @@ -117,6 +117,7 @@ direct_to: Some(airc_core::PeerId::new()), occurred_at_ms: 1_784_227_923_000, text: text.to_string(), + retires_publication: false, } } @@ -612,10 +613,12 @@ #[tokio::test] pub(super) async fn send_happy_path_returns_message_id_and_event_id() { let chat = chat_with_stubs(vec![ - Arc::new(StubDataModule::new(|cmd, _p| { - assert_eq!( - cmd, "data/batch", - "happy path only writes (no other data ops)" + Arc::new(StubDataModule::new(|cmd, p| { + // The row batch, then the publication obligation recorded before the envelope leg + // publishes (#5696). Nothing else. + assert!( + cmd == "data/batch" || (cmd == "data/create" && p["collection"] == "chat_publications"), + "happy path only writes the line and its publication obligation: {cmd}" ); Ok(batch_ok()) })), @@ -656,6 +659,10 @@ let sent = media.clone(); let chat = chat_with_stubs(vec![ Arc::new(StubDataModule::new(move |cmd, p| { + if cmd == "data/create" { + assert_eq!(p["collection"], "chat_publications", "the only create is the publication obligation"); + return Ok(json!({ "success": true })); + } assert_eq!(cmd, "data/batch"); assert_eq!(p["operations"][0]["data"]["content"]["media"], json!([stored])); assert_eq!(p["operations"][0]["data"]["content"]["text"], "Look at the page"); From b18bdec7a3b743d4e60282aa90c037f14ef79017 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 19:10:51 -0600 Subject: [PATCH 4/7] Attribution binds its relay, types the claim, digests every visible field, and commits the obligation with the line (Codex's blockers at f13c54b2) - Relay binding: the obligation names the relay this core publishes callers' lines as (the airc module's scope peer, registered once as chat::publication::relay). attribute refuses any other transport with ForeignRelay, so another peer replaying an exact publication cannot be delegated or retire it. - Typed claim: a person's line carries its own header, continuum.sender_id, which only a chat_transcript envelope stamps. claimed_sender returns Absent | Named | Malformed; a present non-id is refused as MalformedClaim before any consumer, never read as absent. Free-form continuum.source_id provenance (an event bridge, a presence subject) is no claim. - Digest: id, room, sender, text, and every media field a consumer sees (kind, MIME, both handles, description, each with its presence), length-prefixed, with no serialization. - Atomicity: on the envelope leg the obligation commits in the SAME batch as the row and its arrival (persist(.., relayed)). The fallback after a failed sender publish records it alone, still before publishing (record_publication): a crash between leaves an unused obligation, never an unproven line. The docs say exactly this now. Tests (M5, serving down 01:05-01:10Z): mind chat 51 (new: a replay by another peer and a malformed claim are refused; every media mutation changes the digest; the obligation rides the line's batch); core inbound_attach+data_wiring 17 (new: another peer replaying the exact publication, a malformed sender header); kernel wire 1 (claims: absent, named, provenance is no claim, malformed); cognition conversation 54; ratchets exit 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../continuum-core/src/airc/inbound_attach.rs | 13 +- .../src/airc/inbound_attach/tests.rs | 25 +- core/continuum-core/src/modules/airc.rs | 3 + .../src/routing/airc_realtime_wire.rs | 58 ++- .../src/chat/chat_data_handle.rs | 9 +- core/continuum-mind/src/chat/commands/send.rs | 6 +- core/continuum-mind/src/chat/line_store.rs | 4 +- core/continuum-mind/src/chat/publication.rs | 376 ++++++++++++------ core/continuum-mind/src/chat/tests/mod.rs | 25 +- 9 files changed, 348 insertions(+), 171 deletions(-) diff --git a/core/continuum-core/src/airc/inbound_attach.rs b/core/continuum-core/src/airc/inbound_attach.rs index 1e9477b0da..f3ccbbc723 100644 --- a/core/continuum-core/src/airc/inbound_attach.rs +++ b/core/continuum-core/src/airc/inbound_attach.rs @@ -543,8 +543,9 @@ enum Gate { async fn attribution_gate(event: &airc_core::TranscriptEvent, lines: &dyn LineImporter) -> Result { use crate::routing::airc_realtime_wire::{claimed_message, claimed_sender, envelope_from_event}; use continuum_mind::chat::publication::{attribute, publication_digest, Attribution}; - let claimed = claimed_sender(event); - if claimed.is_none() || claimed == Some(event.peer_id) { + use crate::routing::airc_realtime_wire::SenderClaim; + let claim = claimed_sender(event); + if claim == SenderClaim::Absent || claim == SenderClaim::Named(event.peer_id) { return Ok(Gate::Pass { delegated: false }); } let obligation = match claimed_message(event) { @@ -553,14 +554,14 @@ async fn attribution_gate(event: &airc_core::TranscriptEvent, lines: &dyn LineIm }; // The line as received, from the one chat_transcript decoder (its claimed sender, its text and // media); a line that does not decode matches no publication. - let received = match (claimed_message(event), claimed, envelope_from_event(event)) { - (Some(message), Some(sender), Ok(Some(envelope))) => { + let received = match (claimed_message(event), claim, envelope_from_event(event)) { + (Some(message), SenderClaim::Named(sender), Ok(Some(envelope))) => { crate::cognition::conversation::room_event::chat_transcript_content(&envelope, sender.as_uuid()) .map(|turn| publication_digest(message, event.room_id, sender, &turn.text, &turn.media)) } _ => None, }; - match attribute(event.peer_id, claimed, event.room_id, obligation.as_ref(), received) { + match attribute(event.peer_id, claim, event.room_id, obligation.as_ref(), received) { Attribution::Author(_) => Ok(Gate::Pass { delegated: false }), Attribution::Delegated { .. } => Ok(Gate::Pass { delegated: true }), Attribution::Refused { claimed, reason } => { @@ -568,7 +569,7 @@ async fn attribution_gate(event: &airc_core::TranscriptEvent, lines: &dyn LineIm class = "airc.inbound.delegation_refused", room = %event.room_id.as_uuid(), transport = %event.peer_id.as_uuid(), - claimed = %claimed.as_uuid(), + claimed = ?claimed.map(|c| c.as_uuid()), reason = ?reason, "a line claimed to speak for someone it could not prove; refused, not relabeled" ); diff --git a/core/continuum-core/src/airc/inbound_attach/tests.rs b/core/continuum-core/src/airc/inbound_attach/tests.rs index 50fb4b5c51..7e16e22248 100644 --- a/core/continuum-core/src/airc/inbound_attach/tests.rs +++ b/core/continuum-core/src/airc/inbound_attach/tests.rs @@ -146,7 +146,7 @@ async fn chat_transcript_envelope_projects_chat_posted() { let message = Uuid::from_u128(0x3); let (event, _envelope) = relayed_line(PeerId::from_u128(3), sender, RoomId::from_u128(2), "is anyone there?", message); let lines = continuum_mind::chat::line_store::RecordingImporter::default(); - lines.2.lock().expect("test: lock").insert(message, obligation_for("is anyone there?", message, RoomId::from_u128(2), sender)); // test: a fixture step that must succeed + lines.2.lock().expect("test: lock").insert(message, obligation_for(PeerId::from_u128(3), "is anyone there?", message, RoomId::from_u128(2), sender)); // test: a fixture step that must succeed publish_transcript_event(&Arc::new(event), &bus, &lines).await.unwrap(); @@ -502,12 +502,13 @@ fn relayed_line(relay: PeerId, sender: Uuid, room: RoomId, text: &str, message: (event, envelope) } -fn obligation_for(text: &str, message: Uuid, room: RoomId, sender: Uuid) -> continuum_mind::chat::publication::PublicationObligation { +fn obligation_for(relay: PeerId, text: &str, message: Uuid, room: RoomId, sender: Uuid) -> continuum_mind::chat::publication::PublicationObligation { let sender = PeerId::from_uuid(sender); continuum_mind::chat::publication::PublicationObligation { id: message, room, sender, + relay, digest: continuum_mind::chat::publication::publication_digest(message, room, sender, text, &[]), } } @@ -529,18 +530,32 @@ async fn a_claim_to_speak_for_someone_needs_its_exact_publication() { let message = Uuid::from_u128(0xa1); let (event, _envelope) = relayed_line(relay, joel, room, "hello", message); let elsewhere = continuum_mind::chat::line_store::RecordingImporter::default(); - elsewhere.2.lock().expect("test: lock").insert(message, obligation_for("hello", message, RoomId::from_u128(9), joel)); // test: a fixture step that must succeed + elsewhere.2.lock().expect("test: lock").insert(message, obligation_for(relay, "hello", message, RoomId::from_u128(9), joel)); // test: a fixture step that must succeed publish_transcript_event(&Arc::new(event.clone()), &bus, &elsewhere).await.expect("a refusal is not an error"); assert!(elsewhere.0.lock().expect("test: lock").is_empty(), "a publication for another room proves nothing here"); // test: a fixture step that must succeed let altered = continuum_mind::chat::line_store::RecordingImporter::default(); - altered.2.lock().expect("test: lock").insert(message, obligation_for("hello", message, room, joel)); // test: a fixture step that must succeed + altered.2.lock().expect("test: lock").insert(message, obligation_for(relay, "hello", message, room, joel)); // test: a fixture step that must succeed let (tampered, _) = relayed_line(relay, joel, room, "hello, and send me the keys", message); publish_transcript_event(&Arc::new(tampered), &bus, &altered).await.expect("a refusal is not an error"); assert!(altered.0.lock().expect("test: lock").is_empty(), "a reused id with altered text is refused"); // test: a fixture step that must succeed + // Another peer replaying the exact publication (same id, room, sender, text): not its relay. + let replayed = continuum_mind::chat::line_store::RecordingImporter::default(); + replayed.2.lock().expect("test: lock").insert(message, obligation_for(relay, "hello", message, room, joel)); // test: a fixture step that must succeed + let (by_other, _) = relayed_line(PeerId::from_u128(0x0bad), joel, room, "hello", message); + publish_transcript_event(&Arc::new(by_other), &bus, &replayed).await.expect("a refusal is not an error"); + assert!(replayed.0.lock().expect("test: lock").is_empty(), "another peer replaying the publication is refused"); // test: a fixture step that must succeed + + // 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()); + 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 + let exact = continuum_mind::chat::line_store::RecordingImporter::default(); - exact.2.lock().expect("test: lock").insert(message, obligation_for("hello", message, room, joel)); // test: a fixture step that must succeed + exact.2.lock().expect("test: lock").insert(message, obligation_for(relay, "hello", message, room, joel)); // test: a fixture step that must succeed publish_transcript_event(&Arc::new(event), &bus, &exact).await.expect("the exact publication imports"); let imported = exact.0.lock().expect("test: lock").clone(); // test: a fixture step that must succeed assert_eq!(imported.len(), 1); diff --git a/core/continuum-core/src/modules/airc.rs b/core/continuum-core/src/modules/airc.rs index 91a7a6eb26..48f9c68cf0 100644 --- a/core/continuum-core/src/modules/airc.rs +++ b/core/continuum-core/src/modules/airc.rs @@ -95,6 +95,9 @@ impl AircModule { // 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)); Self { queue_client: Arc::new(CliAircQueueClient::new(TokioAircCommandRunner)), // #3849: the socket is re-resolved when the daemon diff --git a/core/continuum-kernel/src/routing/airc_realtime_wire.rs b/core/continuum-kernel/src/routing/airc_realtime_wire.rs index bd4410b366..9f9b18cb05 100644 --- a/core/continuum-kernel/src/routing/airc_realtime_wire.rs +++ b/core/continuum-kernel/src/routing/airc_realtime_wire.rs @@ -15,12 +15,15 @@ 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"; 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.source_id` header the publisher stamped (a relay -/// publishes a human's line for them); the transport peer when the header is absent or is not an id -/// (a presence subject, a free-form source). Read from the header alone: the body is never opened to +/// 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 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). /// /// Trust is the relay rule's, not this decoder's: whether a transport peer may speak for the sender it @@ -28,19 +31,31 @@ pub const HEADER_CONTINUUM_TRACE_ID: &str = "continuum.trace_id"; pub fn logical_sender(event: &TranscriptEvent) -> uuid::Uuid { event .headers - .get(HEADER_CONTINUUM_SOURCE_ID) - .and_then(|value| uuid::Uuid::parse_str(value).ok()) // wire boundary: a header value is text; a non-id source is a non-person publisher + .get(HEADER_CONTINUUM_SENDER_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 } -/// The sender a line's header claims it speaks for, when it names one by id. `None` when no claim -/// (or a non-id source) is made; the transport peer is then the author. -pub fn claimed_sender(event: &TranscriptEvent) -> Option { - event - .headers - .get(HEADER_CONTINUUM_SOURCE_ID) - .and_then(|value| uuid::Uuid::parse_str(value).ok()) // wire boundary: a header value is text - .map(airc_core::PeerId::from_uuid) +/// What a line's `continuum.sender_id` header claims about who it speaks for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SenderClaim { + /// No claim: the transport peer is the author. + Absent, + /// A claim naming this sender. + Named(airc_core::PeerId), + /// A header is present but is not an id: refused before any consumer, never read as absent. + Malformed, +} + +/// 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) { + 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)), + Err(_) => SenderClaim::Malformed, + }, + } } /// The message id a continuum envelope is named by (`continuum.event_id`), when it is an id. @@ -77,6 +92,13 @@ 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 } @@ -189,10 +211,14 @@ 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_SOURCE_ID.to_string(), human.to_string())])); + let relayed = event(Headers::from([(HEADER_CONTINUUM_SENDER_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)); - let named = event(Headers::from([(HEADER_CONTINUUM_SOURCE_ID.to_string(), "persona-1".to_string())])); - assert_eq!(logical_sender(&named), uuid::Uuid::from_u128(0x4e), "a non-id source is not a person"); + 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())])); + assert_eq!(claimed_sender(&garbled), SenderClaim::Malformed, "a present sender header that is not an id"); } } diff --git a/core/continuum-mind/src/chat/chat_data_handle.rs b/core/continuum-mind/src/chat/chat_data_handle.rs index a758d5e372..992b74e3c7 100644 --- a/core/continuum-mind/src/chat/chat_data_handle.rs +++ b/core/continuum-mind/src/chat/chat_data_handle.rs @@ -208,7 +208,7 @@ impl ChatModule { params: ChatSendParams, wire: WireLeg, ) -> Result { - let (message_id, now_ms) = self.persist(¶ms).await?; + let (message_id, now_ms) = self.persist(¶ms, wire == WireLeg::Envelope).await?; match wire { WireLeg::Envelope => self.broadcast_envelope(message_id, ¶ms, now_ms).await, WireLeg::CallerSpeaks => Ok(ChatSendResult { @@ -221,8 +221,11 @@ impl ChatModule { /// Step 1 of a send: persist the message row (ground truth). Returns the /// minted message id and the timestamp the row carries. - pub(super) async fn persist(&self, params: &ChatSendParams) -> Result<(Uuid, u64), String> { + /// `relayed`: this core will publish the line for its caller (the envelope leg), so its + /// publication obligation commits in the same batch as the row and arrival. + pub(super) async fn persist(&self, params: &ChatSendParams, relayed: bool) -> Result<(Uuid, u64), String> { let message_id = Uuid::new_v4(); + let extra = if relayed { vec![Self::publication_op(message_id, params)?] } else { Vec::new() }; let now_ms = continuum_base::time::EpochMs::now().millis(); // Ground truth first: the row and its arrival commit together, or the send fails and no // airc publish is attempted (broadcasting a line the store lacks would diverge). @@ -242,6 +245,7 @@ impl ChatModule { super::line_store::LineWrite::New, params.reply_to_id, content, + extra, ) .await .map_err(|e| format!("chat/send: {e}"))?; @@ -280,7 +284,6 @@ impl ChatModule { // Record the publication obligation BEFORE publishing (Codex on #5696): the exact envelope's // digest, the room and the sender, under the message id. The inbound seam delegates the line // to this sender only on an exact match, so the envelope published is the typed one digested. - self.record_publication(message_id, params).await?; let publish_params = json!({ "envelope": publish_envelope }); // Partial failure path: data succeeded, airc failed. Return diff --git a/core/continuum-mind/src/chat/commands/send.rs b/core/continuum-mind/src/chat/commands/send.rs index 6849123d33..36e4d045c4 100644 --- a/core/continuum-mind/src/chat/commands/send.rs +++ b/core/continuum-mind/src/chat/commands/send.rs @@ -164,7 +164,11 @@ crate::action_command! { } if let Some(e) = publish_err { // The say missed: fall back to the envelope leg so the line - // still reaches the wire, and say why. + // still reaches the wire, and say why. The core now publishes for the caller, + // so its publication obligation is recorded first (#5696). + chat.record_publication(result.message_id, ¶ms) + .await + .map_err(CommandError::Internal)?; let fallback = chat .broadcast_envelope( result.message_id, diff --git a/core/continuum-mind/src/chat/line_store.rs b/core/continuum-mind/src/chat/line_store.rs index a8f9c54a9b..d785ca8c20 100644 --- a/core/continuum-mind/src/chat/line_store.rs +++ b/core/continuum-mind/src/chat/line_store.rs @@ -82,7 +82,7 @@ pub struct ChatStore; impl LineImporter for ChatStore { async fn import(&self, line: PostedLine) -> Result { installed()? - .commit_line(&line, LineWrite::Import, None, json!({ "text": line.text })) + .commit_line(&line, LineWrite::Import, None, json!({ "text": line.text }), Vec::new()) .await } @@ -182,6 +182,7 @@ impl ChatModule { write: LineWrite, reply_to: Option, content: Value, + extra: Vec, ) -> Result { let executor = self.executor()?; // The same ChatMessageEntity shape for every writer; WHO spoke is `senderId`, and @@ -214,6 +215,7 @@ impl ChatModule { ); let append_op = arrival.append_op().map_err(|e| format!("chat line: {e}"))?; let mut operations = vec![message_op, append_op]; + operations.extend(extra); if line.retires_publication { // The relayed line came back: its obligation retires with the import, atomically. operations.push(BatchOperation { diff --git a/core/continuum-mind/src/chat/publication.rs b/core/continuum-mind/src/chat/publication.rs index 19c34506de..d22bd6f924 100644 --- a/core/continuum-mind/src/chat/publication.rs +++ b/core/continuum-mind/src/chat/publication.rs @@ -1,10 +1,14 @@ //! A relayed line's proof of origin. When `chat/send` publishes a line for its caller through the -//! core's relay (the envelope leg), it first records a durable PUBLICATION OBLIGATION in the same -//! batch as the message row: the message id, room, sender (bound to the authenticated caller) and the -//! digest of the exact envelope it publishes. The inbound seam attributes a line to a sender other -//! than its transport author only when the line it received matches an obligation exactly: same id, -//! room, claimed sender and envelope digest. A forged sender header, a different room, or a reused id -//! with altered text matches nothing and is refused; it is never relabeled (Codex on #5696). +//! core's relay (the envelope leg), it records a durable PUBLICATION OBLIGATION in the same batch as +//! the message row and its arrival: the message id, room, sender (bound to the authenticated +//! caller), the relay it publishes as, and the digest of the exact line. (The fallback after a failed +//! sender publish records it alone, still before publishing: [`ChatModule::record_publication`].) +//! +//! The inbound seam attributes a line to a sender other than its transport author only when the line +//! matches an obligation exactly: the same id, from the same relay, in the same room, for the same +//! sender, with the same digest. A forged sender header, a malformed one, another peer replaying the +//! publication, another room, or a reused id with altered content matches nothing and is refused; +//! it is never relabeled (Codex on #5696). //! //! The digest is an integrity check of the publication, computed from its typed fields with no //! serialization; routing still reads only the typed headers. @@ -14,10 +18,13 @@ use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use uuid::Uuid; +use super::chat_data_handle::ChatModule; +use crate::routing::airc_realtime_wire::SenderClaim; + /// The digest of a published line, fed directly with its typed facts (no serialization): message id, -/// room, sender, text and each media item's content handle, each length-prefixed so no two lines -/// can collide by moving a boundary. The publisher computes it from what it sends, the seam from what -/// it received; any altered field changes it. +/// room, sender, text and every field of every media item a consumer sees (kind, MIME, both handles, +/// description, each with its presence), length-prefixed so no two lines collide by moving a boundary. +/// The publisher computes it from what it sends, the seam from what it received. pub fn publication_digest( message: Uuid, room: RoomId, @@ -34,14 +41,24 @@ pub fn publication_digest( field(room.as_uuid().as_bytes()); field(sender.as_uuid().as_bytes()); field(text.as_bytes()); + field(&(media.len() as u64).to_le_bytes()); for item in media { - field( - item.blob_hash - .as_deref() - .or(item.url.as_deref()) - .unwrap_or_default() - .as_bytes(), - ); // unwrap_or_default: an item with neither handle still counts, as an empty field + field(item.kind.as_bytes()); + // An absent field and an empty one hash differently, so neither can stand in for the other. + for optional in [ + &item.mime_type, + &item.blob_hash, + &item.url, + &item.description, + ] { + match optional { + Some(value) => { + field(&[1]); + field(value.as_bytes()); + } + None => field(&[0]), + } + } } hash.finalize().into() } @@ -56,9 +73,23 @@ pub struct PublicationObligation { pub id: Uuid, pub room: RoomId, pub sender: PeerId, + /// The authenticated transport this core publishes relayed lines as: only it may deliver this line. + pub relay: PeerId, pub digest: [u8; 32], } +/// 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 +} + +pub fn relay() -> Option { + RELAY.get().copied() +} + /// Who a received line is from. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Attribution { @@ -66,9 +97,9 @@ pub enum Attribution { Author(PeerId), /// The core relayed it for this sender, proven by its publication obligation. Delegated { sender: PeerId }, - /// A claim to speak for someone else that nothing proves: dropped, said, never relabeled. + /// A claim nothing proves: dropped, said, never relabeled. `claimed` is `None` for a malformed claim. Refused { - claimed: PeerId, + claimed: Option, reason: DelegationRefusal, }, } @@ -76,36 +107,54 @@ pub enum Attribution { /// Why a claim to speak for someone else was refused. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DelegationRefusal { - /// No publication obligation for this message id (a forged claim, or a foreign relay: no - /// scoped relay grant exists yet). + /// The sender header is present but not an id. + MalformedClaim, + /// No publication obligation for this message id. NoOrigin, + /// It arrived from a transport other than the relay the obligation names (a replay by another + /// peer, or a foreign relay: no scoped relay grant exists yet). + ForeignRelay, /// The obligation is for another room. RoomMismatch, /// The obligation names another sender. SenderMismatch, - /// The envelope is not the one published (a reused id with altered content). + /// The line is not the one published (a reused id with altered content). AlteredPublication, } -/// Decide a received line's attribution from its transport author, the sender its header claims, the -/// obligation its message id names (if any) and the digest of the envelope it arrived as (`None` when -/// it could not be decoded, which matches no publication). Pure. +/// Decide a received line's attribution from its transport author, its header's sender claim, the +/// obligation its message id names (if any) and the digest of the line as received (`None` when it +/// could not be decoded, which matches no publication). Pure. pub fn attribute( transport: PeerId, - claimed: Option, + claim: SenderClaim, room: RoomId, obligation: Option<&PublicationObligation>, received: Option<[u8; 32]>, ) -> Attribution { - let claimed = match claimed { - None => return Attribution::Author(transport), - Some(claimed) if claimed == transport => return Attribution::Author(transport), - Some(claimed) => claimed, + let claimed = match claim { + SenderClaim::Absent => return Attribution::Author(transport), + SenderClaim::Named(claimed) if claimed == transport => { + return Attribution::Author(transport) + } + SenderClaim::Named(claimed) => claimed, + SenderClaim::Malformed => { + return Attribution::Refused { + claimed: None, + reason: DelegationRefusal::MalformedClaim, + } + } + }; + let refuse = |reason| Attribution::Refused { + claimed: Some(claimed), + reason, }; - let refuse = |reason| Attribution::Refused { claimed, reason }; let Some(obligation) = obligation else { return refuse(DelegationRefusal::NoOrigin); }; + if obligation.relay != transport { + return refuse(DelegationRefusal::ForeignRelay); + } if obligation.room != room { return refuse(DelegationRefusal::RoomMismatch); } @@ -118,94 +167,16 @@ pub fn attribute( Attribution::Delegated { sender: claimed } } -#[cfg(test)] -mod tests { - use super::*; - - fn obligation(room: RoomId, sender: PeerId, digest: [u8; 32]) -> PublicationObligation { - PublicationObligation { - id: Uuid::new_v4(), - room, - sender, - digest, - } - } - - // what this catches: attribution decided by anything but proof of origin (Codex on #5696): no - // claim and a self claim are the author; a forged claim to be Joel, a room mismatch, another - // sender, and a reused id with altered content are refused; only an exact obligation delegates. - #[test] - fn only_an_exact_publication_delegates() { - let (relay, joel, room) = (PeerId::new(), PeerId::new(), RoomId::new()); - let published = [7u8; 32]; - let exact = obligation(room, joel, published); - assert_eq!( - attribute(relay, None, room, None, Some(published)), - Attribution::Author(relay), - "no claim" - ); - assert_eq!( - attribute(relay, Some(relay), room, None, Some(published)), - Attribution::Author(relay), - "self" - ); - assert_eq!( - attribute(relay, Some(joel), room, None, Some(published)), - Attribution::Refused { - claimed: joel, - reason: DelegationRefusal::NoOrigin - }, - "a forged Joel header proves nothing" - ); - assert_eq!( - attribute( - relay, - Some(joel), - RoomId::new(), - Some(&exact), - Some(published) - ), - Attribution::Refused { - claimed: joel, - reason: DelegationRefusal::RoomMismatch - } - ); - assert!(matches!( - attribute( - relay, - Some(PeerId::new()), - room, - Some(&exact), - Some(published) - ), - Attribution::Refused { - reason: DelegationRefusal::SenderMismatch, - .. - } - )); - assert_eq!( - attribute(relay, Some(joel), room, Some(&exact), Some([9u8; 32])), - Attribution::Refused { - claimed: joel, - reason: DelegationRefusal::AlteredPublication - }, - "a reused id with changed content" - ); - assert_eq!( - attribute(relay, Some(joel), room, Some(&exact), Some(published)), - Attribution::Delegated { sender: joel } - ); - } -} - -impl super::chat_data_handle::ChatModule { - /// Record that this core is publishing this line for `params.sender_id` (bound to the - /// authenticated caller by `chat/send`), before it is published. - pub(super) async fn record_publication( - &self, +impl ChatModule { + /// The obligation for a line this core is about to publish for `params.sender_id` (bound to the + /// authenticated caller by `chat/send`), as the batch operation that records it. + pub(super) fn publication_op( message_id: Uuid, params: &super::types::ChatSendParams, - ) -> Result<(), String> { + ) -> Result { + let relay = relay().ok_or( + "chat/send: this core has no relay identity (the airc module is not attached), so it cannot publish for a caller", + )?; let (room, sender) = ( RoomId::from_uuid(params.room_id), PeerId::from_uuid(params.sender_id), @@ -214,20 +185,33 @@ impl super::chat_data_handle::ChatModule { id: message_id, room, sender, + relay, digest: publication_digest(message_id, room, sender, ¶ms.text, ¶ms.media), }; let data = serde_json::to_value(&obligation).map_err(|e| format!("publication: {e}"))?; // storage boundary: the adapter's row format - let params = serde_json::json!({ - "dbPath": super::chat_data_handle::CHAT_DATA_HANDLE, - "collection": ::COLLECTION, - "id": message_id.to_string(), - "data": data, - }); + Ok(crate::orm::types::BatchOperation { + operation_type: crate::orm::types::BatchOperationType::Create, + collection: ::COLLECTION.to_string(), + id: Some(message_id.to_string()), + data: Some(data), + }) + } + + /// The fallback path's custody: the line is already stored (its sender's own publish failed), so + /// the obligation is recorded on its own, still BEFORE the envelope is published. A crash between + /// leaves an unused obligation (retired by retention), never an unproven line. + pub async fn record_publication( + &self, + message_id: Uuid, + params: &super::types::ChatSendParams, + ) -> Result<(), String> { + let op = Self::publication_op(message_id, params)?; + let params = serde_json::json!({ "dbPath": super::chat_data_handle::CHAT_DATA_HANDLE, "operations": [op] }); let result = self .executor()? - .execute_json("data/create", params) + .execute_json("data/batch", params) .await - .map_err(|e| format!("publication: data/create failed: {e}"))?; + .map_err(|e| format!("publication: data/batch failed: {e}"))?; match result.get("success").and_then(serde_json::Value::as_bool) { Some(true) => Ok(()), _ => Err(format!( @@ -258,6 +242,148 @@ impl super::chat_data_handle::ChatModule { return Ok(None); }; let row = serde_json::from_value(data); // storage boundary: the adapter's row format - row.map(Some).map_err(|e| format!("publication: malformed row: {e}")) + row.map(Some) + .map_err(|e| format!("publication: malformed row: {e}")) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::cognition::conversation::channel_items::MediaItemRequest; + + fn obligation( + relay: PeerId, + room: RoomId, + sender: PeerId, + digest: [u8; 32], + ) -> PublicationObligation { + PublicationObligation { + id: Uuid::new_v4(), + room, + sender, + relay, + digest, + } + } + + // what this catches: attribution decided by anything but proof of origin (Codex on #5696): no + // claim and a self claim are the author; a malformed claim, a forged claim to be Joel, a replay by + // another peer, a room mismatch, another sender and altered content are refused; only an exact + // obligation from its relay delegates. + #[test] + fn only_an_exact_publication_from_its_relay_delegates() { + let (relay, other, joel, room) = + (PeerId::new(), PeerId::new(), PeerId::new(), RoomId::new()); + let published = Some([7u8; 32]); + let exact = obligation(relay, room, joel, [7u8; 32]); + let named = SenderClaim::Named(joel); + assert_eq!( + attribute(relay, SenderClaim::Absent, room, None, published), + Attribution::Author(relay), + "no claim" + ); + assert_eq!( + attribute(relay, SenderClaim::Named(relay), room, None, published), + Attribution::Author(relay), + "self" + ); + assert_eq!( + attribute(relay, SenderClaim::Malformed, room, Some(&exact), published), + Attribution::Refused { + claimed: None, + reason: DelegationRefusal::MalformedClaim + }, + "a present but invalid header is refused, never read as absent" + ); + let refused = + |transport, claim, room, obligation: Option<&PublicationObligation>, received| { + match attribute(transport, claim, room, obligation, received) { + Attribution::Refused { reason, .. } => Some(reason), + _ => None, + } + }; + assert_eq!( + refused(relay, named, room, None, published), + Some(DelegationRefusal::NoOrigin), + "a forged Joel header" + ); + assert_eq!( + refused(other, named, room, Some(&exact), published), + Some(DelegationRefusal::ForeignRelay), + "another peer replaying the exact publication" + ); + assert_eq!( + refused(relay, named, RoomId::new(), Some(&exact), published), + Some(DelegationRefusal::RoomMismatch) + ); + assert_eq!( + refused( + relay, + SenderClaim::Named(PeerId::new()), + room, + Some(&exact), + published + ), + Some(DelegationRefusal::SenderMismatch) + ); + assert_eq!( + refused(relay, named, room, Some(&exact), Some([9u8; 32])), + Some(DelegationRefusal::AlteredPublication) + ); + assert_eq!( + refused(relay, named, room, Some(&exact), None), + Some(DelegationRefusal::AlteredPublication), + "an undecodable line" + ); + assert_eq!( + attribute(relay, named, room, Some(&exact), published), + Attribution::Delegated { sender: joel } + ); + } + + // what this catches: a digest that ignores a field a consumer sees, so altered media still + // matches the publication (Codex on #5696): every media field, and an absent field versus an empty + // one, changes the digest. + #[test] + fn every_consumer_visible_media_field_binds_the_digest() { + let (message, room, sender) = (Uuid::new_v4(), RoomId::new(), PeerId::new()); + let base = MediaItemRequest { + kind: "image".into(), + mime_type: Some("image/png".into()), + blob_hash: Some("sha256:aa".into()), + url: Some("https://a".into()), + description: Some("a cat".into()), + }; + let digest = |item: &MediaItemRequest| { + publication_digest(message, room, sender, "look", std::slice::from_ref(item)) + }; + let original = digest(&base); + let mutations: [fn(&mut MediaItemRequest); 6] = [ + |m| m.kind = "audio".into(), + |m| m.mime_type = Some("image/jpeg".into()), + |m| m.url = Some("https://b".into()), + |m| m.description = Some("a dog".into()), + |m| m.description = None, + |m| m.url = Some(String::new()), + ]; + for (i, mutate) in mutations.iter().enumerate() { + let mut altered = base.clone(); + mutate(&mut altered); + assert_ne!( + digest(&altered), + original, + "mutation {i} must change the digest" + ); + } + assert_ne!( + publication_digest(message, room, sender, "look", &[]), + original, + "dropping the media changes it" + ); + assert_ne!( + publication_digest(message, room, sender, "lookx", std::slice::from_ref(&base)), + original + ); } } diff --git a/core/continuum-mind/src/chat/tests/mod.rs b/core/continuum-mind/src/chat/tests/mod.rs index be29bc26b1..cfbcd4e972 100644 --- a/core/continuum-mind/src/chat/tests/mod.rs +++ b/core/continuum-mind/src/chat/tests/mod.rs @@ -26,6 +26,9 @@ registry.register(module); } 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)); ChatModule::with_executor(executor) } @@ -141,7 +144,7 @@ &line, crate::chat::line_store::LineWrite::Import, None, - json!({ "text": line.text }), + json!({ "text": line.text }), Vec::new(), ) .await .expect("the import commits"); @@ -199,7 +202,7 @@ &line, crate::chat::line_store::LineWrite::Import, None, - json!({ "text": line.text }), + json!({ "text": line.text }), Vec::new(), ) .await .expect("a duplicate is a committed import"); @@ -217,7 +220,7 @@ let chat = chat_with_stubs(vec![Arc::new(data)]); let line = imported_line("unconfirmed"); let err = chat - .commit_line(&line, crate::chat::line_store::LineWrite::Import, None, json!({ "text": line.text })) + .commit_line(&line, crate::chat::line_store::LineWrite::Import, None, json!({ "text": line.text }), Vec::new()) .await .expect_err("a reply without freshness is malformed"); assert!(err.contains("did not say whether it was fresh"), "named: {err}"); @@ -238,7 +241,7 @@ &line, crate::chat::line_store::LineWrite::Import, None, - json!({ "text": line.text }), + json!({ "text": line.text }), Vec::new(), ) .await .expect_err("a refusal is an error"); @@ -614,12 +617,10 @@ pub(super) async fn send_happy_path_returns_message_id_and_event_id() { let chat = chat_with_stubs(vec![ Arc::new(StubDataModule::new(|cmd, p| { - // The row batch, then the publication obligation recorded before the envelope leg - // publishes (#5696). Nothing else. - assert!( - cmd == "data/batch" || (cmd == "data/create" && p["collection"] == "chat_publications"), - "happy path only writes the line and its publication obligation: {cmd}" - ); + assert_eq!(cmd, "data/batch", "happy path only writes (no other data ops)"); + // The envelope leg relays for the caller: the publication obligation commits in the + // SAME batch as the row and its arrival (#5696), never a separate write. + assert_eq!(p["operations"][2]["collection"], "chat_publications", "obligation in the line's batch: {p}"); Ok(batch_ok()) })), Arc::new(StubAircModule::ok(airc_ok_response("evt-happy-001"))), @@ -659,10 +660,6 @@ let sent = media.clone(); let chat = chat_with_stubs(vec![ Arc::new(StubDataModule::new(move |cmd, p| { - if cmd == "data/create" { - assert_eq!(p["collection"], "chat_publications", "the only create is the publication obligation"); - return Ok(json!({ "success": true })); - } assert_eq!(cmd, "data/batch"); assert_eq!(p["operations"][0]["data"]["content"]["media"], json!([stored])); assert_eq!(p["operations"][0]["data"]["content"]["text"], "Look at the page"); From a2fb391e8935422b2d33a438dba5fad30be0432a Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 19:55:54 -0600 Subject: [PATCH 5/7] Relayed lines survive a restart: obligations re-publish until seen back, a retired obligation still proves its replay, and a duplicate is never perceived twice (Codex at b18bdec7) - Arrivals are the inbound seam's alone (P2): chat/send stores its row (plus the publication obligation when relaying) with store_sent_line, and its echo appends the arrival. commit_line is import-only; the LineWrite enum is gone; one message_row builder and one run_batch. - PublicationObligation carries a typed PublicationState {Pending, Retired}. The import of a delegated line marks it Retired (an Update in the same batch), never deleting it, so an exact replay after a restart before the watermark advanced is still attributed, not refused as NoOrigin. A forged claim still finds none. - Restart recovery: republish_pending re-publishes every Pending obligation's line, rebuilt from its stored row through broadcast_envelope (run after ring hydration at start). The digest binds typed fields only, so the rebuilt line is the published one. - The seam imports a chat line FIRST (one decode), and a Duplicate (a replay, a re-publish) is neither fed to perception nor projected again. Known gap until P2 perceives from the store: a line imported but not yet fed when the core died is not re-fed on replay. - RecordingImporter reports Duplicate for a held message id, as the store does. Tests (M5, serving down 01:51-01:55Z): mind chat 52 (new: a retired obligation still delegates its exact line and refuses altered content; a pending publication is re-published from its stored row as the same line); core inbound_attach+data_wiring 18 (new: a replayed line after retirement is attributed once, stored once, projected once); ratchets exit 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../continuum-core/src/airc/inbound_attach.rs | 40 ++++- .../src/airc/inbound_attach/tests.rs | 23 +++ .../src/chat/chat_data_handle.rs | 23 +-- core/continuum-mind/src/chat/line_store.rs | 144 +++++++++++------- core/continuum-mind/src/chat/publication.rs | 120 ++++++++++++++- core/continuum-mind/src/chat/tests/mod.rs | 59 ++++--- 6 files changed, 317 insertions(+), 92 deletions(-) diff --git a/core/continuum-core/src/airc/inbound_attach.rs b/core/continuum-core/src/airc/inbound_attach.rs index f3ccbbc723..4fa0ce27ca 100644 --- a/core/continuum-core/src/airc/inbound_attach.rs +++ b/core/continuum-core/src/airc/inbound_attach.rs @@ -370,6 +370,36 @@ pub async fn publish_transcript_event( Gate::Pass { delegated } => delegated, Gate::Refused => return Ok(()), }; + // THE STORE FIRST, ONCE (Slice P; Codex on #5696): a room line is imported, awaited, before + // anything consumes it; an error ends this attach before the watermark passes the line, and the + // re-attach replays it. A line the store already holds (a replay after a restart, a re-published + // relayed line) is not perceived or projected again. Known gap until P2 perceives from the store: + // a line imported but not yet fed when the core died is not re-fed on replay. + let decoded = envelope_from_event(event); + let chat_line = match &decoded { + Ok(None) => posted_from_message(event), + Ok(Some(envelope)) => posted_from_envelope(envelope, event).map(|mut line| { + line.retires_publication = delegated; + line + }), + Err(_) => None, + }; + if let Some(line) = &chat_line { + let imported = lines + .import(line.clone()) + .await + .map_err(|e| format!("inbound line not stored; re-attaching to replay it: {e}"))?; + if let continuum_mind::chat::line_store::Imported::Duplicate { arrival_seq } = imported { + continuum_base::probe!( + class = "airc.inbound.duplicate_line", + room = %event.room_id.as_uuid(), + message = %line.message_id, + arrival_seq = arrival_seq, + "a line the store already holds arrived again; not perceived or projected twice" + ); + return Ok(()); + } + } let fed = crate::persona::perception_feed::feed(&conversation, EpochMs::now().millis()); if fed > 0 { continuum_base::probe!( @@ -384,7 +414,7 @@ pub async fn publish_transcript_event( // review is verified (signed by its author, accepted in the room's projection, // admitted by the room's self-review policy). It used to settle here, on any // review-shaped event, unchecked. - let envelope = match envelope_from_event(event) { + let envelope = match decoded { Ok(Some(envelope)) => envelope, // Not a Continuum EventBridge envelope. Before dropping it, try // the thin chat projection: a plain airc chat message projects @@ -399,13 +429,7 @@ pub async fn publish_transcript_event( // content). An event is at most one of these; anything else is not // ours here → skip. Classification, never a fallback — a // non-matching kind fabricates nothing. - if let Some(line) = posted_from_message(event) { - // The durable transcript FIRST, awaited (#140, Slice P): an error ends this - // attach before the watermark can pass the line, and the re-attach replays it; - // the import is idempotent by id, so the replay never doubles it. - lines.import(line.clone()).await.map_err(|e| { - format!("inbound line not stored; re-attaching to replay it: {e}") - })?; + if let Some(line) = &chat_line { // task #84: the persona-turn / plain-airc-message stream into // the room. This is the seam a client's live read surface // (positron ChatViewState) is fed from — probe it so the turn diff --git a/core/continuum-core/src/airc/inbound_attach/tests.rs b/core/continuum-core/src/airc/inbound_attach/tests.rs index 7e16e22248..39c1a6fa0a 100644 --- a/core/continuum-core/src/airc/inbound_attach/tests.rs +++ b/core/continuum-core/src/airc/inbound_attach/tests.rs @@ -510,6 +510,7 @@ fn obligation_for(relay: PeerId, text: &str, message: Uuid, room: RoomId, sender sender, relay, digest: continuum_mind::chat::publication::publication_digest(message, room, sender, text, &[]), + state: continuum_mind::chat::publication::PublicationState::Pending, } } @@ -562,3 +563,25 @@ async fn a_claim_to_speak_for_someone_needs_its_exact_publication() { assert_eq!(imported[0].author, PeerId::from_uuid(joel), "delegated to the proven sender"); assert!(imported[0].retires_publication, "the import retires the obligation"); } + +// what this catches: the replay after a restart (Codex on #5696). A relayed line whose echo was +// imported and whose obligation retired arrives again: it is still attributed (not refused as +// having no origin), and as a line the store already holds it is neither stored again nor +// projected again. +#[tokio::test] +async fn a_replayed_line_is_attributed_once_and_never_projected_twice() { + let bus = MessageBus::new(); + let mut receiver = bus.receiver(); + let (relay, joel, room, message) = (PeerId::from_u128(0x4e), Uuid::from_u128(0x10e1), RoomId::from_u128(2), Uuid::from_u128(0xa1)); + let lines = continuum_mind::chat::line_store::RecordingImporter::default(); + let mut retired = obligation_for(relay, "hello", message, room, joel); + retired.state = continuum_mind::chat::publication::PublicationState::Retired; + lines.2.lock().expect("test: lock").insert(message, retired); // test: a fixture step that must succeed + let (event, _) = relayed_line(relay, joel, room, "hello", message); + publish_transcript_event(&Arc::new(event.clone()), &bus, &lines).await.expect("the replay imports"); + assert_eq!(lines.0.lock().expect("test: lock").len(), 1, "attributed and stored once"); // test: a fixture step that must succeed + assert!(timeout(Duration::from_millis(200), receiver.recv()).await.is_ok(), "projected the first time"); + publish_transcript_event(&Arc::new(event), &bus, &lines).await.expect("a duplicate is not an error"); + assert_eq!(lines.0.lock().expect("test: lock").len(), 1, "never stored twice"); // test: a fixture step that must succeed + assert!(timeout(Duration::from_millis(200), receiver.recv()).await.is_err(), "never projected twice"); +} diff --git a/core/continuum-mind/src/chat/chat_data_handle.rs b/core/continuum-mind/src/chat/chat_data_handle.rs index 992b74e3c7..739dfa8769 100644 --- a/core/continuum-mind/src/chat/chat_data_handle.rs +++ b/core/continuum-mind/src/chat/chat_data_handle.rs @@ -227,8 +227,9 @@ impl ChatModule { let message_id = Uuid::new_v4(); let extra = if relayed { vec![Self::publication_op(message_id, params)?] } else { Vec::new() }; let now_ms = continuum_base::time::EpochMs::now().millis(); - // Ground truth first: the row and its arrival commit together, or the send fails and no - // airc publish is attempted (broadcasting a line the store lacks would diverge). + // Ground truth first: the row (and, when this core relays it, its publication obligation) + // commit together, or the send fails and no airc publish is attempted. Its arrival is + // appended when the line comes back through the inbound seam. let line = super::line_store::PostedLine { message_id, room: airc_core::RoomId::from_uuid(params.room_id), @@ -240,15 +241,9 @@ impl ChatModule { retires_publication: false, }; let content = json!({ "text": params.text, "media": params.media }); - self.commit_line( - &line, - super::line_store::LineWrite::New, - params.reply_to_id, - content, - extra, - ) - .await - .map_err(|e| format!("chat/send: {e}"))?; + self.store_sent_line(&line, params.reply_to_id, content, extra) + .await + .map_err(|e| format!("chat/send: {e}"))?; Ok((message_id, now_ms)) } @@ -418,6 +413,12 @@ pub fn install_line_importer(handle: &tokio::runtime::Handle, module: Arc {} + Ok(count) => tracing::info!(count, "re-published relayed lines left pending by the last stop"), + Err(error) => tracing::warn!(error, "pending relayed lines stay pending until the next start"), + } }); } diff --git a/core/continuum-mind/src/chat/line_store.rs b/core/continuum-mind/src/chat/line_store.rs index d785ca8c20..4b77c2b876 100644 --- a/core/continuum-mind/src/chat/line_store.rs +++ b/core/continuum-mind/src/chat/line_store.rs @@ -39,13 +39,6 @@ pub enum Imported { Duplicate { arrival_seq: u64 }, } -/// Whether a line is new (its id was just minted) or imported (it may already be stored). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(super) enum LineWrite { - New, - Import, -} - /// The chat module the inbound seam imports through, installed at its initialize. static IMPORTER: LateBound = LateBound::new("chat::line_store::importer"); @@ -82,7 +75,7 @@ pub struct ChatStore; impl LineImporter for ChatStore { async fn import(&self, line: PostedLine) -> Result { installed()? - .commit_line(&line, LineWrite::Import, None, json!({ "text": line.text }), Vec::new()) + .commit_line(&line, None, json!({ "text": line.text })) .await } @@ -109,6 +102,51 @@ fn installed() -> Result, String> { .ok_or_else(|| "chat store: the chat module is not installed yet (early boot)".to_string()) } +/// The message row of `line` as one batch operation: the same ChatMessageEntity shape for every +/// writer; WHO spoke is `senderId`, and `metadata.source: "user"` for all citizens alike. +fn message_row( + line: &PostedLine, + operation_type: BatchOperationType, + reply_to: Option, + content: Value, +) -> BatchOperation { + BatchOperation { + operation_type, + collection: CHAT_MESSAGES_COLLECTION.to_string(), + id: Some(line.message_id.to_string()), + data: Some(json!({ + "id": line.message_id.to_string(), + "roomId": line.room.as_uuid().to_string(), + "senderId": line.author.as_uuid().to_string(), + "timestamp": now_iso(line.occurred_at_ms), + "content": content, + "replyToId": reply_to.map(|id| id.to_string()), + "metadata": { "source": "user" }, + "status": "sent", + })), + } +} + +impl ChatModule { + /// Run `operations` as one atomic batch; a refusal is an error naming the store's reason. + async fn run_batch(&self, operations: Vec) -> Result { + let params = json!({ "dbPath": CHAT_DATA_HANDLE, "operations": operations }); + let result = self + .executor()? + .execute_json("data/batch", params) + .await + .map_err(|e| format!("chat line: data/batch failed: {e}"))?; + if result.get("success").and_then(Value::as_bool) != Some(true) { + let detail = result + .get("error") + .and_then(Value::as_str) + .unwrap_or("success=false without an error"); + return Err(format!("chat line: the store refused the line: {detail}")); + } + Ok(result) + } +} + /// Records every imported line and reports each as fresh, in order: the seam's test importer. #[cfg(any(test, feature = "test-fixtures"))] #[derive(Default)] @@ -122,7 +160,16 @@ pub struct RecordingImporter( #[async_trait::async_trait] impl LineImporter for RecordingImporter { async fn import(&self, line: PostedLine) -> Result { + // As the store does: a message id already held is a duplicate at its first arrival. let mut lines = self.0.lock().unwrap_or_else(|p| p.into_inner()); // test fixture: a poisoned lock still holds the lines recorded + if let Some(first) = lines + .iter() + .position(|held| held.message_id == line.message_id) + { + return Ok(Imported::Duplicate { + arrival_seq: first as u64 + 1, + }); + } lines.push(line); Ok(Imported::Fresh { arrival_seq: lines.len() as u64, @@ -130,7 +177,12 @@ impl LineImporter for RecordingImporter { } async fn publication(&self, id: Uuid) -> Result, String> { - Ok(self.2.lock().unwrap_or_else(|p| p.into_inner()).get(&id).cloned()) // test fixture: a poisoned lock still holds the obligations + Ok(self + .2 + .lock() + .unwrap_or_else(|p| p.into_inner()) + .get(&id) + .cloned()) // test fixture: a poisoned lock still holds the obligations } async fn watermark(&self, room: RoomId) -> Result, String> { @@ -175,37 +227,36 @@ impl LineImporter for RecordingImporter { } impl ChatModule { - /// Commit `line`'s message row and its arrival in ONE batch. - pub(super) async fn commit_line( + /// Store a line `chat/send` just minted: its message row, plus `extra` (the publication + /// obligation when this core relays it), in ONE batch. No arrival: arrivals are the inbound + /// seam's alone, appended when the line comes back over airc (Codex, #5691 P2). + pub(super) async fn store_sent_line( &self, line: &PostedLine, - write: LineWrite, reply_to: Option, content: Value, extra: Vec, + ) -> Result<(), String> { + let mut operations = vec![message_row( + line, + BatchOperationType::Create, + reply_to, + content, + )]; + operations.extend(extra); + self.run_batch(operations).await.map(|_| ()) + } + + /// Import a line the inbound seam received: its message row (ensured, so a replay is + /// idempotent) and its arrival in ONE batch, and, for a delegated line, its publication + /// obligation marked retired (kept, so an exact replay after a restart still attributes). + pub(super) async fn commit_line( + &self, + line: &PostedLine, + reply_to: Option, + content: Value, ) -> Result { - let executor = self.executor()?; - // The same ChatMessageEntity shape for every writer; WHO spoke is `senderId`, and - // `metadata.source: "user"` for all citizens alike. - let message = json!({ - "id": line.message_id.to_string(), - "roomId": line.room.as_uuid().to_string(), - "senderId": line.author.as_uuid().to_string(), - "timestamp": now_iso(line.occurred_at_ms), - "content": content, - "replyToId": reply_to.map(|id| id.to_string()), - "metadata": { "source": "user" }, - "status": "sent", - }); - let message_op = BatchOperation { - operation_type: match write { - LineWrite::New => BatchOperationType::Create, - LineWrite::Import => BatchOperationType::Ensure, - }, - collection: CHAT_MESSAGES_COLLECTION.to_string(), - id: Some(line.message_id.to_string()), - data: Some(message), - }; + let message_op = message_row(line, BatchOperationType::Ensure, reply_to, content); let arrival = Arrival::new( line.message_id, line.room, @@ -215,28 +266,19 @@ impl ChatModule { ); let append_op = arrival.append_op().map_err(|e| format!("chat line: {e}"))?; let mut operations = vec![message_op, append_op]; - operations.extend(extra); if line.retires_publication { - // The relayed line came back: its obligation retires with the import, atomically. + // The relayed line came back: its obligation is marked retired with the import, + // atomically. Kept, not deleted, so an exact replay after a restart is recognized. operations.push(BatchOperation { - operation_type: BatchOperationType::Delete, - collection: ::COLLECTION.to_string(), + operation_type: BatchOperationType::Update, + collection: + ::COLLECTION + .to_string(), id: Some(line.message_id.to_string()), - data: None, + data: Some(json!({ "state": super::publication::PublicationState::Retired })), }); } - let params = json!({ "dbPath": CHAT_DATA_HANDLE, "operations": operations }); - let result = executor - .execute_json("data/batch", params) - .await - .map_err(|e| format!("chat line: data/batch failed: {e}"))?; - if result.get("success").and_then(Value::as_bool) != Some(true) { - let detail = result - .get("error") - .and_then(Value::as_str) - .unwrap_or("success=false without an error"); - return Err(format!("chat line: the store refused the line: {detail}")); - } + let result = self.run_batch(operations).await?; let appended = result .get("data") .and_then(|d| d.get(1)) diff --git a/core/continuum-mind/src/chat/publication.rs b/core/continuum-mind/src/chat/publication.rs index d22bd6f924..49efe92a01 100644 --- a/core/continuum-mind/src/chat/publication.rs +++ b/core/continuum-mind/src/chat/publication.rs @@ -63,7 +63,17 @@ pub fn publication_digest( hash.finalize().into() } -/// One line `chat/send` published for its caller and has not yet seen come back. +/// Where a publication stands: published (or about to be) and not yet seen back, or seen back. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PublicationState { + /// Recorded before publishing; a restart re-publishes it until its echo is imported. + Pending, + /// Its echo was imported. Kept, so an exact replay of it after a restart still attributes. + Retired, +} + +/// One line `chat/send` publishes for its caller. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, crate::orm::Entity)] #[serde(rename_all = "camelCase")] #[entity(collection = "chat_publications")] @@ -76,6 +86,7 @@ pub struct PublicationObligation { /// The authenticated transport this core publishes relayed lines as: only it may deliver this line. pub relay: PeerId, pub digest: [u8; 32], + pub state: PublicationState, } /// The transport identity this core publishes relayed lines as (the airc module's scope peer), @@ -123,7 +134,7 @@ pub enum DelegationRefusal { } /// Decide a received line's attribution from its transport author, its header's sender claim, the -/// obligation its message id names (if any) and the digest of the line as received (`None` when it +/// obligation its message id names (if any, pending or retired: a retired one is an exact replay) and the digest of the line as received (`None` when it /// could not be decoded, which matches no publication). Pure. pub fn attribute( transport: PeerId, @@ -187,6 +198,7 @@ impl ChatModule { sender, relay, digest: publication_digest(message_id, room, sender, ¶ms.text, ¶ms.media), + state: PublicationState::Pending, }; let data = serde_json::to_value(&obligation).map_err(|e| format!("publication: {e}"))?; // storage boundary: the adapter's row format Ok(crate::orm::types::BatchOperation { @@ -220,6 +232,75 @@ impl ChatModule { } } + /// Restart recovery (Codex on #5696): an obligation still pending had its line stored but may + /// never have been published (the core stopped between). Each is published again, rebuilt + /// from its stored row; an echo that arrives twice is one line, because the import dedupes by + /// message id and a duplicate is never perceived again. Returns how many were re-published. + pub async fn republish_pending(&self) -> Result { + let query = serde_json::json!({ + "dbPath": super::chat_data_handle::CHAT_DATA_HANDLE, + "collection": ::COLLECTION, + "filter": { "state": { "$eq": "pending" } }, + }); + let result = self + .executor()? + .execute_json("data/query", query) + .await + .map_err(|e| format!("publication: pending query failed: {e}"))?; + let mut republished = 0; + for row in super::chat_module::extract_records_as_data(&result) { + let parsed = serde_json::from_value::(row); // storage boundary: the adapter's row format + let obligation = parsed.map_err(|e| format!("publication: malformed row: {e}"))?; + let Some((params, at_ms)) = self.sent_line(obligation.id).await? else { + continue; // no stored line: nothing to publish (the obligation was written with it, so this is a pruned row) + }; + self.broadcast_envelope(obligation.id, ¶ms, at_ms) + .await?; + republished += 1; + } + Ok(republished) + } + + /// The parameters `chat/send` stored a line with, read back from its row, and its time. + async fn sent_line( + &self, + message: Uuid, + ) -> Result, String> { + let params = serde_json::json!({ + "dbPath": super::chat_data_handle::CHAT_DATA_HANDLE, + "collection": super::types::CHAT_MESSAGES_COLLECTION, + "id": message.to_string(), + }); + let result = self + .executor()? + .execute_json("data/read", params) + .await + .map_err(|e| format!("publication: line read failed: {e}"))?; + let Some(row) = result + .get("data") + .and_then(|d| d.get("data")) + .filter(|_| result.get("success").and_then(serde_json::Value::as_bool) == Some(true)) + else { + return Ok(None); + }; + let parsed = serde_json::from_value::(row.clone()); // storage boundary: the adapter's row format + let stored = parsed.map_err(|e| format!("publication: malformed line: {e}"))?; + let at_ms = chrono::DateTime::parse_from_rfc3339(&stored.timestamp) + .map_err(|e| format!("publication: line time: {e}"))? + .timestamp_millis() + .max(0) as u64; + Ok(Some(( + super::types::ChatSendParams { + room_id: stored.room_id, + sender_id: stored.sender_id, + text: stored.content.text, + reply_to_id: stored.reply_to_id, + media: stored.content.media, + }, + at_ms, + ))) + } + /// The obligation a received line's message id names, if any. pub(super) async fn publication( &self, @@ -264,6 +345,7 @@ mod tests { sender, relay, digest, + state: PublicationState::Pending, } } @@ -340,6 +422,21 @@ mod tests { attribute(relay, named, room, Some(&exact), published), Attribution::Delegated { sender: joel } ); + // what this catches: a genuine line replayed after its echo was imported (a restart before + // the watermark advanced) refused as having no origin (Codex on #5696): a retired + // obligation still proves its exact line, while altered content is still refused. + let retired = PublicationObligation { + state: PublicationState::Retired, + ..exact.clone() + }; + assert_eq!( + attribute(relay, named, room, Some(&retired), published), + Attribution::Delegated { sender: joel } + ); + assert_eq!( + refused(relay, named, room, Some(&retired), Some([9u8; 32])), + Some(DelegationRefusal::AlteredPublication) + ); } // what this catches: a digest that ignores a field a consumer sees, so altered media still @@ -387,3 +484,22 @@ mod tests { ); } } + +/// The stored chat row's fields a re-publish needs, typed. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct StoredLine { + room_id: Uuid, + sender_id: Uuid, + timestamp: String, + content: StoredContent, + #[serde(default)] + reply_to_id: Option, +} + +#[derive(Debug, Deserialize)] +struct StoredContent { + text: String, + #[serde(default)] + media: Vec, +} diff --git a/core/continuum-mind/src/chat/tests/mod.rs b/core/continuum-mind/src/chat/tests/mod.rs index cfbcd4e972..cee6864153 100644 --- a/core/continuum-mind/src/chat/tests/mod.rs +++ b/core/continuum-mind/src/chat/tests/mod.rs @@ -140,12 +140,7 @@ let chat = chat_with_stubs(vec![Arc::new(data)]); let line = imported_line("I see the word LIGHTHOUSE in the room."); let imported = chat - .commit_line( - &line, - crate::chat::line_store::LineWrite::Import, - None, - json!({ "text": line.text }), Vec::new(), - ) + .commit_line(&line, None, json!({ "text": line.text })) .await .expect("the import commits"); assert_eq!( @@ -198,12 +193,7 @@ let chat = chat_with_stubs(vec![Arc::new(data)]); let line = imported_line("already stored by send()"); let imported = chat - .commit_line( - &line, - crate::chat::line_store::LineWrite::Import, - None, - json!({ "text": line.text }), Vec::new(), - ) + .commit_line(&line, None, json!({ "text": line.text })) .await .expect("a duplicate is a committed import"); assert_eq!( @@ -220,12 +210,46 @@ let chat = chat_with_stubs(vec![Arc::new(data)]); let line = imported_line("unconfirmed"); let err = chat - .commit_line(&line, crate::chat::line_store::LineWrite::Import, None, json!({ "text": line.text }), Vec::new()) + .commit_line(&line, None, json!({ "text": line.text })) .await .expect_err("a reply without freshness is malformed"); assert!(err.contains("did not say whether it was fresh"), "named: {err}"); } + // what this catches: a relayed line stored with its publication obligation but never published + // because the core stopped between (Codex on #5696): the restart sweep re-publishes it, rebuilt + // from its stored row, as the same line (its message id and sender). + #[tokio::test] + pub(super) async fn a_pending_publication_is_republished_from_its_stored_row() { + let (message, room, sender) = (Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()); + let obligation = json!({ + "id": message, "room": room, "sender": sender, "relay": Uuid::from_u128(0x7e1a), + "digest": vec![0u8; 32], "state": "pending", + }); + let row = json!({ + "id": message, "roomId": room, "senderId": sender, "timestamp": "2026-11-02T01:00:00Z", + "content": { "text": "left pending by the last stop", "media": [] }, "replyToId": null, + }); + let published: Arc>> = Arc::new(Mutex::new(Vec::new())); + let seen = published.clone(); + let chat = chat_with_stubs(vec![ + Arc::new(StubDataModule::new(move |cmd, _p| match cmd { + "data/query" => Ok(json!({ "success": true, "data": [{ "data": obligation.clone() }] })), + "data/read" => Ok(json!({ "success": true, "data": { "data": row.clone() } })), + other => panic!("the sweep only reads: {other}"), + })), + Arc::new(StubAircModule::with(move |p| { + seen.lock().unwrap().push(p); + Ok(airc_ok_response("evt-republished")) + })), + ]); + assert_eq!(chat.republish_pending().await.expect("the sweep runs"), 1); + let calls = published.lock().unwrap(); + assert_eq!(calls.len(), 1, "re-published once"); + assert_eq!(calls[0]["envelope"]["eventId"], message.to_string(), "the same line, by its message id"); + assert_eq!(calls[0]["envelope"]["sourceId"], sender.to_string(), "for the same sender"); + } + // what this catches: a store refusal swallowed as a calm skip. The import is awaited by the // inbound seam so the attach watermark never passes a line the store lacks; a refusal must // therefore be an error the seam sees, never a quiet probe. @@ -237,12 +261,7 @@ let chat = chat_with_stubs(vec![Arc::new(data)]); let line = imported_line("lost?"); let err = chat - .commit_line( - &line, - crate::chat::line_store::LineWrite::Import, - None, - json!({ "text": line.text }), Vec::new(), - ) + .commit_line(&line, None, json!({ "text": line.text })) .await .expect_err("a refusal is an error"); assert!(err.contains("disk full"), "the cause is named: {err}"); @@ -620,7 +639,7 @@ assert_eq!(cmd, "data/batch", "happy path only writes (no other data ops)"); // The envelope leg relays for the caller: the publication obligation commits in the // SAME batch as the row and its arrival (#5696), never a separate write. - assert_eq!(p["operations"][2]["collection"], "chat_publications", "obligation in the line's batch: {p}"); + assert_eq!(p["operations"][1]["collection"], "chat_publications", "obligation in the line's batch: {p}"); Ok(batch_ok()) })), Arc::new(StubAircModule::ok(airc_ok_response("evt-happy-001"))), From 4659c6df24d39a2032c20036d70c3dee3b0524cc Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 21:12:57 -0600 Subject: [PATCH 6/7] Chat has one door into its store; recovery runs on every attach; restart proven on the real store (Codex's #5696 review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex's three blockers on a2fb391e8: 1. Recovery ran once at boot, so a relay not ready then stranded obligations until the next start. It now runs from the room's attach owner on every (re)attach (LineImporter::recover_publications, per room): an error ends that attach and the supervisor's backoff retries it, no new task or poll. A re-publish the relay refuses is an error, never counted as recovered. 2. A refused data/query read as zero rows, and a failed data/read as a pruned line. Every chat store call now goes through ONE door (chat/store.rs: ChatModule::store / query_rows / row / run_batch): it sets the chat handle and turns a refusal into an error. Reads by id are id queries, so None means the store answered and has no row. The watermark read had the same flaw (a refused read looked like a room never imported) and is migrated with it. 3. Real-store validators (tests/restart.rs, the data module over the process home, reopened by a second executor): a refused publish recovers in the same process; a committed line + Pending obligation survives a reopen and publishes; a committed import + Retired obligation replays after a reopen as one line, the exact line is still Delegated, an altered one is refused, and a retired publication is not re-published. Found by the real-store tests: nothing created the chat module's own tables (chat_arrivals, the import watermark, publication obligations) — opening a store adds only the TS entities' indexes — so canary's first import on a live node would be refused with "no such table". The door ensures the chat collections once per executor (ChatSlot, shared by every module built over it) before its first call; a failure retries on the next. Compressed: seven hand-built chat store calls (poll's two query_rows copies, the anchor lookup, drain's two queries, the watermark read+write, the obligation read+write, the line batch) each with its own success check (or none) now go through the door; extract_first_record_field deleted. Tests (M5, serving down 03:07-03:12Z): mind chat 54 (3 real-store restart tests); core inbound_attach + data_wiring + airc 125; core check --tests clean; ratchets exit 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../continuum-core/src/airc/inbound_attach.rs | 15 ++ .../src/chat/chat_data_handle.rs | 62 +++--- core/continuum-mind/src/chat/chat_module.rs | 31 --- core/continuum-mind/src/chat/commands/mod.rs | 3 +- core/continuum-mind/src/chat/commands/poll.rs | 3 +- core/continuum-mind/src/chat/commands/send.rs | 5 +- core/continuum-mind/src/chat/drain.rs | 46 ++-- .../src/chat/import_watermark.rs | 31 +-- core/continuum-mind/src/chat/keyset_page.rs | 27 +-- core/continuum-mind/src/chat/line_store.rs | 39 ++-- core/continuum-mind/src/chat/mod.rs | 5 +- core/continuum-mind/src/chat/publication.rs | 101 +++------ core/continuum-mind/src/chat/store.rs | 154 +++++++++++++ core/continuum-mind/src/chat/tests/mod.rs | 40 +--- core/continuum-mind/src/chat/tests/part_2.rs | 4 +- core/continuum-mind/src/chat/tests/restart.rs | 204 ++++++++++++++++++ 16 files changed, 501 insertions(+), 269 deletions(-) create mode 100644 core/continuum-mind/src/chat/store.rs create mode 100644 core/continuum-mind/src/chat/tests/restart.rs diff --git a/core/continuum-core/src/airc/inbound_attach.rs b/core/continuum-core/src/airc/inbound_attach.rs index 4fa0ce27ca..20548bb34b 100644 --- a/core/continuum-core/src/airc/inbound_attach.rs +++ b/core/continuum-core/src/airc/inbound_attach.rs @@ -261,6 +261,21 @@ pub async fn run_daemon_attach( .attach(request) .await .map_err(|error| format!("failed to attach to airc daemon: {error}"))?; + // The room's transport is ready: publish again what this core relayed into it and has not seen + // back (#5696). This attach owns the recovery; an error ends it, and the supervisor's backoff + // retries, so a publish refused at boot recovers without another process start. + let recovered = lines + .recover_publications(channel) + .await + .map_err(|e| format!("pending publications not recovered; re-attaching to retry: {e}"))?; + if recovered > 0 { + continuum_base::probe!( + class = "airc.attach.publications_recovered", + room = %channel.as_uuid(), + recovered = recovered as u64, + "re-published lines this core relayed and had not seen back" + ); + } // WATERMARK DISCIPLINE (#261, both PR #2057 review findings): the attach // NEVER pre-persists the room tip. The old tip-probe persisted a cursor diff --git a/core/continuum-mind/src/chat/chat_data_handle.rs b/core/continuum-mind/src/chat/chat_data_handle.rs index 739dfa8769..bc005c44fd 100644 --- a/core/continuum-mind/src/chat/chat_data_handle.rs +++ b/core/continuum-mind/src/chat/chat_data_handle.rs @@ -22,7 +22,7 @@ pub struct ChatModule { /// via `install_executor` (the same path every other module uses). /// `with_executor` lets tests inject a custom chain without /// installing into the global registry. - pub(super) executor_slot: Arc>, + pub(super) executor_slot: Arc, } /// Which wire leg a send takes after the data row is written. ONE leg per @@ -42,7 +42,7 @@ impl ChatModule { /// `start_server` via `ServiceModule::install_executor` (task #224). pub fn new() -> Self { Self { - executor_slot: Arc::new(LateBound::new("chat::executor")), + executor_slot: Arc::new(ChatSlot::new()), } } @@ -52,7 +52,7 @@ impl ChatModule { /// real cross-module call path without going through `start_server`. #[cfg(test)] pub fn with_executor(executor: Arc) -> Self { - let executor_slot = Arc::new(LateBound::new("chat::executor")); + let executor_slot = Arc::new(ChatSlot::new()); executor_slot.install(executor); Self { executor_slot } } @@ -66,7 +66,7 @@ impl ChatModule { /// the command surface and the module's own tests. The slot is an /// `Arc`, so this is a pointer clone, and it stays the SAME slot /// `start_server` installs the executor into. - pub(crate) fn from_slot(executor_slot: Arc>) -> Self { + pub(crate) fn from_slot(executor_slot: Arc) -> Self { Self { executor_slot } } @@ -94,23 +94,24 @@ impl ChatModule { /// filter on id). Fails loud when the anchor doesn't exist — silently /// returning unfiltered history would hand the caller the wrong page. pub(super) async fn anchor_timestamp(&self, anchor_id: Uuid) -> Result { - let anchor_query = json!({ - "dbPath": CHAT_DATA_HANDLE, - "collection": CHAT_MESSAGES_COLLECTION, - "filter": { "id": { "$eq": anchor_id.to_string() } }, - "limit": 1, - }); - - let anchor_result = self - .executor()? - .execute_json("data/query", anchor_query) + let anchor = self + .query_rows( + CHAT_MESSAGES_COLLECTION, + json!({ "id": { "$eq": anchor_id.to_string() } }), + None, + Some(1), + ) .await .map_err(|e| format!("chat/poll: anchor lookup failed: {e}"))?; - - extract_first_record_field(&anchor_result, "timestamp").ok_or_else(|| { - // Matches the TS impl's "Message not found" path. - format!("chat/poll: anchor message not found: {anchor_id}") - }) + anchor + .first() + .and_then(|row| row.get("timestamp")) + .and_then(Value::as_str) + .map(str::to_string) + .ok_or_else(|| { + // Matches the TS impl's "Message not found" path. + format!("chat/poll: anchor message not found: {anchor_id}") + }) } /// `chat/poll` — return recent messages, optionally filtered by @@ -139,7 +140,10 @@ impl ChatModule { (None, None) => None, }; let mut messages = match cursor { - Some((anchor, direction)) => self.keyset_page(params.room_id, anchor, direction, limit).await?, + Some((anchor, direction)) => { + self.keyset_page(params.room_id, anchor, direction, limit) + .await? + } None => self.newest_page(params.room_id, limit).await?, }; chronological(&mut messages); @@ -223,9 +227,17 @@ impl ChatModule { /// minted message id and the timestamp the row carries. /// `relayed`: this core will publish the line for its caller (the envelope leg), so its /// publication obligation commits in the same batch as the row and arrival. - pub(super) async fn persist(&self, params: &ChatSendParams, relayed: bool) -> Result<(Uuid, u64), String> { + pub(super) async fn persist( + &self, + params: &ChatSendParams, + relayed: bool, + ) -> Result<(Uuid, u64), String> { let message_id = Uuid::new_v4(); - let extra = if relayed { vec![Self::publication_op(message_id, params)?] } else { Vec::new() }; + let extra = if relayed { + vec![Self::publication_op(message_id, params)?] + } else { + Vec::new() + }; let now_ms = continuum_base::time::EpochMs::now().millis(); // Ground truth first: the row (and, when this core relays it, its publication obligation) // commit together, or the send fails and no airc publish is attempted. Its arrival is @@ -413,12 +425,6 @@ pub fn install_line_importer(handle: &tokio::runtime::Handle, module: Arc {} - Ok(count) => tracing::info!(count, "re-published relayed lines left pending by the last stop"), - Err(error) => tracing::warn!(error, "pending relayed lines stay pending until the next start"), - } }); } diff --git a/core/continuum-mind/src/chat/chat_module.rs b/core/continuum-mind/src/chat/chat_module.rs index b8c78a6b69..c86b31ee54 100644 --- a/core/continuum-mind/src/chat/chat_module.rs +++ b/core/continuum-mind/src/chat/chat_module.rs @@ -108,34 +108,3 @@ impl ServiceModule for ChatModule { } // ── helpers ────────────────────────────────────────────────────────── -/// Extract a single field from the first record in a data-module -/// `data/query` response. The data module returns -/// `{ success, data: [{ id, data: {...} }] }`, where each entry's -/// `data` is the entity payload. Returns the field as a JSON string -/// (which is the shape the TS impl threads downstream) or `None` if -/// the response shape doesn't have it. -pub(super) fn extract_first_record_field(query_result: &Value, field: &str) -> Option { - let records = query_result.get("data")?.as_array()?; - let first = records.first()?; - let data = first.get("data")?; - let value = data.get(field)?; - match value { - Value::String(s) => Some(s.clone()), - other => Some(other.to_string()), - } -} - -/// Extract message payloads from a data-module `data/query` response. -/// The response shape is `{ success, data: [{ id, data: }] }`; -/// we lift each `entity` out of its `DataRecord` envelope. -pub(super) fn extract_records_as_data(query_result: &Value) -> Vec { - query_result - .get("data") - .and_then(|v| v.as_array()) - .map(|arr| { - arr.iter() - .filter_map(|record| record.get("data").cloned()) - .collect() - }) - .unwrap_or_default() -} diff --git a/core/continuum-mind/src/chat/commands/mod.rs b/core/continuum-mind/src/chat/commands/mod.rs index c5443c0e5e..9b4e02e731 100644 --- a/core/continuum-mind/src/chat/commands/mod.rs +++ b/core/continuum-mind/src/chat/commands/mod.rs @@ -14,7 +14,6 @@ use std::sync::Arc; -use crate::runtime::{CommandExecutor, LateBound}; use crate::sdk_codegen::DynCommand; pub mod history; @@ -26,7 +25,7 @@ use send::ChatSend; /// The `chat/*` command objects over the module's shared late-bound executor slot. /// Called from [`ChatModule::commands`](crate::chat::ChatModule::commands). -pub fn command_objects(executor_slot: Arc>) -> Vec> { +pub fn command_objects(executor_slot: Arc) -> Vec> { vec![ Arc::new(ChatPoll { executor_slot: executor_slot.clone(), diff --git a/core/continuum-mind/src/chat/commands/poll.rs b/core/continuum-mind/src/chat/commands/poll.rs index 180378fa1f..a3d5f108ca 100644 --- a/core/continuum-mind/src/chat/commands/poll.rs +++ b/core/continuum-mind/src/chat/commands/poll.rs @@ -13,7 +13,6 @@ use std::sync::Arc; use crate::chat::types::{ChatPollParams, ChatPollResult}; use crate::chat::ChatModule; -use crate::runtime::{CommandExecutor, LateBound}; use crate::sdk_codegen::CommandError; crate::action_command! { @@ -21,7 +20,7 @@ crate::action_command! { /// the room (`roomId`, optional: omit for latest across all rooms) and how many /// messages to retrieve (`limit`, default 50). Pass `afterMessageId` to page /// forward and return only messages newer than one you've already seen. - pub struct ChatPoll { executor_slot: Arc> } + pub struct ChatPoll { executor_slot: Arc } name: "chat/poll", access: AiSafe, params: ChatPollParams, diff --git a/core/continuum-mind/src/chat/commands/send.rs b/core/continuum-mind/src/chat/commands/send.rs index 36e4d045c4..0eccfbf47a 100644 --- a/core/continuum-mind/src/chat/commands/send.rs +++ b/core/continuum-mind/src/chat/commands/send.rs @@ -18,7 +18,6 @@ use uuid::Uuid; use crate::chat::types::{ChatSendParams, ChatSendResult}; use crate::chat::ChatModule; -use crate::runtime::{CommandExecutor, LateBound}; use crate::sdk_codegen::CommandError; /// The caller-facing wire shape — `senderId` is OPTIONAL here and resolved by @@ -55,7 +54,7 @@ crate::action_command! { /// (personas act as themselves; the operator's CLI speaks as the operator /// self-peer). This is a persona's primary voice: it stores the message locally /// AND broadcasts it over airc. - pub struct ChatSend { executor_slot: Arc> } + pub struct ChatSend { executor_slot: Arc } name: "chat/send", access: AiSafe, params: ChatSendWireParams, @@ -241,7 +240,7 @@ mod tests { // anyone but itself is refused before anything is stored or published. #[tokio::test] async fn an_authenticated_caller_cannot_speak_as_someone_else() { - let command = ChatSend { executor_slot: Arc::new(LateBound::new("test::chat_send")) }; + let command = ChatSend { executor_slot: Arc::new(crate::chat::ChatSlot::new()) }; let caller = crate::identity::PeerId::from_uuid(Uuid::new_v4()); let ctx = crate::sdk_codegen::Ctx { caller: Some(crate::routing::CallerIdentity::airc(caller)), diff --git a/core/continuum-mind/src/chat/drain.rs b/core/continuum-mind/src/chat/drain.rs index 0d81c903bf..89971c899a 100644 --- a/core/continuum-mind/src/chat/drain.rs +++ b/core/continuum-mind/src/chat/drain.rs @@ -14,8 +14,7 @@ use airc_core::{PeerId, RoomId}; use serde_json::{json, Value}; use super::arrival::Arrival; -use super::chat_data_handle::{ChatModule, CHAT_DATA_HANDLE}; -use super::chat_module::extract_records_as_data; +use super::chat_data_handle::ChatModule; /// Why history between two sequences cannot be perceived. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -101,36 +100,21 @@ impl ChatModule { rooms: &[RoomId], intake: usize, ) -> Result<(StoreFacts, Vec), String> { - let executor = self.executor()?; let collection = ::COLLECTION; let rooms_typed = rooms; let rooms: Vec = rooms.iter().map(|r| r.as_uuid().to_string()).collect(); - let page = json!({ - "dbPath": CHAT_DATA_HANDLE, - "collection": collection, - "filter": { "arrivalSeq": { "$gt": cursor.through }, "room": { "$in": rooms } }, - "sort": [{ "field": "arrivalSeq", "direction": "asc" }], - "limit": intake, - }); - let floor = json!({ - "dbPath": CHAT_DATA_HANDLE, - "collection": collection, - "filter": {}, - "sort": [{ "field": "arrivalSeq", "direction": "asc" }], - "limit": 1, - }); - let rows = executor - .execute_json("data/query", page) - .await - .map_err(|e| format!("drain: page query failed: {e}"))?; - let oldest = executor - .execute_json("data/query", floor) - .await - .map_err(|e| format!("drain: floor query failed: {e}"))?; - let arrivals = decode(extract_records_as_data(&rows))?; - let retained_floor = decode(extract_records_as_data(&oldest))? - .first() - .map(|a| a.arrival_seq); + let by_sequence = || Some(json!([{ "field": "arrivalSeq", "direction": "asc" }])); + let page = json!({ "arrivalSeq": { "$gt": cursor.through }, "room": { "$in": rooms } }); + let arrivals = decode( + self.query_rows(collection, page, by_sequence(), Some(intake)) + .await?, + )?; + let retained_floor = decode( + self.query_rows(collection, json!({}), by_sequence(), Some(1)) + .await?, + )? + .first() + .map(|a| a.arrival_seq); let mut unvouched_import = false; for room in rooms_typed { if let Some(imported) = self.import_watermark(*room).await? { @@ -152,7 +136,9 @@ impl ChatModule { fn decode(rows: Vec) -> Result, String> { let decode_row = |row: Value| serde_json::from_value::(row); // storage boundary: the adapter's row format - rows.into_iter().map(|row| decode_row(row).map_err(|e| format!("drain: malformed arrival row: {e}"))).collect() + rows.into_iter() + .map(|row| decode_row(row).map_err(|e| format!("drain: malformed arrival row: {e}"))) + .collect() } #[cfg(test)] diff --git a/core/continuum-mind/src/chat/import_watermark.rs b/core/continuum-mind/src/chat/import_watermark.rs index e416dcb165..ed895223c1 100644 --- a/core/continuum-mind/src/chat/import_watermark.rs +++ b/core/continuum-mind/src/chat/import_watermark.rs @@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use uuid::Uuid; -use super::chat_data_handle::{ChatModule, CHAT_DATA_HANDLE}; +use super::chat_data_handle::ChatModule; use crate::orm::types::{BatchOperation, BatchOperationType}; /// A position in a room's airc transcript (the daemon's cursor), typed. @@ -63,20 +63,12 @@ impl ChatModule { &self, room: RoomId, ) -> Result, String> { - let executor = self.executor()?; - let params = json!({ "dbPath": CHAT_DATA_HANDLE, "collection": COLLECTION, "id": room.as_uuid().to_string() }); - let result = executor - .execute_json("data/read", params) - .await - .map_err(|e| format!("import watermark: data/read failed: {e}"))?; - if result.get("success").and_then(Value::as_bool) != Some(true) { - return Ok(None); // no row: the store has never imported this room - } - let Some(data) = result.get("data").and_then(|d| d.get("data")).cloned() else { - return Ok(None); + let Some(row) = self + .row::(COLLECTION, room.as_uuid()) + .await? + else { + return Ok(None); // the store confirms no row: it has never imported this room }; - let row: ImportWatermarkRow = serde_json::from_value(data) - .map_err(|e| format!("import watermark: malformed row: {e}"))?; // storage boundary: the adapter's row format Ok(Some(ImportedThrough { position: ImportWatermark { epoch: row.epoch, @@ -131,7 +123,6 @@ impl ChatModule { room: RoomId, writes: Vec<(BatchOperationType, Value)>, ) -> Result<(), String> { - let executor = self.executor()?; let operations: Vec = writes .into_iter() .map(|(operation_type, data)| BatchOperation { @@ -141,15 +132,7 @@ impl ChatModule { data: Some(data), }) .collect(); - let params = json!({ "dbPath": CHAT_DATA_HANDLE, "operations": operations }); - let result = executor - .execute_json("data/batch", params) - .await - .map_err(|e| format!("import watermark: data/batch failed: {e}"))?; - match result.get("success").and_then(Value::as_bool) { - Some(true) => Ok(()), - _ => Err(format!("import watermark: the store refused it: {result}")), - } + self.run_batch(operations).await.map(drop) } } diff --git a/core/continuum-mind/src/chat/keyset_page.rs b/core/continuum-mind/src/chat/keyset_page.rs index 55406f1111..a524cb0296 100644 --- a/core/continuum-mind/src/chat/keyset_page.rs +++ b/core/continuum-mind/src/chat/keyset_page.rs @@ -53,7 +53,7 @@ impl ChatModule { tie.insert("timestamp".to_string(), json!({ "$eq": anchor_timestamp })); tie.insert("id".to_string(), operator(strictly, json!(anchor.to_string()))); let mut rows = self - .query_rows(tie, json!([{ "field": "id", "direction": sort }]), limit) + .query_rows(CHAT_MESSAGES_COLLECTION, Value::Object(tie), Some(json!([{ "field": "id", "direction": sort }])), Some(limit)) .await?; if rows.len() < limit { @@ -63,7 +63,7 @@ impl ChatModule { { "field": "timestamp", "direction": sort }, { "field": "id", "direction": sort }, ]); - rows.extend(self.query_rows(past, order, limit - rows.len()).await?); + rows.extend(self.query_rows(CHAT_MESSAGES_COLLECTION, Value::Object(past), Some(order), Some(limit - rows.len())).await?); } Ok(rows) } @@ -74,28 +74,7 @@ impl ChatModule { { "field": "timestamp", "direction": "desc" }, { "field": "id", "direction": "desc" }, ]); - self.query_rows(room_filter(room_id), order, limit).await - } - - async fn query_rows( - &self, - filter: serde_json::Map, - sort: Value, - limit: usize, - ) -> Result, String> { - let query = json!({ - "dbPath": CHAT_DATA_HANDLE, - "collection": CHAT_MESSAGES_COLLECTION, - "filter": filter, - "sort": sort, - "limit": limit, - }); - let result = self - .executor()? - .execute_json("data/query", query) - .await - .map_err(|e| format!("chat/poll: query failed: {e}"))?; - Ok(extract_records_as_data(&result)) + self.query_rows(CHAT_MESSAGES_COLLECTION, Value::Object(room_filter(room_id)), Some(order), Some(limit)).await } } diff --git a/core/continuum-mind/src/chat/line_store.rs b/core/continuum-mind/src/chat/line_store.rs index 4b77c2b876..f3ffb02263 100644 --- a/core/continuum-mind/src/chat/line_store.rs +++ b/core/continuum-mind/src/chat/line_store.rs @@ -8,7 +8,7 @@ use serde_json::{json, Value}; use uuid::Uuid; use super::arrival::{Arrival, ArrivalKind}; -use super::chat_data_handle::{now_iso, ChatModule, CHAT_DATA_HANDLE}; +use super::chat_data_handle::{now_iso, ChatModule}; use super::import_watermark::{ImportHistory, ImportWatermark, ImportedThrough}; use super::publication::PublicationObligation; use super::types::CHAT_MESSAGES_COLLECTION; @@ -54,6 +54,11 @@ pub trait LineImporter: Send + Sync { /// the store has not committed. async fn import(&self, line: PostedLine) -> Result; + /// Publish again the lines this core relayed into `room` and has not seen back (pending + /// obligations): run by the room's attach owner on every (re)attach, so a refused publish is + /// retried with the attach's backoff, never left for the next process start. + async fn recover_publications(&self, room: RoomId) -> Result; + /// The publication obligation `id` names, if this core published that line for a caller. async fn publication(&self, id: Uuid) -> Result, String>; @@ -79,6 +84,10 @@ impl LineImporter for ChatStore { .await } + async fn recover_publications(&self, room: RoomId) -> Result { + installed()?.republish_pending(room).await + } + async fn publication(&self, id: Uuid) -> Result, String> { installed()?.publication(id).await } @@ -127,26 +136,6 @@ fn message_row( } } -impl ChatModule { - /// Run `operations` as one atomic batch; a refusal is an error naming the store's reason. - async fn run_batch(&self, operations: Vec) -> Result { - let params = json!({ "dbPath": CHAT_DATA_HANDLE, "operations": operations }); - let result = self - .executor()? - .execute_json("data/batch", params) - .await - .map_err(|e| format!("chat line: data/batch failed: {e}"))?; - if result.get("success").and_then(Value::as_bool) != Some(true) { - let detail = result - .get("error") - .and_then(Value::as_str) - .unwrap_or("success=false without an error"); - return Err(format!("chat line: the store refused the line: {detail}")); - } - Ok(result) - } -} - /// Records every imported line and reports each as fresh, in order: the seam's test importer. #[cfg(any(test, feature = "test-fixtures"))] #[derive(Default)] @@ -176,6 +165,10 @@ impl LineImporter for RecordingImporter { }) } + async fn recover_publications(&self, _room: RoomId) -> Result { + Ok(0) + } + async fn publication(&self, id: Uuid) -> Result, String> { Ok(self .2 @@ -308,6 +301,10 @@ impl LineImporter for RefusingImporter { Err("test: the store refused the line".to_string()) } + async fn recover_publications(&self, _room: RoomId) -> Result { + Err("test: the relay refused the publish".to_string()) + } + async fn publication(&self, _id: Uuid) -> Result, String> { Err("test: the store cannot read".to_string()) } diff --git a/core/continuum-mind/src/chat/mod.rs b/core/continuum-mind/src/chat/mod.rs index 3eb72a8e13..fa3b3c2dae 100644 --- a/core/continuum-mind/src/chat/mod.rs +++ b/core/continuum-mind/src/chat/mod.rs @@ -47,7 +47,7 @@ use async_trait::async_trait; use serde_json::{json, Value}; use uuid::Uuid; -use crate::runtime::{command_executor::CommandExecutor, CommandResult, LateBound, ModuleConfig, ModulePriority, ServiceModule}; +use crate::runtime::{command_executor::CommandExecutor, CommandResult, ModuleConfig, ModulePriority, ServiceModule}; use crate::sdk_codegen::DynCommand; pub mod types; @@ -68,7 +68,8 @@ pub mod orm_entities; mod chat_data_handle; pub use chat_data_handle::*; mod chat_module; -use chat_module::*; +mod store; +pub use store::ChatSlot; mod keyset_page; pub mod commands; use keyset_page::{chronological, PageDirection}; diff --git a/core/continuum-mind/src/chat/publication.rs b/core/continuum-mind/src/chat/publication.rs index 49efe92a01..7797648fa7 100644 --- a/core/continuum-mind/src/chat/publication.rs +++ b/core/continuum-mind/src/chat/publication.rs @@ -218,73 +218,56 @@ impl ChatModule { params: &super::types::ChatSendParams, ) -> Result<(), String> { let op = Self::publication_op(message_id, params)?; - let params = serde_json::json!({ "dbPath": super::chat_data_handle::CHAT_DATA_HANDLE, "operations": [op] }); - let result = self - .executor()? - .execute_json("data/batch", params) - .await - .map_err(|e| format!("publication: data/batch failed: {e}"))?; - match result.get("success").and_then(serde_json::Value::as_bool) { - Some(true) => Ok(()), - _ => Err(format!( - "publication: the store refused the obligation: {result}" - )), - } + self.run_batch(vec![op]).await.map(drop) } - /// Restart recovery (Codex on #5696): an obligation still pending had its line stored but may - /// never have been published (the core stopped between). Each is published again, rebuilt - /// from its stored row; an echo that arrives twice is one line, because the import dedupes by - /// message id and a duplicate is never perceived again. Returns how many were re-published. - pub async fn republish_pending(&self) -> Result { - let query = serde_json::json!({ - "dbPath": super::chat_data_handle::CHAT_DATA_HANDLE, - "collection": ::COLLECTION, - "filter": { "state": { "$eq": "pending" } }, - }); - let result = self - .executor()? - .execute_json("data/query", query) - .await - .map_err(|e| format!("publication: pending query failed: {e}"))?; + /// Publication recovery for `room` (Codex on #5696): an obligation still pending had its line + /// stored but may never have been published (the core stopped between, or the relay refused). + /// Each is published again, rebuilt from its stored row; an echo that arrives twice is one line, + /// because the import dedupes by message id and a duplicate is never perceived again. Run by the + /// room's attach owner on every (re)attach; an error ends that attach and its backoff retries it. + /// Returns how many were re-published. + pub async fn republish_pending(&self, room: RoomId) -> Result { + let pending = self + .query_rows(::COLLECTION, serde_json::json!({ "state": { "$eq": "pending" }, "room": { "$eq": room.as_uuid().to_string() } }), None, None) + .await?; let mut republished = 0; - for row in super::chat_module::extract_records_as_data(&result) { + for row in pending { let parsed = serde_json::from_value::(row); // storage boundary: the adapter's row format let obligation = parsed.map_err(|e| format!("publication: malformed row: {e}"))?; + // A confirmed-absent line (never stored, or pruned) has nothing to publish; a failed + // read is an error, never mistaken for absence. let Some((params, at_ms)) = self.sent_line(obligation.id).await? else { - continue; // no stored line: nothing to publish (the obligation was written with it, so this is a pruned row) + continue; }; - self.broadcast_envelope(obligation.id, ¶ms, at_ms) + // `broadcast_envelope` reports a refused publish as a warning (chat/send's partial + // success); for recovery a line not published is a failure, never "recovered". + let sent = self + .broadcast_envelope(obligation.id, ¶ms, at_ms) .await?; + if let Some(warning) = sent.warning { + return Err(format!( + "publication: line {} not re-published: {warning}", + obligation.id + )); + } republished += 1; } Ok(republished) } - /// The parameters `chat/send` stored a line with, read back from its row, and its time. + /// The parameters `chat/send` stored a line with, read back from its row, and its time; `None` + /// only when the store confirms there is no such row. async fn sent_line( &self, message: Uuid, ) -> Result, String> { - let params = serde_json::json!({ - "dbPath": super::chat_data_handle::CHAT_DATA_HANDLE, - "collection": super::types::CHAT_MESSAGES_COLLECTION, - "id": message.to_string(), - }); - let result = self - .executor()? - .execute_json("data/read", params) - .await - .map_err(|e| format!("publication: line read failed: {e}"))?; - let Some(row) = result - .get("data") - .and_then(|d| d.get("data")) - .filter(|_| result.get("success").and_then(serde_json::Value::as_bool) == Some(true)) + let Some(stored) = self + .row::(super::types::CHAT_MESSAGES_COLLECTION, message) + .await? else { return Ok(None); }; - let parsed = serde_json::from_value::(row.clone()); // storage boundary: the adapter's row format - let stored = parsed.map_err(|e| format!("publication: malformed line: {e}"))?; let at_ms = chrono::DateTime::parse_from_rfc3339(&stored.timestamp) .map_err(|e| format!("publication: line time: {e}"))? .timestamp_millis() @@ -306,25 +289,11 @@ impl ChatModule { &self, id: Uuid, ) -> Result, String> { - let params = serde_json::json!({ - "dbPath": super::chat_data_handle::CHAT_DATA_HANDLE, - "collection": ::COLLECTION, - "id": id.to_string(), - }); - let result = self - .executor()? - .execute_json("data/read", params) - .await - .map_err(|e| format!("publication: data/read failed: {e}"))?; - if result.get("success").and_then(serde_json::Value::as_bool) != Some(true) { - return Ok(None); - } - let Some(data) = result.get("data").and_then(|d| d.get("data")).cloned() else { - return Ok(None); - }; - let row = serde_json::from_value(data); // storage boundary: the adapter's row format - row.map(Some) - .map_err(|e| format!("publication: malformed row: {e}")) + self.row( + ::COLLECTION, + id, + ) + .await } } diff --git a/core/continuum-mind/src/chat/store.rs b/core/continuum-mind/src/chat/store.rs new file mode 100644 index 0000000000..7f35f00f78 --- /dev/null +++ b/core/continuum-mind/src/chat/store.rs @@ -0,0 +1,154 @@ +//! The chat store's one door (#5696): every read and write of the chat handle goes through +//! [`ChatModule::store`]. It ensures the chat module's own collections before the first call +//! (nothing else creates them: opening a store adds only the TS-declared entities' indexes), sets +//! the chat handle, and turns a refusal into an error, so absence is only ever an empty answer from +//! a store that succeeded, never a failed read mistaken for "no row". + +use super::chat_data_handle::{ChatModule, CHAT_DATA_HANDLE}; +use super::orm_entities::CHAT_ORM_COLLECTIONS; +use crate::orm::types::BatchOperation; +use crate::runtime::{command_executor::CommandExecutor, LateBound}; +use serde_json::{json, Value}; +use std::sync::Arc; +use uuid::Uuid; + +/// What every chat module built over one executor shares: the late-bound executor, and whether its +/// store's chat collections exist yet (ensured once, on first use; a failure retries on the next). +pub struct ChatSlot { + executor: LateBound, + collections_ready: tokio::sync::OnceCell<()>, +} + +impl ChatSlot { + pub fn new() -> Self { + Self { + executor: LateBound::new("chat::executor"), + collections_ready: tokio::sync::OnceCell::new(), + } + } + + pub fn install(&self, executor: Arc) { + self.executor.install(executor); + } + + pub fn cloned(&self) -> Option> { + self.executor.cloned() + } +} + +impl Default for ChatSlot { + fn default() -> Self { + Self::new() + } +} + +impl ChatModule { + /// Run a `data/*` command against the chat handle: the module's ONE way into its store. + pub(super) async fn store(&self, command: &str, mut params: Value) -> Result { + let executor = self.executor()?; + self.executor_slot + .collections_ready + .get_or_try_init(|| ensure_chat_collections(&executor)) + .await?; + params["dbPath"] = json!(CHAT_DATA_HANDLE); + let result = executor + .execute_json(command, params) + .await + .map_err(|e| format!("chat store: {command} failed: {e}"))?; + match refusal(command, &result) { + Some(refused) => Err(refused), + None => Ok(result), + } + } + + /// The rows of `collection` matching `filter`, optionally sorted and limited. + pub(super) async fn query_rows( + &self, + collection: &str, + filter: Value, + sort: Option, + limit: Option, + ) -> Result, String> { + let mut query = json!({ "collection": collection, "filter": filter }); + if let Some(sort) = sort { + query["sort"] = sort; + } + if let Some(limit) = limit { + query["limit"] = json!(limit); + } + Ok(extract_records_as_data( + &self.store("data/query", query).await?, + )) + } + + /// The row `id` names in `collection`, `None` only when the store confirms there is none. + pub(super) async fn row( + &self, + collection: &str, + id: Uuid, + ) -> Result, String> { + let rows = self + .query_rows( + collection, + json!({ "id": { "$eq": id.to_string() } }), + None, + Some(1), + ) + .await?; + let Some(row) = rows.into_iter().next() else { + return Ok(None); + }; + let parsed = serde_json::from_value(row); // storage boundary: the adapter's row format + parsed + .map(Some) + .map_err(|e| format!("chat store: malformed {collection} row {id}: {e}")) + } + + /// Run `operations` as one atomic batch. + pub(super) async fn run_batch(&self, operations: Vec) -> Result { + self.store("data/batch", json!({ "operations": operations })) + .await + } +} + +/// Create the chat module's own collections with their declared indexes (the arrival's unique +/// sequence and message id among them). Idempotent. +async fn ensure_chat_collections(executor: &Arc) -> Result<(), String> { + for collection in CHAT_ORM_COLLECTIONS { + let params = json!({ "collection": collection, "dbPath": CHAT_DATA_HANDLE }); + let result = executor + .execute_json("data/ensure-schema", params) + .await + .map_err(|e| format!("chat store: ensuring {collection} failed: {e}"))?; + if let Some(refused) = refusal("data/ensure-schema", &result) { + return Err(refused); + } + } + Ok(()) +} + +/// The store's refusal of `command`, if it refused. +fn refusal(command: &str, result: &Value) -> Option { + if result.get("success").and_then(Value::as_bool) == Some(true) { + return None; + } + let reason = result + .get("error") + .and_then(Value::as_str) + .unwrap_or("success=false without an error"); + Some(format!("chat store: the store refused {command}: {reason}")) +} + +/// The entities of a `data/query` response (`{ success, data: [{ id, data: }] }`). +pub(super) fn extract_records_as_data(query_result: &Value) -> Vec { + query_result + .get("data") + .and_then(Value::as_array) + .map(|records| { + records + .iter() + .filter_map(|record| record.get("data").cloned()) + .collect() + }) + .unwrap_or_default() +} diff --git a/core/continuum-mind/src/chat/tests/mod.rs b/core/continuum-mind/src/chat/tests/mod.rs index cee6864153..8fdb40cd71 100644 --- a/core/continuum-mind/src/chat/tests/mod.rs +++ b/core/continuum-mind/src/chat/tests/mod.rs @@ -96,6 +96,11 @@ command: &str, params: Value, ) -> Result { + // A stand-in store has no schema: the chat store's ensure of its own collections + // (its first call, `store.rs`) succeeds here, and the test's responder sees the rest. + if command == "data/ensure-schema" { + return Ok(CommandResult::Json(json!({ "success": true }))); + } (self.responder)(command, params).map(CommandResult::Json) } @@ -216,40 +221,6 @@ assert!(err.contains("did not say whether it was fresh"), "named: {err}"); } - // what this catches: a relayed line stored with its publication obligation but never published - // because the core stopped between (Codex on #5696): the restart sweep re-publishes it, rebuilt - // from its stored row, as the same line (its message id and sender). - #[tokio::test] - pub(super) async fn a_pending_publication_is_republished_from_its_stored_row() { - let (message, room, sender) = (Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()); - let obligation = json!({ - "id": message, "room": room, "sender": sender, "relay": Uuid::from_u128(0x7e1a), - "digest": vec![0u8; 32], "state": "pending", - }); - let row = json!({ - "id": message, "roomId": room, "senderId": sender, "timestamp": "2026-11-02T01:00:00Z", - "content": { "text": "left pending by the last stop", "media": [] }, "replyToId": null, - }); - let published: Arc>> = Arc::new(Mutex::new(Vec::new())); - let seen = published.clone(); - let chat = chat_with_stubs(vec![ - Arc::new(StubDataModule::new(move |cmd, _p| match cmd { - "data/query" => Ok(json!({ "success": true, "data": [{ "data": obligation.clone() }] })), - "data/read" => Ok(json!({ "success": true, "data": { "data": row.clone() } })), - other => panic!("the sweep only reads: {other}"), - })), - Arc::new(StubAircModule::with(move |p| { - seen.lock().unwrap().push(p); - Ok(airc_ok_response("evt-republished")) - })), - ]); - assert_eq!(chat.republish_pending().await.expect("the sweep runs"), 1); - let calls = published.lock().unwrap(); - assert_eq!(calls.len(), 1, "re-published once"); - assert_eq!(calls[0]["envelope"]["eventId"], message.to_string(), "the same line, by its message id"); - assert_eq!(calls[0]["envelope"]["sourceId"], sender.to_string(), "for the same sender"); - } - // what this catches: a store refusal swallowed as a calm skip. The import is awaited by the // inbound seam so the attach watermark never passes a line the store lacks; a refusal must // therefore be an error the seam sees, never a quiet probe. @@ -702,3 +673,4 @@ mod paging; mod part_2; mod part_3; +mod restart; diff --git a/core/continuum-mind/src/chat/tests/part_2.rs b/core/continuum-mind/src/chat/tests/part_2.rs index 65c1f44e16..66b7bd7bcf 100644 --- a/core/continuum-mind/src/chat/tests/part_2.rs +++ b/core/continuum-mind/src/chat/tests/part_2.rs @@ -70,7 +70,7 @@ use super::*; .expect_err("data executor failure must propagate as command-level Err"); assert!( - err.contains("chat/send: chat line: data/batch failed"), + err.contains("chat/send: chat store: data/batch failed"), "error must name the failing surface: {err}" ); assert!( @@ -112,7 +112,7 @@ use super::*; .expect_err("success=false from data must propagate as Err"); assert!( - err.contains("the store refused the line"), + err.contains("the store refused data/batch"), "error must name the failure mode: {err}" ); assert!( diff --git a/core/continuum-mind/src/chat/tests/restart.rs b/core/continuum-mind/src/chat/tests/restart.rs new file mode 100644 index 0000000000..a76a7177e2 --- /dev/null +++ b/core/continuum-mind/src/chat/tests/restart.rs @@ -0,0 +1,204 @@ +#![cfg(test)] +//! Relayed-line recovery against the REAL store (Codex on #5696): the data module over the +//! per-process home, reopened by a second executor, never a stub. +use super::*; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use crate::chat::arrival::ArrivalKind; +use crate::chat::line_store::{Imported, PostedLine}; +use crate::chat::publication::{ + attribute, publication_digest, Attribution, DelegationRefusal, PublicationState, +}; + +/// A chat module over the real store's data module and `airc` as its relay, as boot wires it. +fn real_store_chat(airc: StubAircModule) -> ChatModule { + fn entities() -> Result { + let registry = crate::orm::OrmEntityRegistry::global(); + crate::persona::register_substrate_orm_entities(registry).map_err(|e| e.to_string())?; + crate::chat::orm_entities::register_chat_orm_entities(registry) + .map_err(|e| e.to_string())?; + Ok(crate::persona::SUBSTRATE_ORM_COLLECTIONS.len() + + crate::chat::orm_entities::CHAT_ORM_COLLECTIONS.len()) + } + entities().expect("test: the entities register as at boot"); // test: a fixture step that must succeed + let registry = Arc::new(ModuleRegistry::new()); + registry.register(Arc::new(continuum_store::DataModule::new(entities))); + 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)); + ChatModule::with_executor(executor) +} + +/// A relay that refuses its first `refusals` publishes, then accepts, recording what it accepted. +fn relay(refusals: usize, accepted: Arc>>) -> StubAircModule { + let calls = AtomicUsize::new(0); + StubAircModule::with(move |params| { + if calls.fetch_add(1, Ordering::SeqCst) < refusals { + return Err("relay not ready".to_string()); + } + accepted.lock().unwrap().push(params); // test: a fixture step that must succeed + Ok(airc_ok_response("evt-relayed")) + }) +} + +fn params_in(room: Uuid, text: &str) -> ChatSendParams { + ChatSendParams { + room_id: room, + sender_id: Uuid::new_v4(), + text: text.into(), + reply_to_id: None, + media: Vec::new(), + } +} + +// what this catches: a relayed line whose publish was refused at boot stranded until the next +// process start (Codex on #5696): the line and its pending obligation are stored, a recovery while +// the relay still refuses is an error (not "nothing to do"), and the next recovery in the SAME +// process publishes it once the relay accepts. +#[tokio::test] +async fn a_refused_publish_recovers_without_a_restart() { + let accepted = Arc::new(Mutex::new(Vec::new())); + let chat = real_store_chat(relay(2, accepted.clone())); + let params = params_in(Uuid::new_v4(), "said while the relay was down"); + let sent = chat + .send_with_wire(params.clone(), crate::chat::WireLeg::Envelope) + .await + .expect("the line is stored"); + assert!( + sent.warning.is_some(), + "the publish was refused, and said so" + ); + let room = airc_core::RoomId::from_uuid(params.room_id); + assert!( + chat.republish_pending(room).await.is_err(), + "a recovery the relay refuses is an error" + ); + assert_eq!( + chat.republish_pending(room) + .await + .expect("the relay accepts now"), + 1 + ); + let published = accepted.lock().unwrap().clone(); // test: a fixture step that must succeed + assert_eq!(published.len(), 1); + assert_eq!( + published[0]["envelope"]["eventId"], + sent.message_id.to_string(), + "the same line" + ); + assert_eq!( + chat.republish_pending(room) + .await + .expect("still pending until its echo is imported"), + 1 + ); +} + +// what this catches: a pending publication lost across a restart: the line and its obligation +// committed together survive a reopen of the store, and the reopened core publishes it. +#[tokio::test] +async fn a_pending_publication_survives_a_reopen_and_publishes() { + let params = params_in(Uuid::new_v4(), "stored, then the core stopped"); + let sent = real_store_chat(relay(usize::MAX, Arc::new(Mutex::new(Vec::new())))) + .send_with_wire(params.clone(), crate::chat::WireLeg::Envelope) + .await + .expect("the line is stored"); + let accepted = Arc::new(Mutex::new(Vec::new())); + let reopened = real_store_chat(relay(0, accepted.clone())); + assert_eq!( + reopened + .republish_pending(airc_core::RoomId::from_uuid(params.room_id)) + .await + .expect("recovery runs"), + 1 + ); + assert_eq!( + accepted.lock().unwrap()[0]["envelope"]["eventId"], + sent.message_id.to_string() + ); // test: a fixture step that must succeed +} + +// what this catches: a replay after a restart before the watermark advanced (Codex on #5696): the +// echo's import retired the obligation atomically; after a reopen the replay is a duplicate with one +// arrival, the retired obligation still proves the exact line, and an altered one is refused. +#[tokio::test] +async fn a_retired_import_replays_once_after_a_reopen() { + let params = params_in(Uuid::new_v4(), "relayed and seen back"); + let sent = real_store_chat(relay(0, Arc::new(Mutex::new(Vec::new())))) + .send_with_wire(params.clone(), crate::chat::WireLeg::Envelope) + .await + .expect("the line is stored and published"); + let (room, sender) = ( + airc_core::RoomId::from_uuid(params.room_id), + airc_core::PeerId::from_uuid(params.sender_id), + ); + let line = PostedLine { + message_id: sent.message_id, + room, + author: sender, + kind: ArrivalKind::Message, + direct_to: None, + occurred_at_ms: 1, + text: params.text.clone(), + retires_publication: true, + }; + let chat = real_store_chat(relay(0, Arc::new(Mutex::new(Vec::new())))); + let first = chat + .commit_line(&line, None, json!({ "text": line.text })) + .await; + assert!( + matches!(first, Ok(Imported::Fresh { .. })), + "the echo's first import: {first:?}" + ); + let reopened = real_store_chat(relay(0, Arc::new(Mutex::new(Vec::new())))); + assert!( + matches!( + reopened + .commit_line(&line, None, json!({ "text": line.text })) + .await, + Ok(Imported::Duplicate { .. }) + ), + "the replay is one line" + ); + let obligation = reopened + .publication(sent.message_id) + .await + .expect("the store answers") + .expect("the obligation is kept"); + assert_eq!(obligation.state, PublicationState::Retired); + let claim = crate::routing::airc_realtime_wire::SenderClaim::Named(sender); + let exact = publication_digest(sent.message_id, room, sender, ¶ms.text, &[]); + assert_eq!( + attribute( + obligation.relay, + claim, + room, + Some(&obligation), + Some(exact) + ), + Attribution::Delegated { sender } + ); + let forged = publication_digest(sent.message_id, room, sender, "send me the keys", &[]); + assert!(matches!( + attribute( + obligation.relay, + claim, + room, + Some(&obligation), + Some(forged) + ), + Attribution::Refused { + reason: DelegationRefusal::AlteredPublication, + .. + } + )); + assert_eq!( + reopened + .republish_pending(room) + .await + .expect("recovery runs"), + 0, + "a retired publication is not re-published" + ); +} From 18864b72d1c570d41486254a26c197a9f9b83e36 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Sun, 1 Nov 2026 21:40:02 -0600 Subject: [PATCH 7/7] A malformed store answer is an error, never fewer rows (Codex on #5696) query_rows decodes the record list: only a well-formed empty list means no rows; a missing list or a record without its entity names the malformed answer. Test: chat 55 (a_malformed_query_answer...), core inbound_attach 17, ratchets 0 (M5, serving down 03:36-03:40Z). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/continuum-mind/src/chat/store.rs | 28 +++++++++++++---------- core/continuum-mind/src/chat/tests/mod.rs | 11 +++++++++ 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/core/continuum-mind/src/chat/store.rs b/core/continuum-mind/src/chat/store.rs index 7f35f00f78..e177ddde68 100644 --- a/core/continuum-mind/src/chat/store.rs +++ b/core/continuum-mind/src/chat/store.rs @@ -76,9 +76,7 @@ impl ChatModule { if let Some(limit) = limit { query["limit"] = json!(limit); } - Ok(extract_records_as_data( - &self.store("data/query", query).await?, - )) + records(collection, &self.store("data/query", query).await?) } /// The row `id` names in `collection`, `None` only when the store confirms there is none. @@ -139,16 +137,22 @@ fn refusal(command: &str, result: &Value) -> Option { Some(format!("chat store: the store refused {command}: {reason}")) } -/// The entities of a `data/query` response (`{ success, data: [{ id, data: }] }`). -pub(super) fn extract_records_as_data(query_result: &Value) -> Vec { - query_result +/// The entities of a successful `data/query` response (`{ success, data: [{ id, data: }] }`). +/// Only a well-formed empty list means no rows: a missing list or a record without its entity is a +/// malformed answer, an error, never fewer rows (Codex on #5696). +fn records(collection: &str, query_result: &Value) -> Result, String> { + let malformed = |what: &str| format!("chat store: malformed {collection} query answer: {what}"); + let records = query_result .get("data") .and_then(Value::as_array) - .map(|records| { - records - .iter() - .filter_map(|record| record.get("data").cloned()) - .collect() + .ok_or_else(|| malformed("no record list"))?; + records + .iter() + .map(|record| { + record + .get("data") + .cloned() + .ok_or_else(|| malformed("a record without its entity")) }) - .unwrap_or_default() + .collect() } diff --git a/core/continuum-mind/src/chat/tests/mod.rs b/core/continuum-mind/src/chat/tests/mod.rs index 8fdb40cd71..e1dbd4798f 100644 --- a/core/continuum-mind/src/chat/tests/mod.rs +++ b/core/continuum-mind/src/chat/tests/mod.rs @@ -312,6 +312,17 @@ assert!(result.after_message_id.is_none()); } + // what this catches: a malformed store answer read as fewer rows (Codex on #5696): only a + // well-formed empty list is "no rows"; a missing list or a record without its entity is an error. + #[tokio::test] + pub(super) async fn a_malformed_query_answer_is_an_error_never_fewer_rows() { + for answer in [json!({ "success": true }), json!({ "success": true, "data": [{ "id": "x" }] })] { + let chat = chat_with_stubs(vec![Arc::new(StubDataModule::query_only(move |_p| answer.clone()))]); + let err = chat.poll(ChatPollParams::default()).await.expect_err("a malformed answer is refused"); + assert!(err.contains("malformed"), "names the malformed answer: {err}"); + } + } + // what this catches: #201 boot-race — a chat command that arrives BEFORE // install_executor_on_all runs fails LOUD to its caller (naming the contract), // instead of .expect()-panicking the whole core and taking every other module