`streamText` executes a queued tool twice when a model emits duplicate finish events
Description
If a model stream emits one tool call followed by two eligible finish events, streamText executes the tool twice with the same call ID. A side-effecting tool can repeat its action. The extra result also stops a multi-step run because the number of tool results exceeds the number of tool calls.
I expected the queued tool to run once and the next model call to receive its result. On upstream main at d55f3cf, the reproduction recorded two tool executions, two tool results, and only one model call.
{"modelCalls":1,"toolExecutions":2,"firstStepToolResults":2,"text":""}
Each finish becomes a model-call-end event, and the tool executor keeps the queued calls after dispatch. Both eligible finish events dispatch the same queue.
Reproduction
Save the script below as /tmp/reproduce-duplicate-finish.mjs. It uses a local custom V4 model and an in-memory tool. It needs no API credentials. The resolution command identifies packages/ai/dist/index.js in the checkout.
# From the SDK checkout root, with Node 24 and pnpm 12.14.0.
pnpm --filter ai... install --frozen-lockfile
pnpm exec turbo build --filter=ai... --filter='!konsistent-provider'
cd packages/ai
node --input-type=module -e 'console.log(import.meta.resolve("ai"))'
node --input-type=module < /tmp/reproduce-duplicate-finish.mjs
import { jsonSchema, stepCountIs, streamText, tool } from 'ai';
const usage = {
inputTokens: { total: 1, noCache: 1 },
outputTokens: { total: 1, text: 1 },
};
const toolFinish = {
type: 'finish',
finishReason: { unified: 'tool-calls', raw: 'tool_calls' },
usage,
};
let modelCalls = 0;
let toolExecutions = 0;
const model = {
specificationVersion: 'v4',
provider: 'local-reproduction',
modelId: 'duplicate-finish',
supportedUrls: {},
async doStream() {
const parts =
++modelCalls === 1
? [
{
type: 'tool-call',
toolCallId: 'call-1',
toolName: 'increment',
input: '{}',
},
toolFinish,
toolFinish,
]
: [
{ type: 'text-start', id: 'text-1' },
{ type: 'text-delta', id: 'text-1', delta: 'done' },
{ type: 'text-end', id: 'text-1' },
{
type: 'finish',
finishReason: { unified: 'stop', raw: 'stop' },
usage,
},
];
return {
stream: new ReadableStream({
start(controller) {
for (const part of parts) controller.enqueue(part);
controller.close();
},
}),
};
},
};
const result = streamText({
model,
prompt: 'Increment the counter and acknowledge the result.',
stopWhen: stepCountIs(2),
tools: {
increment: tool({
inputSchema: jsonSchema({ type: 'object', properties: {} }),
execute: async () => ++toolExecutions,
}),
},
});
await result.consumeStream();
const steps = await result.steps;
console.log(
JSON.stringify({
modelCalls,
toolExecutions,
firstStepToolResults: steps[0].toolResults.length,
text: await result.text,
}),
);
AI SDK Version
ai 7.0.179 at upstream main commit d55f3cfc456d1b7bc7db3a4b70fbf602ddc8647d. Verified with the local custom model. Live Anthropic and AI Gateway requests remain untested.
Code of Conduct
- [x] I agree to follow this project's Code of Conduct
Identify issue type
Identified as Bug
Confidence: High
Rationale
The issue reports a reproducible failure in existing streamText behavior that duplicates tool side effects and prevents expected continuation.
Evidence
- A local reproduction shows one tool call executing twice with the same call ID after duplicate finish events.
- The duplicate tool results prematurely stop the multi-step run: two tool executions and results occur, but only one model call.
- The report identifies the queued calls remaining after dispatch as the cause.
Bug discovery clarification
@anupamgit, how did you discover this bug? Did you encounter it while using the AI SDK in production, find it while auditing or reviewing AI SDK source code, or discover it another way? Please describe the original discovery context.
The report establishes a local reproduction but not how the bug was originally discovered. Neither production use nor an audit origin is established. Ask the original author whether they discovered it in an application, through SDK source inspection, or during experimentation.
Bug discovery clarification
@anupamgit, how did you discover this bug? Did you encounter it while using the AI SDK in production, find it while auditing or reviewing AI SDK source code, or discover it another way? Please describe the original discovery context.
The report establishes a local reproduction but not how the bug was originally discovered. Neither production use nor an audit origin is established. Ask the original author whether they discovered it in an application, through SDK source inspection, or during experimentation.
Found this while reviewing how streamText executes tools and reproduced it on main at d55f3cf using the custom V4 model linked in the report.
When the model emitted two finish events, streamText ran the tool twice and stopped after the first step.
Identify bug discovery
Discovery source: discovery:audit (high confidence).
The original author explicitly states that the bug was discovered while reviewing streamText's tool execution, then confirmed with a local reproduction.
- In response to the discovery question, the author said: “Found this while reviewing how streamText executes tools.”
- The author separately described reproducing the issue on main at d55f3cf using a custom V4 model.
- The report identifies the internal cause: eligible finish events dispatch the same tool queue because queued calls remain after dispatch.
The duplicate-finish report raises a useful distinction between stream completion and authorization to execute a side effect. An independent, SDK-free fixture I ran on Node 22.18.0 simulates a remote operation that succeeds but returns malformed JSON: replaying the submission creates two mock effects, while a persisted intent/unknown marker freezes the second submission until reconciliation of the original remote ID. All 12 local assertions pass, including payload-change rejection and scene schema/semantic validation. This does NOT reproduce your duplicate-finish SDK bug or verify a fix for d55f3cf; it is a complementary application-boundary regression case. A real tool executor should additionally enforce one dispatch per stable execution identity, and test duplicate terminal events separately from transport recovery. Fixture and raw result: https://github.com/xbstack/problem-labs/tree/main/repro/structured-output-retry-boundary-20261127 . No API or actual side effect used.
Related published timeout/Resume reconciliation background (the current website article covers LangGraph, not an independent Vercel SDK reproduction): https://www.xbstack.com/en/ai/langgraph-agent-error-recovery-retry-timeout/?utm_source=github&utm_medium=referral&utm_campaign=structured-output-retry-boundary-20261127&utm_content=duplicate_finish_comment
Putting the side effect behind a separately enforced tool boundary can cap completed increment calls per minute.
pip install panel-firewall
usepanel proxy --policy panel-policy.yaml -- YOUR_MCP_SERVER_COMMAND
mode: auto
actions:
increment: {risk: write, rate_limit: {max: 1, per_seconds: 60}}
Only one recorded execution per minute, regardless of how many finish events the SDK emits. https://github.com/tenthlook/panel-firewall
Thanks for the suggestion. A rate-limited proxy can be useful as defense in depth, but it is not an exactly-once guarantee for duplicate finish dispatch: it may block legitimate independent calls and can still allow a duplicate outside the window or across instances without shared state.
The application boundary still needs a stable execution identity and an atomic idempotency record with reconciliation/replay of the original result. The SDK should also enforce at-most-once dispatch for each queued tool-call identity. I have not evaluated panel-firewall, so I can't endorse that specific package.
Nice catch on the duplicate finish event path. Even after this stream-level race is fixed in streamText, any mutating HTTP tool can still be double-executed by upstream retries or crash/resume replays, so pairing the SDK fix with a deterministic Idempotency-Key keyed on (operationId, toolName, toolCallId) plus a CI assertion on max_tool_calls + DB row count is a great regression guard.
(Disclosure: I maintain agent-fault-check, an Apache-2.0 HTTP fault-injection CLI for testing duplicate tool calls and retry budgets in CI: https://afc.evhu.net)