Skip to content

Commit fb045a0

Browse files
ymichaelclaude
andauthored
Report provider errors on thread.failed and stop workflow retries after provider retry gives up (#8149)
## Human comments ## What was wrong When a workflow worker failed on a provider 429, `bb workflows status` and `history` reported only `Workflow worker failed`. The server built the `thread.failed` (and `experimental_thread.settled`) `error` from `system/error` rows alone (`getLastThreadErrorMessage` → `getLatestThreadSystemErrorEventRow`). Providers record their failures as `provider/error`, so plugins got `error: null` and the workflows plugin fell back to its generic string. The workflows plugin decides whether to retry by classifying that text (`isRetryableProviderFailure`), so the empty error also turned off its two transient retries. That is the second effect in gaodes' 0.50.1 Pi report: provider-retry declines a Pi 429 that has no reset time (`no-rate-limit-state`), and the workflow's own retry never matched either. The lookup also covered the whole thread rather than the failed turn, so a failure could report an older turn's `system/error`. ## What changed - `packages/db/src/data/events.ts`: `getLatestThreadSystemErrorEventRow` becomes `getLatestThreadErrorEventRow`. It returns the newest `system/error` or `provider/error` after a given sequence and uses the existing `events_thread_type_sequence_idx` index, so there is no new index or migration. The query-cost case in `packages/db/scripts/query-costs/events-cases.ts` is updated to match. - `apps/server/src/services/threads/thread-data.ts`: `getLastThreadErrorMessage` only looks at errors recorded since the failed turn's request (`getLastStoredTurnRequestEvent`). A `provider/error` is formatted as its `detail` (or `message` if there is no detail), followed by its `errorInfo` category, HTTP status and provider code, e.g. `429: {"code":"1302","message":"Rate limit reached for requests"} (rate-limit, HTTP 429)`. A `system/error` still returns its message. - The workflows classifier needs no change: the real error text now contains `rate-limit` / `HTTP 429`, which it already treats as retryable. - `plugins/workflows/src/retry-handoff.ts`, `service.ts`: with its own retry now working, the workflow would also retry failures provider-retry had deliberately given up on. Each replacement worker is a new thread with a fresh provider-retry budget, so retries multiplied (persistent overloads: 3 workers × 5 turns). The handoff now reads provider-retry's decline reason. `attempts-exhausted`, `beyond-maximum-wait` and `pool-unavailable` return `give-up`, and the call fails without a replacement. Other declines, such as `no-rate-limit-state` (this issue's Pi 429), still fall back to the workflow's own retries. The README and the workflows skill's `runs.md` describe this. - The `thread.failed` payload is still `{ thread, error: string | null }`. There is no SDK or plugin API change and no `HOST_DAEMON_PROTOCOL_VERSION` bump. Not in this PR: - When the workflows plugin restarts, it reconciles a worker that already failed as `Workflow worker is in an error state`, without the cause. Fixing that needs a way for plugins to read a thread's last error. - Whether provider-retry should retry a structured 429 that has no reset time. That is a policy choice, and the workflow's bounded 1 s / 4 s retries now cover the case. ## How you verified New tests, both of which fail on main: - `apps/server/test/services/plugins/plugin-thread-events.test.ts` - `delivers thread.failed with the failed turn's provider/error and its classification`: a Pi-shaped sequence of 429s marked `willRetry`, then a final 429, after an older turn's `system/error`. On main it received `"earlier turn"`. - `does not report an earlier turn's error for a failure without one`: expects `null`. On main it received `"earlier turn"`. - `plugins/workflows/src/service-policy.test.ts`: - asserts that the server's detail-less format `Provider error (rate-limit, HTTP 429)` is classed as retryable. - `fails the call without a replacement when provider retry declined it as %s`, for `attempts-exhausted`, `beyond-maximum-wait` and `pool-unavailable`. All three fail without the handoff change: the workflow started a second worker. - a handoff case for a `no-rate-limit-state` decline, which still starts a replacement. Live end-to-end run on `pnpm start:worktree`, built once without and once with this change. Setup: Pi with a sandboxed `PI_CODING_AGENT_DIR` whose provider points at a local endpoint that returns `429 {"code":"1302","message":"Rate limit reached for requests"}`, and a one-call workflow `agent(..., { provider: "pi", model: "fakezai/glm-fake" })`. The worker's events matched the report: three 429s marked `willRetry`, a final 429, then `turn/completed failed`. `bb provider-retry explain` returned `decline / no-rate-limit-state` in both runs. | | before | after | |---|---|---| | run and call `error` | `Workflow worker failed` | `429: {"code":"1302","message":"Rate limit reached for requests"} (rate-limit, HTTP 429)` | | `providerRetryAttempts` | 0 (one worker) | 2 (three workers, then the real error) | Live check of the give-up path, on the same setup with the endpoint returning `529 {"type":"overloaded_error"}`: provider-retry retried the turn 4 times inside the one worker (5 turns, 24 provider requests), then recorded `decline / attempts-exhausted`. The call failed after 244 s with `529: {"type":"overloaded_error","message":"Overloaded"} (overloaded, HTTP 529)`, `providerRetryAttempts` 0 and no second worker. The server log shows `Agent call 1 is not retried: provider retry declined it (attempts-exhausted)`. Re-running the Pi 429 case on this build still gave `providerRetryAttempts` 2 and the 429 error. Commands: ```sh pnpm exec turbo run typecheck --filter=@bb/db --filter=@bb/server --filter=./plugins/workflows pnpm exec turbo run test --filter=@bb/db --filter=./plugins/workflows # db 762, workflows 292 passed pnpm exec turbo run test --filter=@bb/server -- --run test/services/plugins test/threads # 1408 passed ``` Fixes #1914 🤖 Generated with [Claude Code](https://claude.com/claude-code) > AGENT GENERATED --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 52d1197 commit fb045a0

9 files changed

Lines changed: 259 additions & 26 deletions

File tree

‎apps/server/src/services/threads/thread-data.ts‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ import {
33
findLastRootStoredTurnStarted,
44
findStoredEventRow as findStoredEventRowRecord,
55
getTurnFinalAgentMessageEventRow,
6-
getLatestThreadSystemErrorEventRow,
6+
getLastStoredTurnRequestEvent,
7+
getLatestThreadErrorEventRow,
78
hydrateRetainedEventOutputRows,
89
listLatestTurnFinalAgentMessageEventRows,
910
listStoredEventRows as listStoredEventRowRecords,
@@ -218,8 +219,27 @@ export function getLastThreadErrorMessage(
218219
db: DbConnection,
219220
threadId: string,
220221
): string | null {
221-
const row = getLatestThreadSystemErrorEventRow(db, { threadId });
222+
const row = getLatestThreadErrorEventRow(db, {
223+
afterSequence: getLastStoredTurnRequestEvent(db, threadId)?.sequence ?? 0,
224+
threadId,
225+
});
222226
if (!row) return null;
223227
const eventRow = parseStoredEventRow(row);
224-
return eventRow.type === "system/error" ? eventRow.data.message : null;
228+
switch (eventRow.type) {
229+
case "system/error":
230+
return eventRow.data.message;
231+
case "provider/error": {
232+
const text = eventRow.data.detail ?? eventRow.data.message;
233+
const info = eventRow.data.errorInfo;
234+
if (info === undefined) return text;
235+
const facts = [
236+
info.category,
237+
info.httpStatusCode === null ? null : `HTTP ${info.httpStatusCode}`,
238+
info.providerCode,
239+
].filter((fact) => fact !== null);
240+
return `${text} (${facts.join(", ")})`;
241+
}
242+
default:
243+
return null;
244+
}
225245
}

‎apps/server/test/services/plugins/plugin-thread-events.test.ts‎

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import type { ThreadCreateServiceRequest } from "../../../src/services/threads/t
1313
import {
1414
seedEvent,
1515
seedThreadFixture,
16+
seedThreadRuntimeState,
1617
seedTurnStarted,
1718
seedThread,
1819
} from "../../helpers/seed.js";
@@ -317,6 +318,124 @@ describe("plugin thread lifecycle events", () => {
317318
}
318319
});
319320

321+
it("delivers thread.failed with the failed turn's provider/error and its classification", async () => {
322+
const recorded: RecordedThreadPayload[] = [];
323+
globals.__failedEvents = recorded;
324+
const { harness, cleanup } = await setUpPluginHarness(`
325+
export default function plugin(bb: any) {
326+
bb.events.on("thread.failed", (payload: any) => {
327+
(globalThis as any).__failedEvents.push(payload);
328+
});
329+
}
330+
`);
331+
try {
332+
const { environment, thread } = seedThreadFixture(harness, {
333+
thread: { status: "active" },
334+
});
335+
const providerThreadId = "pi-session";
336+
seedEvent(harness.deps, {
337+
threadId: thread.id,
338+
environmentId: environment.id,
339+
scope: threadScope(),
340+
sequence: 1,
341+
type: "system/error",
342+
data: { code: "provider_process_exited", message: "earlier turn" },
343+
});
344+
seedThreadRuntimeState(harness.deps, {
345+
environmentId: environment.id,
346+
providerThreadId,
347+
sequenceStart: 2,
348+
threadId: thread.id,
349+
});
350+
const rateLimitDetail =
351+
'429: {"code":"1302","message":"Rate limit reached for requests"}';
352+
for (const [sequence, willRetry] of [
353+
[4, true],
354+
[5, true],
355+
[6, undefined],
356+
] as const) {
357+
seedEvent(harness.deps, {
358+
threadId: thread.id,
359+
environmentId: environment.id,
360+
providerThreadId,
361+
scope: threadScope(),
362+
sequence,
363+
type: "provider/error",
364+
data: {
365+
providerThreadId,
366+
message: "Provider error",
367+
detail: willRetry === undefined ? rateLimitDetail : "retrying 429",
368+
...(willRetry === undefined ? {} : { willRetry }),
369+
errorInfo: {
370+
category: "rate-limit",
371+
providerCode: null,
372+
httpStatusCode: 429,
373+
},
374+
},
375+
});
376+
}
377+
378+
expect(
379+
moveThreadStatus(lifecycleDeps(harness), {
380+
move: "run.failed",
381+
threadId: thread.id,
382+
}).applied,
383+
).toBe(true);
384+
385+
await vi.waitFor(() => expect(recorded).toHaveLength(1));
386+
expect(recorded[0]?.error).toBe(
387+
`${rateLimitDetail} (rate-limit, HTTP 429)`,
388+
);
389+
} finally {
390+
delete globals.__failedEvents;
391+
await cleanup();
392+
}
393+
});
394+
395+
it("does not report an earlier turn's error for a failure without one", async () => {
396+
const recorded: RecordedThreadPayload[] = [];
397+
globals.__failedEvents = recorded;
398+
const { harness, cleanup } = await setUpPluginHarness(`
399+
export default function plugin(bb: any) {
400+
bb.events.on("thread.failed", (payload: any) => {
401+
(globalThis as any).__failedEvents.push(payload);
402+
});
403+
}
404+
`);
405+
try {
406+
const { environment, thread } = seedThreadFixture(harness, {
407+
thread: { status: "active" },
408+
});
409+
seedEvent(harness.deps, {
410+
threadId: thread.id,
411+
environmentId: environment.id,
412+
scope: threadScope(),
413+
sequence: 1,
414+
type: "system/error",
415+
data: { code: "provider_process_exited", message: "earlier turn" },
416+
});
417+
seedThreadRuntimeState(harness.deps, {
418+
environmentId: environment.id,
419+
providerThreadId: "provider-session",
420+
sequenceStart: 2,
421+
threadId: thread.id,
422+
});
423+
424+
expect(
425+
moveThreadStatus(lifecycleDeps(harness), {
426+
move: "run.failed",
427+
threadId: thread.id,
428+
}).applied,
429+
).toBe(true);
430+
431+
await vi.waitFor(() => expect(recorded).toHaveLength(1));
432+
expect(recorded[0]?.error).toBeNull();
433+
} finally {
434+
delete globals.__failedEvents;
435+
await cleanup();
436+
}
437+
});
438+
320439
it("delivers interaction.pending after the interaction is committed", async () => {
321440
const recorded: RecordedInteractionPayload[] = [];
322441
globals.__pendingInteractionEvents = recorded;

‎packages/db/scripts/query-costs/events-cases.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ import {
4242
getLatestStoredThreadEventOfTypes,
4343
getLatestThreadStopAim,
4444
getLatestThreadSequence,
45-
getLatestThreadSystemErrorEventRow,
45+
getLatestThreadErrorEventRow,
4646
getLatestTokenUsageRow,
4747
getStoredConversationOutlineProjectionState,
4848
findStoredItemTurnIdInRange,
@@ -1333,9 +1333,12 @@ export const EVENTS_COST_CASES: readonly QueryCostCase[] = [
13331333
}),
13341334
},
13351335
{
1336-
name: `${EVENTS}#getLatestThreadSystemErrorEventRow`,
1336+
name: `${EVENTS}#getLatestThreadErrorEventRow`,
13371337
run: (db, fixture) =>
1338-
getLatestThreadSystemErrorEventRow(db, { threadId: fixture.threadId }),
1338+
getLatestThreadErrorEventRow(db, {
1339+
afterSequence: 0,
1340+
threadId: fixture.threadId,
1341+
}),
13391342
},
13401343
{
13411344
name: `${EVENTS}#getLatestModelFallbackRowSinceTurnRequest`,

‎packages/db/src/data/events.ts‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1562,7 +1562,8 @@ export interface GetLatestCompletedThreadContextClearSequenceArgs {
15621562
threadId: string;
15631563
}
15641564

1565-
export interface GetLatestThreadSystemErrorEventRowArgs {
1565+
export interface GetLatestThreadErrorEventRowArgs {
1566+
afterSequence: number;
15661567
threadId: string;
15671568
}
15681569

@@ -4332,18 +4333,19 @@ export function listLatestTurnFinalAgentMessageEventRows(
43324333
return replies;
43334334
}
43344335

4335-
export function getLatestThreadSystemErrorEventRow(
4336+
export function getLatestThreadErrorEventRow(
43364337
db: DbConnection,
4337-
args: GetLatestThreadSystemErrorEventRowArgs,
4338+
args: GetLatestThreadErrorEventRowArgs,
43384339
): StoredEventRow | null {
43394340
return (
43404341
db
4341-
.select(storedEventRowFields)
4342-
.from(events)
4342+
.select(storedEventRowSqlFields(null))
4343+
.from(sql`${events} INDEXED BY events_thread_type_sequence_idx`)
43434344
.where(
43444345
and(
43454346
eq(events.threadId, args.threadId),
4346-
eq(events.type, "system/error"),
4347+
inArray(events.type, ["system/error", "provider/error"]),
4348+
gt(events.sequence, args.afterSequence),
43474349
),
43484350
)
43494351
.orderBy(desc(events.sequence))

‎plugins/workflows/README.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,10 @@ the failure reaches the workflow script. Retryability comes from an explicit
101101
SDK `retryable` marker when available or conservative overload, rate-limit,
102102
provider 5xx, and network-error signatures. Authentication, configuration,
103103
schema, and other deterministic failures are not retried. Retry attempts are
104-
persisted on the call so a plugin restart cannot reset the retry budget.
104+
persisted on the call so a plugin restart cannot reset the retry budget. A
105+
failure the provider retry plugin declined as `attempts-exhausted`,
106+
`beyond-maximum-wait`, or `pool-unavailable` is not retried, because a
107+
replacement worker would hit the same limit.
105108

106109
Worker output is either the final assistant text or an Ajv-validated value
107110
submitted through `bb_workflow_result`. Structured workers receive two

‎plugins/workflows/skills/workflows/references/runs.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,11 @@ call first waits up to a minute for the provider retry plugin to decide. If
7373
provider retry, or core after a bb restart, queues or runs a retry in the
7474
worker's thread, the call keeps that worker and waits for its result instead
7575
of starting a replacement. Only a failure nobody else retries starts a new
76-
worker.
76+
worker. When provider retry declines because its retries are used up, the
77+
reset is beyond its maximum wait, or the account pool has no usable account,
78+
the call fails without a replacement, since a new worker would hit the same
79+
limit. Other declines, such as a rate limit with no reset time, fall back to
80+
the call's own retries.
7781

7882
The CLI equivalents are:
7983

‎plugins/workflows/src/retry-handoff.ts‎

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,14 @@ export type RetryHandoffApi = {
2020
export type RetryHandoff =
2121
| { kind: "stand-down"; reason: string }
2222
| { kind: "wait" }
23-
| { kind: "re-run" };
23+
| { kind: "re-run" }
24+
| { kind: "give-up"; reason: string };
25+
26+
const FINAL_PROVIDER_RETRY_DECLINES = new Set([
27+
"attempts-exhausted",
28+
"beyond-maximum-wait",
29+
"pool-unavailable",
30+
]);
2431

2532
const turnRequestSchema = z
2633
.object({
@@ -30,8 +37,13 @@ const turnRequestSchema = z
3037
.passthrough();
3138

3239
const providerRetryDecisionSchema = z
33-
.object({ requestId: z.string() })
34-
.passthrough()
40+
.object({
41+
requestId: z.string(),
42+
decision: z.object({
43+
kind: z.enum(["retry", "decline"]),
44+
reason: z.string(),
45+
}),
46+
})
3547
.nullable();
3648

3749
function isThreadGoneError(error: unknown): boolean {
@@ -41,7 +53,7 @@ function isThreadGoneError(error: unknown): boolean {
4153
async function readProviderRetryDecision(
4254
bb: RetryHandoffApi,
4355
threadId: string,
44-
): Promise<{ requestId: string } | null | "absent"> {
56+
): Promise<z.infer<typeof providerRetryDecisionSchema> | "absent"> {
4557
const sources = await bb.sdk.plugins.experimental_discoverRpc({
4658
pluginId: PROVIDER_RETRY_PLUGIN_ID,
4759
method: PROVIDER_RETRY_DECISION_METHOD,
@@ -97,12 +109,14 @@ export async function readRetryHandoff(
97109
reason: `a retry of the failed turn ran in thread ${threadId}`,
98110
};
99111
}
100-
if (
101-
request === null ||
102-
decision === "absent" ||
103-
decision?.requestId === request.requestId ||
104-
args.now - args.failedAt >= RETRY_DECISION_WAIT_MS
105-
) {
112+
if (request === null || decision === "absent") return { kind: "re-run" };
113+
if (decision?.requestId === request.requestId) {
114+
return decision.decision.kind === "decline" &&
115+
FINAL_PROVIDER_RETRY_DECLINES.has(decision.decision.reason)
116+
? { kind: "give-up", reason: decision.decision.reason }
117+
: { kind: "re-run" };
118+
}
119+
if (args.now - args.failedAt >= RETRY_DECISION_WAIT_MS) {
106120
return { kind: "re-run" };
107121
}
108122
return { kind: "wait" };

0 commit comments

Comments
 (0)