ai icon indicating copy to clipboard operation
ai copied to clipboard

`streamText`: `streamRetries` re-dials the provider immediately, with no delay, backoff or `retry-after` handling

Open mkondratek opened this issue 4 weeks ago • 6 comments

Description

maxRetries (request-start retries) uses retryWithExponentialBackoffRespectingRetryHeaders: 2 s, then 4 s, and it honours retry-after / retry-after-ms. streamRetries (retries for provider error events received after streaming has started) has none of that. When an error part arrives, streamText awaits onError, cancels the reader and calls the model again right away.

Some providers deliver overload as an SSE error event after a 200 instead of as an HTTP 529/503. Anthropic documents this: an in-stream overloaded_error event is the streaming form of the 529 response (https://docs.claude.com/en/build-with-claude/streaming#error-events), and their own SDK retries 5xx with exponential backoff (https://docs.claude.com/en/api/errors). OpenAI-compatible servers do the same with a {"error": {...}} frame.

So the same overload gets two different treatments depending on when it arrives:

  • as an HTTP status: retried after 2 s, then 4 s, retry-after respected;
  • as a stream error event: retried 3 times within a few milliseconds, every attempt hitting the same overload, then surfaced to the user.

In production we see all stream retries exhaust within roughly 100 ms against an overloaded provider. The retry budget is spent before the provider has had any chance to recover.

Relevant code in [email protected], packages/ai/src/generate-text/stream-text.ts (lines 2887-2925 in the published tarball; dist/index.js 9960-9977):

onErrorResult = await onError({ error });
// ...
const automaticRetry = !isToolChoiceViolation && automaticStreamRetryCount < streamRetries;
// ...
await languageModelStreamReader.cancel(error);
bufferedAttemptParts = [];
closeOpenAttemptParts();
retryLanguageModelCall = await callLanguageModel(); // immediately

prepareRetries({ parameter: 'streamRetries' }) builds the same backoff strategy as for maxRetries, but only its maxRetries count is used; the retry function is discarded.

Reproduction

Minimal script using the OpenAI-compatible provider with a custom fetch. The first response is a 200 whose first SSE frame is an error object; the second response succeeds. The timestamps show the gap between the two fetch calls.

import { streamText } from 'ai';
import { createOpenAICompatible } from '@ai-sdk/openai-compatible';

const sse = (payload: unknown) => `data: ${JSON.stringify(payload)}\n\n`;

const overloaded = sse({
  error: {
    message: 'Our servers are currently overloaded. Please try again later.',
    type: 'service_unavailable_error',
    code: 'server_is_overloaded',
    param: null,
  },
});

const chunk = (delta: unknown, finish: string | null = null) =>
  sse({
    id: 'cmpl-1',
    object: 'chat.completion.chunk',
    created: 1,
    model: 'test-model',
    choices: [{ index: 0, delta, finish_reason: finish }],
  });

const ok =
  chunk({ role: 'assistant', content: 'hello' }) +
  chunk({}, 'stop') +
  'data: [DONE]\n\n';

const bodies = [overloaded, ok];
const fetchTimes: number[] = [];

const fetchMock: typeof fetch = async () => {
  fetchTimes.push(performance.now());
  const body = bodies[Math.min(fetchTimes.length - 1, bodies.length - 1)];
  return new Response(body, {
    status: 200,
    headers: { 'content-type': 'text/event-stream' },
  });
};

const provider = createOpenAICompatible({
  name: 'test',
  baseURL: 'http://fake.local/v1',
  apiKey: 'test-key',
  fetch: fetchMock,
});

const result = streamText({
  model: provider('test-model'),
  prompt: 'say hello',
  streamRetries: 3,
  onError: ({ error }) => {
    console.log('onError:', (error as Error).message);
  },
});

let text = '';
for await (const part of result.textStream) text += part;

console.log('text:', text);
console.log('fetch calls:', fetchTimes.length);
console.log(
  'gap between fetch #1 and #2 (ms):',
  (fetchTimes[1] - fetchTimes[0]).toFixed(1),
);

Output with [email protected] and @ai-sdk/[email protected] (the code path is unchanged in [email protected]), Bun 1.x:

onError: Our servers are currently overloaded. Please try again later.
text: hello
fetch calls: 2
gap between fetch #1 and #2 (ms): 2.0

Change bodies to [overloaded, overloaded, overloaded, overloaded] to see all three retries land within a few milliseconds and the step end with the error.

(The same shape can be built with MockLanguageModelV4 from ai/test by enqueuing { type: 'error', error } as the first part; the custom-fetch version is kept here because it shows the real wire format.)

Expected behavior

Stream retries should wait between attempts the way request-start retries do: an exponential backoff (same defaults as maxRetries: 2 s initial, factor 2), honouring retry-after / retry-after-ms when the provider sends them, and abortable through abortSignal. onError should still be awaited before the wait, so applications can log or show status.

Ideally only retryable errors would consume the budget. StreamProviderError already carries isRetryable and statusCode; a deterministic error (invalid request, context window, auth) reproduces on every attempt and re-dialing it three times only adds load.

Proposed API

Reuse the existing retry strategy instead of adding a new one. prepareRetries already returns { maxRetries, retry } for streamRetries; the retry function could wrap the re-dial:

streamText({
  model,
  prompt,
  streamRetries: 3,
  // new, optional; defaults mirror maxRetries
  streamRetryDelay: {
    initialDelayInMs: 2000,
    backoffFactor: 2,
    respectRetryHeaders: true,
  },
});

Semantics:

  • Before each automatic re-dial, wait initialDelayInMs * backoffFactor ** (attempt - 1), or the provider's retry-after/retry-after-ms value when present and within the same 0-60 s bound the request-start strategy uses. The headers are available on the response of the failed attempt; for providers that carry a retry hint in the error payload, StreamProviderError.data could feed the same function.
  • abortSignal cancels the wait, as it does for request-start retries.
  • onError is awaited first, then the wait, then callLanguageModel().
  • Callback-directed retries (onError returning { retry: true }) get the same wait; a { retry: true, delayInMs } result could override it per call.
  • Default for the new option: the maxRetries defaults (2 s, factor 2). Passing { initialDelayInMs: 0 } restores the current immediate re-dial. If changing the default is considered a behavior change, default to 0 and document the recommendation.

Alternative: a single retryStrategy option covering both request-start and stream retries, in the spirit of retryWithExponentialBackoffRespectingRetryHeaders being exported from @ai-sdk/provider-utils:

streamText({
  model,
  prompt,
  maxRetries: 2,
  streamRetries: 3,
  retryStrategy: retryWithExponentialBackoffRespectingRetryHeaders({ initialDelayInMs: 1000 }),
});

This avoids a second set of knobs, but changes how maxRetries is configured today, so the first proposal is the smaller change.

Current workaround

Because onError is awaited before the re-dial, the only place to put a delay is inside onError:

let attempt = 0;
streamText({
  model,
  prompt,
  streamRetries: 3,
  onError: async ({ error }) => {
    attempt += 1;
    if (attempt <= 3 && looksTransient(error)) {
      await new Promise(r => setTimeout(r, Math.min(1000 * 2 ** (attempt - 1), 8000)));
    }
  },
});

This works but has problems: the counter has to be reset per step by hand (onStepStart), the callback cannot tell whether a retry will actually follow (errors that exhaust the budget, RetryError from request-start retries, tool-choice violations and transport failures all reach onError too), it cannot see retry-after, and an async onError is subject to the race in #23762 where the retry is skipped if the provider stream errors right after the error part.

Environment

  • ai: 7.0.162 (also reproduced on 7.0.136)
  • @ai-sdk/openai-compatible: current; the same applies to @ai-sdk/anthropic (4.0.78 checked: its stream parser maps the SSE error event to an error part)
  • Node.js 22, macOS; the code path is runtime-independent

Related: #18668 (origin of streamRetries), #23762 (async onError race), #22395 (same gap listed as out of scope for WorkflowAgent: "retries currently start immediately, like streamText").

mkondratek avatar Nov 04 '26 20:11 mkondratek

Identify issue type

Identified as Bug
Confidence: High

Rationale

The issue reports a concrete failure in existing retry behavior: immediate stream retries exhaust the retry budget before an overloaded provider can recover. The accompanying enhancement proposals do not supersede that bug report.

Evidence

  • A reproducible script shows streamText re-dialing an overloaded provider after approximately 2 ms, exhausting stream retries within roughly 100 ms in production.
  • Request-start retries apply exponential backoff and respect retry headers, but the stream retry path discards the retry strategy and immediately calls the model again.
  • The proposed API enhancements address this concrete retry failure.

ai-sdk-factory[bot] avatar Nov 04 '26 20:11 ai-sdk-factory[bot]

Identify bug discovery

Discovery source: discovery:usage (high confidence).

The author explicitly reports observing retry exhaustion against an overloaded provider in production. The source analysis and mock reproduction explain that reported production failure rather than establishing an audit origin.

  • The author states: “In production we see all stream retries exhaust within roughly 100 ms against an overloaded provider.”
  • They describe the observed consequence: “The retry budget is spent before the provider has had any chance to recover.”
  • The minimal custom-fetch reproduction is presented separately from the production observation and demonstrates the same immediate-retry behavior.

ai-sdk-factory[bot] avatar Nov 04 '26 20:11 ai-sdk-factory[bot]

Bug Reproduction - AI SDK 7

Bug was reproduced.

Branch: main PR: successful reproduction pull request

Details

  • examples/ai-functions/src/reproduction/issue-24524.ts reproduces retry-budget exhaustion on workspace [email protected]: four streaming attempts complete within 3 ms, producing a terminal error and no text before the model’s 2.5-second recovery window.
  • Expected backoff would preserve retries long enough to recover; the request-start control succeeds with hello after approximately 2- and 4-second waits.
  • Stream response headers retry-after and retry-after-ms, and callback-directed retries, likewise fail to allow recovery.
  • An awaited delay inside onError successfully recovers; nonretryable stream errors still consume all three automatic retries.
  • packages/ai/src/generate-text/stream-text.ts discards the prepared stream retry function and immediately re-dials; upgrading to the checked-out version does not resolve the behavior.
  • Coverage is core-library-only: live providers, the reported Node 22/Bun environments, the separate async-callback race, and cancellation during a retry wait were not verified; retries finish before the scheduled abort.

Relevant Documentation

  • https://platform.claude.com/docs/en/build-with-claude/streaming
  • https://platform.claude.com/docs/en/api/errors
  • https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text

ai-sdk-factory[bot] avatar Nov 10 '26 14:11 ai-sdk-factory[bot]

Hey @mkondratek, thanks for putting together the wire reproduction and tracing this in production!

I spent some time tracing the in-stream retry path against commit f9d43bdaa7 on main:

1. Why the re-dial happens immediately:
In stream-text.ts, prepareRetries({ parameter: 'streamRetries' }) constructs the backoff strategy, but the stream loop only extracts the numeric streamRetries count and discards the backoff helper. When a provider emits an in-stream { type: 'error' } part (like Anthropic's overloaded_error or OpenAI's server_is_overloaded), streamText cancels the active reader and calls callLanguageModel() immediately in the next microtask without inspecting response.headers for retry-after or applying exponential backoff.

2. Handling backoff and consumer cancellation safely:
Injecting an abortable delay before callLanguageModel() using the standard 2s / 2x exponential schedule and parsing retry-after-ms / retry-after (with case-insensitive matching across both error.responseHeaders and response.headers) gives overloaded providers time to recover.

To prevent zombie re-dials, the delay also needs to be interrupted if the downstream consumer cancels the stream directly (cancel()) while a retry wait is in progress.

3. Blast radius & scope boundary:
I deliberately kept this change surgically scoped to the missing delay and header inspection:

  • It does not change retry eligibility or gate on isRetryable, keeping it completely compatible with @n1ckoates' active PR #24785 for sibling #24525.
  • It does not alter nested request-start maxRetries budgets inside callLanguageModel() (as discussed in #24715).

I put together a minimal reproduction test and verified patch on my fork here:

Happy to open a PR or share the test suite if helpful!

jadibdev avatar Nov 10 '26 18:11 jadibdev

Bugfix - AI SDK 7

Created bugfix and opened PR: #24876

Root Cause

The stream retry path used only the prepared retry count, discarded its backoff strategy, and immediately called the model again. Code inspection and the reproduction confirmed missing delays and ignored retry headers.

Summary

Added abortable exponential backoff and retry-header handling for automatic and callback-directed stream retries, preserving retry eligibility. Added an ai patch changeset. Replaced an expensive Mistral test buffer comparison with exact Buffer.equals verification to resolve the full-suite timeout without reducing coverage.

Testing

Added regression coverage for exponential delays, retry headers, callback ordering, aborts, and consumer cancellation. Updated timeout tests for delayed retries. Mistral tests pass with full byte-comparison coverage retained.

ai-sdk-factory[bot] avatar Nov 10 '26 20:11 ai-sdk-factory[bot]

:rocket: Published in:

Package Version
ai 7.0.187 github npm
@ai-sdk/alibaba 2.0.97 github npm
@ai-sdk/amazon-bedrock 5.0.152 github npm
@ai-sdk/angular 3.0.187 github npm
@ai-sdk/anthropic 4.0.113 github npm
@ai-sdk/anthropic-aws 2.0.106 github npm
@ai-sdk/assemblyai 3.0.91 github npm
@ai-sdk/azure 4.0.135 github npm
@ai-sdk/baseten 2.1.78 github npm
@ai-sdk/black-forest-labs 2.0.91 github npm
@ai-sdk/bytedance 2.0.92 github npm
@ai-sdk/cartesia 3.0.82 github npm
@ai-sdk/cerebras 3.0.99 github npm
@ai-sdk/code-mode 1.0.144 github npm
@ai-sdk/cohere 4.0.90 github npm
@ai-sdk/deepgram 3.1.60 github npm
@ai-sdk/deepinfra 3.0.99 github npm
@ai-sdk/deepseek 3.0.93 github npm
@ai-sdk/devtools 1.0.91 github npm
@ai-sdk/elevenlabs 3.0.92 github npm
@ai-sdk/fal 3.0.90 github npm
@ai-sdk/fireworks 3.0.102 github npm
@ai-sdk/fish-audio 3.0.65 github npm
@ai-sdk/gateway 4.0.160 github npm
@ai-sdk/gladia 3.0.88 github npm
@ai-sdk/gmicloud 3.0.70 github npm
@ai-sdk/google 4.0.130 github npm
@ai-sdk/google-vertex 5.0.151 github npm
@ai-sdk/groq 4.0.90 github npm
@ai-sdk/harness 1.0.199 github npm
@ai-sdk/harness-acp 1.0.139 github npm
@ai-sdk/harness-claude-code 1.0.203 github npm
@ai-sdk/harness-cline 1.0.127 github npm
@ai-sdk/harness-codex 1.0.201 github npm
@ai-sdk/harness-cursor 1.0.114 github npm
@ai-sdk/harness-deepagents 1.0.199 github npm
@ai-sdk/harness-fx 1.0.116 github npm
@ai-sdk/harness-github-copilot 1.0.96 github npm
@ai-sdk/harness-grok-build 1.0.138 github npm
@ai-sdk/harness-opencode 1.0.202 github npm
@ai-sdk/harness-pi 1.0.202 github npm
@ai-sdk/heygen 3.0.31 github npm
@ai-sdk/huggingface 2.0.99 github npm
@ai-sdk/hume 3.0.87 github npm
@ai-sdk/klingai 4.0.91 github npm
@ai-sdk/langchain 3.0.187 github npm
@ai-sdk/liquid 3.0.5 github npm
@ai-sdk/llamaindex 3.0.187 github npm
@ai-sdk/luma 3.0.90 github npm
@ai-sdk/mcp 2.0.108 github npm
@ai-sdk/minimax 3.0.90 github npm
@ai-sdk/mistral 4.0.93 github npm
@ai-sdk/moonshotai 3.0.99 github npm
@ai-sdk/open-responses 2.0.93 github npm
@ai-sdk/openai 4.0.127 github npm
@ai-sdk/openai-compatible 3.0.98 github npm
@ai-sdk/otel 1.0.187 github npm
@ai-sdk/parallel 3.0.15 github npm
@ai-sdk/perplexity 5.0.41 github npm
@ai-sdk/policy-opa 1.0.187 github npm
@ai-sdk/prodia 2.0.90 github npm
@ai-sdk/provider 4.0.40 github npm
@ai-sdk/provider-utils 5.0.87 github npm
@ai-sdk/quiverai 2.0.89 github npm
@ai-sdk/react 4.0.192 github npm
@ai-sdk/replicate 3.0.90 github npm
@ai-sdk/revai 3.0.87 github npm
@ai-sdk/rsc 3.0.187 github npm
@ai-sdk/sandbox-just-bash 1.0.199 github npm
@ai-sdk/sandbox-vercel 1.0.199 github npm
@ai-sdk/scaledown 3.0.7 github npm
@ai-sdk/subquadratic 3.0.0 github npm
@ai-sdk/svelte 5.0.187 github npm
@ai-sdk/tencent 3.0.9 github npm
@ai-sdk/togetherai 3.0.100 github npm
@ai-sdk/tool-bash 1.0.41 github npm
@ai-sdk/tool-web-fetch 1.0.37 github npm
@ai-sdk/topaz 3.0.34 github npm
@ai-sdk/tui 1.0.188 github npm
@ai-sdk/typesafe-ai 3.0.46 github npm
@ai-sdk/valibot 3.0.87 github npm
@ai-sdk/voyage 2.0.89 github npm
@ai-sdk/vue 4.0.187 github npm
@ai-sdk/workflow 2.0.119 github npm
@ai-sdk/workflow-harness 1.0.199 github npm
@ai-sdk/xai 5.0.54 github npm
@ai-sdk/zai 3.0.61 github npm

github-actions[bot] avatar Dec 01 '26 17:12 github-actions[bot]