Skip to content

Give each tool call its own id when a model reuses or omits one - #2255

Merged
fazxes merged 2 commits into
mainfrom
fazxes/unique-tool-call-ids
Nov 24, 2026
Merged

fazxes merged 2 commits into
mainfrom
fazxes/unique-tool-call-ids

Conversation

@fazxes

@fazxes fazxes commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

When a model reused a tool call id, repeated one in a reply, or left it out, fx lost calls or stopped the turn:

  • One id in several replies (case F): every edit ran, but the live transcript, the recap, and ACP showed only the first call. After a resume all of them showed.
  • One id several times in one reply (case G) and empty ids (case H): the turn stopped with request failed: malformed authoritative tool identity, and no call ran. On a custom OpenAI-compatible or Anthropic-compatible connection the stream failed instead.

Now a call gets its own id when the model's id cannot be used, so no call is lost and no turn stops for this. A call that repeats an earlier call exactly keeps its id, so the subagent tool still answers a message it already ran from saved state.

Root cause

fx used the id the model sent as the call's own identity and never made it unique.

  • Admission (authoritativeToolAdmission in src/core/shared/types.zig) compares ids only inside one reply. A reused id passes, and the live transcript, which keys calls by turn and id, drops the second call's start as a late event (src/ui/transcript/runtime.zig, late lifecycle event ignored).
  • The same check rejects a reply whose ids repeat or are blank, so the turn stops.
  • The custom adapters reject such replies themselves: chat_completions_protocol.zig (InvalidToolCallId, ConflictingIdentity), anthropic_messages_protocol.zig (InvalidEvent, ConflictingIdentity), and responses_protocol.zig (ToolCallLimitExceeded; a function_call with no call_id was dropped).

Design

Two designs were weighed.

  • A, chosen: fx gives a call its own id when the model's id is unusable. A call keeps the model's id when the id is not empty or blank, fits the stored limits (256 bytes, valid UTF-8), and no call in the conversation has it. Any other call gets fx_call_<n>, the first number that no id in the conversation or the reply has.
  • B, rejected: an internal fx id, with the model's id kept for the wire. It needs a new saved field, and it cannot fix G or H, because a repeated or empty id cannot go back to the provider. It differs from A only for F.

One exception keeps the subagent tool's replay guard. The subagent tool keys a delegation by its call id: a message it already ran is answered from saved state instead of running again. So a call keeps a reused id when it is a call from an earlier reply sent again: the same id, the same tool, and the same arguments. Only one call in a reply can keep an id this way; a second copy in the same reply gets an fx id.

"Same arguments" means:

  • Both parse to the same JSON value (json_comparison.serializedEqual). Key order and whitespace do not matter, escapes that decode to the same text match, and 1 and 1.0 differ. Text that is not JSON matches only byte for byte.
  • They also match with an exact {"request": ...} wrapper taken off either side, an object or JSON text of one (tool_args.unwrapRequest). fx takes that wrapper off before it stores shell, subagent, and read_tool_result calls, so a stored call and the model's repeat of it can differ by it.
  • Arguments that nest deeper than 64 levels are compared only as sent, because std.json.Stringify must never see them.

Where the rule lives:

  • tool_call_ids.ReplyIds (src/gateway/tool_call_ids.zig) holds the rule. It takes as used every call and result id in the request, the aliases the request sends for non-portable ids, and this turn's earlier calls. Compaction can take those out of the request, so core passes them in the new borrowed current_turn_messages field of RequestData and ModelRequest.
  • Each adapter applies it while it reads the stream, before it writes its replay state, so the call, its streamed input, its replay part, and what fx saves all carry the same id:
    • AI Gateway (client.zig): SseCallIds rewrites each tool event's id before the parser and the replay builder read it. Streamed input keeps its pairing with its call, and a reused stream id after its call ended starts a new call.
    • OpenAI-compatible (chat_completions_protocol.zig): ids are given when the reply ends, before _tool_call_ids is written.
    • Anthropic-compatible (anthropic_messages_protocol.zig): ids are given when a tool_use block starts, so the live start already has its id.
    • Responses (responses_protocol.zig, used by Codex, Grok, and custom Responses connections): ids are given at output_item.added; later events are still checked against the server's own call_id.
    • The SDK host path reads AI Gateway streams and gets the same rule.
  • The streaming adapters (AI Gateway, Anthropic-compatible, Responses) announce a call's start live before its arguments are complete. A call that turns out to be a call sent again gets its id back when the reply ends, and the id it started under becomes its provisional_id. The transcript already uses that field to match a start to its final call, and it is never saved.
  • A call the provider ran itself keeps its own id, because its result comes back under that id.
  • Core's admission check stays as it was, as a backstop. A wrong-typed id, such as a number, is still a malformed event.

What the model receives

  • A call whose id was empty, blank, repeated in one reply, used by a different earlier call in the conversation, or too long to store now comes back to the model under its fx id, in the tool call and in its result, from the next request on.
  • A call that repeats an earlier call with the same id, tool, and arguments comes back under that id, as before.
  • Calls with ids the model chose uniquely are sent exactly as before. The three request bodies of a unique-id run are byte for byte the same on main and on this branch.

Saved sessions

There is no format change: the fx id is stored in the call's existing id field. Sessions saved before this change, which can hold one id in several steps, resume as before and are sent to the model unchanged. Only a new call that reuses a saved id for different work gets an fx id.

Package size

libfx reads AI Gateway streams through the same parser, so fx-core.wasm carries the new rule. It grows by about 4.8 KB: 2,462,396 bytes on main b59801471, 2,467,236 with this PR, past its 2,465,000-byte budget. The second commit raises that one budget to 2,475,000 bytes. Every other package stays within its budget.

Before and after

The macOS binary against a fake gateway, three edits of g.tse that each swap seven lines for one. Main is 381fb613a, the merge base.

Case Main, live Main, after resume This branch, live and after resume
F: dup in 3 replies ● Edited g.tse +1/-7, 1 file changed +1 -7 ● Edited g.tse +3/-21 · 3 edits ● Edited g.tse +3/-21 · 3 edits, 1 file changed +3 -21
G: same 3 times in 1 reply ✗ system: request failed: malformed authoritative tool identity, 0 of 3 edits Resuming the interrupted request the same row and recap, 3 of 3 edits
H: empty ids the same failure, 0 of 3 edits the same the same row and recap, 3 of 3 edits
U: unique ids u1 to u3 3 of 3 edits the same the same; the 3 request bodies (21157, 22021, 22471 bytes) are byte for byte the same as main's

Ids the model got back with each result: F dup, fx_call_1, fx_call_2; G same, fx_call_1, fx_call_2; H fx_call_1, fx_call_2, fx_call_3.

Tests

Unit tests, which fail on main for F, G, and H in each adapter:

  • AI Gateway (client.zig): consumeSseStream gives a call id repeated in one reply an fx id, consumeSseStream gives calls with missing, empty, blank, or oversized ids fx ids, consumeSseStream keeps each repeated-id call's replay part on its own id, and an AI Gateway call id an earlier step, this turn, or the wire already uses gets an fx id. The earlier-step test, a call the AI Gateway provider runs keeps its own id, even one already used, and unique AI Gateway call ids come through byte for byte take the new conversation input, so they do not compile on main; the others fail there.
  • OpenAI-compatible: chat completions gives a call the id an earlier step used an fx id and chat completions gives repeated, missing, empty, and oversized call ids fx ids, and sends them back.
  • Anthropic-compatible: anthropic messages gives a call the id an earlier step used an fx id and anthropic messages gives repeated, missing, empty, and oversized call ids fx ids.
  • Responses: configured responses gives a call the id an earlier step used an fx id, configured responses gives repeated, missing, and empty call ids fx ids, and OpenAI Codex gives an oversized call id an fx id and rejects an oversized tool name.
  • Core: every model request carries this turn's calls so far, which a reply may not reuse (tool_flow.zig).

The same-call rule:

  • tool_call_ids.zig: key order, whitespace, and escapes; 1 against 1.0; another tool; text that is not JSON; a second copy in one reply; an id only a tool result holds; a compacted call from this turn; the request wrapper as an object or as JSON text, on either side; a wrapper beside another key; arguments nested 300 levels deep.
  • One test in each adapter: a call sent again keeps its id, a second copy in the same reply gets an fx id, and in the streaming adapters the id it started under becomes its provisional_id.
  • unique AI Gateway call ids come through byte for byte and a reply keeps every provider id no other call has, byte for byte.

E2E tests:

  • tui-tool-story.test.ts: edits whose calls have <case> each run and count, live and after resume, for F, G, and H. All three fail on main.
  • acp.test.ts: each ACP tool call has its own toolCallId when the model reuses, repeats, or leaves out ids. It fails on main.
  • sessions.test.ts: a session saved with one call id in several steps resumes as before, and a new reuse gets an fx id. It writes a session in main's shape and checks that it resumes and is sent unchanged. On main it fails only at the new reuse.
  • gateway-stream-lifecycle.test.ts: subagent replay returns saved success and failure without another worker passes unchanged. The blank, long-id, and long-provisional cases and the Codex and Grok 257-byte case in tui-auth-source-selection.test.ts now expect the call to run under an fx id.
  • The 13 E2E files this touches, run in full on the merge with main b59801471: tui-tool-story 32 pass, sessions 115 (30 skip), gateway-stream-lifecycle 370 (2 skip), tui-auth-source-selection 231, configured-providers 116, tui-custom-connection-errors 6, acp 294 (14 skip), session-recovery 35 (1 skip), ask-presentation 23, tui-gateway-stream-lifecycle 110, tui-full-detail 11, config-persistence 33, and tui-resume 93 with 1 failure. That failure, manual upgrade output links stable notes and dev changes, comes from building a tree with no .git folder: main b59801471 built the same way fails it too, and this branch passes it in its git checkout.

Other checks:

  • Unit suite on the merge with main: 12602 pass, 27 skip, and 12 failures. The same 12 tests fail on main b59801471 in the same sandbox, which runs as root (read-only folders and files, undo of a protected file, a read-only blob).
  • TLA+: configured_provider, agent_runtime, recovery, auth, gateway_open, saved_turn, and toolbox checks pass, and the configured_provider, agent_runtime (both drivers), recovery, gateway_open, and saved_turn drivers accept the change.
  • Mutations: 30 in all, every one caught. 13 cover the id rule and the adapters, 16 the same-call rule, and one the depth guard; without the guard the deep test crashes in std.json.Stringify.
  • Fuzzing: a new reply_call_ids target for the rule. See Check findings for the rounds.

Threat review

The model, or the server it speaks through, chooses every call id. An id decides which call a result, a replay part, a live row, an ACP toolCallId, and a subagent delegation belong to.

  • Ids that look like fx's own: fx_call_<n> is the first number that no id in the request (calls and results), no alias the request sends (fx_<hash>_<n>), no call from this turn, and no call in this reply has. A model id in either form is an ordinary id: it is kept when no other call has it and replaced when one does. Tests: fx ids skip every id the conversation holds, fx's own forms too and the alias case in the AI Gateway test.
  • Another call's identity: a reused id is kept only for the same tool and the same arguments as the earlier call with that id, and only once in a reply. A model cannot send other work under an earlier call's id to get that call's saved result. On main, a different subagent message under a used id was refused as operation_conflict; now it runs as a new message, which the model could already ask for with a new id.
  • Long ids, invalid UTF-8, and control bytes: ids over 256 bytes or with invalid UTF-8 are never stored or sent back; they get fx ids. The stream and event size limits still bound what fx reads. An id with control bytes that fx can store is handled as on main.
  • Deeply nested arguments: the same-call check parses the model's arguments and writes the inner request object back out. Text nested past 64 levels skips that step, because std.json.Stringify stops a safe build past 256 levels. Without the guard, a 300-level wrapper crashed the test binary; the unit test now covers it. Parsing and serializedEqual do not recurse.
  • Cost: the check runs only for a call whose id fx replaced, and compares it only with earlier calls that have that id.

Check findings

node ~/.agents/skills/factory/bin/check --base 381fb613a reports 76 findings, the same on 3bbeb8e05 and 6cabb9f0c.

  • removed-assert (18). Each one is in a test that pinned the old rejection or the old kept id, which this PR changes on purpose; the same tests now check the new result.
    • src/gateway/client.zig (5): the tests that expected a repeated id to stay as sent, a missing id to stay absent and empty, one start, and no identity failure. They are renamed (consumeSseStream gives a call id repeated in one reply an fx id, consumeSseStream gives calls with missing, empty, blank, or oversized ids fx ids) and now check each fx id, each start, and admission.
    • tests/e2e/gateway-stream-lifecycle.test.ts (6): the unstorable-id test.each expected exit 1, MalformedAuthoritativeToolIdentity, no tool calls, one request, no file, and a trace line for every kind; blank current tool id is rejected before file execution expected the same. The name kinds keep those checks. The long-id and long-provisional kinds (an oversized tool id runs under an fx id beside its sibling) and the blank id (a blank tool id runs under an fx id) now check that the call runs, its result, and the ids sent back.
    • tests/e2e/tui-auth-source-selection.test.ts (7): the Codex and Grok case expected a 257-byte id to be refused. It now expects both lengths to run, with the 256-byte id kept and the 257-byte id replaced by fx_call_1, in the request body and in the saved history.
  • model-covered (6): agent_runtime, auth, saved_turn, and toolbox for orchestrator.zig, gateway_open for client.zig, and configured_provider for the adapters. None of these models has call ids in its state. The orchestrator change only passes this turn's messages into the request, the client.zig change is in the event parser and not in opening the stream, and the adapter change keeps every connection, retry, and resume step the same. All seven checks pass, and their drivers accept the change (see Tests).
  • fuzz-reached (49): 10 direct targets (reply_call_ids, vercel_stream, chat_completions_stream, responses_stream, responses_text, gateway_event_class, gateway_team_display, provider_finish_raw, request_wrapper_text, tool_argument_diagnostic) ran for 60 seconds each on this commit: all ok, with no reproducer. The 39 related targets reach the change only through types.zig (where admission now calls the new ConversationIdentity.isBlank), stream_provider.zig (the new borrowed field), or builtins/gateway.zig; I left them to the nightly run.
  • fuzz-setup (2): src/fuzz_targets.zig and tests/fuzz/targets.json register reply_call_ids. python3 -m unittest scripts.tests.test_fuzz_nightly passes (21 tests) and zig build fuzz replays every target (9/9 steps). The Fuzz workflow on this PR is the last check.
  • concurrency-added (1): client.zig, a cancel flag (std.atomic.Value(bool)) in a test helper, the same flag the other stream tests use. The TSan workflow on this branch passed (run 45281468470) with 7 WARNING: ThreadSanitizer lines, the same 7 as main's nightly run on e27ae3e51 (the stuck-lookup test helper, three in capture_store, and a shell_snapshot thread leak among them). None names this helper or code this PR changes.

Limits

  • An identical call sent again in a later step of the same turn keeps its id, as on main, so its live row and its ACP toolCallId still merge with the first call's until a resume. The call itself runs.
  • The same-call match knows only the request wrapper among fx's argument fixes. A repeat that differs from the stored call only by another fix, such as the action fx fills in for shell, gets an fx id and runs as a new call. Only the subagent tool keys work by call id, and the wrapper is its only fix.
  • An fx id is unique within the conversation the request carries and this turn. After compaction removes earlier turns, a later fx_call_<n> can repeat an id from a turn the model no longer sees. The transcript keys calls by turn, and saved sessions pair results step by step, so neither is affected.

A model can send one tool call id in several replies, repeat it within one
reply, or leave it empty. fx used the model's id as the call's identity, so
the live transcript, the recap, and ACP lost every call after the first, and
a repeated or empty id stopped the turn.

Each provider adapter now gives a call an fx id (fx_call_<n>) when the
model's id is empty, blank, cannot be stored, repeats an id earlier in the
reply, or repeats one the conversation already used, before it writes its
replay state. A call from an earlier reply sent again with the same id,
tool, and arguments keeps its id, so the subagent replay guard still answers
it from saved state. Calls the provider ran keep their own ids. Core passes
this turn's messages to the adapters, since compaction can drop them from
the request.
@fazxes fazxes added the type: bug Fixes incorrect behavior label Nov 23, 2026
libfx reads AI Gateway streams through the same parser, so it needs the
rule that gives each tool call its own id. That code adds about 4.8 KB to
fx-core.wasm, which was already at 2,462,396 of its 2,465,000 bytes on
main.
@fazxes fazxes closed this Nov 24, 2026
@fazxes fazxes reopened this Nov 24, 2026
@fazxes
fazxes marked this pull request as ready for review November 24, 2026 02:20
@fazxes
fazxes merged commit 4979bfe into main Nov 24, 2026
293 of 297 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: bug Fixes incorrect behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant