c7761573f5
DeepSeek v4 rejects a payload where an assistant message carries a tool_call whose tool result does not follow it immediately (HTTP 400 "An assistant message with 'tool_calls' must be followed by tool messages responding to each 'tool_call_id'"). Context compression can displace a tool result past a user turn; the result then lands ~100 messages away from its declaring assistant message. Two gaps let the poisoned shape reach the wire (reproduced from the production request dump of session 4d8727cbcf04, replayed through both functions): 1. repair_message_sequence Pass 1 drops the displaced tool RESULT as stray but leaves the declaring assistant message carrying the now unanswered tool_call (with empty content) in the durable history. 2. sanitize_api_messages stubbed only globally-absent result ids: the displaced result still exists in the transcript, so the id survives the set-subtraction, no stub is injected, and the payload 400s. Fix both layers so every path is order-independent: - repair_message_sequence: new Pass 2 prunes tool_calls that have no result in the immediately-following tool run (matching on id or call_id, same superset rule as Pass 1). If pruning empties the turn (no content/reasoning left), the whole message is dropped rather than sending an empty assistant message. Codex interim turns are exempt, as in Pass 0. - sanitize_api_messages: the orphan/stub logic is rewritten as a single rolling positional walk that drops results not immediately following their declaring assistant (including results appearing BEFORE their call) and injects stub results for positionally-uncovered calls even when a mispositioned result exists elsewhere. Adds six regression tests: repair pruning, whole-turn drop when pruned calls were the only payload, valid-pair negative control, positional stub injection, result-before-call orphan drop, and a fully-paired transcript negative control.