diff --git a/loop/loop_test.go b/loop/loop_test.go index 1cc4c70c1..182b0869e 100644 --- a/loop/loop_test.go +++ b/loop/loop_test.go @@ -10,6 +10,7 @@ import ( "os" "os/exec" "path/filepath" + "slices" "strings" "sync" "testing" @@ -528,6 +529,42 @@ func TestInsertMissingToolResults(t *testing.T) { } } +// Synthetic results are rebuilt on every request and never stored, so they +// must come out in the same order each time; otherwise the request bytes +// change and the prompt cache misses from the interrupted turn onward. +func TestInsertMissingToolResultsIsDeterministic(t *testing.T) { + ids := []string{"tool_1", "tool_2", "tool_3", "tool_4", "tool_5", "tool_6"} + assistant := llm.Message{Role: llm.MessageRoleAssistant} + for _, id := range ids { + assistant.Content = append(assistant.Content, llm.Content{Type: llm.ContentTypeToolUse, ID: id, ToolName: "bash"}) + } + answered := llm.Content{Type: llm.ContentTypeToolResult, ToolUseID: "tool_3"} + user := llm.Message{Role: llm.MessageRoleUser, Content: []llm.Content{answered, {Type: llm.ContentTypeText, Text: "stop"}}} + + want := []string{"tool_1", "tool_2", "tool_4", "tool_5", "tool_6", "tool_3"} + for range 50 { + req := &llm.Request{Messages: []llm.Message{assistant, user}} + (&RunConfig{Logger: slog.Default()}).insertMissingToolResults(req) + var got []string + for _, c := range req.Messages[1].Content { + if c.Type == llm.ContentTypeToolResult { + got = append(got, c.ToolUseID) + } + } + if !slices.Equal(got, want) { + t.Fatalf("tool_result order = %v, want %v", got, want) + } + } + + // A repeated tool_use ID still gets a single synthetic result. + assistant.Content = append(assistant.Content, assistant.Content[0]) + req := &llm.Request{Messages: []llm.Message{assistant, user}} + (&RunConfig{Logger: slog.Default()}).insertMissingToolResults(req) + if n := len(req.Messages[1].Content); n != len(want)+1 { + t.Fatalf("got %d content items with a repeated tool_use ID, want %d", n, len(want)+1) + } +} + func TestInsertMissingToolResultsWithEdgeCases(t *testing.T) { // Test for the bug: when an assistant error message is recorded after a tool_use // but before tool execution, the tool_use is "hidden" from insertMissingToolResults diff --git a/loop/run.go b/loop/run.go index 9bde837dd..c90227ce6 100644 --- a/loop/run.go +++ b/loop/run.go @@ -963,8 +963,11 @@ func (l *RunConfig) insertMissingToolResults(req *llm.Request) { totalInserted := 0 totalRemoved := 0 - // Track the tool_use IDs from the most recent assistant message + // Track the tool_use IDs from the most recent assistant message, and their + // order: synthetic results must come out the same way on every request, or + // the prompt cache misses from this point on. var prevAssistantToolUseIDs map[string]bool + var prevAssistantToolUseOrder []string for i := 0; i < len(req.Messages); i++ { msg := req.Messages[i] @@ -982,9 +985,11 @@ func (l *RunConfig) insertMissingToolResults(req *llm.Request) { // Track all tool_use IDs in this assistant message prevAssistantToolUseIDs = make(map[string]bool) + prevAssistantToolUseOrder = nil for _, c := range msg.Content { - if c.Type == llm.ContentTypeToolUse { + if c.Type == llm.ContentTypeToolUse && !prevAssistantToolUseIDs[c.ID] { prevAssistantToolUseIDs[c.ID] = true + prevAssistantToolUseOrder = append(prevAssistantToolUseOrder, c.ID) } } newMessages = append(newMessages, msg) @@ -1054,7 +1059,7 @@ func (l *RunConfig) insertMissingToolResults(req *llm.Request) { // Check if we need to add missing tool_results for this user message if prevAssistantToolUseIDs != nil { var prefix []llm.Content - for toolUseID := range prevAssistantToolUseIDs { + for _, toolUseID := range prevAssistantToolUseOrder { if !existingResultIDs[toolUseID] { prefix = append(prefix, llm.Content{ Type: llm.ContentTypeToolResult, @@ -1084,6 +1089,7 @@ func (l *RunConfig) insertMissingToolResults(req *llm.Request) { // Reset for next iteration - user message "consumes" the previous tool_uses prevAssistantToolUseIDs = nil + prevAssistantToolUseOrder = nil } else { newMessages = append(newMessages, msg) }