fix(openai-base): report incomplete Chat Completions streams #1604
main fromrefs/pull/1604/head·merged by AlemTuzlak View on GitHubA Chat Completions stream that stops after partial text, with no finish_reason and no final usage-only chunk, was reported as a normal success: RUN_FINISHED with finishReason: 'stop', and onFinish got the partial text. This PR makes the shared @tanstack/openai-base adapter emit RUN_ERROR with code incomplete-stream for that stream, the same code that the Responses adapter already uses. Fix by @L-1ngg. A maintainer added a merge of main and the follow-up commit e0e28038d.
🎯 Changes#
processStreamChunksrecords if the last chunk was a usage-only chunk (choices: []withusage).- After the lifecycle cleanup, the adapter emits
RUN_ERROR(incomplete-stream) when nofinish_reasonarrived and the last chunk was not usage-only. Partial text stays available.onErrorruns,onFinishdoes not, and pending server tools do not run. - A finish reason followed by a usage chunk still finishes with usage. A usage-only tail with no finish reason still finishes, as before.
- Unit test
chat-completions-incomplete-stream.test.tsand E2E route plus specchat-completions-incomplete-stream. - Maintainer follow-up: the
finish_reason=falsecase inopenai-malformed-tool-arguments.spec.ts(from #1602) now expectsincomplete-stream. That stream stops after a truncated tool call with no finish reason, so it is an incomplete stream. The tool still does not run. - Docs:
docs/chat/streaming.mddescribes the check.docs/config.jsonhas the newupdatedAt. Patch changeset for@tanstack/openai-base.
✅ Checklist#
- I have followed the steps in the Contributing guide.
- I have tested code changes locally with
pnpm run test:pr, or these tests do not apply to this pull request. - I fully understand the code in this pull request, including any code generated with AI assistance.
- Docs: I updated
docs/for this change, or this change is not user-facing. - Changeset: I added a changeset (
pnpm changeset), or this PR does not change a published package.
The author ran pnpm test:pr on the first commit. After the merge of main, the maintainer ran package-scoped checks only (see Testing).
🚀 Release Impact#
- This change affects published code, and I have generated a changeset.
- This change is docs/CI/dev-only (no release).
Root cause#
Issue. A Chat Completions response with partial text and then EOF (no finish_reason, no usage-only chunk) emits RUN_FINISHED and calls onFinish with the partial content. Every adapter built on the shared Chat Completions base is affected.
Cause. After the loop in OpenAIBaseChatCompletionsTextAdapter.processStreamChunks, the code closes open lifecycles and then maps a missing finish reason to stop (pendingFinishReason ?? 'stop'). Nothing checks that the stream really completed.
Fix. After the cleanup, the adapter emits RUN_ERROR with code incomplete-stream unless a finish reason arrived or the last chunk was usage-only. Usage on an earlier chunk does not count.
Possible alternatives#
- Require only a finish reason. This removes the old usage-only tail case from #676. Not taken because no evidence shows that all affected providers now send a finish reason.
- Accept any usage (
!lastUsage). About the same size. Not taken because a stream with usage on every chunk can then pass as complete after a cut. - Detect
[DONE]. The OpenAI SDK consumes that marker before the adapter sees chunks. Not taken because it needs a different parser or SDK internals.
Testing#
Commands run
Maintainer repro, agent-written test (one text chunk, then EOF, through chat() with onFinish and onError spies). Against the main source (cf90e4185):
× reports EOF after partial text as incomplete-stream, not success
AssertionError: expected [ 'RUN_STARTED', …(4) ] to not include 'RUN_FINISHED'
Tests 1 failed | 1 passed (2)
Against this PR:
Test Files 1 passed (1)
Tests 2 passed (2)
The PR test chat-completions-incomplete-stream.test.ts against the main source: 6 failed, 4 passed. On this PR: all pass.
Package checks after the merge of main (vitest with --maxWorkers=2, then test:types, test:oxlint, build). All passed:
openai-base(263 tests, plustest:build)ai-openai,ai-groq,ai-byteplus,ai-bedrockai-vercel-gateway,ai-cloudflare,ai-lovable,ai-llmgatewayoxfmt --checkon the changed files, andpnpm test:docs
Not run locally: the Playwright E2E suite (CI runs it) and the full testing/e2e type check (it needs every workspace package built). The changed spec files and the new route have no type errors. A unit test that copies the #1602 route with no finish reason showed one request, no tool run, and one incomplete-stream error. That matches the updated spec.
Manual test
- On
main, callchat()with an adapter fromcreateOpenaiChatCompletionsand afetchstub that returns onedata:chunk withcontent: 'partial', then ends. - Add middleware with
onFinishandonError. Onmain,onFinishruns and the last event isRUN_FINISHED. - On this branch, repeat.
onErrorruns once,onFinishdoes not run, and the last event isRUN_ERRORwith codeincomplete-stream.
How this PR makes testing easy. packages/openai-base/tests/chat-completions-incomplete-stream.test.ts runs the real OpenAI SDK decoder with stubbed SSE bodies. testing/e2e/tests/chat-completions-incomplete-stream.spec.ts covers the public factory and an HTTP route. No provider key is needed.
Linked issues#
Fixes #1603
Risk / rollback#
A provider that ends a good answer with no finish reason and no usage-only tail now gets incomplete-stream. The OpenAI SDK hides [DONE], so a stream with only [DONE] after content also needs a finish reason or a usage-only tail. Live providers were not tested. To undo, revert this PR.
Public API change#
Caller options do not change. A stream that ends early now goes to onError, not onFinish.
Before
middleware: [{ name: 'result', onFinish: (_ctx, info) => accept(info.content) }]
After
middleware: [
{
name: 'result',
onFinish: (_ctx, info) => accept(info.content),
onError: (_ctx, info) => reportError(info.error),
},
]
🤖 Generated with Claude Code
Summary by CodeRabbit#
Bug Fixes
- Incomplete Chat Completions streams now report an error instead of appearing to finish successfully. Partial text remains available, and unfinished tool calls are not executed.
- Streams ending with a finish reason or a usage-only final chunk continue to complete normally, with usage data preserved.
Documentation
- Clarified how incomplete streams are handled, including streams where the OpenAI SDK consumes the
[DONE]marker.
- Clarified how incomplete streams are handled, including streams where the OpenAI SDK consumes the
- 1
github-actions[bot](GitHub profile, opens in a new tab) assignedjherr
Thanks for the PR, @L-1ngg! 🙌 @jherr will take a look.
Automated pre-review checks
- ✅ CI passing
- ✅ No merge conflicts
- ✅ Changeset present
- ✅ E2E test changes included
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) added labelsmerge-conflicts
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelsmerge-conflicts
🦋 Changeset detected#
Latest commit: e0e28038dd09bf9facab45ddff57c9f38ff1c794
The changes in this PR will be included in the next version bump.
This PR includes changesets to release 1 package
Name Type @tanstack/openai-base Patch Not sure what this means? Click here to learn what changesets are.
Click here if you're a maintainer who wants to add another changeset to this PR
Maintainer review: findings#
Thank you for the clear issue and the fix, @L-1ngg. This is the review result. I also pushed a merge of the latest
main(ac6ddfb47) because the branch had a conflict intesting/e2e/src/routeTree.gen.ts. The resolution keeps themainroute tree and adds only the one route from this PR.Security#
Clean. The diff changes no
package.json, no lockfile, no CI workflow, and no script. The tests and the E2E route use a localfetchstub with a placeholder key. They make no network calls.Root cause#
- Issue. A Chat Completions stream can stop after partial text, with no
finish_reasonand no final usage-only chunk.chat()then emitsRUN_FINISHEDwithfinishReason: 'stop'and callsonFinishwith the partial text, as if the answer was complete. - Cause. In
OpenAIBaseChatCompletionsTextAdapter.processStreamChunks, the code after the loop closes open lifecycles and then maps a missing finish reason tostop(pendingFinishReason ?? 'stop'). Nothing checks that the stream really completed. - Fix. After the lifecycle cleanup, the adapter emits
RUN_ERRORwith codeincomplete-streamwhen nofinish_reasonarrived and the last chunk was not a usage-only chunk. This is the same code that the Responses adapter already uses for the same problem.
Repro (written by me, not copied from the PR)#
My test streams one text chunk and then ends. It runs
chat()withonFinishandonErrorspies.On
mainsource (cf90e4185), it fails as the issue says:× reports EOF after partial text as incomplete-stream, not success AssertionError: expected [ 'RUN_STARTED', …(4) ] to not include 'RUN_FINISHED' Tests 1 failed | 1 passed (2)On the PR source, it passes:
Test Files 1 passed (1) Tests 2 passed (2)I also ran your
chat-completions-incomplete-stream.test.tsagainst themainsource: 6 failed, 4 passed. So that test is a real repro, and I keep it as the unit test for this fix.Keep check#
packages/openai-base/tests/chat-completions-empty-choices.test.ts: the PR only rewrites comments and one test title. The test behavior does not change. This is not needed for the fix, so I will revert it tomain.- All other hunks are the fix, the repro test, the E2E coverage, the docs, and the changeset. They stay.
- A smaller check is possible:
!pendingFinishReason && !lastUsage. It accepts usage from any earlier chunk, so a stream with usage on every chunk can still pass as complete. YourendsWithUsageOnlyChunkflag costs about the same and is stricter, so I keep it.
Required changes#
- Conflict with #1602 on
main.testing/e2e/tests/openai-malformed-tool-arguments.spec.tshas afinish_reason=falsecase. That stream stops after a truncated tool call ({"path":) with no finish reason, and the spec expects a second model request and noRUN_ERROR. With this PR, that stream is an incomplete stream, so the run stops withincomplete-stream. The tool still does not run, which was the goal of #1602. This case will fail in CI after the merge. I will update that case to expect the new behavior: no tool run, one request, and oneincomplete-streamerror. - Docs date.
docs/chat/streaming.mdhas new content, so itsupdatedAtindocs/config.jsonmust change, as the repo rules say. I will set it to today.
CodeRabbit and reviewers#
CodeRabbit: no actionable findings (only a summary). No human review comments.
What I will push#
- Revert the comment-only edits in
chat-completions-empty-choices.test.ts. - Update the
finish_reason=falsecase inopenai-malformed-tool-arguments.spec.ts. - Bump
updatedAtforchat/streamingindocs/config.json.
I will not change the fix itself.
- Issue. A Chat Completions stream can stop after partial text, with no
Maintainer follow-up: pushed#
ac6ddfb47: merge ofmain(cf90e4185). The conflict intesting/e2e/src/routeTree.gen.tsis resolved: themaintree plus the one route from this PR.e0e28038d:openai-malformed-tool-arguments.spec.ts: thefinish_reason=falsecase now expects one request, no tool run, and oneincomplete-streamerror. Without this change, that #1602 case fails after this PR.chat-completions-empty-choices.test.ts: reverted tomain. The PR only changed comments there.docs/config.json:updatedAtforchat/streamingis now2026-10-07.
The fix itself did not change. Unit tests, types, oxlint, and build pass for
openai-baseand the eight adapters that extend its Chat Completions base. I did not run E2E locally. CI runs it. The PR body now has the root cause, alternatives, and both repro transcripts.AlemTuzlak approved these changes
View your CI Pipeline Execution ↗ for commit e0e28038dd09bf9facab45ddff57c9f38ff1c794
Command Status Duration Result nx run-many --targets=build --exclude=examples/...✅ Succeeded 1m 48s View ↗
☁️ Nx Cloud last updated this comment at
2026-10-07 15:58:48UTC@tanstack/ai
npm i https://pkg.pr.new/@tanstack/ai@1604@tanstack/ai-acp
npm i https://pkg.pr.new/@tanstack/ai-acp@1604@tanstack/ai-angular
npm i https://pkg.pr.new/@tanstack/ai-angular@1604@tanstack/ai-anthropic
npm i https://pkg.pr.new/@tanstack/ai-anthropic@1604@tanstack/ai-bedrock
npm i https://pkg.pr.new/@tanstack/ai-bedrock@1604@tanstack/ai-byteplus
npm i https://pkg.pr.new/@tanstack/ai-byteplus@1604@tanstack/ai-claude-code
npm i https://pkg.pr.new/@tanstack/ai-claude-code@1604@tanstack/ai-client
npm i https://pkg.pr.new/@tanstack/ai-client@1604@tanstack/ai-cloudflare
npm i https://pkg.pr.new/@tanstack/ai-cloudflare@1604@tanstack/ai-code-mode
npm i https://pkg.pr.new/@tanstack/ai-code-mode@1604@tanstack/ai-code-mode-snippets
npm i https://pkg.pr.new/@tanstack/ai-code-mode-snippets@1604@tanstack/ai-codex
npm i https://pkg.pr.new/@tanstack/ai-codex@1604@tanstack/ai-cohere
npm i https://pkg.pr.new/@tanstack/ai-cohere@1604@tanstack/ai-compaction
npm i https://pkg.pr.new/@tanstack/ai-compaction@1604@tanstack/ai-devtools-core
npm i https://pkg.pr.new/@tanstack/ai-devtools-core@1604@tanstack/ai-durable-stream
npm i https://pkg.pr.new/@tanstack/ai-durable-stream@1604@tanstack/ai-elevenlabs
npm i https://pkg.pr.new/@tanstack/ai-elevenlabs@1604@tanstack/ai-event-client
npm i https://pkg.pr.new/@tanstack/ai-event-client@1604@tanstack/ai-fal
npm i https://pkg.pr.new/@tanstack/ai-fal@1604@tanstack/ai-gemini
npm i https://pkg.pr.new/@tanstack/ai-gemini@1604@tanstack/ai-grok
npm i https://pkg.pr.new/@tanstack/ai-grok@1604@tanstack/ai-grok-build
npm i https://pkg.pr.new/@tanstack/ai-grok-build@1604@tanstack/ai-groq
npm i https://pkg.pr.new/@tanstack/ai-groq@1604@tanstack/ai-isolate-cloudflare
npm i https://pkg.pr.new/@tanstack/ai-isolate-cloudflare@1604@tanstack/ai-isolate-daytona
npm i https://pkg.pr.new/@tanstack/ai-isolate-daytona@1604@tanstack/ai-isolate-e2b
npm i https://pkg.pr.new/@tanstack/ai-isolate-e2b@1604@tanstack/ai-isolate-node
npm i https://pkg.pr.new/@tanstack/ai-isolate-node@1604@tanstack/ai-isolate-quickjs
npm i https://pkg.pr.new/@tanstack/ai-isolate-quickjs@1604@tanstack/ai-isolate-quickjs-bun
npm i https://pkg.pr.new/@tanstack/ai-isolate-quickjs-bun@1604@tanstack/ai-llmgateway
npm i https://pkg.pr.new/@tanstack/ai-llmgateway@1604@tanstack/ai-lovable
npm i https://pkg.pr.new/@tanstack/ai-lovable@1604@tanstack/ai-mcp
npm i https://pkg.pr.new/@tanstack/ai-mcp@1604@tanstack/ai-memory
npm i https://pkg.pr.new/@tanstack/ai-memory@1604@tanstack/ai-mistral
npm i https://pkg.pr.new/@tanstack/ai-mistral@1604@tanstack/ai-octane
npm i https://pkg.pr.new/@tanstack/ai-octane@1604@tanstack/ai-ollama
npm i https://pkg.pr.new/@tanstack/ai-ollama@1604@tanstack/ai-ollaya
npm i https://pkg.pr.new/@tanstack/ai-ollaya@1604@tanstack/ai-openai
npm i https://pkg.pr.new/@tanstack/ai-openai@1604@tanstack/ai-opencode
npm i https://pkg.pr.new/@tanstack/ai-opencode@1604@tanstack/ai-openrouter
npm i https://pkg.pr.new/@tanstack/ai-openrouter@1604@tanstack/ai-perplexity
npm i https://pkg.pr.new/@tanstack/ai-perplexity@1604@tanstack/ai-persistence
npm i https://pkg.pr.new/@tanstack/ai-persistence@1604@tanstack/ai-preact
npm i https://pkg.pr.new/@tanstack/ai-preact@1604@tanstack/ai-react
npm i https://pkg.pr.new/@tanstack/ai-react@1604@tanstack/ai-react-ui
npm i https://pkg.pr.new/@tanstack/ai-react-ui@1604@tanstack/ai-reactor
npm i https://pkg.pr.new/@tanstack/ai-reactor@1604@tanstack/ai-remix
npm i https://pkg.pr.new/@tanstack/ai-remix@1604@tanstack/ai-sandbox
npm i https://pkg.pr.new/@tanstack/ai-sandbox@1604@tanstack/ai-sandbox-blaxel
npm i https://pkg.pr.new/@tanstack/ai-sandbox-blaxel@1604@tanstack/ai-sandbox-boxd
npm i https://pkg.pr.new/@tanstack/ai-sandbox-boxd@1604@tanstack/ai-sandbox-cloudflare
npm i https://pkg.pr.new/@tanstack/ai-sandbox-cloudflare@1604@tanstack/ai-sandbox-daytona
npm i https://pkg.pr.new/@tanstack/ai-sandbox-daytona@1604@tanstack/ai-sandbox-docker
npm i https://pkg.pr.new/@tanstack/ai-sandbox-docker@1604@tanstack/ai-sandbox-e2b
npm i https://pkg.pr.new/@tanstack/ai-sandbox-e2b@1604@tanstack/ai-sandbox-local-process
npm i https://pkg.pr.new/@tanstack/ai-sandbox-local-process@1604@tanstack/ai-sandbox-railway
npm i https://pkg.pr.new/@tanstack/ai-sandbox-railway@1604@tanstack/ai-sandbox-sprites
npm i https://pkg.pr.new/@tanstack/ai-sandbox-sprites@1604@tanstack/ai-sandbox-upstash-box
npm i https://pkg.pr.new/@tanstack/ai-sandbox-upstash-box@1604@tanstack/ai-sandbox-vercel
npm i https://pkg.pr.new/@tanstack/ai-sandbox-vercel@1604@tanstack/ai-skills
npm i https://pkg.pr.new/@tanstack/ai-skills@1604@tanstack/ai-solid
npm i https://pkg.pr.new/@tanstack/ai-solid@1604@tanstack/ai-solid-ui
npm i https://pkg.pr.new/@tanstack/ai-solid-ui@1604@tanstack/ai-svelte
npm i https://pkg.pr.new/@tanstack/ai-svelte@1604@tanstack/ai-typesafe
npm i https://pkg.pr.new/@tanstack/ai-typesafe@1604@tanstack/ai-utils
npm i https://pkg.pr.new/@tanstack/ai-utils@1604@tanstack/ai-vercel-gateway
npm i https://pkg.pr.new/@tanstack/ai-vercel-gateway@1604@tanstack/ai-vertex
npm i https://pkg.pr.new/@tanstack/ai-vertex@1604@tanstack/ai-vue
npm i https://pkg.pr.new/@tanstack/ai-vue@1604@tanstack/ai-vue-ui
npm i https://pkg.pr.new/@tanstack/ai-vue-ui@1604@tanstack/ai-worldlabs
npm i https://pkg.pr.new/@tanstack/ai-worldlabs@1604@tanstack/openai-base
npm i https://pkg.pr.new/@tanstack/openai-base@1604@tanstack/preact-ai-devtools
npm i https://pkg.pr.new/@tanstack/preact-ai-devtools@1604@tanstack/react-ai-devtools
npm i https://pkg.pr.new/@tanstack/react-ai-devtools@1604@tanstack/solid-ai-devtools
npm i https://pkg.pr.new/@tanstack/solid-ai-devtools@1604@tanstack/svelte-ai-devtools
npm i https://pkg.pr.new/@tanstack/svelte-ai-devtools@1604commit:
e0e2803AlemTuzlak merged this077c96a
AlemTuzlak closed this
Sign in to join this conversation.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
74a81c60-9a40-4723-9050-be418d12e778📥 Commits
Reviewing files that changed from the base of the PR and between ac6ddfb47ee071ad57a01bb0761ee25dfd05f001 and e0e28038dd09bf9facab45ddff57c9f38ff1c794.
📒 Files selected for processing (2)
docs/config.jsontesting/e2e/tests/openai-malformed-tool-arguments.spec.tsIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 2 remain after this review.
📝 Walkthrough
Walkthrough#
Chat Completions streams that end without a finish reason or a final usage-only chunk now emit an
incomplete-streamerror instead of reporting success. Partial text remains available, and tests cover lifecycle cleanup, accepted completion signals, cancellation, and end-to-end behavior.Changes#
Chat Completions stream completion
packages/openai-base/src/adapters/chat-completions-text.ts,packages/openai-base/tests/chat-completions-incomplete-stream.test.ts,docs/chat/streaming.md,.changeset/short-streams-report-errors.md,docs/config.jsonRUN_ERRORwith codeincomplete-streamif the stream has no finish reason and no usage-only tail. Unit tests cover incomplete and accepted streams, lifecycle cleanup, and cancellation. Documentation and the changeset describe the handling.testing/e2e/src/routes/api.chat-completions-incomplete-stream.ts,testing/e2e/src/routeTree.gen.ts,testing/e2e/tests/chat-completions-incomplete-stream.spec.ts,testing/e2e/tests/openai-malformed-tool-arguments.spec.tsPriority: ➖ Normal
Estimated code review effort: 3 (Moderate) | ~20 minutes
Change: Bug fix · Severity of issue fixed: Medium
Suggested reviewers:
alemtuzlakMerge Risk: ⚪ Minimal · up to
e0e28The documentation date and test expectations do not present a merge-blocking risk. Live-provider compatibility remains unverified, but no failure is established.
Security Architecture Review#
Security architecture risk: 🔵 Low · up to
122c3The change strengthens failure containment: incomplete responses retain partial output but no longer authorize pending server tools through a successful completion. No introduced security concern was established in the inspected paths. Malformed-stream recovery and the test server’s deployment exposure remain incompletely verified.
Retained concerns No architecture-level concerns identified.
Security review details
Security Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
#1603]. The shared adapter retains partial output and closes open lifecycles. When nofinish_reasonand no final empty-choices usage chunk exist, it emits `R…#1603]. The adapter change implements incomplete Chat Completions detection. The unit tests, E2E route and tests, documentation, generated route metadata, and changeset verify…✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share