fix(ai): keep retryAfterMs and HTTP status on a rejected chat() #2301
main fromrefs/pull/2301/head·opened View on GitHubFixes #2294
chat({ stream: false }) and chat({ outputSchema }) reject with an Error that drops retryAfterMs. A caller that awaits chat() cannot honor Retry-After. When the provider body sets code to rate_limit_exceeded, that Error also has no HTTP status.
streamToText() built the Error from the RUN_ERROR and kept only message, code, and rawEvent. chat() had already moved retryAfterMs, errorType, and requestId onto metadata.tanstack. The structured-output path built a second Error from message and code only.
Both paths now copy those fields, plus rawEvent and rawText, onto the thrown Error. status is the numeric HTTP status from the SDK error, including when code stays the provider code. Adapters that already spread toRunErrorDetails() put status on the RUN_ERROR, and chat() moves it to metadata.tanstack.status.
There is no new error class. Callers read the fields the same way they already read code and rawText.
🎯 Changes#
runErrorEventToErrorcopiesretryAfterMs,errorType,requestId,rawText, andstatusfrom the chunk or frommetadata.tanstack.chat({ outputSchema })stores those fields on the finalization error and throws the same Error shape. The non-streaming structured-output fallback fills them from the thrown SDK error.toRunErrorDetailsalso returns a numeric HTTPstatus.
✅ 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.
🚀 Release Impact#
- This change affects published code, and I have generated a changeset.
- This change is docs/CI/dev-only (no release).
Root cause#
The RUN_ERROR already carried the wait (retryAfterMs), the provider error type, and the request id. chat() moves those extras onto metadata.tanstack before a caller iterates the stream. The Error thrown for stream: false did not read them. The Error thrown for outputSchema was built again from message and code, so it also dropped rawEvent. code prefers the provider body (rate_limit_exceeded) over the HTTP status, and nothing else kept the status.
Testing#
packages/ai/tests/chat-run-error-fields.test.ts awaits chat({ stream: false }) and chat({ outputSchema }) on a mocked 429. Before this change the text path kept code and rawEvent and dropped retryAfterMs, errorType, requestId, and status (3 failed). The structured-output path kept only code. After this change those fields are on the Error, including when the structured-output call itself throws. toRunErrorDetails accepts status 429 and 529 and ignores a string status.
Commands that passed:
vitest run tests/chat-run-error-fields.test.ts tests/run-error-details.test.ts tests/stream-to-response.test.ts tests/chat-retry.test.ts tests/structured-output-middleware.test.ts(102 passed).vitest runof the new file,run-error-details, and the stream-processoronErrorcases (13 passed, 284 skipped).- Full
vitest runinpackages/ai(172 files, 2892 passed), and theopenai-base,ai-anthropicandai-openroutersuites (all passed), since those adapters spreadtoRunErrorDetails()into theirRUN_ERROR. tsc --noEmitinpackages/ai.oxlinton the touched sources (existinganywarnings only).
Not run: pnpm run test:pr and the full E2E suite.
Reproduction#
Mock every request as HTTP 429 with retry-after: 42 and a JSON body whose error.code is null or rate_limit_exceeded. Await chat({ stream: false }) and chat({ outputSchema }) with maxRetries: 0. No network and no API key. The thrown Error has retryAfterMs 42000. With a provider code, code stays rate_limit_exceeded and status is 429.
This change was prepared with assistance from an AI coding tool.
Summary by CodeRabbit#
- Bug Fixes
- Non-streaming and structured-output chat errors now preserve rate-limit and provider details, including retry timing, error type, request ID, raw response data, and HTTP status.
- Middleware also receives retry timing when these errors occur.
- Documentation
- Added guidance on handling rate-limit errors and checking HTTP status and retry timing.
- 1
pcbeingused33(GitHub profile, opens in a new tab) linked this to fix #2294
No actionable comments were generated in the recent review.
Walkthrough
-
Chat error paths now retain provider details, including retry timing and HTTP status, when non-streaming and structured-output calls reject. Run-error conversion reads details from events and TanStack metadata. Tests and documentation cover the updated fields.
Changes: Chat error details
Layer / File(s) Summary HTTP status extraction and event fields
packages/ai/src/activities/error-payload.ts,packages/ai/src/types.tsError payload extraction includes integer HTTP statuses from 100 through 599. Run metadata and RunErrorEventadd an optional numericstatusfield.Shared run-error conversion
packages/ai/src/utilities/errors.tsrunErrorEventToErrorreads provider details from the event, with TanStack metadata as fallback.errorFromRunDetailsbuilds errors with defined detail fields.Chat finalization and fallback errors
packages/ai/src/activities/chat/index.tsChat finalization records provider details and uses them to construct errors. Synthesized fallback RUN_ERRORevents include available provider error details.Error-field tests and documentation
packages/ai/tests/*run-error*,docs/chat/stream-events.md,.changeset/chat-reject-keeps-retry-after.mdTests check retained error fields and status validation. Documentation and the changeset describe details available on rejected chat calls. Estimated code review effort: 3 (Moderate) | ~20 minutes
Change: Bug fix · Severity of issue fixed: Medium
Suggested reviewers:
alemtuzlak,jsonkim,jan-kubica
Merge Risk:
Minimal · up to1d4e8-
Rejected non-streaming and structured-output chat() calls now keep retry timing, error type, request ID, raw event and numeric HTTP status on the thrown error. The change only adds optional fields and does not alter retry behavior. No merge-blocking risk was identified.
Pre-merge checks:
4-
Check name Status Explanation Title check The title names the main change: chat() rejections keep retryAfterMs and the HTTP status on the thrown Error. The changeset covers the stream:false and outputSchema paths, and the code adds status to … Description check The description follows the template. It has a Changes section, a checklist, and a Release Impact section. Its checklist marks docs, changeset, and contributing-guide items as done. The description al… Linked Issues check Issue #2294requires that the Error rejected bychat({ stream: false })andchat({ outputSchema })carryretryAfterMs,errorType,requestId,rawEvent, and an HTTP status field separate fro…Out of Scope Changes check All changed files relate to the #2294objective or support it:
-packages/ai/src/utilities/errors.ts,packages/ai/src/activities/chat/index.ts,packages/ai/src/activities/error-payload.ts: imple…Full details: Title check
-
Explanation
The title names the main change: chat() rejections keep retryAfterMs and the HTTP status on the thrown Error. The changeset covers the stream:false and outputSchema paths, and the code adds status to toRunErrorDetails and RUN_ERROR handling. The title is specific and accurate.
Full details: Description check
-
Explanation
The description follows the template. It has a Changes section, a checklist, and a Release Impact section. Its checklist marks docs, changeset, and contributing-guide items as done. The description also explains the root cause, the testing done, and a reproduction. The one gap is that the unchecked test:pr box is explained only by the note that pnpm run test:pr was not run, and the author does not say why that command was skipped.
Full details: Linked Issues check
-
Explanation
Issue
#2294requires that the Error rejected bychat({ stream: false })andchat({ outputSchema })carryretryAfterMs,errorType,requestId,rawEvent, and an HTTP status field separate fromcode.The reviewed changes cover each requirement on both paths:
runErrorEventToErrorinpackages/ai/src/utilities/errors.tscopiesretryAfterMs,errorType,requestId,rawText, andstatusfrom theRUN_ERRORchunk or itsmetadata.tanstackfallback. This path serveschat({ stream: false })throughstreamToText().chat({ outputSchema })inpackages/ai/src/activities/chat/index.tsstores these fields on the finalization error. The non-streaming structured-output fallback fills them from the thrown SDK error. The sharederrorFromRunDetailshelper builds the Error, andrawEventis retained.toRunErrorDetailsinpackages/ai/src/activities/error-payload.tsreturns a numericstatuswhen the SDK error has an integer status from 100 through 599.codekeeps the provider value, sostatusremains available whencodeisrate_limit_exceeded.packages/ai/tests/chat-run-error-fields.test.tscovers both chat paths with a mocked 429 and asserts the fields.run-error-details.test.tscovers status retention and rejection of invalid statuses.
The PR does not change retry policy, which the issue does not require. The exported helper and error shape are optional suggestions in the issue, and the PR meets the stated requirements without a new error class.
The assessment relies on the whole-PR summary and the PR description. I did not inspect the source hunks directly, so the verdict assumes the summarized behavior matches the code.
Full details: Out of Scope Changes check
-
Explanation
All changed files relate to the
#2294objective or support it:packages/ai/src/utilities/errors.ts,packages/ai/src/activities/chat/index.ts,packages/ai/src/activities/error-payload.ts: implement field propagation on the rejectedchat()paths and the numericstatus.packages/ai/src/types.ts: adds the optionalstatusfield toRunErrorEventandTanStackRunMetadata, and revises thecodeandretryAfterMsdocumentation the issue identifies as inaccurate.packages/ai/tests/chat-run-error-fields.test.tsandpackages/ai/tests/run-error-details.test.ts: test the new behavior.docs/chat/stream-events.mdand.changeset/chat-reject-keeps-retry-after.md: document the behavior and release it, as the repository requires for published packages.
No file changes retry behavior or unrelated features.
-
Finishing Touches
-
Generate unit tests (beta)
-
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
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.
Recent review info-
Run configuration-
- Source mode: Auto
- Repository: TanStack/ai
- Branch: main
- File: .coderabbit.yaml
- Commit: 840ea56
- Layers: Repository YAML
- Review profile: CHILL
- Plan: Advanced
- Run ID:
93927594-0f8d-483b-a4b6-481ad976d2a2
Commits-
Reviewing files that changed from the base of the PR and between 840ea56621f4c32de4359849a0beaa343db60fe3 and 1d4e868734f70caf76899cea23b7e377bfed2b39.
Files selected for processing: 8-
.changeset/chat-reject-keeps-retry-after.mddocs/chat/stream-events.mdpackages/ai/src/activities/chat/index.tspackages/ai/src/activities/error-payload.tspackages/ai/src/types.tspackages/ai/src/utilities/errors.tspackages/ai/tests/chat-run-error-fields.test.tspackages/ai/tests/run-error-details.test.ts
Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.
-
-
tanstack-source added labelsbug
github-actions[bot](GitHub profile, opens in a new tab) assignedjherr
Thanks for the PR, @pcbeingused33! 🙌 @jherr will take a look.
Automated pre-review checks
- ✅ CI passing
- ✅ No merge conflicts
- ✅ Changeset present
- ⚠️ No E2E test changes detected — behavior changes need coverage under
testing/e2e/(see CONTRIBUTING)
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
Sign in to join this conversation.
🦋 Changeset detected#
Latest commit: 1d4e868734f70caf76899cea23b7e377bfed2b39
The changes in this PR will be included in the next version bump.
This PR includes changesets to release 2 packages
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