diff --git a/core/continuum-cognition/src/cognition/conversation/room_event.rs b/core/continuum-cognition/src/cognition/conversation/room_event.rs index fb0675a8ad..97f7f285fb 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 { +pub 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 }) } @@ -254,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, @@ -287,12 +306,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 +334,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 +359,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..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 @@ -362,6 +377,44 @@ 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(()), + }; + // 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!( @@ -376,7 +429,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 @@ -391,13 +444,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 @@ -459,7 +506,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 @@ -505,7 +553,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 @@ -522,6 +570,53 @@ 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}; + 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) { + 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), 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, 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 } => { + continuum_base::probe!( + class = "airc.inbound.delegation_refused", + room = %event.room_id.as_uuid(), + transport = %event.peer_id.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" + ); + 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 +629,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(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, &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,107 @@ 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(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, &[]), + state: continuum_mind::chat::publication::PublicationState::Pending, + } +} + +// 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(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(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(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); + 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-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 6ab6de5e03..9f9b18cb05 100644 --- a/core/continuum-kernel/src/routing/airc_realtime_wire.rs +++ b/core/continuum-kernel/src/routing/airc_realtime_wire.rs @@ -15,9 +15,54 @@ 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.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 +/// 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_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 +} + +/// 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. +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, @@ -47,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 } @@ -129,3 +181,44 @@ 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_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)); + 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 520f08f86b..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); @@ -208,7 +212,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,11 +225,23 @@ 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). + // 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), @@ -234,16 +250,12 @@ 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( - &line, - super::line_store::LineWrite::New, - params.reply_to_id, - content, - ) - .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)) } @@ -276,6 +288,9 @@ 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. let publish_params = json!({ "envelope": publish_envelope }); // Partial failure path: data succeeded, airc failed. Return 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 418447eb73..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, @@ -65,9 +64,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() @@ -150,7 +163,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, @@ -218,6 +235,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(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)), + ..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/drain.rs b/core/continuum-mind/src/chat/drain.rs new file mode 100644 index 0000000000..89971c899a --- /dev/null +++ b/core/continuum-mind/src/chat/drain.rs @@ -0,0 +1,257 @@ +//! 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; + +/// 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 collection = ::COLLECTION; + let rooms_typed = rooms; + let rooms: Vec = rooms.iter().map(|r| r.as_uuid().to_string()).collect(); + 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? { + unvouched_import |= matches!( + imported.history, + super::import_watermark::ImportHistory::UnvouchedThrough { .. } + ); + } + } + Ok(( + StoreFacts { + retained_floor, + unvouched_import, + }, + arrivals, + )) + } +} + +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() +} + +#[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/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 fa24666453..f3ffb02263 100644 --- a/core/continuum-mind/src/chat/line_store.rs +++ b/core/continuum-mind/src/chat/line_store.rs @@ -8,8 +8,9 @@ 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; 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. @@ -35,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"); @@ -57,6 +54,14 @@ 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>; + /// How far the store has imported `room` from airc; `None` when it never has. async fn watermark(&self, room: RoomId) -> Result, String>; @@ -75,10 +80,18 @@ 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, None, json!({ "text": line.text })) .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 + } + async fn watermark(&self, room: RoomId) -> Result, String> { installed()?.import_watermark(room).await } @@ -98,25 +111,73 @@ 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", + })), + } +} + /// Records every imported line and reports each as fresh, in order: the seam's test importer. #[cfg(any(test, feature = "test-fixtures"))] #[derive(Default)] pub struct RecordingImporter( pub std::sync::Mutex>, pub std::sync::Mutex>, + pub std::sync::Mutex>, ); #[cfg(any(test, feature = "test-fixtures"))] #[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, }) } + async fn recover_publications(&self, _room: RoomId) -> Result { + Ok(0) + } + + 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 @@ -159,36 +220,36 @@ impl LineImporter for RecordingImporter { } impl ChatModule { - /// Commit `line`'s message row and its arrival in ONE batch. + /// 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, + 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, - write: LineWrite, 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, @@ -197,18 +258,20 @@ 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 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 mut operations = vec![message_op, append_op]; + if line.retires_publication { + // 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::Update, + collection: + ::COLLECTION + .to_string(), + id: Some(line.message_id.to_string()), + data: Some(json!({ "state": super::publication::PublicationState::Retired })), + }); } + let result = self.run_batch(operations).await?; let appended = result .get("data") .and_then(|d| d.get(1)) @@ -238,6 +301,14 @@ 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()) + } + 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 8b24c6439f..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; @@ -61,12 +61,15 @@ 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; 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/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..7797648fa7 --- /dev/null +++ b/core/continuum-mind/src/chat/publication.rs @@ -0,0 +1,474 @@ +//! 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 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. + +use airc_core::{PeerId, RoomId}; +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 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, + 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()); + field(&(media.len() as u64).to_le_bytes()); + for item in media { + 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() +} + +/// 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")] +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, + /// 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), +/// 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 { + /// 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 nothing proves: dropped, said, never relabeled. `claimed` is `None` for a malformed claim. + Refused { + claimed: Option, + reason: DelegationRefusal, + }, +} + +/// Why a claim to speak for someone else was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DelegationRefusal { + /// 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 line is not the one published (a reused id with altered content). + AlteredPublication, +} + +/// Decide a received line's attribution from its transport author, its header's sender claim, the +/// 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, + claim: SenderClaim, + room: RoomId, + obligation: Option<&PublicationObligation>, + received: Option<[u8; 32]>, +) -> Attribution { + 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 Some(obligation) = obligation else { + return refuse(DelegationRefusal::NoOrigin); + }; + if obligation.relay != transport { + return refuse(DelegationRefusal::ForeignRelay); + } + 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 } +} + +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 { + 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), + ); + let obligation = PublicationObligation { + id: message_id, + room, + 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 { + 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)?; + self.run_batch(vec![op]).await.map(drop) + } + + /// 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 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; + }; + // `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; `None` + /// only when the store confirms there is no such row. + async fn sent_line( + &self, + message: Uuid, + ) -> Result, String> { + let Some(stored) = self + .row::(super::types::CHAT_MESSAGES_COLLECTION, message) + .await? + else { + return Ok(None); + }; + 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, + id: Uuid, + ) -> Result, String> { + self.row( + ::COLLECTION, + id, + ) + .await + } +} + +#[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, + state: PublicationState::Pending, + } + } + + // 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 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 + // 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 + ); + } +} + +/// 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/store.rs b/core/continuum-mind/src/chat/store.rs new file mode 100644 index 0000000000..e177ddde68 --- /dev/null +++ b/core/continuum-mind/src/chat/store.rs @@ -0,0 +1,158 @@ +//! 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); + } + records(collection, &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 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) + .ok_or_else(|| malformed("no record list"))?; + records + .iter() + .map(|record| { + record + .get("data") + .cloned() + .ok_or_else(|| malformed("a record without its entity")) + }) + .collect() +} diff --git a/core/continuum-mind/src/chat/tests/mod.rs b/core/continuum-mind/src/chat/tests/mod.rs index c80c0c8829..e1dbd4798f 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) } @@ -93,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) } @@ -117,6 +125,7 @@ direct_to: Some(airc_core::PeerId::new()), occurred_at_ms: 1_784_227_923_000, text: text.to_string(), + retires_publication: false, } } @@ -136,12 +145,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 }), - ) + .commit_line(&line, None, json!({ "text": line.text })) .await .expect("the import commits"); assert_eq!( @@ -194,12 +198,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 }), - ) + .commit_line(&line, None, json!({ "text": line.text })) .await .expect("a duplicate is a committed import"); assert_eq!( @@ -216,7 +215,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, 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}"); @@ -233,12 +232,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 }), - ) + .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}"); @@ -318,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 @@ -612,11 +617,11 @@ #[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| { + 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"][1]["collection"], "chat_publications", "obligation in the line's batch: {p}"); Ok(batch_ok()) })), Arc::new(StubAircModule::ok(airc_ok_response("evt-happy-001"))), @@ -679,3 +684,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" + ); +}