Skip to content
Source
Sign inSign up
TanStack/ai

fix(ai): keep retryAfterMs and HTTP status on a rejected chat() #2301

Openpcbeingused33(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromrefs/pull/2301/headopened View on GitHub

pcbeingused33(GitHub profile, opens in a new tab)commented

Fixes #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

  • runErrorEventToError copies retryAfterMs, errorType, requestId, rawText, and status from the chunk or from metadata.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.
  • toRunErrorDetails also returns a numeric HTTP status.

✅ 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 run of the new file, run-error-details, and the stream-processor onError cases (13 passed, 284 skipped).
  • Full vitest run in packages/ai (172 files, 2892 passed), and the openai-base, ai-anthropic and ai-openrouter suites (all passed), since those adapters spread toRunErrorDetails() into their RUN_ERROR.
  • tsc --noEmit in packages/ai.
  • oxlint on the touched sources (existing any warnings 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. 🦋 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
      NameType
      @tanstack/aiPatch
      @tanstack/ai-optimize-evalsPatch

      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

    2. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      Explain Change →

      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.ts
      Error payload extraction includes integer HTTP statuses from 100 through 599. Run metadata and RunErrorEvent add an optional numeric status field.
      Shared run-error conversion
      packages/ai/src/utilities/errors.ts
      runErrorEventToError reads provider details from the event, with TanStack metadata as fallback. errorFromRunDetails builds errors with defined detail fields.
      Chat finalization and fallback errors
      packages/ai/src/activities/chat/index.ts
      Chat finalization records provider details and uses them to construct errors. Synthesized fallback RUN_ERROR events 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.md
      Tests 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 to 1d4e8

      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: Passed 4

      Check nameStatusExplanation
      Title checkPassedThe 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 checkPassedThe 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 checkPassedIssue #2294 requires that the Error rejected by chat({ stream: false }) and chat({ outputSchema }) carry retryAfterMs, errorType, requestId, rawEvent, and an HTTP status field separate fro…
      Out of Scope Changes checkPassedAll changed files relate to the #2294 objective 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 #2294 requires that the Error rejected by chat({ stream: false }) and chat({ outputSchema }) carry retryAfterMs, errorType, requestId, rawEvent, and an HTTP status field separate from code.

      The reviewed changes cover each requirement on both paths:

      • runErrorEventToError in packages/ai/src/utilities/errors.ts copies retryAfterMs, errorType, requestId, rawText, and status from the RUN_ERROR chunk or its metadata.tanstack fallback. This path serves chat({ stream: false }) through streamToText().
      • chat({ outputSchema }) in packages/ai/src/activities/chat/index.ts stores these fields on the finalization error. The non-streaming structured-output fallback fills them from the thrown SDK error. The shared errorFromRunDetails helper builds the Error, and rawEvent is retained.
      • toRunErrorDetails in packages/ai/src/activities/error-payload.ts returns a numeric status when the SDK error has an integer status from 100 through 599. code keeps the provider value, so status remains available when code is rate_limit_exceeded.
      • packages/ai/tests/chat-run-error-fields.test.ts covers both chat paths with a mocked 429 and asserts the fields. run-error-details.test.ts covers 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 #2294 objective 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 rejected chat() paths and the numeric status.
      • packages/ai/src/types.ts: adds the optional status field to RunErrorEvent and TanStackRunMetadata, and revises the code and retryAfterMs documentation the issue identifies as inaccurate.
      • packages/ai/tests/chat-run-error-fields.test.ts and packages/ai/tests/run-error-details.test.ts: test the new behavior.
      • docs/chat/stream-events.md and .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.

      Share

      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.md
      • docs/chat/stream-events.md
      • packages/ai/src/activities/chat/index.ts
      • packages/ai/src/activities/error-payload.ts
      • packages/ai/src/types.ts
      • packages/ai/src/utilities/errors.ts
      • packages/ai/tests/chat-run-error-fields.test.ts
      • packages/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.

    3. tanstack-source added labelsbug

    4. 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)
      Automated triage — a human review follows.
    5. github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer

Sign in to join this conversation.