refactor(runtime): serial tool dispatch in RunTurn + error/abort tests
- Drop the wasted partitionToolCalls call; RunTurn dispatches serially by design (deterministic ordering for durable replay), so loop toolCalls directly. - Fix doc-comment overclaim: RunTurn is headless and does not emit Run's trace/slog tool-result lines nor parallelize batches. - Make TurnResult.Err consistent: mid-dispatch abort now passes ctx.Err(). - Document single-active-turn invariant on turnSlice. - Add TestRunTurn_LLMError and TestRunTurn_PreCancelledContext.
This commit is contained in:
1 parent
35896d215a
commit
b7f4cfcf4a
2 files changed
+78
-14
No files matched your search
+22
-14
@@ -25,13 +25,17 @@ type TurnResult struct {
|
||||
type TurnEmit func(AgentEvent)
|
||||
|
||||
// RunTurn executes exactly one turn of the agent loop against the current
|
||||
// session and returns the entries it produced. First call of a session passes
|
||||
// the user message; continuation calls pass "".
|
||||
// session and returns the entries it produced. The first call of a session
|
||||
// passes the user message; continuation calls pass "".
|
||||
//
|
||||
// RunTurn deliberately omits compaction, knowledge-graph ingest/recall, and
|
||||
// the streaming-tool kickoff that Run performs — those concerns stay in Run.
|
||||
// It reuses the same tested helpers (assembleMessages, dispatchTool,
|
||||
// partitionToolCalls) so its per-turn behavior matches Run's.
|
||||
// RunTurn is the durable unit for a per-turn driver: each call can be wrapped
|
||||
// as a checkpointed step whose return value (TurnResult.Entries) rebuilds
|
||||
// session state on replay. It differs from Run by design: it is headless
|
||||
// (live events go only through the emit callback, never an internal channel),
|
||||
// it dispatches tool calls serially (Run parallelizes concurrency-safe
|
||||
// batches), and it does NOT perform compaction, knowledge-graph recall/ingest,
|
||||
// streaming-tool kickoff, or the trace/slog emissions that Run's emitToolResult
|
||||
// produces. Those remain Run's responsibility.
|
||||
func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.ImageContent, emit TurnEmit) (TurnResult, error) {
|
||||
if emit == nil {
|
||||
emit = func(AgentEvent) {}
|
||||
@@ -122,14 +126,15 @@ func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.Imag
|
||||
return r.turnSlice(startLen, true, "completed", lastUsage, nil), nil
|
||||
}
|
||||
|
||||
batches := partitionToolCalls(toolCalls, r.Tools)
|
||||
for _, b := range batches {
|
||||
for _, tc := range b.calls {
|
||||
result, aborted := r.dispatchTool(ctx, tc, nil)
|
||||
emit(AgentEvent{Type: EventToolResult, ToolCall: &tc, Result: &result})
|
||||
if aborted {
|
||||
return r.turnSlice(startLen, true, "aborted", lastUsage, nil), nil
|
||||
}
|
||||
// RunTurn dispatches tool calls serially by design: deterministic
|
||||
// ordering keeps durable replay simple, and parallel/concurrency-safe
|
||||
// batching deliberately stays in Run (see the doc comment). dispatchTool
|
||||
// appends the tool_call and tool_result entries to the session.
|
||||
for _, tc := range toolCalls {
|
||||
result, aborted := r.dispatchTool(ctx, tc, nil)
|
||||
emit(AgentEvent{Type: EventToolResult, ToolCall: &tc, Result: &result})
|
||||
if aborted {
|
||||
return r.turnSlice(startLen, true, "aborted", lastUsage, ctx.Err()), nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,6 +142,9 @@ func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.Imag
|
||||
}
|
||||
|
||||
// turnSlice builds a TurnResult from the entries appended since startLen.
|
||||
// It assumes a single active turn per session: the delta entries[startLen:]
|
||||
// is correct only because no other goroutine appends to this session
|
||||
// concurrently during the turn.
|
||||
func (r *Runtime) turnSlice(startLen int, done bool, reason string, usage *llm.Usage, err error) TurnResult {
|
||||
all := r.Session.Entries()
|
||||
var delta []session.SessionEntry
|
||||
|
||||
@@ -107,3 +107,59 @@ func TestRunTurn_ToolCall_NotDone_ThenDone(t *testing.T) {
|
||||
require.True(t, res2.Done, "second turn (no tool calls) should be terminal")
|
||||
require.Equal(t, "completed", res2.StopReason)
|
||||
}
|
||||
|
||||
// TestRunTurn_LLMError: the provider emits a mid-stream EventError. RunTurn
|
||||
// does NOT use Run's stream-fallback path, so the error surfaces directly:
|
||||
// the turn is terminal with StopReason "error" and a non-nil Err.
|
||||
//
|
||||
// Note on the fake: scriptedStreamLLM's scriptedStreamEvent cannot carry an
|
||||
// error value (it has no error field), so it cannot emit a meaningful
|
||||
// EventError. We reuse streamingOnlyProvider from streamfallback_test.go —
|
||||
// the same-package fake the streaming tests use to simulate a mid-stream
|
||||
// error (text delta then EventError with a real error).
|
||||
func TestRunTurn_LLMError(t *testing.T) {
|
||||
llmProvider := &streamingOnlyProvider{}
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: llmProvider,
|
||||
Tools: newEchoRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "test",
|
||||
}
|
||||
|
||||
res, err := rt.RunTurn(context.Background(), "do it", nil, nil)
|
||||
require.NoError(t, err, "RunTurn surfaces stream errors via TurnResult.Err, not its own error return")
|
||||
require.True(t, res.Done, "an errored turn must be terminal")
|
||||
require.Equal(t, "error", res.StopReason)
|
||||
require.Error(t, res.Err)
|
||||
require.EqualValues(t, 1, llmProvider.streamCalls.Load(), "stream hit exactly once (no fallback in RunTurn)")
|
||||
}
|
||||
|
||||
// TestRunTurn_PreCancelledContext: a context cancelled before RunTurn runs
|
||||
// must short-circuit to an aborted turn with a non-nil Err, and the LLM must
|
||||
// never be called. scriptedStreamLLM exposes a `calls` counter, so we assert
|
||||
// the provider was never invoked.
|
||||
func TestRunTurn_PreCancelledContext(t *testing.T) {
|
||||
llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{
|
||||
{typ: llm.EventTextDelta, text: "should never run"},
|
||||
{typ: llm.EventDone},
|
||||
}}
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: llmProvider,
|
||||
Tools: newEchoRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "test",
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
res, err := rt.RunTurn(ctx, "hi", nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "aborted", res.StopReason)
|
||||
require.Error(t, res.Err)
|
||||
require.EqualValues(t, 0, llmProvider.calls.Load(), "LLM must not be called when context is pre-cancelled")
|
||||
}
|
||||
Reference in new issue
Block a user