From 30fbb5ce4a5363000e913d89a96fa2ffe866eca5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A9o=20Monnom?= Date: Wed, 18 Nov 2026 09:50:30 -0800 Subject: [PATCH] text: a tool lost with its worker settles as an internal error, read-back failures are logged, e2e tests follow the binding and routing contract --- .../livekit/agents/voice/agent_run.py | 14 ++- .../src/session/machine/machine_tests.rs | 43 +++++++++ .../lk-agents-core/src/session/machine/mod.rs | 4 +- rust/crates/lk-agents-core/src/session/mod.rs | 6 +- .../lk-agents-core/src/session/routing.rs | 95 ++++++++++++++++--- .../src/text_session/runner.rs | 11 +++ tests/e2e/test_text.py | 18 +++- tests/e2e/text_worker.py | 22 ++++- tests/host/test_callbacks.py | 24 +++++ 9 files changed, 209 insertions(+), 28 deletions(-) diff --git a/python/livekit-agents/livekit/agents/voice/agent_run.py b/python/livekit-agents/livekit/agents/voice/agent_run.py index afa741260a..3605e08b66 100644 --- a/python/livekit-agents/livekit/agents/voice/agent_run.py +++ b/python/livekit-agents/livekit/agents/voice/agent_run.py @@ -373,9 +373,17 @@ def prepare_arguments( async def render_read_back(prepared: _Prepared) -> ReadBackAnswer: assert isinstance(prepared.tool, FunctionTool) and prepared.tool.info.read_back - question = prepared.tool.info.read_back(*prepared.args, **prepared.kwargs) - if inspect.isawaitable(question): - question = await question + try: + question = prepared.tool.info.read_back(*prepared.args, **prepared.kwargs) + if inspect.isawaitable(question): + question = await question + except Exception: + # the call settles as an internal error; the cause is only visible here + logger.exception( + "exception occurred while rendering a tool's read-back", + extra={"function": prepared.tool.info.name}, + ) + raise if isinstance(question, InputRequired): return ReadBackAnswerInputRequired(question=question.question, verbatim=question.verbatim) return ReadBackAnswerQuestion(question=str(question)) diff --git a/rust/crates/lk-agents-core/src/session/machine/machine_tests.rs b/rust/crates/lk-agents-core/src/session/machine/machine_tests.rs index 39eb2efdbe..45df1fa7bd 100644 --- a/rust/crates/lk-agents-core/src/session/machine/machine_tests.rs +++ b/rust/crates/lk-agents-core/src/session/machine/machine_tests.rs @@ -1194,3 +1194,46 @@ fn late_prepared_arguments_are_released_even_after_the_session_settles() { #[path = "remote_resume_tests.rs"] mod remote_resume; + +// Catches: a worker that died inside a local tool leaving the conversation unusable, every +// later request refused with "an admitted tool has no recorded result". +#[test] +fn a_tool_lost_with_its_worker_settles_as_an_internal_error_and_the_conversation_continues() { + let mut cfg = config(false, ChatHistory::Fresh, false); + cfg.agents.get_mut("desk").unwrap().agent_tools.clear(); // `book` is a plain local tool + let mut first = Driver::new(cfg.clone(), None, "hello"); + first.reply("Hi.", &[]); + let mut state = first.turn().state; + // What the killed worker checkpointed: the admitted call, never its result. + let call = lk_agents_abi::FunctionCall { + id: "item_book".into(), + call_id: "call_book".into(), + name: "book".into(), + arguments: json!({"nights": 2}).to_string(), + created_at: std::time::UNIX_EPOCH, + extra: Default::default(), + group_id: None, + }; + let root = state.root_frame_id.clone(); + state.frames.get_mut(&root).unwrap().history.push(call.clone().into()); + + let next = Driver::new(cfg, Some(state), "are you there?"); + + assert_eq!( + next.session.lost_tools, + [LostTool { + agent_name: "desk".into(), + tool_name: "book".into(), + call_id: "call_book".into() + }] + ); + let (_, chat_ctx) = next.request(); + let at = chat_ctx.items.iter().position(|item| item.id() == call.id).unwrap(); + let ChatItem::FunctionCallOutput(output) = &chat_ctx.items[at + 1] else { + panic!("the lost call is settled right after itself: {:?}", chat_ctx.items) + }; + assert_eq!( + (output.call_id.as_str(), output.output.as_str(), output.is_error), + ("call_book", lk_agents_abi::llm::tool_executor::INTERNAL_ERROR_OUTPUT, true) + ); +} diff --git a/rust/crates/lk-agents-core/src/session/machine/mod.rs b/rust/crates/lk-agents-core/src/session/machine/mod.rs index 62aea50444..5746067c4b 100644 --- a/rust/crates/lk-agents-core/src/session/machine/mod.rs +++ b/rust/crates/lk-agents-core/src/session/machine/mod.rs @@ -13,7 +13,7 @@ pub(super) mod tool_output; impl Session { pub fn new(config: SessionConfig, input: SessionInput) -> Result { config.validate()?; - let state = match input.state { + let mut state = match input.state { Some(mut state) => { if state.session_id != input.session_id { return Err(RoutingError::InvalidState("session identity changed".into())); @@ -58,8 +58,10 @@ impl Session { config.root_agent.clone(), ), }; + let lost_tools = config.settle_lost_tools(&mut state); config.validate_state(&state)?; Ok(Self { + lost_tools, failure_input_requirements: Vec::new(), tool_outputs: BTreeMap::new(), config, diff --git a/rust/crates/lk-agents-core/src/session/mod.rs b/rust/crates/lk-agents-core/src/session/mod.rs index 2f4d8fe3e5..558a8c8152 100644 --- a/rust/crates/lk-agents-core/src/session/mod.rs +++ b/rust/crates/lk-agents-core/src/session/mod.rs @@ -33,7 +33,9 @@ pub use lk_agents_abi::text_session::{ ChildCallStatus, FrameId, ParentCall, PendingChildCall, SessionFrame, SessionSnapshot, TextSessionError, TextSessionTurn, }; -pub use routing::{ChatHistory, LocalAgentTool, RoutingError, SessionAgent, SessionConfig}; +pub use routing::{ + ChatHistory, LocalAgentTool, LostTool, RoutingError, SessionAgent, SessionConfig, +}; // Checkpoints describe accepted progress; running invocation resources are never serialized. @@ -176,6 +178,8 @@ impl Phase { } pub struct Session { + /// Tools the restored conversation settled as internal errors; the host reports them. + pub lost_tools: Vec, failure_input_requirements: Vec, tool_outputs: BTreeMap<(String, crate::agent_run::ToolOutputId), machine::tool_output::Pending>, config: SessionConfig, diff --git a/rust/crates/lk-agents-core/src/session/routing.rs b/rust/crates/lk-agents-core/src/session/routing.rs index b9a6125f1e..5f6071e234 100644 --- a/rust/crates/lk-agents-core/src/session/routing.rs +++ b/rust/crates/lk-agents-core/src/session/routing.rs @@ -7,6 +7,15 @@ use super::{ChildCallStatus, SessionSnapshot}; pub use lk_agents_abi::text_session::{ChatHistory, LocalAgentTool, RoutingError}; +/// A tool a restored conversation settled as an internal error: it was running when its +/// process stopped, so its outcome is unknown. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LostTool { + pub agent_name: String, + pub tool_name: String, + pub call_id: String, +} + #[derive(Debug, Clone)] pub struct SessionAgent { pub definition: AgentDefinition, @@ -75,6 +84,77 @@ impl SessionConfig { Ok(()) } + /// An admitted local tool whose result was never recorded and that nothing else settles: + /// its process stopped while it ran (the partition was taken over), so it never will be. + fn lost( + &self, + state: &SessionSnapshot, + frame: &super::SessionFrame, + call: &lk_agents_abi::FunctionCall, + ) -> bool { + let completed = frame.history.iter().any(|item| { + matches!(item, + lk_agents_abi::ChatItem::FunctionCallOutput(output) if output.id == call.output_id()) + }); + let local_child = self.agents[&frame.agent_name].agent_tools.contains_key(&call.name); + let remote_origin = frame.completed + && frame.parent.is_some() + && state.remote_agents.values().any(|remote| { + remote.requests.values().any(|request| { + request.origin.as_ref().is_some_and(|origin| { + origin.agent_id == frame.id.value && origin.call_id == call.id + }) + }) + }); + !crate::tool_calls::provisional(call) && !completed && !local_child && !remote_origin + } + + /// Settles each lost tool of a restored conversation as an internal error, right after its + /// call, so the conversation can continue. Its outcome is unknown (it may have taken + /// effect); the framework never runs it again. Returns them for the host to report. + pub(super) fn settle_lost_tools(&self, state: &mut SessionSnapshot) -> Vec { + let mut lost = Vec::new(); + let ids: Vec<_> = state.frames.keys().cloned().collect(); + for id in ids { + let frame = &state.frames[&id]; + if !self.agents.contains_key(&frame.agent_name) { + continue; // validate_state reports the unknown agent + } + let calls: Vec<_> = frame + .history + .iter() + .enumerate() + .filter_map(|(at, item)| match item { + lk_agents_abi::ChatItem::FunctionCall(call) + if self.lost(state, frame, call) => + { + Some((at, call.clone())) + } + _ => None, + }) + .collect(); + let agent_name = frame.agent_name.clone(); + let history = &mut state.frames.get_mut(&id).expect("listed above").history; + for (at, call) in calls.into_iter().rev() { + let mut output = lk_agents_abi::FunctionCallOutput::new( + call.output_id(), + call.call_id.clone(), + lk_agents_abi::llm::tool_executor::INTERNAL_ERROR_OUTPUT, + true, + call.created_at, + ); + output.name = call.name.clone(); + history.insert(at + 1, output.into()); + lost.push(LostTool { + agent_name: agent_name.clone(), + tool_name: call.name, + call_id: call.call_id, + }); + } + } + lost + } + pub(super) fn validate_state(&self, state: &SessionSnapshot) -> Result<(), RoutingError> { let invalid = |reason: &str| RoutingError::InvalidState(reason.into()); for (id, remote) in &state.remote_agents { @@ -164,20 +244,7 @@ impl SessionConfig { "a live local tool has no final outcome; its progress cannot be resumed", )); } - let completed = frame.history.iter().any(|item| matches!(item, - lk_agents_abi::ChatItem::FunctionCallOutput(output) if output.id == call.output_id())); - let local_child = - self.agents[&frame.agent_name].agent_tools.contains_key(&call.name); - let remote_origin = frame.completed - && frame.parent.is_some() - && state.remote_agents.values().any(|remote| { - remote.requests.values().any(|request| { - request.origin.as_ref().is_some_and(|origin| { - origin.agent_id == frame.id.value && origin.call_id == call.id - }) - }) - }); - if !completed && !local_child && !remote_origin { + if self.lost(state, frame, call) { return Err(invalid( "an admitted tool has no recorded result; reconcile its outcome before resuming", )); diff --git a/rust/crates/lk-agents-runtime/src/text_session/runner.rs b/rust/crates/lk-agents-runtime/src/text_session/runner.rs index 5d531a1f7d..47d561b164 100644 --- a/rust/crates/lk-agents-runtime/src/text_session/runner.rs +++ b/rust/crates/lk-agents-runtime/src/text_session/runner.rs @@ -416,6 +416,17 @@ fn start( ) .map_err(|e| Invalid(e.to_string()))? .with_checkpoints(); + for lost in std::mem::take(&mut session.lost_tools) { + log::warn!( + target: lk_agents_abi::LOG_TARGET, + "tool `{}` (call {}) of agent `{}` was running when its worker stopped; its outcome \ + is unknown (it may have taken effect), it is recorded as an internal error and is \ + not run again", + lost.tool_name, + lost.call_id, + lost.agent_name, + ); + } if request.session_sink.is_some() { session = session.with_persistence(); } diff --git a/tests/e2e/test_text.py b/tests/e2e/test_text.py index d327c68e22..c53fbd6ede 100644 --- a/tests/e2e/test_text.py +++ b/tests/e2e/test_text.py @@ -39,7 +39,7 @@ INPUT_REQUIRED = pb.TaskState.TASK_STATE_INPUT_REQUIRED async def said(thread: str) -> list[str | None]: """The thread's persisted message texts.""" - history = await Thread(AgentDBStorage(), thread, partition_key="e2e").chat_history() + history = await Thread(AgentDBStorage(), thread).chat_history() return [item.text_content for item in history.items if item.type == "message"] @@ -75,7 +75,8 @@ async def test_a_resent_message_returns_its_task_without_running_again( async def test_an_answer_to_a_question_asked_on_one_worker_is_delivered_on_another( workers: Workers, thread: str ) -> None: - """A asks for an email; B delivers the reply as the pending tool's output, once.""" + """A asks for an email; B recognizes the reply as its answer and the agent continues, once. + The asking tool already finished: its output records the question, the reply follows it.""" asked = await workers.a.send(workers.a.message("need-email", thread)) replied = await workers.b.send(workers.b.message("alice@example.com", thread)) @@ -85,9 +86,15 @@ async def test_an_answer_to_a_question_asked_on_one_worker_is_delivered_on_anoth "Which email?", ) assert answer(replied) == "completed: alice@example.com" - history = await Thread(AgentDBStorage(), thread, partition_key="e2e").chat_history() + history = await Thread(AgentDBStorage(), thread).chat_history() outputs = [item.output for item in history.items if item.type == "function_call_output"] - assert outputs == ["alice@example.com"] + assert outputs == ["waiting for the person's answer to: Which email?"] + assert await said(thread) == [ + "need-email", + "Which email?", + "alice@example.com", + "completed: alice@example.com", + ] async def test_yes_on_another_worker_books_the_read_back_terms_exactly_once( @@ -141,7 +148,8 @@ async def test_a_worker_killed_mid_turn_leaves_a_failed_task_and_the_thread_usab pb.Task(), ) assert orphan.status.state == pb.TaskState.TASK_STATE_FAILED - assert orphan.metadata[REASON] == "worker-lost" + # A failed task carries its reason on its status message. + assert orphan.status.message.metadata[REASON] == "worker-lost" assert [call for call in service.calls if call.operation == "book"] == [] diff --git a/tests/e2e/text_worker.py b/tests/e2e/text_worker.py index dd2a0e2a57..2c46a5fb2d 100644 --- a/tests/e2e/text_worker.py +++ b/tests/e2e/text_worker.py @@ -8,6 +8,7 @@ from __future__ import annotations import argparse import asyncio +import json import logging import os from datetime import timedelta @@ -16,7 +17,7 @@ import httpx from starlette.requests import Request from starlette.responses import PlainTextResponse -from livekit.agents import Agent, AgentServer, InputRequired, RunContext +from livekit.agents import Agent, AgentServer, DelegationOptions, InputRequired, RunContext from livekit.agents.a2a import A2ASessionContext from livekit.agents.llm import ChatContext from livekit.agents.storage import AgentDBStorage @@ -49,6 +50,16 @@ def answer(chat_ctx: ChatContext) -> Reply: return replies.get(text, "reply: " + text) +ANSWERS = {"yes", "no", "alice@example.com"} + + +def route(chat_ctx: ChatContext) -> Reply: + """The routing model: the scripted answers respond to the open question; nothing else does.""" + prompt = json.loads(last_input(chat_ctx) or "{}") + answers = prompt.get("latest_message") in ANSWERS and prompt.get("candidates") + return tool_call("route_input_response", candidates=[0] if answers else [], unclear=False) + + def make_app(worker: str, service_url: str, port: int) -> AgentServer: storage = AgentDBStorage( holder=worker, lease_ttl=timedelta(seconds=2), renew_interval=timedelta(seconds=0.5) @@ -78,7 +89,7 @@ def make_app(worker: str, service_url: str, port: int) -> AgentServer: """Wait for the external lookup service.""" return await service(ctx.context.model_copy(update={"operation": "wait"})) - @agent.tool(needs_approval=lambda terms: f"Book {terms}? Yes or no?") + @agent.tool(needs_approval=lambda ctx, terms: f"Book {terms}? Yes or no?") async def book(ctx: RunContext[ServiceCall], terms: str) -> str: """Book the exact quoted terms.""" return await service(ctx.context.model_copy(update={"operation": "book", "terms": terms})) @@ -101,10 +112,13 @@ def make_app(worker: str, service_url: str, port: int) -> AgentServer: terms=ctx.message.text_content or "", ) ) + # The binding continues the thread's conversation, its pending question and approval + # included; supplied history alone can neither answer nor approve. + app = ServiceCall(worker=worker, thread=ctx.thread.id, operation="") return await agent.run( ctx.message, - message_history=ctx.message_history, - context=ServiceCall(worker=worker, thread=ctx.thread.id, operation=""), + context=ctx.store.bind(app), + delegation=DelegationOptions(routing_model=FakeLLM(route)), ) server.a2a_session(endpoint="desk", description="E2E scripted desk")(handler) diff --git a/tests/host/test_callbacks.py b/tests/host/test_callbacks.py index f05674ce0d..7e8a29f7cf 100644 --- a/tests/host/test_callbacks.py +++ b/tests/host/test_callbacks.py @@ -320,6 +320,30 @@ async def test_a_read_back_function_asks_for_a_missing_detail_then_reads_back() assert asked.status == "input_required" and asked.question == "Book monday to jo@example.com?" +# Catches: a read-back that raises settling its call as an internal error with no trace of why +# (a read-back missing the tool's `ctx` parameter was invisible end to end). +async def test_a_read_back_that_raises_is_logged_and_settles_as_an_internal_error( + caplog: pytest.LogCaptureFixture, +) -> None: + def read_back(terms: str) -> str: # missing the tool's `ctx` parameter + return f"Book {terms}?" + + desk = Agent(instructions="Help.", llm=FakeLLM([tool_call("book", terms="slot-9"), "done"])) + + @desk.tool(needs_approval=read_back) + async def book(ctx: RunContext, terms: str) -> str: + """Book.""" + return "booked" + + result = await desk.run("book slot-9") + + assert result.status == "completed" + outputs = [i.output for i in result.new_messages() if i.type == "function_call_output"] + assert outputs == ["An internal error occurred"] + assert "exception occurred while rendering a tool's read-back" in caplog.text + assert "TypeError" in caplog.text + + async def test_a_python_judge_gets_the_conversation_reference_and_model() -> None: """A judge group hands each Python judge the very conversation, reference and model.""" seen: list[tuple[ChatContext, ChatContext | None, LLM | None]] = []