From b7f4cfcf4afd2be4d7f36d2d76a0c9e9fa5be329 Mon Sep 17 00:00:00 2001 From: sausheong Date: Sun, 7 Jun 2026 23:47:32 +0800 Subject: [PATCH] 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. --- runtime/runturn.go | 36 +++++++++++++++----------- runtime/runturn_test.go | 56 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 14 deletions(-) diff --git a/runtime/runturn.go b/runtime/runturn.go index cc3c43f..9fa7fe4 100644 --- a/runtime/runturn.go +++ b/runtime/runturn.go @@ -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 diff --git a/runtime/runturn_test.go b/runtime/runturn_test.go index 9fa47ee..78f5cfc 100644 --- a/runtime/runturn_test.go +++ b/runtime/runturn_test.go @@ -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") +}