fix: trimMessages() orphans tool messages, crashes OpenAI runs#70
Merged
fix: trimMessages() orphans tool messages, crashes OpenAI runs#70
Conversation
The sliding window in trimMessages() slices the last 39 messages but can cut right between an assistant message (with tool_calls) and its tool response. OpenAI's API enforces strict tool message pairing and hard-rejects orphaned tool messages with a 400. Other providers don't crash but silently feed the model a tool response with no context for what was called or why, degrading reasoning quality. Reproduced on broken-auth-enum: GPT-5.4 crashes at iteration 18 every time. Claude Sonnet 4.5 and Grok 3 survive to iteration 50 but with degraded context. The fix is embarrassingly simple — after the existing same-role dedup loop, skip any orphaned tool messages at the start of the trimmed tail. Closes #69
pi3-code
approved these changes
Mar 10, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
trimMessages()sliding window can slice between anassistantmessage (withtool_calls) and itstoolresponse, orphaning the tool message. OpenAI hard-rejects this with a 400 — every other provider silently degrades by feeding the model a tool response with zero context for what was called.Reproduced on
broken-auth-enum:The fix adds a second skip loop after the existing same-role dedup — any
toolmessages at the start of the trimmed tail get dropped since their parentassistantmessage was already sliced off.Only manifests on challenges requiring ~20+ iterations. Easy challenges that complete in <15 iterations never trigger this.
Test plan
Closes #69