Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 25 additions & 23 deletions backend/internal/service/openai_responses_input_compat.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,60 +34,62 @@ func sanitizeOpenAIResponsesOrphanToolOutputs(reqBody map[string]any, input []an
return false
}

toolCallIDs := make(map[string]struct{}, len(input))
referenceIDs := make(map[string]struct{}, len(input))
// In a paired history, only one of each two items provides a context ID.
contextIDs := make(map[string]struct{}, len(input)/2)
for _, rawItem := range input {
item, ok := rawItem.(map[string]any)
if !ok {
continue
}
itemType := strings.TrimSpace(firstNonEmptyString(item["type"]))
itemType := firstNonEmptyString(item["type"])
if itemType == "item_reference" {
if id := strings.TrimSpace(firstNonEmptyString(item["id"])); id != "" {
referenceIDs[id] = struct{}{}
if id := firstNonEmptyString(item["id"]); id != "" {
contextIDs[id] = struct{}{}
}
continue
}
if !isCodexToolCallContextItemType(itemType) {
continue
}
if id := strings.TrimSpace(firstNonEmptyString(item["call_id"], item["id"])); id != "" {
toolCallIDs[id] = struct{}{}
if id := firstNonEmptyString(item["call_id"], item["id"]); id != "" {
contextIDs[id] = struct{}{}
}
}

modified := false
normalized := make([]any, 0, len(input))
for _, rawItem := range input {
var normalized []any
keepFrom := 0
for i, rawItem := range input {
item, ok := rawItem.(map[string]any)
if !ok || !isCodexToolCallOutputItemType(strings.TrimSpace(firstNonEmptyString(item["type"]))) {
normalized = append(normalized, rawItem)
if !ok {
continue
}
itemType := firstNonEmptyString(item["type"])
if !isCodexToolCallOutputItemType(itemType) {
continue
}

callID := strings.TrimSpace(firstNonEmptyString(item["call_id"]))
callID := firstNonEmptyString(item["call_id"])
// Codex sends externally supplied inputs (such as task delegation) as
// named function outputs without a preceding function call. Preserve
// their native type, namespace and output instead of silently dropping
// the request that started the turn.
if callID == "" && strings.TrimSpace(firstNonEmptyString(item["type"])) == "function_call_output" &&
strings.TrimSpace(firstNonEmptyString(item["name"])) != "" {
normalized = append(normalized, rawItem)
if callID == "" && itemType == "function_call_output" && firstNonEmptyString(item["name"]) != "" {
continue
}
_, hasToolCall := toolCallIDs[callID]
_, hasReference := referenceIDs[callID]
if callID != "" && (hasToolCall || hasReference) {
normalized = append(normalized, rawItem)
if _, matched := contextIDs[callID]; matched {
continue
}

modified = true
if normalized == nil {
normalized = make([]any, 0, len(input)-1)
}
normalized = append(normalized, input[keepFrom:i]...)
keepFrom = i + 1
}
if !modified {
if normalized == nil {
return false
}
reqBody["input"] = normalized
reqBody["input"] = append(normalized, input[keepFrom:]...)
return true
}

Expand Down
13 changes: 13 additions & 0 deletions backend/internal/service/openai_responses_input_compat_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ func TestSanitizeOpenAIResponsesOrphanToolOutputs(t *testing.T) {
require.True(t, sanitizeOpenAIResponsesOrphanToolOutputs(reqBody, input, false))
got, ok := reqBody["input"].([]any)
require.True(t, ok)
require.NotNil(t, got)
require.Empty(t, got)
})

Expand Down Expand Up @@ -86,6 +87,18 @@ func TestSanitizeOpenAIResponsesOrphanToolOutputs(t *testing.T) {
require.False(t, sanitizeOpenAIResponsesOrphanToolOutputs(reqBody, input, true))
require.Equal(t, input, reqBody["input"])
})

t.Run("removing separated orphans preserves the caller's slice", func(t *testing.T) {
orphan := map[string]any{"type": "function_call_output", "call_id": "missing"}
input := []any{orphan, "first", orphan, orphan, "last", orphan}
reqBody := map[string]any{"input": input}
require.True(t, sanitizeOpenAIResponsesOrphanToolOutputs(reqBody, input, false))
result, ok := reqBody["input"].([]any)
require.True(t, ok)
require.Equal(t, []any{"first", "last"}, result)
result[0] = "updated"
require.Equal(t, []any{orphan, "first", orphan, orphan, "last", orphan}, input)
})
}

func TestWebSocketCompatibilityPreservesNamedDelegation(t *testing.T) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,44 @@ func BenchmarkOAuthResponsesCompatibilityMessageHistory(b *testing.B) {
}
}
}

func TestOrphanCleanupSmallPairedHistoryAllocations(t *testing.T) {
input := []any{
map[string]any{"type": "function_call_output", "call_id": "paired"},
map[string]any{"type": "item_reference", "id": "paired"},
}
body := map[string]any{"input": input}
allocs := testing.AllocsPerRun(100, func() {
if sanitizeOpenAIResponsesOrphanToolOutputs(body, input, false) {
t.Fatal("removed a paired output")
}
})
if allocs > 0 {
t.Fatalf("unchanged two-item history allocated %.0f times per call", allocs)
}
}

func BenchmarkSanitizeOrphanToolOutputs(b *testing.B) {
for _, pairs := range []int{1, 1024} {
input := make([]any, 0, 2*pairs+1)
for i := 0; i < pairs; i++ {
id := fmt.Sprint(i)
input = append(input, map[string]any{"type": "function_call", "call_id": id},
map[string]any{"type": "function_call_output", "call_id": id})
}
for _, orphan := range []bool{false, true} {
if orphan {
input = append(input, map[string]any{"type": "function_call_output", "call_id": "missing"})
}
b.Run(fmt.Sprintf("pairs=%d/orphan=%t", pairs, orphan), func(b *testing.B) {
body := map[string]any{"input": input}
b.ReportAllocs()
for b.Loop() {
if sanitizeOpenAIResponsesOrphanToolOutputs(body, input, false) != orphan {
b.Fatal("unexpected change to tool history")
}
}
})
}
}
}
Loading