fix(server): usage-limit recovery survives notification wakes that did no work #38498
Openyspreen(GitHub profile, opens in a new tab)wants to merge 8 commits into
main fromrefs/pull/38498/headopened View on GitHubyspreen(GitHub profile, opens in a new tab) linked this to fix #16815, #38497
tanstack-source added labelsbug
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- @@ -581,3 +631,5 @@581631 }582632 retained.push(item);583633 }634+ for (const [id, item] of limitItems) {635+ if (!visibleLocalIds.has(id)) retained.push(item);
juliusmarminge added labelstakeover:in-progress
- @@ -6898,4 +6898,5 @@68986898 source === undefined ||68996899 (source.status !== "interrupted" &&69006900 !(source.status === "failed" && limited?.class === "usage_limit")) ||6901- latestExecutedRun(projection.runs)?.id !== source.id ||6901+ (6902+ usageLimitBlockedRun(projection.runs, projection.turnItems, null) ??@@ -12738,3 +12736,19 @@12738- turnItemRunIds: [latest.id],12739- })12736+ // Stop must also disarm a limited run that completed notification wakes hide. Only the12737+ // latest failure's errors and the inputs of runs completed before its reset can matter.12738+ const readItems = (filter: Parameters<typeof projectionStore.getThreadRecords>[2]) =>12739+ projectionStore12740+ .getThreadRecords(thread.id, ["turnItems"], filter)1274012741 .pipe(mapDispatchError(input.command));12742+ const failed = latestExecutedRun(runs.filter((run) => run.status === "failed"));12743+ const errors =12744+ failed === null12745+ ? []12746+ : (yield* readItems({ turnItemTypes: ["error"], turnItemRunIds: [failed.id] })).turnItems;12747+ const resetAt = latestRootProviderFailure(failed, errors)?.resetAt;12748+ const resetMs = resetAt == null ? Number.NaN : Date.parse(resetAt);12749+ const wakeRunIds = runs12750+ .filter(12751+ (run) =>12752+ run.status === "completed" &&12753+ run.completedAt !== null &&12754+ DateTime.toEpochMillis(run.completedAt) <= resetMs,@@ -4710,0 +4722,21 @@4722+ ON latest_failure_error.turn_item_id = (4723+ SELECT error.turn_item_id FROM orchestration_v2_projection_turn_items error4724+ WHERE error.thread_id = t.thread_id4725+ AND error.run_id = latest_failure.run_id4726+ AND error.node_id IS json_extract(latest_failure.payload_json, '$.rootNodeId')4727+ AND error.type = 'error' AND error.status = 'failed'4728+ ORDER BY error.updated_at DESC, error.ordinal DESC, error.turn_item_id DESC4729+ LIMIT 14730+ )4731+ `;4732+ // Mirrors the wake rule of usageLimitBlockedRun: a run that a notification started and4733+ // that completed before the newest usage-limit failure resets did no work, so it must4734+ // not replace that failure as the latest run.4735+ const isLimitedWake = (alias: string) => {4736+ const run = sql.literal(alias);4737+ return sql`(4738+ ${run}.status = 'completed'4739+ AND COALESCE(4740+ json_extract(latest_failure_error.payload_json, '$.failure.class') = 'usage_limit'4741+ AND julianday(${run}.completed_at) <= julianday(4742+ json_extract(latest_failure_error.payload_json, '$.failure.resetAt')@@ -7778,0 +7853,21 @@7853+ WHERE error.thread_id = t.thread_id AND error.run_id = r.run_id7854+ AND error.type = 'error' AND error.status = 'failed'7855+ AND error.node_id IS json_extract(r.payload_json, '$.rootNodeId')7856+ ORDER BY error.updated_at DESC, error.ordinal DESC, error.turn_item_id DESC7857+ LIMIT 17858+ )7859+ WHERE t.thread_id = ${threadId}7860+ AND EXISTS (7861+ SELECT 1 FROM orchestration_v2_projection_turn_items limited7862+ WHERE limited.thread_id = t.thread_id7863+ AND limited.type = 'error' AND limited.status = 'failed'7864+ AND json_extract(limited.payload_json, '$.failure.class') = 'usage_limit'7865+ )7866+ AND json_extract(item.payload_json, '$.failure.class') = 'usage_limit'7867+ ), later AS (7868+ -- Runs omitted here are not loaded at all, which leaves the result unchanged.7869+ SELECT run.run_id, run.payload_json7870+ FROM orchestration_v2_projection_runs run, blocked7871+ WHERE run.thread_id = ${threadId} AND run.ordinal > blocked.ordinal7872+ ORDER BY run.ordinal DESC7873+ LIMIT ${LIMIT_EVIDENCE_MAX_RUNS}@@ -7778,0 +7886,21 @@7886+ ORDER BY first_input.ordinal7887+ LIMIT 17888+ )7889+ WHERE start.type = 'notification'7890+ `;7891+ const loadedRunIds = new Set<string>(projection.runs.map((run) => run.id));7892+ const loadedItemIds = new Set<string>(projection.turnItems.map((item) => item.id));7893+ const runIds = rows.flatMap((row) =>7894+ row.kind === "run" && !loadedRunIds.has(row.id) ? [row.id] : [],7895+ );7896+ const itemIds = rows.flatMap((row) =>7897+ row.kind === "item" && !loadedItemIds.has(row.id) ? [row.id] : [],7898+ );7899+ if (runIds.length === 0 && itemIds.length === 0) return projection;7900+ const runRows = yield* sql<PayloadRow>`7901+ SELECT payload_json FROM orchestration_v2_projection_runs7902+ WHERE thread_id = ${threadId}7903+ AND run_id IN (SELECT value FROM json_each(${encodeIdList(runIds)}))7904+ `;7905+ const itemRows = yield* sql<PayloadRow>`7906+ SELECT payload_json FROM orchestration_v2_projection_turn_items@@ -8130,3 +8271,4 @@81308271 candidate.status = 'cancelled'81318272 AND json_extract(candidate.payload_json, '$.startedAt') IS NULL81328273 )8274+ AND NOT ${isLimitedWake("candidate")}@@ -711,0 +773,21 @@773+ });774+775+ expect(bounded.projection.visibleTurnItems).toHaveLength(2);776+ expect(777+ usageLimitBlockedRun(bounded.projection.runs, bounded.projection.turnItems, null)?.id,778+ ).toBe(limited.id);779+ // Retained wake starts are stubs: a 50 KB notification detail must not reach the snapshot.780+ const visibleIds = new Set(bounded.projection.visibleTurnItems.map((row) => row.sourceItemId));781+ const retained = bounded.projection.turnItems.filter((item) => !visibleIds.has(item.id));782+ expect(retained.length).toBeGreaterThan(0);783+ expect(JSON.stringify(retained).length).toBeLessThan(10_000);784+785+ // Evidence past a quarter of the budget is dropped, so the snapshot stays within it.786+ const tight = buildBoundedThreadProjection({787+ projection: full,788+ snapshotSequence: 1,789+ policy: { maxItems: 2, maxEncodedBytes: 8_000 },790+ });791+ expect(792+ usageLimitBlockedRun(tight.projection.runs, tight.projection.turnItems, null),793+ ).toBeNull();@@ -558,3 +559,14 @@558559 );559560 }560561562+// usageLimitBlockedRun needs the limited run's root error and the notification that started each563+// later run, and a long chain of wakes pushes both out of the window. Starts are kept as stubs564+// without their unbounded detail, and dropped past a quarter of the budget (clients then show565+// the plain latest run).566+function limitRecoveryItems(567+ projection: Pick<OrchestrationV2ThreadProjection, "runs" | "turnItems">,568+ maxEncodedBytes: number,569+): ReadonlyMap<string, OrchestrationV2TurnItem> {570+ const items = new Map<string, OrchestrationV2TurnItem>();571+ const blocked = usageLimitBlockedRun(projection.runs, projection.turnItems, null);572+ if (blocked === null) return items;@@ -558,3 +559,17 @@558559 );559560 }560561562+// usageLimitBlockedRun needs the limited run's root error and the notification that started each563+// later run, and a long chain of wakes pushes both out of the window. Starts are kept as stubs564+// without their unbounded detail, and dropped past a quarter of the budget (clients then show565+// the plain latest run).566+function limitRecoveryItems(567+ projection: Pick<OrchestrationV2ThreadProjection, "runs" | "turnItems">,568+ maxEncodedBytes: number,569+): ReadonlyMap<string, OrchestrationV2TurnItem> {570+ const items = new Map<string, OrchestrationV2TurnItem>();571+ const blocked = usageLimitBlockedRun(projection.runs, projection.turnItems, null);572+ if (blocked === null) return items;573+ const laterRoots = new Set<string>();574+ for (const run of projection.runs) {575+ if (run.ordinal > blocked.ordinal && run.rootNodeId !== null) {@@ -560,0 +563,21 @@563+// later run, and a long chain of wakes pushes both out of the window. Starts are kept as stubs564+// without their unbounded detail, and dropped past a quarter of the budget (clients then show565+// the plain latest run).566+function limitRecoveryItems(567+ projection: Pick<OrchestrationV2ThreadProjection, "runs" | "turnItems">,568+ maxEncodedBytes: number,569+): ReadonlyMap<string, OrchestrationV2TurnItem> {570+ const items = new Map<string, OrchestrationV2TurnItem>();571+ const blocked = usageLimitBlockedRun(projection.runs, projection.turnItems, null);572+ if (blocked === null) return items;573+ const laterRoots = new Set<string>();574+ for (const run of projection.runs) {575+ if (run.ordinal > blocked.ordinal && run.rootNodeId !== null) {576+ laterRoots.add(String(run.rootNodeId));577+ }578+ }579+ if (laterRoots.size === 0) return items;580+ const firstInputs = new Map<string, OrchestrationV2TurnItem>();581+ for (const item of projection.turnItems) {582+ if (item.type === "error" && item.runId === blocked.id && item.nodeId === blocked.rootNodeId) {583+ items.set(String(item.id), item);@@ -560,0 +584,21 @@584+ } else if (585+ (item.type === "user_message" || item.type === "notification") &&586+ item.nodeId !== null &&587+ laterRoots.has(String(item.nodeId))588+ ) {589+ const first = firstInputs.get(String(item.nodeId));590+ if (first === undefined || item.ordinal < first.ordinal) {591+ firstInputs.set(String(item.nodeId), item);592+ }593+ }594+ }595+ let startBytes = 0;596+ const starts: Array<OrchestrationV2TurnItem> = [];597+ for (const item of firstInputs.values()) {598+ if (item.type !== "notification") continue;599+ const { detail: _detail, ...rest } = item;600+ const stub = { ...rest, title: null, summary: item.summary.slice(0, 120).trimEnd() };601+ startBytes += bytesOfJson(stub);602+ starts.push(stub);603+ }604+ if (startBytes <= maxEncodedBytes / 4) {@@ -137,4 +140,5 @@137140 })138141 )139142 continue;140- row = { ...row, item: currentItem };143+ // Retained notifications are stubs without detail; the page row has the full item.144+ if (recovery) turnItemById.set(String(row.sourceItemId), row.item);@@ -97,0 +112,21 @@112+ const failed = latestExecutedRun(runs.filter((run) => run.status === "failed"));113+ const failure = latestRootProviderFailure(failed, turnItems);114+ if (failure?.class !== "usage_limit" || failure.resetAt == null) return runs;115+ const resetMs = Date.parse(failure.resetAt);116+ if (!Number.isFinite(resetMs)) return runs;117+ const firstInputs = new Map<string, { readonly type: string; readonly ordinal: number }>();118+ for (const item of turnItems) {119+ if (item.nodeId == null || item.ordinal == null) continue;120+ if (item.type !== "user_message" && item.type !== "notification") continue;121+ const first = firstInputs.get(item.nodeId);122+ if (first === undefined || item.ordinal < first.ordinal) {123+ firstInputs.set(item.nodeId, { type: item.type, ordinal: item.ordinal });124+ }125+ }126+ return runs.filter(127+ (run) =>128+ run.status !== "completed" ||129+ run.completedAt === null ||130+ DateTime.toEpochMillis(run.completedAt) > resetMs ||131+ run.rootNodeId === null ||132+ firstInputs.get(run.rootNodeId)?.type !== "notification",@@ -98,6 +122,20 @@122+ if (first === undefined || item.ordinal < first.ordinal) {123+ firstInputs.set(item.nodeId, { type: item.type, ordinal: item.ordinal });124+ }125+ }126+ return runs.filter(127+ (run) =>128+ run.status !== "completed" ||129+ run.completedAt === null ||130+ DateTime.toEpochMillis(run.completedAt) > resetMs ||131+ run.rootNodeId === null ||132+ firstInputs.get(run.rootNodeId)?.type !== "notification",133+ );134+}135+98136 export function usageLimitBlockedRun(99137 runs: ReadonlyArray<OrchestrationV2Run>,100138 turnItems: ReadonlyArray<FailureScanTurnItem>,101139 sessionError: string | null,102140 ): OrchestrationV2Run | null {103- const executed = latestExecutedRun(runs);141+ const executed = latestExecutedRun(runsWithoutLimitedWakes(runs, turnItems));
- @@ -7778,0 +7865,21 @@7865+ AND error.node_id IS json_extract(r.payload_json, '$.rootNodeId')7866+ ORDER BY error.updated_at DESC, error.ordinal DESC, error.turn_item_id DESC7867+ LIMIT 17868+ )7869+ -- The blocked run, when there is one, is the newest failed run.7870+ WHERE t.thread_id = ${threadId}7871+ AND json_extract(latest_failure_error.payload_json, '$.failure.class') = 'usage_limit'7872+ AND json_extract(item.payload_json, '$.failure.class') = 'usage_limit'7873+ )7874+ SELECT 'run' AS kind, run_id AS id FROM blocked7875+ UNION ALL SELECT 'item', error_id FROM blocked7876+ UNION ALL7877+ SELECT 'item', ${firstRootInput("run", "turn_item_id")}7878+ FROM orchestration_v2_projection_threads t7879+ ${latestFailureJoins}7880+ INNER JOIN orchestration_v2_projection_runs run ON run.thread_id = t.thread_id7881+ WHERE t.thread_id = ${threadId}7882+ AND run.run_id IN (SELECT value FROM json_each(${encodeIdList(7883+ projection.runs.map((run) => run.id),7884+ )}))7885+ AND ${isWakeCandidate("run")}@@ -560,0 +589,21 @@589+ } else if (590+ (item.type === "user_message" || item.type === "notification") &&591+ item.nodeId !== null &&592+ candidateRoots.has(String(item.nodeId))593+ ) {594+ const first = firstInputs.get(String(item.nodeId));595+ if (first === undefined || item.ordinal < first.ordinal) {596+ firstInputs.set(String(item.nodeId), item);597+ }598+ }599+ }600+ let startBytes = 0;601+ const starts: Array<OrchestrationV2TurnItem> = [];602+ for (const item of firstInputs.values()) {603+ let stub: OrchestrationV2TurnItem;604+ if (item.type === "notification") {605+ const { detail: _detail, ...rest } = item;606+ stub = { ...rest, title: null, summary: item.summary.slice(0, 120).trimEnd() };607+ } else if (item.type === "user_message") {608+ const { context: _context, ...rest } = item;609+ stub = { ...rest, text: item.text.slice(0, 120), attachments: [] };
- @@ -558,3 +563,17 @@558563 );559564 }560565566+// usageLimitBlockedRun needs the limited run's latest root error and the first input of each wake567+// candidate, and a long chain of wakes pushes both out of the window. Inputs are kept as stubs568+// without their unbounded text, and dropped past a quarter of the budget (clients then show569+// the plain latest run).570+function limitRecoveryItems(571+ projection: Pick<OrchestrationV2ThreadProjection, "runs" | "turnItems">,572+ maxEncodedBytes: number,573+): ReadonlyMap<string, OrchestrationV2TurnItem> {574+ const items = new Map<string, OrchestrationV2TurnItem>();575+ const candidateRoots = new Set<string>();576+ for (const run of usageLimitWakeCandidates(projection.runs, projection.turnItems)) {577+ if (run.rootNodeId !== null) candidateRoots.add(String(run.rootNodeId));578+ }579+ if (candidateRoots.size === 0) return items;@@ -97 +101,21 @@97101102+/**103+ * Subagents that die on a usage limit start notification runs that finish before the reset104+ * with no work to show. These candidates ran on the limited provider after its latest failure105+ * and before the reset; continuations and other providers' runs are never wakes.106+ */107+export function usageLimitWakeCandidates(108+ runs: ReadonlyArray<OrchestrationV2Run>,109+ turnItems: ReadonlyArray<FailureScanTurnItem>,110+): ReadonlyArray<OrchestrationV2Run> {111+ const failed = latestExecutedRun(runs.filter((run) => run.status === "failed"));112+ const failure = latestRootProviderFailure(failed, turnItems);113+ if (failed === null || failure?.class !== "usage_limit" || failure.resetAt == null) return [];114+ const resetMs = Date.parse(failure.resetAt);115+ if (!Number.isFinite(resetMs)) return [];116+ return runs.filter(117+ (run) =>118+ run.status === "completed" &&119+ run.completedAt !== null &&120+ run.rootNodeId !== null &&121+ run.providerInstanceId === failed.providerInstanceId &&
- @@ -1711,0 +1721,21 @@1721+ R extends {1722+ readonly runs: ReadonlyArray<OrchestrationV2Run>;1723+ readonly turnItems: ReadonlyArray<OrchestrationV2TurnItem>;1724+ },1725+ >(threadId: ThreadId, records: R) {1726+ const read = (filter: ProjectionRecordFilter) =>1727+ projectionStore1728+ .getThreadRecords(threadId, ["turnItems"], filter)1729+ .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));1730+ const runIds = usageLimitWakeCandidates(records.runs, records.turnItems).map((run) => run.id);1731+ if (runIds.length === 0) return records;1732+ const inputs = (yield* read({1733+ turnItemTypes: ["user_message", "notification"],1734+ turnItemRunIds: runIds,1735+ })).turnItems;1736+ const loaded = new Set(records.turnItems.map((item) => item.id));1737+ let turnItems = [...records.turnItems, ...inputs.filter((item) => !loaded.has(item.id))];1738+ const started = notificationStartedWakeCandidates(records.runs, turnItems).map((run) => run.id);1739+ if (started.length > 0) {1740+ const known = new Set(turnItems.map((item) => item.id));1741+ const all = (yield* read({ turnItemRunIds: started })).turnItems;@@ -7778,0 +7882,21 @@7882+ LIMIT 17883+ )7884+ -- The blocked run, when there is one, is the newest failed run.7885+ WHERE t.thread_id = ${threadId}7886+ AND json_extract(latest_failure_error.payload_json, '$.failure.class') = 'usage_limit'7887+ AND json_extract(item.payload_json, '$.failure.class') = 'usage_limit'7888+ )7889+ SELECT 'run' AS kind, run_id AS id FROM blocked7890+ UNION ALL SELECT 'item', error_id FROM blocked7891+ UNION ALL7892+ SELECT 'item', ${firstRootInput("run", "turn_item_id")}7893+ FROM orchestration_v2_projection_threads t7894+ ${latestFailureJoins}7895+ INNER JOIN orchestration_v2_projection_runs run ON run.thread_id = t.thread_id7896+ WHERE t.thread_id = ${threadId}7897+ AND run.run_id IN (SELECT value FROM json_each(${encodeIdList(7898+ projection.runs.map((run) => run.id),7899+ )}))7900+ AND ${isWakeCandidate("run")}7901+ -- A notification start alone would mark a run that did work as a wake.7902+ AND (${firstRootInput("run", "type")} IS 'user_message' OR ${holdsNoWork("run")})
juliusmarminge added labelstakeover:blocked
juliusmarminge removed labelstakeover:in-progress
github-actions[bot](GitHub profile, opens in a new tab) added labelsneeds-rebase
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed