From 21f3d3776aa25e65d9f058a44b2365b02352f4ee Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 3 Nov 2026 12:43:03 +0000 Subject: [PATCH 1/6] test(server): reproduce #30156 awaited task lost when Claude exits while idle These tests reproduce #30156: when the Claude process exits while the thread is idle and holds an awaited background task, the run should record the task as cancelled background work and the agent should be woken with a note naming it. Co-Authored-By: Claude Opus 5.5 --- ...laudeAutomaticDelivery.integration.test.ts | 200 ++++++++++++++++++ 1 file changed, 200 insertions(+) diff --git a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts index e28bb374651dc..9837d52431ba1 100644 --- a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts +++ b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts @@ -20,6 +20,7 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; @@ -36,9 +37,11 @@ import * as EffectWorker from "./EffectWorker.ts"; import * as EventSink from "./EventSink.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import * as ProviderSessionManager from "./ProviderSessionManager.ts"; import * as ThreadLaunchService from "./ThreadLaunchService.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; import * as ServerSettings from "../serverSettings.ts"; @@ -490,3 +493,200 @@ it.effect.each(deliveries)( ), ), ); + +it.effect("wakes the agent when Claude's process exits while it awaits background work", () => + Effect.scoped( + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace("claude-idle-exit-awaited-task"); + const processes: Array> = []; + const offers: SDKUserMessage[] = []; + const taskId = "b8sleep180"; + const registry = Layer.unwrap( + Effect.gen(function* () { + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: modelSelection.instanceId, + settings, + environment: {}, + attachmentsDir: cwd, + fileSystem: yield* FileSystem.FileSystem, + path: yield* Path.Path, + random: yield* SecureRandom.SecureRandom, + idAllocator: yield* IdAllocator.IdAllocatorV2, + continuationRequests: yield* ProviderContinuationRequests.ProviderContinuationRequests, + queryRunner: { + allocateSessionId: Effect.succeed(sessionId), + open: () => + Effect.gen(function* () { + const sdkMessages = yield* Queue.unbounded(); + processes.push(sdkMessages); + return { + messages: Stream.fromQueue(sdkMessages), + offer: (message: SDKUserMessage) => + Effect.sync(() => void offers.push(message)), + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: Queue.shutdown(sdkMessages), + }; + }), + forkSession: () => Effect.die("unused"), + subagentLaunchToolUseId: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }); + return ProviderAdapterRegistry.layerSingle(adapter); + }), + ).pipe( + Layer.provide(Layer.mergeAll(IdAllocator.layer, NodeServices.layer, NodeCrypto.layer)), + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2; + const threadId = ThreadId.make("thread:idle-exit-awaited-task"); + const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) => + orchestrator.streamDomainEvents.pipe( + Stream.filter(predicate), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create"), + threadId, + projectId: ProjectId.make("project:idle-exit-awaited-task"), + title: "Idle exit", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + const running = yield* watch( + (event) => event.type === "provider-turn.updated" && event.payload.status === "running", + ); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("first"), + threadId, + messageId: MessageId.make("first"), + text: "Sleep 180 seconds in the background and wait for it.", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + yield* worker.drain(); + yield* Fiber.join(running); + const firstProcess = processes[0]!; + const rostered = yield* watch( + (event) => + event.type === "provider-thread.updated" && + event.payload.pendingBackgroundTasks?.some((task) => task.taskId === taskId) === true, + ); + yield* Queue.offer( + firstProcess, + frame({ + type: "system", + subtype: "background_tasks_changed", + tasks: [{ task_id: taskId, task_type: "local_bash", description: "sleep 180" }], + uuid: "roster", + session_id: sessionId, + }), + ); + yield* Fiber.join(rostered); + const records = yield* orchestrator.getThreadRecords(threadId, ["providerThreads"]); + const providerThread = records.providerThreads[0]!; + const runtime = yield* sessions.get(providerThread.providerSessionId!); + if (Option.isNone(runtime) || runtime.value.awaitBackgroundTasks === undefined) { + return yield* Effect.die("Claude runtime must accept background waits"); + } + const awaited = yield* watch( + (event) => + event.type === "provider-thread.updated" && + event.payload.pendingBackgroundTasks?.some((task) => task.awaited === true) === true, + ); + yield* runtime.value.awaitBackgroundTasks({ + providerThread, + taskIds: [taskId], + awaited: true, + }); + yield* Fiber.join(awaited); + const settled = yield* watch( + (event) => + event.type === "run.updated" && + (event.payload.status === "waiting" || event.payload.status === "completed"), + ); + yield* Queue.offer(firstProcess, result("waiting-on-sleep", false)); + yield* Fiber.join(settled); + yield* worker.drain(); + const beforeExit = yield* orchestrator.getThreadProjection(threadId); + const firstRun = beforeExit.runs[0]!; + assert.deepEqual( + beforeExit.providerThreads[0]?.pendingBackgroundTasks?.map((task) => [ + task.taskId, + task.awaited, + ]), + [[taskId, true]], + ); + + const cleared = yield* watch( + (event) => + event.type === "provider-thread.updated" && + event.payload.pendingBackgroundTasks?.length === 0, + ); + const woken = yield* watch( + (event) => event.type === "run.updated" && event.payload.id !== firstRun.id, + ); + // The CLI exits (SIGTERM) while the thread is idle; the T3 server keeps running. + yield* Queue.shutdown(firstProcess); + yield* Fiber.join(cleared); + yield* worker.drain(); + + const afterExit = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual( + afterExit.runs + .find((run) => run.id === firstRun.id) + ?.restartCancelledBackgroundWork?.map((work) => work.id), + [taskId], + "the run must record the awaited task the exited process took with it", + ); + yield* Fiber.join(woken); + yield* worker.drain(); + assert.isTrue( + offers.slice(1).some((offer) => JSON.stringify(offer.message).includes(taskId)), + "the agent must be woken with a note naming the lost task", + ); + assert.equal( + (yield* orchestrator.getThreadProjection(threadId)).messages.filter( + (message) => message.createdBy === "user", + ).length, + 1, + ); + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { name: "claude-idle-exit-awaited-task" }, + registry, + { runEffectWorker: false, runContinuationWorker: true }, + ), + ), + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), +); From f154b7536648e8b3f4cb3d039e33fbac00f1294a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 3 Nov 2026 13:10:02 +0000 Subject: [PATCH 2/6] fix(server): wake the agent when Claude exits while awaiting background work When the Claude process exited on its own while the thread was idle, its background-task roster was cleared and the awaited work vanished until the next user message. The adapter now reports the roster tasks the exit took with it (minus any whose task_notification is already buffered) on its provider-thread update. The ingestor records them on the provider thread's latest run as cancelled background work, as server-restart recovery does, and queues the restart continuation in the same commit. The continuation wakes the agent only for awaited work and keeps its project-setting gate; the note and notification say the provider process exited instead of claiming a server restart. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.ts | 32 ++++++-- ...laudeAutomaticDelivery.integration.test.ts | 54 ++++++++----- apps/server/src/orchestration-v2/EventSink.ts | 12 ++- .../orchestration-v2/ProviderEventIngestor.ts | 79 +++++++++++++++++-- .../ProviderRuntimeRecoveryService.ts | 22 +----- .../orchestration-v2/RestartBackgroundNote.ts | 24 +++++- .../orchestration-v2/RestartContinuation.ts | 9 ++- packages/contracts/src/orchestrationV2.ts | 2 + .../src/server/ProviderAdapter.ts | 3 + 9 files changed, 177 insertions(+), 60 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 674f55c524d75..1873871ba93b4 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -5363,6 +5363,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( readonly nativeThreadId: string; readonly providerThread: OrchestrationV2ProviderThread; readonly status?: OrchestrationV2ProviderThread["status"]; + readonly lostBackgroundTasks?: ReadonlyArray; }) { const roster = rosterForNativeThread( yield* Ref.get(pendingBackgroundTasksByNativeThread), @@ -5388,6 +5389,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( type: "provider_thread.updated", driver: CLAUDE_PROVIDER, providerThread, + ...(input.lostBackgroundTasks === undefined || input.lostBackgroundTasks.length === 0 + ? {} + : { lostBackgroundTasks: input.lostBackgroundTasks }), }); }); @@ -5572,13 +5576,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( nativeThreadId: string, options?: { readonly status?: OrchestrationV2ProviderThread["status"]; + /** The process exited on its own, so roster tasks without a buffered outcome are lost. */ + readonly exitedUnexpectedly?: boolean; }, ) { - const hadRoster = - rosterForNativeThread( - yield* Ref.get(pendingBackgroundTasksByNativeThread), - nativeThreadId, - ).size > 0; + const roster = rosterForNativeThread( + yield* Ref.get(pendingBackgroundTasksByNativeThread), + nativeThreadId, + ); + const hadRoster = roster.size > 0; const remembered = (yield* Ref.get(lastProviderThreadByNativeThread)).get(nativeThreadId); const hadPersistedRoster = (remembered?.pendingBackgroundTasks?.length ?? 0) > 0; const priorOpaqueTombstones = taskIdSetForNativeThread( @@ -5597,6 +5603,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const preservedOpaqueTombstones = [...priorOpaqueTombstones].filter((taskId) => bufferedTaskNotificationIds.has(taskId), ); + // A buffered task_notification already reports its outcome through the wake buffer. + const lostBackgroundTasks = + options?.exitedUnexpectedly === true + ? claudePendingBackgroundTasksFromRoster( + roster, + taskIdSetForNativeThread( + yield* Ref.get(awaitedBackgroundTasksByNativeThread), + nativeThreadId, + ), + ).filter((task) => !bufferedTaskNotificationIds.has(task.taskId)) + : []; yield* clearPendingBackgroundTasksForNativeThread(nativeThreadId); yield* clearNativeThreadTaskIdSet( wakeEligibleBackgroundTasksByNativeThread, @@ -5631,6 +5648,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( nativeThreadId, providerThread: remembered, status, + lostBackgroundTasks, }); }); @@ -7963,7 +7981,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }), }); } else { - yield* resetBackgroundTaskStateForNativeThreadProcess(closedQuery.nativeThreadId); + yield* resetBackgroundTaskStateForNativeThreadProcess(closedQuery.nativeThreadId, { + exitedUnexpectedly: !interrupted, + }); } // Preserve buffered outcomes before Stop clears the wake buffer. yield* endSubagentsOfClosedQuery({ diff --git a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts index 9837d52431ba1..efd5a0f8423ec 100644 --- a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts +++ b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts @@ -494,7 +494,7 @@ it.effect.each(deliveries)( ), ); -it.effect("wakes the agent when Claude's process exits while it awaits background work", () => +const exitWhileIdle = (awaited: boolean) => Effect.scoped( Effect.gen(function* () { const cwd = yield* checkpointWorkspace("claude-idle-exit-awaited-task"); @@ -601,23 +601,25 @@ it.effect("wakes the agent when Claude's process exits while it awaits backgroun }), ); yield* Fiber.join(rostered); - const records = yield* orchestrator.getThreadRecords(threadId, ["providerThreads"]); - const providerThread = records.providerThreads[0]!; - const runtime = yield* sessions.get(providerThread.providerSessionId!); - if (Option.isNone(runtime) || runtime.value.awaitBackgroundTasks === undefined) { - return yield* Effect.die("Claude runtime must accept background waits"); + if (awaited) { + const records = yield* orchestrator.getThreadRecords(threadId, ["providerThreads"]); + const providerThread = records.providerThreads[0]!; + const runtime = yield* sessions.get(providerThread.providerSessionId!); + if (Option.isNone(runtime) || runtime.value.awaitBackgroundTasks === undefined) { + return yield* Effect.die("Claude runtime must accept background waits"); + } + const awaitedRoster = yield* watch( + (event) => + event.type === "provider-thread.updated" && + event.payload.pendingBackgroundTasks?.some((task) => task.awaited === true) === true, + ); + yield* runtime.value.awaitBackgroundTasks({ + providerThread, + taskIds: [taskId], + awaited: true, + }); + yield* Fiber.join(awaitedRoster); } - const awaited = yield* watch( - (event) => - event.type === "provider-thread.updated" && - event.payload.pendingBackgroundTasks?.some((task) => task.awaited === true) === true, - ); - yield* runtime.value.awaitBackgroundTasks({ - providerThread, - taskIds: [taskId], - awaited: true, - }); - yield* Fiber.join(awaited); const settled = yield* watch( (event) => event.type === "run.updated" && @@ -633,7 +635,7 @@ it.effect("wakes the agent when Claude's process exits while it awaits backgroun task.taskId, task.awaited, ]), - [[taskId, true]], + [[taskId, awaited ? true : undefined]], ); const cleared = yield* watch( @@ -657,6 +659,13 @@ it.effect("wakes the agent when Claude's process exits while it awaits backgroun [taskId], "the run must record the awaited task the exited process took with it", ); + // Drained effects already dispatched any wake, so a missing one fails here instead of hanging. + assert.equal( + afterExit.runs.some((run) => run.id !== firstRun.id), + awaited, + "only awaited work wakes the agent without a user message", + ); + if (!awaited) return; yield* Fiber.join(woken); yield* worker.drain(); assert.isTrue( @@ -688,5 +697,12 @@ it.effect("wakes the agent when Claude's process exits while it awaits backgroun ), ), ), - ), + ); + +it.effect("wakes the agent when Claude's process exits while it awaits background work", () => + exitWhileIdle(true), +); + +it.effect("records but does not wake for an unawaited shell lost when Claude's process exits", () => + exitWhileIdle(false), ); diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.ts index b210d3c9840ae..6dd7507ab657c 100644 --- a/apps/server/src/orchestration-v2/EventSink.ts +++ b/apps/server/src/orchestration-v2/EventSink.ts @@ -117,6 +117,7 @@ export interface EventSinkV2Shape { readonly activeAttemptId: RunAttemptId; readonly expectedLastRunOrdinal: number; readonly events: ReadonlyArray; + readonly effects?: ReadonlyArray; }) => Effect.Effect< { readonly committed: boolean; @@ -571,12 +572,17 @@ const layerBase: Layer.Layer< events: normalized, }); const outcomes = yield* applyStoredEvents(storedEvents); + yield* effectOutbox.enqueue(input.effects ?? []); return { committed: true as const, storedEvents, outcomes }; }), (result) => - result.committed - ? publishStoredEvents(result.storedEvents, result.outcomes) - : Effect.void, + Effect.gen(function* () { + if (!result.committed) return; + if (input.effects !== undefined && input.effects.length > 0) { + yield* effectOutbox.notifyAvailable(input.effects.length); + } + yield* publishStoredEvents(result.storedEvents, result.outcomes); + }), ); }); diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts index f27580d909aff..89080f69bd034 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts @@ -41,6 +41,11 @@ import { makeProviderFailureTurnItem } from "@t3tools/provider-core/server/failu import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; import { stripUnservedToolOutputImageBytes } from "./toolOutputImageBytes.ts"; import { boundFileChangeForStorage } from "./WireProjection.ts"; +import { + cancelledRosterTaskWork, + latestStartedRun, + mergeRestartCancelledBackgroundWork, +} from "./RestartBackgroundNote.ts"; export class ProviderEventNormalizeError extends Schema.TaggedError()( "ProviderEventNormalizeError", @@ -456,6 +461,39 @@ export const layer: Layer.Layer< return events; }); + // The run records what an unexpected process exit took, as a server restart would. + const lostBackgroundWorkEvents = Effect.fnUntraced(function* ( + input: ProviderEventIngestInput, + threadId: ThreadId, + ) { + if (input.event.type !== "provider_thread.updated") return []; + const lostTasks = input.event.lostBackgroundTasks ?? []; + if (lostTasks.length === 0 || input.event.providerThread.ownerNodeId !== null) return []; + const run = latestStartedRun( + (yield* projections.getThreadRecords(threadId, ["runs"])).runs, + input.event.providerThread.id, + ); + if (run === undefined) return []; + const work = lostTasks.map((task) => ({ + ...cancelledRosterTaskWork(task), + cause: "provider_exit" as const, + })); + return [ + yield* makeDomainEvent(input, { + type: "run.background-work-cancelled", + threadId, + runId: run.id, + payload: { + runId: run.id, + restartCancelledBackgroundWork: mergeRestartCancelledBackgroundWork( + run.restartCancelledBackgroundWork ?? [], + work, + ), + }, + }), + ]; + }); + const normalize: ProviderEventIngestorV2Shape["normalize"] = /* This helper runs for individual orchestration events; the enclosing operation owns the span. */ Effect.fnUntraced( @@ -507,10 +545,12 @@ export const layer: Layer.Layer< threadId, payload: input.event.providerThread, }); + const lost = yield* lostBackgroundWorkEvents(input, threadId); return input.event.retainedNativeTurnIds === undefined - ? [updated] + ? [updated, ...lost] : [ updated, + ...lost, ...(yield* rollBackRewoundRuns(input, { threadId, providerThreadId: input.event.providerThread.id, @@ -677,6 +717,24 @@ export const layer: Layer.Layer< if (events.length === 0) { return []; } + // The continuation wakes the agent only for awaited work; the rest rides along on the next user message. + const effects = events.flatMap((event) => + event.type === "run.background-work-cancelled" + ? [ + { + id: `effect:restart-continuation:${event.payload.runId}`, + commandId: + input.commandId ?? + CommandId.make(`command:provider-exit:${event.payload.runId}`), + threadId: event.threadId, + request: { + type: "provider-runtime.continue" as const, + sourceRunId: event.payload.runId, + }, + }, + ] + : [], + ); const mapWriteError = (cause: unknown) => new ProviderEventPublishError({ providerSessionId: input.providerSessionId, @@ -690,18 +748,22 @@ export const layer: Layer.Layer< ...(input.commandId === undefined ? {} : { commandId: input.commandId }), ...input.writeIfProviderThreadOwner, events, + ...(effects.length === 0 ? {} : { effects }), }) .pipe(retryLockTimeout, Effect.mapError(mapWriteError)); return ownerResult.storedEvents; } if (input.writeIfRunCurrent === undefined) { - return yield* eventSink - .write({ - guardPendingUserInputCancellations: true, - ...(input.commandId === undefined ? {} : { commandId: input.commandId }), - events, - }) - .pipe(retryLockTimeout, Effect.mapError(mapWriteError)); + const write = { + guardPendingUserInputCancellations: true, + ...(input.commandId === undefined ? {} : { commandId: input.commandId }), + events, + }; + return yield* ( + effects.length === 0 + ? eventSink.write(write) + : eventSink.writeWithEffects({ ...write, effects }) + ).pipe(retryLockTimeout, Effect.mapError(mapWriteError)); } const result = yield* eventSink .writeIfRunCurrent({ @@ -710,6 +772,7 @@ export const layer: Layer.Layer< threadId: input.threadId, ...input.writeIfRunCurrent, events, + ...(effects.length === 0 ? {} : { effects }), }) .pipe(retryLockTimeout, Effect.mapError(mapWriteError)); return result.storedEvents; diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts index c344357972268..3990e5b1d0f6f 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts @@ -1,4 +1,3 @@ -import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { CommandId, @@ -32,9 +31,9 @@ import { import { awaitingProviderThreadId, cancelledRosterTaskWork, + latestStartedRun, cancelledTurnItemWork, mergeRestartCancelledBackgroundWork, - neverStarted, } from "./RestartBackgroundNote.ts"; export class ProviderRuntimeRecoveryError extends Schema.TaggedError()( @@ -156,23 +155,6 @@ const cancelledItem = ( ? { ...item, status: "cancelled", secretStatus: "cancelled", completedAt: now, updatedAt: now } : { ...item, status: "cancelled", completedAt: now, updatedAt: now }; -function latestStartedRun( - projection: ProjectionStore.ProjectionRuntimeRecoveryState, - providerThreadId: ProviderThreadId, -) { - return projection.runs.reduce( - (latest, run) => - run.providerThreadId === providerThreadId && - run.status !== "queued" && - run.status !== "rolled_back" && - !neverStarted(run) && - (latest === undefined || runRanAfter(run, latest)) - ? run - : latest, - undefined, - ); -} - export const make = Effect.gen(function* () { const settings = yield* ServerSettings.ServerSettingsService; const projections = yield* ProjectionStore.ProjectionStoreV2; @@ -630,7 +612,7 @@ export const make = Effect.gen(function* () { }); } for (const [providerThreadId, work] of cancelledBackgroundWork) { - const noteRun = latestStartedRun(projection, providerThreadId); + const noteRun = latestStartedRun(projection.runs, providerThreadId); if (noteRun === undefined) continue; // Use a separate event; stale run snapshots can overwrite intervening lifecycle changes. events.push({ diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts index 24afd61d6186a..9ec80344b8576 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts @@ -118,11 +118,16 @@ export function cancelledRosterTaskWork(task: OrchestrationV2PendingBackgroundTa const MAX_NOTE_ENTRIES = 10; +/** Work lost to an unexpected provider process exit; the T3 server kept running. */ +export function cancelledByProviderExit(work: ReadonlyArray>): boolean { + return work.length > 0 && work.every((entry) => entry.cause === "provider_exit"); +} + /** Bounds entries and labels to protect the context budget. */ export function restartCancelledBackgroundWorkNote(work: ReadonlyArray): string { const omitted = work.length - MAX_NOTE_ENTRIES; return [ - "Note: the T3 server restarted, and this background work was cancelled before it finished. It will not report back on its own, so resume or restart what you still need and wait for its result:", + `Note: ${cancelledByProviderExit(work) ? "the provider process exited" : "the T3 server restarted"}, and this background work was cancelled before it finished. It will not report back on its own, so resume or restart what you still need and wait for its result:`, ...work.slice(0, MAX_NOTE_ENTRIES).map((entry) => `- ${entry.kind}: ${entry.label}`), ...(omitted > 0 ? [`- and ${omitted} more`] : []), ].join("\n"); @@ -167,6 +172,23 @@ export function runOutcome( : run.status; } +export function latestStartedRun( + runs: ReadonlyArray, + providerThreadId: NonNullable, +): OrchestrationV2Run | undefined { + return runs.reduce( + (latest, run) => + run.providerThreadId === providerThreadId && + run.status !== "queued" && + run.status !== "rolled_back" && + !neverStarted(run) && + (latest === undefined || runRanAfter(run, latest)) + ? run + : latest, + undefined, + ); +} + /** Unstarted runs have no lost work to continue, except prepared continuations carrying a source run. */ export function neverStarted( run: Pick, diff --git a/apps/server/src/orchestration-v2/RestartContinuation.ts b/apps/server/src/orchestration-v2/RestartContinuation.ts index 20d110d335aa2..d818afeb64d1b 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.ts @@ -18,6 +18,7 @@ import { isNativeMaintenanceCommand } from "./CommandPolicy.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; import { awaitingProviderThreadId, + cancelledByProviderExit, cancelledRosterTaskWork, cancelledTurnItemWork, continuationFailedBeforePrompt, @@ -315,9 +316,11 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta notification: { source: { kind: "system" }, outcome: "updated", - summary: note.settled - ? "T3 Code restarted and stopped background work" - : "T3 Code restarted and resumed this turn", + summary: cancelledByProviderExit(note.work) + ? "The provider process exited and stopped background work" + : note.settled + ? "T3 Code restarted and stopped background work" + : "T3 Code restarted and resumed this turn", detail: text, }, attachments: [], diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 785f41e3aa0fb..3e2514ede9a83 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -640,6 +640,8 @@ export const OrchestrationV2RestartCancelledBackgroundWork = Schema.Struct({ id: Schema.optional(TrimmedNonEmptyString), /** The agent was waiting on this work, so its restart note wakes the agent even for a shell. */ awaited: Schema.optional(Schema.Literal(true)), + /** Absent when a T3 server restart or shutdown cancelled the work. */ + cause: Schema.optional(Schema.Literal("provider_exit")), }); export type OrchestrationV2RestartCancelledBackgroundWork = typeof OrchestrationV2RestartCancelledBackgroundWork.Type; diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 9d83da489b306..484585cd07771 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -8,6 +8,7 @@ import { OrchestrationV2AppThread, OrchestrationV2ConversationMessage, OrchestrationV2ExecutionNode, + OrchestrationV2PendingBackgroundTask, OrchestrationV2ProviderSession, OrchestrationV2PlanArtifact, OrchestrationV2ProviderCapabilities, @@ -99,6 +100,8 @@ export const ProviderAdapterV2Event = Schema.Union([ /** Work remaining at this point in the event stream, including native continuations. */ pendingBackgroundWork: Schema.optional(Schema.Boolean), retainedNativeTurnIds: Schema.optional(Schema.Array(Schema.String)), + /** Roster tasks an unexpected provider process exit took with it. */ + lostBackgroundTasks: Schema.optional(Schema.Array(OrchestrationV2PendingBackgroundTask)), }), Schema.Struct({ type: Schema.Literal("provider_turn.updated"), From cb0a1801c561cb9202a16b80602f84e959ad22bb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 3 Nov 2026 13:33:16 +0000 Subject: [PATCH 3/6] fix(server): wake the agent when Claude stops awaited work before exiting On SIGTERM, Claude reports the awaited task as stopped and empties its roster before the process exits. The roster snapshot then had nothing to report, the buffered notification's wake never ran, and the run's event subscription had already closed. An idle outcome's wake report now keeps its roster task and await mark. An unexpected idle exit reports those whose wake never started, plus roster tasks, as a background_work.lost event that the session ingests without a run. This replaces the provider_thread.updated field and the owner-guarded write effects. Query replacement now marks the old query stopping so it is not reported as an exit, and the note no longer claims the work was cancelled. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.ts | 76 ++++++++++++++----- ...laudeAutomaticDelivery.integration.test.ts | 56 +++++++++++--- apps/server/src/orchestration-v2/EventSink.ts | 12 +-- .../orchestration-v2/ProviderEventIngestor.ts | 21 +++-- .../ProviderSessionManager.ts | 12 +-- .../orchestration-v2/RestartBackgroundNote.ts | 4 +- .../orchestration-v2/RestartContinuation.ts | 2 +- .../orchestration-v2/RunExecutionService.ts | 3 +- .../src/server/ProviderAdapter.ts | 11 ++- 9 files changed, 138 insertions(+), 59 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 1873871ba93b4..9cbcea9e91825 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -558,6 +558,13 @@ export interface ClaudeAgentSdkQuerySession { type ClaudeQueryStreamExit = Exit.Exit; +interface WakeReportEntry { + readonly report: BackgroundWorkReport; + readonly turn: number; + /** The roster task, with the agent's await mark, whose idle outcome this reports. */ + readonly task?: OrchestrationV2PendingBackgroundTask; +} + export class ClaudeAgentSdkQueryRunnerError extends Schema.TaggedError()( "ClaudeAgentSdkQueryRunnerError", { @@ -4954,10 +4961,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( // Keep report stamps atomic with turn changes. const wakeReportsByNativeThread = yield* Ref.make<{ readonly userTurns: ReadonlyMap; - readonly reports: ReadonlyMap< - string, - ReadonlyMap - >; + readonly reports: ReadonlyMap>; }>({ userTurns: new Map(), reports: new Map() }); const backgroundedSubagentTaskIds = yield* Ref.make>(new Set()); // Nested subagent completions notify their owner and never wake the root. @@ -4968,6 +4972,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( nativeThreadId: string, taskId: string, report: BackgroundWorkReport, + task?: OrchestrationV2PendingBackgroundTask, ) => Ref.update(wakeReportsByNativeThread, ({ userTurns, reports }) => ({ userTurns, @@ -4976,6 +4981,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( new Map(reports.get(nativeThreadId)).set(taskId, { report, turn: userTurns.get(nativeThreadId) ?? 0, + ...(task === undefined ? {} : { task }), }), ), })); @@ -5001,6 +5007,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); const clearWakeReports = (nativeThreadId: string) => takeWakeReports(nativeThreadId).pipe(Effect.asVoid); + // Reports from before the latest user turn reached the agent in that turn. + const takeUnwokenReportTasks = (nativeThreadId: string) => + Ref.modify(wakeReportsByNativeThread, ({ userTurns, reports }) => { + const turn = userTurns.get(nativeThreadId) ?? 0; + const tasks = [...(reports.get(nativeThreadId)?.values() ?? [])].flatMap((entry) => + entry.task !== undefined && entry.turn === turn ? [entry.task] : [], + ); + const remaining = new Map(reports); + remaining.delete(nativeThreadId); + return [tasks, { userTurns, reports: remaining }] as const; + }); // Empty roster levels can precede notifications; retain tasks for wake attribution. const lastKnownOpaqueTasks = yield* Ref.make( new Map(), @@ -5363,7 +5380,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( readonly nativeThreadId: string; readonly providerThread: OrchestrationV2ProviderThread; readonly status?: OrchestrationV2ProviderThread["status"]; - readonly lostBackgroundTasks?: ReadonlyArray; }) { const roster = rosterForNativeThread( yield* Ref.get(pendingBackgroundTasksByNativeThread), @@ -5389,9 +5405,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( type: "provider_thread.updated", driver: CLAUDE_PROVIDER, providerThread, - ...(input.lostBackgroundTasks === undefined || input.lostBackgroundTasks.length === 0 - ? {} - : { lostBackgroundTasks: input.lostBackgroundTasks }), }); }); @@ -5603,16 +5616,21 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const preservedOpaqueTombstones = [...priorOpaqueTombstones].filter((taskId) => bufferedTaskNotificationIds.has(taskId), ); - // A buffered task_notification already reports its outcome through the wake buffer. + // Claude reports an idle outcome only by waking itself, so an exit before that wake loses it. const lostBackgroundTasks = options?.exitedUnexpectedly === true - ? claudePendingBackgroundTasksFromRoster( - roster, - taskIdSetForNativeThread( - yield* Ref.get(awaitedBackgroundTasksByNativeThread), - nativeThreadId, - ), - ).filter((task) => !bufferedTaskNotificationIds.has(task.taskId)) + ? [ + ...claudePendingBackgroundTasksFromRoster( + roster, + taskIdSetForNativeThread( + yield* Ref.get(awaitedBackgroundTasksByNativeThread), + nativeThreadId, + ), + ).filter((task) => !bufferedTaskNotificationIds.has(task.taskId)), + ...((yield* Ref.get(requestedContinuations)).has(nativeThreadId) + ? [] + : yield* takeUnwokenReportTasks(nativeThreadId)), + ] : []; yield* clearPendingBackgroundTasksForNativeThread(nativeThreadId); yield* clearNativeThreadTaskIdSet( @@ -5630,10 +5648,19 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( preservedOpaqueTombstones, ); } - if (!hadRoster && !hadPersistedRoster) { + if (remembered === undefined) { return; } - if (remembered === undefined) { + if (lostBackgroundTasks.length > 0 && remembered.appThreadId !== null) { + yield* emitProviderEvent({ + type: "background_work.lost", + driver: CLAUDE_PROVIDER, + threadId: remembered.appThreadId, + providerThreadId: remembered.id, + tasks: lostBackgroundTasks, + }); + } + if (!hadRoster && !hadPersistedRoster) { return; } const activeContext = yield* Ref.get(activeTurn); @@ -5648,7 +5675,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( nativeThreadId, providerThread: remembered, status, - lostBackgroundTasks, }); }); @@ -8142,10 +8168,21 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ? message.summary : null; if (isPendingTaskNotification) { + const task = claudePendingBackgroundTasksFromRoster( + rosterForNativeThread( + yield* Ref.get(pendingBackgroundTasksByNativeThread), + wakeInput.nativeThreadId, + ), + taskIdSetForNativeThread( + yield* Ref.get(awaitedBackgroundTasksByNativeThread), + wakeInput.nativeThreadId, + ), + ).find((candidate) => candidate.taskId === message.task_id); yield* recordWakeReport( wakeInput.nativeThreadId, message.task_id, yield* opaqueTaskWakeReport(wakeInput.nativeThreadId, message), + task, ); } else if (isPendingSubagentNotification) { const registered = (yield* Ref.get(sessionSubagentsByTaskId)).get(message.task_id); @@ -10506,6 +10543,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); const closedExistingNativeThreadId = existing !== null ? existing.nativeThreadId : null; if (existing !== null) { + existing.stopping = true; yield* existing.query.close.pipe(Effect.ignore); if (existing.nativeThreadId !== nativeThreadId) { yield* clearWakeStateForNativeThread(existing.nativeThreadId); diff --git a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts index efd5a0f8423ec..37f572ddccf67 100644 --- a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts +++ b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts @@ -494,7 +494,8 @@ it.effect.each(deliveries)( ), ); -const exitWhileIdle = (awaited: boolean) => +// SIGKILL ends the stream without a frame. SIGTERM makes the CLI stop its tasks first. +const exitWhileIdle = (awaited: boolean, signal: "SIGKILL" | "SIGTERM") => Effect.scoped( Effect.gen(function* () { const cwd = yield* checkpointWorkspace("claude-idle-exit-awaited-task"); @@ -638,17 +639,48 @@ const exitWhileIdle = (awaited: boolean) => [[taskId, awaited ? true : undefined]], ); - const cleared = yield* watch( - (event) => - event.type === "provider-thread.updated" && - event.payload.pendingBackgroundTasks?.length === 0, - ); + const recorded = yield* watch((event) => event.type === "run.background-work-cancelled"); const woken = yield* watch( (event) => event.type === "run.updated" && event.payload.id !== firstRun.id, ); - // The CLI exits (SIGTERM) while the thread is idle; the T3 server keeps running. + if (signal === "SIGTERM") { + const stopped = yield* watch( + (event) => + event.type === "provider-thread.updated" && + event.payload.pendingBackgroundTasks?.length === 0, + ); + yield* Queue.offerAll(firstProcess, [ + frame({ + type: "system", + subtype: "task_notification", + task_id: taskId, + status: "stopped", + output_file: "", + summary: "sleep 180", + uuid: "stopped", + session_id: sessionId, + }), + frame({ + type: "system", + subtype: "task_updated", + task_id: taskId, + patch: { status: "killed", end_time: 1 }, + uuid: "killed", + session_id: sessionId, + }), + frame({ + type: "system", + subtype: "background_tasks_changed", + tasks: [], + uuid: "roster-empty", + session_id: sessionId, + }), + ]); + yield* Fiber.join(stopped); + } + // The CLI exits while the thread is idle; the T3 server keeps running. yield* Queue.shutdown(firstProcess); - yield* Fiber.join(cleared); + yield* Fiber.join(recorded); yield* worker.drain(); const afterExit = yield* orchestrator.getThreadProjection(threadId); @@ -700,9 +732,13 @@ const exitWhileIdle = (awaited: boolean) => ); it.effect("wakes the agent when Claude's process exits while it awaits background work", () => - exitWhileIdle(true), + exitWhileIdle(true, "SIGKILL"), +); + +it.effect("wakes the agent when Claude stops awaited background work before exiting", () => + exitWhileIdle(true, "SIGTERM"), ); it.effect("records but does not wake for an unawaited shell lost when Claude's process exits", () => - exitWhileIdle(false), + exitWhileIdle(false, "SIGKILL"), ); diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.ts index 6dd7507ab657c..b210d3c9840ae 100644 --- a/apps/server/src/orchestration-v2/EventSink.ts +++ b/apps/server/src/orchestration-v2/EventSink.ts @@ -117,7 +117,6 @@ export interface EventSinkV2Shape { readonly activeAttemptId: RunAttemptId; readonly expectedLastRunOrdinal: number; readonly events: ReadonlyArray; - readonly effects?: ReadonlyArray; }) => Effect.Effect< { readonly committed: boolean; @@ -572,17 +571,12 @@ const layerBase: Layer.Layer< events: normalized, }); const outcomes = yield* applyStoredEvents(storedEvents); - yield* effectOutbox.enqueue(input.effects ?? []); return { committed: true as const, storedEvents, outcomes }; }), (result) => - Effect.gen(function* () { - if (!result.committed) return; - if (input.effects !== undefined && input.effects.length > 0) { - yield* effectOutbox.notifyAvailable(input.effects.length); - } - yield* publishStoredEvents(result.storedEvents, result.outcomes); - }), + result.committed + ? publishStoredEvents(result.storedEvents, result.outcomes) + : Effect.void, ); }); diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts index 89080f69bd034..0a725e5655614 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts @@ -464,17 +464,18 @@ export const layer: Layer.Layer< // The run records what an unexpected process exit took, as a server restart would. const lostBackgroundWorkEvents = Effect.fnUntraced(function* ( input: ProviderEventIngestInput, - threadId: ThreadId, + event: Extract< + ProviderAdapter.ProviderAdapterV2Event, + { readonly type: "background_work.lost" } + >, ) { - if (input.event.type !== "provider_thread.updated") return []; - const lostTasks = input.event.lostBackgroundTasks ?? []; - if (lostTasks.length === 0 || input.event.providerThread.ownerNodeId !== null) return []; + const threadId = event.threadId; const run = latestStartedRun( (yield* projections.getThreadRecords(threadId, ["runs"])).runs, - input.event.providerThread.id, + event.providerThreadId, ); if (run === undefined) return []; - const work = lostTasks.map((task) => ({ + const work = event.tasks.map((task) => ({ ...cancelledRosterTaskWork(task), cause: "provider_exit" as const, })); @@ -545,12 +546,10 @@ export const layer: Layer.Layer< threadId, payload: input.event.providerThread, }); - const lost = yield* lostBackgroundWorkEvents(input, threadId); return input.event.retainedNativeTurnIds === undefined - ? [updated, ...lost] + ? [updated] : [ updated, - ...lost, ...(yield* rollBackRewoundRuns(input, { threadId, providerThreadId: input.event.providerThread.id, @@ -658,6 +657,8 @@ export const layer: Layer.Layer< } case "background_work.updated": return []; + case "background_work.lost": + return yield* lostBackgroundWorkEvents(input, input.event); case "command_output.delta": // Live output is routed to the command output hub before ingestion. return []; @@ -748,7 +749,6 @@ export const layer: Layer.Layer< ...(input.commandId === undefined ? {} : { commandId: input.commandId }), ...input.writeIfProviderThreadOwner, events, - ...(effects.length === 0 ? {} : { effects }), }) .pipe(retryLockTimeout, Effect.mapError(mapWriteError)); return ownerResult.storedEvents; @@ -772,7 +772,6 @@ export const layer: Layer.Layer< threadId: input.threadId, ...input.writeIfRunCurrent, events, - ...(effects.length === 0 ? {} : { effects }), }) .pipe(retryLockTimeout, Effect.mapError(mapWriteError)); return result.storedEvents; diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index f06011676c667..c5bc2bd139615 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -270,10 +270,12 @@ function sessionKey(providerSessionId: ProviderSessionId): string { return String(providerSessionId); } -function sessionScopedRuntimeRequestThreadId( +function sessionScopedEventThreadId( event: ProviderAdapter.ProviderAdapterV2Event, ): ThreadId | undefined { switch (event.type) { + case "background_work.lost": + return event.threadId; case "runtime_request.updated": return event.runtimeRequest.providerTurnId === null ? event.threadId : undefined; case "node.updated": @@ -2001,10 +2003,10 @@ export const layerWithOptions = ( }); } // Some providers can block before a run subscriber exists - // (project trust, login, or session-switch hooks). Persist - // their runless request artifacts directly so the normal T3 - // request UI can answer them and unblock session setup. - const threadId = sessionScopedRuntimeRequestThreadId(event); + // (project trust, login, or session-switch hooks), and lost + // work can follow the last one. Persist these runless events + // directly so the normal T3 request UI can answer them. + const threadId = sessionScopedEventThreadId(event); if (threadId !== undefined) { yield* Effect.gen(function* () { const current = (yield* Ref.get(sessions)).get( diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts index 9ec80344b8576..0bc1882333754 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts @@ -127,7 +127,9 @@ export function cancelledByProviderExit(work: ReadonlyArray> export function restartCancelledBackgroundWorkNote(work: ReadonlyArray): string { const omitted = work.length - MAX_NOTE_ENTRIES; return [ - `Note: ${cancelledByProviderExit(work) ? "the provider process exited" : "the T3 server restarted"}, and this background work was cancelled before it finished. It will not report back on its own, so resume or restart what you still need and wait for its result:`, + cancelledByProviderExit(work) + ? "Note: your agent process exited before this background work reported back. It will not report back on its own, so check or restart what you still need and wait for its result:" + : "Note: the T3 server restarted, and this background work was cancelled before it finished. It will not report back on its own, so resume or restart what you still need and wait for its result:", ...work.slice(0, MAX_NOTE_ENTRIES).map((entry) => `- ${entry.kind}: ${entry.label}`), ...(omitted > 0 ? [`- and ${omitted} more`] : []), ].join("\n"); diff --git a/apps/server/src/orchestration-v2/RestartContinuation.ts b/apps/server/src/orchestration-v2/RestartContinuation.ts index d818afeb64d1b..5f76a066bc0ae 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.ts @@ -317,7 +317,7 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta source: { kind: "system" }, outcome: "updated", summary: cancelledByProviderExit(note.work) - ? "The provider process exited and stopped background work" + ? "The agent process exited before background work reported back" : note.settled ? "T3 Code restarted and stopped background work" : "T3 Code restarted and resumed this turn", diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 6a52fac447926..23a3e0a6d3a5a 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -512,8 +512,9 @@ export function routeProviderEvent( ]; case "background_work.updated": return [state.ownedProviderTurns.has(event.providerTurnId), state]; + case "background_work.lost": case "command_output.delta": - // The session manager hands live output to the command output hub; runs never see it. + // The session manager routes these elsewhere; runs never see them. return [false, state]; case "turn.terminal": return event.providerTurnId === state.rootProviderTurnId diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 484585cd07771..bf00d2bfc8707 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -100,8 +100,6 @@ export const ProviderAdapterV2Event = Schema.Union([ /** Work remaining at this point in the event stream, including native continuations. */ pendingBackgroundWork: Schema.optional(Schema.Boolean), retainedNativeTurnIds: Schema.optional(Schema.Array(Schema.String)), - /** Roster tasks an unexpected provider process exit took with it. */ - lostBackgroundTasks: Schema.optional(Schema.Array(OrchestrationV2PendingBackgroundTask)), }), Schema.Struct({ type: Schema.Literal("provider_turn.updated"), @@ -137,6 +135,15 @@ export const ProviderAdapterV2Event = Schema.Union([ providerTurnId: ProviderTurnId, pending: Schema.Boolean, }), + // The process exited before this work reported back. It can follow the run's last event, so it + // is ingested without one. + Schema.Struct({ + type: Schema.Literal("background_work.lost"), + driver: ProviderDriverKind, + threadId: ThreadId, + providerThreadId: ProviderThreadId, + tasks: Schema.Array(OrchestrationV2PendingBackgroundTask), + }), /** Unpersisted deltas go only to clients showing the row; final output arrives in turn_item.updated. */ Schema.Struct({ type: Schema.Literal("command_output.delta"), From 5138245ed28cc15ce1574f7c08be3b7c26f5f6b7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 3 Nov 2026 14:05:24 +0000 Subject: [PATCH 4/6] fix(server): wake once for a Claude exit that races its run settling The wake for work lost to a Claude process exit was queued with the loss itself, so an exit that landed before the run's terminal write committed was consumed against a still-running run and never retried. The event sink now queues it inside whichever commit, loss or settle, lands second. Claude can also empty its roster before the stop notification arrives; the adapter now keeps the task and its await mark across that empty level so the exit still reports and wakes for awaited work. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.ts | 42 ++++-- ...laudeAutomaticDelivery.integration.test.ts | 141 ++++++++++++------ apps/server/src/orchestration-v2/EventSink.ts | 101 +++++++++---- .../orchestration-v2/ProviderEventIngestor.ts | 41 ++--- .../ProviderRuntimeRecoveryService.ts | 2 +- .../orchestration-v2/RestartBackgroundNote.ts | 12 ++ .../testkit/ProviderReplayHarness.ts | 11 +- 7 files changed, 232 insertions(+), 118 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 9cbcea9e91825..b90e900553ec1 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -5477,16 +5477,28 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ); } const listed = new Set(tasks.map((task) => task.taskId)); - yield* Ref.update(awaitedBackgroundTasksByNativeThread, (current) => { + const unlisted = yield* Ref.modify(awaitedBackgroundTasksByNativeThread, (current) => { const awaited = current.get(nativeThreadId); - if (awaited === undefined) return current; + const none: ReadonlyArray = []; + if (awaited === undefined) return [none, current] as const; const kept = new Set([...awaited].filter((taskId) => listed.has(taskId))); - if (kept.size === awaited.size) return current; + if (kept.size === awaited.size) return [none, current] as const; const updated = new Map(current); if (kept.size === 0) updated.delete(nativeThreadId); else updated.set(nativeThreadId, kept); - return updated; + return [[...awaited].filter((taskId) => !listed.has(taskId)), updated] as const; }); + // Keep the agent's await mark for a notification that follows the empty level. + if (unlisted.length > 0) { + yield* Ref.update(lastKnownOpaqueTasks, (current) => { + const updated = new Map(current); + for (const taskId of unlisted) { + const task = current.get(taskId); + if (task !== undefined) updated.set(taskId, { ...task, awaited: true }); + } + return updated; + }); + } }); const upsertPendingBackgroundTask = @@ -8168,16 +8180,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ? message.summary : null; if (isPendingTaskNotification) { - const task = claudePendingBackgroundTasksFromRoster( - rosterForNativeThread( - yield* Ref.get(pendingBackgroundTasksByNativeThread), - wakeInput.nativeThreadId, - ), - taskIdSetForNativeThread( - yield* Ref.get(awaitedBackgroundTasksByNativeThread), - wakeInput.nativeThreadId, - ), - ).find((candidate) => candidate.taskId === message.task_id); + const task = + claudePendingBackgroundTasksFromRoster( + rosterForNativeThread( + yield* Ref.get(pendingBackgroundTasksByNativeThread), + wakeInput.nativeThreadId, + ), + taskIdSetForNativeThread( + yield* Ref.get(awaitedBackgroundTasksByNativeThread), + wakeInput.nativeThreadId, + ), + ).find((candidate) => candidate.taskId === message.task_id) ?? + (yield* Ref.get(lastKnownOpaqueTasks)).get(message.task_id); yield* recordWakeReport( wakeInput.nativeThreadId, message.task_id, diff --git a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts index 37f572ddccf67..e2e037d189ea9 100644 --- a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts +++ b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts @@ -15,6 +15,7 @@ import { type OrchestrationV2DomainEvent, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -494,11 +495,39 @@ it.effect.each(deliveries)( ), ); -// SIGKILL ends the stream without a frame. SIGTERM makes the CLI stop its tasks first. -const exitWhileIdle = (awaited: boolean, signal: "SIGKILL" | "SIGTERM") => +// SIGKILL ends the stream without a frame. SIGTERM makes the CLI stop its tasks first; the +// empty roster level can come before or after the stop notification. +const exitWhileIdle = (options: { + readonly awaited: boolean; + readonly signal: "SIGKILL" | "SIGTERM" | "SIGTERM-roster-first"; + /** Exit while the run's settling write has not committed yet. */ + readonly beforeRunSettles?: boolean; +}) => Effect.scoped( Effect.gen(function* () { + const { awaited, signal } = options; const cwd = yield* checkpointWorkspace("claude-idle-exit-awaited-task"); + const settleHeld = yield* Deferred.make(); + const releaseSettle = yield* Deferred.make(); + const holdSettle = (events: ReadonlyArray) => + options.beforeRunSettles === true && + events.some( + (event) => + event.type === "run.updated" && + (event.payload.status === "waiting" || event.payload.status === "completed"), + ) + ? Deferred.succeed(settleHeld, undefined).pipe( + Effect.andThen(Deferred.await(releaseSettle)), + ) + : Effect.void; + const wrapEventSink = (sink: EventSink.EventSinkV2Shape): EventSink.EventSinkV2Shape => ({ + ...sink, + write: (input) => holdSettle(input.events).pipe(Effect.andThen(sink.write(input))), + writeWithEffects: (input) => + holdSettle(input.events).pipe(Effect.andThen(sink.writeWithEffects(input))), + writeIfRunCurrent: (input) => + holdSettle(input.events).pipe(Effect.andThen(sink.writeIfRunCurrent(input))), + }); const processes: Array> = []; const offers: SDKUserMessage[] = []; const taskId = "b8sleep180"; @@ -627,10 +656,15 @@ const exitWhileIdle = (awaited: boolean, signal: "SIGKILL" | "SIGTERM") => (event.payload.status === "waiting" || event.payload.status === "completed"), ); yield* Queue.offer(firstProcess, result("waiting-on-sleep", false)); - yield* Fiber.join(settled); - yield* worker.drain(); + if (options.beforeRunSettles === true) { + yield* Deferred.await(settleHeld); + } else { + yield* Fiber.join(settled); + yield* worker.drain(); + } const beforeExit = yield* orchestrator.getThreadProjection(threadId); const firstRun = beforeExit.runs[0]!; + if (options.beforeRunSettles === true) assert.equal(firstRun.status, "running"); assert.deepEqual( beforeExit.providerThreads[0]?.pendingBackgroundTasks?.map((task) => [ task.taskId, @@ -643,45 +677,54 @@ const exitWhileIdle = (awaited: boolean, signal: "SIGKILL" | "SIGTERM") => const woken = yield* watch( (event) => event.type === "run.updated" && event.payload.id !== firstRun.id, ); - if (signal === "SIGTERM") { + if (signal !== "SIGKILL") { const stopped = yield* watch( (event) => event.type === "provider-thread.updated" && event.payload.pendingBackgroundTasks?.length === 0, ); - yield* Queue.offerAll(firstProcess, [ - frame({ - type: "system", - subtype: "task_notification", - task_id: taskId, - status: "stopped", - output_file: "", - summary: "sleep 180", - uuid: "stopped", - session_id: sessionId, - }), - frame({ - type: "system", - subtype: "task_updated", - task_id: taskId, - patch: { status: "killed", end_time: 1 }, - uuid: "killed", - session_id: sessionId, - }), - frame({ - type: "system", - subtype: "background_tasks_changed", - tasks: [], - uuid: "roster-empty", - session_id: sessionId, - }), - ]); + const notification = frame({ + type: "system", + subtype: "task_notification", + task_id: taskId, + status: "stopped", + output_file: "", + summary: "sleep 180", + uuid: "stopped", + session_id: sessionId, + }); + const emptyRoster = frame({ + type: "system", + subtype: "background_tasks_changed", + tasks: [], + uuid: "roster-empty", + session_id: sessionId, + }); + const killed = frame({ + type: "system", + subtype: "task_updated", + task_id: taskId, + patch: { status: "killed", end_time: 1 }, + uuid: "killed", + session_id: sessionId, + }); + yield* Queue.offerAll( + firstProcess, + signal === "SIGTERM" + ? [notification, killed, emptyRoster] + : [emptyRoster, notification, killed], + ); yield* Fiber.join(stopped); } // The CLI exits while the thread is idle; the T3 server keeps running. yield* Queue.shutdown(firstProcess); yield* Fiber.join(recorded); yield* worker.drain(); + if (options.beforeRunSettles === true) { + yield* Deferred.succeed(releaseSettle, undefined); + yield* Fiber.join(settled); + yield* worker.drain(); + } const afterExit = yield* orchestrator.getThreadProjection(threadId); assert.deepEqual( @@ -700,14 +743,20 @@ const exitWhileIdle = (awaited: boolean, signal: "SIGKILL" | "SIGTERM") => if (!awaited) return; yield* Fiber.join(woken); yield* worker.drain(); - assert.isTrue( - offers.slice(1).some((offer) => JSON.stringify(offer.message).includes(taskId)), - "the agent must be woken with a note naming the lost task", + const afterWake = yield* orchestrator.getThreadProjection(threadId); + assert.lengthOf( + afterWake.runs.filter((run) => run.id !== firstRun.id), + 1, + "the agent must be woken exactly once", + ); + assert.lengthOf(offers.slice(1), 1); + assert.include( + JSON.stringify(offers[1]?.message), + taskId, + "the wake must carry a note naming the lost task", ); assert.equal( - (yield* orchestrator.getThreadProjection(threadId)).messages.filter( - (message) => message.createdBy === "user", - ).length, + afterWake.messages.filter((message) => message.createdBy === "user").length, 1, ); }).pipe( @@ -715,7 +764,7 @@ const exitWhileIdle = (awaited: boolean, signal: "SIGKILL" | "SIGTERM") => ProviderReplayHarness.layerWithRegistry( { name: "claude-idle-exit-awaited-task" }, registry, - { runEffectWorker: false, runContinuationWorker: true }, + { runEffectWorker: false, runContinuationWorker: true, wrapEventSink }, ), ), ); @@ -732,13 +781,21 @@ const exitWhileIdle = (awaited: boolean, signal: "SIGKILL" | "SIGTERM") => ); it.effect("wakes the agent when Claude's process exits while it awaits background work", () => - exitWhileIdle(true, "SIGKILL"), + exitWhileIdle({ awaited: true, signal: "SIGKILL" }), ); it.effect("wakes the agent when Claude stops awaited background work before exiting", () => - exitWhileIdle(true, "SIGTERM"), + exitWhileIdle({ awaited: true, signal: "SIGTERM" }), +); + +it.effect("wakes the agent when Claude empties its roster before stopping awaited work", () => + exitWhileIdle({ awaited: true, signal: "SIGTERM-roster-first" }), +); + +it.effect("wakes the agent once when Claude exits before its last run settles", () => + exitWhileIdle({ awaited: true, signal: "SIGKILL", beforeRunSettles: true }), ); it.effect("records but does not wake for an unawaited shell lost when Claude's process exits", () => - exitWhileIdle(false, "SIGKILL"), + exitWhileIdle({ awaited: false, signal: "SIGKILL" }), ); diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.ts index b210d3c9840ae..24778e4912a65 100644 --- a/apps/server/src/orchestration-v2/EventSink.ts +++ b/apps/server/src/orchestration-v2/EventSink.ts @@ -26,6 +26,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import { replayAndBufferProjectedLiveEvents } from "./LiveStreamBudget.ts"; import type { UnsequencedProjectEvent } from "../persistence/OrchestrationEventStore.ts"; import { projectDomainEventForWire } from "./WireProjection.ts"; +import { owesProviderExitWake } from "./RestartBackgroundNote.ts"; import { makeRunOutcomeRecorder, type RunOutcome } from "./RunMetrics.ts"; import * as CommandReceiptStore from "./CommandReceiptStore.ts"; @@ -66,6 +67,12 @@ export class EventSinkStreamError extends Schema.TaggedError; + /** Wakes queued in the same transaction, to notify after it commits. */ + readonly wakes: number; +} + export interface EventSinkV2Shape { readonly write: (input: { /** Return no events if another thread owns this native session at commit time. */ @@ -245,14 +252,13 @@ const layerBase: Layer.Layer< // Recorded before publication, so an interrupted publish cannot lose a committed outcome. const publishStoredEvents = ( events: ReadonlyArray, - outcomes: ReadonlyArray, + applied: AppliedEvents, ) => - runOutcomes - .record(outcomes) - .pipe( - Effect.andThen(eventStore.publishCommitted(events)), - Effect.andThen(publishLiveEvents(events)), - ); + (applied.wakes > 0 ? effectOutbox.notifyAvailable(applied.wakes) : Effect.void).pipe( + Effect.andThen(runOutcomes.record(applied.outcomes)), + Effect.andThen(eventStore.publishCommitted(events)), + Effect.andThen(publishLiveEvents(events)), + ); // Serialize commit and publish; reordered publication makes clients drop earlier sequences. const publishLane = yield* Semaphore.make(1); @@ -352,6 +358,42 @@ const layerBase: Layer.Layer< ); }; + // A process exit can be recorded before its run settles or after; whichever commit lands second + // sees both, so the wake is queued in the same transaction regardless of order. + const providerExitWakes = Effect.fnUntraced(function* ( + storedEvents: ReadonlyArray, + ) { + const candidates = new Map(); + for (const { event } of storedEvents) { + if ( + (event.type === "run.background-work-cancelled" && + event.payload.restartCancelledBackgroundWork.some( + (work) => work.cause === "provider_exit", + )) || + (event.type === "run.updated" && + (event.payload.status === "completed" || event.payload.status === "waiting")) + ) + candidates.set( + event.type === "run.updated" ? event.payload.id : event.payload.runId, + event.threadId, + ); + } + const wakes: Array = []; + for (const [runId, threadId] of candidates) { + const run = (yield* projectionStore.getThreadRecords(threadId, ["runs"], { + runIds: [runId], + })).runs[0]; + if (run === undefined || !owesProviderExitWake(run)) continue; + wakes.push({ + id: `effect:restart-continuation:${runId}`, + commandId: CommandId.make(`command:provider-exit:${runId}`), + threadId, + request: { type: "provider-runtime.continue", sourceRunId: runId }, + }); + } + return wakes; + }); + const applyStoredEvents = /* This helper runs for individual orchestration events; the enclosing operation owns the span. */ Effect.fnUntraced(function* (storedEvents: ReadonlyArray) { @@ -381,8 +423,13 @@ const layerBase: Layer.Layer< updated_at = excluded.updated_at `; } + const wakes = yield* providerExitWakes(storedEvents); + yield* effectOutbox.enqueue(wakes); // Read lineage here, on the connection this transaction holds; see makeRunOutcomeRecorder. - return yield* runOutcomes.prepare(storedEvents); + return { + outcomes: yield* runOutcomes.prepare(storedEvents), + wakes: wakes.length, + } satisfies AppliedEvents; }); // The enclosing write or commit span already traces this per-event projection merge. @@ -430,7 +477,7 @@ const layerBase: Layer.Layer< AND json_extract(payload_json, '$.nativeThreadRef.nativeId') = ${imported.nativeThreadRef.nativeId} LIMIT 1 `; - if (owners.length > 0) return { committed: [], outcomes: [] }; + if (owners.length > 0) return { committed: [], applied: { outcomes: [], wakes: 0 } }; } // Checkpoint capture can finish after a cohort writer reads its parent run. // Merge in this transaction so the event log and projection keep that completion. @@ -446,16 +493,16 @@ const layerBase: Layer.Layer< ...(input.commandId === undefined ? {} : { commandId: input.commandId }), events: normalized, }); - const outcomes = yield* applyStoredEvents(committed); + const applied = yield* applyStoredEvents(committed); yield* effectOutbox.enqueue(input.effects); - return { committed, outcomes }; + return { committed, applied }; }).pipe(Effect.withTracerEnabled(false)), - ({ committed, outcomes }) => + ({ committed, applied }) => Effect.gen(function* () { if (input.effects.length > 0) { yield* effectOutbox.notifyAvailable(input.effects.length); } - yield* publishStoredEvents(committed, outcomes); + yield* publishStoredEvents(committed, applied); }), ); return committed; @@ -505,9 +552,9 @@ const layerBase: Layer.Layer< ...(input.commandId === undefined ? {} : { commandId: input.commandId }), events: normalized, }); - const outcomes = yield* applyStoredEvents(storedEvents); + const applied = yield* applyStoredEvents(storedEvents); yield* effectOutbox.enqueue(input.effects ?? []); - return { committed: true as const, storedEvents, outcomes }; + return { committed: true as const, storedEvents, applied }; }), (result) => Effect.gen(function* () { @@ -515,7 +562,7 @@ const layerBase: Layer.Layer< if (input.effects !== undefined && input.effects.length > 0) { yield* effectOutbox.notifyAvailable(input.effects.length); } - yield* publishStoredEvents(result.storedEvents, result.outcomes); + yield* publishStoredEvents(result.storedEvents, result.applied); }), ); }, @@ -570,13 +617,11 @@ const layerBase: Layer.Layer< ...(input.commandId === undefined ? {} : { commandId: input.commandId }), events: normalized, }); - const outcomes = yield* applyStoredEvents(storedEvents); - return { committed: true as const, storedEvents, outcomes }; + const applied = yield* applyStoredEvents(storedEvents); + return { committed: true as const, storedEvents, applied }; }), (result) => - result.committed - ? publishStoredEvents(result.storedEvents, result.outcomes) - : Effect.void, + result.committed ? publishStoredEvents(result.storedEvents, result.applied) : Effect.void, ); }); @@ -606,13 +651,11 @@ const layerBase: Layer.Layer< const normalized = yield* normalizeEvents(input.events); const storedEvents = yield* eventStore.append({ events: normalized }); - const outcomes = yield* applyStoredEvents(storedEvents); - return { committed: true as const, storedEvents, outcomes }; + const applied = yield* applyStoredEvents(storedEvents); + return { committed: true as const, storedEvents, applied }; }), (result) => - result.committed - ? publishStoredEvents(result.storedEvents, result.outcomes) - : Effect.void, + result.committed ? publishStoredEvents(result.storedEvents, result.applied) : Effect.void, ); }); @@ -672,7 +715,7 @@ const layerBase: Layer.Layer< new Error(`Command ${input.commandId} produced no orchestration events.`), ); } - const outcomes = yield* applyStoredEvents(storedEvents); + const applied = yield* applyStoredEvents(storedEvents); yield* effectOutbox.enqueue(input.effects); const receipt: CommandReceiptStore.CommandReceiptV2 = { commandId: input.commandId, @@ -691,7 +734,7 @@ const layerBase: Layer.Layer< threadId: input.threadId, ...input.cancelUnsettledEffects, }); - return { receipt, storedEvents, outcomes, committed: true as const, cancelledEffectIds }; + return { receipt, storedEvents, applied, committed: true as const, cancelledEffectIds }; }), (result) => Effect.gen(function* () { @@ -699,7 +742,7 @@ const layerBase: Layer.Layer< if (result.committed && input.effects.length > 0) { yield* effectOutbox.notifyAvailable(input.effects.length); } - if (result.committed) yield* publishStoredEvents(result.storedEvents, result.outcomes); + if (result.committed) yield* publishStoredEvents(result.storedEvents, result.applied); }), ); return { diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts index 0a725e5655614..91820d58da94b 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts @@ -38,14 +38,14 @@ import * as ProjectionStore from "./ProjectionStore.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import { makeProviderFailureTurnItem } from "@t3tools/provider-core/server/failure"; -import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; -import { stripUnservedToolOutputImageBytes } from "./toolOutputImageBytes.ts"; -import { boundFileChangeForStorage } from "./WireProjection.ts"; import { cancelledRosterTaskWork, latestStartedRun, mergeRestartCancelledBackgroundWork, } from "./RestartBackgroundNote.ts"; +import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; +import { stripUnservedToolOutputImageBytes } from "./toolOutputImageBytes.ts"; +import { boundFileChangeForStorage } from "./WireProjection.ts"; export class ProviderEventNormalizeError extends Schema.TaggedError()( "ProviderEventNormalizeError", @@ -718,24 +718,6 @@ export const layer: Layer.Layer< if (events.length === 0) { return []; } - // The continuation wakes the agent only for awaited work; the rest rides along on the next user message. - const effects = events.flatMap((event) => - event.type === "run.background-work-cancelled" - ? [ - { - id: `effect:restart-continuation:${event.payload.runId}`, - commandId: - input.commandId ?? - CommandId.make(`command:provider-exit:${event.payload.runId}`), - threadId: event.threadId, - request: { - type: "provider-runtime.continue" as const, - sourceRunId: event.payload.runId, - }, - }, - ] - : [], - ); const mapWriteError = (cause: unknown) => new ProviderEventPublishError({ providerSessionId: input.providerSessionId, @@ -754,16 +736,13 @@ export const layer: Layer.Layer< return ownerResult.storedEvents; } if (input.writeIfRunCurrent === undefined) { - const write = { - guardPendingUserInputCancellations: true, - ...(input.commandId === undefined ? {} : { commandId: input.commandId }), - events, - }; - return yield* ( - effects.length === 0 - ? eventSink.write(write) - : eventSink.writeWithEffects({ ...write, effects }) - ).pipe(retryLockTimeout, Effect.mapError(mapWriteError)); + return yield* eventSink + .write({ + guardPendingUserInputCancellations: true, + ...(input.commandId === undefined ? {} : { commandId: input.commandId }), + events, + }) + .pipe(retryLockTimeout, Effect.mapError(mapWriteError)); } const result = yield* eventSink .writeIfRunCurrent({ diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts index 3990e5b1d0f6f..aab2a488ee7eb 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts @@ -31,8 +31,8 @@ import { import { awaitingProviderThreadId, cancelledRosterTaskWork, - latestStartedRun, cancelledTurnItemWork, + latestStartedRun, mergeRestartCancelledBackgroundWork, } from "./RestartBackgroundNote.ts"; diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts index 0bc1882333754..42730c2ed4d08 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts @@ -165,6 +165,18 @@ export function isAwaitedWork(work: Pick): boolean { return work.awaited === true || (work.kind !== "shell" && work.kind !== "monitor"); } +/** A settled run whose process exit took work the agent awaited, so the agent is owed a wake. */ +export function owesProviderExitWake( + run: Pick, +): boolean { + return ( + (run.status === "completed" || run.status === "waiting") && + (run.restartCancelledBackgroundWork ?? []).some( + (work) => work.cause === "provider_exit" && isAwaitedWork(work), + ) + ); +} + export function runOutcome( run: Pick, ): OrchestrationV2Run["status"] { diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts index 746ff0f844fe2..e74b4426a51af 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts @@ -281,6 +281,8 @@ export function layerWithRegistry( readonly recoverOnStartup?: boolean; readonly continueThreadsAfterServerUpdate?: boolean; readonly managedPolicy?: ManagedPolicyDocument; + /** Intercepts every write, e.g. to hold one until a test releases it. */ + readonly wrapEventSink?: (sink: EventSink.EventSinkV2Shape) => EventSink.EventSinkV2Shape; } = {}, ): Layer.Layer< | Orchestrator.OrchestratorV2 @@ -328,9 +330,16 @@ export function layerWithRegistry( EffectOutbox.layer, TurnItemPositionStore.layer, ).pipe(Layer.provide(layerDatabase)); - const layerEventSinkProvided = EventSink.layerFromStores.pipe( + const layerEventSinkBase = EventSink.layerFromStores.pipe( Layer.provide(Layer.mergeAll(layerStores, layerDatabase)), ); + const wrapEventSink = options.wrapEventSink; + const layerEventSinkProvided = + wrapEventSink === undefined + ? layerEventSinkBase + : Layer.effect(EventSink.EventSinkV2, Effect.map(EventSink.EventSinkV2, wrapEventSink)).pipe( + Layer.provide(layerEventSinkBase), + ); const layerRuntime = RuntimePolicy.layerEnforcingCeiling.pipe( Layer.provide(Layer.merge(layerRuntimeBase, layerServerSettings)), ); From 11cb7d0c65448b5dd702a1d018946c4553591ec5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 3 Nov 2026 14:49:52 +0000 Subject: [PATCH 5/6] refactor(server): trace the provider-exit lost-work ingestion as a named span Co-Authored-By: Claude Opus 5.5 --- .../orchestration-v2/ProviderEventIngestor.ts | 64 ++++++++++--------- 1 file changed, 33 insertions(+), 31 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts index 91820d58da94b..4cb096de2a866 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts @@ -462,38 +462,40 @@ export const layer: Layer.Layer< }); // The run records what an unexpected process exit took, as a server restart would. - const lostBackgroundWorkEvents = Effect.fnUntraced(function* ( - input: ProviderEventIngestInput, - event: Extract< - ProviderAdapter.ProviderAdapterV2Event, - { readonly type: "background_work.lost" } - >, - ) { - const threadId = event.threadId; - const run = latestStartedRun( - (yield* projections.getThreadRecords(threadId, ["runs"])).runs, - event.providerThreadId, - ); - if (run === undefined) return []; - const work = event.tasks.map((task) => ({ - ...cancelledRosterTaskWork(task), - cause: "provider_exit" as const, - })); - return [ - yield* makeDomainEvent(input, { - type: "run.background-work-cancelled", - threadId, - runId: run.id, - payload: { + const lostBackgroundWorkEvents = Effect.fn("ProviderEventIngestor.lostBackgroundWorkEvents")( + function* ( + input: ProviderEventIngestInput, + event: Extract< + ProviderAdapter.ProviderAdapterV2Event, + { readonly type: "background_work.lost" } + >, + ) { + const threadId = event.threadId; + const run = latestStartedRun( + (yield* projections.getThreadRecords(threadId, ["runs"])).runs, + event.providerThreadId, + ); + if (run === undefined) return []; + const work = event.tasks.map((task) => ({ + ...cancelledRosterTaskWork(task), + cause: "provider_exit" as const, + })); + return [ + yield* makeDomainEvent(input, { + type: "run.background-work-cancelled", + threadId, runId: run.id, - restartCancelledBackgroundWork: mergeRestartCancelledBackgroundWork( - run.restartCancelledBackgroundWork ?? [], - work, - ), - }, - }), - ]; - }); + payload: { + runId: run.id, + restartCancelledBackgroundWork: mergeRestartCancelledBackgroundWork( + run.restartCancelledBackgroundWork ?? [], + work, + ), + }, + }), + ]; + }, + ); const normalize: ProviderEventIngestorV2Shape["normalize"] = /* This helper runs for individual orchestration events; the enclosing operation owns the span. */ From c0a1378dbca44812b1c290ac69ac7acd8085234f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 11:41:10 +0000 Subject: [PATCH 6/6] fix(server): a pending Claude wake covers only the tasks its buffer reports An owed task whose notification never arrived is still lost when the process exits, even while another task's wake is requested. Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/Adapters/ClaudeAdapterV2.ts | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index c86176d8a427a..4631cd2402467 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -7144,7 +7144,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const preservedOpaqueTombstones = [...priorOpaqueTombstones].filter((taskId) => bufferedTaskNotificationIds.has(taskId), ); - // Idle outcomes reach Claude only through a wake, which this process can no longer run. + // Idle outcomes reach Claude only through a wake; a requested one still delivers its buffer. const wakeRequested = (yield* Ref.get(requestedContinuations)).has(nativeThreadId); const lostBackgroundTasks = options?.exitedUnexpectedly === true @@ -7155,11 +7155,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* Ref.get(awaitedBackgroundTasksByNativeThread), nativeThreadId, ), - ).filter( - (task) => !(wakeRequested && bufferedTaskNotificationIds.has(task.taskId)), ), - ...(wakeRequested ? [] : yield* owedWakeTasksForNativeThread(nativeThreadId)), - ] + ...(yield* owedWakeTasksForNativeThread(nativeThreadId)), + ].filter((task) => !(wakeRequested && bufferedTaskNotificationIds.has(task.taskId))) : []; scheduledWakeupsByNativeThread.delete(nativeThreadId); possibleEarlyWakeNativeThreads.delete(nativeThreadId);