diff --git a/crates/infinity-agent-core/src/event_processor.rs b/crates/infinity-agent-core/src/event_processor.rs index d42957a6..c517bae8 100644 --- a/crates/infinity-agent-core/src/event_processor.rs +++ b/crates/infinity-agent-core/src/event_processor.rs @@ -79,13 +79,19 @@ pub enum PrepareResult { CompactionApplied, } -/// What the model wants to do after a completion stream finishes. +/// What the model wants to do, as surfaced by the completion stream. pub enum CompletionAction { - /// Model produced text and is done (no tool call). + /// Model produced text and is done (no tool call). Carries the round's + /// final response (including usage, if the provider reported it). Done(FinalResponse), /// Model wants to execute a tool call. Under the RAP protocol tools are /// fire-and-forget: the agent loop stops after dispatching the call and /// the result arrives as a new input message later. + /// + /// By the time this action is yielded, [`run_completion`] has already + /// flushed the turn and synced the history, so the call is durable and + /// may be dispatched **immediately** — the consumer does not have to + /// wait for the stream to finish (see [`execute_action`]). ExecuteToolCall { tool_name: String, tool_args: serde_json::Value, @@ -99,7 +105,9 @@ pub enum CompletionAction { pub enum CompletionEvent { /// A chunk of text from the model. TextChunk(String), - /// The terminal event — what to do next. + /// Something the model decided to do. `ExecuteToolCall` is yielded as + /// soon as the call is complete and durable, which may be well before + /// the model's stream ends; `Done` is yielded once per model response. Action(CompletionAction), /// A tool call that was synchronously processed. SyncToolCall { @@ -1905,6 +1913,18 @@ where })?; should_loop_back = true; } else { + // Make the call durable *before* handing it + // out: the consumer may dispatch it the moment + // it is yielded, while this stream is still + // draining the model's tail (the `Final` chunk + // and any ignored post-call content). The + // inputs that led to this call were validated + // by the first chunk of this request (see + // above); re-asserting that here is idempotent + // and keeps the durability precondition local. + history.mark_inputs_model_validated(); + history.sync().await?; + yield CompletionEvent::Action(CompletionAction::ExecuteToolCall { tool_name: call.function.name.clone(), tool_args: call.function.arguments.clone(), @@ -1965,6 +1985,15 @@ where // or emit output). // ═══════════════════════════════════════════════════════════════════════ +/// Dispatch a [`CompletionAction`]. `Done` is a no-op; `ExecuteToolCall` +/// invokes the tool's fire-and-forget `execute`. +/// +/// Durability: the tool call must be persisted before this is called, so a +/// crash between persist and dispatch leaves a history the result can still +/// attach to. [`run_completion`] syncs the history *before* yielding an +/// `ExecuteToolCall`, so a consumer of its stream may call this as soon as +/// the action arrives — concurrently with draining the rest of the stream — +/// without any additional barrier. pub async fn execute_action( action: CompletionAction, tool_registry: &HashMap>, diff --git a/crates/infinity-agent-core/src/system/thread.rs b/crates/infinity-agent-core/src/system/thread.rs index 71fef7b8..325f946d 100644 --- a/crates/infinity-agent-core/src/system/thread.rs +++ b/crates/infinity-agent-core/src/system/thread.rs @@ -7,6 +7,7 @@ use std::collections::{HashMap, HashSet}; use std::rc::Rc; use futures_util::StreamExt; +use futures_util::stream::FuturesUnordered; use infinity_provider_protocol::message::{ToolResultContent, UserContent}; use infinity_provider_protocol::{ToolDefinition, Usage}; use tokio::sync::oneshot; @@ -407,13 +408,16 @@ where /// Execute one step over a batch that has **not** been run through the /// deferral policy: prepare `inputs` into history, run at most one - /// completion round, commit durably, and dispatch at most one - /// asynchronous tool call. Callers are expected to apply + /// completion round, commit durably, and dispatch the asynchronous tool + /// call (if any). Callers are expected to apply /// [`filter_deferrable`](Self::filter_deferrable) first. /// - /// Events are delivered to `observer` synchronously as they occur; the - /// turn is synced to the conversation store before the tool call (if - /// any) is dispatched. + /// Events are delivered to `observer` synchronously as they occur. A tool + /// call is dispatched *eagerly*, as soon as the completion stream yields + /// it (the stream has synced the call to the conversation store by then), + /// rather than after the model's stream has fully ended; the dispatch + /// runs concurrently with draining the rest of the stream, and the step + /// does not return until it has completed. /// /// `cancel` aborts the completion stream early (user interruption). The /// cancelled step still flushes and commits whatever streamed before the @@ -519,7 +523,6 @@ where observer.on_event(&thread_id, &AgentEvent::CompletionStarted); self.in_flight.set(true); - let mut action = None; let mut usage: Option = None; { let mut stream = std::pin::pin!(event_processor::run_completion( @@ -535,69 +538,86 @@ where cancel, )); - while let Some(ev) = stream.next().await { - match ev { - Ok(event) => self.handle_completion_event( - event, - observer, - &thread_id, - &mut action, - &mut usage, - ), - Err(e) => { - observer.on_event( - &thread_id, - &AgentEvent::Info { - text: format!("Error: {}", e), - }, - ); - break; + // ── Eager dispatch: a tool call is fired the moment the stream + // yields it, while the model's tail (the `Final` chunk carrying + // usage, plus any ignored post-call content) is still being + // drained. `run_completion` has already synced the call to the + // store before yielding it, so the durability barrier holds. A + // failed dispatch enqueues an error tool result so the agent + // recovers instead of waiting forever. The set is drained before + // the step returns, so a step never leaves a dispatch in flight. + // (A set rather than a single slot so that, once the stream + // yields several calls per turn, they all dispatch eagerly.) ── + let mut dispatches = FuturesUnordered::new(); + let mut stream_done = false; + loop { + tokio::select! { + ev = stream.next(), if !stream_done => match ev { + Some(Ok(event)) => { + if let Some(action) = self.handle_completion_event( + event, + observer, + &thread_id, + &mut usage, + ) { + dispatches.push( + event_processor::execute_action_with_error_result( + action, + &tool_registry, + &tool_context, + ), + ); + } + } + Some(Err(e)) => { + observer.on_event( + &thread_id, + &AgentEvent::Info { + text: format!("Error: {}", e), + }, + ); + stream_done = true; + } + None => stream_done = true, + }, + Some(res) = dispatches.next(), if !dispatches.is_empty() => { + if let Err(e) = res { + observer.on_event( + &thread_id, + &AgentEvent::Info { + text: format!("Error: {}", e), + }, + ); + } } + else => break, } } } self.in_flight.set(false); *self.current_thinking.borrow_mut() = None; - // ── Commit phase: the turn becomes durable before anything external - // can react to it. ── + // ── Commit phase: anything the round left pending (a text-only turn, + // or the tail of a tool-call turn) becomes durable before the round + // is reported finished. ── self.history.sync().await?; observer.on_event(&thread_id, &AgentEvent::CompletionFinished { usage }); - // ── Dispatch phase: fire the tool call (if any) after the commit - // barrier, so the call is durable in history before its result can - // possibly arrive. A failed dispatch enqueues an error tool result - // so the agent recovers instead of waiting forever. ── - if let Some(action) = action - && let Err(e) = event_processor::execute_action_with_error_result( - action, - &tool_registry, - &tool_context, - ) - .await - { - observer.on_event( - &thread_id, - &AgentEvent::Info { - text: format!("Error: {}", e), - }, - ); - } - Ok(StepOutcome::Completed { usage, context_window: model.context_window, }) } + /// Translate one completion event into observer events and local state. + /// Returns the action to dispatch, if the event carried one. fn handle_completion_event( &self, event: CompletionEvent, observer: &impl ThreadObserver, thread_id: &ThreadId, - action: &mut Option, usage: &mut Option, - ) { + ) -> Option { match event { CompletionEvent::Info(text) => { observer.on_event(thread_id, &AgentEvent::Info { text }); @@ -655,33 +675,130 @@ where *usage = Some(u); } } - CompletionEvent::Action(a) => { - if let CompletionAction::ExecuteToolCall { - ref tool_name, - ref tool_args, - ref display_as, + CompletionEvent::Action(action @ CompletionAction::ExecuteToolCall { .. }) => { + let CompletionAction::ExecuteToolCall { + tool_name, + tool_args, + display_as, .. - } = a - { - *self.current_thinking.borrow_mut() = None; - observer.on_event( - thread_id, - &AgentEvent::ToolCall { - name: tool_name.clone(), - args: tool_args.clone(), - display_as: display_as.clone(), - }, - ); - } - assert!(action.is_none(), "bug: multiple terminal actions"); - *action = Some(a); + } = &action + else { + unreachable!("bug: matched ExecuteToolCall above") + }; + *self.current_thinking.borrow_mut() = None; + observer.on_event( + thread_id, + &AgentEvent::ToolCall { + name: tool_name.clone(), + args: tool_args.clone(), + display_as: display_as.clone(), + }, + ); + return Some(action); } } + None } } #[cfg(test)] mod tests { + use crate::message::InfinityMessage; + use crate::system::local::ChannelSender; use crate::system::test_support::*; + use crate::tools::{Tool, ToolContext}; + use async_trait::async_trait; + use tokio::sync::mpsc; + + /// An async tool that reports (on a channel) the moment its dispatch + /// runs, so a test can observe *when* the runtime fired it. + struct NotifyingTool { + tx: mpsc::UnboundedSender<()>, + } + + #[async_trait] + impl Tool for NotifyingTool { + fn name(&self) -> &str { + "notifying_tool" + } + fn description(&self) -> &str { + "notifies on dispatch" + } + fn parameters(&self) -> serde_json::Value { + serde_json::json!({"type":"object","properties":{}}) + } + async fn execute( + &self, + _: serde_json::Value, + _: rap_protocol::ToolCallId, + _: Option, + _: &ToolContext, + ) -> Result<(), Box> { + self.tx.send(()).expect("test receiver alive"); + Ok(()) + } + } + + /// A tool call is dispatched as soon as the model emits it, not once the + /// model's stream has ended, and the call is already durable in the store + /// at that point. + #[tokio::test(flavor = "current_thread")] + async fn tool_call_dispatches_before_stream_finishes() { + let local = tokio::task::LocalSet::new(); + local + .run_until(async { + let (dispatched_tx, mut dispatched_rx) = mpsc::unbounded_channel(); + let (mut running, mut rx, mut ctrl, conv) = start_system( + vec![Box::new(NotifyingTool { tx: dispatched_tx })], + None, + ); + let thread_id = rap_protocol::ThreadId::from_ref("t1"); + running.send_user_text(thread_id, "use tool").await; + let _req = ctrl.next_request().await; + + // Emit the tool call but keep the model stream open: no + // `Final` chunk yet. + ctrl.send_tool_call("call-1", "notifying_tool", serde_json::json!({})); + + tokio::time::timeout(std::time::Duration::from_secs(5), dispatched_rx.recv()) + .await + .expect("tool must be dispatched while the model stream is still open") + .expect("dispatch channel closed"); + + // The durability barrier held: the call reached the store + // before the tool ran. + let stored = conv.thread_messages(thread_id).unwrap_or_default(); + assert!( + stored + .iter() + .any(|(m, _)| matches!(m, InfinityMessage::ToolCall { call, .. } if call.id == "call-1")), + "tool call must be persisted before dispatch; stored: {}", + stored.len() + ); + + // The round is not reported finished until the stream ends. + let mut finished_events = 0; + while let Ok(ev) = rx.try_recv() { + if let Evt::E(crate::system::events::AgentEvent::CompletionFinished { .. }) = ev { + finished_events += 1; + } + } + assert_eq!(finished_events, 0, "round must still be in progress"); + + ctrl.finish(); + collect_until_finished(&mut rx).await; + + // Settle the call so the thread can idle out. + running + .send(tool_result_input("t1", "call-1", "tool done").0, "res-1") + .await; + let _req2 = ctrl.next_request().await; + ctrl.send_text("all done"); + ctrl.finish(); + collect_until_finished(&mut rx).await; + wait_idle(&mut running).await; + }) + .await; + } /// A tool call whose dispatch fails must feed an error result back to the /// agent (as a new input through the loopback queue) instead of leaving the diff --git a/docs/docs/infinity-runtime/architecture.md b/docs/docs/infinity-runtime/architecture.md index 002cc5f0..0817fc7b 100644 --- a/docs/docs/infinity-runtime/architecture.md +++ b/docs/docs/infinity-runtime/architecture.md @@ -67,7 +67,7 @@ Unknown tool names take the same loop-back path with an injected error result, s ## Turns and durability -Streaming output is buffered in a **turn buffer** and is only committed when the turn completes, either because the model finishes without a tool call or because a tool call ends the turn. If the stream errors mid-turn, the buffer is discarded and the completion retries, so half-streamed assistant messages will never reach storage. When a tool call ends a turn, the runtime flushes the buffer *before* dispatching the invocation, which guarantees that the call is durable in history before its result can possibly arrive. +Streaming output is buffered in a **turn buffer** and is only committed when the turn completes, either because the model finishes without a tool call or because a tool call ends the turn. If the stream errors mid-turn, the buffer is discarded and the completion retries, so half-streamed assistant messages will never reach storage. When a tool call ends a turn, the runtime flushes the buffer and syncs it to the store *before* dispatching the invocation, which guarantees that the call is durable in history before its result can possibly arrive. The dispatch itself is eager: it fires as soon as the call has been persisted, without waiting for the model's stream to end (the provider may still be delivering its final usage chunk, or further concurrent tool calls), so the tool's latency overlaps the stream's tail instead of adding to it. Durability alone is not enough, because queues redeliver. Every input message and completion carries a stable ID, and the `StateStore` tracks which IDs each thread has already processed. A redelivered message will be recognized in `prepare_input` and skipped, which makes slices effectively idempotent on top of at-least-once delivery. diff --git a/docs/docs/infinity-runtime/low-level/completion-loop.md b/docs/docs/infinity-runtime/low-level/completion-loop.md index 860b7735..85524690 100644 --- a/docs/docs/infinity-runtime/low-level/completion-loop.md +++ b/docs/docs/infinity-runtime/low-level/completion-loop.md @@ -35,7 +35,7 @@ Many messages will end at this phase, so a slice only pays for a model call when ## `run_completion`: Stream the Model `run_completion` returns a `Stream` of `CompletionEvent`s: text chunks, reasoning start/stop/chunks, synchronous tool calls and their results, informational messages, and finally a terminal `Action`. It takes the provider, the model ID and whether that model accepts image input, the [`HistoryManager`](./history-manager.md), the tool definitions, registry, and context, the thread and message IDs, an optional extra system prompt, and a `oneshot::Receiver<()>` cancellation handle. Dropping or firing the sender will abort the stream, which is how interruption is implemented. -As the stream runs, it buffers the turn into the history manager (`handle_completion`) and flushes at turn boundaries. Provider failures are handled according to the [`ErrorClass`](../model-providers.md#writing-a-provider) the provider attached to them: `Transient` errors are retried after a short delay and `Throttled` errors after a longer backoff, both from clean committed history and up to a fixed retry limit, while `Fatal` errors end the stream. A `ContextOverflow` triggers recovery instead of a plain retry: if the only new input is a single tool result or subscription event, its body is replaced with a placeholder and the completion is retried; otherwise the new user input is dropped (and any pending tool results are settled as interrupted) and the stream ends, so that an oversized message can never wedge the thread. The runtime applies no timeouts of its own; stall detection, if any, belongs to the provider. Tools that opt into synchronous execution (`Tool::execute_synchronous`) are invoked inline, and their results loop back into the completion without ending the slice. The stream's terminal event is a `CompletionAction`: +As the stream runs, it buffers the turn into the history manager (`handle_completion`) and flushes at turn boundaries. Provider failures are handled according to the [`ErrorClass`](../model-providers.md#writing-a-provider) the provider attached to them: `Transient` errors are retried after a short delay and `Throttled` errors after a longer backoff, both from clean committed history and up to a fixed retry limit, while `Fatal` errors end the stream. A `ContextOverflow` triggers recovery instead of a plain retry: if the only new input is a single tool result or subscription event, its body is replaced with a placeholder and the completion is retried; otherwise the new user input is dropped (and any pending tool results are settled as interrupted) and the stream ends, so that an oversized message can never wedge the thread. The runtime applies no timeouts of its own; stall detection, if any, belongs to the provider. Tools that opt into synchronous execution (`Tool::execute_synchronous`) are invoked inline, and their results loop back into the completion without ending the slice. The model's decisions surface as `CompletionAction`s: ```rust # use infinity_provider_protocol::FinalResponse; @@ -54,6 +54,8 @@ pub enum CompletionAction { } ``` +`Done` is yielded once the model's response ends (it carries the round's usage). `ExecuteToolCall` is yielded **as soon as the call is complete**, which can be well before the model's stream ends: the model may still be streaming its tail (the final chunk with usage, or further concurrent tool calls, which the runtime currently ignores). Before yielding it, `run_completion` flushes the turn and syncs the history, so the yielded call is already durable and may be dispatched immediately. The stream itself is the queue of actions: a consumer that wants minimum latency polls the stream and the in-flight dispatches concurrently (for example with a `select!` over the stream and a `FuturesUnordered` of dispatches), which is what the agent system's step does. + ## `execute_action`: Dispatch and Stop ```rust # use std::collections::HashMap; @@ -70,9 +72,9 @@ pub async fn execute_action( # { unimplemented!() } ``` -For `Done`, this is a no-op. For `ExecuteToolCall`, it calls the tool's `execute`, which dispatches the invocation (typically an HTTP POST to a RAP tool server) and returns without waiting for a result. **You must call this only after `history.sync()` has persisted the turn.** Because the turn is durable before the dispatch, a crash between persist and dispatch is recoverable: the persisted history already contains the tool call, so the eventual result message has something to attach to. The result will arrive later as a new `InputMessage` through your `InputSender`, which starts the next slice. +For `Done`, this is a no-op. For `ExecuteToolCall`, it calls the tool's `execute`, which dispatches the invocation (typically an HTTP POST to a RAP tool server) and returns without waiting for a result. **The tool call must be persisted before it is dispatched.** `run_completion` guarantees this for the actions it yields (it syncs before yielding `ExecuteToolCall`), so you may call `execute_action` the moment the action arrives, while you continue draining the stream. Because the call is durable before the dispatch, a crash between persist and dispatch is recoverable: the persisted history already contains the tool call, so the eventual result message has something to attach to. The result will arrive later as a new `InputMessage` through your `InputSender`, which starts the next slice. ## Composing a Slice -A full slice strings the three functions together: it prepares every message in the batch, runs one completion if anything was actionable, syncs the history, and dispatches the resulting tool call. This composition is deliberately not a separate low-level entry point. The ordering between its phases carries the runtime's durability guarantees (the turn must be synced before the tool call goes out, and observers must see events at defined moments), so the composed slice lives in one place: the agent system's step pipeline. [`AgentSystem::step`](../agent-systems/step-mode.md) is that composition for platform-driven batches, and [`LocalAgentSystem::start`](../agent-systems/running-locally.md) wraps the same pipeline in a per-thread driver that adds batching, interruption, deferral while a tool call is pending, idle teardown, and auto-compaction. +A full slice strings the three functions together: it prepares every message in the batch, runs one completion if anything was actionable, dispatches each tool call as the stream yields it, and syncs the history once the stream ends. This composition is deliberately not a separate low-level entry point. The ordering between its phases carries the runtime's durability guarantees (a tool call must be synced before it goes out, and observers must see events at defined moments), so the composed slice lives in one place: the agent system's step pipeline. [`AgentSystem::step`](../agent-systems/step-mode.md) is that composition for platform-driven batches, and [`LocalAgentSystem::start`](../agent-systems/running-locally.md) wraps the same pipeline in a per-thread driver that adds batching, interruption, deferral while a tool call is pending, idle teardown, and auto-compaction. -You should reach for the individual functions when you are building something that those layers cannot express, such as a custom scheduler that interleaves preparation and completion differently, a replay tool that runs `prepare_input` without ever completing, or a new platform binding with its own notion of a batch. If you compose them yourself, you must preserve the ordering contract: `history.sync()` always comes before `execute_action`. At the system layer, events reach your application through the [`ThreadObserver`](../agent-systems/observers.md); at this level, you observe the `CompletionEvent` stream from `run_completion` directly. +You should reach for the individual functions when you are building something that those layers cannot express, such as a custom scheduler that interleaves preparation and completion differently, a replay tool that runs `prepare_input` without ever completing, or a new platform binding with its own notion of a batch. If you compose them yourself, you must preserve the ordering contract: a tool call is synced before `execute_action` dispatches it (which `run_completion` does for you), and the slice does not end while a dispatch is still in flight. At the system layer, events reach your application through the [`ThreadObserver`](../agent-systems/observers.md); at this level, you observe the `CompletionEvent` stream from `run_completion` directly. diff --git a/docs/docs/infinity-runtime/low-level/history-manager.md b/docs/docs/infinity-runtime/low-level/history-manager.md index b86fdf90..77f22fad 100644 --- a/docs/docs/infinity-runtime/low-level/history-manager.md +++ b/docs/docs/infinity-runtime/low-level/history-manager.md @@ -70,7 +70,7 @@ history.sync().await?; 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. +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. `run_completion` enforces this itself: it flushes the turn and calls `sync` *before* yielding an `ExecuteToolCall`, so the action is durable by the time a consumer sees it and can be dispatched right away, while the model's stream is still being drained. If you drive [`execute_action`](./completion-loop.md) yourself with calls that did not come through `run_completion`, you must preserve the same ordering. ## Compaction and Threading Helpers The manager also carries the state for the runtime's [threading](../built-in/threading.md) and compaction features. A custom driving loop will need to interact with each of them at a specific moment: