diff --git a/core/continuum-core/src/airc/inbound_attach.rs b/core/continuum-core/src/airc/inbound_attach.rs index ef95c43a86..42d437b413 100644 --- a/core/continuum-core/src/airc/inbound_attach.rs +++ b/core/continuum-core/src/airc/inbound_attach.rs @@ -19,6 +19,8 @@ use crate::cognition::conversation::room_event::chat_transcript_message; use crate::routing::airc_realtime_wire::{bus_event_from_envelope, envelope_from_event}; use crate::ipc::positron_kanban_source::KANBAN_CHANGED; use crate::ipc::positron_source::CHAT_POSTED; +use continuum_mind::chat::import_watermark::ImportWatermark; +use continuum_mind::chat::line_store::{LineImporter, PostedLine}; use crate::ipc::positron_wall_source::WALL_CHANGED; use crate::runtime::MessageBus; @@ -132,61 +134,50 @@ pub fn spawn_daemon_attach( }); } -/// Where the per-channel attach watermark persists — the CONSUMER CURSOR -/// (task #242). One tiny JSON file per channel under the user's continuum -/// state dir: the [`IpcCursor`] this process has caught up to, threaded back -/// as [`AttachStart::After`] on the next attach so a core reboot resumes at -/// the gap instead of replaying the room's entire history into the UI and -/// every persona's perception (glass-boxed three times on 2026-07-30 — each -/// reboot re-fed days of transcript as fresh inbox to every mind). -/// -/// Under the canonical continuum home, never a cwd-relative `.`: on the 5090 -/// (2026-10-06) the Windows service had no `HOME`, the old `unwrap_or(".")` -/// resolved `.\.continuum\state` against an unwritable working directory, and -/// 592 persists failed "Access is denied", so every core restart re-fed the -/// room into the desktop, the human views and every persona as if it were new. -fn cursor_path(channel: &RoomId) -> Result { - Ok(crate::paths::continuum_home()? - .join("state") - .join(format!("airc-attach-cursor-{}.json", channel.as_uuid()))) +/// The per-channel attach watermark — the CONSUMER CURSOR (task #242): the [`IpcCursor`] this +/// core has caught up to, threaded back as [`AttachStart::After`] on the next attach so a reboot +/// resumes at the gap instead of replaying the room's history into the UI and every persona's +/// perception (glass-boxed three times on 2026-07-30). It lives in the chat store beside the lines +/// it vouches for (`chat::import_watermark`, Slice P), written through the ORM; every line up to +/// it has already been imported, because the seam awaits each import before the next frame. +async fn load_cursor(lines: &dyn LineImporter, channel: &RoomId) -> Result, String> { + if let Some(imported) = lines.watermark(*channel).await? { + let mark = imported.position; + return Ok(Some(IpcCursor { epoch: mark.epoch, counter: mark.counter, event_id: airc_core::EventId::from_uuid(mark.event_id) })); + } + migrate_legacy_cursor(lines, channel).await } -fn load_cursor(channel: &RoomId) -> Option { - let path = match cursor_path(channel) { - Ok(path) => path, - Err(error) => { - warn!("airc attach cursor has no home ({error}): this attach starts as a first attach"); - return None; - } +/// One-time migration: a node that persisted its watermark as a JSON file before the store owned +/// it (`state/airc-attach-cursor-.json`) hands it to the store and removes the file, so the +/// first attach after the upgrade resumes where the last one stopped. That file advanced +/// independently of the old lossy writer, so it does NOT vouch that the lines before it were +/// stored: the store records it as unvouched through that position (`ImportHistory`), and a reader +/// of that history perceives a gap (Codex on #5694). A missing or corrupt file is a first attach. +async fn migrate_legacy_cursor(lines: &dyn LineImporter, channel: &RoomId) -> Result, String> { + let Ok(home) = crate::paths::continuum_home() else { + return Ok(None); }; - let raw = std::fs::read_to_string(path).ok()?; - // A corrupt watermark degrades to first-attach semantics (one full seed) — - // annoying, never wrong. It is presentation-adjacent state, not truth: the - // durable transcript is the storage of record either way. - serde_json::from_str(&raw).ok() -} - -fn persist_cursor(channel: &RoomId, cursor: &IpcCursor) { - let path = match cursor_path(channel) { - Ok(path) => path, - Err(error) => { - warn!("failed to persist airc attach cursor: no continuum home ({error})"); - return; - } + let path = home.join("state").join(format!("airc-attach-cursor-{}.json", channel.as_uuid())); + let Some(cursor) = std::fs::read_to_string(&path).ok().and_then(|raw| serde_json::from_str::(&raw).ok()) else { // storage boundary: the legacy cursor file's JSON + return Ok(None); }; - if let Some(dir) = path.parent() { - let _ = std::fs::create_dir_all(dir); + lines.migrate_watermark(*channel, mark_of(&cursor)).await?; + if let Err(error) = std::fs::remove_file(&path) { + warn!("migrated the airc attach cursor into the store but could not remove {}: {error}", path.display()); } - match serde_json::to_string(cursor) { - Ok(json) => { - if let Err(error) = std::fs::write(&path, json) { - warn!( - "failed to persist airc attach cursor to {}: {error}", - path.display() - ); - } - } - Err(error) => warn!("failed to serialize airc attach cursor: {error}"), + Ok(Some(cursor)) +} + +fn mark_of(cursor: &IpcCursor) -> ImportWatermark { + ImportWatermark { epoch: cursor.epoch, counter: cursor.counter, event_id: cursor.event_id.as_uuid() } +} + +/// Record the daemon's advance (always an already-delivered, already-imported event). A failure +/// costs a larger replay on the next attach, which the idempotent import absorbs: said, not fatal. +async fn persist_cursor(lines: &dyn LineImporter, channel: &RoomId, cursor: &IpcCursor) { + if let Err(error) = lines.advance_watermark(*channel, mark_of(cursor)).await { + warn!("failed to persist the airc attach watermark for {channel}: {error}"); } } @@ -264,7 +255,8 @@ pub async fn run_daemon_attach( // The room starts at join for a fresh node — personas perceive the // room AS IT IS NOW (#131), and deep history is #249's bounded // durable-transcript hydration, never a perception replay. - let request = attach_request_for_cursor(channel, load_cursor(&channel)); + let lines = continuum_mind::chat::line_store::ChatStore; + let request = attach_request_for_cursor(channel, load_cursor(&lines, &channel).await?); let mut stream = client .attach(request) .await @@ -303,13 +295,17 @@ pub async fn run_daemon_attach( probe_class = "airc.cursor.advanced", "attach watermark advanced (daemon heartbeat) — persisting" ); - persist_cursor(&channel, advanced_to); + persist_cursor(&lines, &channel, advanced_to).await; } - handle_attach_response(response, &bus).await?; + handle_attach_response(response, &bus, &lines).await?; } } -pub async fn handle_attach_response(response: Response, bus: &MessageBus) -> Result<(), String> { +pub async fn handle_attach_response( + response: Response, + bus: &MessageBus, + lines: &dyn LineImporter, +) -> Result<(), String> { match response { Response::Ok => Ok(()), // v5 owner-core schema (task #82): the daemon now streams raw @@ -318,7 +314,7 @@ pub async fn handle_attach_response(response: Response, bus: &MessageBus) -> Res // TranscriptEvent. A malformed buffer is logged + skipped (the // live stream shouldn't die because one event failed to parse). Response::Event { envelope } => match decode_wire_event(envelope) { - Ok(event) => publish_transcript_event(&Arc::new(event), bus).await, + Ok(event) => publish_transcript_event(&Arc::new(event), bus, lines).await, Err(error) => { warn!("Skipping malformed airc daemon event: {error}"); Ok(()) @@ -338,6 +334,7 @@ pub async fn handle_attach_response(response: Response, bus: &MessageBus) -> Res pub async fn publish_transcript_event( event: &Arc, bus: &MessageBus, + lines: &dyn LineImporter, ) -> Result<(), String> { // THE ONE INBOUND DECODE POINT for room events: the transport kind and headers // decide protocol frame or conversation, before anything reads the payload. The @@ -394,7 +391,13 @@ 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((name, payload)) = chat_posted_from_message(event) { + 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}") + })?; // 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 @@ -412,9 +415,9 @@ pub async fn publish_transcript_event( crate::cognition::deliberation_budget::record_room_speech( event.room_id.as_uuid(), Some(event.peer_id.as_uuid()), - payload["content"].as_str().unwrap_or_default(), + &line.text, ); - bus.publish_async_only(name, payload); + bus.publish_async_only(CHAT_POSTED, chat_posted_payload(&line)); } else if let Some((name, payload)) = wall_changed_from_event(event) { bus.publish_async_only(name, payload); } else if let Some((name, payload)) = kanban_changed_from_event(event) { @@ -456,10 +459,16 @@ pub async fn publish_transcript_event( "first capacity offer heard from a grid peer", ); } - } else if let Some((name, payload)) = chat_posted_from_envelope(&envelope, event) { + } else if let Some(line) = posted_from_envelope(&envelope, event) { + // 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 + .import(line.clone()) + .await + .map_err(|e| format!("inbound line not stored; re-attaching to replay it: {e}"))?; continuum_base::probe!( class = "airc.chat.projected", - sender_id = %payload["senderId"], + sender_id = %line.author.as_uuid(), room_id = %event.room_id.as_uuid(), event_id = %event.event_id.as_uuid(), "chat_transcript envelope projected to chat:posted for positron" @@ -468,9 +477,9 @@ pub async fn publish_transcript_event( crate::cognition::deliberation_budget::record_room_speech( event.room_id.as_uuid(), Some(event.peer_id.as_uuid()), - payload["content"].as_str().unwrap_or_default(), + &line.text, ); - bus.publish_async_only(name, payload); + bus.publish_async_only(CHAT_POSTED, chat_posted_payload(&line)); } Ok(()) } @@ -478,7 +487,7 @@ pub async fn publish_transcript_event( /// Project a `chat_transcript` envelope (a human `chat/send`, the web /// client — the `Body::Json` room-message shape) into the SAME thin /// `chat:posted` payload the plain-text sibling -/// [`chat_posted_from_message`] emits. Returns `None` for any other +/// [`posted_from_message`] emits. Returns `None` for any other /// envelope (EventBridge, presence, media-control) — it is not a chat line. /// /// Identity-free like its sibling: `senderId` is the envelope's logical @@ -492,10 +501,10 @@ pub async fn publish_transcript_event( /// the inline id means the projection, the durable chat store, and the /// original `chat/send` all agree on ONE identity per human message, so /// the store-side projector (#140) dedups instead of double-writing. -fn chat_posted_from_envelope( +fn posted_from_envelope( envelope: &AircRealtimeEnvelope, event: &airc_core::TranscriptEvent, -) -> Option<(&'static str, serde_json::Value)> { +) -> Option { let (sender_id, content) = chat_transcript_message(envelope, event.peer_id.as_uuid())?; let message_id = match &envelope.payload { crate::routing::airc_realtime::AircRealtimePayload::ExistingSchema { payload } => payload @@ -507,14 +516,36 @@ fn chat_posted_from_envelope( _ => None, } .unwrap_or_else(|| event.event_id.as_uuid()); - let payload = serde_json::json!({ - "messageId": message_id, - "roomId": event.room_id.as_uuid(), - "senderId": sender_id, - "content": content, - "timestamp": event.occurred_at_ms, - }); - Some((CHAT_POSTED, payload)) + let mut line = posted_line(event, content)?; + line.message_id = message_id; + line.author = airc_core::PeerId::from_uuid(sender_id); + Some(line) +} + +/// 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 { + let arrival = continuum_mind::chat::arrival::Arrival::of_event(event)?; + Some(PostedLine { + message_id: arrival.message_id, + room: arrival.room, + author: arrival.author, + kind: arrival.kind, + direct_to: arrival.direct_to, + occurred_at_ms: event.occurred_at_ms, + text, + }) +} + +/// The `chat:posted` projection cue the positron renderer reads, derived from the typed line. +fn chat_posted_payload(line: &PostedLine) -> serde_json::Value { + serde_json::json!({ + "messageId": line.message_id, + "roomId": line.room.as_uuid(), + "senderId": line.author.as_uuid(), + "content": line.text, + "timestamp": line.occurred_at_ms, + }) } /// Decode a `grid_capacity` envelope's inline payload into a [`CapacityOffer`]. @@ -547,21 +578,12 @@ fn capacity_offer_from_envelope( /// is a presence fact, never a message fact — see /// `airc-to-positron-chat-projection`. airc's `event_id` IS the stable /// `message_id` (same event → same id across replay + peers). -fn chat_posted_from_message( - event: &airc_core::TranscriptEvent, -) -> Option<(&'static str, serde_json::Value)> { +fn posted_from_message(event: &airc_core::TranscriptEvent) -> Option { if event.kind != TranscriptKind::Message { return None; } let content = event.body.as_ref()?.as_text()?; - let payload = serde_json::json!({ - "messageId": event.event_id.as_uuid(), - "roomId": event.room_id.as_uuid(), - "senderId": event.peer_id.as_uuid(), - "content": content, - "timestamp": event.occurred_at_ms, - }); - Some((CHAT_POSTED, payload)) + posted_line(event, content.to_string()) } /// Project a `WallPostPublished` transcript event into the `wall:changed` diff --git a/core/continuum-core/src/airc/inbound_attach/tests.rs b/core/continuum-core/src/airc/inbound_attach/tests.rs index 549cc97315..32b1b2d4e6 100644 --- a/core/continuum-core/src/airc/inbound_attach/tests.rs +++ b/core/continuum-core/src/airc/inbound_attach/tests.rs @@ -113,7 +113,7 @@ async fn valid_continuum_event_reaches_message_bus() { headers_for_envelope(&envelope), ); - publish_transcript_event(&Arc::new(event), &bus).await.unwrap(); + publish_transcript_event(&Arc::new(event), &bus, &continuum_mind::chat::line_store::RecordingImporter::default()).await.unwrap(); let delivered = timeout(Duration::from_millis(200), receiver.recv()) .await @@ -167,7 +167,7 @@ async fn chat_transcript_envelope_projects_chat_posted() { headers_for_envelope(&envelope), ); - publish_transcript_event(&Arc::new(event), &bus).await.unwrap(); + publish_transcript_event(&Arc::new(event), &bus, &continuum_mind::chat::line_store::RecordingImporter::default()).await.unwrap(); let delivered = timeout(Duration::from_millis(200), receiver.recv()) .await @@ -202,7 +202,7 @@ async fn non_continuum_body_is_ignored() { Default::default(), ); - publish_transcript_event(&Arc::new(event), &bus).await.unwrap(); + publish_transcript_event(&Arc::new(event), &bus, &continuum_mind::chat::line_store::RecordingImporter::default()).await.unwrap(); assert!(timeout(Duration::from_millis(20), receiver.recv()) .await @@ -224,7 +224,7 @@ async fn plain_chat_message_projects_thin_chat_posted() { let mut receiver = bus.receiver(); let event = transcript_event(Some(Body::text("hello room")), Default::default()); - publish_transcript_event(&Arc::new(event), &bus).await.unwrap(); + publish_transcript_event(&Arc::new(event), &bus, &continuum_mind::chat::line_store::RecordingImporter::default()).await.unwrap(); let delivered = timeout(Duration::from_millis(200), receiver.recv()) .await @@ -259,7 +259,7 @@ async fn non_message_kind_does_not_project_chat() { let mut event = transcript_event(None, Default::default()); event.kind = TranscriptKind::Receipt; - publish_transcript_event(&Arc::new(event), &bus).await.unwrap(); + publish_transcript_event(&Arc::new(event), &bus, &continuum_mind::chat::line_store::RecordingImporter::default()).await.unwrap(); assert!(timeout(Duration::from_millis(20), receiver.recv()) .await @@ -281,7 +281,7 @@ async fn wall_post_event_projects_thin_wall_changed_signal() { let mut event = transcript_event(None, Default::default()); event.kind = TranscriptKind::WallPostPublished; - publish_transcript_event(&Arc::new(event), &bus).await.unwrap(); + publish_transcript_event(&Arc::new(event), &bus, &continuum_mind::chat::line_store::RecordingImporter::default()).await.unwrap(); let delivered = timeout(Duration::from_millis(200), receiver.recv()) .await @@ -324,7 +324,7 @@ async fn work_board_event_projects_thin_kanban_changed_signal() { let mut event = transcript_event(Some(body), headers); event.kind = TranscriptKind::System; - publish_transcript_event(&Arc::new(event), &bus).await.unwrap(); + publish_transcript_event(&Arc::new(event), &bus, &continuum_mind::chat::line_store::RecordingImporter::default()).await.unwrap(); let delivered = timeout(Duration::from_millis(200), receiver.recv()) .await @@ -347,7 +347,7 @@ async fn malformed_continuum_body_is_ignored() { headers_for_envelope(&envelope), ); - publish_transcript_event(&Arc::new(event), &bus).await.unwrap(); + publish_transcript_event(&Arc::new(event), &bus, &continuum_mind::chat::line_store::RecordingImporter::default()).await.unwrap(); assert!(timeout(Duration::from_millis(20), receiver.recv()) .await @@ -398,14 +398,14 @@ async fn a_peer_command_in_a_room_never_reaches_a_mind_and_room_speech_still_doe command.kind = TranscriptKind::Command; command.room_id = RoomId::from_uuid(ROOM); command.target = MentionTarget::Peer(PeerId::from_uuid(persona)); - publish_transcript_event(&Arc::new(command), &bus) + publish_transcript_event(&Arc::new(command), &bus, &continuum_mind::chat::line_store::RecordingImporter::default()) .await .expect("a protocol frame is routed, not an error"); assert!(wakes.try_recv().is_err(), "a peer command is not something she perceives"); let mut speech = transcript_event(Some(Body::text("@Aiko how is it going?")), airc_core::Headers::new()); speech.room_id = RoomId::from_uuid(ROOM); - publish_transcript_event(&Arc::new(speech), &bus) + publish_transcript_event(&Arc::new(speech), &bus, &continuum_mind::chat::line_store::RecordingImporter::default()) .await .expect("room speech is fed"); let woke = matches!( @@ -415,3 +415,88 @@ async fn a_peer_command_in_a_room_never_reaches_a_mind_and_room_speech_still_doe crate::persona::perception_feed::unregister(persona); assert!(woke, "a line addressed to her in her room still wakes her"); } + +// what this catches: a room line reaching minds and screens without being in the durable store +// (the old lossy bus writer dropped lines under lag), or its routing header being lost on the way: +// the seam imports each line once, typed, with its addressee, before anything else consumes it. +#[tokio::test] +async fn a_room_line_is_imported_with_its_header_before_it_is_projected() { + let bus = MessageBus::new(); + let lines = continuum_mind::chat::line_store::RecordingImporter::default(); + let mut event = transcript_event( + Some(Body::text("@Aiko the build is green")), + airc_core::Headers::new(), + ); + event.target = MentionTarget::Peer(PeerId::from_u128(7)); + publish_transcript_event(&Arc::new(event), &bus, &lines) + .await + .expect("the line is stored and projected"); + let imported = lines.0.lock().expect("test: the fixture lock").clone(); // test: a fixture step that must succeed + assert_eq!(imported.len(), 1, "imported exactly once"); + assert_eq!(imported[0].message_id, EventId::from_u128(1).as_uuid()); + assert_eq!( + imported[0].direct_to, + Some(PeerId::from_u128(7)), + "the addressee rides the header" + ); + assert_eq!(imported[0].text, "@Aiko the build is green"); +} + +// what this catches: a line the store refused being acknowledged anyway. The seam must return an +// error, which ends the attach before the watermark passes the line, so the re-attach replays it. +#[tokio::test] +async fn a_refused_import_ends_the_attach_so_the_line_replays() { + let bus = MessageBus::new(); + let event = transcript_event(Some(Body::text("hello")), airc_core::Headers::new()); + let err = publish_transcript_event( + &Arc::new(event), + &bus, + &continuum_mind::chat::line_store::RefusingImporter, + ) + .await + .expect_err("a refused line is an error at the seam"); + assert!( + err.contains("re-attaching to replay it"), + "the error says what happens next: {err}" + ); +} + +// what this catches: the attach watermark living anywhere but the store that holds the lines it +// vouches for (it was a hand-written JSON file), or a store that cannot answer being read as "never +// attached" (which would replay a whole first attach instead of retrying): the cursor round-trips +// through the injected store, and an unreadable store is an error the attach retries on. +#[tokio::test] +async fn the_attach_watermark_round_trips_through_the_store() { + let lines = continuum_mind::chat::line_store::RecordingImporter::default(); + let room = RoomId::from_u128(2); + let cursor = IpcCursor { epoch: 3, counter: 42, event_id: EventId::from_u128(9) }; + persist_cursor(&lines, &room, &cursor).await; + assert_eq!(load_cursor(&lines, &room).await.expect("the store answers"), Some(cursor)); + assert!( + load_cursor(&continuum_mind::chat::line_store::RefusingImporter, &room).await.is_err(), + "an unreadable store is retried, never treated as a first attach" + ); +} + +// what this catches: the pre-store cursor file (which advanced while the old lossy writer could drop +// lines) being migrated as if it vouched that every earlier line is stored (Codex on #5694). An old +// cursor beyond a line the store never got: the migrated watermark resumes the attach there, records +// its history as unvouched through that point, and keeps that history as the watermark advances. +#[tokio::test] +async fn a_migrated_cursor_never_vouches_for_the_lines_before_it() { + use continuum_mind::chat::import_watermark::ImportHistory; + let lines = continuum_mind::chat::line_store::RecordingImporter::default(); + let room = RoomId::from_u128(0x5694); + let old = IpcCursor { epoch: 7, counter: 900, event_id: EventId::from_u128(0x900) }; + let state = crate::paths::continuum_home().expect("test: the per-process home").join("state"); // test: a fixture step that must succeed + std::fs::create_dir_all(&state).expect("test: the state dir"); // test: a fixture step that must succeed + let file = state.join(format!("airc-attach-cursor-{}.json", room.as_uuid())); + std::fs::write(&file, serde_json::to_string(&old).expect("test: the cursor serializes")).expect("test: the legacy file"); // test: writing the legacy fixture the migration reads + assert_eq!(load_cursor(&lines, &room).await.expect("the store answers"), Some(old), "the attach resumes at the old cursor"); + assert!(!file.exists(), "the migrated file is removed"); + let unvouched = ImportHistory::UnvouchedThrough { epoch: 7, counter: 900, event_id: old.event_id.as_uuid() }; + let history = |lines: &continuum_mind::chat::line_store::RecordingImporter| lines.1.lock().expect("test: the fixture lock").get(&room).map(|m| m.history); // test: a fixture step that must succeed + assert_eq!(history(&lines), Some(unvouched), "the line the old writer dropped is not vouched for"); + 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"); +} diff --git a/core/continuum-core/src/modules/data_wiring.rs b/core/continuum-core/src/modules/data_wiring.rs index d34910388b..a0cb9b0a5d 100644 --- a/core/continuum-core/src/modules/data_wiring.rs +++ b/core/continuum-core/src/modules/data_wiring.rs @@ -11,12 +11,23 @@ pub fn wire_substrate_orm_entities() -> Result { let registry = crate::orm::OrmEntityRegistry::global(); crate::persona::register_substrate_orm_entities(registry) .map_err(|e| format!("substrate ORM entity registration conflict — boot refused: {e}"))?; - Ok(crate::persona::SUBSTRATE_ORM_COLLECTIONS + continuum_mind::chat::orm_entities::register_chat_orm_entities(registry) + .map_err(|e| format!("chat ORM entity registration conflict — boot refused: {e}"))?; + Ok(substrate_collections() .iter() .filter(|c| registry.resolve(c).is_some()) .count()) } +/// Every collection the boot wiring registers: the persona substrate's and the chat store's. +fn substrate_collections() -> Vec<&'static str> { + crate::persona::SUBSTRATE_ORM_COLLECTIONS + .iter() + .chain(continuum_mind::chat::orm_entities::CHAT_ORM_COLLECTIONS) + .copied() + .collect() +} + /// The data module as this core boots it: the store's module with the substrate's entities. pub fn data_module() -> DataModule { DataModule::new(wire_substrate_orm_entities) @@ -34,8 +45,8 @@ mod tests { #[test] fn boot_wiring_makes_every_substrate_collection_resolvable_on_the_global_registry() { let n = wire_substrate_orm_entities().expect("no conflict on a fresh or repeated wiring"); // JUSTIFIED: the invariant under test - assert_eq!(n, crate::persona::SUBSTRATE_ORM_COLLECTIONS.len(), "every substrate collection resolves"); - for c in crate::persona::SUBSTRATE_ORM_COLLECTIONS { + assert_eq!(n, substrate_collections().len(), "every substrate collection resolves"); + for c in substrate_collections() { assert!(crate::orm::OrmEntityRegistry::global().resolve(c).is_some(), "{c} must resolve"); } assert!(crate::orm::OrmEntityRegistry::global().resolve("staged_credit").is_some()); diff --git a/core/continuum-kernel/src/orm/adapter.rs b/core/continuum-kernel/src/orm/adapter.rs index 1898144b14..e431887072 100644 --- a/core/continuum-kernel/src/orm/adapter.rs +++ b/core/continuum-kernel/src/orm/adapter.rs @@ -136,6 +136,12 @@ pub trait StorageAdapter: Send + Sync { /// vector. The returned values describe operations that all committed. async fn batch(&self, operations: Vec) -> StorageResult>; + /// The committed high-water of a collection written by + /// [`super::types::BatchOperationType::Append`]: rises when an append commits, published by + /// the committing write itself (cancellation-safe for the caller). A hint to drain from a + /// cursor, never the data. + fn sequence_revision(&self, collection: &str) -> tokio::sync::watch::Receiver; + // ─── Schema Operations ─────────────────────────────────────────────────── /// Ensure collection schema exists diff --git a/core/continuum-kernel/src/orm/gated_adapter.rs b/core/continuum-kernel/src/orm/gated_adapter.rs index f208aeeddd..b408f2a8f7 100644 --- a/core/continuum-kernel/src/orm/gated_adapter.rs +++ b/core/continuum-kernel/src/orm/gated_adapter.rs @@ -114,6 +114,9 @@ impl StorageAdapter for GatedAdapter { async fn batch(&self, operations: Vec) -> StorageResult> { self.write(move |a| Box::pin(async move { a.batch(operations).await })).await } + fn sequence_revision(&self, collection: &str) -> tokio::sync::watch::Receiver { + self.inner.sequence_revision(collection) + } async fn upsert_monotonic(&self, record: DataRecord, field: &str) -> StorageResult { let field = field.to_string(); self.write(move |a| Box::pin(async move { a.upsert_monotonic(record, &field).await })).await diff --git a/core/continuum-kernel/src/orm/mod.rs b/core/continuum-kernel/src/orm/mod.rs index 64968913a1..2969a70ce4 100644 --- a/core/continuum-kernel/src/orm/mod.rs +++ b/core/continuum-kernel/src/orm/mod.rs @@ -51,10 +51,10 @@ pub use continuum_orm_derive::Entity; pub use migration::{MigrationEngine, MigrationHandle}; pub use query::{QueryBuilder, QueryOperator, SortDirection, StorageQuery}; pub use sqlite::{IndexFailure, IndexPass, SqliteAdapter}; -pub use store::{OrmStore, OrmStoreError}; +pub use store::{commit_appending, OrmStore, OrmStoreError}; pub use types::{ CascadeRule, CollectionSchema, DataRecord, FieldType, ForeignKeyRef, RecordMetadata, - SchemaField, SchemaIndex, StorageResult, + SchemaField, SchemaIndex, SequenceSpec, Sequenced, StorageResult, }; pub use vector::{ BackfillVectorsProgress, BackfillVectorsRequest, EmbeddingModel, GenerateEmbeddingRequest, diff --git a/core/continuum-kernel/src/orm/sqlite.rs b/core/continuum-kernel/src/orm/sqlite.rs index ba8303586c..862ec7436d 100644 --- a/core/continuum-kernel/src/orm/sqlite.rs +++ b/core/continuum-kernel/src/orm/sqlite.rs @@ -36,6 +36,7 @@ mod ensure_indexes; pub use ensure_indexes::{IndexFailure, IndexPass}; mod sqlite_adapter; mod conditional; +mod sequenced; mod file; #[cfg(test)] diff --git a/core/continuum-kernel/src/orm/sqlite/conditional.rs b/core/continuum-kernel/src/orm/sqlite/conditional.rs index 18b50b7e21..7794abce9a 100644 --- a/core/continuum-kernel/src/orm/sqlite/conditional.rs +++ b/core/continuum-kernel/src/orm/sqlite/conditional.rs @@ -58,6 +58,22 @@ impl SqliteAdapter { } } +/// Insert `record` unless a row with its id exists (left untouched). Returns whether it inserted. +pub(super) fn ensure_row(conn: &Connection, record: &DataRecord) -> Result { + let table = naming::to_table_name(&record.collection); + let now = chrono::Utc::now().to_rfc3339(); + let (columns, values) = insert_columns(record, &now); + let sql = format!( + "INSERT INTO {table} ({}) VALUES ({}) ON CONFLICT(id) DO NOTHING", + columns.join(", "), + vec!["?"; columns.len()].join(", "), + ); + let params: Vec<&dyn rusqlite::ToSql> = values.iter().map(|b| b.as_ref()).collect(); + conn.execute(&sql, params.as_slice()) + .map(|rows| rows == 1) + .map_err(|e| format!("ensure failed: {e}")) +} + /// Insert `record`, or overwrite its row only where the stored `field` <= the new one. fn upsert_monotonic(conn: &Connection, record: &DataRecord, field: &str) -> StorageResult { let table = naming::to_table_name(&record.collection); diff --git a/core/continuum-kernel/src/orm/sqlite/open_connection.rs b/core/continuum-kernel/src/orm/sqlite/open_connection.rs index 0d25f98686..82cc9709cb 100644 --- a/core/continuum-kernel/src/orm/sqlite/open_connection.rs +++ b/core/continuum-kernel/src/orm/sqlite/open_connection.rs @@ -95,6 +95,8 @@ pub struct SqliteAdapter { /// to look like JSON stays the string it is. Collections nobody declared (the /// TS-style dynamic tables) keep the legacy sniff. pub(super) declared: Arc>>>>, + /// Each sequenced collection's committed high-water, published by the committing write. + pub(super) sequences: Arc, } impl SqliteAdapter { @@ -105,6 +107,7 @@ impl SqliteAdapter { reader_index: AtomicUsize::new(0), last_pressure_check: Arc::new(AtomicU64::new(0)), declared: Arc::new(std::sync::RwLock::new(HashMap::new())), + sequences: Arc::default(), } } @@ -561,6 +564,32 @@ pub(super) fn do_batch_one( Err(r.error.unwrap_or_else(|| "update failed".to_string())) // the adapter reported failure without detail; the operation still failed } } + BatchOperationType::Ensure => { + let (Some(id), Some(data)) = (op.id, op.data) else { + return Err("ensure requires both id and data".to_string()); + }; + let record = DataRecord { + id, + collection: op.collection, + data, + metadata: RecordMetadata::default(), + }; + let created = super::conditional::ensure_row(conn, &record)?; + Ok(json!({"success": true, "created": created})) + } + BatchOperationType::Append(spec) => { + let (Some(id), Some(data)) = (op.id, op.data) else { + return Err("append requires both id and data".to_string()); + }; + let record = DataRecord { + id, + collection: op.collection, + data, + metadata: RecordMetadata::default(), + }; + let sequenced = super::sequenced::append_sequenced(conn, record, &spec)?; + Ok(json!({"success": true, "seq": sequenced.seq, "fresh": sequenced.fresh})) + } BatchOperationType::Delete => { let Some(id) = op.id else { return Err("delete requires an id".to_string()); diff --git a/core/continuum-kernel/src/orm/sqlite/sequenced.rs b/core/continuum-kernel/src/orm/sqlite/sequenced.rs new file mode 100644 index 0000000000..f5597a928f --- /dev/null +++ b/core/continuum-kernel/src/orm/sqlite/sequenced.rs @@ -0,0 +1,111 @@ +//! The sequenced append: a row numbered by a commit-ordered sequence, deduplicated by a unique +//! field. Runs only inside [`do_batch`](super::open_connection)'s `BEGIN IMMEDIATE` transaction +//! on the single writer connection, so the `max + 1` read and the insert can never interleave +//! with another writer: sequence order is commit order. Numbers come from a durable high-water, +//! so pruning rows never re-issues one. + +use rusqlite::{Connection, OptionalExtension}; +use serde_json::{json, Value}; + +use super::value_to_sql_boxed; +use crate::orm::adapter::naming; +use crate::orm::types::{DataRecord, SequenceSpec, Sequenced}; + +/// Append `record` under `spec`; the caller is inside the batch transaction. +pub(super) fn append_sequenced( + conn: &Connection, + mut record: DataRecord, + spec: &SequenceSpec, +) -> Result { + let table = naming::to_table_name(&record.collection); + let seq_col = naming::to_snake_case(&spec.sequence); + let unique_col = naming::to_snake_case(&spec.unique); + let unique_value = record.data.get(&spec.unique).ok_or_else(|| { + format!( + "append: the record has no `{}` to deduplicate by", + spec.unique + ) + })?; + let existing: Option = conn + .query_row( + &format!("SELECT {seq_col} FROM {table} WHERE {unique_col} = ?1"), + [value_to_sql_boxed(unique_value)], + |row| row.get(0), + ) + .optional() + .map_err(|e| format!("append: reading the existing row failed: {e}"))?; + if let Some(seq) = existing { + return Ok(Sequenced { + seq: seq as u64, + fresh: false, + }); + } + // The next sequence comes from a durable per-collection high-water that only rises, never from + // MAX over surviving rows: a pruned newest row (or a collection pruned to empty) must not + // re-issue a sequence a cursor already passed (Cormac on #5694). First use seeds it from any + // existing rows. Same transaction as the insert, so a rollback returns the number. + conn.execute_batch("CREATE TABLE IF NOT EXISTS orm_sequence_heads (collection TEXT PRIMARY KEY, high INTEGER NOT NULL)") + .map_err(|e| format!("append: preparing the sequence heads failed: {e}"))?; + let next: i64 = conn + .query_row( + &format!( + "INSERT INTO orm_sequence_heads (collection, high) VALUES (?1, (SELECT COALESCE(MAX({seq_col}), 0) + 1 FROM {table})) \ + ON CONFLICT(collection) DO UPDATE SET high = high + 1 RETURNING high" + ), + [&table], + |row| row.get(0), + ) + .map_err(|e| format!("append: advancing the sequence failed: {e}"))?; + match &mut record.data { + Value::Object(fields) => { + fields.insert(spec.sequence.clone(), json!(next)); + } + _ => return Err("append: the record's data is not an object".to_string()), + } + let created = super::do_create(conn, record, None); + if !created.success { + return Err(created + .error + .unwrap_or_else(|| "append: create failed".to_string())); // the adapter reported failure without detail; the operation still failed + } + Ok(Sequenced { + seq: next as u64, + fresh: true, + }) +} + +/// The store-owned revision of each sequenced collection: the highest sequence committed. It is +/// published by the blocking write itself, right after `COMMIT` and before that write returns, so +/// a caller dropped at the commit await cannot strand a committed row unannounced: the bump has +/// the commit's custody, not the caller's. A consumer treats it as a hint and drains the store +/// from its own cursor; a bump naming a sequence it already drained is a no-op. +#[derive(Default)] +pub(crate) struct SequenceRevisions( + std::sync::Mutex>>, +); + +impl SequenceRevisions { + fn sender(&self, collection: &str) -> tokio::sync::watch::Sender { + let mut senders = self.0.lock().unwrap_or_else(|p| p.into_inner()); // poisoned = read the last map; a revision is a hint, never lost data + senders + .entry(collection.to_string()) + .or_insert_with(|| tokio::sync::watch::channel(0).0) + .clone() + } + + /// A receiver that wakes when `collection`'s committed high-water rises. + pub(crate) fn subscribe(&self, collection: &str) -> tokio::sync::watch::Receiver { + self.sender(collection).subscribe() + } + + /// Raise `collection`'s high-water to `seq` (never lowers it). + pub(super) fn publish(&self, collection: &str, seq: u64) { + self.sender(collection).send_if_modified(|high| { + let rises = seq > *high; + if rises { + *high = seq; + } + rises + }); + } +} diff --git a/core/continuum-kernel/src/orm/sqlite/sqlite_adapter.rs b/core/continuum-kernel/src/orm/sqlite/sqlite_adapter.rs index c620d58454..78bd6cdebc 100644 --- a/core/continuum-kernel/src/orm/sqlite/sqlite_adapter.rs +++ b/core/continuum-kernel/src/orm/sqlite/sqlite_adapter.rs @@ -246,15 +246,40 @@ impl StorageAdapter for SqliteAdapter { }; let pressure = self.last_pressure_check.clone(); let declared = self.declared.read().map(|d| d.clone()).unwrap_or_default(); // unwrap_or: a poisoned lock reads as "nothing declared" — the legacy sniff, never a refused batch + let sequences = Arc::clone(&self.sequences); + let appends: Vec<(usize, String)> = operations + .iter() + .enumerate() + .filter(|(_, op)| matches!(op.operation_type, BatchOperationType::Append(_))) + .map(|(index, op)| (index, op.collection.clone())) + .collect(); tokio::task::spawn_blocking(move || { let conn = conn.lock().unwrap(); apply_memory_pressure(&conn, &pressure); - do_batch(&conn, operations, &declared) + let result = do_batch(&conn, operations, &declared); + // Published inside the committing write, after COMMIT: the revision has the + // commit's custody, so a caller dropped at the await cannot strand the row. + if let Some(values) = result.data.as_ref().filter(|_| result.success) { + for (index, collection) in &appends { + if let Some(seq) = values + .get(*index) + .and_then(|v| v.get("seq")) + .and_then(Value::as_u64) + { + sequences.publish(collection, seq); + } + } + } + result }) .await .unwrap_or_else(|e| StorageResult::err(format!("spawn_blocking failed: {}", e))) } + fn sequence_revision(&self, collection: &str) -> tokio::sync::watch::Receiver { + self.sequences.subscribe(collection) + } + async fn ensure_schema(&self, schema: CollectionSchema) -> StorageResult { let conn = match self.get_writer() { Ok(c) => c, diff --git a/core/continuum-kernel/src/orm/sqlite/tests.rs b/core/continuum-kernel/src/orm/sqlite/tests.rs index 1420bc07de..79345a9484 100644 --- a/core/continuum-kernel/src/orm/sqlite/tests.rs +++ b/core/continuum-kernel/src/orm/sqlite/tests.rs @@ -369,3 +369,200 @@ }; assert!(adapter.create(more).await.success, "the store still writes"); } + + /// The sequenced append and the store-owned revision it publishes (Slice P's arrival order). + mod sequenced { + use super::*; + use crate::orm::types::{FieldType, SchemaField, SequenceSpec}; + + fn field(name: &str, field_type: FieldType) -> SchemaField { + SchemaField { + name: name.to_string(), + field_type, + indexed: true, + unique: false, + nullable: false, + max_length: None, + foreign_key: None, + } + } + + async fn arrivals() -> (SqliteAdapter, tempfile::TempDir) { + let (adapter, dir) = setup_adapter().await; + let schema = CollectionSchema { + collection: "arrivals".to_string(), + fields: vec![ + field("messageId", FieldType::String), + field("arrivalSeq", FieldType::Number), + ], + indexes: vec![], + }; + assert!( + adapter.ensure_schema(schema).await.success, + "test: the schema registers" + ); // test: a fixture step that must succeed + let lines = CollectionSchema { + collection: "lines".to_string(), + fields: vec![field("text", FieldType::String)], + indexes: vec![], + }; + assert!( + adapter.ensure_schema(lines).await.success, + "test: the line schema registers" + ); // test: a fixture step that must succeed + (adapter, dir) + } + + fn append(id: &str, message: &str) -> BatchOperation { + BatchOperation { + operation_type: BatchOperationType::Append(SequenceSpec { + sequence: "arrivalSeq".into(), + unique: "messageId".into(), + }), + collection: "arrivals".to_string(), + id: Some(id.to_string()), + data: Some(json!({"messageId": message})), + } + } + + fn seq_of(result: &StorageResult>) -> (u64, bool) { + let last = result + .data + .as_ref() + .and_then(|v| v.last()) + .expect("test: the batch reported its append"); // test: the assertion failing loudly + ( + last["seq"].as_u64().expect("test: a sequence"), + last["fresh"].as_bool().expect("test: a freshness flag"), + ) // test: the assertion failing loudly + } + + // what this catches: an arrival order that is not commit order, or a duplicate import + // minting a second arrival for one message (the replay cursor would deliver it twice). + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn appends_number_in_commit_order_and_a_duplicate_reuses_its_arrival() { + let (adapter, _dir) = arrivals().await; + assert_eq!( + seq_of(&adapter.batch(vec![append("a1", "m1")]).await), + (1, true) + ); + assert_eq!( + seq_of(&adapter.batch(vec![append("a2", "m2")]).await), + (2, true) + ); + assert_eq!( + seq_of(&adapter.batch(vec![append("a3", "m1")]).await), + (1, false), + "the duplicate reuses m1's arrival" + ); + assert!( + !adapter.read("arrivals", &"a3".to_string()).await.success, + "no second row for m1" + ); + assert_eq!( + seq_of(&adapter.batch(vec![append("a4", "m3")]).await), + (3, true), + "no gap from the duplicate" + ); + } + + // what this catches: an import of a line already stored failing the whole batch (so a + // replay after a crash could never commit), or minting a second row or arrival for it. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn an_ensured_row_and_its_append_are_idempotent_together() { + let (adapter, _dir) = arrivals().await; + let line = |arrival: &str| { + vec![ + BatchOperation { + operation_type: BatchOperationType::Ensure, + collection: "lines".into(), + id: Some("m1".into()), + data: Some(json!({"text": "hi"})), + }, + append(arrival, "m1"), + ] + }; + let first = adapter.batch(line("a1")).await; + assert_eq!( + first.data.as_ref().map(|v| v[0]["created"].clone()), + Some(json!(true)) + ); + assert_eq!(seq_of(&first), (1, true)); + let again = adapter.batch(line("a2")).await; + assert!(again.success, "the replay commits: {:?}", again.error); + assert_eq!( + again.data.as_ref().map(|v| v[0]["created"].clone()), + Some(json!(false)), + "the stored line is untouched" + ); + assert_eq!(seq_of(&again), (1, false), "and its arrival is reused"); + } + + // what this catches: a pruned newest row (or a collection pruned to empty) re-issuing a + // sequence a cursor already passed, so the cursor silently skips the new row (Cormac on #5694). + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn pruning_never_reissues_a_sequence() { + let (adapter, _dir) = arrivals().await; + assert_eq!(seq_of(&adapter.batch(vec![append("a1", "m1")]).await), (1, true)); + assert_eq!(seq_of(&adapter.batch(vec![append("a2", "m2")]).await), (2, true)); + assert!(adapter.delete("arrivals", &"a2".to_string()).await.success, "test: prune the newest"); // test: a fixture step that must succeed + assert_eq!(seq_of(&adapter.batch(vec![append("a3", "m3")]).await), (3, true), "2 is never re-issued"); + assert!(adapter.delete("arrivals", &"a1".to_string()).await.success); + assert!(adapter.delete("arrivals", &"a3".to_string()).await.success, "test: prune to empty"); // test: a fixture step that must succeed + assert_eq!(seq_of(&adapter.batch(vec![append("a4", "m4")]).await), (4, true), "an emptied collection does not restart at 1"); + } + + // what this catches: a rolled-back batch consuming a sequence or announcing a revision + // for a row that never committed (a consumer would wait for, or skip over, a ghost). + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_rolled_back_append_neither_numbers_nor_announces() { + let (adapter, _dir) = arrivals().await; + let revision = adapter.sequence_revision("arrivals"); + let broken = BatchOperation { + operation_type: BatchOperationType::Create, + collection: "arrivals".into(), + id: Some("x".into()), + data: None, + }; + assert!( + !adapter + .batch(vec![append("a1", "m1"), broken]) + .await + .success + ); + assert_eq!( + *revision.borrow(), + 0, + "nothing committed, nothing announced" + ); + assert_eq!( + seq_of(&adapter.batch(vec![append("a1", "m1")]).await), + (1, true), + "the rolled-back sequence is reused" + ); + assert_eq!(*revision.borrow(), 1); + } + + // what this catches: a committed row stranded unannounced because its writer was + // dropped at the commit await (Codex at 2abfa3c3). The future is polled once (the + // blocking write is spawned) and dropped; the revision still rises. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_writer_dropped_at_the_commit_await_still_announces_its_row() { + let (adapter, _dir) = arrivals().await; + let mut revision = adapter.sequence_revision("arrivals"); + let mut write = Box::pin(adapter.batch(vec![append("a1", "m1")])); + let _ = futures::poll!(&mut write); // the first poll spawns the blocking write; whether it has finished does not matter + drop(write); + tokio::time::timeout( + std::time::Duration::from_secs(5), + revision.wait_for(|high| *high == 1), + ) + .await + .expect("test: the dropped writer's commit is announced") // test: the assertion failing loudly + .expect("test: the revision stays owned by the store"); // test: the assertion failing loudly + assert!( + adapter.read("arrivals", &"a1".to_string()).await.success, + "and the row is there" + ); + } + } diff --git a/core/continuum-kernel/src/orm/store.rs b/core/continuum-kernel/src/orm/store.rs index 8419dd7e1e..9ff10c8670 100644 --- a/core/continuum-kernel/src/orm/store.rs +++ b/core/continuum-kernel/src/orm/store.rs @@ -49,7 +49,7 @@ use uuid::Uuid; use crate::orm::adapter::StorageAdapter; use crate::orm::entity::OrmEntity; use crate::orm::query::{QueryBuilder, StorageQuery}; -use crate::orm::types::{BatchOperation, BatchOperationType, DataRecord, RecordMetadata, StorageResult}; +use crate::orm::types::{BatchOperation, BatchOperationType, DataRecord, RecordMetadata, SequenceSpec, Sequenced, StorageResult}; /// Typed failure modes for OrmStore operations. Per [[no-fallbacks- /// ever]] + the typed-error pattern: every failure mode is named so @@ -259,6 +259,27 @@ where }) } + /// The sequenced append of a new row ([`BatchOperationType::Append`]), as the last operation + /// of an atomic [`commit_appending`]. + pub fn append_op( + &self, + id: Uuid, + entity: &T, + spec: SequenceSpec, + ) -> Result { + Ok(BatchOperation { + operation_type: BatchOperationType::Append(spec), + collection: T::COLLECTION.to_string(), + id: Some(id.to_string()), + data: Some(row_data(entity)?), + }) + } + + /// The committed high-water of this collection's sequence: wakes when an append commits. + pub fn sequence_revision(&self) -> tokio::sync::watch::Receiver { + self.adapter.sequence_revision(T::COLLECTION) + } + /// Save `entity` as row `id` unless that row already holds a GREATER `field`: ONE /// atomic backend operation ([`StorageAdapter::upsert_monotonic`]), so the compare /// can never be separated from the write. Returns whether it was written. @@ -299,6 +320,32 @@ pub async fn commit(adapter: &Arc, operations: Vec, + mut prior: Vec, + append: BatchOperation, +) -> Result { + let collection = append.collection.clone(); + prior.push(append); + let values = unwrap_adapter(adapter.batch(prior).await, "batch", "atomic append")?; + values + .last() + .and_then(|v| { + Some(Sequenced { + seq: v.get("seq")?.as_u64()?, + fresh: v.get("fresh")?.as_bool()?, + }) + }) + .ok_or(OrmStoreError::AdapterFailed { + operation: "append", + collection, + detail: "the adapter's append result carried no sequence".to_string(), + }) +} + /// Generic StorageResult unwrap for adapter CRUD operations. fn unwrap_adapter( result: StorageResult, diff --git a/core/continuum-kernel/src/orm/types.rs b/core/continuum-kernel/src/orm/types.rs index e63d00a4e0..0545948f2e 100644 --- a/core/continuum-kernel/src/orm/types.rs +++ b/core/continuum-kernel/src/orm/types.rs @@ -280,6 +280,30 @@ pub enum BatchOperationType { Read, Update, Delete, + /// Create the row unless a row with its id already exists; an existing row is left untouched. + /// An idempotent import: the same line written twice is one row. + Ensure, + /// Create the row with the next value of a commit-ordered sequence, unless a row already + /// holds the same unique value (then nothing is written and that row's sequence is returned). + Append(SequenceSpec), +} + +/// How an [`BatchOperationType::Append`] numbers its row: `sequence` is assigned +/// `max(sequence) + 1` inside the batch's write transaction, so sequence order IS commit order +/// (a row can never be acknowledged past an earlier allocation that commits later); `unique` +/// names the field whose value identifies the row, so a duplicate reuses the first row. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS, schemars::JsonSchema)] +#[ts(export, export_to = "../../../protocol/typescript/orm/SequenceSpec.ts")] +pub struct SequenceSpec { + pub sequence: String, + pub unique: String, +} + +/// What an append did: `fresh` when this batch created the row, otherwise the existing row's. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct Sequenced { + pub seq: u64, + pub fresh: bool, } /// Batch storage operation diff --git a/core/continuum-mind/Cargo.toml b/core/continuum-mind/Cargo.toml index dea1f2f671..5248187c3c 100644 --- a/core/continuum-mind/Cargo.toml +++ b/core/continuum-mind/Cargo.toml @@ -75,6 +75,7 @@ continuum-positron = { path = "../continuum-positron", features = ["test-fixture continuum-genome = { path = "../continuum-genome", features = ["test-fixtures"] } continuum-rooms = { path = "../continuum-rooms", features = ["test-fixtures"] } continuum-experience = { path = "../continuum-experience", features = ["test-fixtures"] } +continuum-cognition = { path = "../continuum-cognition", features = ["test-fixtures"] } # the shared TranscriptEvent fixture (channel_digest::test_event_in) # The real store, so loop tests write obligations through the same data module production uses # (stop-drain S2: a turn runs only on a confirmed obligation). The store sits below the mind. continuum-store = { path = "../continuum-store", features = ["test-fixtures"] } diff --git a/core/continuum-mind/src/chat/arrival.rs b/core/continuum-mind/src/chat/arrival.rs new file mode 100644 index 0000000000..0c7a2f7b49 --- /dev/null +++ b/core/continuum-mind/src/chat/arrival.rs @@ -0,0 +1,161 @@ +//! A room line's ARRIVAL: the store-owned record of when a message became visible to the core, in +//! commit order (PERCEPTION-FROM-THE-STORE.md, Slice P). Written in the SAME transaction as the +//! message row, by every writer of `chat_messages`; a duplicate import of one message reuses its +//! first arrival. The arrival is the header every perception consumer routes on (room, author, +//! kind, addressee) — the message body is never opened to route. + +use airc_core::{MentionTarget, PeerId, RoomId, TranscriptEvent, TranscriptKind}; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use crate::orm::{OrmStoreError, SequenceSpec}; + +/// The collection's sequence and dedupe fields: `arrivalSeq` is assigned in commit order; +/// `messageId` identifies the line, so a second import of it reuses the first arrival. +pub fn arrival_sequence() -> SequenceSpec { + SequenceSpec { + sequence: "arrivalSeq".to_string(), + unique: "messageId".to_string(), + } +} + +/// What kind of room line arrived, from the transport's own kind header. Exhaustive over the +/// kinds a mind can perceive; [`ArrivalKind::of`] decides every transport kind explicitly, so a +/// new one is a compile error here, never a silent default. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ArrivalKind { + Message, + Attachment, + Receipt, + Presence, + System, +} + +impl ArrivalKind { + /// The arrival kind of a transport kind, or `None` for substrate traffic that is not a room + /// line (lifecycle, protocol, board and identity publications). + pub fn of(kind: TranscriptKind) -> Option { + match kind { + TranscriptKind::Message => Some(Self::Message), + TranscriptKind::Attachment => Some(Self::Attachment), + TranscriptKind::Receipt => Some(Self::Receipt), + TranscriptKind::Presence => Some(Self::Presence), + TranscriptKind::System => Some(Self::System), + TranscriptKind::SessionControl + | TranscriptKind::PeerArrived + | TranscriptKind::PeerDeparted + | TranscriptKind::WireEstablished + | TranscriptKind::WireLost + | TranscriptKind::RoomJoined + | TranscriptKind::RoomParted + | TranscriptKind::SubscriptionAdvanced + | TranscriptKind::Command + | TranscriptKind::CommandResult + | TranscriptKind::WallPostPublished + | TranscriptKind::DoctrinePublished + | TranscriptKind::IdentityPublished + | TranscriptKind::ChannelPurposePublished => None, + } + } +} + +/// One arrival: the routing header of one room line, numbered in commit order. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, crate::orm::Entity)] +#[serde(rename_all = "camelCase")] +#[entity(collection = "chat_arrivals")] +#[entity(index(name = "idx_chat_arrivals_message", fields = ["messageId"], unique = true))] +#[entity(index(name = "idx_chat_arrivals_seq", fields = ["arrivalSeq"], unique = true))] +pub struct Arrival { + #[entity(primary_key)] + pub id: Uuid, + /// Commit order; assigned by the store inside the writing transaction, never by a caller + /// (whatever the caller sets is overwritten). + pub arrival_seq: u64, + /// The message row this arrival announces (the chat store's row id). + pub message_id: Uuid, + #[entity(indexed)] + pub room: RoomId, + pub author: PeerId, + pub kind: ArrivalKind, + /// The one peer the line is addressed to, when it is addressed to one. + pub direct_to: Option, +} + +impl Arrival { + /// A new arrival for `message_id` (its sequence is the store's to assign). + pub fn new( + message_id: Uuid, + room: RoomId, + author: PeerId, + kind: ArrivalKind, + direct_to: Option, + ) -> Self { + Self { + id: Uuid::new_v4(), + arrival_seq: 0, + message_id, + room, + author, + kind, + direct_to, + } + } + + /// The arrival of a transport event, read from its header alone (kind, ids, addressee); + /// `None` when the event is not a room line. + pub fn of_event(event: &TranscriptEvent) -> Option { + let kind = ArrivalKind::of(event.kind)?; + let direct_to = match event.target { + MentionTarget::Peer(peer) => Some(peer), + MentionTarget::All | MentionTarget::Room(_) => None, + }; + Some(Self::new( + event.event_id.as_uuid(), + event.room_id, + event.peer_id, + kind, + direct_to, + )) + } + + /// The batch operation that appends this arrival under [`arrival_sequence`]; commit it in the + /// same batch as its message row. + pub fn append_op(&self) -> Result { + Ok(crate::orm::types::BatchOperation { + operation_type: crate::orm::types::BatchOperationType::Append(arrival_sequence()), + collection: ::COLLECTION.to_string(), + id: Some(self.id.to_string()), + data: Some(serde_json::to_value(self).map_err(OrmStoreError::SerializeFailed)?), // storage boundary: the adapter's row format + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // what this catches: routing facts read from anything but the header — an addressed line + // losing its addressee, or a lifecycle event becoming a room line a mind perceives. + #[test] + fn an_arrival_is_read_from_the_transport_header_alone() { + let peer = PeerId::new(); + let mut event = continuum_cognition::cognition::channel_digest::test_event_in( + RoomId::new(), + "hello", + 1, + ); + event.target = MentionTarget::Peer(peer); + let arrival = Arrival::of_event(&event).expect("a message is a room line"); // test: the assertion failing loudly + assert_eq!( + (arrival.kind, arrival.direct_to, arrival.message_id), + (ArrivalKind::Message, Some(peer), event.event_id.as_uuid()) + ); + event.kind = TranscriptKind::PeerArrived; + assert_eq!( + Arrival::of_event(&event), + None, + "lifecycle traffic is not a room line" + ); + } +} diff --git a/core/continuum-mind/src/chat/chat_data_handle.rs b/core/continuum-mind/src/chat/chat_data_handle.rs index a9c1df66b9..520f08f86b 100644 --- a/core/continuum-mind/src/chat/chat_data_handle.rs +++ b/core/continuum-mind/src/chat/chat_data_handle.rs @@ -222,62 +222,28 @@ 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> { - let executor = self.executor()?; let message_id = Uuid::new_v4(); let now_ms = continuum_base::time::EpochMs::now().millis(); - let now_iso = now_iso(now_ms); - - // ── Step 1: persist locally (ground truth) ─────────────────── - // - // Build the entity payload matching `ChatMessageEntity`'s - // expected shape on the TS side — text-only content for this - // first migration, `metadata.source: "user"`, status sent. - // Media + replyToId threading + system messages are deferred. - let entity_data = json!({ - "id": message_id.to_string(), - "roomId": params.room_id.to_string(), - "senderId": params.sender_id.to_string(), - "timestamp": now_iso, - "content": { "text": params.text, "media": params.media }, - "replyToId": params.reply_to_id.map(|u| u.to_string()), - "metadata": { "source": "user" }, - "status": "sent", - }); - - let create_params = json!({ - "dbPath": CHAT_DATA_HANDLE, - "collection": CHAT_MESSAGES_COLLECTION, - "id": message_id.to_string(), - "data": entity_data, - }); - - // Hard failure: data layer didn't store the message. No airc - // publish is attempted — the message doesn't exist locally, - // so broadcasting it would create the bad-divergence case. - // Surface as command-level Err. - let create_result = executor - .execute_json("data/create", create_params) - .await - .map_err(|e| format!("chat/send: data/create failed: {e}"))?; - - // The data module's `data/create` returns - // `{success: true|false, error?: "..."}`. A success=false - // path is the "stored the request but the write didn't land" - // case (validation, unique constraint, etc.) — still hard - // failure from chat's perspective. - if !create_result - .get("success") - .and_then(|v| v.as_bool()) - .unwrap_or(false) - { - let inner = create_result - .get("error") - .and_then(|v| v.as_str()) - .unwrap_or("data module returned success=false without an error message"); - return Err(format!( - "chat/send: data/create returned success=false: {inner}" - )); - } + // 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). + let line = super::line_store::PostedLine { + message_id, + room: airc_core::RoomId::from_uuid(params.room_id), + author: airc_core::PeerId::from_uuid(params.sender_id), + kind: super::arrival::ArrivalKind::Message, + direct_to: None, + occurred_at_ms: now_ms, + text: params.text.clone(), + }; + 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}"))?; Ok((message_id, now_ms)) } @@ -340,76 +306,6 @@ impl ChatModule { } } - /// Persist one `chat:posted` projection into the durable chat store (#140). - /// - /// The projection is the ONE seam every room line crosses — a persona's - /// `say()` and a human/web `chat/send` alike — so persisting here makes the - /// transcript durable for BOTH speakers with one writer. Idempotent by id: - /// a human line was already stored by `send()` under the same `messageId` - /// (the envelope carries it through the projection), so the second write - /// reports `success=false` (unique id) and is skipped with a probe — an - /// EXPECTED duplicate, never an error. A persona line's id is airc's - /// `event_id` (stable across replay), so restarts can't double-store either. - pub async fn persist_posted(&self, payload: Value) -> Result<(), String> { - let executor = self.executor()?; - let field = |k: &str| -> Result { - payload - .get(k) - .and_then(Value::as_str) - .map(String::from) - .ok_or_else(|| format!("chat:posted payload missing `{k}`: {payload}")) - }; - let message_id = field("messageId")?; - let room_id = field("roomId")?; - let sender_id = field("senderId")?; - let content = field("content")?; - let occurred_at_ms = payload - .get("timestamp") - .and_then(Value::as_u64) - .ok_or_else(|| format!("chat:posted payload missing `timestamp`: {payload}"))?; - let iso = now_iso(occurred_at_ms); - - // Same ChatMessageEntity shape `send()` writes — one entity, two writers - // converging on one row id. `metadata.source: "user"` for both: personas - // are citizens (users), not system lines; WHO spoke is `senderId`. - let entity_data = json!({ - "id": message_id, - "roomId": room_id, - "senderId": sender_id, - "timestamp": iso, - "content": { "text": content }, - "replyToId": null, - "metadata": { "source": "user" }, - "status": "sent", - }); - let create_params = json!({ - "dbPath": CHAT_DATA_HANDLE, - "collection": CHAT_MESSAGES_COLLECTION, - "id": message_id, - "data": entity_data, - }); - let result = executor - .execute_json("data/create", create_params) - .await - .map_err(|e| format!("chat:posted persist: data/create failed: {e}"))?; - if result.get("success").and_then(Value::as_bool) != Some(true) { - // Almost always the send()-already-stored duplicate (same id). Keep it - // visible-but-calm: one probe line, never a hard error — a projector - // that errors on every human message would drown real faults. - let detail = result - .get("error") - .and_then(serde_json::Value::as_str) - .unwrap_or("success=false"); - continuum_base::probe!( - class = "chat.persist.skipped", - message_id = message_id.as_str(), - detail = detail, - "chat:posted row not written (duplicate id or store refusal)" - ); - } - Ok(()) - } - /// #265: seed the repetition-perception speech rings from the durable /// transcript at boot. The rings (`record_room_speech` / /// `record_own_speech`) are in-process statics, so a reboot wipes them at @@ -417,7 +313,7 @@ impl ChatModule { /// every persona re-emits its greeting 2+ times with the repetition and /// [settled] facts blind (observed live 2026-07-30, twice). The durable /// store (#140) already holds the history; this replays the latest - /// `RING_HYDRATION_SCAN` lines (chronological, all rooms — each ring keeps + /// lines of one `chat/poll` page (chronological, all rooms — each ring keeps /// only its own bounded tail) so the facts have priors from the first tick. /// /// Waits boundedly for the executor slot — this runs from the persist @@ -425,7 +321,6 @@ impl ChatModule { /// `install_executor_on_all` (the #201 ordering); a missing executor here /// is a not-yet, not a bug, so we poll the slot instead of panicking. pub async fn hydrate_speech_rings(&self) -> Result<(), String> { - const RING_HYDRATION_SCAN: usize = 200; const EXECUTOR_WAIT: std::time::Duration = std::time::Duration::from_secs(15); const EXECUTOR_POLL: std::time::Duration = std::time::Duration::from_millis(250); @@ -444,13 +339,14 @@ impl ChatModule { room_id: None, after_message_id: None, before_message_id: None, - limit: Some(RING_HYDRATION_SCAN), + // One page, the poll's own (each ring keeps only its own bounded tail). + limit: None, }) .await?; let mut seeded = 0usize; for msg in &result.messages { - // Stored ChatMessageEntity shape (see `persist_posted`): roomId, + // Stored ChatMessageEntity shape (see `line_store::commit_line`): roomId, // senderId, content.text. Malformed rows are skipped, not fatal — // hydration is best-effort priors, never a boot gate. let room = msg @@ -498,53 +394,22 @@ impl Default for ChatModule { } } -/// Spawn the durable-transcript writer (#140): a bus-receiver task (same shape as -/// `cognition::dispatch_listener::spawn`) that persists every `chat:posted` projection — -/// the ONE seam a persona's `say()` and a human/web `chat/send` both cross — into the -/// chat store via [`ChatModule::persist_posted`]. This is a receiver task rather than a -/// module `event_subscription` because `chat:posted` is published with -/// `publish_async_only`, which feeds only the broadcast channel; module subscriptions -/// are dispatched exclusively by the synchronous `publish(..., registry)` path. +/// Install the chat module as the inbound seam's line importer and seed the repetition-fact +/// speech rings from the durable transcript (#265). The importer is the durable-transcript writer +/// now: the inbound seam AWAITS each line's import (`line_store::import`), where it used to ride +/// a lossy broadcast receiver whose lag silently dropped lines from the store. /// -/// Spawned from `ChatModule::initialize` on the ModuleContext's runtime HANDLE — -/// registration runs on a non-tokio thread, and a bare `tokio::spawn` there panics the -/// boot ("no reactor running", observed live 2026-07-16). Idempotent per process: -/// initialize runs once per module. -pub fn spawn_persist_listener( - handle: &tokio::runtime::Handle, - bus: Arc, - module: Arc, -) { - let mut rx = bus.receiver(); +/// Spawned from `ChatModule::initialize` on the ModuleContext's runtime HANDLE (registration runs +/// on a non-tokio thread; a bare `tokio::spawn` there panics the boot, 2026-07-16). +pub fn install_line_importer(handle: &tokio::runtime::Handle, module: Arc) { + super::line_store::install_importer(Arc::clone(&module)); handle.spawn(async move { - // #265: seed the repetition-fact speech rings from the durable - // transcript BEFORE consuming live events — a reboot wipes the - // in-process rings exactly when the wake-greeting round needs them. - // The subscription above is already live, so no line is missed while - // we hydrate; a hydration failure degrades to cold rings, loudly. if let Err(error) = module.hydrate_speech_rings().await { tracing::warn!( error, "speech-ring hydration failed — repetition facts start cold this boot (#265)" ); } - loop { - let event = match rx.recv().await { - Ok(e) => e, - // Lagged (slow consumer) — keep going; a persisted line missed under lag - // is recoverable on the next send, and the store is not the wire. - Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue, - Err(tokio::sync::broadcast::error::RecvError::Closed) => return, - }; - if event.name != crate::chat::CHAT_POSTED { - continue; - } - if let Err(error) = module.persist_posted((*event.payload).clone()).await { // persist consumes an owned Value; one copy at the boundary - // Loud but non-fatal: one malformed payload must not kill the - // transcript writer for the rest of the process lifetime. - tracing::warn!(error, "chat:posted persist failed (#140)"); - } - } }); } diff --git a/core/continuum-mind/src/chat/chat_module.rs b/core/continuum-mind/src/chat/chat_module.rs index b1de939f22..b8c78a6b69 100644 --- a/core/continuum-mind/src/chat/chat_module.rs +++ b/core/continuum-mind/src/chat/chat_module.rs @@ -11,15 +11,9 @@ impl ServiceModule for ChatModule { // legacy path that TS commands still use today and will // keep working through this module while consumers migrate. command_prefixes: &["chat/", "collaboration/chat/"], - // Chat doesn't use module event_subscriptions. The durable- - // transcript writer (#140) rides `spawn_persist_listener` (a bus - // receiver task, same shape as cognition::dispatch_listener) - // because `chat:posted` is published via `publish_async_only`, - // which feeds ONLY the broadcast channel — module subscriptions - // are dispatched exclusively by the synchronous `publish(..., - // registry)` path, so a subscription here would be dead wiring - // (verified against message_bus.rs before wiring; the - // "deferred tier" its docs mention is not built). + // Chat doesn't use module event_subscriptions: the durable-transcript writer + // (#140) is the inbound seam's awaited import (`line_store::import`), never a + // bus subscription that could lag and drop a line. event_subscriptions: &[], needs_dedicated_thread: false, max_concurrency: 0, @@ -28,15 +22,10 @@ impl ServiceModule for ChatModule { } async fn initialize(&self, ctx: &crate::runtime::ModuleContext) -> Result<(), String> { - // #140: the durable-transcript writer — persists every `chat:posted` - // projection (persona say + human chat/send, the one seam both cross). - // Spawned here (inside the runtime) rather than at registration, which - // runs on a non-tokio thread. `from_slot` shares this module's - // late-bound executor, filled by install_executor_on_all before any - // event can arrive from a live room. - spawn_persist_listener( + // #140: the durable-transcript writer is the inbound seam's awaited import through this + // module (`line_store::import`); `from_slot` shares this module's late-bound executor. + install_line_importer( &ctx.runtime, - ctx.bus.clone(), Arc::new(ChatModule::from_slot(self.executor_slot.clone())), ); Ok(()) diff --git a/core/continuum-mind/src/chat/import_watermark.rs b/core/continuum-mind/src/chat/import_watermark.rs new file mode 100644 index 0000000000..e416dcb165 --- /dev/null +++ b/core/continuum-mind/src/chat/import_watermark.rs @@ -0,0 +1,165 @@ +//! How far the chat store has imported each room from airc: the attach watermark, a durable +//! acceptance identity (PERCEPTION-FROM-THE-STORE.md, Slice P). It lives in the store beside the +//! lines it vouches for, written through the ORM, keyed by the room, with a typed history saying +//! what it vouches for before it. + +use airc_core::RoomId; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use uuid::Uuid; + +use super::chat_data_handle::{ChatModule, CHAT_DATA_HANDLE}; +use crate::orm::types::{BatchOperation, BatchOperationType}; + +/// A position in a room's airc transcript (the daemon's cursor), typed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ImportWatermark { + pub epoch: u64, + pub counter: u64, + pub event_id: Uuid, +} + +/// Whether every line before the watermark is in the store. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case", tag = "history")] +pub enum ImportHistory { + /// Every line up to the watermark was imported through the awaited seam. + Complete, + /// The watermark was migrated from the pre-store cursor file, which advanced independently of + /// the old lossy writer: lines at or before this position may be missing from the store (Codex + /// on #5694). A reader of that history perceives a gap; it is never vouched for. + UnvouchedThrough { + epoch: u64, + counter: u64, + event_id: Uuid, + }, +} + +/// How far the store has imported a room, and what it vouches for before that. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ImportedThrough { + pub position: ImportWatermark, + pub history: ImportHistory, +} + +/// One room's import watermark row; its id IS the room. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, crate::orm::Entity)] +#[serde(rename_all = "camelCase")] +#[entity(collection = "chat_import_watermarks")] +pub struct ImportWatermarkRow { + #[entity(primary_key)] + pub id: Uuid, + pub epoch: u64, + pub counter: u64, + pub event_id: Uuid, + pub history: ImportHistory, +} + +const COLLECTION: &str = "chat_import_watermarks"; + +impl ChatModule { + /// The room's watermark and history, or `None` when the store has never imported it. + pub(super) async fn import_watermark( + &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 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, + counter: row.counter, + event_id: row.event_id, + }, + history: row.history, + })) + } + + /// Advance the room's watermark (a position already delivered and imported). A new row's + /// history is complete; an existing row keeps its history, so a migrated room stays unvouched + /// before its migration point however far it advances. + pub(super) async fn advance_import_watermark( + &self, + room: RoomId, + mark: ImportWatermark, + ) -> Result<(), String> { + let full = row_value(room, mark, ImportHistory::Complete)?; + let position = + json!({ "epoch": mark.epoch, "counter": mark.counter, "eventId": mark.event_id }); + self.write_watermark( + room, + vec![ + (BatchOperationType::Ensure, full), + (BatchOperationType::Update, position), + ], + ) + .await + } + + /// Record a watermark migrated from the pre-store cursor file: unvouched through that position. + pub(super) async fn migrate_import_watermark( + &self, + room: RoomId, + mark: ImportWatermark, + ) -> Result<(), String> { + let history = ImportHistory::UnvouchedThrough { + epoch: mark.epoch, + counter: mark.counter, + event_id: mark.event_id, + }; + self.write_watermark( + room, + vec![(BatchOperationType::Ensure, row_value(room, mark, history)?)], + ) + .await + } + + async fn write_watermark( + &self, + room: RoomId, + writes: Vec<(BatchOperationType, Value)>, + ) -> Result<(), String> { + let executor = self.executor()?; + let operations: Vec = writes + .into_iter() + .map(|(operation_type, data)| BatchOperation { + operation_type, + collection: COLLECTION.to_string(), + id: Some(room.as_uuid().to_string()), + 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}")), + } + } +} + +fn row_value(room: RoomId, mark: ImportWatermark, history: ImportHistory) -> Result { + let row = ImportWatermarkRow { + id: room.as_uuid(), + epoch: mark.epoch, + counter: mark.counter, + event_id: mark.event_id, + history, + }; + serde_json::to_value(&row).map_err(|e| format!("import watermark: {e}")) // storage boundary: the adapter's row format +} diff --git a/core/continuum-mind/src/chat/line_store.rs b/core/continuum-mind/src/chat/line_store.rs new file mode 100644 index 0000000000..fa24666453 --- /dev/null +++ b/core/continuum-mind/src/chat/line_store.rs @@ -0,0 +1,252 @@ +//! The ONE write path of a room line into the chat store: the message row and its [`Arrival`], +//! committed together in one batch (PERCEPTION-FROM-THE-STORE.md, Slice P). Two writers use it: +//! a human `chat/send` (a new line) and the inbound airc seam (an import, idempotent by id, so a +//! replay after a crash commits without a second row or arrival). + +use airc_core::{PeerId, RoomId}; +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::import_watermark::{ImportHistory, ImportWatermark, ImportedThrough}; +use super::types::CHAT_MESSAGES_COLLECTION; +use crate::orm::types::{BatchOperation, BatchOperationType}; +use crate::runtime::late_bound::LateBound; + +/// A room line, typed: the routing header and the text, never a JSON payload to fish fields from. +#[derive(Debug, Clone, PartialEq)] +pub struct PostedLine { + pub message_id: Uuid, + pub room: RoomId, + pub author: PeerId, + pub kind: ArrivalKind, + pub direct_to: Option, + pub occurred_at_ms: u64, + pub text: String, +} + +/// Where a line landed in arrival order. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Imported { + /// This write created the line, at this arrival. + Fresh { arrival_seq: u64 }, + /// The line was already stored; its existing arrival. + 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"); + +pub(super) fn install_importer(module: std::sync::Arc) { + IMPORTER.install(module); +} + +/// Where the inbound seam stores the lines it receives. Injected into the seam, so production +/// writes the chat store and a test records what the seam would have written. +#[async_trait::async_trait] +pub trait LineImporter: Send + Sync { + /// Store `line` (idempotent by its id); awaited, so the attach watermark never passes a line + /// the store has not committed. + async fn import(&self, line: PostedLine) -> Result; + + /// How far the store has imported `room` from airc; `None` when it never has. + async fn watermark(&self, room: RoomId) -> Result, String>; + + /// Record how far the store has imported `room` (a position already delivered and imported). + async fn advance_watermark(&self, room: RoomId, mark: ImportWatermark) -> Result<(), String>; + + /// Record a position migrated from the pre-store cursor file: unvouched through it. + async fn migrate_watermark(&self, room: RoomId, mark: ImportWatermark) -> Result<(), String>; +} + +/// The chat store, as the inbound seam's importer: the installed chat module, resolved at each +/// import (before it is installed an import fails, and the seam re-attaches and replays). +pub struct ChatStore; + +#[async_trait::async_trait] +impl LineImporter for ChatStore { + async fn import(&self, line: PostedLine) -> Result { + installed()? + .commit_line(&line, LineWrite::Import, None, json!({ "text": line.text })) + .await + } + + async fn watermark(&self, room: RoomId) -> Result, String> { + installed()?.import_watermark(room).await + } + + async fn advance_watermark(&self, room: RoomId, mark: ImportWatermark) -> Result<(), String> { + installed()?.advance_import_watermark(room, mark).await + } + + async fn migrate_watermark(&self, room: RoomId, mark: ImportWatermark) -> Result<(), String> { + installed()?.migrate_import_watermark(room, mark).await + } +} + +fn installed() -> Result, String> { + IMPORTER + .cloned() + .ok_or_else(|| "chat store: the chat module is not installed yet (early boot)".to_string()) +} + +/// 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>, +); + +#[cfg(any(test, feature = "test-fixtures"))] +#[async_trait::async_trait] +impl LineImporter for RecordingImporter { + async fn import(&self, line: PostedLine) -> Result { + let mut lines = self.0.lock().unwrap_or_else(|p| p.into_inner()); // test fixture: a poisoned lock still holds the lines recorded + lines.push(line); + Ok(Imported::Fresh { + arrival_seq: lines.len() as u64, + }) + } + + async fn watermark(&self, room: RoomId) -> Result, String> { + Ok(self + .1 + .lock() + .unwrap_or_else(|p| p.into_inner()) + .get(&room) + .copied()) // test fixture: a poisoned lock still holds the marks + } + + async fn advance_watermark(&self, room: RoomId, mark: ImportWatermark) -> Result<(), String> { + let mut marks = self.1.lock().unwrap_or_else(|p| p.into_inner()); // test fixture: a poisoned lock still holds the marks + let history = marks + .get(&room) + .map_or(ImportHistory::Complete, |m| m.history); + marks.insert( + room, + ImportedThrough { + position: mark, + history, + }, + ); + Ok(()) + } + + async fn migrate_watermark(&self, room: RoomId, mark: ImportWatermark) -> Result<(), String> { + let history = ImportHistory::UnvouchedThrough { + epoch: mark.epoch, + counter: mark.counter, + event_id: mark.event_id, + }; + self.1.lock().unwrap_or_else(|p| p.into_inner()).insert( + room, + ImportedThrough { + position: mark, + history, + }, + ); // test fixture: a poisoned lock still holds the marks + Ok(()) + } +} + +impl ChatModule { + /// Commit `line`'s message row and its arrival in ONE batch. + 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 arrival = Arrival::new( + line.message_id, + line.room, + line.author, + line.kind, + 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 appended = result + .get("data") + .and_then(|d| d.get(1)) + .ok_or("chat line: the batch reported no arrival")?; + let arrival_seq = appended + .get("seq") + .and_then(Value::as_u64) + .ok_or("chat line: the arrival carried no sequence")?; + match appended.get("fresh").and_then(Value::as_bool) { + Some(true) => Ok(Imported::Fresh { arrival_seq }), + Some(false) => Ok(Imported::Duplicate { arrival_seq }), + // An append that does not say whether it created the arrival is a malformed reply, never a + // duplicate: reading it as one would vouch for a line nobody confirmed (Codex on #5694). + None => Err("chat line: the arrival did not say whether it was fresh".to_string()), + } + } +} + +/// Refuses every import: the seam's test importer for a store that cannot write. +#[cfg(any(test, feature = "test-fixtures"))] +pub struct RefusingImporter; + +#[cfg(any(test, feature = "test-fixtures"))] +#[async_trait::async_trait] +impl LineImporter for RefusingImporter { + async fn import(&self, _line: PostedLine) -> Result { + Err("test: the store refused the line".to_string()) + } + + async fn watermark(&self, _room: RoomId) -> Result, String> { + Err("test: the store cannot read".to_string()) + } + + async fn advance_watermark(&self, _room: RoomId, _mark: ImportWatermark) -> Result<(), String> { + Err("test: the store refused the watermark".to_string()) + } + + async fn migrate_watermark(&self, _room: RoomId, _mark: ImportWatermark) -> Result<(), String> { + Err("test: the store refused the watermark".to_string()) + } +} diff --git a/core/continuum-mind/src/chat/mod.rs b/core/continuum-mind/src/chat/mod.rs index 277f2eb37c..8b24c6439f 100644 --- a/core/continuum-mind/src/chat/mod.rs +++ b/core/continuum-mind/src/chat/mod.rs @@ -59,6 +59,10 @@ pub const CHAT_POSTED: &str = "chat:posted"; use types::{ChatPollParams, ChatPollResult, ChatSendParams, ChatSendResult, CHAT_MESSAGES_COLLECTION, DEFAULT_POLL_LIMIT}; +pub mod arrival; +pub mod line_store; +pub mod import_watermark; +pub mod orm_entities; mod chat_data_handle; pub use chat_data_handle::*; mod chat_module; diff --git a/core/continuum-mind/src/chat/orm_entities.rs b/core/continuum-mind/src/chat/orm_entities.rs new file mode 100644 index 0000000000..6265971d24 --- /dev/null +++ b/core/continuum-mind/src/chat/orm_entities.rs @@ -0,0 +1,18 @@ +//! The chat store's Rust-authored ORM entities, registered by the chat module itself (never by a +//! sibling that would import chat and close a module loop). + +/// Every collection [`register_chat_orm_entities`] registers. +pub const CHAT_ORM_COLLECTIONS: &[&str] = &[ + ::COLLECTION, + ::COLLECTION, +]; + +/// Register the chat store's entities (arrivals with their unique indexes; import watermarks). +/// Idempotent; a conflicting shape refuses boot. +pub fn register_chat_orm_entities( + registry: &crate::orm::OrmEntityRegistry, +) -> Result<(), crate::orm::RegistrationError> { + registry.register::()?; + registry.register::()?; + Ok(()) +} diff --git a/core/continuum-mind/src/chat/tests/mod.rs b/core/continuum-mind/src/chat/tests/mod.rs index 60417967a0..c80c0c8829 100644 --- a/core/continuum-mind/src/chat/tests/mod.rs +++ b/core/continuum-mind/src/chat/tests/mod.rs @@ -32,7 +32,7 @@ /// Stub data module: handles any `data/*` command by returning a /// canned response built by the test's closure. The closure /// receives BOTH the command name and the params so tests can - /// branch on command (`data/query` vs `data/create` etc.) or + /// branch on command (`data/query` vs `data/batch` etc.) or /// inspect the inbound shape. /// /// `chat/poll` tests use the params-only `Self::query_only` @@ -102,131 +102,146 @@ } // ── config + dispatch ──────────────────────────────────────────── - // what this catches: #140/#177 — the durable-transcript writer. A projected - // chat:posted line (a persona's spoken reply — the shape that was an - // airc+positron-only ghost, invisible to chat/poll, LIGHTHOUSE diagnosis - // 2026-07-16) must land in the chat store as a ChatMessageEntity row under the - // projection's messageId, with the logical sender and ISO timestamp. If this - // write disappears, persona speech stops surviving the process again. + /// The `data/batch` reply the store gives a committed line: the message row, then its + /// arrival at sequence 1. ONE construction site for every chat test's data stub. + pub(super) fn batch_ok() -> Value { + json!({ "success": true, "data": [{ "success": true }, { "success": true, "seq": 1, "fresh": true }] }) + } + + fn imported_line(text: &str) -> crate::chat::line_store::PostedLine { + crate::chat::line_store::PostedLine { + message_id: Uuid::new_v4(), + room: airc_core::RoomId::new(), + author: airc_core::PeerId::new(), + kind: crate::chat::arrival::ArrivalKind::Message, + direct_to: Some(airc_core::PeerId::new()), + occurred_at_ms: 1_784_227_923_000, + text: text.to_string(), + } + } + + // what this catches: #140/#177 and Slice P — a room line imported from the inbound seam + // must land as ONE atomic batch: the ChatMessageEntity row (ensured, so a replay is + // idempotent) and its arrival carrying the typed routing header. If either half goes + // missing, persona speech stops surviving the process or stops being perceivable in order. #[tokio::test] - pub(super) async fn chat_posted_event_persists_a_persona_line_into_the_store() { + pub(super) async fn an_imported_line_commits_its_row_and_arrival_in_one_batch() { let seen: Arc>> = Arc::new(Mutex::new(Vec::new())); let seen_in = seen.clone(); let data = StubDataModule::new(move |command, params| { - assert_eq!(command, "data/create", "persist path must write, not query"); + assert_eq!(command, "data/batch", "a line is one atomic batch"); seen_in.lock().unwrap().push(params); - Ok(json!({ "success": true })) + Ok(batch_ok()) }); let chat = chat_with_stubs(vec![Arc::new(data)]); - - let message_id = Uuid::new_v4(); - let sender = Uuid::new_v4(); - let room = Uuid::new_v4(); - chat.persist_posted(json!({ - "messageId": message_id, - "roomId": room, - "senderId": sender, - "content": "I see the word LIGHTHOUSE in the room.", - "timestamp": 1_784_227_923_000u64, - })) - .await - .expect("persist path succeeds"); - - let calls = seen.lock().unwrap(); + 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 }), + ) + .await + .expect("the import commits"); assert_eq!( - calls.len(), - 1, - "exactly one durable write per projected line" + imported, + crate::chat::line_store::Imported::Fresh { arrival_seq: 1 } ); - let p = &calls[0]; - assert_eq!(p["collection"], CHAT_MESSAGES_COLLECTION); - assert_eq!(p["id"], message_id.to_string()); + let calls = seen.lock().unwrap(); + assert_eq!(calls.len(), 1, "exactly one durable write per line"); + let [row, arrival] = calls[0]["operations"] + .as_array() + .expect("operations") + .as_slice() + else { + panic!("a line is exactly its row and its arrival: {}", calls[0]); + }; assert_eq!( - p["data"]["senderId"], - sender.to_string(), - "logical speaker attributed" + row["operationType"], "ensure", + "an import never fails on a line already stored" ); + assert_eq!(row["collection"], CHAT_MESSAGES_COLLECTION); + assert_eq!(row["data"]["senderId"], line.author.as_uuid().to_string()); assert_eq!( - p["data"]["content"]["text"], + row["data"]["content"]["text"], "I see the word LIGHTHOUSE in the room." ); - assert!( - p["data"]["timestamp"] - .as_str() - .unwrap_or("") - .starts_with("2026-"), - "airc occurred_at_ms rendered as the ISO timestamp the entity carries: {}", - p["data"]["timestamp"] + assert!(row["data"]["timestamp"] + .as_str() + .unwrap_or("") + .starts_with("2026-")); + assert_eq!(arrival["collection"], "chat_arrivals"); + assert_eq!(arrival["data"]["messageId"], line.message_id.to_string()); + assert_eq!(arrival["data"]["kind"], "message"); + assert_eq!( + arrival["data"]["directTo"], + json!(line.direct_to.map(|p| p.as_uuid())), + "the addressee rides the header" ); } - // what this catches: idempotence of the two-writer convergence. A HUMAN line is - // stored by send() first and then arrives again via its own projection under the - // SAME messageId — the store refuses the duplicate (success=false) and the - // projector must treat that as the expected no-op, never an error (an erroring - // projector would fire on every human message and drown real faults). + // what this catches: the two-writer convergence. A human line stored by send() arrives + // again through its own projection under the SAME id: the import commits and reports the + // existing arrival, never an error and never a second arrival. #[tokio::test] - pub(super) async fn duplicate_projection_of_a_sent_message_is_a_calm_no_op() { - let data = StubDataModule::new(move |command, _params| { - assert_eq!(command, "data/create"); - Ok(json!({ "success": false, "error": "unique constraint: id exists" })) + pub(super) async fn a_duplicate_import_reports_its_existing_arrival() { + let data = StubDataModule::new(|_command, _params| { + Ok( + json!({ "success": true, "data": [{ "success": true, "created": false }, { "success": true, "seq": 7, "fresh": false }] }), + ) }); let chat = chat_with_stubs(vec![Arc::new(data)]); - chat.persist_posted(json!({ - "messageId": Uuid::new_v4(), - "roomId": Uuid::new_v4(), - "senderId": Uuid::new_v4(), - "content": "already stored by send()", - "timestamp": 1_784_227_923_000u64, - })) - .await - .expect("a duplicate row is an EXPECTED no-op, not an error"); + 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 }), + ) + .await + .expect("a duplicate is a committed import"); + assert_eq!( + imported, + crate::chat::line_store::Imported::Duplicate { arrival_seq: 7 } + ); } - // what this catches: THE WIRING, not just the logic (the dead-subscription trap this - // slice nearly shipped). `chat:posted` is published via `publish_async_only`, which - // NEVER dispatches module event_subscriptions — so the durable-transcript writer must - // be a live bus-receiver task. This publishes through the exact same call the - // projector uses and asserts the row write actually happens. If someone "simplifies" - // the listener back into event_subscriptions, this goes red instead of persona speech - // silently going ghost again. + // what this catches: an append reply that does not say whether it created the arrival being + // read as a duplicate, vouching for a line nobody confirmed (Codex on #5694). #[tokio::test] - pub(super) async fn persist_listener_receives_async_published_chat_posted() { - use std::time::Duration; - let seen: Arc>> = Arc::new(Mutex::new(Vec::new())); - let seen_in = seen.clone(); - let data = StubDataModule::new(move |command, params| { - assert_eq!(command, "data/create"); - seen_in.lock().unwrap().push(params); - Ok(json!({ "success": true })) - }); - let chat = Arc::new(chat_with_stubs(vec![Arc::new(data)])); - let bus = Arc::new(crate::runtime::message_bus::MessageBus::new()); - // receiver created before publish; the tokio::test runtime is the handle - spawn_persist_listener(&tokio::runtime::Handle::current(), bus.clone(), chat); - - bus.publish_async_only( - crate::chat::CHAT_POSTED, - json!({ - "messageId": Uuid::new_v4(), - "roomId": Uuid::new_v4(), - "senderId": Uuid::new_v4(), - "content": "spoken by a persona", - "timestamp": 1_784_227_923_000u64, - }), - ); + pub(super) async fn an_append_reply_without_freshness_is_an_error() { + let data = StubDataModule::new(|_command, _params| Ok(json!({ "success": true, "data": [{ "success": true }, { "success": true, "seq": 3 }] }))); + 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 })) + .await + .expect_err("a reply without freshness is malformed"); + assert!(err.contains("did not say whether it was fresh"), "named: {err}"); + } - for _ in 0..100 { - if !seen.lock().unwrap().is_empty() { - break; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - assert_eq!( - seen.lock().unwrap().len(), - 1, - "the listener must persist the async-published room line" - ); + // what this catches: a store refusal swallowed as a calm skip. The import is awaited by the + // inbound seam so the attach watermark never passes a line the store lacks; a refusal must + // therefore be an error the seam sees, never a quiet probe. + #[tokio::test] + pub(super) async fn a_refused_import_is_an_error() { + let data = StubDataModule::new(|_command, _params| { + Ok(json!({ "success": false, "error": "disk full" })) + }); + 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 }), + ) + .await + .expect_err("a refusal is an error"); + assert!(err.contains("disk full"), "the cause is named: {err}"); } #[test] @@ -599,10 +614,10 @@ let chat = chat_with_stubs(vec![ Arc::new(StubDataModule::new(|cmd, _p| { assert_eq!( - cmd, "data/create", + cmd, "data/batch", "happy path only writes (no other data ops)" ); - Ok(json!({ "success": true })) + Ok(batch_ok()) })), Arc::new(StubAircModule::ok(airc_ok_response("evt-happy-001"))), ]); @@ -641,10 +656,10 @@ let sent = media.clone(); let chat = chat_with_stubs(vec![ Arc::new(StubDataModule::new(move |cmd, p| { - assert_eq!(cmd, "data/create"); - assert_eq!(p["data"]["content"]["media"], json!([stored])); - assert_eq!(p["data"]["content"]["text"], "Look at the page"); - Ok(json!({ "success": true })) + assert_eq!(cmd, "data/batch"); + assert_eq!(p["operations"][0]["data"]["content"]["media"], json!([stored])); + assert_eq!(p["operations"][0]["data"]["content"]["text"], "Look at the page"); + Ok(batch_ok()) })), Arc::new(StubAircModule::with(move |p| { assert_eq!(p["envelope"]["payload"]["payload"]["inline"]["media"], json!([sent])); diff --git a/core/continuum-mind/src/chat/tests/part_2.rs b/core/continuum-mind/src/chat/tests/part_2.rs index d44a83b4a8..65c1f44e16 100644 --- a/core/continuum-mind/src/chat/tests/part_2.rs +++ b/core/continuum-mind/src/chat/tests/part_2.rs @@ -6,7 +6,7 @@ use super::*; pub(super) async fn send_with_airc_failure_returns_warning_and_null_event_id() { let chat = chat_with_stubs(vec![ Arc::new(StubDataModule::new(|_cmd, _p| { - Ok(json!({ "success": true })) + Ok(batch_ok()) })), Arc::new(StubAircModule::err( "airc daemon socket unreachable: ENOENT", @@ -70,7 +70,7 @@ use super::*; .expect_err("data executor failure must propagate as command-level Err"); assert!( - err.contains("chat/send: data/create failed"), + err.contains("chat/send: chat line: 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("success=false"), + err.contains("the store refused the line"), "error must name the failure mode: {err}" ); assert!( @@ -139,10 +139,10 @@ use super::*; let chat = chat_with_stubs(vec![ Arc::new(StubDataModule::new(move |cmd, _p| { - if cmd == "data/create" { - data_log.lock().unwrap().push("data/create"); + if cmd == "data/batch" { + data_log.lock().unwrap().push("data/batch"); } - Ok(json!({ "success": true })) + Ok(batch_ok()) })), Arc::new(StubAircModule::with(move |_p| { airc_log.lock().unwrap().push("airc/realtime-publish"); @@ -157,7 +157,7 @@ use super::*; let calls = call_log.lock().unwrap().clone(); assert_eq!( calls, - vec!["data/create", "airc/realtime-publish"], + vec!["data/batch", "airc/realtime-publish"], "data MUST be called before airc — the dual-write ordering invariant" ); } @@ -178,10 +178,10 @@ use super::*; let chat = chat_with_stubs(vec![ Arc::new(StubDataModule::new(move |cmd, params| { - if cmd == "data/create" { + if cmd == "data/batch" { *observer.lock().unwrap() = Some(params); } - Ok(json!({ "success": true })) + Ok(batch_ok()) })), Arc::new(StubAircModule::ok(airc_ok_response("evt-wire-001"))), ]); @@ -201,20 +201,20 @@ use super::*; .lock() .unwrap() .clone() - .expect("data/create must have been called"); + .expect("data/batch must have been called"); assert_eq!( create["dbPath"], "main", "writes go to the main adapter handle" ); - assert_eq!(create["collection"], "chat_messages"); + assert_eq!(create["operations"][0]["collection"], "chat_messages"); assert_eq!( - create["id"], + create["operations"][0]["id"], result.message_id.to_string(), "create.id matches the returned message_id" ); - let entity = &create["data"]; + let entity = &create["operations"][0]["data"]; assert_eq!(entity["id"], result.message_id.to_string()); assert_eq!(entity["roomId"], room_id.to_string()); assert_eq!(entity["senderId"], sender_id.to_string()); @@ -250,7 +250,7 @@ use super::*; let chat = chat_with_stubs(vec![ Arc::new(StubDataModule::new(|_cmd, _p| { - Ok(json!({ "success": true })) + Ok(batch_ok()) })), Arc::new(StubAircModule::with(move |params| { *observer.lock().unwrap() = Some(params); @@ -366,12 +366,12 @@ use super::*; let chat = chat_with_stubs(vec![ Arc::new(StubDataModule::new(move |cmd, params| { - if cmd == "data/create" { - let id_str = params["id"].as_str().expect("data/create must carry an id"); + if cmd == "data/batch" { + let id_str = params["operations"][0]["id"].as_str().expect("data/batch must carry the message id"); let id = Uuid::parse_str(id_str).expect("id must be a UUID"); writes_tracker.lock().unwrap().push(id); } - Ok(json!({ "success": true })) + Ok(batch_ok()) })), Arc::new(StubAircModule::ok(airc_ok_response("evt-conc-001"))), ]); @@ -410,7 +410,7 @@ use super::*; assert_eq!( writes.lock().unwrap().len(), PARALLEL, - "every concurrent send must have called data/create exactly once" + "every concurrent send must have called data/batch exactly once" ); // Returned ids are all distinct. @@ -435,7 +435,7 @@ use super::*; /// Per-call ordering invariant under concurrency: even when N /// concurrent calls interleave globally, EACH call's own - /// `data/create` must precede its own `airc/realtime-publish`. The + /// `data/batch` must precede its own `airc/realtime-publish`. The /// dual-write design's bad-divergence safety net depends on this. /// /// Strategy: tag every observation with the `message_id` (== the @@ -451,12 +451,12 @@ use super::*; let chat = chat_with_stubs(vec![ Arc::new(StubDataModule::new(move |cmd, params| { - if cmd == "data/create" { - let id_str = params["id"].as_str().unwrap(); + if cmd == "data/batch" { + let id_str = params["operations"][0]["id"].as_str().unwrap(); let id = Uuid::parse_str(id_str).unwrap(); - data_log.lock().unwrap().push((id, "data/create")); + data_log.lock().unwrap().push((id, "data/batch")); } - Ok(json!({ "success": true })) + Ok(batch_ok()) })), Arc::new(StubAircModule::with(move |params| { let inline_id = params["envelope"]["payload"]["payload"]["inline"]["messageId"] @@ -502,7 +502,7 @@ use super::*; let mut sorted = events.clone(); sorted.sort_by_key(|(idx, _)| *idx); assert_eq!( - sorted[0].1, "data/create", + sorted[0].1, "data/batch", "per-call ordering: data MUST come before airc for id={id}, observed={sorted:?}" ); assert_eq!( @@ -526,7 +526,7 @@ use super::*; let chat = chat_with_stubs(vec![ Arc::new(StubDataModule::new(|_cmd, _p| { - Ok(json!({ "success": true })) + Ok(batch_ok()) })), Arc::new(StubAircModule::with(|params| { // Drive the airc outcome from the inline message text. diff --git a/protocol/typescript/orm/BatchOperationType.ts b/protocol/typescript/orm/BatchOperationType.ts index 8e1b6fd0d7..4a4438f6ae 100644 --- a/protocol/typescript/orm/BatchOperationType.ts +++ b/protocol/typescript/orm/BatchOperationType.ts @@ -1,6 +1,7 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { SequenceSpec } from "./SequenceSpec"; /** * Batch operation type */ -export type BatchOperationType = "create" | "read" | "update" | "delete"; +export type BatchOperationType = "create" | "read" | "update" | "delete" | "ensure" | { "append": SequenceSpec }; diff --git a/protocol/typescript/orm/SequenceSpec.ts b/protocol/typescript/orm/SequenceSpec.ts new file mode 100644 index 0000000000..fdd754caad --- /dev/null +++ b/protocol/typescript/orm/SequenceSpec.ts @@ -0,0 +1,9 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * How an [`BatchOperationType::Append`] numbers its row: `sequence` is assigned + * `max(sequence) + 1` inside the batch's write transaction, so sequence order IS commit order + * (a row can never be acknowledged past an earlier allocation that commits later); `unique` + * names the field whose value identifies the row, so a duplicate reuses the first row. + */ +export type SequenceSpec = { sequence: string, unique: string, };