WorkflowAgent: a model stream that fails or stalls after it opens always ends the run (no stream-level recovery)
Description
When a WorkflowAgent model call fails after its response stream opened, or the stream stops producing chunks, nothing retries it. In a long durable run this throws away all the work done so far over one transient fault. That holds even when the error is classified retryable and maxRetries is set. I'm filing this as a design discussion. Part of the behaviour is intentional (#18827). Part of it looks like a side effect of #18873. And the pieces needed to recover safely already exist in the package.
Versions: @ai-sdk/[email protected], [email protected], @ai-sdk/[email protected], [email protected]. The relevant files are identical on main (e00b1b14e).
Measured in real durable runs (@workflow/vitest, local world). Attempt 1 fails as described; attempt 2 would succeed. maxRetries: 2:
| failure after the stream opened | result | model calls |
|---|---|---|
read throws (socket drop after 200: provider-utils yields APICallError, isRetryable: true) |
step fails failed after 0 retries, run fails |
1 |
{ type: 'error' } part (normalized to StreamProviderError, isRetryable: true) |
loop ends; result.error set, finishReason: 'error' |
1 |
stream goes silent, no timeout |
step waits until the platform kills the invocation | 1 |
stream goes silent, timeout: 2000 |
call aborted; stream() resolves with 0 steps and no error |
1 |
| control: dispatch rejects with 503 | retried in-step, succeeds | 3 |
Reproduction
Plain Node, no workflow runtime needed (same shape as #22073):
import { WorkflowAgent } from '@ai-sdk/workflow';
import { APICallError } from '@ai-sdk/provider';
import { MockLanguageModelV4 } from 'ai/test';
const usage = { inputTokens: { total: 1, noCache: 1 }, outputTokens: { total: 1, text: 1 } };
const head = [
{ type: 'stream-start', warnings: [] },
{ type: 'text-start', id: 't' },
{ type: 'text-delta', id: 't', delta: 'partial ' },
];
const okStream = () => new ReadableStream({ start(c) {
for (const p of [...head, { type: 'text-end', id: 't' },
{ type: 'finish', finishReason: { unified: 'stop', raw: 'stop' }, usage }]) c.enqueue(p);
c.close();
} });
let calls = 0;
const model = new MockLanguageModelV4({
doStream: async () => ({
stream: ++calls > 1 ? okStream() : new ReadableStream({ start(c) {
for (const p of head) c.enqueue(p);
// what @ai-sdk/provider-utils produces when the socket drops after HTTP 200
setTimeout(() => c.error(new APICallError({
message: 'Failed to process successful response', url: 'https://x',
requestBodyValues: {}, statusCode: 200, isRetryable: true,
})), 10);
} }),
}),
});
const agent = new WorkflowAgent({ model, maxRetries: 2 });
await agent.stream({ messages: [{ role: 'user', content: 'hi' }] })
.catch(e => console.log(e.name, e.isRetryable)); // AI_APICallError true
console.log({ calls }); // { calls: 1 }
Swapping the throw for { type: 'error', error: { message: 'Service temporarily unavailable', statusCode: 503 } } followed by a finish part gives result.error = AI_StreamProviderError (isRetryable: true) after 1 call. Inside a workflow the thrown case ends the run with FatalError: Step "…doStreamStep" failed after 0 retries: Failed to process successful response. The client stream receives reset-step, model-call-start, text-start, text-delta, finish: no error chunk, and the text part is never closed.
Where it comes from
packages/workflow/src/do-stream-step.ts:131-190:prepareRetrieswraps onlystreamModelCall(...), which resolves once the response opens. The read loop (:230) rethrows (:438-443).do-stream-step.ts:471-473:doStreamStep.maxRetries = 0, from #18873, so retry layers do not stack. Before 1.0.68 the step had nomaxRetries, and the runtime's default of 3 step retries covered a read that threw. The layers only overlapped on dispatch errors, so for read errors removing the step layer left no retry at all. That conflicts with the reference doc formaxRetries: "How many times to retry retryable model-call failures" (01-workflow-agent.mdx:443).do-stream-step.ts:429-436: error parts become terminal data on purpose (#18827, and the integration test "surfaces stream error data without retrying the model step").do-stream-step.ts:57-72: the only timer is the absolutetimeoutAt. WithmaxRetries = 0, a model step that the platform kills mid-stall also cannot be re-run.@workflow/corestep-executor.ts:548-575fails the redelivered step withexceeded max retries (0 retries).
Why recovery is cheaper here than it was for streamText
streamText needed streamRetries (#18718) with careful attempt isolation, because tools can run while the stream is consumed. In WorkflowAgent the model step only accumulates: tool calls execute in separate steps after doStreamStep returns (workflow-agent.ts executeTool). Retrying a failed attempt therefore only needs the step's local accumulators reset. No client-side tool from the failed attempt can have run. Provider-executed tools are the exception, with the same caveat streamText documents. Two more pieces already exist:
reset-step(#18843) makes the client drop the parts of an invalidated attempt, anddoStreamStepalready writes it before each attempt (:225-228).- Classification exists too:
StreamProviderError.isRetryablefor error parts, andAPICallError/GatewayError.isRetryablefor thrown reads (#19890).
Proposal
A streamRetries?: number option on WorkflowAgent (constructor and stream()). It would sit next to maxRetries, with streamText's semantics: omitted means today's behaviour. It would cover:
- a thrown, retryable read error after the stream opened;
- an
errorpart whose error is retryable; - if #22090 lands, a
firstChunkMs/chunkMsexpiry. A stalled stream is the most common transient case, and ending the run on it gives no recovery.
There are two ways to place it:
- A, inside the step (smallest change). Loop over open+consume in
doStreamStep: reset the accumulators, writereset-step, back off with the existingretryWithExponentialBackoffRespectingRetryHeaders. The downside is that the backoff runs in-process, so it burns function time and counts towardmaxDuration. And because callbacks cannot cross the step boundary, the decision can only useisRetryable. - B, in the iterator (durable).
doStreamStepreturns a stream failure as data, the wayterminalErroralready works. That preserves error identity and adds no step retry.modelCallIteratorthen decides in workflow context, whereonErrorcan return{ retry: true }as it does forstreamText, and waits with the workflowsleep(), which costs no compute. It then callsdoStreamStepagain, as a fresh step that starts withreset-step.doStreamStep.maxRetries = 0stays, so layers never stack, and the budget stays per call.
We have run a version of B in production for about six weeks, as a patch on 1.0.30 that uses durable RetryableError backoff. Two lessons came out of it:
- A long durable backoff matters. In our experience, gateway or provider 5xx episodes last tens of seconds to minutes. Durable sleep makes a budget of several minutes free, while the in-step default (2 s, then 4 s) rarely outlasts one of these episodes.
- Status-based
isRetryableis not enough to decide. Some failures that are deterministic for a given prompt reach us as 5xx through a gateway: content-moderation refusals, and provider-specific "invalid request" errors wrapped as 500. Retrying the identical prompt only adds minutes of dead air before the real error surfaces. A caller-side veto, which B'sonErrorgives for free, has paid for itself.
Production impact (ours, aggregate)
- On an earlier engine version, one transient gateway 5xx ended an agent run that had been working for 41 minutes (file writes, a deploy). In one 15-day window, 2 of the 7 run-ending provider failures were transient gateway errors that a few minutes of backoff would have absorbed.
- We have seen model calls wait 1.5–3.5 minutes with no output and no error. In the cases we traced, the wait came before the response opened, which only a per-step deadline covers (#17314). For stalls after the stream opens, we run an idle watchdog that aborts the step so it is retried: 120 s allowed between chunks, 300 s before the first.
- The opposite risk is just as real. During two incidents, 7 and 11 runs per day spent about 6 minutes each retrying a failure that could not succeed (a withdrawn model id, a provider content filter) before the run stopped. So whatever form recovery takes, it needs a classification hook.
Related
#18667 / #18668 / #18718 (streamRetries, streamText only), #19890 (body errors retryable; partial attempts deliberately not retried), #18823 / #18873 (maxRetries effective; doStreamStep.maxRetries = 0), #18824 / #18827 (error parts terminal), #18481 / #18843 (reset-step), #22073 / #22090 (WorkflowAgent chunk timeouts, which currently end the call), #17314 (firstChunkMs is armed only after the response opens, so a request whose headers never arrive is covered only by stepMs), #12595.
Side observation, not investigated further: when stream() fails with an execution error, closeOutput still writes finish (workflow-agent.ts:3195-3203) and no error chunk, so the client renders the truncated answer as complete.
Identify issue type
Identified as Bug
Confidence: High
Rationale
The issue demonstrates concrete current failures in retry and stream termination behavior, including a documented retry option not applying to post-open stream failures. Although it proposes a new streamRetries option, the underlying report is broken existing behavior, so it is classified as a bug.
Evidence
- With
maxRetries: 2, retryable errors after the response stream opens make only one model call and can terminate the durable run. - The report provides a reproducible case where a retryable
APICallErrorduring stream consumption is rethrown outside the retry wrapper. - This conflicts with the documented
maxRetriesbehavior of retrying retryable model-call failures. - Retryable stream error parts are treated as terminal data, while stalled streams either hang or resolve without an error after timeout.
Bug Reproduction - AI SDK 7
Bug was reproduced.
Branch: main
PR: successful reproduction pull request
Details
- Added
examples/ai-functions/src/reproduction/issue-22379-workflow-agent-stream-retries.ts, covering retryable read failures, retryable error parts, silent streams, timeout behavior, dispatch retries, and emitted chunk types. - A retryable post-open
APICallErrormade one model call and rejected the run instead of retrying and completing the successful second attempt. - A retryable error part made one model call and returned
AI_StreamProviderErrorwithfinishReason: 'error'instead of retrying. - A silent stream remained pending without a timeout; with a 50 ms timeout it resolved after one call with zero steps and no error.
- The dispatch-failure control retried twice and succeeded on its third call, confirming
maxRetriesapplies before stream consumption. - The rejected read emitted
reset-step,model-call-start,text-start,text-delta, andfinish, but no error or text-end chunk.
Relevant Documentation
- https://ai-sdk.dev/docs/reference/ai-sdk-workflow/workflow-agent
- https://ai-sdk.dev/docs/ai-sdk-core/error-handling
Bugfix - AI SDK 7
Created bugfix and opened PR: #22395
Root Cause
doStreamStep wrapped only model dispatch in prepareRetries; stream consumption occurred outside that boundary, while retryable error parts were returned as terminal data and durable step retries were disabled. The original reproduction confirmed both post-open failure paths made only one call.
Summary
Extended the existing model-call retry boundary through stream consumption, reset per-attempt state and streamed output, retried retryable StreamProviderError parts, and preserved the final terminal error when retries are exhausted. Added a workflow patch changeset.
Testing
Added regression tests for retryable stream-read failures, retryable provider error parts, attempt-state reset, successful recovery, and exhausted error-part retries.
Thanks for writing up the failure table. I turned it into a known-answer matrix (expected result written down before running) and ran it against main (5a3c13c) and the #22395 head (d08bbea), with maxRetries: 2.
| scenario | expected | main | #22395 | |
|---|---|---|---|---|
| S1 | read throws after 200 (isRetryable: true), attempt 2 ok |
2 calls, resolves with attempt 2 text | fail: 1 call, rejects AI_APICallError, ends in bare finish |
pass: 2 calls, resolves stop, 2046 ms |
| S2 | { type: 'error' } part (503), attempt 2 ok |
2 calls, resolves, no error | fail: 1 call, result.error AI_StreamProviderError, finishReason: 'error' |
pass: 2 calls, resolves stop, 2010 ms. Attempt 1 error chunk still written before reset-step |
| S3 | read throws, isRetryable: false (your side observation) |
1 call, rejects, error chunk instead of bare finish |
fail: 1 call, rejects, …text-delta, finish, no error chunk |
fail: same as main |
| S4 | content filter refusal sent as retryable 500, every attempt (your "opposite risk") | your requested behaviour: caller veto, 1 call, no backoff. No veto hook exists | 1 call, 1 ms, only because main never retries after open | fail: 3 calls, 6026 ms, rejects AI_RetryError. onError fires once, after retries, returns void |
| S5a | read throws (retryable) on every attempt | 3 calls, failure surfaced with error chunk, no duplicated text |
fail: 1 call, rejects, no error chunk |
fail: 3 calls, 6030 ms, no duplicated text, but rejects AI_RetryError, no error chunk, bare finish |
| S5b | error part (503) on every attempt |
as S5a | fail: 1 call | pass: 3 calls, 6027 ms, result.error AI_StreamProviderError, error chunks, no duplicated text |
| S6 | stream goes silent, timeout: 50 |
your view: no silent success with 0 steps (code treats the resolve as intended) | resolves, 0 steps, no error, 54 ms | same as main, 64 ms |
Takeaways:
- #22395 fixes the two retryable paths after open: S1, S2 and S5b recover or fail cleanly within
maxRetries, onereset-stepper attempt, no duplicated text. - It misses the terminal signal. Thrown failures (S3, S5a) still end in a bare
finishwith noerrorchunk, exhausted thrown reads now reject asAI_RetryErrorinstead of the originalAPICallError, and in S2 the attempt 1errorchunk reaches the client beforereset-step. - The classification hook you asked for is not there, so a deterministic 5xx now costs 3 calls and about 6 s of in-step backoff by default.
Matrix test (plain Node, MockLanguageModelV4, no keys)
Copied to packages/workflow/src/ in both trees, then pnpm exec vitest --config vitest.node.config.js --run src/issue-22379-matrix.test.ts.
// Known-answer scenario matrix for vercel/ai#22379.
// Each scenario states the EXPECTED correct outcome first, then measures:
// model calls, resolve/reject, result.error, chunk types on the writable, wall time.
import { APICallError } from '@ai-sdk/provider';
import { MockLanguageModelV4 } from 'ai/test';
import { describe, expect, it } from 'vitest';
import { WorkflowAgent } from './workflow-agent.js';
const usage = {
inputTokens: { total: 1, noCache: 1, cacheRead: undefined, cacheWrite: undefined },
outputTokens: { total: 1, text: 1, reasoning: undefined },
};
const head = (delta: string) => [
{ type: 'stream-start' as const, warnings: [] },
{ type: 'text-start' as const, id: 't' },
{ type: 'text-delta' as const, id: 't', delta },
];
const finish = (unified: 'stop' | 'error') => ({
type: 'finish' as const,
finishReason: { unified, raw: unified },
usage,
});
// Emits parts one per pull, then either closes or errors.
function partsStream(
parts: unknown[],
end: { error?: unknown; hang?: boolean; abortSignal?: AbortSignal } = {},
) {
const queue = [...parts];
return new ReadableStream({
pull(c) {
const p = queue.shift();
if (p !== undefined) return c.enqueue(p);
if (end.hang) {
// silent: no more chunks; like a real fetch body, error the stream on abort
return new Promise<void>(() => {
end.abortSignal?.addEventListener('abort', () => c.error(end.abortSignal!.reason), { once: true });
});
}
if (end.error !== undefined) return c.error(end.error);
c.close();
},
});
}
const okStream = (text: string) =>
partsStream([...head(text), { type: 'text-end', id: 't' }, finish('stop')]);
const readThrow = (isRetryable: boolean, statusCode = 200, message = 'Failed to process successful response') =>
new APICallError({ message, url: 'https://x', requestBodyValues: {}, statusCode, isRetryable });
type Run = {
calls: number;
rejected: boolean;
rejection?: unknown;
result?: any;
chunks: any[];
ms: number;
onErrorCalls: number;
};
async function run(
makeStream: (call: number, abortSignal?: AbortSignal) => ReadableStream,
opts: { maxRetries?: number; timeout?: number; onError?: (e: { error: unknown }) => unknown } = {},
): Promise<Run> {
let calls = 0;
let onErrorCalls = 0;
const chunks: any[] = [];
const model = new MockLanguageModelV4({
doStream: async (o: any) => ({ stream: makeStream(++calls, o?.abortSignal) as any }),
});
const agent = new WorkflowAgent({ model, maxRetries: opts.maxRetries ?? 2 });
const t0 = Date.now();
let rejected = false;
let rejection: unknown;
let result: any;
try {
result = await agent.stream({
messages: [{ role: 'user', content: 'hi' }],
writable: new WritableStream({ write(c) { chunks.push(c); } }),
...(opts.timeout != null ? { timeout: opts.timeout } : {}),
onError: ((e: { error: unknown }) => {
onErrorCalls++;
return opts.onError?.(e);
}) as any,
});
} catch (e) {
rejected = true;
rejection = e;
}
return { calls, rejected, rejection, result, chunks, ms: Date.now() - t0, onErrorCalls };
}
// Text the client would show if it honours reset-step (drop parts of an invalidated attempt).
function uiText(chunks: any[]) {
let text = '';
for (const c of chunks) {
if (c.type === 'reset-step') text = '';
if (c.type === 'text-delta') text += c.delta ?? c.textDelta ?? c.text ?? '';
}
return text;
}
function report(id: string, r: Run, extra: Record<string, unknown> = {}) {
const types = r.chunks.map(c => c.type);
const line = {
scenario: id,
calls: r.calls,
outcome: r.rejected ? 'reject' : 'resolve',
rejection: r.rejected ? `${(r.rejection as any)?.name}: ${(r.rejection as any)?.message}`.slice(0, 120) : undefined,
resultError: r.result && 'error' in r.result ? String((r.result.error as any)?.name ?? r.result.error) : undefined,
finishReason: r.result?.finishReason,
steps: r.result?.steps?.length,
resetSteps: types.filter(t => t === 'reset-step').length,
hasErrorChunk: types.includes('error'),
lastChunk: types.at(-1),
uiText: uiText(r.chunks),
onErrorCalls: r.onErrorCalls,
ms: r.ms,
chunks: types.join(','),
...extra,
};
console.log('MATRIX ' + JSON.stringify(line));
return line;
}
describe('issue #22379 scenario matrix', () => {
it('S1 retryable read throw after open, attempt 2 succeeds -> 2 calls, success, text from attempt 2, reset-step between', async () => {
const r = await run(n => (n === 1 ? partsStream(head('partial '), { error: readThrow(true) }) : okStream('second attempt')));
const m = report('S1', r);
expect(m.calls).toBe(2);
expect(r.rejected).toBe(false);
expect(r.result?.error).toBeUndefined();
expect(r.result?.steps?.at(-1)?.text).toBe('second attempt');
expect(m.resetSteps).toBeGreaterThanOrEqual(2);
expect(m.uiText).toBe('second attempt');
}, 30000);
it('S2 retryable error part (503), attempt 2 succeeds -> 2 calls, success', async () => {
const r = await run(n =>
n === 1
? partsStream([...head('partial '), { type: 'error', error: { message: 'Service temporarily unavailable', statusCode: 503 } }, finish('error')])
: okStream('second attempt'),
);
const m = report('S2', r);
expect(m.calls).toBe(2);
expect(r.rejected).toBe(false);
expect(r.result?.error).toBeUndefined();
expect(m.uiText).toBe('second attempt');
}, 30000);
it('S3 NON-retryable read throw -> 1 call, reject, error chunk (not bare finish)', async () => {
const r = await run(() => partsStream(head('partial '), { error: readThrow(false) }));
const m = report('S3', r);
expect(m.calls).toBe(1);
expect(r.rejected).toBe(true);
expect(m.hasErrorChunk).toBe(true);
expect(m.lastChunk).not.toBe('finish');
}, 30000);
it('S4 deterministic failure dressed as retryable 500 (moderation) -> caller veto honoured: 1 call, no backoff', async () => {
const r = await run(
() => partsStream(head('partial '), { error: readThrow(true, 500, 'content_filter: request blocked by moderation') }),
// the veto the reporter asks for (streamText-style). No such contract exists in WorkflowAgent.onError (returns void).
{ onError: () => ({ retry: false }) },
);
const m = report('S4', r, { vetoHookInTypes: false });
expect(m.calls).toBe(1);
expect(m.ms).toBeLessThan(1000);
expect(r.rejected || r.result?.error !== undefined).toBe(true);
}, 30000);
it('S5a retries exhausted (retryable read throw every attempt) -> 3 calls, failure surfaced, error chunk, reset-step per attempt, no duplicated text', async () => {
const r = await run(n => partsStream(head(`attempt${n} `), { error: readThrow(true) }));
const m = report('S5a', r);
expect(m.calls).toBe(3);
expect(r.rejected || r.result?.error !== undefined).toBe(true);
expect(m.hasErrorChunk).toBe(true);
expect(m.resetSteps).toBeGreaterThanOrEqual(3);
expect(m.uiText).toBe('attempt3 ');
}, 30000);
it('S5b retries exhausted (retryable 503 error part every attempt) -> 3 calls, result.error, error chunk, no duplicated text', async () => {
const r = await run(n =>
partsStream([...head(`attempt${n} `), { type: 'error', error: { message: 'Service temporarily unavailable', statusCode: 503 } }, finish('error')]),
);
const m = report('S5b', r);
expect(m.calls).toBe(3);
expect(r.rejected || r.result?.error !== undefined).toBe(true);
expect(m.hasErrorChunk).toBe(true);
expect(m.resetSteps).toBeGreaterThanOrEqual(3);
expect(m.uiText).toBe('attempt3 ');
}, 30000);
it("S6 silent stream + timeout 50ms -> (reporter's view) must not resolve as success with 0 steps and no error", async () => {
const r = await run((_n, abortSignal) => partsStream(head('partial '), { hang: true, abortSignal }), { timeout: 50 });
const m = report('S6', r);
const silentSuccess = !r.rejected && (r.result?.steps?.length ?? 0) === 0 && r.result?.error === undefined;
expect(silentSuccess).toBe(false);
}, 30000);
});
Happy to adjust rows or turn this into a PR test if maintainers want it. How do these rows come out on your 1.0.30 patch?