From a2cba455c396efc25ca903397bbee02ea9329c38 Mon Sep 17 00:00:00 2001 From: Shadaj Laddad Date: Tue, 27 Oct 2026 17:50:01 +0000 Subject: [PATCH] refactor(infinity-daemon)!: crash-safe, versioned, append-only thread persistence MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Make the disk-backed daemon durable against being killed at any point, and stop rewriting whole history files on every completion. ## Conversation log (`threads/{thread_id}.jsonl`) * Each thread's conversation is now an append-only JSONL log (`persist::ThreadLog`). The first line is a `header` carrying the format version and thread id; every later line is a `message` (inputs carry the dedup id they arrived under) or a `compaction_summary`. Appends are a single `write_all` + `fdatasync`, so a crash can tear at most the final line. * Loading recovers the **longest valid prefix**: a torn trailing line is dropped (with a warning) and the file truncated to the last complete line before anything new is appended. A complete-but-unparseable line, or a header from a newer version, is a loud error rather than a silent reset. * Legacy whole-snapshot `{thread_id}.json` files are migrated into the log on first load (the log is written atomically, so a crash mid-migration just retries); the legacy file is left in place and ignored thereafter. ## Versioned, atomically written documents * `{thread_id}.meta.json`, `{thread_id}.views.json`, `state/{thread_id}.state.json` and `sessions.json` now carry a `version` field and are written via `tempfile::NamedTempFile` in the same directory + fsync + `persist` (rename) (`persist::write_atomic`), so readers only ever see the old or the new contents and abandoned temp files are removed on drop. Unversioned files from older daemons read as version 0 and are upgraded eagerly on first load; files from a newer daemon are refused instead of being overwritten. * Load/save errors are no longer swallowed: trait methods propagate them, and the synchronous getters log them and skip any save. ## Dedup ids live only on inputs, and are looked up in history * `StateStore::get_processed_ids` / `add_processed_message_ids` are **removed**. `ConversationStore` gains `is_message_processed(thread_id, message_id)`, a point lookup against the persisted history. This eliminates the partial-write hazard of a message landing in one store but its dedup id not landing in the other, and the DSQL backend no longer needs DynamoDB for this (`SELECT EXISTS` with a new `(session_id, message_id)` index). The daemon's `.state.json` drops the `processed_message_ids` field. * Only inputs from the input queue carry a dedup id: `append_messages` takes `Vec<(InfinityMessage, Option)>`, and the synthetic ids the runtime used to mint for model output, synchronous/unknown-tool results, interrupt markers and child-thread seeds are gone. `HistoryManager::handle_input` is the single place dedup ids are checked and recorded (in-process set first, then the store); `handle_content(message)` folds runtime-minted content with no id. `handle_completion` and `run_completion` lose their id parameters. * DSQL: `message_id` becomes nullable (`ALTER COLUMN … DROP NOT NULL`, which Aurora DSQL supports, run idempotently at startup). * `InMemoryConversationStore` keeps a per-thread `HashSet` of input dedup ids alongside the entries (same lock, same mutation paths) so the lookup is O(1). ## Interruptions (incorporates and refines PR #170) * User interruptions are recorded as a first-class `InfinityMessage::Interrupt` history entry (rendered to the model at request time) instead of rewriting user text. When user text settles a pending tool call, the marker is committed **known-safe** (sound: a `ToolCall` at the tail implies no unvalidated inputs, asserted by `append_known_safe`), so "the user stopped the agent" is durable even if the text is later dropped as oversized. * `step_no_defer` gains an unconditional commit barrier (`sync()`) between the prepare and completion phases, so anything committed while folding inputs is durable before tools are cancelled or the model is invoked. * **Event** interruptions (subscription events, child reports) record no marker: the event itself is the record and `render_history` infers the interruption, answering the call with `TOOL_CALL_INTERRUPTED_BY_EVENT_TEXT`. A history that ends on a bare tool call therefore means "cut off mid-flight" — the signal a future auto-resume needs — rather than a deliberate stop. * Interrupt markers that arrive while unvalidated inputs precede them stay unvalidated but are never dropped by overflow recovery (fixes a #170 edge case where a kept subscription event could follow a stranded tool call). ## Breaking changes BREAKING CHANGE: `StateStore::get_processed_ids` and `add_processed_message_ids` are removed; `ConversationStore::is_message_processed` is a new required method and `append_messages` takes `Option` dedup ids. BREAKING CHANGE: `stores::ThreadState` no longer has `processed_message_ids`. BREAKING CHANGE: `HistoryManager::handle_content` / `handle_completion` and `run_completion` no longer take message/completion ids. BREAKING CHANGE: daemons older than this cannot read the new `.jsonl` logs, histories containing `interrupt` entries, or migrated sessions with id-less entries. ## Not covered (by design, for now) Inputs the model has not yet validated are still held only in memory and are lost on a crash (the existing context-overflow protection); a durable inbox is the next step toward auto-resume. Co-authored-by: Infinity 🤖 PR: #178 --- .../src/event_processor.rs | 679 +++++++--- crates/infinity-agent-core/src/message.rs | 197 ++- ..._subscription_event_tool_interruption.snap | 12 - ...consecutive_text_chunks_are_coalesced.snap | 2 +- ...ks_not_coalesced_across_non_text_item.snap | 6 +- ...ests__thread_report_tool_interruption.snap | 12 - ..._message_interrupts_pending_tool_call.snap | 11 +- crates/infinity-agent-core/src/stores.rs | 109 +- .../infinity-agent-core/src/system/defer.rs | 4 +- .../src/system/local/driver.rs | 12 +- .../infinity-agent-core/src/system/tests.rs | 44 +- .../infinity-agent-core/src/system/thread.rs | 28 +- .../infinity-agent-core/src/tools/thread.rs | 5 +- crates/infinity-agent-core/src/traits.rs | 44 +- .../src/conversation_history.rs | 68 +- .../infinity-agent-lambda/src/state_store.rs | 47 - crates/infinity-daemon/Cargo.toml | 2 +- crates/infinity-daemon/src/lib.rs | 1 + crates/infinity-daemon/src/memory_store.rs | 1198 +++++++++++++---- crates/infinity-daemon/src/persist.rs | 565 ++++++++ crates/infinity-daemon/src/session/display.rs | 8 +- crates/infinity-daemon/src/session_store.rs | 108 +- .../low-level/history-manager.md | 12 +- 23 files changed, 2461 insertions(+), 713 deletions(-) create mode 100644 crates/infinity-daemon/src/persist.rs diff --git a/crates/infinity-agent-core/src/event_processor.rs b/crates/infinity-agent-core/src/event_processor.rs index d934fd83..d42957a6 100644 --- a/crates/infinity-agent-core/src/event_processor.rs +++ b/crates/infinity-agent-core/src/event_processor.rs @@ -121,10 +121,15 @@ pub enum CompletionEvent { // ── HistoryManager (unchanged from before) ── +/// A history entry awaiting persistence. #[derive(Serialize, Clone)] pub struct PendingItem { message: InfinityMessage, - message_id: String, + /// The dedup id for inputs that arrived on the input queue (see + /// [`HistoryManager::handle_input`]); `None` for entries the runtime + /// minted itself (model output, synthetic tool results, interrupt + /// markers settling a tool call), which can never be redelivered. + dedup_id: Option, } /// Result of matching an incoming tool result against the history tail (see @@ -145,6 +150,12 @@ pub struct HistoryManager { pub root_thread_id: ThreadId, ancestor_chain: Vec, pub history: RefCell>, + /// Dedup ids of inputs handled during this process lifetime (persisted + /// or not). Ids persisted by an earlier incarnation are not preloaded; + /// they are looked up in the conversation store on demand by + /// [`Self::handle_input`] and cached here once seen. Only + /// `handle_input` reads or writes this set (plus + /// [`Self::drop_unvalidated_user_inputs`], which forgets dropped ids). processed_message_ids: RefCell>, metadata: RefCell>, // Un-persisted content moves through three phases: @@ -215,11 +226,6 @@ impl HistoryManager { .await .unwrap_or(None); - let processed_message_ids = state_store - .get_processed_ids(&thread_id) - .await - .unwrap_or_default(); - Ok(Self { conversation_store, state_store, @@ -227,7 +233,7 @@ impl HistoryManager { root_thread_id, ancestor_chain, history: RefCell::new(history), - processed_message_ids: RefCell::new(processed_message_ids), + processed_message_ids: RefCell::new(HashSet::new()), metadata: RefCell::new(metadata), pending_items: RefCell::new(Vec::new()), unvalidated_items: RefCell::new(Vec::new()), @@ -238,7 +244,17 @@ impl HistoryManager { }) } - pub fn handle_content( + /// Fold an incoming input into history unless its dedup id has already + /// been processed — either during this process lifetime (tracked in + /// memory) or durably, by a previous incarnation of the thread (looked up + /// in the conversation store). Returns `false` for duplicates and for + /// inputs [`Self::handle_content`] ignores. This is the only place dedup + /// ids are checked and recorded. + /// + /// Anything this commits as known-safe (an interrupt marker settling a + /// tool call) is made durable by the step's commit barrier right after + /// the prepare phase, before the model is invoked. + pub async fn handle_input( &self, message: InfinityMessage, message_id: String, @@ -247,7 +263,35 @@ impl HistoryManager { tracing::info!("Message {} already processed, skipping", message_id); return Ok(false); } + if self + .conversation_store + .is_message_processed(&self.thread_id, &message_id) + .await + .map_err(|e| Box::new(e) as BoxError)? + { + tracing::info!("Message {} already persisted, skipping", message_id); + self.processed_message_ids.borrow_mut().insert(message_id); + return Ok(false); + } + let is_new = self.fold(message, Some(message_id.clone()))?; + self.processed_message_ids.borrow_mut().insert(message_id); + Ok(is_new) + } + /// Fold runtime-minted content (a synthetic tool result produced during a + /// completion round) into history, settling or interrupting a pending + /// tool call as appropriate. Returns `false` if the content was ignored + /// (a tool result for an already-answered or non-existent call). + /// + /// Such content carries no dedup id — it is created in-process and can + /// never be redelivered. Inputs from the input queue go through + /// [`Self::handle_input`] instead. + pub fn handle_content(&self, message: InfinityMessage) -> Result { + self.fold(message, None) + } + + /// Shared body of [`Self::handle_input`] and [`Self::handle_content`]. + fn fold(&self, message: InfinityMessage, dedup_id: Option) -> Result { // SubscriptionEvent with an embedded invocation is self-contained — // treat it like a non-tool-result (may interrupt a pending call). let is_self_contained_subscription = matches!( @@ -258,6 +302,7 @@ impl HistoryManager { } ); + let mut interrupts_tool_call = false; if !is_self_contained_subscription { if let Some(tool_result) = message.tool_result() { match self.match_tool_result(&tool_result.id) { @@ -267,7 +312,6 @@ impl HistoryManager { "Tool call {} already processed, ignoring duplicate", tool_result.id ); - self.processed_message_ids.borrow_mut().insert(message_id); return Ok(false); } ToolResultMatch::NoPendingCall => { @@ -279,14 +323,19 @@ impl HistoryManager { } } } else { - self.interrupt_pending_tool_call(); + interrupts_tool_call = self.interrupt_pending_tool_call(&message); } } else { - self.interrupt_pending_tool_call(); + interrupts_tool_call = self.interrupt_pending_tool_call(&message); } - self.append_unvalidated(message, message_id.clone()); - self.processed_message_ids.borrow_mut().insert(message_id); + if interrupts_tool_call && matches!(message, InfinityMessage::Interrupt) { + // The incoming marker is the one settling the call; same + // reasoning as in `interrupt_pending_tool_call`. + self.append_known_safe(message, dedup_id); + } else { + self.append_unvalidated(message, dedup_id); + } Ok(true) } @@ -318,10 +367,36 @@ impl HistoryManager { ToolResultMatch::NoPendingCall } - /// If the last history entry is an unanswered tool call, inject a - /// synthetic "interrupted" result. (A tool call at the tail is unanswered - /// by construction: its result would have been appended after it.) - fn interrupt_pending_tool_call(&self) { + /// If the last history entry is an unanswered tool call, the incoming + /// item interrupts it: record the call for cancellation and return + /// `true`. (A tool call at the tail is unanswered by construction: its + /// result would have been appended after it.) + /// + /// How the interruption is *recorded* depends on who caused it: + /// + /// * **User text** gets an explicit [`InfinityMessage::Interrupt`] + /// appended here, committed as **known-safe** so the step's commit + /// barrier persists it before the model is invoked or the tool is + /// cancelled. The user stopping the agent must be durable + /// even if the text itself is later dropped as oversized (a stopped + /// agent is idle; it must not look like it was cut off mid-flight), and + /// the marker renders to a fixed short token so it can never be the + /// overflow cause. Committing it known-safe is sound because a tool + /// call at the tail is committed model output, which implies every + /// earlier input was already validated (asserted by + /// [`Self::append_known_safe`]). + /// * **Events** (subscription events, child reports) get no marker: the + /// event itself is the record, and `render_history` infers the + /// interruption from it. Events are never dropped (overflow recovery + /// placeholder-replaces them), so nothing is lost — and if the process + /// dies before the event is validated, the persisted history ends on + /// the bare tool call, which correctly reads as "in flight" to a + /// future resume rather than as a deliberate stop. + /// * An incoming **interrupt marker** is appended by the caller (known- + /// safe when it settles a call, otherwise unvalidated; see + /// [`Self::drop_unvalidated_user_inputs`] for how it survives either + /// way). + fn interrupt_pending_tool_call(&self, incoming: &InfinityMessage) -> bool { let last_call = self.history.borrow().last().and_then(|m| { if let InfinityMessage::ToolCall { call, .. } = m { Some(call.clone()) @@ -329,25 +404,17 @@ impl HistoryManager { None } }); - if let Some(tool_call) = last_call { - tracing::info!("Tool call {} interrupted by incoming message", tool_call.id); - self.interrupted_tool_calls - .borrow_mut() - .push(ToolCallId::from(tool_call.id.clone())); - let synthetic_result = InfinityMessage::ToolResult { - result: ToolResult { - id: tool_call.id.clone(), - call_id: tool_call.call_id.clone(), - content: vec![ToolResultContent::Text( - infinity_provider_protocol::message::Text { - text: TOOL_CALL_INTERRUPTED_TEXT.to_owned(), - }, - )], - }, - display_segments: None, - }; - self.append_unvalidated(synthetic_result, format!("{}-interrupted", tool_call.id)); + let Some(tool_call) = last_call else { + return false; + }; + tracing::info!("Tool call {} interrupted by incoming message", tool_call.id); + self.interrupted_tool_calls + .borrow_mut() + .push(ToolCallId::from(tool_call.id)); + if matches!(incoming, InfinityMessage::User { .. }) { + self.append_known_safe(InfinityMessage::Interrupt, None); } + true } /// Buffer a streamed assistant chunk for the current turn. The chunk is @@ -355,15 +422,7 @@ impl HistoryManager { /// until the turn reaches a flush point ([`Self::flush_turn`]) or is /// discarded on failure ([`Self::discard_turn`]). This keeps partial, /// possibly-abandoned turns out of committed history. - pub fn handle_completion( - &self, - completion: &StreamChunk, - completion_id: String, - display_as: Option, - ) { - if self.processed_message_ids.borrow().contains(&completion_id) { - return; - } + pub fn handle_completion(&self, completion: &StreamChunk, display_as: Option) { // Coalesce consecutive streamed text chunks into a single buffer entry // so that a multi-chunk assistant response is persisted as one message // rather than one row per chunk (which blows up disk usage). @@ -391,7 +450,7 @@ impl HistoryManager { }; self.turn_buffer.borrow_mut().push(PendingItem { message: infinity_message, - message_id: completion_id, + dedup_id: None, }); } @@ -407,7 +466,7 @@ impl HistoryManager { pub fn flush_turn(&self) { let drained = std::mem::take(&mut *self.turn_buffer.borrow_mut()); for item in drained { - self.append_known_safe(item.message, item.message_id); + self.append_known_safe(item.message, item.dedup_id); } } @@ -465,23 +524,22 @@ impl HistoryManager { /// result) to the in-memory history. The item is not persistable yet: /// it stays in `unvalidated_items` until the model produces output for /// it (see [`Self::mark_inputs_model_validated`]). - fn append_unvalidated(&self, message: InfinityMessage, message_id: String) { + fn append_unvalidated(&self, message: InfinityMessage, dedup_id: Option) { assert!( self.turn_buffer.borrow().is_empty(), "bug: append_unvalidated called with un-flushed turn_buffer content" ); self.history.borrow_mut().push(message.clone()); - self.unvalidated_items.borrow_mut().push(PendingItem { - message, - message_id, - }); + self.unvalidated_items + .borrow_mut() + .push(PendingItem { message, dedup_id }); } /// Append *model-produced* content (assistant text/reasoning, tool /// calls) to the in-memory history and the known-safe persistence /// queue. - fn append_known_safe(&self, message: InfinityMessage, message_id: String) { + fn append_known_safe(&self, message: InfinityMessage, dedup_id: Option) { assert!( self.turn_buffer.borrow().is_empty(), "bug: append_known_safe called with un-flushed turn_buffer content" @@ -496,10 +554,9 @@ impl HistoryManager { ); self.history.borrow_mut().push(message.clone()); - self.pending_items.borrow_mut().push(PendingItem { - message, - message_id, - }); + self.pending_items + .borrow_mut() + .push(PendingItem { message, dedup_id }); } /// Promote all unvalidated inputs to the known-safe persistence queue. @@ -520,7 +577,10 @@ impl HistoryManager { /// Drop all unvalidated *user* inputs: items that are neither tool /// results nor subscription events (those are placeholder-replaceable, /// see [`Self::replace_unvalidated_tool_results`], and answering a tool - /// call is always better than stranding it). Dropped items are removed + /// call is always better than stranding it) nor interrupt markers (an + /// interruption happened regardless of what becomes of the input that + /// caused it, and the marker cannot be the overflow cause). Dropped + /// items are removed /// from the in-memory history and their dedup IDs forgotten so a /// redelivery is not silently ignored. Returns how many items were /// dropped. @@ -544,11 +604,15 @@ impl HistoryManager { for item in unvalidated.drain(..) { if matches!( item.message, - InfinityMessage::ToolResult { .. } | InfinityMessage::SubscriptionEvent { .. } + InfinityMessage::ToolResult { .. } + | InfinityMessage::SubscriptionEvent { .. } + | InfinityMessage::Interrupt ) { kept.push(item); } else { - processed.remove(&item.message_id); + if let Some(id) = &item.dedup_id { + processed.remove(id); + } dropped += 1; } } @@ -638,35 +702,17 @@ impl HistoryManager { if pending_items.is_empty() { return Ok(()); } - let msgs: Vec<(InfinityMessage, String)> = pending_items + let msgs: Vec<(InfinityMessage, Option)> = pending_items .iter() - .map(|item| (item.message.clone(), item.message_id.clone())) + .map(|item| (item.message.clone(), item.dedup_id.clone())) .collect(); + // The dedup ids travel with the messages: the store answers later + // `is_message_processed` lookups from them, so there is no second + // write that could be lost separately. self.conversation_store .append_messages(&self.thread_id, msgs) .await .map_err(|e| Box::new(e) as BoxError)?; - // Only inputs that are not naturally idempotent need durable dedup - // IDs: user text and subscription events (a redelivered subscription - // event would mint a fresh invocation and be appended again). Tool - // results are deduplicated against the history tail itself, and - // assistant/tool-call items only exist downstream of a deduped input. - let msg_ids: Vec = pending_items - .iter() - .filter(|i| { - matches!( - i.message, - InfinityMessage::User { .. } | InfinityMessage::SubscriptionEvent { .. } - ) - }) - .map(|i| i.message_id.clone()) - .collect(); - if !msg_ids.is_empty() { - let _ = self - .state_store - .add_processed_message_ids(&self.thread_id, msg_ids) - .await; - } Ok(()) } @@ -685,10 +731,8 @@ impl HistoryManager { /// `false`, image tool-result content is replaced with a text placeholder /// so the history can be sent to models without image support. pub fn get_history(&self, supports_image_input: bool) -> Vec { - self.history - .borrow() - .iter() - .flat_map(|m| m.clone().into_messages()) + crate::message::render_history(self.history.borrow().iter()) + .into_iter() .map(|mut msg| { if !supports_image_input { strip_image_tool_results(&mut msg); @@ -970,13 +1014,7 @@ where display_as: None, }; conversation_store - .append_messages( - &sub_thread_id, - vec![( - spawn_tool_call, - format!("{}-compaction-call", spawn_call_id), - )], - ) + .append_messages(&sub_thread_id, vec![(spawn_tool_call, None)]) .await .map_err(|e| Box::new(e) as BoxError)?; @@ -1038,6 +1076,19 @@ where }); } + // Interrupt marker: like any non-result entry, folding it settles a + // trailing unanswered tool call. + if input_msg + .synthetic + .as_ref() + .is_some_and(SyntheticKind::is_interrupt) + { + current_history + .handle_input(InfinityMessage::Interrupt, message_id) + .await?; + return Ok(PrepareResult::Handled); + } + let is_subscription = input_msg.subscription; let user_content = match input_msg.content { @@ -1166,7 +1217,7 @@ where // No need to prepend an "interrupted" result for trailing tool calls // because the safe_spawn_point already excludes them from the child's // inherited history. - let mut child_messages: Vec<(InfinityMessage, String)> = Vec::new(); + let mut child_messages: Vec<(InfinityMessage, Option)> = Vec::new(); // Write event + spawn tool calls directly to child's store let event_tool_call = InfinityMessage::ToolCall { @@ -1213,9 +1264,9 @@ where display_segments: None, }; child_messages.extend(vec![ - (spawn_tool_call, format!("{}-spawn-call", spawn_call_id)), - (spawn_tool_result, format!("{}-spawn-result", spawn_call_id)), - (event_tool_call, format!("{}-event-call", event_call_id)), + (spawn_tool_call, None), + (spawn_tool_result, None), + (event_tool_call, None), ]); conversation_store .append_messages(&sub_thread_id, child_messages) @@ -1282,7 +1333,9 @@ where } }; - let is_new = current_history.handle_content(infinity_msg, message_id.clone())?; + let is_new = current_history + .handle_input(infinity_msg, message_id.clone()) + .await?; if !is_new { tracing::info!("Message was duplicate or ignored, skipping agent processing"); @@ -1364,9 +1417,8 @@ where ), }) } else if let InputMessageContent::User(UserContent::Text(ref text)) = input_msg.content { - let display_text = text.text.strip_prefix("").unwrap_or(&text.text); Some(AgentEvent::UserInput { - text: display_text.to_owned(), + text: text.text.clone(), }) } else { None @@ -1390,14 +1442,7 @@ pub const IMAGE_OMITTED_PLACEHOLDER: &str = pub const TOOL_RESULT_TOO_LARGE_PLACEHOLDER: &str = "[tool result omitted: it was too large for the model's remaining context window]"; -/// Text used to settle a tool call as interrupted. Injected when a user -/// message arrives while the call is unanswered, and also substituted for a -/// pending tool result during overflow recovery when user input had to be -/// dropped: the next thing the model sees is a fresh user message, and -/// "interrupted by user" describes that situation accurately, whereas a -/// "too large" placeholder could mislead the model into re-running the -/// tool. -pub const TOOL_CALL_INTERRUPTED_TEXT: &str = "Tool call interrupted by user"; +pub use crate::message::TOOL_CALL_INTERRUPTED_TEXT; /// Maximum number of retries for one completion round (transient and /// throttled provider errors). @@ -1410,6 +1455,7 @@ const TRANSIENT_RETRY_DELAY: Duration = Duration::from_secs(5); /// How [`run_completion`] recovered from a provider-declared context /// overflow (see [`ErrorClass::ContextOverflow`]). +#[derive(Debug, PartialEq, Eq)] enum OverflowRecovery { /// The not-known-safe queue was exactly one replaceable item (tool /// result / subscription event) — the culprit is unambiguous, so it was @@ -1489,8 +1535,6 @@ pub fn run_completion<'a: 'b, 'b, P, C, S, M>( tools: &'a [ToolDefinition], tool_registry: &'a HashMap>, tool_context: &'a ToolContext, - group_id: &'a ThreadId, - message_id: &'a str, extra_system_prompt: Option<&'a str>, cancel_rx: tokio::sync::oneshot::Receiver<()>, ) -> impl futures_util::Stream> + 'b @@ -1502,7 +1546,6 @@ where { async_stream::try_stream! { let mut cancel_rx = cancel_rx; - let mut completion_counter: usize = 0; let mut is_thinking = false; let mut retry_count = 0; @@ -1739,9 +1782,6 @@ where if let StreamChunk::Reasoning(ref r) = chunk && r.first_signature().is_none() { continue; } - let completion_id = format!("{}-{}-completion-{}", group_id, message_id, completion_counter); - completion_counter += 1; - // After the turn's first tool call, the model may keep // streaming: Bedrock emits *concurrent* tool calls in one // assistant message (each closed content block yields @@ -1769,7 +1809,7 @@ where } else { None }; - history.handle_completion(&chunk, completion_id, tool_display_as.clone()); + history.handle_completion(&chunk, tool_display_as.clone()); match chunk { StreamChunk::Text(text) => { if is_thinking { @@ -1806,7 +1846,7 @@ where }, display_segments: None, }; - history.handle_content(tool_result, format!("{}-unknown-tool", call.id))?; + history.handle_content(tool_result)?; should_loop_back = true; continue; } else if !tool_names.contains(call.function.name.as_str()) { @@ -1822,7 +1862,7 @@ where }, display_segments: None, }; - history.handle_content(tool_result, format!("{}-unknown-tool", call.id))?; + history.handle_content(tool_result)?; should_loop_back = true; continue; } @@ -1859,15 +1899,10 @@ where }; yield CompletionEvent::SyncToolResult(res.clone()); - let sync_id = format!("{}-sync-result-{}", call.id, completion_counter); - completion_counter += 1; - history.handle_content( - InfinityMessage::ToolResult { - result: res, - display_segments: None, - }, - sync_id, - )?; + history.handle_content(InfinityMessage::ToolResult { + result: res, + display_segments: None, + })?; should_loop_back = true; } else { yield CompletionEvent::Action(CompletionAction::ExecuteToolCall { @@ -2131,9 +2166,9 @@ mod tests { let text_chunk = |s: &str| StreamChunk::Text(s.to_owned()); - hm.handle_completion(&text_chunk("Hello"), "c-1".to_owned(), None); - hm.handle_completion(&text_chunk(", "), "c-2".to_owned(), None); - hm.handle_completion(&text_chunk("world"), "c-3".to_owned(), None); + hm.handle_completion(&text_chunk("Hello"), None); + hm.handle_completion(&text_chunk(", "), None); + hm.handle_completion(&text_chunk("world"), None); // While streaming, the chunks accumulate in the buffer (not yet // committed) and coalesce into a single entry. @@ -2162,10 +2197,10 @@ mod tests { }, }); - hm.handle_completion(&text_chunk("before"), "c-1".to_owned(), None); + hm.handle_completion(&text_chunk("before"), None); // A non-text item in between breaks the run of text chunks. - hm.handle_completion(&tool_call, "c-2".to_owned(), None); - hm.handle_completion(&text_chunk("after"), "c-3".to_owned(), None); + hm.handle_completion(&tool_call, None); + hm.handle_completion(&text_chunk("after"), None); // The tool call between the two text chunks should prevent them from // being coalesced, leaving three distinct buffered items which commit @@ -2193,8 +2228,8 @@ mod tests { ), ); let text = StreamChunk::Text("partial answer".to_owned()); - hm.handle_completion(&reasoning, "c-1".to_owned(), None); - hm.handle_completion(&text, "c-2".to_owned(), None); + hm.handle_completion(&reasoning, None); + hm.handle_completion(&text, None); // Mid-turn: committed history still ends on the user message; the // streamed content lives only in the buffer, so nothing is persisted or @@ -2224,7 +2259,7 @@ mod tests { .await; let text = StreamChunk::Text("partial answer".to_owned()); - hm.handle_completion(&text, "c-1".to_owned(), None); + hm.handle_completion(&text, None); assert_eq!(hm.turn_buffer.borrow().len(), 1); hm.discard_turn(); @@ -2259,8 +2294,8 @@ mod tests { Some("sig".to_owned()), ), ); - hm.handle_completion(&text, "c-1".to_owned(), None); - hm.handle_completion(&reasoning, "c-2".to_owned(), None); + hm.handle_completion(&text, None); + hm.handle_completion(&reasoning, None); assert_eq!(hm.turn_buffer.borrow().len(), 2); hm.flush_turn_trimming_reasoning(); @@ -2302,9 +2337,9 @@ mod tests { ) }; let empty_text = StreamChunk::Text(" ".to_owned()); - hm.handle_completion(&reasoning("first"), "c-1".to_owned(), None); - hm.handle_completion(&empty_text, "c-2".to_owned(), None); - hm.handle_completion(&reasoning("second"), "c-3".to_owned(), None); + hm.handle_completion(&reasoning("first"), None); + hm.handle_completion(&empty_text, None); + hm.handle_completion(&reasoning("second"), None); hm.flush_turn_trimming_reasoning(); @@ -2329,7 +2364,7 @@ mod tests { assert_eq!(hm.current_turn_view().len(), 1); let text = StreamChunk::Text("streaming...".to_owned()); - hm.handle_completion(&text, "c-1".to_owned(), None); + hm.handle_completion(&text, None); // Mid-turn the view includes the buffered partial message even though // it is not yet in committed history (for subscriber replay). @@ -2452,8 +2487,191 @@ mod tests { .expect("prepare input"); assert_eq!(result, PrepareResult::Ready); - // Should have: original user, tool call, synthetic interrupted result, new user msg - insta::assert_json_snapshot!(hm.history.into_inner()); + // Should have: original user, tool call, interrupt, new user msg + // (no synthetic result is stored)... + insta::assert_json_snapshot!(hm.history.borrow().clone()); + // ...but the model still sees the call answered as interrupted. + let rendered = hm.get_history(true); + assert_eq!( + rendered[2..], + [ + Message::User { + content: vec![UserContent::ToolResult(ToolResult { + id: "tc-1".to_owned(), + call_id: None, + content: vec![ToolResultContent::Text( + infinity_provider_protocol::message::Text { + text: TOOL_CALL_INTERRUPTED_TEXT.to_owned(), + } + )], + })], + }, + Message::User { + content: vec![UserContent::text("actually, never mind")], + }, + ] + ); + } + + /// An interrupt marker settles a pending call by itself (no second + /// entry), and a late real result for the call is ignored. + #[tokio::test] + async fn interrupt_marker_settles_pending_tool_call() { + let store = InMemoryConversationStore::new(); + let initial = vec![tool_call_msg("tc-1", "some_tool", serde_json::json!({}))]; + let hm = make_history(&store, initial).await; + for (input, id) in [ + (InputMessage::interrupt("thread-1"), "msg-1"), + (tool_result_input("thread-1", "tc-1", "late", None), "msg-2"), + ] { + prepare_input(input, id.to_owned(), &hm, &store, &StubSender) + .await + .expect("prepare input"); + } + assert!(matches!( + hm.history.borrow().as_slice(), + [InfinityMessage::ToolCall { .. }, InfinityMessage::Interrupt] + )); + assert_eq!( + hm.take_interrupted_tool_calls(), + vec![ToolCallId::from("tc-1")] + ); + } + + /// An interruption that settles a pending tool call is committed + /// known-safe, so the step's commit barrier persists it before any + /// completion runs — while the interrupting input itself stays + /// unvalidated and unpersisted. + #[tokio::test] + async fn interrupt_settling_tool_call_is_known_safe() { + let store = InMemoryConversationStore::new(); + let initial = vec![ + Message::User { + content: vec![UserContent::text("do something")], + }, + tool_call_msg("tc-1", "some_tool", serde_json::json!({})), + ]; + let hm = make_history(&store, initial).await; + + prepare_input( + user_text_msg("thread-1", "never mind"), + "msg-2".to_owned(), + &hm, + &store, + &StubSender, + ) + .await + .expect("prepare input"); + + assert!( + matches!( + hm.pending_items.borrow().as_slice(), + [PendingItem { + message: InfinityMessage::Interrupt, + .. + }] + ), + "the marker is the only known-safe item" + ); + assert_eq!(hm.unvalidated_len(), 1, "the user text awaits validation"); + + // What the step's commit barrier writes before invoking the model: + hm.sync().await.expect("sync"); + let stored = persisted(&store); + assert!( + stored.contains("(Interrupt, None)"), + "interrupt is durable: {stored}" + ); + assert!( + !stored.contains("never mind"), + "the interrupting input is not: {stored}" + ); + } + + /// If the interrupting input turns out to be oversized and is dropped on + /// context overflow, the interruption is still recorded and the tool + /// call stays settled in the retry request. + #[tokio::test] + async fn oversized_interrupting_input_keeps_the_tool_call_settled() { + let store = InMemoryConversationStore::new(); + let initial = vec![ + Message::User { + content: vec![UserContent::text("do something")], + }, + tool_call_msg("tc-1", "some_tool", serde_json::json!({})), + ]; + let hm = make_history(&store, initial).await; + prepare_input( + user_text_msg("thread-1", "enormous"), + "msg-2".to_owned(), + &hm, + &store, + &StubSender, + ) + .await + .expect("prepare input"); + + assert_eq!( + recover_from_overflow(&hm), + OverflowRecovery::DroppedInputs(1) + ); + assert!(matches!( + hm.history.borrow().as_slice(), + [ + InfinityMessage::User { .. }, + InfinityMessage::ToolCall { .. }, + InfinityMessage::Interrupt + ] + )); + // The model never sees an unanswered tool_use. + let rendered = hm.get_history(true); + assert_eq!( + rendered.last(), + Some(&Message::User { + content: vec![UserContent::ToolResult(ToolResult { + id: "tc-1".to_owned(), + call_id: None, + content: vec![ToolResultContent::Text( + infinity_provider_protocol::message::Text { + text: TOOL_CALL_INTERRUPTED_TEXT.to_owned(), + } + )], + })], + }) + ); + } + + /// An interrupt marker that does not settle a tool call (user text + /// interrupting a streaming completion whose inputs were not yet + /// validated) cannot be committed known-safe without breaking the + /// safe-after-unvalidated ordering, so it stays unvalidated — but an + /// overflow drop still preserves it. + #[tokio::test] + async fn interrupt_after_unvalidated_input_survives_overflow_drop() { + let store = InMemoryConversationStore::new(); + let hm = make_history(&store, vec![]).await; + let user = |text: &str| InfinityMessage::User { + content: UserContent::text(text), + }; + // Inputs with dedup ids, exactly as the driver would deliver them. + hm.handle_input(user("first"), "a".to_owned()) + .await + .expect("first"); + hm.handle_input(InfinityMessage::Interrupt, "b-interrupt".to_owned()) + .await + .expect("interrupt"); + hm.handle_input(user("second, oversized"), "b".to_owned()) + .await + .expect("second"); + assert_eq!(hm.unvalidated_len(), 3, "nothing was committed known-safe"); + assert!(hm.pending_items.borrow().is_empty()); + + assert_eq!(hm.drop_unvalidated_user_inputs(), 2); + assert!(matches!( + hm.history.borrow().as_slice(), + [InfinityMessage::Interrupt] + )); + assert_eq!(hm.unvalidated_len(), 1); } #[tokio::test] @@ -2559,7 +2777,7 @@ mod tests { assert_eq!(result, PrepareResult::Ready); insta::assert_json_snapshot!( hm.history.into_inner(), - { "[3].result.id" => "[uuid]", "[3].invocation.id" => "[uuid]" } + { "[2].result.id" => "[uuid]", "[2].invocation.id" => "[uuid]" } ); } @@ -2787,7 +3005,76 @@ mod tests { assert_eq!(hm.thread_id.as_str(), "thread-1"); insta::assert_json_snapshot!( hm.history.into_inner(), - { "[3].result.id" => "[uuid]", "[3].invocation.id" => "[uuid]" } + { "[2].result.id" => "[uuid]", "[2].invocation.id" => "[uuid]" } + ); + } + + /// An event that interrupts a pending tool call records no marker: the + /// event is the record. Nothing is persisted until the model validates + /// it (so a crash here leaves the log ending on the tool call — "in + /// flight", not "stopped"), the call is still reported for + /// cancellation, and the model sees it answered as interrupted by an + /// event. + #[tokio::test] + async fn event_interruption_is_inferred_not_recorded() { + let store = InMemoryConversationStore::new(); + let initial = vec![ + Message::User { + content: vec![UserContent::text("wait for it")], + }, + tool_call_msg("tc-sleep", "sleep", serde_json::json!({"seconds": 60})), + ]; + let hm = make_history(&store, initial).await; + + let input = tool_result_input( + "thread-1", + "tc-sleep", + "something happened", + Some(SyntheticKind::Tagged( + TaggedSyntheticKind::SubscriptionEvent { + tool_call_id: "tc-sleep".into(), + associative: true, + r#final: false, + }, + )), + ); + prepare_input(input, "msg-2".to_owned(), &hm, &store, &StubSender) + .await + .expect("prepare input"); + + assert!(matches!( + hm.history.borrow().as_slice(), + [ + InfinityMessage::User { .. }, + InfinityMessage::ToolCall { .. }, + InfinityMessage::SubscriptionEvent { .. } + ] + )); + assert_eq!(hm.unvalidated_len(), 1, "the event is unvalidated"); + assert!(hm.pending_items.borrow().is_empty(), "nothing known-safe"); + assert_eq!( + persisted(&store), + "[]", + "nothing reached the store before validation" + ); + assert_eq!( + hm.take_interrupted_tool_calls(), + vec![ToolCallId::from("tc-sleep")] + ); + let rendered = hm.get_history(true); + assert_eq!( + rendered[2], + Message::User { + content: vec![UserContent::ToolResult(ToolResult { + id: "tc-sleep".to_owned(), + call_id: None, + content: vec![ToolResultContent::Text( + infinity_provider_protocol::message::Text { + text: crate::message::TOOL_CALL_INTERRUPTED_BY_EVENT_TEXT.to_owned(), + } + )], + })], + } ); } @@ -2842,7 +3129,6 @@ mod tests { // Spawn the stream consumer let handle = tokio::task::spawn_local(async move { - let thread_id = ThreadId::from("thread-1"); let stream = run_completion( &provider, "mock", @@ -2852,8 +3138,6 @@ mod tests { &tool_defs, &tool_registry, &ctx, - &thread_id, - "msg-1", None, cancel_rx, ); @@ -2904,7 +3188,6 @@ mod tests { let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { - let thread_id = ThreadId::from("thread-1"); let stream = run_completion( &provider, "mock", @@ -2914,8 +3197,6 @@ mod tests { &tool_defs, &tool_registry, &ctx, - &thread_id, - "msg-1", None, cancel_rx, ); @@ -2969,7 +3250,6 @@ mod tests { let (_cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { - let thread_id = ThreadId::from("thread-1"); let stream = run_completion( &provider, "mock", @@ -2979,8 +3259,6 @@ mod tests { &tool_defs, &tool_registry, &ctx, - &thread_id, - "msg-1", None, cancel_rx, ); @@ -3055,7 +3333,6 @@ mod tests { let (_cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { - let thread_id = ThreadId::from("thread-1"); let stream = run_completion( &provider, "mock", @@ -3065,8 +3342,6 @@ mod tests { &tool_defs, &tool_registry, &ctx, - &thread_id, - "msg-1", None, cancel_rx, ); @@ -3173,7 +3448,6 @@ mod tests { let (_cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { - let thread_id = ThreadId::from("thread-1"); let stream = run_completion( &provider, "mock", @@ -3183,8 +3457,6 @@ mod tests { &tool_defs, &tool_registry, &ctx, - &thread_id, - "msg-1", None, cancel_rx, ); @@ -3299,8 +3571,6 @@ mod tests { let (tool_names, tool_defs, tool_registry) = no_tools(); let ctx = tool_context(); let (_cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); - - let thread_id_owned = ThreadId::from("thread-1"); let handle = tokio::task::spawn_local(async move { let stream = run_completion( &provider, @@ -3311,8 +3581,6 @@ mod tests { &tool_defs, &tool_registry, &ctx, - &thread_id_owned, - "msg-1", None, cancel_rx, ); @@ -3350,7 +3618,6 @@ mod tests { let (_cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { - let thread_id = ThreadId::from("thread-1"); let stream = run_completion( &provider, "mock", @@ -3360,8 +3627,6 @@ mod tests { &tool_defs, &tool_registry, &ctx, - &thread_id, - "msg-1", None, cancel_rx, ); @@ -3409,7 +3674,6 @@ mod tests { let (_cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { - let thread_id = ThreadId::from("thread-1"); let stream = run_completion( &provider, "mock", @@ -3419,8 +3683,6 @@ mod tests { &tool_defs, &tool_registry, &ctx, - &thread_id, - "msg-1", None, cancel_rx, ); @@ -3513,7 +3775,6 @@ mod tests { let (_cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { - let thread_id = ThreadId::from("thread-1"); let stream = run_completion( &provider, "mock", @@ -3523,8 +3784,6 @@ mod tests { &tool_defs, &tool_registry, &ctx, - &thread_id, - "msg-1", None, cancel_rx, ); @@ -3616,7 +3875,6 @@ mod tests { let (_cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { - let thread_id = ThreadId::from("thread-1"); let stream = run_completion( &provider, "mock", @@ -3626,8 +3884,6 @@ mod tests { &tool_defs, &tool_registry, &ctx, - &thread_id, - "msg-1", None, cancel_rx, ); @@ -3744,7 +4000,6 @@ mod tests { let (_cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { - let thread_id = ThreadId::from("thread-1"); let stream = run_completion( &provider, "mock", @@ -3754,8 +4009,6 @@ mod tests { &tool_defs, &tool_registry, &ctx, - &thread_id, - "msg-1", None, cancel_rx, ); @@ -3810,7 +4063,6 @@ mod tests { let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { - let thread_id = ThreadId::from("thread-1"); let stream = run_completion( &provider, "mock", @@ -3820,8 +4072,6 @@ mod tests { &tool_defs, &tool_registry, &ctx, - &thread_id, - "msg-1", None, cancel_rx, ); @@ -3884,7 +4134,6 @@ mod tests { let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let hm_task = hm.clone(); - let thread_id_owned = ThreadId::from("thread-1"); let handle = tokio::task::spawn_local(async move { let stream = run_completion( &provider, @@ -3895,8 +4144,6 @@ mod tests { &tool_defs, &tool_registry, &ctx, - &thread_id_owned, - "msg-1", None, cancel_rx, ); @@ -3971,7 +4218,6 @@ mod tests { let (_cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { - let thread_id = ThreadId::from("thread-1"); let stream = run_completion( &provider, "mock", @@ -3981,8 +4227,6 @@ mod tests { &tool_defs, &tool_registry, &ctx, - &thread_id, - "msg-1", None, cancel_rx, ); @@ -4046,7 +4290,6 @@ mod tests { let (_cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { - let thread_id = ThreadId::from("thread-1"); let stream = run_completion( &provider, "mock", @@ -4056,8 +4299,6 @@ mod tests { &tool_defs, &tool_registry, &ctx, - &thread_id, - "msg-1", None, cancel_rx, ); @@ -4161,7 +4402,6 @@ mod tests { let (_cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let hm_task = hm.clone(); - let thread_id_owned = ThreadId::from("thread-1"); let handle = tokio::task::spawn_local(async move { let stream = run_completion( &provider, @@ -4172,8 +4412,6 @@ mod tests { &tool_defs, &tool_registry, &ctx, - &thread_id_owned, - "msg-1", None, cancel_rx, ); @@ -4250,10 +4488,9 @@ mod tests { let (_cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { - let thread_id = ThreadId::from("thread-1"); let stream = run_completion( &provider, "mock", false, &hm, &tool_names, &tool_defs, &tool_registry, - &ctx, &thread_id, "msg-1", None, cancel_rx, + &ctx, None, cancel_rx, ); tokio::pin!(stream); let mut got_done = false; @@ -4505,31 +4742,32 @@ mod tests { /// Feed a user text input through the same path a step uses /// (`handle_content`), as opposed to `make_history` which fabricates /// already-committed history. - fn add_user_input( + async fn add_user_input( hm: &HistoryManager, text: &str, message_id: &str, ) { let accepted = hm - .handle_content( + .handle_input( InfinityMessage::User { content: UserContent::text(text), }, message_id.to_owned(), ) + .await .expect("handle user input"); assert!(accepted, "input should be accepted"); } /// Feed a tool-result input through the same path a step uses. - fn add_tool_result_input( + async fn add_tool_result_input( hm: &HistoryManager, tool_call_id: &str, text: &str, message_id: &str, ) { let accepted = hm - .handle_content( + .handle_input( InfinityMessage::ToolResult { result: ToolResult { id: tool_call_id.to_owned(), @@ -4544,6 +4782,7 @@ mod tests { }, message_id.to_owned(), ) + .await .expect("handle tool result input"); assert!(accepted, "tool result should be accepted"); } @@ -4557,7 +4796,6 @@ mod tests { ) -> Vec { let (tool_names, tool_defs, tool_registry) = no_tools(); let ctx = tool_context(); - let thread_id = ThreadId::from("thread-1"); let stream = run_completion( provider, "mock", @@ -4567,8 +4805,6 @@ mod tests { &tool_defs, &tool_registry, &ctx, - &thread_id, - "msg-1", None, cancel_rx, ); @@ -4617,7 +4853,7 @@ mod tests { let (provider, mut ctrl) = mock_provider(); let convo_store = InMemoryConversationStore::new(); let hm = make_history(&convo_store, vec![]).await; - add_user_input(&hm, "HUGE INPUT", "msg-huge"); + add_user_input(&hm, "HUGE INPUT", "msg-huge").await; let (_cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { @@ -4669,7 +4905,7 @@ mod tests { ], ) .await; - add_tool_result_input(&hm, "tc-1", "HUGE RESULT", "msg-tr"); + add_tool_result_input(&hm, "tc-1", "HUGE RESULT", "msg-tr").await; let (_cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { @@ -4732,7 +4968,7 @@ mod tests { ) .await; let accepted = hm - .handle_content( + .handle_input( InfinityMessage::SubscriptionEvent { result: Box::new(ToolResult { id: "evt-1".to_owned(), @@ -4753,6 +4989,7 @@ mod tests { }, "msg-evt".to_owned(), ) + .await .expect("handle subscription event"); assert!(accepted); let (_cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); @@ -4820,8 +5057,8 @@ mod tests { .await; // The tool result arrives first, then a huge user input // interrupts before the model produced any output. - add_tool_result_input(&hm, "tc-1", "normal tool result", "msg-tr"); - add_user_input(&hm, "HUGE USER INPUT", "msg-huge"); + add_tool_result_input(&hm, "tc-1", "normal tool result", "msg-tr").await; + add_user_input(&hm, "HUGE USER INPUT", "msg-huge").await; let (_cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { @@ -4907,7 +5144,7 @@ mod tests { ], ) .await; - add_tool_result_input(&hm, "tc-1", "HUGE RESULT", "msg-tr"); + add_tool_result_input(&hm, "tc-1", "HUGE RESULT", "msg-tr").await; let (_cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { @@ -4956,7 +5193,7 @@ mod tests { // A later user input does not need to interrupt anything — // the call is already answered in memory. - add_user_input(&hm, "hello again", "msg-next"); + add_user_input(&hm, "hello again", "msg-next").await; let history = format!("{:?}", hm.history.borrow()); assert!(history.contains(TOOL_CALL_INTERRUPTED_TEXT)); assert!(history.contains("hello again")); @@ -4976,7 +5213,7 @@ mod tests { let (provider, mut ctrl) = mock_provider(); let convo_store = InMemoryConversationStore::new(); let hm = make_history(&convo_store, vec![]).await; - add_user_input(&hm, "hello there", "msg-1"); + add_user_input(&hm, "hello there", "msg-1").await; let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { @@ -5015,7 +5252,7 @@ mod tests { let (provider, mut ctrl) = mock_provider(); let convo_store = InMemoryConversationStore::new(); let hm = make_history(&convo_store, vec![]).await; - add_user_input(&hm, "hello there", "msg-1"); + add_user_input(&hm, "hello there", "msg-1").await; let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { @@ -5055,7 +5292,7 @@ mod tests { let (provider, mut ctrl) = mock_provider(); let convo_store = InMemoryConversationStore::new(); let hm = make_history(&convo_store, vec![]).await; - add_user_input(&hm, "hi", "msg-1"); + add_user_input(&hm, "hi", "msg-1").await; let (_cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { @@ -5096,7 +5333,7 @@ mod tests { let (provider, mut ctrl) = mock_provider(); let convo_store = InMemoryConversationStore::new(); let hm = make_history(&convo_store, vec![]).await; - add_user_input(&hm, "hi", "msg-1"); + add_user_input(&hm, "hi", "msg-1").await; let (_cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { @@ -5131,7 +5368,7 @@ mod tests { let (provider, mut ctrl) = mock_provider(); let convo_store = InMemoryConversationStore::new(); let hm = make_history(&convo_store, vec![]).await; - add_user_input(&hm, "hi", "msg-1"); + add_user_input(&hm, "hi", "msg-1").await; let (_cancel_tx, cancel_rx) = tokio::sync::oneshot::channel(); let handle = tokio::task::spawn_local(async move { @@ -5166,7 +5403,7 @@ mod tests { async fn sync_does_not_persist_inputs_before_model_output() { let store = InMemoryConversationStore::new(); let hm = make_history(&store, vec![]).await; - add_user_input(&hm, "not yet validated", "msg-1"); + add_user_input(&hm, "not yet validated", "msg-1").await; hm.sync().await.expect("sync"); assert!( !persisted(&store).contains("not yet validated"), @@ -5182,12 +5419,8 @@ mod tests { async fn flushing_model_output_with_unvalidated_inputs_panics() { let store = InMemoryConversationStore::new(); let hm = make_history(&store, vec![]).await; - add_user_input(&hm, "pending input", "msg-1"); - hm.handle_completion( - &StreamChunk::Text("model output".to_owned()), - "completion-1".to_owned(), - None, - ); + add_user_input(&hm, "pending input", "msg-1").await; + hm.handle_completion(&StreamChunk::Text("model output".to_owned()), None); // Flushing without validating the pending input first violates // sequentiality. hm.flush_turn(); @@ -5199,7 +5432,7 @@ mod tests { async fn safe_spawn_point_excludes_unvalidated_inputs() { let store = InMemoryConversationStore::new(); let hm = make_history(&store, vec![]).await; - add_user_input(&hm, "not persisted yet", "msg-1"); + add_user_input(&hm, "not persisted yet", "msg-1").await; assert_eq!( hm.safe_spawn_point(), 0, diff --git a/crates/infinity-agent-core/src/message.rs b/crates/infinity-agent-core/src/message.rs index 13b5f9e9..eddeceff 100644 --- a/crates/infinity-agent-core/src/message.rs +++ b/crates/infinity-agent-core/src/message.rs @@ -1,5 +1,5 @@ use infinity_provider_protocol::message::{ - AssistantContent, Message, ToolCall, ToolResult, UserContent, + AssistantContent, Message, Text, ToolCall, ToolResult, ToolResultContent, UserContent, }; use rap_protocol::{ChoiceId, ProviderCallId, ThreadId, ToolCallId}; use serde::{Deserialize, Serialize}; @@ -68,6 +68,10 @@ pub enum TaggedSyntheticKind { Compaction, #[serde(rename = "compaction_complete")] CompactionComplete, + /// Interrupt marker: folded into history as [`InfinityMessage::Interrupt`] + /// at the point the thread's in-flight work was interrupted. + #[serde(rename = "interrupt")] + Interrupt, } impl SyntheticKind { @@ -86,6 +90,7 @@ impl SyntheticKind { SyntheticKind::Tagged(TaggedSyntheticKind::CompactionComplete) => { ToolCallId::from_ref("") } + SyntheticKind::Tagged(TaggedSyntheticKind::Interrupt) => ToolCallId::from_ref(""), SyntheticKind::SubscriptionEvent(id) => id, } } @@ -115,6 +120,11 @@ impl SyntheticKind { ) } + /// Whether this is an interrupt marker. + pub fn is_interrupt(&self) -> bool { + matches!(self, SyntheticKind::Tagged(TaggedSyntheticKind::Interrupt)) + } + /// Associative subscription events are injected inline into the subscribing /// thread's history (like thread reports) rather than spawning a child thread. pub fn is_associative(&self) -> bool { @@ -169,6 +179,18 @@ impl InputMessage { subscription: false, } } + + /// An interrupt marker addressed to `thread_id`; the content is unused. + pub fn interrupt(thread_id: impl Into) -> Self { + Self { + content: InputMessageContent::User(UserContent::text(String::new())), + group_id: thread_id.into(), + metadata: None, + synthetic: Some(SyntheticKind::Tagged(TaggedSyntheticKind::Interrupt)), + display_as: None, + subscription: false, + } + } } /// Wraps message content with optional display metadata that survives @@ -223,6 +245,102 @@ pub enum InfinityMessage { #[serde(default, skip_serializing_if = "Option::is_none")] invocation: Option>, }, + /// The thread's in-flight work was interrupted here. The model-facing + /// [`INTERRUPT_TOKEN`] is derived at render time by [`render_history`]. + #[serde(rename = "interrupt")] + Interrupt, +} + +/// The token the model sees for an [`InfinityMessage::Interrupt`]. Older +/// versions stored it as a literal prefix of the interrupting user text. +pub const INTERRUPT_TOKEN: &str = ""; + +/// Text used to settle a tool call as interrupted by the user. Rendered for a +/// call followed by an [`InfinityMessage::Interrupt`] (or, in histories cut +/// short by a crash, directly by user text), and also substituted for a +/// pending tool result during overflow recovery when user input had to be +/// dropped: the next thing the model sees is a fresh user message, and +/// "interrupted by user" describes that situation accurately, whereas a +/// "too large" placeholder could mislead the model into re-running the tool. +pub const TOOL_CALL_INTERRUPTED_TEXT: &str = "Tool call interrupted by user"; + +/// Text used to settle a tool call that was cut short by an incoming event +/// (a subscription event or a child thread's report), which follows it +/// directly in history. +pub const TOOL_CALL_INTERRUPTED_BY_EVENT_TEXT: &str = + "Tool call interrupted by an incoming event (see the next message)"; + +/// Render history into the [`Message`]s sent to the model. +/// +/// A tool call that is directly followed by anything other than a tool call +/// or a tool result was interrupted; it is rendered as answered with an +/// "interrupted" result whose text names the cause (the user for an +/// [`InfinityMessage::Interrupt`] or user text, an incoming event for a +/// subscription event). Event interruptions are *inferred* this way rather +/// than recorded: the event itself is the record, and a history that ends on +/// the bare tool call therefore means the thread was cut off mid-flight, +/// not stopped. +/// +/// An [`InfinityMessage::Interrupt`] that does not settle a tool call is +/// prefixed onto the user text that follows it (the shape older versions +/// stored), or rendered standalone if none does. Consecutive interrupts +/// collapse into one token. +pub fn render_history<'a>(history: impl IntoIterator) -> Vec { + let mut messages = Vec::new(); + let mut interrupted = false; + let mut prev: Option<&InfinityMessage> = None; + for msg in history { + if let Some(InfinityMessage::ToolCall { call, .. }) = prev.replace(msg) + && !matches!( + msg, + InfinityMessage::ToolCall { .. } | InfinityMessage::ToolResult { .. } + ) + { + let reason = match msg { + InfinityMessage::SubscriptionEvent { .. } => TOOL_CALL_INTERRUPTED_BY_EVENT_TEXT, + _ => TOOL_CALL_INTERRUPTED_TEXT, + }; + messages.push(Message::User { + content: vec![UserContent::ToolResult(interrupted_result(call, reason))], + }); + if matches!(msg, InfinityMessage::Interrupt) { + // The marker's whole meaning was the settlement above. + continue; + } + } + match msg { + InfinityMessage::Interrupt => interrupted = true, + InfinityMessage::User { + content: UserContent::Text(text), + } if interrupted => { + interrupted = false; + messages.push(Message::User { + content: vec![UserContent::text(format!("{INTERRUPT_TOKEN}{}", text.text))], + }); + } + other => { + if std::mem::take(&mut interrupted) { + messages.extend(InfinityMessage::Interrupt.into_messages()); + } + messages.extend(other.clone().into_messages()); + } + } + } + if interrupted { + messages.extend(InfinityMessage::Interrupt.into_messages()); + } + messages +} + +/// The result the model sees for an interrupted tool call. +fn interrupted_result(call: &ToolCall, reason: &str) -> ToolResult { + ToolResult { + id: call.id.clone(), + call_id: call.call_id.clone(), + content: vec![ToolResultContent::Text(Text { + text: reason.to_owned(), + })], + } } impl InfinityMessage { @@ -257,6 +375,9 @@ impl InfinityMessage { }); msgs } + Self::Interrupt => vec![Message::User { + content: vec![UserContent::text(INTERRUPT_TOKEN)], + }], } } @@ -297,3 +418,77 @@ impl InfinityMessage { } } } + +#[cfg(test)] +mod tests { + use super::*; + + fn user(text: &str) -> InfinityMessage { + InfinityMessage::User { + content: UserContent::text(text), + } + } + + fn rendered(history: impl IntoIterator) -> Vec { + history + .into_iter() + .flat_map(InfinityMessage::into_messages) + .collect() + } + + #[test] + fn interrupt_without_following_text_renders_standalone() { + let assistant = InfinityMessage::Assistant { + content: AssistantContent::text("hi"), + }; + assert_eq!( + render_history(&[user("go"), InfinityMessage::Interrupt]), + rendered([user("go"), user("")]) + ); + assert_eq!( + render_history(&[InfinityMessage::Interrupt, assistant.clone()]), + rendered([user(""), assistant]) + ); + } + + #[test] + fn interrupt_after_tool_call_renders_as_interrupted_result() { + let tool_call = ToolCall { + id: "tc-1".to_owned(), + call_id: None, + function: infinity_provider_protocol::message::ToolFunction { + name: "some_tool".to_owned(), + arguments: serde_json::json!({}), + }, + }; + // Older versions stored this synthetic result; it renders unchanged. + let legacy = InfinityMessage::ToolResult { + result: interrupted_result(&tool_call, TOOL_CALL_INTERRUPTED_TEXT), + display_segments: None, + }; + let call = InfinityMessage::ToolCall { + call: tool_call, + display_as: None, + }; + assert_eq!( + render_history(&[call.clone(), InfinityMessage::Interrupt, user("hi")]), + rendered([call.clone(), legacy.clone(), user("hi")]) + ); + assert_eq!( + render_history(&[call.clone(), legacy.clone(), user("hi")]), + rendered([call, legacy, user("hi")]) + ); + } + + #[test] + fn consecutive_interrupts_collapse_into_one_token() { + assert_eq!( + render_history(&[ + InfinityMessage::Interrupt, + InfinityMessage::Interrupt, + user("again") + ]), + rendered([user("again")]) + ); + } +} diff --git a/crates/infinity-agent-core/src/snapshots/infinity_agent_core__event_processor__tests__associative_subscription_event_tool_interruption.snap b/crates/infinity-agent-core/src/snapshots/infinity_agent_core__event_processor__tests__associative_subscription_event_tool_interruption.snap index 0f80c57f..8f9ed480 100644 --- a/crates/infinity-agent-core/src/snapshots/infinity_agent_core__event_processor__tests__associative_subscription_event_tool_interruption.snap +++ b/crates/infinity-agent-core/src/snapshots/infinity_agent_core__event_processor__tests__associative_subscription_event_tool_interruption.snap @@ -22,18 +22,6 @@ expression: hm.history.into_inner() } } }, - { - "kind": "tool_result", - "result": { - "id": "tc-cmd", - "content": [ - { - "type": "text", - "text": "Tool call interrupted by user" - } - ] - } - }, { "kind": "subscription_event", "result": { diff --git a/crates/infinity-agent-core/src/snapshots/infinity_agent_core__event_processor__tests__consecutive_text_chunks_are_coalesced.snap b/crates/infinity-agent-core/src/snapshots/infinity_agent_core__event_processor__tests__consecutive_text_chunks_are_coalesced.snap index df0d2455..8b64cf8b 100644 --- a/crates/infinity-agent-core/src/snapshots/infinity_agent_core__event_processor__tests__consecutive_text_chunks_are_coalesced.snap +++ b/crates/infinity-agent-core/src/snapshots/infinity_agent_core__event_processor__tests__consecutive_text_chunks_are_coalesced.snap @@ -10,6 +10,6 @@ expression: hm.pending_items.borrow().clone() "text": "Hello, world" } }, - "message_id": "c-1" + "dedup_id": null } ] diff --git a/crates/infinity-agent-core/src/snapshots/infinity_agent_core__event_processor__tests__text_chunks_not_coalesced_across_non_text_item.snap b/crates/infinity-agent-core/src/snapshots/infinity_agent_core__event_processor__tests__text_chunks_not_coalesced_across_non_text_item.snap index 0bb9b744..1a545846 100644 --- a/crates/infinity-agent-core/src/snapshots/infinity_agent_core__event_processor__tests__text_chunks_not_coalesced_across_non_text_item.snap +++ b/crates/infinity-agent-core/src/snapshots/infinity_agent_core__event_processor__tests__text_chunks_not_coalesced_across_non_text_item.snap @@ -10,7 +10,7 @@ expression: hm.pending_items.borrow().clone() "text": "before" } }, - "message_id": "c-1" + "dedup_id": null }, { "message": { @@ -23,7 +23,7 @@ expression: hm.pending_items.borrow().clone() } } }, - "message_id": "c-2" + "dedup_id": null }, { "message": { @@ -32,6 +32,6 @@ expression: hm.pending_items.borrow().clone() "text": "after" } }, - "message_id": "c-3" + "dedup_id": null } ] diff --git a/crates/infinity-agent-core/src/snapshots/infinity_agent_core__event_processor__tests__thread_report_tool_interruption.snap b/crates/infinity-agent-core/src/snapshots/infinity_agent_core__event_processor__tests__thread_report_tool_interruption.snap index b14e86c6..37e8f9e7 100644 --- a/crates/infinity-agent-core/src/snapshots/infinity_agent_core__event_processor__tests__thread_report_tool_interruption.snap +++ b/crates/infinity-agent-core/src/snapshots/infinity_agent_core__event_processor__tests__thread_report_tool_interruption.snap @@ -22,18 +22,6 @@ expression: hm.history.into_inner() } } }, - { - "kind": "tool_result", - "result": { - "id": "tc-sub", - "content": [ - { - "type": "text", - "text": "Tool call interrupted by user" - } - ] - } - }, { "kind": "subscription_event", "result": { diff --git a/crates/infinity-agent-core/src/snapshots/infinity_agent_core__event_processor__tests__user_message_interrupts_pending_tool_call.snap b/crates/infinity-agent-core/src/snapshots/infinity_agent_core__event_processor__tests__user_message_interrupts_pending_tool_call.snap index b9d62f4d..9c6e0a4b 100644 --- a/crates/infinity-agent-core/src/snapshots/infinity_agent_core__event_processor__tests__user_message_interrupts_pending_tool_call.snap +++ b/crates/infinity-agent-core/src/snapshots/infinity_agent_core__event_processor__tests__user_message_interrupts_pending_tool_call.snap @@ -23,16 +23,7 @@ expression: hm.history.into_inner() } }, { - "kind": "tool_result", - "result": { - "id": "tc-1", - "content": [ - { - "type": "text", - "text": "Tool call interrupted by user" - } - ] - } + "kind": "interrupt" }, { "kind": "user", diff --git a/crates/infinity-agent-core/src/stores.rs b/crates/infinity-agent-core/src/stores.rs index 1ab14751..ea477320 100644 --- a/crates/infinity-agent-core/src/stores.rs +++ b/crates/infinity-agent-core/src/stores.rs @@ -62,12 +62,33 @@ pub struct CompactionSummary { pub up_to_order: i64, } +/// One thread's message history plus an index of its dedup ids, kept +/// together so [`ConversationStore::is_message_processed`] is O(1) and the +/// index can never drift from the entries. +#[derive(Default)] +struct ThreadMessages { + entries: Vec<(InfinityMessage, Option)>, + ids: HashSet, +} + +impl ThreadMessages { + fn from_entries(entries: Vec<(InfinityMessage, Option)>) -> Self { + let ids = entries.iter().filter_map(|(_, id)| id.clone()).collect(); + Self { entries, ids } + } + + fn extend(&mut self, messages: Vec<(InfinityMessage, Option)>) { + self.ids + .extend(messages.iter().filter_map(|(_, id)| id.clone())); + self.entries.extend(messages); + } +} + /// An in-memory [`ConversationStore`]: threads, message history, the thread /// tree, and compaction summaries, all in process memory. #[derive(Clone, Default)] pub struct InMemoryConversationStore { - #[expect(clippy::type_complexity, reason = "shared state")] - messages: Arc>>>, + messages: Arc>>, threads: Arc>>, compaction_summaries: Arc>>>, } @@ -102,17 +123,17 @@ impl InMemoryConversationStore { .insert(thread_id.to_owned(), info); } - /// Snapshot one thread's messages (with their dedup IDs), if any were - /// ever appended. + /// Snapshot one thread's messages (with the dedup IDs of those that + /// arrived as inputs), if any were ever appended. pub fn thread_messages( &self, thread_id: &ThreadId, - ) -> Option> { + ) -> Option)>> { self.messages .lock() .expect("bug: mutex poisoned") .get(thread_id) - .cloned() + .map(|t| t.entries.clone()) } /// Restore one thread's messages. Returns `true` if messages for the @@ -120,12 +141,12 @@ impl InMemoryConversationStore { pub fn set_thread_messages( &self, thread_id: &ThreadId, - messages: Vec<(InfinityMessage, String)>, + messages: Vec<(InfinityMessage, Option)>, ) -> bool { self.messages .lock() .expect("bug: mutex poisoned") - .insert(thread_id.to_owned(), messages) + .insert(thread_id.to_owned(), ThreadMessages::from_entries(messages)) .is_some() } @@ -232,7 +253,8 @@ impl ConversationStore for InMemoryConversationStore { let msgs = self.messages.lock().expect("bug: mutex poisoned"); Ok(msgs .get(session_id) - .map(|v| { + .map(|t| { + let v = &t.entries; let start = start_from.unwrap_or(0) as usize; let end = up_to.map(|u| u as usize).unwrap_or(v.len()).min(v.len()); let start = start.min(end); @@ -244,7 +266,7 @@ impl ConversationStore for InMemoryConversationStore { async fn append_messages( &self, session_id: &ThreadId, - messages: Vec<(InfinityMessage, String)>, + messages: Vec<(InfinityMessage, Option)>, ) -> Result<(), Self::Error> { let mut store = self.messages.lock().expect("bug: mutex poisoned"); store @@ -254,6 +276,17 @@ impl ConversationStore for InMemoryConversationStore { Ok(()) } + async fn is_message_processed( + &self, + thread_id: &ThreadId, + message_id: &str, + ) -> Result { + let msgs = self.messages.lock().expect("bug: mutex poisoned"); + Ok(msgs + .get(thread_id) + .is_some_and(|t| t.ids.contains(message_id))) + } + async fn spawn_thread( &self, parent_thread_id: &ThreadId, @@ -407,8 +440,6 @@ impl ConversationStore for InMemoryConversationStore { /// embeddings that layer persistence on top (export/restore). #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct ThreadState { - #[serde(default)] - pub processed_message_ids: HashSet, #[serde(default)] pub metadata: Option, #[serde(default)] @@ -417,11 +448,10 @@ pub struct ThreadState { pub pending_user_choices: Vec, } -/// An in-memory [`StateStore`]: processed IDs, metadata, and active -/// subscription tracking in process memory. +/// An in-memory [`StateStore`]: metadata, active subscriptions and pending +/// user choices in process memory. #[derive(Clone, Default)] pub struct InMemoryStateStore { - processed_ids: Arc>>>, metadata: Arc>>, subscriptions: Arc>>>, pending_user_choices: Arc>>>, @@ -434,7 +464,6 @@ impl InMemoryStateStore { /// Snapshot one thread's state (see [`ThreadState`]). pub fn thread_state(&self, thread_id: &ThreadId) -> ThreadState { - let processed = self.processed_ids.lock().expect("bug: mutex poisoned"); let metadata = self.metadata.lock().expect("bug: mutex poisoned"); let subscriptions = self.subscriptions.lock().expect("bug: mutex poisoned"); let pending_user_choices = self @@ -442,7 +471,6 @@ impl InMemoryStateStore { .lock() .expect("bug: mutex poisoned"); ThreadState { - processed_message_ids: processed.get(thread_id).cloned().unwrap_or_default(), metadata: metadata.get(thread_id).cloned(), subscriptions: subscriptions.get(thread_id).cloned().unwrap_or_default(), pending_user_choices: pending_user_choices @@ -454,10 +482,6 @@ impl InMemoryStateStore { /// Restore one thread's state (see [`ThreadState`]). pub fn set_thread_state(&self, thread_id: &ThreadId, state: ThreadState) { - self.processed_ids - .lock() - .expect("bug: mutex poisoned") - .insert(thread_id.to_owned(), state.processed_message_ids); if let Some(meta) = state.metadata { self.metadata .lock() @@ -483,27 +507,6 @@ impl InMemoryStateStore { impl StateStore for InMemoryStateStore { type Error = InMemoryStoreError; - async fn get_processed_ids( - &self, - thread_id: &ThreadId, - ) -> Result, Self::Error> { - let store = self.processed_ids.lock().expect("bug: mutex poisoned"); - Ok(store.get(thread_id).cloned().unwrap_or_default()) - } - - async fn add_processed_message_ids( - &self, - thread_id: &ThreadId, - message_ids: Vec, - ) -> Result<(), Self::Error> { - let mut store = self.processed_ids.lock().expect("bug: mutex poisoned"); - store - .entry(thread_id.to_owned()) - .or_default() - .extend(message_ids); - Ok(()) - } - async fn get_metadata( &self, root_thread_id: &ThreadId, @@ -644,8 +647,8 @@ mod tests { .append_messages( ThreadId::from_ref("root"), vec![ - (user_msg("root one"), "m1".to_owned()), - (user_msg("root two"), "m2".to_owned()), + (user_msg("root one"), Some("m1".to_owned())), + (user_msg("root two"), Some("m2".to_owned())), ], ) .await @@ -661,7 +664,7 @@ mod tests { .await .expect("spawn fresh child"); store - .append_messages(&child, vec![(user_msg("child own"), "c1".to_owned())]) + .append_messages(&child, vec![(user_msg("child own"), Some("c1".to_owned()))]) .await .expect("append child"); @@ -683,7 +686,7 @@ mod tests { store .append_messages( ThreadId::from_ref("root"), - vec![(user_msg("root secret"), "m1".to_owned())], + vec![(user_msg("root secret"), Some("m1".to_owned()))], ) .await .expect("append"); @@ -699,7 +702,10 @@ mod tests { .await .expect("spawn fresh child"); store - .append_messages(&fresh, vec![(user_msg("fresh work"), "f1".to_owned())]) + .append_messages( + &fresh, + vec![(user_msg("fresh work"), Some("f1".to_owned()))], + ) .await .expect("append fresh"); @@ -713,7 +719,10 @@ mod tests { .await .expect("spawn grandchild"); store - .append_messages(&grandchild, vec![(user_msg("gc work"), "g1".to_owned())]) + .append_messages( + &grandchild, + vec![(user_msg("gc work"), Some("g1".to_owned()))], + ) .await .expect("append grandchild"); @@ -739,7 +748,7 @@ mod tests { store .append_messages( ThreadId::from_ref("root"), - vec![(user_msg("root one"), "m1".to_owned())], + vec![(user_msg("root one"), Some("m1".to_owned()))], ) .await .expect("append"); @@ -754,7 +763,7 @@ mod tests { .await .expect("spawn child"); store - .append_messages(&child, vec![(user_msg("child own"), "c1".to_owned())]) + .append_messages(&child, vec![(user_msg("child own"), Some("c1".to_owned()))]) .await .expect("append child"); diff --git a/crates/infinity-agent-core/src/system/defer.rs b/crates/infinity-agent-core/src/system/defer.rs index 989e0129..f4d39afa 100644 --- a/crates/infinity-agent-core/src/system/defer.rs +++ b/crates/infinity-agent-core/src/system/defer.rs @@ -4,8 +4,8 @@ //! When a thread has dispatched a tool call and is waiting for its result, //! processing an unrelated synthetic event (a subscription event, a child //! thread's report, a message from the parent) would *interrupt* the pending -//! call: the runtime injects a synthetic "interrupted" result so the history -//! stays well-formed, and the real result is later dropped as stale. To avoid +//! call: the event is appended after it, the call is rendered to the model as +//! interrupted, and the real result is later dropped as stale. To avoid //! cancelling work that is still running, such events should be deferred //! until the pending call is answered. //! diff --git a/crates/infinity-agent-core/src/system/local/driver.rs b/crates/infinity-agent-core/src/system/local/driver.rs index 201a2afd..e82dd5a2 100644 --- a/crates/infinity-agent-core/src/system/local/driver.rs +++ b/crates/infinity-agent-core/src/system/local/driver.rs @@ -195,13 +195,11 @@ pub(crate) async fn drive_thread( .into_iter() .partition(|(msg, _)| is_user_text_input(msg)); - if let InputMessageContent::User(UserContent::Text(text)) = - &mut user_inputs[0].0.content - { - text.text = format!("{}", text.text); - } else { - panic!("bug: user_inputs should only contain user text"); - } + // The marker records the interruption and settles a + // trailing tool call (see `render_history`). + let marker_id = format!("{}-interrupt", user_inputs[0].1); + let marker = (InputMessage::interrupt(thread_id.to_owned()), marker_id); + user_inputs.insert(0, marker); pending_batch.extend(non_user_inputs); user_inputs diff --git a/crates/infinity-agent-core/src/system/tests.rs b/crates/infinity-agent-core/src/system/tests.rs index 4bde4307..a40220f8 100644 --- a/crates/infinity-agent-core/src/system/tests.rs +++ b/crates/infinity-agent-core/src/system/tests.rs @@ -189,7 +189,7 @@ async fn user_text_interrupts_active_completion() { let local = tokio::task::LocalSet::new(); local .run_until(async { - let (running, mut rx, mut ctrl, _conv) = start_system(vec![], None); + let (running, mut rx, mut ctrl, conv) = start_system(vec![], None); running .send_user_text(ThreadId::from_ref("t1"), "first") .await; @@ -205,18 +205,30 @@ async fn user_text_interrupts_active_completion() { .send_user_text(ThreadId::from_ref("t1"), "stop that") .await; let req2 = ctrl.next_request().await; - let has_interrupt = req2.chat_history.into_iter().any(|m| { - if let infinity_provider_protocol::message::Message::User { content } = &m - && let Some(UserContent::Text(t)) = content.first() - { - return t.text.contains(""); - } - false - }); - assert!(has_interrupt, "interrupting input should carry the marker"); + assert_eq!( + req2.chat_history.last(), + Some(&infinity_provider_protocol::message::Message::User { + content: vec![UserContent::text("stop that")] + }) + ); ctrl.send_text("ok stopped"); ctrl.finish(); + // The cancelled first round reports its own completion first. + collect_until_finished(&mut rx).await; collect_until_finished(&mut rx).await; + + // The interrupt is its own history entry; the text is stored as typed. + let stored = conv + .thread_messages(ThreadId::from_ref("t1")) + .unwrap_or_default(); + assert!( + stored.windows(2).any(|w| matches!( + w, + [(crate::message::InfinityMessage::Interrupt, _), (crate::message::InfinityMessage::User { content: UserContent::Text(t) }, _)] + if t.text == "stop that" + )), + "{stored:?}" + ); }) .await; } @@ -512,7 +524,7 @@ async fn shutdown_persists_model_validated_tool_result() { /// arrived tool result must not persist that result: the model never /// validated it, and it could be the oversized input that permanently /// wedges the thread. The durable state keeps the tool call unanswered -/// (a later user input settles it with a synthetic "interrupted" result). +/// (a later user input settles it as interrupted). #[tokio::test(flavor = "current_thread")] async fn shutdown_does_not_persist_unvalidated_tool_result() { let local = tokio::task::LocalSet::new(); @@ -1329,8 +1341,8 @@ async fn oversized_tool_result_never_wedges_the_thread() { /// Reboot recovery: a session dies while a tool result was still /// unvalidated, so the durable store ends on the unanswered tool *call*. /// When a fresh session boots from that store and user input arrives, the -/// stranded call must be settled with a synthetic "interrupted" result and -/// the thread must keep working. +/// stranded call must be settled with an interrupt (rendered to the model +/// as an "interrupted" result) and the thread must keep working. #[tokio::test(flavor = "current_thread")] async fn rebooted_session_settles_persisted_unanswered_tool_call() { let local = tokio::task::LocalSet::new(); @@ -1401,10 +1413,12 @@ async fn rebooted_session_settles_persisted_unanswered_tool_call() { assert_eq!(texts, vec!["back online"]); wait_idle(&mut running2).await; - // Everything from the recovered round is validated + persisted. + // Everything from the recovered round is validated + persisted; + // the call is settled by an interrupt entry, not a fake result. let stored = persisted(&conv, "t1"); assert!( - stored.contains("Tool call interrupted by user") + stored.contains("(Interrupt, None)") + && !stored.contains("Tool call interrupted by user") && stored.contains("hello again") && stored.contains("back online"), "recovered round must persist; store: {stored}" diff --git a/crates/infinity-agent-core/src/system/thread.rs b/crates/infinity-agent-core/src/system/thread.rs index 68fe013f..71fef7b8 100644 --- a/crates/infinity-agent-core/src/system/thread.rs +++ b/crates/infinity-agent-core/src/system/thread.rs @@ -208,8 +208,8 @@ where /// The thread is waiting for the result of a dispatched tool call whose /// tool represents in-flight work (i.e. it is not a passive tool like the /// sleep family). While this is `Some`, deferrable synthetic events must - /// not be processed — doing so would inject an "interrupted" result for - /// a call that is actually still running. + /// not be processed — doing so would settle a call that is actually + /// still running as interrupted. /// /// If the thread's configuration has not been resolved yet (no step has /// run), the call is conservatively treated as active. @@ -434,17 +434,20 @@ where // ── Prepare phase: fold each input into history ── let mut any_ready = false; - let mut last_message_id = String::new(); for (input_msg, message_id) in inputs { - if self - .prepare_one(input_msg, message_id.clone(), observer) - .await? - { + if self.prepare_one(input_msg, message_id, observer).await? { any_ready = true; - last_message_id = message_id; } } + // ── Commit barrier: everything known-safe after folding the inputs + // (an interrupt marker settling a tool call, a partial turn flushed + // by a cancelled step) becomes durable before anything external + // reacts to it — before tools are cancelled below and before the + // model is invoked. Unvalidated inputs are untouched by `sync`, so + // this is always safe to do unconditionally. ── + self.history.sync().await?; + // Best-effort: notify RAP tool servers about interrupted tool calls. // Dismissing the associated pending user choices is a durable state // transition: it is awaited before the step continues, so the agent @@ -473,11 +476,8 @@ where } if !any_ready { - // Commit anything already known-safe (e.g. processed IDs from - // deduped inputs). Interruption results and other fresh inputs - // stay unvalidated — and unpersisted — until a completion - // produces model output for them. - self.history.sync().await?; + // Fresh inputs stay unvalidated — and unpersisted — until a + // completion produces model output for them. return Ok(StepOutcome::Skipped); } @@ -531,8 +531,6 @@ where &tool_defs, &tool_registry, &tool_context, - &thread_id, - &last_message_id, config.extra_system_prompt.as_deref(), cancel, )); diff --git a/crates/infinity-agent-core/src/tools/thread.rs b/crates/infinity-agent-core/src/tools/thread.rs index dc6349cf..ef7c6367 100644 --- a/crates/infinity-agent-core/src/tools/thread.rs +++ b/crates/infinity-agent-core/src/tools/thread.rs @@ -161,10 +161,7 @@ impl Tool for Spawn }; if let Err(e) = self .conversation_store - .append_messages( - &new_thread_id, - vec![(spawn_tool_call, format!("{}-spawn-call", id))], - ) + .append_messages(&new_thread_id, vec![(spawn_tool_call, None)]) .await { tracing::error!("failed to seed child thread with spawn call: {e}"); diff --git a/crates/infinity-agent-core/src/traits.rs b/crates/infinity-agent-core/src/traits.rs index 7d63001e..7cfad6c3 100644 --- a/crates/infinity-agent-core/src/traits.rs +++ b/crates/infinity-agent-core/src/traits.rs @@ -148,12 +148,32 @@ pub trait ConversationStore: Send + Sync + Clone { Ok((combined, None, ancestor_prefix_len)) } + /// Append entries to a thread's own history. Each entry carries the dedup + /// id it arrived under if it was an input from the input queue, or `None` + /// if the runtime minted it (model output, synthetic tool results, + /// interrupt markers); only the former are ever consulted by + /// [`is_message_processed`](Self::is_message_processed). async fn append_messages( &self, session_id: &ThreadId, - messages: Vec<(InfinityMessage, String)>, + messages: Vec<(InfinityMessage, Option)>, ) -> Result<(), Self::Error>; + /// Whether a message with dedup id `message_id` has already been + /// persisted to `thread_id`'s own history. + /// + /// The runtime consults this for each incoming input it has not seen in + /// its own lifetime, so a redelivered input (after a crash, or a retried + /// delivery) is not appended twice. The answer is a point lookup against + /// the persisted history rather than a separately recorded set, so a + /// crash between two writes can never leave a message persisted without + /// its dedup id (or vice versa). + async fn is_message_processed( + &self, + thread_id: &ThreadId, + message_id: &str, + ) -> Result; + async fn spawn_thread( &self, parent_thread_id: &ThreadId, @@ -217,26 +237,16 @@ pub trait ConversationStore: Send + Sync + Clone { ) -> Result, Self::Error>; } -/// Key-value state store for processed message IDs, metadata, toolset caches -/// (DynamoDB in Lambda, in-memory HashMap for CLI). +/// Key-value state store for session metadata, active subscriptions and +/// pending user choices (DynamoDB in Lambda, in-memory HashMap for CLI). +/// +/// Processed message ids are deliberately *not* part of this store: they are +/// looked up in the conversation history itself (see +/// [`ConversationStore::is_message_processed`]). #[async_trait] pub trait StateStore: Send + Sync + Clone { type Error: std::error::Error + Send + Sync + 'static; - /// Durably deduplicated message IDs for this thread. Only inputs that are - /// not naturally idempotent are tracked (user text and subscription - /// events); tool results are deduplicated against history itself. - async fn get_processed_ids( - &self, - thread_id: &ThreadId, - ) -> Result, Self::Error>; - - async fn add_processed_message_ids( - &self, - thread_id: &ThreadId, - message_ids: Vec, - ) -> Result<(), Self::Error>; - async fn get_metadata( &self, root_thread_id: &ThreadId, diff --git a/crates/infinity-agent-lambda/src/conversation_history.rs b/crates/infinity-agent-lambda/src/conversation_history.rs index 5bd3ecd7..d8f15b27 100644 --- a/crates/infinity-agent-lambda/src/conversation_history.rs +++ b/crates/infinity-agent-lambda/src/conversation_history.rs @@ -101,6 +101,21 @@ impl DsqlConversationStore { .await .map_err(|e| Error::from(format!("Failed to create index: {}", e)))?; + // Runtime-minted entries (model output, synthetic tool results, + // interrupt markers) have no dedup id; only inputs do. Idempotent. + sqlx::query(r#"ALTER TABLE conversation_history ALTER COLUMN message_id DROP NOT NULL"#) + .execute(&pool) + .await + .map_err(|e| Error::from(format!("Failed to make message_id nullable: {}", e)))?; + + sqlx::query( + r#"CREATE INDEX ASYNC IF NOT EXISTS idx_conversation_history_session_message_id + ON conversation_history (session_id, message_id)"#, + ) + .execute(&pool) + .await + .map_err(|e| Error::from(format!("Failed to create message_id index: {}", e)))?; + sqlx::query( r#"CREATE TABLE IF NOT EXISTS thread_hierarchy ( thread_id VARCHAR(255) PRIMARY KEY, @@ -153,6 +168,20 @@ impl DsqlConversationStore { } } +/// Decode a `message_data` column: the current [`InfinityMessage`] JSON, or +/// the legacy bare [`Message`] written before display metadata was stored. +/// Undecodable rows are logged and skipped. +fn parse_message_data(json_str: String) -> Option { + if let Ok(msg) = serde_json::from_str::(&json_str) { + Some(msg) + } else if let Ok(msg) = serde_json::from_str::(&json_str) { + Some(InfinityMessage::from_message(msg)) + } else { + tracing::error!("skipping undecodable conversation_history row: {json_str}"); + None + } +} + #[async_trait] impl ConversationStore for DsqlConversationStore { type Error = DsqlError; @@ -212,23 +241,16 @@ impl ConversationStore for DsqlConversationStore { .await .map_err(|e| DsqlError(format!("Failed to load history: {}", e)))?; - let mut messages = Vec::new(); - for row in rows { - let json_str: String = row.get("message_data"); - // Try new InfinityMessage format first, fall back to the legacy bare Message - if let Ok(msg) = serde_json::from_str::(&json_str) { - messages.push(msg); - } else if let Ok(msg) = serde_json::from_str::(&json_str) { - messages.push(InfinityMessage::from_message(msg)); - } - } - Ok(messages) + Ok(rows + .iter() + .filter_map(|row| parse_message_data(row.get("message_data"))) + .collect()) } async fn append_messages( &self, session_id: &ThreadId, - messages: Vec<(InfinityMessage, String)>, + messages: Vec<(InfinityMessage, Option)>, ) -> Result<(), DsqlError> { if messages.is_empty() { return Ok(()); @@ -246,7 +268,7 @@ impl ConversationStore for DsqlConversationStore { let mut current_order = max_order.unwrap_or(0); let mut session_ids = Vec::new(); let mut message_orders = Vec::new(); - let mut message_ids_vec = Vec::new(); + let mut message_ids_vec: Vec> = Vec::new(); let mut message_data = Vec::new(); for (message, message_id) in messages { @@ -284,6 +306,26 @@ impl ConversationStore for DsqlConversationStore { Ok(()) } + async fn is_message_processed( + &self, + thread_id: &ThreadId, + message_id: &str, + ) -> Result { + // Every history row carries the dedup id it was appended under, so + // this is a point lookup on the history itself (no separate table to + // drift out of sync with it). + sqlx::query_scalar( + r#"SELECT EXISTS ( + SELECT 1 FROM conversation_history WHERE session_id = $1 AND message_id = $2 + )"#, + ) + .bind(thread_id.as_str()) + .bind(message_id) + .fetch_one(&self.pool) + .await + .map_err(|e| DsqlError(format!("Failed to check processed message id: {e}"))) + } + async fn spawn_thread( &self, parent_thread_id: &ThreadId, diff --git a/crates/infinity-agent-lambda/src/state_store.rs b/crates/infinity-agent-lambda/src/state_store.rs index cd085169..a068e345 100644 --- a/crates/infinity-agent-lambda/src/state_store.rs +++ b/crates/infinity-agent-lambda/src/state_store.rs @@ -3,7 +3,6 @@ use aws_sdk_dynamodb::{Client as DynamoDbClient, types::AttributeValue}; use infinity_agent_core::ThreadId; use infinity_agent_core::system::UserChoice; use infinity_agent_core::traits::StateStore; -use std::collections::HashSet; #[derive(Clone)] pub struct DynamoDbStateStore { @@ -30,52 +29,6 @@ impl DynamoDbStateStore { impl StateStore for DynamoDbStateStore { type Error = DynamoError; - async fn get_processed_ids( - &self, - thread_id: &ThreadId, - ) -> Result, DynamoError> { - let result = self - .client - .get_item() - .table_name(&self.table_name) - .key("session", AttributeValue::S(thread_id.as_str().to_owned())) - .send() - .await - .map_err(|e| DynamoError(format!("Failed to get processed IDs: {}", e)))?; - - if let Some(item) = result.item { - let processed_ids = - if let Some(AttributeValue::Ss(ids)) = item.get("processed_message_ids") { - ids.iter().cloned().collect() - } else { - HashSet::new() - }; - Ok(processed_ids) - } else { - Ok(HashSet::new()) - } - } - - async fn add_processed_message_ids( - &self, - thread_id: &ThreadId, - message_ids: Vec, - ) -> Result<(), DynamoError> { - if message_ids.is_empty() { - return Ok(()); - } - self.client - .update_item() - .table_name(&self.table_name) - .key("session", AttributeValue::S(thread_id.as_str().to_owned())) - .update_expression("ADD processed_message_ids :ids") - .expression_attribute_values(":ids", AttributeValue::Ss(message_ids)) - .send() - .await - .map_err(|e| DynamoError(format!("Failed to add processed message IDs: {}", e)))?; - Ok(()) - } - async fn get_metadata( &self, root_thread_id: &ThreadId, diff --git a/crates/infinity-daemon/Cargo.toml b/crates/infinity-daemon/Cargo.toml index 7b0b1ca3..7332a59f 100644 --- a/crates/infinity-daemon/Cargo.toml +++ b/crates/infinity-daemon/Cargo.toml @@ -42,6 +42,7 @@ http-body-util = "0.1" tokio-util = { version = "0.7", features = ["codec", "rt"] } bytes = "1" dirs = "6" +tempfile = { workspace = true } tokio-tungstenite = "0.26" include_dir = { version = "0.7", optional = true } @@ -57,7 +58,6 @@ nix = { version = "0.31", features = ["signal"] } [dev-dependencies] tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } rap-test-servers = { path = "../rap-test-servers" } -tempfile = { workspace = true } infinity-provider-protocol = { path = "../infinity-provider-protocol", version = "^0.2.0", features = ["mock"] } insta = { workspace = true } diff --git a/crates/infinity-daemon/src/lib.rs b/crates/infinity-daemon/src/lib.rs index b42feb9a..d51897bd 100644 --- a/crates/infinity-daemon/src/lib.rs +++ b/crates/infinity-daemon/src/lib.rs @@ -5,6 +5,7 @@ pub mod mcp_proxy; pub mod memory_store; pub mod migrate; pub mod models; +pub mod persist; pub mod rap_callback; pub mod rap_servers; pub mod remote; diff --git a/crates/infinity-daemon/src/memory_store.rs b/crates/infinity-daemon/src/memory_store.rs index bcfb3ee4..393c3a60 100644 --- a/crates/infinity-daemon/src/memory_store.rs +++ b/crates/infinity-daemon/src/memory_store.rs @@ -1,16 +1,44 @@ -//! The daemon's stores: the core in-memory stores wrapped with per-thread -//! JSON-file persistence and daemon-only bookkeeping. +//! The daemon's stores: the core in-memory stores wrapped with crash-safe +//! per-thread file persistence and daemon-only bookkeeping. //! //! All shared [`ConversationStore`] / [`StateStore`] semantics (spawn orders, //! ancestor chains, compaction cutoffs, dedup sets, subscriptions, metadata) //! live in `infinity_agent_core::stores` — the trait impls here are pure //! delegation. This module layers on top: //! -//! - lazy per-thread loading from and saving to `{dir}/{thread_id}*.json`, +//! - lazy per-thread loading from and saving to the files below, //! - daemon-only per-thread extras ([`ThreadExtras`]: title, children, //! token totals, timestamps, the selected model), //! - transient and persisted views, //! - session serialization for migration. +//! +//! # On-disk layout +//! +//! Under the threads directory (`{state_dir}/threads`): +//! +//! | file | contents | write pattern | +//! |---|---|---| +//! | `{thread_id}.jsonl` | conversation log: messages (inputs with their dedup ids) and compaction summaries | append-only ([`ThreadLog`]) | +//! | `{thread_id}.meta.json` | [`ThreadMeta`]: core thread info + daemon extras | atomic replace | +//! | `{thread_id}.views.json` | RAP views (`view_type → content`) | atomic replace | +//! +//! Under the state directory (`{state_dir}/state`): +//! +//! | file | contents | write pattern | +//! |---|---|---| +//! | `{thread_id}.state.json` | subscriptions, pending user choices, session metadata | atomic replace | +//! +//! The conversation log is the single source of truth for everything that is +//! derived from the conversation. In particular processed (dedup) message ids +//! are *not* stored separately: each input entry carries its dedup id, and +//! [`ConversationStore::is_message_processed`] looks ids up in the loaded +//! log. This removes the partial-write hazard of a message landing in one +//! file but its dedup id not landing in another. +//! +//! Every file is versioned (see [`crate::persist`]). Threads persisted by +//! older daemons (a whole-snapshot `{thread_id}.json` instead of the log, and +//! unversioned metadata/state files) are migrated on first load; the legacy +//! snapshot file is left in place and ignored once the log exists. use async_trait::async_trait; use infinity_agent_core::ThreadId; @@ -27,6 +55,13 @@ use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; +#[cfg(test)] +use crate::persist::THREAD_LOG_VERSION; +use crate::persist::{ + self, LoadedThreadLog, PersistError, THREAD_META_VERSION, THREAD_STATE_VERSION, + THREAD_VIEWS_VERSION, ThreadLog, ThreadLogEntry, +}; + // ── Error type ── #[derive(Debug)] @@ -44,6 +79,35 @@ impl From for MemoryError { } } +impl From for MemoryError { + fn from(e: PersistError) -> Self { + MemoryError(e.to_string()) + } +} + +// ── File paths ── + +fn log_path(dir: &Path, thread_id: &ThreadId) -> PathBuf { + dir.join(format!("{thread_id}.jsonl")) +} + +/// The pre-log whole-snapshot file written by older daemons. +fn legacy_snapshot_path(dir: &Path, thread_id: &ThreadId) -> PathBuf { + dir.join(format!("{thread_id}.json")) +} + +fn meta_path(dir: &Path, thread_id: &ThreadId) -> PathBuf { + dir.join(format!("{thread_id}.meta.json")) +} + +fn views_path(dir: &Path, thread_id: &ThreadId) -> PathBuf { + dir.join(format!("{thread_id}.views.json")) +} + +fn state_path(dir: &Path, thread_id: &ThreadId) -> PathBuf { + dir.join(format!("{thread_id}.state.json")) +} + // ── Persistent conversation store backed by shared in-memory semantics ── #[derive(Clone)] @@ -54,9 +118,9 @@ pub struct PersistentConversationStore { /// here iff it has one in `core` (both are created together by the /// spawn/load/import paths of this wrapper). extras: Arc>>, - /// Directory where per-thread JSON files are stored. `None` disables persistence. + /// Directory where per-thread files are stored. `None` disables persistence. dir: Option, - /// Tracks which thread IDs have had their full data loaded from disk. + /// Tracks which thread IDs have had their conversation log loaded. loaded: Arc>>, /// Tracks which thread IDs have had their metadata loaded from disk. metadata_loaded: Arc>>, @@ -105,11 +169,11 @@ impl ThreadExtras { } } -/// The serialization shape of a thread's metadata (`{thread_id}.meta.json` -/// and the `metadata` field of [`SerializedThread`]): the core -/// [`ThreadInfo`] and the daemon's [`ThreadExtras`] flattened into one -/// object, byte-compatible with the format written before the core/daemon -/// store split. +/// The serialization shape of a thread's metadata (the body of +/// `{thread_id}.meta.json` and the `metadata` field of [`SerializedThread`]): +/// the core [`ThreadInfo`] and the daemon's [`ThreadExtras`] flattened into +/// one object, byte-compatible with the format written before the +/// core/daemon store split. #[derive(Clone, Serialize, Deserialize)] pub(crate) struct ThreadMeta { #[serde(flatten)] @@ -118,6 +182,41 @@ pub(crate) struct ThreadMeta { pub(crate) extras: ThreadExtras, } +/// `{thread_id}.meta.json`: a [`ThreadMeta`] plus the format version. Files +/// written before versioning lack the field and read as +/// [`persist::LEGACY_VERSION`]; the layout is otherwise identical. +#[derive(Serialize, Deserialize)] +struct ThreadMetaFile { + #[serde(default)] + version: u32, + #[serde(flatten)] + meta: ThreadMeta, +} + +/// `{thread_id}.views.json`. Files written before versioning were the bare +/// `views` map; see [`PersistentConversationStore::load_views`]. +#[derive(Serialize, Deserialize)] +struct ViewsFile { + version: u32, + views: HashMap, +} + +/// `{thread_id}.state.json`: a thread's [`ThreadState`] plus the format +/// version. Files written before versioning carried a `processed_message_ids` +/// field; it is ignored on load (processed ids are derived from the +/// conversation log, see the module docs). +#[derive(Serialize, Deserialize)] +struct ThreadStateFile { + #[serde(default)] + version: u32, + #[serde(default)] + metadata: Option, + #[serde(default)] + subscriptions: HashSet, + #[serde(default)] + pending_user_choices: Vec, +} + /// Serde default marking `selected_model` as absent in old serialized /// metadata; replaced with the store's default model on load. The empty /// provider id is a safe sentinel because the daemon's `ModelCatalog` asserts @@ -129,18 +228,31 @@ fn unset_model_ref() -> ModelRef { } } -/// Per-thread snapshot written to `{dir}/{thread_id}.json`. +/// A thread's full conversation, as exchanged in [`SerializedThread`] (the +/// daemon-to-daemon migration wire format) and as read from the legacy +/// whole-snapshot `{thread_id}.json` file. #[derive(Serialize)] pub(crate) struct ThreadSnapshot { - messages: Vec<(InfinityMessage, String)>, + /// Entries with their dedup ids (`None` for runtime-minted entries; files + /// and peers predating optional ids always carry one). + messages: Vec<(InfinityMessage, Option)>, #[serde(default)] compaction_summaries: Vec, } +impl From for LoadedThreadLog { + fn from(s: ThreadSnapshot) -> Self { + LoadedThreadLog { + messages: s.messages, + compaction_summaries: s.compaction_summaries, + } + } +} + /// Helper struct for deserializing the new format directly. #[derive(Deserialize)] struct NewThreadSnapshot { - messages: Vec<(InfinityMessage, String)>, + messages: Vec<(InfinityMessage, Option)>, #[serde(default)] compaction_summaries: Vec, } @@ -189,7 +301,7 @@ impl<'de> Deserialize<'de> for ThreadSnapshot { { *display_segments = Some(segs.clone()); } - (inf, id) + (inf, Some(id)) }) .collect(); @@ -231,7 +343,7 @@ pub(crate) struct SerializedThread { } impl PersistentConversationStore { - /// Create a store that persists each thread to its own JSON file under `dir`. + /// Create a store that persists each thread to its own files under `dir`. /// `default_model` is assigned to new threads and backfilled into metadata /// that predates per-thread model tracking. `id_source` generates ids for /// newly spawned threads (deterministic in tests). @@ -241,7 +353,9 @@ impl PersistentConversationStore { id_source: Arc, ) -> Self { let dir = dir.as_ref().to_path_buf(); - std::fs::create_dir_all(&dir).ok(); + if let Err(error) = std::fs::create_dir_all(&dir) { + tracing::error!(dir = %dir.display(), %error, "failed to create threads directory"); + } Self { core: core_stores::InMemoryConversationStore::new(), extras: Arc::new(Mutex::new(HashMap::new())), @@ -311,7 +425,7 @@ impl PersistentConversationStore { e.total_tokens_used = total_tokens_used; } } - self.save_thread_metadata(thread_id); + self.save_thread_metadata_logged(thread_id); } /// Notify that a session's thread tree changed. @@ -346,68 +460,114 @@ impl PersistentConversationStore { .insert(thread_id.to_owned(), meta.extras); } - /// Write a single thread's metadata to `{dir}/{thread_id}.meta.json`. - fn save_thread_metadata(&self, thread_id: &ThreadId) { - let Some(ref dir) = self.dir else { return }; - if let Some(meta) = self.thread_meta(thread_id) { - let path = dir.join(format!("{}.meta.json", thread_id)); - if let Ok(json) = serde_json::to_string_pretty(&meta) { - std::fs::write(path, json).ok(); - } + /// Atomically write a single thread's metadata to `{dir}/{thread_id}.meta.json`. + fn save_thread_metadata(&self, thread_id: &ThreadId) -> Result<(), MemoryError> { + let Some(ref dir) = self.dir else { + return Ok(()); + }; + let Some(meta) = self.thread_meta(thread_id) else { + return Ok(()); + }; + persist::write_json_atomic( + &meta_path(dir, thread_id), + &ThreadMetaFile { + version: THREAD_META_VERSION, + meta, + }, + )?; + Ok(()) + } + + /// [`Self::save_thread_metadata`] for synchronous callers that cannot + /// propagate the error: it is logged instead (the in-memory state stays + /// authoritative and the next successful save catches up). + fn save_thread_metadata_logged(&self, thread_id: &ThreadId) { + if let Err(error) = self.save_thread_metadata(thread_id) { + tracing::error!(%thread_id, %error, "failed to persist thread metadata"); + } + } + + /// Append committed conversation entries to the thread's log. + fn append_log( + &self, + thread_id: &ThreadId, + entries: &[ThreadLogEntry], + ) -> Result<(), MemoryError> { + let Some(ref dir) = self.dir else { + return Ok(()); + }; + ThreadLog { + path: &log_path(dir, thread_id), + thread_id, } + .append(entries)?; + Ok(()) } - /// Write a single thread's data to `{dir}/{thread_id}.json` and metadata to `.meta.json`. - /// No-op when persistence is disabled. - fn save_thread(&self, thread_id: &ThreadId) { - let Some(ref dir) = self.dir else { return }; - let snapshot = ThreadSnapshot { + /// Replace the thread's whole conversation log with the in-memory + /// contents (import/migration only; ordinary writes append). + fn rewrite_log(&self, thread_id: &ThreadId) -> Result<(), MemoryError> { + let Some(ref dir) = self.dir else { + return Ok(()); + }; + let contents = LoadedThreadLog { messages: self.core.thread_messages(thread_id).unwrap_or_default(), compaction_summaries: self.core.thread_compaction_summaries(thread_id), }; - - let path = dir.join(format!("{}.json", thread_id)); - if let Ok(json) = serde_json::to_string_pretty(&snapshot) { - std::fs::write(path, json).ok(); + ThreadLog { + path: &log_path(dir, thread_id), + thread_id, } - self.save_thread_metadata(thread_id); + .rewrite(&contents)?; + Ok(()) } /// Ensure a thread's metadata (core info + extras) is loaded from disk. - /// Tries `.meta.json` first; falls back to extracting from the full `.json` snapshot - /// and writes the `.meta.json` for future fast loads. - fn ensure_thread_metadata_loaded(&self, thread_id: &ThreadId) { - let Some(ref dir) = self.dir else { return }; + /// Tries `.meta.json` first; falls back to extracting from the legacy + /// `.json` snapshot and writes the `.meta.json` for future fast loads. + /// + /// On failure the thread is *not* marked loaded (so nothing is saved over + /// the unreadable file) and the error is returned. + fn ensure_thread_metadata_loaded(&self, thread_id: &ThreadId) -> Result<(), MemoryError> { + let Some(ref dir) = self.dir else { + return Ok(()); + }; let mut meta_loaded = self.metadata_loaded.lock().expect("bug: mutex poisoned"); if meta_loaded.contains(thread_id) { - return; + return Ok(()); } // Never overwrite a thread that already exists in memory (e.g. it // was created via ensure_root_thread before anything was persisted). let already_in_memory = self.core.thread_info(thread_id).is_some(); - // Try the fast metadata file first. - let meta_path = dir.join(format!("{}.meta.json", thread_id)); - if let Ok(json) = std::fs::read_to_string(&meta_path) - && let Ok(meta) = serde_json::from_str::(&json) - { - if !already_in_memory { - self.restore_thread_meta(thread_id, meta); + let meta_file = meta_path(dir, thread_id); + match persist::read_json::(&meta_file)? { + Some(file) => { + persist::check_version(&meta_file, file.version, THREAD_META_VERSION)?; + if !already_in_memory { + let outdated = file.version < THREAD_META_VERSION; + self.restore_thread_meta(thread_id, file.meta); + if outdated { + // Upgrade eagerly so every file on disk is at the + // current version once it has been read. + self.save_thread_metadata(thread_id)?; + } + } } - } else { - // Fall back: extract thread_info from the full snapshot file. - let full_path = dir.join(format!("{}.json", thread_id)); - if let Ok(json) = std::fs::read_to_string(&full_path) - && let Ok(val) = serde_json::from_str::(&json) - && let Some(info_val) = val.get("thread_info") - && let Ok(meta) = serde_json::from_value::(info_val.clone()) - && !already_in_memory - { - self.restore_thread_meta(thread_id, meta); - // Migrate: write the .meta.json for next time. - self.save_thread_metadata(thread_id); + None => { + // Fall back: extract thread_info from the legacy snapshot file. + let full_path = legacy_snapshot_path(dir, thread_id); + if let Some(val) = persist::read_json::(&full_path)? + && let Some(info_val) = val.get("thread_info") + && let Ok(meta) = serde_json::from_value::(info_val.clone()) + && !already_in_memory + { + self.restore_thread_meta(thread_id, meta); + // Migrate: write the .meta.json for next time. + self.save_thread_metadata(thread_id)?; + } } } @@ -415,50 +575,101 @@ impl PersistentConversationStore { self.migrate_from_session_store(thread_id, dir); meta_loaded.insert(thread_id.to_owned()); + Ok(()) } - /// Ensure a thread's full data (messages, compaction summaries) is loaded. - /// Calls `ensure_thread_metadata_loaded` first. - fn ensure_thread_loaded(&self, thread_id: &ThreadId) { - self.ensure_thread_metadata_loaded(thread_id); + /// [`Self::ensure_thread_metadata_loaded`] for synchronous getters that + /// cannot propagate the error: it is logged and `false` returned, so the + /// caller falls back to its "unknown thread" answer and skips any save. + fn metadata_loaded_or_log(&self, thread_id: &ThreadId) -> bool { + match self.ensure_thread_metadata_loaded(thread_id) { + Ok(()) => true, + Err(error) => { + tracing::error!(%thread_id, %error, "failed to load thread metadata"); + false + } + } + } - let Some(ref dir) = self.dir else { return }; + /// Ensure a thread's conversation (messages, compaction summaries, views) + /// is loaded. Calls `ensure_thread_metadata_loaded` first. + /// + /// Loads the thread's log, recovering the longest valid prefix after a + /// crash (see [`ThreadLog::load`]). A thread with no log but a legacy + /// whole-snapshot `{thread_id}.json` is migrated: the log is written + /// (atomically) from the snapshot and used from then on. + fn ensure_thread_loaded(&self, thread_id: &ThreadId) -> Result<(), MemoryError> { + self.ensure_thread_metadata_loaded(thread_id)?; + + let Some(ref dir) = self.dir else { + return Ok(()); + }; let mut loaded = self.loaded.lock().expect("bug: mutex poisoned"); if loaded.contains(thread_id) { - return; + return Ok(()); } - let path = dir.join(format!("{}.json", thread_id)); - if let Ok(json) = std::fs::read_to_string(&path) - && let Ok(snapshot) = serde_json::from_str::(&json) - { + let path = log_path(dir, thread_id); + let log = ThreadLog { + path: &path, + thread_id, + }; + let contents = match log.load()? { + Some(contents) => Some(contents), + None => self.migrate_legacy_snapshot(dir, &log)?, + }; + if let Some(contents) = contents { assert!( - !self.core.set_thread_messages(thread_id, snapshot.messages), + !self.core.set_thread_messages(thread_id, contents.messages), "bug: thread {thread_id} messages loaded twice" ); assert!( !self .core - .set_thread_compaction_summaries(thread_id, snapshot.compaction_summaries), + .set_thread_compaction_summaries(thread_id, contents.compaction_summaries), "bug: thread {thread_id} compaction summaries loaded twice" ); } loaded.insert(thread_id.to_owned()); - self.load_views(thread_id); + self.load_views(thread_id)?; + Ok(()) + } + + /// If a legacy whole-snapshot `{thread_id}.json` exists, convert it into + /// the thread's log (written atomically, so a crash mid-migration simply + /// retries next time) and return its contents. The legacy file is left + /// in place; it is never read again once the log exists. + fn migrate_legacy_snapshot( + &self, + dir: &Path, + log: &ThreadLog<'_>, + ) -> Result, MemoryError> { + let legacy = legacy_snapshot_path(dir, log.thread_id); + let Some(snapshot) = persist::read_json::(&legacy)? else { + return Ok(None); + }; + let contents = LoadedThreadLog::from(snapshot); + log.rewrite(&contents)?; + tracing::info!( + thread_id = %log.thread_id, + messages = contents.messages.len(), + "migrated legacy thread snapshot to the conversation log" + ); + Ok(Some(contents)) } /// Whether metadata exists for this thread (in memory or on disk). pub fn has_thread(&self, thread_id: &ThreadId) -> bool { - self.ensure_thread_metadata_loaded(thread_id); + self.metadata_loaded_or_log(thread_id); self.core.thread_info(thread_id).is_some() } /// Resolve a thread ID to its root thread ID (i.e. the session ID). pub fn get_root_thread_id(&self, thread_id: &ThreadId) -> ThreadId { - self.ensure_thread_metadata_loaded(thread_id); + self.metadata_loaded_or_log(thread_id); self.core .thread_info(thread_id) .map(|t| t.root_thread_id) @@ -467,7 +678,7 @@ impl PersistentConversationStore { /// Get the parent thread ID, if any. pub fn get_thread_parent_id(&self, thread_id: &ThreadId) -> Option { - self.ensure_thread_metadata_loaded(thread_id); + self.metadata_loaded_or_log(thread_id); self.core .thread_info(thread_id) .and_then(|t| t.parent_thread_id) @@ -475,21 +686,23 @@ impl PersistentConversationStore { /// Set the title for a thread. pub fn set_thread_title(&self, thread_id: &ThreadId, title: &str) { - self.ensure_thread_metadata_loaded(thread_id); + if !self.metadata_loaded_or_log(thread_id) { + return; + } { let mut extras = self.extras.lock().expect("bug: mutex poisoned"); if let Some(e) = extras.get_mut(thread_id) { e.title = Some(title.to_owned()); } } - self.save_thread_metadata(thread_id); + self.save_thread_metadata_logged(thread_id); self.notify_session(thread_id); } /// Get the model selected for this specific thread. Does NOT fall back to /// the parent thread — every thread is assigned a model at creation time. pub fn get_thread_model(&self, thread_id: &ThreadId) -> ModelRef { - self.ensure_thread_metadata_loaded(thread_id); + self.metadata_loaded_or_log(thread_id); let extras = self.extras.lock().expect("bug: mutex poisoned"); extras .get(thread_id) @@ -499,14 +712,16 @@ impl PersistentConversationStore { /// Set the model selected for a thread. pub fn set_thread_model(&self, thread_id: &ThreadId, model: ModelRef) { - self.ensure_thread_metadata_loaded(thread_id); + if !self.metadata_loaded_or_log(thread_id) { + return; + } { let mut extras = self.extras.lock().expect("bug: mutex poisoned"); if let Some(e) = extras.get_mut(thread_id) { e.selected_model = model; } } - self.save_thread_metadata(thread_id); + self.save_thread_metadata_logged(thread_id); } /// List every thread in a session, including the root and descendants that @@ -522,7 +737,7 @@ impl PersistentConversationStore { if !visited.insert(thread_id.to_owned()) { continue; } - self.ensure_thread_metadata_loaded(&thread_id); + self.metadata_loaded_or_log(&thread_id); let children = { let extras = self.extras.lock().expect("bug: mutex poisoned"); extras @@ -543,7 +758,7 @@ impl PersistentConversationStore { &self, parent_id: &ThreadId, ) -> Vec { - self.ensure_thread_metadata_loaded(parent_id); + self.metadata_loaded_or_log(parent_id); let mut result = Vec::new(); let mut queue = vec![parent_id.to_owned()]; while let Some(pid) = queue.pop() { @@ -555,7 +770,7 @@ impl PersistentConversationStore { .unwrap_or_default() }; for child_id in children { - self.ensure_thread_metadata_loaded(&child_id); + self.metadata_loaded_or_log(&child_id); let Some(info) = self.core.thread_info(&child_id) else { continue; }; @@ -577,7 +792,7 @@ impl PersistentConversationStore { } pub fn get_total_tokens_used(&self, thread_id: &ThreadId) -> usize { - self.ensure_thread_metadata_loaded(thread_id); + self.metadata_loaded_or_log(thread_id); self.extras .lock() .expect("bug: mutex poisoned") @@ -587,7 +802,9 @@ impl PersistentConversationStore { } pub fn set_total_tokens_used(&self, thread_id: &ThreadId, tokens: usize) { - self.ensure_thread_metadata_loaded(thread_id); + if !self.metadata_loaded_or_log(thread_id) { + return; + } if let Some(e) = self .extras .lock() @@ -596,12 +813,12 @@ impl PersistentConversationStore { { e.total_tokens_used = tokens; } - self.save_thread_metadata(thread_id); + self.save_thread_metadata_logged(thread_id); self.notify_session(thread_id); } pub fn get_last_updated(&self, thread_id: &ThreadId) -> String { - self.ensure_thread_metadata_loaded(thread_id); + self.metadata_loaded_or_log(thread_id); self.extras .lock() .expect("bug: mutex poisoned") @@ -611,7 +828,9 @@ impl PersistentConversationStore { } pub fn set_last_updated(&self, thread_id: &ThreadId, ts: &str) { - self.ensure_thread_metadata_loaded(thread_id); + if !self.metadata_loaded_or_log(thread_id) { + return; + } if let Some(e) = self .extras .lock() @@ -620,48 +839,71 @@ impl PersistentConversationStore { { e.last_updated = ts.to_owned(); } - self.save_thread_metadata(thread_id); + self.save_thread_metadata_logged(thread_id); } - /// Write views to `{dir}/{thread_id}.views.json`. - fn save_views(&self, thread_id: &ThreadId) { - let Some(ref dir) = self.dir else { return }; + /// Atomically write views to `{dir}/{thread_id}.views.json` (or remove + /// the file when there are none). + fn save_views(&self, thread_id: &ThreadId) -> Result<(), MemoryError> { + let Some(ref dir) = self.dir else { + return Ok(()); + }; let views = self.views.lock().expect("bug: mutex poisoned"); - let path = dir.join(format!("{}.views.json", thread_id)); + let path = views_path(dir, thread_id); match views.get(thread_id) { Some(v) if !v.is_empty() => { - if let Ok(json) = serde_json::to_string_pretty(v) { - std::fs::write(path, json).ok(); - } + persist::write_json_atomic( + &path, + &ViewsFile { + version: THREAD_VIEWS_VERSION, + views: v.clone(), + }, + )?; } - _ => { - let _ = std::fs::remove_file(path); // file might already not exist - } - } - } - - /// Load views from `{dir}/{thread_id}.views.json`. - fn load_views(&self, thread_id: &ThreadId) { - tracing::info!("Loading views for thread {thread_id}"); - let Some(ref dir) = self.dir else { return }; - let path = dir.join(format!("{}.views.json", thread_id)); - match std::fs::read_to_string(&path) { - Ok(json) => match serde_json::from_str::>(&json) { - Ok(v) => { - self.views - .lock() - .expect("bug: mutex poisoned") - .insert(thread_id.to_owned(), v); - } + _ => match std::fs::remove_file(&path) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Err(e) => { - tracing::error!("Failed to deserialize views: {e}"); + return Err(MemoryError(format!( + "failed to remove {}: {e}", + path.display() + ))); } }, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} // file does not exist, okay - Err(e) => { - tracing::error!("Failed to load views file: {e}"); + } + Ok(()) + } + + /// Load views from `{dir}/{thread_id}.views.json`, accepting both the + /// versioned [`ViewsFile`] and the pre-versioning bare map. + fn load_views(&self, thread_id: &ThreadId) -> Result<(), MemoryError> { + let Some(ref dir) = self.dir else { + return Ok(()); + }; + let path = views_path(dir, thread_id); + let Some(raw) = persist::read_json::(&path)? else { + return Ok(()); + }; + let (views, outdated) = match serde_json::from_value::(raw.clone()) { + Ok(file) => { + persist::check_version(&path, file.version, THREAD_VIEWS_VERSION)?; + (file.views, file.version < THREAD_VIEWS_VERSION) } + // Legacy: the bare `view_type → content` map. + Err(_) => ( + serde_json::from_value::>(raw) + .map_err(|e| MemoryError(format!("{}: corrupt: {e}", path.display())))?, + true, + ), + }; + self.views + .lock() + .expect("bug: mutex poisoned") + .insert(thread_id.to_owned(), views); + if outdated { + self.save_views(thread_id)?; } + Ok(()) } /// Update a view for a thread and persist. @@ -673,12 +915,16 @@ impl PersistentConversationStore { .or_default() .insert(view_type.to_owned(), content); } - self.save_views(thread_id); + if let Err(error) = self.save_views(thread_id) { + tracing::error!(%thread_id, %error, "failed to persist views"); + } } /// Get all views for a thread. pub fn get_views(&self, thread_id: &ThreadId) -> HashMap { - self.ensure_thread_loaded(thread_id); + if let Err(error) = self.ensure_thread_loaded(thread_id) { + tracing::error!(%thread_id, %error, "failed to load thread"); + } self.views .lock() .expect("bug: mutex poisoned") @@ -688,7 +934,7 @@ impl PersistentConversationStore { } pub fn get_thread_title(&self, thread_id: &ThreadId) -> Option { - self.ensure_thread_metadata_loaded(thread_id); + self.metadata_loaded_or_log(thread_id); self.extras .lock() .expect("bug: mutex poisoned") @@ -701,7 +947,10 @@ impl PersistentConversationStore { let mut threads: HashMap = HashMap::new(); let mut queue = vec![root_thread_id.to_owned()]; while let Some(tid) = queue.pop() { - self.ensure_thread_loaded(&tid); + if let Err(error) = self.ensure_thread_loaded(&tid) { + tracing::error!(thread_id = %tid, %error, "failed to load thread for serialization"); + continue; + } let Some(metadata) = self.thread_meta(&tid) else { continue; }; @@ -752,8 +1001,9 @@ impl PersistentConversationStore { .lock() .expect("bug: mutex poisoned") .insert(tid.clone()); - self.save_thread(&tid); - self.save_views(&tid); + self.rewrite_log(&tid)?; + self.save_thread_metadata(&tid)?; + self.save_views(&tid)?; } Ok(()) } @@ -764,7 +1014,7 @@ impl ConversationStore for PersistentConversationStore { type Error = MemoryError; async fn ensure_root_thread(&self, thread_id: &ThreadId) -> Result<(), MemoryError> { - self.ensure_thread_loaded(thread_id); + self.ensure_thread_loaded(thread_id)?; let inserted = self.core.thread_info(thread_id).is_none(); if inserted { self.core.ensure_root_thread(thread_id).await?; @@ -772,13 +1022,15 @@ impl ConversationStore for PersistentConversationStore { thread_id.to_owned(), ThreadExtras::new(self.default_model.clone()), ); - self.save_thread(thread_id); + // The conversation log is created by the first append. + self.save_thread_metadata(thread_id)?; } Ok(()) } async fn thread_exists(&self, thread_id: &ThreadId) -> Result { - Ok(self.has_thread(thread_id)) + self.ensure_thread_metadata_loaded(thread_id)?; + Ok(self.core.thread_info(thread_id).is_some()) } async fn load_history_up_to( @@ -787,7 +1039,7 @@ impl ConversationStore for PersistentConversationStore { start_from: Option, up_to: Option, ) -> Result, MemoryError> { - self.ensure_thread_loaded(session_id); + self.ensure_thread_loaded(session_id)?; Ok(self .core .load_history_up_to(session_id, start_from, up_to) @@ -797,15 +1049,36 @@ impl ConversationStore for PersistentConversationStore { async fn append_messages( &self, session_id: &ThreadId, - messages: Vec<(InfinityMessage, String)>, + messages: Vec<(InfinityMessage, Option)>, ) -> Result<(), MemoryError> { - self.ensure_thread_loaded(session_id); + self.ensure_thread_loaded(session_id)?; tracing::trace!("Appending messages to store"); + // Durable first, then in memory: a failed append must not leave the + // in-memory history ahead of the log. + let entries: Vec = messages + .iter() + .map(|(message, id)| ThreadLogEntry::Message { + id: id.clone(), + message: message.clone(), + }) + .collect(); + self.append_log(session_id, &entries)?; self.core.append_messages(session_id, messages).await?; - self.save_thread(session_id); Ok(()) } + async fn is_message_processed( + &self, + thread_id: &ThreadId, + message_id: &str, + ) -> Result { + self.ensure_thread_loaded(thread_id)?; + Ok(self + .core + .is_message_processed(thread_id, message_id) + .await?) + } + async fn spawn_thread( &self, parent_thread_id: &ThreadId, @@ -813,7 +1086,7 @@ impl ConversationStore for PersistentConversationStore { is_for_subscription_event: bool, context: SpawnContext, ) -> Result { - self.ensure_thread_loaded(parent_thread_id); + self.ensure_thread_loaded(parent_thread_id)?; let new_id = self.id_source.generate(); { // Hold the load-tracking locks while creating the thread so a @@ -849,21 +1122,25 @@ impl ConversationStore for PersistentConversationStore { meta_loaded.insert(new_id.clone()); } - self.save_thread(&new_id); - self.save_thread_metadata(parent_thread_id); + // The child's identity first (its own file), then the parent's + // children list. A crash in between leaves an orphan child file that + // nothing references — harmless — rather than a parent pointing at a + // child that does not exist. + self.save_thread_metadata(&new_id)?; + self.save_thread_metadata(parent_thread_id)?; self.notify_session(parent_thread_id); Ok(new_id) } async fn is_thread_closed(&self, thread_id: &ThreadId) -> Result { - self.ensure_thread_metadata_loaded(thread_id); + self.ensure_thread_metadata_loaded(thread_id)?; Ok(self.core.is_thread_closed(thread_id).await?) } async fn close_thread(&self, thread_id: &ThreadId) -> Result<(), MemoryError> { - self.ensure_thread_metadata_loaded(thread_id); + self.ensure_thread_metadata_loaded(thread_id)?; self.core.close_thread(thread_id).await?; - self.save_thread_metadata(thread_id); + self.save_thread_metadata(thread_id)?; self.notify_session(thread_id); Ok(()) } @@ -872,7 +1149,7 @@ impl ConversationStore for PersistentConversationStore { &self, thread_id: &ThreadId, ) -> Result { - self.ensure_thread_metadata_loaded(thread_id); + self.ensure_thread_metadata_loaded(thread_id)?; Ok(self.core.is_subscription_event_thread(thread_id).await?) } @@ -880,7 +1157,7 @@ impl ConversationStore for PersistentConversationStore { &self, thread_id: &ThreadId, ) -> Result { - self.ensure_thread_metadata_loaded(thread_id); + self.ensure_thread_metadata_loaded(thread_id)?; Ok(self.core.is_fresh_context_thread(thread_id).await?) } @@ -888,7 +1165,7 @@ impl ConversationStore for PersistentConversationStore { &self, thread_id: &ThreadId, ) -> Result, MemoryError> { - self.ensure_thread_metadata_loaded(thread_id); + self.ensure_thread_metadata_loaded(thread_id)?; Ok(self.core.get_thread_parent_info(thread_id).await?) } @@ -900,7 +1177,7 @@ impl ConversationStore for PersistentConversationStore { // (and its ordering semantics) to the core store. let mut current = thread_id.to_owned(); loop { - self.ensure_thread_metadata_loaded(¤t); + self.ensure_thread_metadata_loaded(¤t)?; match self .core .thread_info(¤t) @@ -919,11 +1196,17 @@ impl ConversationStore for PersistentConversationStore { summary: &str, up_to_order: i64, ) -> Result<(), MemoryError> { - self.ensure_thread_loaded(thread_id); + self.ensure_thread_loaded(thread_id)?; + self.append_log( + thread_id, + &[ThreadLogEntry::CompactionSummary { + summary: summary.to_owned(), + up_to_order, + }], + )?; self.core .save_compaction_summary(thread_id, summary, up_to_order) .await?; - self.save_thread(thread_id); Ok(()) } @@ -932,7 +1215,7 @@ impl ConversationStore for PersistentConversationStore { thread_id: &ThreadId, up_to_order: Option, ) -> Result, MemoryError> { - self.ensure_thread_loaded(thread_id); + self.ensure_thread_loaded(thread_id)?; Ok(self .core .load_latest_compaction_summary_up_to(thread_id, up_to_order) @@ -940,7 +1223,7 @@ impl ConversationStore for PersistentConversationStore { } async fn is_compaction_thread(&self, thread_id: &ThreadId) -> Result { - self.ensure_thread_metadata_loaded(thread_id); + self.ensure_thread_metadata_loaded(thread_id)?; Ok(self.core.is_compaction_thread(thread_id).await?) } @@ -948,9 +1231,9 @@ impl ConversationStore for PersistentConversationStore { &self, thread_id: &ThreadId, ) -> Result<(), MemoryError> { - self.ensure_thread_metadata_loaded(thread_id); + self.ensure_thread_metadata_loaded(thread_id)?; self.core.mark_thread_as_compaction(thread_id).await?; - self.save_thread_metadata(thread_id); + self.save_thread_metadata(thread_id)?; Ok(()) } @@ -958,7 +1241,7 @@ impl ConversationStore for PersistentConversationStore { &self, thread_id: &ThreadId, ) -> Result, MemoryError> { - self.ensure_thread_metadata_loaded(thread_id); + self.ensure_thread_metadata_loaded(thread_id)?; Ok(self.core.get_thread_spawn_order(thread_id).await?) } } @@ -967,11 +1250,11 @@ impl ConversationStore for PersistentConversationStore { #[derive(Clone)] pub struct PersistentStateStore { - /// The shared store semantics (processed IDs, metadata, subscriptions). + /// The shared store semantics (metadata, subscriptions, pending choices). core: core_stores::InMemoryStateStore, /// Directory where per-thread state JSON files are stored. dir: PathBuf, - /// Tracks which keys have already been loaded (or attempted) from disk. + /// Tracks which keys have already been loaded from disk. loaded: Arc>>, // Used to resolve child threads for stopped-session policy. conversation_store: PersistentConversationStore, @@ -985,7 +1268,9 @@ impl PersistentStateStore { session_store: Arc>, ) -> Self { let dir = dir.as_ref().to_path_buf(); - std::fs::create_dir_all(&dir).ok(); + if let Err(error) = std::fs::create_dir_all(&dir) { + tracing::error!(dir = %dir.display(), %error, "failed to create state directory"); + } Self { core: core_stores::InMemoryStateStore::new(), dir, @@ -996,7 +1281,7 @@ impl PersistentStateStore { } pub fn has_pending_choices(&self, thread_id: &ThreadId) -> bool { - self.ensure_loaded(thread_id); + self.loaded_or_log(thread_id); !self .core .thread_state(thread_id) @@ -1019,7 +1304,7 @@ impl PersistentStateStore { thread_id: &ThreadId, choice_id: &rap_protocol::ChoiceId, ) -> Option { - self.ensure_loaded(thread_id); + self.loaded_or_log(thread_id); self.core .thread_state(thread_id) .pending_user_choices @@ -1051,31 +1336,60 @@ impl PersistentStateStore { Ok(()) } - /// Write a single key's state data to `{dir}/{key}.state.json`. The file - /// is the serialized core [`ThreadState`] snapshot. - fn save_key(&self, key: &ThreadId) { - let snapshot = self.core.thread_state(key); - let path = self.dir.join(format!("{}.state.json", key)); - if let Ok(json) = serde_json::to_string_pretty(&snapshot) { - std::fs::write(path, json).ok(); - } + /// Atomically write a single key's state to `{dir}/{key}.state.json`. + fn save_key(&self, key: &ThreadId) -> Result<(), MemoryError> { + let state = self.core.thread_state(key); + persist::write_json_atomic( + &state_path(&self.dir, key), + &ThreadStateFile { + version: THREAD_STATE_VERSION, + metadata: state.metadata, + subscriptions: state.subscriptions, + pending_user_choices: state.pending_user_choices, + }, + )?; + Ok(()) } - /// Ensure a key's data is loaded from disk into the core store. - fn ensure_loaded(&self, key: &ThreadId) { + /// Ensure a key's data is loaded from disk into the core store. On + /// failure the key is not marked loaded (so nothing is saved over the + /// unreadable file) and the error is returned. + fn ensure_loaded(&self, key: &ThreadId) -> Result<(), MemoryError> { let mut loaded = self.loaded.lock().expect("bug: mutex poisoned"); if loaded.contains(key) { - return; + return Ok(()); } - let path = self.dir.join(format!("{}.state.json", key)); - if let Ok(json) = std::fs::read_to_string(&path) - && let Ok(snapshot) = serde_json::from_str::(&json) - { - self.core.set_thread_state(key, snapshot); + let path = state_path(&self.dir, key); + let mut outdated = false; + if let Some(file) = persist::read_json::(&path)? { + persist::check_version(&path, file.version, THREAD_STATE_VERSION)?; + outdated = file.version < THREAD_STATE_VERSION; + self.core.set_thread_state( + key, + ThreadState { + metadata: file.metadata, + subscriptions: file.subscriptions, + pending_user_choices: file.pending_user_choices, + }, + ); } loaded.insert(key.to_owned()); + if outdated { + // Upgrade eagerly (this also drops the legacy + // `processed_message_ids` field). + self.save_key(key)?; + } + Ok(()) + } + + /// [`Self::ensure_loaded`] for synchronous getters that cannot propagate + /// the error: it is logged instead. + fn loaded_or_log(&self, key: &ThreadId) { + if let Err(error) = self.ensure_loaded(key) { + tracing::error!(thread_id = %key, %error, "failed to load thread state"); + } } } @@ -1083,32 +1397,11 @@ impl PersistentStateStore { impl StateStore for PersistentStateStore { type Error = MemoryError; - async fn get_processed_ids( - &self, - thread_id: &ThreadId, - ) -> Result, MemoryError> { - self.ensure_loaded(thread_id); - Ok(self.core.get_processed_ids(thread_id).await?) - } - - async fn add_processed_message_ids( - &self, - thread_id: &ThreadId, - message_ids: Vec, - ) -> Result<(), MemoryError> { - self.ensure_loaded(thread_id); - self.core - .add_processed_message_ids(thread_id, message_ids) - .await?; - self.save_key(thread_id); - Ok(()) - } - async fn get_metadata( &self, root_thread_id: &ThreadId, ) -> Result, MemoryError> { - self.ensure_loaded(root_thread_id); + self.ensure_loaded(root_thread_id)?; Ok(self.core.get_metadata(root_thread_id).await?) } @@ -1117,17 +1410,16 @@ impl StateStore for PersistentStateStore { root_thread_id: &ThreadId, metadata: serde_json::Value, ) -> Result<(), MemoryError> { - self.ensure_loaded(root_thread_id); + self.ensure_loaded(root_thread_id)?; self.core.set_metadata(root_thread_id, metadata).await?; - self.save_key(root_thread_id); - Ok(()) + self.save_key(root_thread_id) } async fn get_active_subscriptions( &self, thread_id: &ThreadId, ) -> Result, MemoryError> { - self.ensure_loaded(thread_id); + self.ensure_loaded(thread_id)?; Ok(self.core.get_active_subscriptions(thread_id).await?) } @@ -1136,12 +1428,11 @@ impl StateStore for PersistentStateStore { thread_id: &ThreadId, tool_call_id: &rap_protocol::ToolCallId, ) -> Result<(), MemoryError> { - self.ensure_loaded(thread_id); + self.ensure_loaded(thread_id)?; self.core .add_active_subscription(thread_id, tool_call_id) .await?; - self.save_key(thread_id); - Ok(()) + self.save_key(thread_id) } async fn remove_active_subscription( @@ -1149,12 +1440,11 @@ impl StateStore for PersistentStateStore { thread_id: &ThreadId, tool_call_id: &rap_protocol::ToolCallId, ) -> Result<(), MemoryError> { - self.ensure_loaded(thread_id); + self.ensure_loaded(thread_id)?; self.core .remove_active_subscription(thread_id, tool_call_id) .await?; - self.save_key(thread_id); - Ok(()) + self.save_key(thread_id) } async fn add_pending_user_choice( @@ -1162,9 +1452,9 @@ impl StateStore for PersistentStateStore { thread_id: &ThreadId, choice: UserChoice, ) -> Result<(), MemoryError> { - self.ensure_loaded(thread_id); + self.ensure_loaded(thread_id)?; self.core.add_pending_user_choice(thread_id, choice).await?; - self.save_key(thread_id); + self.save_key(thread_id)?; self.conversation_store.notify_session(thread_id); Ok(()) } @@ -1174,11 +1464,11 @@ impl StateStore for PersistentStateStore { thread_id: &ThreadId, choice_id: &rap_protocol::ChoiceId, ) -> Result<(), MemoryError> { - self.ensure_loaded(thread_id); + self.ensure_loaded(thread_id)?; self.core .remove_pending_user_choice(thread_id, choice_id) .await?; - self.save_key(thread_id); + self.save_key(thread_id)?; self.conversation_store.notify_session(thread_id); Ok(()) } @@ -1187,7 +1477,7 @@ impl StateStore for PersistentStateStore { &self, thread_id: &ThreadId, ) -> Result, MemoryError> { - self.ensure_loaded(thread_id); + self.ensure_loaded(thread_id)?; Ok(self.core.get_pending_user_choices(thread_id).await?) } @@ -1275,7 +1565,10 @@ mod tests { store .append_messages( ThreadId::from_ref("root"), - vec![(user_msg("p1"), "m1".into()), (asst_msg("p2"), "m2".into())], + vec![ + (user_msg("p1"), Some("m1".into())), + (asst_msg("p2"), Some("m2".into())), + ], ) .await .expect("append root messages"); @@ -1293,13 +1586,16 @@ mod tests { store .append_messages( ThreadId::from_ref("root"), - vec![(user_msg("p3"), "m3".into()), (asst_msg("p4"), "m4".into())], + vec![ + (user_msg("p3"), Some("m3".into())), + (asst_msg("p4"), Some("m4".into())), + ], ) .await .expect("append root messages after spawn"); store - .append_messages(&child, vec![(user_msg("c1"), "m5".into())]) + .append_messages(&child, vec![(user_msg("c1"), Some("m5".into()))]) .await .expect("append child messages"); @@ -1338,7 +1634,7 @@ mod tests { store .append_messages( ThreadId::from_ref("root"), - vec![(user_msg("r1"), "m1".into())], + vec![(user_msg("r1"), Some("m1".into()))], ) .await .expect("append root messages"); @@ -1355,7 +1651,10 @@ mod tests { store .append_messages( &child, - vec![(user_msg("c1"), "m2".into()), (asst_msg("c2"), "m3".into())], + vec![ + (user_msg("c1"), Some("m2".into())), + (asst_msg("c2"), Some("m3".into())), + ], ) .await .expect("append child messages"); @@ -1370,7 +1669,7 @@ mod tests { .await .expect("spawn grandchild thread"); store - .append_messages(&grandchild, vec![(user_msg("g1"), "m4".into())]) + .append_messages(&grandchild, vec![(user_msg("g1"), Some("m4".into()))]) .await .expect("append grandchild messages"); @@ -1398,10 +1697,10 @@ mod tests { .append_messages( ThreadId::from_ref("root"), vec![ - (user_msg("old1"), "m1".into()), - (asst_msg("old2"), "m2".into()), - (user_msg("new1"), "m3".into()), - (asst_msg("new2"), "m4".into()), + (user_msg("old1"), Some("m1".into())), + (asst_msg("old2"), Some("m2".into())), + (user_msg("new1"), Some("m3".into())), + (asst_msg("new2"), Some("m4".into())), ], ) .await @@ -1443,9 +1742,9 @@ mod tests { .append_messages( ThreadId::from_ref("root"), vec![ - (user_msg("old1"), "m1".into()), - (asst_msg("old2"), "m2".into()), - (user_msg("recent"), "m3".into()), + (user_msg("old1"), Some("m1".into())), + (asst_msg("old2"), Some("m2".into())), + (user_msg("recent"), Some("m3".into())), ], ) .await @@ -1466,7 +1765,7 @@ mod tests { .await .expect("spawn child thread"); store - .append_messages(&child, vec![(user_msg("c1"), "m4".into())]) + .append_messages(&child, vec![(user_msg("c1"), Some("m4".into()))]) .await .expect("append child messages"); @@ -1500,11 +1799,11 @@ mod tests { .append_messages( ThreadId::from_ref("root"), vec![ - (user_msg("a"), "m1".into()), - (asst_msg("b"), "m2".into()), - (user_msg("c"), "m3".into()), - (asst_msg("d"), "m4".into()), - (user_msg("e"), "m5".into()), + (user_msg("a"), Some("m1".into())), + (asst_msg("b"), Some("m2".into())), + (user_msg("c"), Some("m3".into())), + (asst_msg("d"), Some("m4".into())), + (user_msg("e"), Some("m5".into())), ], ) .await @@ -1529,7 +1828,7 @@ mod tests { .await .expect("spawn child thread"); store - .append_messages(&child, vec![(user_msg("c1"), "m6".into())]) + .append_messages(&child, vec![(user_msg("c1"), Some("m6".into()))]) .await .expect("append child messages"); @@ -1563,7 +1862,10 @@ mod tests { store .append_messages( ThreadId::from_ref("root"), - vec![(user_msg("r1"), "m1".into()), (asst_msg("r2"), "m2".into())], + vec![ + (user_msg("r1"), Some("m1".into())), + (asst_msg("r2"), Some("m2".into())), + ], ) .await .expect("append root messages"); @@ -1585,10 +1887,10 @@ mod tests { .append_messages( &child, vec![ - (user_msg("c1"), "m3".into()), - (asst_msg("c2"), "m4".into()), - (user_msg("c3"), "m5".into()), - (asst_msg("c4"), "m6".into()), + (user_msg("c1"), Some("m3".into())), + (asst_msg("c2"), Some("m4".into())), + (user_msg("c3"), Some("m5".into())), + (asst_msg("c4"), Some("m6".into())), ], ) .await @@ -1628,4 +1930,436 @@ mod tests { assert_eq!(t.text, "c3"); } } + + // ── Durability ── + + fn open_store(dir: &Path) -> PersistentConversationStore { + PersistentConversationStore::new_with_dir( + dir, + test_model(), + Arc::new(crate::ids::UuidIdSource), + ) + } + + fn texts(history: &[InfinityMessage]) -> Vec { + history + .iter() + .map(|m| match m { + InfinityMessage::User { + content: UserContent::Text(t), + } => t.text.clone(), + InfinityMessage::Assistant { + content: AssistantContent::Text(t), + } => t.text.clone(), + other => panic!("unexpected message {other:?}"), + }) + .collect() + } + + /// A fresh store over the same directory (a daemon restart) sees every + /// committed message, compaction summary, metadata field and view. + #[tokio::test] + async fn restart_reloads_everything_from_disk() { + let dir = tempfile::tempdir().expect("create temp dir"); + let root = ThreadId::from_ref("root"); + let child = { + let store = open_store(dir.path()); + store.ensure_root_thread(root).await.expect("root"); + store + .append_messages( + root, + vec![ + (user_msg("hi"), Some("m1".into())), + (asst_msg("hello"), Some("m2".into())), + ], + ) + .await + .expect("append"); + store + .append_messages(root, vec![(user_msg("more"), Some("m3".into()))]) + .await + .expect("append again"); + store + .save_compaction_summary(root, "summary", 2) + .await + .expect("compaction"); + store.set_thread_title(root, "My session"); + store.set_total_tokens_used(root, 1234); + store.set_view(root, "diff", serde_json::json!({"files": 1})); + let child = store + .spawn_thread( + root, + rap_protocol::ToolCallId::from_ref("tc-1"), + false, + SpawnContext::InheritUpTo(3), + ) + .await + .expect("spawn"); + store + .append_messages(&child, vec![(user_msg("child"), Some("c1".into()))]) + .await + .expect("append child"); + child + }; + + // Only the new file kinds exist; nothing writes the legacy snapshot. + let names: Vec = std::fs::read_dir(dir.path()) + .expect("list") + .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned()) + .collect(); + assert!(names.contains(&"root.jsonl".to_owned()), "{names:?}"); + assert!(names.contains(&"root.meta.json".to_owned()), "{names:?}"); + assert!(names.contains(&"root.views.json".to_owned()), "{names:?}"); + assert!(!names.contains(&"root.json".to_owned()), "{names:?}"); + + let store = open_store(dir.path()); + let own = store + .load_history_up_to(root, None, None) + .await + .expect("load"); + assert_eq!(texts(&own), vec!["hi", "hello", "more"]); + let (history, compacted, _) = store + .load_history_with_ancestors(root) + .await + .expect("load with ancestors"); + assert_eq!(compacted, Some(2)); + assert_eq!(history.len(), 2, "summary + the one message after it"); + assert_eq!(store.get_thread_title(root), Some("My session".to_owned())); + assert_eq!(store.get_total_tokens_used(root), 1234); + assert_eq!( + store.get_views(root).get("diff"), + Some(&serde_json::json!({"files": 1})) + ); + assert_eq!(store.get_thread_parent_id(&child), Some(root.to_owned())); + assert_eq!(store.get_open_subthreads(root).len(), 1); + assert_eq!( + texts( + &store + .load_history_up_to(&child, None, None) + .await + .expect("load child") + ), + vec!["child"] + ); + } + + /// Each append adds lines to the log rather than rewriting it, so the + /// per-completion write cost is proportional to the new content. + #[tokio::test] + async fn appends_are_append_only() { + let dir = tempfile::tempdir().expect("create temp dir"); + let root = ThreadId::from_ref("root"); + let store = open_store(dir.path()); + store.ensure_root_thread(root).await.expect("root"); + let path = dir.path().join("root.jsonl"); + + store + .append_messages(root, vec![(user_msg("a"), Some("m1".into()))]) + .await + .expect("append"); + let first = std::fs::read(&path).expect("read"); + store + .append_messages(root, vec![(user_msg("b"), Some("m2".into()))]) + .await + .expect("append"); + let second = std::fs::read(&path).expect("read"); + assert!( + second.starts_with(&first), + "the earlier contents are a byte prefix of the later file" + ); + assert_eq!( + std::str::from_utf8(&second).expect("utf8").lines().count(), + 3, + "header + two messages" + ); + } + + /// A crash mid-append leaves a torn last line; on restart the thread + /// loads the complete prefix and keeps working. + #[tokio::test] + async fn torn_append_recovers_prefix_on_restart() { + let dir = tempfile::tempdir().expect("create temp dir"); + let root = ThreadId::from_ref("root"); + { + let store = open_store(dir.path()); + store.ensure_root_thread(root).await.expect("root"); + store + .append_messages( + root, + vec![ + (user_msg("a"), Some("m1".into())), + (asst_msg("b"), Some("m2".into())), + ], + ) + .await + .expect("append"); + } + // Simulate the crash: the third message was only partially written. + let path = dir.path().join("root.jsonl"); + let mut torn = std::fs::read(&path).expect("read"); + let full_line = serde_json::to_vec(&ThreadLogEntry::Message { + id: Some("m3".to_owned()), + message: user_msg("c"), + }) + .expect("serialize"); + torn.extend_from_slice(&full_line[..full_line.len() / 2]); + std::fs::write(&path, &torn).expect("write torn"); + + let store = open_store(dir.path()); + let history = store + .load_history_up_to(root, None, None) + .await + .expect("load"); + assert_eq!(texts(&history), vec!["a", "b"]); + + // The thread keeps working after recovery, and a further restart sees + // the repaired log plus the new message. + store + .append_messages(root, vec![(user_msg("d"), Some("m4".into()))]) + .await + .expect("append after recovery"); + let store = open_store(dir.path()); + let history = store + .load_history_up_to(root, None, None) + .await + .expect("load"); + assert_eq!(texts(&history), vec!["a", "b", "d"]); + } + + /// A thread persisted by an older daemon as a whole-snapshot `.json` + /// (with unversioned `.meta.json`) is migrated into the log on first + /// load, and the migrated log is what later loads use. + #[tokio::test] + async fn legacy_snapshot_is_migrated_to_log() { + let dir = tempfile::tempdir().expect("create temp dir"); + let root = ThreadId::from_ref("root"); + let legacy_snapshot = serde_json::json!({ + "messages": [ + [serde_json::to_value(user_msg("old hi")).expect("ser"), "m1"], + [serde_json::to_value(asst_msg("old hello")).expect("ser"), "m2"], + ], + "compaction_summaries": [{"summary": "old summary", "up_to_order": 1}], + }); + std::fs::write( + dir.path().join("root.json"), + serde_json::to_vec(&legacy_snapshot).expect("ser"), + ) + .expect("write legacy snapshot"); + std::fs::write( + dir.path().join("root.meta.json"), + serde_json::to_vec(&serde_json::json!({ + "parent_thread_id": null, + "root_thread_id": "root", + "spawn_message_order": null, + "spawn_tool_call_id": null, + "closed": false, + "is_subscription_event": false, + "title": "legacy title", + "children": [], + "total_tokens_used": 7, + "last_updated": "2024", + })) + .expect("ser"), + ) + .expect("write legacy meta"); + + let store = open_store(dir.path()); + let history = store + .load_history_up_to(root, None, None) + .await + .expect("load"); + assert_eq!(texts(&history), vec!["old hi", "old hello"]); + assert_eq!( + store + .load_latest_compaction_summary_up_to(root, None) + .await + .expect("compaction"), + Some(("old summary".to_owned(), 1)) + ); + assert_eq!( + store.get_thread_title(root), + Some("legacy title".to_owned()) + ); + assert_eq!( + store.get_thread_model(root), + test_model(), + "missing selected_model is backfilled" + ); + assert!(dir.path().join("root.jsonl").exists(), "log written"); + assert!( + dir.path().join("root.json").exists(), + "legacy snapshot left in place" + ); + + // Appends go to the log; the legacy snapshot is never consulted again. + store + .append_messages(root, vec![(user_msg("new"), Some("m3".into()))]) + .await + .expect("append"); + std::fs::remove_file(dir.path().join("root.json")).expect("remove legacy"); + let store = open_store(dir.path()); + let history = store + .load_history_up_to(root, None, None) + .await + .expect("load"); + assert_eq!(texts(&history), vec!["old hi", "old hello", "new"]); + // The rewritten metadata is versioned. + let meta: serde_json::Value = serde_json::from_slice( + &std::fs::read(dir.path().join("root.meta.json")).expect("read meta"), + ) + .expect("parse meta"); + assert_eq!(meta["version"], serde_json::json!(THREAD_META_VERSION)); + assert_eq!(meta["title"], serde_json::json!("legacy title")); + } + + /// Processed-id lookups are answered from the log itself, so they + /// survive a restart with no separate file to fall out of sync. + #[tokio::test] + async fn processed_ids_are_looked_up_in_the_log() { + let dir = tempfile::tempdir().expect("create temp dir"); + let root = ThreadId::from_ref("root"); + let conv = open_store(dir.path()); + conv.ensure_root_thread(root).await.expect("root"); + conv.append_messages( + root, + vec![ + (user_msg("u"), Some("user-1".into())), + (asst_msg("a"), Some("asst-1".into())), + (InfinityMessage::Interrupt, None), + ], + ) + .await + .expect("append"); + + for store in [conv, open_store(dir.path())] { + for id in ["user-1", "asst-1"] { + assert!( + store.is_message_processed(root, id).await.expect("lookup"), + "{id} is persisted" + ); + } + assert!( + !store + .is_message_processed(root, "user-2") + .await + .expect("lookup") + ); + assert!( + !store + .is_message_processed(ThreadId::from_ref("other"), "user-1") + .await + .expect("lookup"), + "ids are scoped per thread" + ); + } + assert!( + !dir.path().join("root.state.json").exists(), + "no state file is written for processed ids" + ); + } + + /// A pre-versioning views file (the bare `view_type → content` map) + /// loads, and is rewritten in the versioned shape on first load. + #[tokio::test] + async fn legacy_views_file_is_upgraded() { + let dir = tempfile::tempdir().expect("create temp dir"); + let root = ThreadId::from_ref("root"); + std::fs::write( + dir.path().join("root.views.json"), + serde_json::to_vec(&serde_json::json!({"legacy": {"x": 2}})).expect("ser"), + ) + .expect("write legacy views"); + + let store = open_store(dir.path()); + assert_eq!( + store.get_views(root).get("legacy"), + Some(&serde_json::json!({"x": 2})) + ); + let upgraded: serde_json::Value = serde_json::from_slice( + &std::fs::read(dir.path().join("root.views.json")).expect("read"), + ) + .expect("parse"); + assert_eq!(upgraded["version"], serde_json::json!(THREAD_VIEWS_VERSION)); + assert_eq!(upgraded["views"]["legacy"], serde_json::json!({"x": 2})); + } + + /// A log written by a newer daemon is refused (never appended to in the + /// old format), and the refusal surfaces as an error rather than an + /// empty thread. + #[tokio::test] + async fn newer_log_version_is_refused() { + let dir = tempfile::tempdir().expect("create temp dir"); + let root = ThreadId::from_ref("root"); + std::fs::write( + dir.path().join("root.jsonl"), + format!( + "{{\"kind\":\"header\",\"version\":{},\"thread_id\":\"root\"}}\n", + THREAD_LOG_VERSION + 1 + ), + ) + .expect("write"); + let store = open_store(dir.path()); + let err = store + .append_messages(root, vec![(user_msg("x"), Some("m1".into()))]) + .await + .expect_err("newer version must be refused"); + assert!(err.to_string().contains("newer"), "{err}"); + assert_eq!( + std::fs::read_to_string(dir.path().join("root.jsonl")) + .expect("read") + .lines() + .count(), + 1, + "nothing was appended" + ); + } + + /// A pre-versioning state file (which carried processed ids) loads, is + /// rewritten in the versioned shape without them, and its subscriptions + /// and pending choices survive. + #[tokio::test] + async fn legacy_state_file_is_upgraded() { + let dir = tempfile::tempdir().expect("create temp dir"); + let root = ThreadId::from_ref("root"); + let (change_tx, _change_rx) = tokio::sync::mpsc::unbounded_channel(); + let session_store = Arc::new(tokio::sync::Mutex::new( + crate::session_store::SessionStore::load( + &dir.path().join("sessions.json").to_string_lossy(), + change_tx, + ), + )); + let state_dir = dir.path().join("state"); + std::fs::create_dir_all(&state_dir).expect("mkdir"); + std::fs::write( + state_dir.join("root.state.json"), + serde_json::to_vec(&serde_json::json!({ + "processed_message_ids": ["stale-1"], + "metadata": {"user_id": "u1"}, + "subscriptions": ["sub-1"], + "pending_user_choices": [], + })) + .expect("ser"), + ) + .expect("write legacy state"); + + let conv = open_store(&dir.path().join("threads")); + let state = PersistentStateStore::new(&state_dir, conv.clone(), session_store); + assert_eq!( + state.get_active_subscriptions(root).await.expect("subs"), + vec![rap_protocol::ToolCallId::from("sub-1")] + ); + assert_eq!( + state.get_metadata(root).await.expect("metadata"), + Some(serde_json::json!({"user_id": "u1"})) + ); + let upgraded: serde_json::Value = serde_json::from_slice( + &std::fs::read(state_dir.join("root.state.json")).expect("read"), + ) + .expect("parse"); + assert_eq!(upgraded["version"], serde_json::json!(THREAD_STATE_VERSION)); + assert!( + upgraded.get("processed_message_ids").is_none(), + "processed ids are no longer stored: {upgraded}" + ); + } } diff --git a/crates/infinity-daemon/src/persist.rs b/crates/infinity-daemon/src/persist.rs new file mode 100644 index 00000000..f9d5ed79 --- /dev/null +++ b/crates/infinity-daemon/src/persist.rs @@ -0,0 +1,565 @@ +//! Crash-safe file primitives for the daemon's on-disk state. +//! +//! Two write patterns cover every file the daemon persists: +//! +//! - **Append-only logs** ([`ThreadLog`]): a thread's conversation history is +//! a JSONL file whose first line is a [`ThreadLogEntry::Header`] and whose +//! remaining lines are appended, never rewritten. A crash mid-append can +//! only tear the *last* line, so loading recovers the longest valid prefix +//! and truncates the torn tail before anything new is appended. +//! - **Atomic replacement** ([`write_atomic`]): small "last writer wins" +//! documents (thread metadata, tool state, views, the session index) are +//! written to a temporary file in the same directory, fsynced, and renamed +//! over the destination, so readers only ever see the old or the new +//! contents, never a partial write. +//! +//! Every file carries a format version so future layout changes can migrate +//! old files explicitly instead of guessing from their shape. Files written +//! before versioning was introduced deserialize with version +//! [`LEGACY_VERSION`] (`0`). + +use std::fs::{File, OpenOptions}; +use std::io::{self, Write}; +use std::path::Path; + +use infinity_agent_core::ThreadId; +use infinity_agent_core::message::InfinityMessage; +use infinity_agent_core::stores::CompactionSummary; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; + +/// The version deserialized for files written before format versioning +/// existed (the `version` field is absent). +pub const LEGACY_VERSION: u32 = 0; + +/// Current format version of a thread's conversation log (`{thread_id}.jsonl`). +pub const THREAD_LOG_VERSION: u32 = 1; +/// Current format version of a thread's metadata file (`{thread_id}.meta.json`). +pub const THREAD_META_VERSION: u32 = 1; +/// Current format version of a thread's views file (`{thread_id}.views.json`). +pub const THREAD_VIEWS_VERSION: u32 = 1; +/// Current format version of a thread's tool-state file (`{thread_id}.state.json`). +pub const THREAD_STATE_VERSION: u32 = 1; +/// Current format version of the session index (`sessions.json`). +pub const SESSIONS_VERSION: u32 = 1; + +/// Errors from reading or writing persisted state. +#[derive(Debug)] +pub enum PersistError { + Io { + path: String, + source: io::Error, + }, + /// The file is well-formed but was written by a newer format version + /// than this daemon understands. Refusing to read (and therefore to + /// write) it is deliberate: appending in the old format would corrupt + /// the newer file. + UnsupportedVersion { + path: String, + found: u32, + supported: u32, + }, + /// A complete, newline-terminated log line (or a whole JSON document) + /// failed to parse. This is not a torn write — torn tails are repaired + /// transparently — so it is surfaced rather than silently truncated. + Corrupt { + path: String, + detail: String, + }, +} + +impl std::fmt::Display for PersistError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + PersistError::Io { path, source } => write!(f, "{path}: {source}"), + PersistError::UnsupportedVersion { + path, + found, + supported, + } => write!( + f, + "{path}: format version {found} is newer than the supported version {supported} \ + (was this file written by a newer daemon?)" + ), + PersistError::Corrupt { path, detail } => write!(f, "{path}: corrupt: {detail}"), + } + } +} + +impl std::error::Error for PersistError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + PersistError::Io { source, .. } => Some(source), + _ => None, + } + } +} + +fn io_err(path: &Path, source: io::Error) -> PersistError { + PersistError::Io { + path: path.display().to_string(), + source, + } +} + +/// Fail if `found` is a version this daemon cannot read. +pub fn check_version(path: &Path, found: u32, supported: u32) -> Result<(), PersistError> { + if found > supported { + return Err(PersistError::UnsupportedVersion { + path: path.display().to_string(), + found, + supported, + }); + } + Ok(()) +} + +/// Flush a directory so a rename (or new file) inside it is durable. +fn sync_dir(dir: &Path) -> io::Result<()> { + // Directory fsync is a no-op or unsupported on some platforms/filesystems; + // those report an error we can safely ignore after logging. + match File::open(dir).and_then(|d| d.sync_all()) { + Ok(()) => Ok(()), + Err(e) if cfg!(windows) => { + tracing::debug!(dir = %dir.display(), error = %e, "directory fsync unsupported"); + Ok(()) + } + Err(e) => Err(e), + } +} + +/// Atomically replace the file at `path` with `bytes`: write to a uniquely +/// named temporary file in the same directory, fsync it, rename it over +/// `path`, and fsync the directory. A crash at any point leaves either the +/// previous contents or the new ones; the temporary file is removed on every +/// failure path (it is dropped unless persisted). +pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), PersistError> { + let dir = path.parent().unwrap_or_else(|| Path::new(".")); + (|| -> io::Result<()> { + let mut tmp = tempfile::Builder::new() + .prefix(".") + .suffix(".tmp") + .tempfile_in(dir)?; + tmp.write_all(bytes)?; + tmp.as_file().sync_all()?; + tmp.persist(path).map_err(|e| e.error)?; + sync_dir(dir) + })() + .map_err(|e| io_err(path, e)) +} + +/// Serialize `value` as pretty JSON and [`write_atomic`] it to `path`. +pub fn write_json_atomic(path: &Path, value: &T) -> Result<(), PersistError> { + let json = serde_json::to_vec_pretty(value).map_err(|e| PersistError::Corrupt { + path: path.display().to_string(), + detail: format!("serialization failed: {e}"), + })?; + write_atomic(path, &json) +} + +/// Read and parse a JSON document, returning `Ok(None)` if the file does not +/// exist. Parse failures are reported as [`PersistError::Corrupt`]. +pub fn read_json(path: &Path) -> Result, PersistError> { + let bytes = match std::fs::read(path) { + Ok(b) => b, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(io_err(path, e)), + }; + serde_json::from_slice(&bytes) + .map(Some) + .map_err(|e| PersistError::Corrupt { + path: path.display().to_string(), + detail: e.to_string(), + }) +} + +// ── Thread conversation log ── + +/// One line of a thread's conversation log. +/// +/// The log is the single source of truth for a thread's conversation: its +/// messages (each with the dedup id it was delivered under, so processed-id +/// tracking is derived from the log rather than kept in a second file) and +/// its compaction summaries, in the order they were committed. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum ThreadLogEntry { + /// Always the first line. + Header { version: u32, thread_id: ThreadId }, + /// A committed history entry. `id` is the dedup id an input arrived + /// under; runtime-minted entries (model output, synthetic tool results, + /// interrupt markers) have none. + Message { + #[serde(default, skip_serializing_if = "Option::is_none")] + id: Option, + message: InfinityMessage, + }, + /// A compaction summary covering the thread's first `up_to_order` + /// messages. + CompactionSummary { summary: String, up_to_order: i64 }, +} + +/// The contents of a thread log after loading. Message ids follow the +/// [`ThreadLogEntry::Message`] convention. +#[derive(Debug, Default)] +pub struct LoadedThreadLog { + pub messages: Vec<(InfinityMessage, Option)>, + pub compaction_summaries: Vec, +} + +/// A thread's append-only conversation log at a fixed path. +pub struct ThreadLog<'a> { + pub path: &'a Path, + pub thread_id: &'a ThreadId, +} + +impl ThreadLog<'_> { + fn corrupt(&self, detail: String) -> PersistError { + PersistError::Corrupt { + path: self.path.display().to_string(), + detail, + } + } + + fn header_line(&self) -> Vec { + let mut line = serde_json::to_vec(&ThreadLogEntry::Header { + version: THREAD_LOG_VERSION, + thread_id: self.thread_id.to_owned(), + }) + .expect("bug: header serialization failed"); + line.push(b'\n'); + line + } + + fn encode(&self, entries: &[ThreadLogEntry]) -> Result, PersistError> { + let mut buf = Vec::new(); + for entry in entries { + serde_json::to_writer(&mut buf, entry) + .map_err(|e| self.corrupt(format!("serialization failed: {e}")))?; + buf.push(b'\n'); + } + Ok(buf) + } + + /// Load the log, returning `Ok(None)` if it does not exist. + /// + /// Recovers the longest valid prefix: a trailing line without a + /// terminating newline is a torn write from a crash mid-append, so it is + /// dropped (with a warning) and the file is truncated to the last + /// complete line, keeping the on-disk log consistent with what was + /// loaded before anything new is appended. A complete line that fails + /// to parse is *not* a torn write and is reported as corruption. + pub fn load(&self) -> Result, PersistError> { + let bytes = match std::fs::read(self.path) { + Ok(b) => b, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(io_err(self.path, e)), + }; + + // Split into complete lines; whatever follows the last newline is a + // torn tail. + let valid_len = bytes.iter().rposition(|&b| b == b'\n').map_or(0, |i| i + 1); + if valid_len < bytes.len() { + tracing::warn!( + path = %self.path.display(), + dropped_bytes = bytes.len() - valid_len, + "thread log has a torn trailing line (crash mid-append?); \ + recovering the last complete prefix" + ); + OpenOptions::new() + .write(true) + .open(self.path) + .and_then(|f| f.set_len(valid_len as u64)) + .map_err(|e| io_err(self.path, e))?; + } + let complete = &bytes[..valid_len]; + + let mut loaded = LoadedThreadLog::default(); + let mut saw_header = false; + for (idx, line) in complete.split(|&b| b == b'\n').enumerate() { + if line.is_empty() { + // The final split element after the last '\n', or a stray + // blank line. + continue; + } + let entry: ThreadLogEntry = serde_json::from_slice(line) + .map_err(|e| self.corrupt(format!("line {}: {e}", idx + 1)))?; + match entry { + ThreadLogEntry::Header { version, thread_id } => { + if saw_header { + return Err(self.corrupt(format!("line {}: duplicate header", idx + 1))); + } + check_version(self.path, version, THREAD_LOG_VERSION)?; + if thread_id != *self.thread_id { + return Err(self.corrupt(format!( + "header names thread {thread_id} but file belongs to {}", + self.thread_id + ))); + } + saw_header = true; + } + entry if !saw_header => { + return Err(self.corrupt(format!( + "line {}: expected header, found {entry:?}", + idx + 1 + ))); + } + ThreadLogEntry::Message { id, message } => loaded.messages.push((message, id)), + ThreadLogEntry::CompactionSummary { + summary, + up_to_order, + } => loaded.compaction_summaries.push(CompactionSummary { + summary, + up_to_order, + }), + } + } + // An empty (or fully torn) file is indistinguishable from a missing + // one: the header is written with the first append. + Ok(Some(loaded)) + } + + /// Append entries durably. Creates the file (with its header) on first + /// use. All lines are written with a single `write_all` followed by + /// `fdatasync`, so a crash tears at most the final line. If the write + /// itself fails, the file is truncated back to its previous length so a + /// partial line can never end up in the middle of the log. + pub fn append(&self, entries: &[ThreadLogEntry]) -> Result<(), PersistError> { + if entries.is_empty() { + return Ok(()); + } + let mut file = OpenOptions::new() + .create(true) + .append(true) + .open(self.path) + .map_err(|e| io_err(self.path, e))?; + let previous_len = file.metadata().map_err(|e| io_err(self.path, e))?.len(); + let mut buf = if previous_len == 0 { + self.header_line() + } else { + Vec::new() + }; + buf.extend(self.encode(entries)?); + if let Err(e) = file.write_all(&buf).and_then(|()| file.sync_data()) { + if let Err(truncate_err) = file.set_len(previous_len) { + tracing::error!( + path = %self.path.display(), + error = %truncate_err, + "failed to roll back a partial append; the torn tail will be \ + recovered on next load" + ); + } + return Err(io_err(self.path, e)); + } + Ok(()) + } + + /// Replace the whole log (header included) atomically. Used when a thread + /// is imported or migrated from an older on-disk format, never for + /// ordinary appends. + pub fn rewrite(&self, contents: &LoadedThreadLog) -> Result<(), PersistError> { + let mut buf = self.header_line(); + let entries: Vec = contents + .messages + .iter() + .map(|(message, id)| ThreadLogEntry::Message { + id: id.clone(), + message: message.clone(), + }) + .chain(contents.compaction_summaries.iter().map(|c| { + ThreadLogEntry::CompactionSummary { + summary: c.summary.clone(), + up_to_order: c.up_to_order, + } + })) + .collect(); + buf.extend(self.encode(&entries)?); + write_atomic(self.path, &buf) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use infinity_provider_protocol::message::UserContent; + + fn user(text: &str) -> InfinityMessage { + InfinityMessage::User { + content: UserContent::text(text), + } + } + + /// Messages as `(dedup id, JSON)` pairs, for equality assertions + /// (`InfinityMessage` is not `PartialEq`). + fn as_json( + messages: &[(InfinityMessage, Option)], + ) -> Vec<(Option, serde_json::Value)> { + messages + .iter() + .map(|(m, id)| (id.clone(), serde_json::to_value(m).expect("serialize"))) + .collect() + } + + fn msg_entry(id: &str, text: &str) -> ThreadLogEntry { + ThreadLogEntry::Message { + id: Some(id.to_owned()), + message: user(text), + } + } + + #[test] + fn append_then_load_round_trips() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("t.jsonl"); + let log = ThreadLog { + path: &path, + thread_id: ThreadId::from_ref("t"), + }; + assert!(log.load().expect("load missing").is_none()); + + log.append(&[msg_entry("m1", "one"), msg_entry("m2", "two")]) + .expect("append"); + log.append(&[ThreadLogEntry::CompactionSummary { + summary: "s".to_owned(), + up_to_order: 2, + }]) + .expect("append compaction"); + + let loaded = log.load().expect("load").expect("exists"); + assert_eq!( + as_json(&loaded.messages), + as_json(&[ + (user("one"), Some("m1".to_owned())), + (user("two"), Some("m2".to_owned())) + ]) + ); + assert_eq!(loaded.compaction_summaries.len(), 1); + assert_eq!(loaded.compaction_summaries[0].up_to_order, 2); + + // Exactly one header line, first. + let text = std::fs::read_to_string(&path).expect("read"); + let lines: Vec<&str> = text.lines().collect(); + assert_eq!(lines.len(), 4); + assert!(lines[0].contains("\"kind\":\"header\"")); + assert!(lines[0].contains(&format!("\"version\":{THREAD_LOG_VERSION}"))); + } + + #[test] + fn torn_tail_is_dropped_and_truncated() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("t.jsonl"); + let log = ThreadLog { + path: &path, + thread_id: ThreadId::from_ref("t"), + }; + log.append(&[msg_entry("m1", "one"), msg_entry("m2", "two")]) + .expect("append"); + + // Simulate a crash mid-append: a partial third line. + let mut f = OpenOptions::new() + .append(true) + .open(&path) + .expect("open for append"); + f.write_all(b"{\"kind\":\"message\",\"id\":\"m3\",\"mess") + .expect("write partial"); + drop(f); + let torn_len = std::fs::metadata(&path).expect("stat").len(); + + let loaded = log.load().expect("load").expect("exists"); + assert_eq!(loaded.messages.len(), 2, "torn line is dropped"); + assert!( + std::fs::metadata(&path).expect("stat").len() < torn_len, + "file truncated to the last complete line" + ); + + // Appending after recovery yields a clean log. + log.append(&[msg_entry("m3", "three")]).expect("append"); + let loaded = log.load().expect("load").expect("exists"); + assert_eq!(loaded.messages.len(), 3); + assert_eq!(loaded.messages[2].1.as_deref(), Some("m3")); + } + + #[test] + fn torn_header_recovers_to_empty_log() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("t.jsonl"); + std::fs::write(&path, b"{\"kind\":\"header\",\"ver").expect("write"); + let log = ThreadLog { + path: &path, + thread_id: ThreadId::from_ref("t"), + }; + let loaded = log.load().expect("load").expect("exists"); + assert!(loaded.messages.is_empty()); + // The next append rewrites the header. + log.append(&[msg_entry("m1", "one")]).expect("append"); + let text = std::fs::read_to_string(&path).expect("read"); + assert_eq!(text.lines().count(), 2); + assert!(text.lines().next().expect("header").contains("header")); + } + + #[test] + fn complete_but_corrupt_line_is_an_error_not_truncated() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("t.jsonl"); + let log = ThreadLog { + path: &path, + thread_id: ThreadId::from_ref("t"), + }; + log.append(&[msg_entry("m1", "one")]).expect("append"); + let mut f = OpenOptions::new() + .append(true) + .open(&path) + .expect("open for append"); + f.write_all(b"not json\n").expect("write garbage"); + drop(f); + let before = std::fs::metadata(&path).expect("stat").len(); + let err = log.load().expect_err("corrupt line must fail"); + assert!(matches!(err, PersistError::Corrupt { .. }), "{err}"); + assert_eq!( + std::fs::metadata(&path).expect("stat").len(), + before, + "corruption is never silently truncated" + ); + } + + #[test] + fn newer_version_is_rejected() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("t.jsonl"); + std::fs::write( + &path, + format!( + "{{\"kind\":\"header\",\"version\":{},\"thread_id\":\"t\"}}\n", + THREAD_LOG_VERSION + 1 + ), + ) + .expect("write"); + let log = ThreadLog { + path: &path, + thread_id: ThreadId::from_ref("t"), + }; + let err = log.load().expect_err("newer version must fail"); + assert!( + matches!(err, PersistError::UnsupportedVersion { .. }), + "{err}" + ); + } + + #[test] + fn rewrite_replaces_contents() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("t.jsonl"); + let log = ThreadLog { + path: &path, + thread_id: ThreadId::from_ref("t"), + }; + log.append(&[msg_entry("old", "old")]).expect("append"); + log.rewrite(&LoadedThreadLog { + messages: vec![(user("new"), None)], + compaction_summaries: vec![], + }) + .expect("rewrite"); + let loaded = log.load().expect("load").expect("exists"); + assert_eq!(as_json(&loaded.messages), as_json(&[(user("new"), None)])); + } +} diff --git a/crates/infinity-daemon/src/session/display.rs b/crates/infinity-daemon/src/session/display.rs index f6ccc05d..a1d47a57 100644 --- a/crates/infinity-daemon/src/session/display.rs +++ b/crates/infinity-daemon/src/session/display.rs @@ -143,12 +143,11 @@ pub(crate) fn history_message_to_daemon( } InfinityMessage::User { content } => { if let UserContent::Text(text) = content { - // Interrupting inputs are stored with the `` - // prefix the model sees; strip it for display exactly like - // the live `AgentEvent::UserInput` echo does. + // Older histories stored interrupting text with the + // `` prefix; hide it on replay. let display_text = text .text - .strip_prefix("") + .strip_prefix(infinity_agent_core::message::INTERRUPT_TOKEN) .unwrap_or(&text.text) .to_owned(); Some(DaemonMessage::UserInputEcho { @@ -169,5 +168,6 @@ pub(crate) fn history_message_to_daemon( None } } + InfinityMessage::Interrupt => None, } } diff --git a/crates/infinity-daemon/src/session_store.rs b/crates/infinity-daemon/src/session_store.rs index c732b7c5..982a03d9 100644 --- a/crates/infinity-daemon/src/session_store.rs +++ b/crates/infinity-daemon/src/session_store.rs @@ -1,9 +1,12 @@ use infinity_agent_core::ThreadId; +use std::path::Path; use std::{collections::HashMap, path::PathBuf}; use serde::{Deserialize, Serialize}; use tokio::sync::mpsc; +use crate::persist::{self, PersistError, SESSIONS_VERSION}; + #[derive(Serialize, Deserialize, Clone, Debug)] pub struct SessionEntry { pub cwd: PathBuf, @@ -34,8 +37,16 @@ impl SessionEntry { } } +/// The session index (`{state_dir}/sessions.json`): every session's working +/// directory and lifecycle flags, keyed by root thread id. Written atomically +/// (see [`crate::persist::write_atomic`]) so a crash mid-save never leaves a +/// truncated index. #[derive(Serialize, Deserialize)] pub struct SessionStore { + /// Format version (see [`SESSIONS_VERSION`]); absent in files written + /// before versioning. + #[serde(default)] + pub version: u32, pub sessions: HashMap, #[serde(skip)] path: String, @@ -44,56 +55,73 @@ pub struct SessionStore { } impl SessionStore { + /// Load the index from `path`. A missing file yields an empty store. An + /// unreadable one is logged and also yields an empty store — but a file + /// written by a newer daemon (unsupported version) is a hard error, since + /// saving over it would destroy data this daemon cannot interpret. pub fn load(path: &str, change_tx: mpsc::UnboundedSender) -> Self { - let sessions = std::fs::read_to_string(path) - .ok() - .and_then(|s| { - // Try new HashMap format first - if let Ok(store) = serde_json::from_str::(&s) { - return Some(store.sessions); - } - // Fall back to legacy Vec format - #[derive(Deserialize)] - struct LegacyEntry { - thread_id: ThreadId, - } - #[derive(Deserialize)] - struct LegacyStore { - sessions: Vec, - } - if let Ok(legacy) = serde_json::from_str::(&s) { - let map = legacy - .sessions - .into_iter() - .map(|e| { - ( - e.thread_id, - SessionEntry { - cwd: std::env::current_dir() - .expect("failed to get current directory"), - shut_down: false, - idle: false, - archived: false, - }, - ) - }) - .collect(); - return Some(map); - } - None - }) - .unwrap_or_default(); + let sessions = match Self::read_sessions(path) { + Ok(sessions) => sessions, + Err(error @ PersistError::UnsupportedVersion { .. }) => { + panic!("cannot load session index: {error}"); + } + Err(error) => { + tracing::error!(%error, "failed to load session index; starting empty"); + HashMap::new() + } + }; Self { + version: SESSIONS_VERSION, sessions, path: path.to_owned(), change_tx: Some(change_tx), } } + fn read_sessions(path: &str) -> Result, PersistError> { + let path = Path::new(path); + let Some(raw) = persist::read_json::(path)? else { + return Ok(HashMap::new()); + }; + // Current (and pre-versioning) HashMap format. + if let Ok(store) = serde_json::from_value::(raw.clone()) { + persist::check_version(path, store.version, SESSIONS_VERSION)?; + return Ok(store.sessions); + } + // Legacy Vec format. + #[derive(Deserialize)] + struct LegacyEntry { + thread_id: ThreadId, + } + #[derive(Deserialize)] + struct LegacyStore { + sessions: Vec, + } + let legacy: LegacyStore = + serde_json::from_value(raw).map_err(|e| PersistError::Corrupt { + path: path.display().to_string(), + detail: e.to_string(), + })?; + Ok(legacy + .sessions + .into_iter() + .map(|e| { + ( + e.thread_id, + SessionEntry { + cwd: std::env::current_dir().expect("failed to get current directory"), + shut_down: false, + idle: false, + archived: false, + }, + ) + }) + .collect()) + } + pub fn save(&self) -> Result<(), Box> { - let json = serde_json::to_string_pretty(self)?; - std::fs::write(&self.path, json)?; + persist::write_json_atomic(Path::new(&self.path), self)?; Ok(()) } diff --git a/docs/docs/infinity-runtime/low-level/history-manager.md b/docs/docs/infinity-runtime/low-level/history-manager.md index c760b95d..b86fdf90 100644 --- a/docs/docs/infinity-runtime/low-level/history-manager.md +++ b/docs/docs/infinity-runtime/low-level/history-manager.md @@ -30,15 +30,19 @@ Constructing the manager restores the thread's world from durable storage: - The **ancestor chain** is loaded via `ConversationStore::get_ancestor_chain`, identifying the root thread and every parent between it and this thread. - The **history** is loaded via `load_history_with_ancestors`, which reconstructs a child thread's inherited context: ancestor messages up to each spawn point, with the most recent compaction summary (from this thread or any ancestor) substituted for everything it covers. A freshly spawned child thread therefore sees its parent's conversation up to the moment of the spawn, and compaction transparently shortens what gets loaded. -- The **deduplication set** of processed message IDs comes from `StateStore::get_processed_ids`, along with per-conversation metadata. +- The **per-conversation metadata** comes from the `StateStore`. Nothing else is preloaded: whether an input was already processed is answered on demand by `ConversationStore::is_message_processed`, a point lookup against the persisted history (which stores each input together with the dedup ID it arrived under). Because everything is restored on load, an agent's full state can be rebuilt in any process, at any time, from the two stores. This is the property that makes the runtime serverless-capable. ## Committed History and the Turn Buffer The manager keeps three layers of unpersisted state on top of the in-memory `history`: -- **Unvalidated inputs** are inputs (user text, tool results, injected synthetic results) that the model has not produced any output for yet. Inputs accepted by `handle_content` land here. They are part of the in-memory history, so the next completion includes them, but `sync()` will not persist them: one of them could be the oversized message that overflows the model's context window, and persisting it would wedge the thread on that message forever. As soon as the model streams any output for a request, `mark_inputs_model_validated` promotes them, since output proves that the context fit. +- **Unvalidated inputs** are inputs (user text, tool results, injected synthetic results) that the model has not produced any output for yet. Inputs accepted by `handle_input` land here. They are part of the in-memory history, so the next completion includes them, but `sync()` will not persist them: one of them could be the oversized message that overflows the model's context window, and persisting it would wedge the thread on that message forever. As soon as the model streams any output for a request, `mark_inputs_model_validated` promotes them, since output proves that the context fit. - **Known-safe items** (`pending_items`) are promoted inputs and model-produced content that will be persisted by the next `sync()`. Model output can only be committed after the inputs it answers have been promoted, so known-safe items always precede unvalidated ones in history order. + + Interrupt markers are the one kind of input that can skip validation. When **user text** arrives while the history ends on an unanswered tool call, the manager records an `Interrupt` entry that settles the call (rendered to the model as an "interrupted by user" tool result). Because a tool call at the tail is committed model output, nothing unvalidated can precede it, so the marker is committed known-safe, and the step's commit barrier (an unconditional `sync()` between the prepare and completion phases) persists it before the interrupted tool is cancelled or the model is invoked — regardless of what later happens to the text that caused it. A marker that arrives in any other position (user text cutting off a streaming completion whose inputs have not yet been validated) must stay unvalidated to preserve the ordering above, but it is never dropped by overflow recovery. + + An **event** (subscription event or child report) that interrupts a tool call records no marker. The event itself is the record — it is never dropped, only placeholder-replaced on overflow — and `render_history` infers the interruption from it, answering the call with an "interrupted by an incoming event" result. This keeps the persisted history honest for a future resume: if the process dies before the event is validated, the log ends on the bare tool call and reads as "in flight", not as a deliberate stop. - **The turn buffer** holds assistant content for the turn that is currently streaming. `handle_completion` buffers each streamed chunk (coalescing consecutive text chunks into one message) without committing it. The turn buffer exists because a streaming turn can fail or be interrupted halfway. At a **flush point** (meaning that the turn completed, or a turn-ending tool call arrived), `flush_turn` commits the buffer into history; `flush_turn_trimming_reasoning` additionally drops trailing reasoning, so that a committed turn never ends on a thinking block. On a mid-stream failure that will be retried, `discard_turn` drops the buffer so that the retry can rebuild its request from clean committed history. @@ -62,9 +66,9 @@ history.sync().await?; # } ``` -`sync` writes the known-safe items committed since the last sync: they go through `ConversationStore::append_messages`, and the IDs that need durable deduplication go through the `StateStore`. Unvalidated inputs stay in memory until the model has answered them. It asserts that the turn buffer is empty, since calling it with un-flushed turn content is a bug (that content would be silently lost). +`sync` writes the known-safe items committed since the last sync through `ConversationStore::append_messages`. Inputs are paired with the dedup ID they arrived under; entries the runtime minted itself (model output, synthetic tool results, interrupt markers) carry none, since they can never be redelivered. Unvalidated inputs stay in memory until the model has answered them. It asserts that the turn buffer is empty, since calling it with un-flushed turn content is a bug (that content would be silently lost). -The persisted IDs are what make redelivery safe. Only inputs that are not naturally idempotent need them: user text and subscription events (a redelivered subscription event would mint a fresh injected invocation and be appended again). `handle_content(message, message_id)` is the single entry point for appending input to history: it consults the processed-ID set first, so a redelivered message (with the same `message_id`) will be skipped. Tool results do not need durable IDs at all, because they can be deduplicated against the history tail itself: the manager walks back across the trailing tool calls and results, and discards a result whose call is already answered (or has no live call). Because the IDs are persisted in the same `sync()` that persists the messages, a crash between processing and persistence will reprocess the message rather than duplicate it. +The persisted IDs are what make redelivery safe. `handle_input(message, message_id)` is the single entry point for appending an incoming input to history, and the only place dedup IDs are checked or recorded: it first checks the IDs handled in this process, then asks the `ConversationStore` whether the ID was persisted by an earlier incarnation of the thread, and skips the message if so. (`handle_content(message)` is the id-less counterpart for content the runtime mints during a completion round.) Tool results are additionally deduplicated against the history tail itself: the manager walks back across the trailing tool calls and results, and discards a result whose call is already answered (or has no live call). Because each ID is stored with its message in the same `append_messages` call, there is no separate write that can be lost: a crash between processing and persistence will reprocess the message rather than duplicate it, and an input can never be persisted without its ID. The loop's core ordering guarantee is built on this call: **a tool call is dispatched only after the turn that produced it has been synced.** If the process dies after dispatch, the persisted history already contains the tool call, so the eventual result message has something to attach to. The high-level API's step enforces this ordering (sync, then dispatch). If you drive [`execute_action`](./completion-loop.md) yourself, you must preserve it.