fix(server): settle background agents the provider stopped reporting #9391
Closedamanthanvi(GitHub profile, opens in a new tab)wants to merge 15 commits into
main fromrefs/pull/9391/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/orchestration/ThreadTaskSettlement.ts line 211OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +191,21 @@191+ fillIdentity(entry, payload);192+ entries.set(taskId, entry);193+ break;194+ }195+ case "task.progress": {196+ const entry = existing ?? newEntry(taskId, payload, "running");197+ const status = asFoldStatus(payload.status);198+ if (status !== undefined) {199+ applyStatus(entry, status);200+ } else if (201+ // A usage-only tick must not restart a task that is already known.202+ // As the FIRST row for a task it does start it: the client fold203+ // does the same, so a child whose start row aged out of retention204+ // still reads as live on both sides instead of only one.205+ (payload.usageSnapshot !== true || existing === undefined) &&206+ entry.status !== "terminal" &&207+ entry.status !== "idle"208+ ) {209+ entry.status = "running";210+ }211+ entry.payload = payload;apps/server/src/serverRuntimeStartup.ts lines 470 to 470OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -457,3 +458,13 @@457458 !liveThreadIds.has(thread.id),458459 );459460461+ // Background work outlives the turn, so the headline case is wider than an462+ // orphaned turn: a thread whose turn ended is `ready` with no active turn463+ // while its children keep running. Any thread with a session this process464+ // does not own has lost that work, and a restart leaves the in-memory465+ // liveness registry empty while the persisted rows still read "running".466+ // Archived and deleted threads are skipped — settling writes rows.467+ for (const thread of threads) {468+ if (469+ thread.session === null ||470+ thread.session.status === "stopped" ||apps/server/src/orchestration/Layers/ProviderCommandReactor.ts line 1701Resolvedby amanthanvi(GitHub profile, opens in a new tab)@@ -1338,0 +1347,21 @@1347+ // already queued when Stop arrived has to land first — otherwise a1348+ // task.updated(running) from before the interrupt is written after the1349+ // settlement row and re-arms both the registry and the client fold.1350+ // Bounded: a hot event stream must not hold Stop hostage.1351+ const drained = yield* providerRuntimeIngestion.drain.pipe(1352+ Effect.timeoutOption(INTERRUPT_INGESTION_DRAIN_TIMEOUT),1353+ );1354+ if (Option.isNone(drained)) {1355+ yield* Effect.logWarning(1356+ "provider runtime ingestion did not drain before background task settlement",1357+ { threadId: event.payload.threadId },1358+ );1359+ }1360+1361+ // Stop is a host promise, not a provider request: children the provider1362+ // has already forgotten (compaction, a lost thread tree) never emit a1363+ // terminal event of their own, so settle the persisted rows here. Covers1364+ // both a successful interrupt and the stopSession fallback above; tasks1365+ // the provider does still own emit their own terminal rows afterwards,1366+ // which is harmless.1367+ yield* settleThreadTasks({apps/server/src/orchestration/ThreadTaskSettlement.ts lines 143 to 145OutdatedResolvedby amanthanvi(GitHub profile, opens in a new tab)@@ -0,0 +125,21 @@125+ }126+}127+128+function newEntry(taskId: string, payload: Record<string, unknown>, status: FoldStatus): FoldEntry {129+ return { taskId, status, payload, isWorkflow: false, parentAgentId: undefined };130+}131+132+/** Rows without the server-stamped agent classification are background work. */133+function isAgentRow(payload: Record<string, unknown>): boolean {134+ return payload.agentKind === "agent";135+}136+137+function asFoldStatus(value: unknown): FoldStatus | undefined {138+ return typeof value === "string" ? KNOWN_STATUSES.get(value) : undefined;139+}140+141+/** Terminal is sticky: a duplicate or late terminal row never slides state. */142+function applyStatus(entry: FoldEntry, next: FoldStatus): void {143+ if (entry.status === "terminal" && next === "terminal") {144+ return;145+ }
- apps/server/src/orchestration/ThreadTaskSettlement.ts lines 336 to 342OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +322,21 @@322+ const activity: OrchestrationThreadActivity = {323+ id: settledTaskActivityId(input.threadId, task.taskId),324+ createdAt: input.createdAt,325+ tone: "info",326+ kind: "task.updated",327+ summary: "Task interrupted",328+ payload: {329+ taskId: task.taskId,330+ status: input.status,331+ endedAt: input.createdAt,332+ ...task.linkage,333+ },334+ turnId: null,335+ };336+ yield* orchestrationEngine.dispatch({337+ type: "thread.activity.append",338+ commandId: CommandId.make(`task-settle:${yield* crypto.randomUUIDv4}`),339+ threadId: input.threadId,340+ activity,341+ createdAt: input.createdAt,342+ });
- apps/server/src/orchestration/ThreadTaskSettlement.ts line 470Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +426,21 @@426+ if (existing) {427+ existing.push(row);428+ } else {429+ rowsByThreadId.set(row.threadId, [row]);430+ }431+ }432+ for (const [threadId, threadRows] of rowsByThreadId) {433+ const liveTasks = selectLiveAgentTasks(threadRows);434+ if (liveTasks.length === 0) {435+ continue;436+ }437+ yield* writeSettledTasks({438+ threadId,439+ liveTasks,440+ status: input.status,441+ createdAt: input.createdAt,442+ });443+ }444+ });445+446+ yield* settle.pipe(withSettlementRecovery(input.threadIds));
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/orchestration/Layers/ProviderCommandReactor.ts line 1686Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1538,3 +1544,11 @@15381544 yield* providerService15391545 .interruptTurn({ threadId: event.payload.threadId })15401546 .pipe(Effect.catchCause(recoverInterruptFailure));1547+1548+ // Settlement reads persisted rows, so every provider event that was1549+ // already queued when Stop arrived has to land first — otherwise a1550+ // task.updated(running) from before the interrupt is written after the1551+ // settlement row and re-arms both the registry and the client fold.1552+ // Bounded: a hot event stream must not hold Stop hostage.1553+ const drained = yield* providerRuntimeIngestion.drain.pipe(1554+ Effect.timeoutOption(INTERRUPT_INGESTION_DRAIN_TIMEOUT),
- @@ -1671,0 +1685,21 @@1685+ const drained = yield* providerRuntimeIngestion.drain.pipe(1686+ Effect.timeoutOption(INTERRUPT_INGESTION_DRAIN_TIMEOUT),1687+ );1688+ if (Option.isNone(drained)) {1689+ yield* Effect.logWarning(1690+ "provider runtime ingestion did not drain before background task settlement",1691+ { threadId: event.payload.threadId },1692+ );1693+ }1694+1695+ // The host guarantees Stop; the provider does not. Children the provider1696+ // has already forgotten (compaction, a lost thread tree) never emit a1697+ // terminal event of their own, so settle the persisted rows here. Covers1698+ // both a successful interrupt and the stopSession fallback above; tasks1699+ // the provider does still own emit their own terminal rows afterwards,1700+ // which is harmless.1701+ yield* settleThreadTasks({1702+ threadId: event.payload.threadId,1703+ status: "interrupted",1704+ createdAt: event.payload.createdAt,1705+ });
juliusmarminge closed this
Sign in to join this conversation.


macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed