Skip to content
TypeScript

fix(server): settle Claude background agents when their process exits (#19464)

James Ca3d73c930ed4
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index 447272221f6..c0f60c3411c 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -9292,59 +9292,84 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
- it.effect("ends a subagent's open call when the CLI exits while the root turn is idle", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const TOOL_USE_ID = "toolu-idle-exit";
- const BASH = "toolu-idle-exit-bash";
- const harness = yield* makeWakeHarness;
- const now = yield* DateTime.now;
- const bashStatuses = () =>
- harness.events.flatMap((event) =>
- event.type === "turn_item.updated" && event.turnItem.nativeItemRef?.nativeId === BASH
- ? [`${event.turnItem.type}:${event.turnItem.status}`]
- : [],
+ it.effect.each(["exit", "Stop"] as const)(
+ "settles a plain background subagent and its open call on %s after the root turn completes",
+ (reason) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const TOOL_USE_ID = "toolu-idle-exit";
+ const BASH = "toolu-idle-exit-bash";
+ const harness = yield* makeWakeHarnessWithOptions({ close: Queue.shutdown });
+ const now = yield* DateTime.now;
+ const bashStatuses = () =>
+ harness.events.flatMap((event) =>
+ event.type === "turn_item.updated" && event.turnItem.nativeItemRef?.nativeId === BASH
+ ? [`${event.turnItem.type}:${event.turnItem.status}`]
+ : [],
+ );
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-claude-idle-exit"),
+ text: "Audit in the background.",
+ attachments: [],
+ }),
);
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: RunAttemptId.make("attempt-claude-idle-exit"),
- text: "Audit in the background.",
- attachments: [],
- }),
- );
- for (const frame of [
- makeSubagentTaskStartedFrame({
- taskId: "task-idle-exit",
- toolUseId: TOOL_USE_ID,
- uuid: "00000000-0000-4000-8000-000000000981",
- }),
- ...makeSubagentAssistantFrames({
+ yield* harness.offerAndWait(
+ makeSubagentTaskStartedFrame({
+ taskId: "task-idle-exit",
+ toolUseId: TOOL_USE_ID,
+ uuid: "00000000-0000-4000-8000-000000000981",
+ }),
+ );
+ const started = yield* Queue.take(harness.subagentReceipts);
+ assert.equal(started.subagent.status, "running");
+ for (const frame of makeSubagentAssistantFrames({
parentToolUseId: TOOL_USE_ID,
uuid: "00000000-0000-4000-8000-000000000982",
bashToolUseId: BASH,
- }),
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-000000000983",
- result: "Auditing in the background.",
- }),
- ]) {
- yield* Queue.offer(harness.sdkMessages, frame);
- }
- yield* awaitUntil(() => harness.terminalEvents().length === 1, "launch turn terminal");
- assert.deepEqual(bashStatuses(), ["command_execution:running"]);
+ })) {
+ yield* harness.offerAndWait(frame);
+ }
+ yield* harness.offerAndWait(
+ makeResultFrame({
+ uuid: "00000000-0000-4000-8000-000000000983",
+ result: "Auditing in the background.",
+ }),
+ );
+ const terminal = yield* Queue.take(harness.terminalReceipts);
+ assert.equal(terminal.status, "completed");
+ assert.isTrue(yield* harness.hasPendingBackgroundWork);
+ assert.deepEqual(bashStatuses(), ["command_execution:running"]);
- yield* Queue.shutdown(harness.sdkMessages);
- yield* awaitUntil(() => bashStatuses().length === 2, "call ended");
- assert.deepEqual(bashStatuses(), ["command_execution:running", "command_execution:failed"]);
- }).pipe(
- Effect.provide(
- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
+ if (reason === "Stop") {
+ yield* harness.runtime.interruptTurn({
+ providerThread: harness.providerThread,
+ providerTurnId: terminal.providerTurnId,
+ requestRuntimeRestart: true,
+ });
+ } else {
+ yield* Queue.shutdown(harness.sdkMessages);
+ }
+ let ended = yield* Queue.take(harness.subagentReceipts);
+ while (ended.subagent.status === "running") {
+ ended = yield* Queue.take(harness.subagentReceipts);
+ }
+ assert.equal(ended.subagent.nativeTaskRef?.nativeId, "task-idle-exit");
+ assert.equal(ended.subagent.status, reason === "Stop" ? "cancelled" : "failed");
+ assert.isFalse(yield* harness.hasPendingBackgroundWork);
+ assert.deepEqual(bashStatuses(), [
+ "command_execution:running",
+ reason === "Stop" ? "command_execution:interrupted" : "command_execution:failed",
+ ]);
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
+ ),
),
),
- ),
);
it.effect("ends a subagent's open call when Stop's close of the CLI times out", () =>
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index e969520bd05..a5e19ed1ca5 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -6396,11 +6396,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
cause?: Cause.Cause<ClaudeAgentSdkQueryRunnerError>,
) {
const current = yield* Ref.get(activeTurn);
- const context =
- current?.nativeThreadId === closedQuery.nativeThreadId ? current : closedQuery.lastTurn;
+ // A replacement query can reuse the native thread id; only this query's turn is ours.
+ const context = closedQuery.lastTurn;
if (context === null) return;
const interrupted =
closedQuery.stopping || (yield* Ref.get(interruptedTurns)).has(context.providerTurnId);
+ // Finalization can yield to a replacement process; capture ownership and outcomes first.
const subagents = yield* Ref.get(sessionSubagentsByTaskId);
const buffered = (yield* Ref.get(wakeBuffers)).get(closedQuery.nativeThreadId)?.messages;
if (current === context) {
@@ -6420,9 +6421,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
} else {
yield* resetBackgroundTaskStateForNativeThreadProcess(closedQuery.nativeThreadId);
}
+ // Preserve buffered outcomes before Stop clears the wake buffer.
for (const [taskId, subagent] of subagents) {
if (
- subagent.task.workflow === undefined ||
subagent.task.status !== "running" ||
closedQuery.subagentsFromEarlierProcesses.has(subagent)
)
diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRecovery.integration.test.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRecovery.integration.test.ts
index 4fb521beac0..afd195d4e76 100644
--- a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRecovery.integration.test.ts
+++ b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRecovery.integration.test.ts
@@ -5,6 +5,7 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
+import * as SqlClient from "effect/sql/SqlClient";
import * as CodexReplay from "effect-codex-app-server/replay";
import {
type OrchestrationV2ThreadProjection,
@@ -25,6 +26,7 @@ import {
} from "../Adapters/CursorAdapterV2.testkit.ts";
import * as CursorAdapterV2Testkit from "../Adapters/CursorAdapterV2.testkit.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
+import * as EffectWorker from "../EffectWorker.ts";
import * as SqlitePersistence from "../../persistence/Sqlite.ts";
import { provideDeterministicTestRuntime } from "./DeterministicRuntime.ts";
import {
@@ -46,8 +48,14 @@ import {
assertUserMessagesInclude,
projectionFor,
} from "./fixtures/shared.ts";
-import type { OrchestratorV2ScenarioResult } from "./OrchestratorScenario.ts";
-import { runOrchestratorV2ProviderReplayScenario } from "./ProviderReplayHarness.ts";
+import {
+ runOrchestratorV2Scenario,
+ type OrchestratorV2ScenarioResult,
+} from "./OrchestratorScenario.ts";
+import {
+ layerProviderReplay,
+ runOrchestratorV2ProviderReplayScenario,
+} from "./ProviderReplayHarness.ts";
import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
import { materializeReplayTranscriptRuntimeInstructions } from "./ReplayRuntimeInstructions.ts";
import {
@@ -111,11 +119,15 @@ const readClaudeCancelledSubagentResumeTranscript = Effect.fn(
const firstOutcome = indices.find(
(index) => frameField(index, "subtype") === "task_notification",
);
- if (firstSubagentFrame === undefined || firstOutcome === undefined) {
+ const firstExit = recorded.entries.findIndex((entry) => entry.type === "runtime_exit");
+ if (firstSubagentFrame === undefined || firstOutcome === undefined || firstExit < 0) {
throw new Error("Expected the recorded subagent's first run.");
}
const entries = recorded.entries
- .filter((_, index) => index < firstSubagentFrame || index > firstOutcome)
+ // A CLI exit settles the task; hold at query.open:2 until the crash snapshot instead.
+ .filter(
+ (_, index) => (index < firstSubagentFrame || index > firstOutcome) && index !== firstExit,
+ )
.map((entry) => {
if (entry.type !== "expect_outbound" || entry.label !== "prompt.offer:2") return entry;
const frame = entry.frame as {
@@ -524,18 +536,31 @@ describe("orchestrator replay recovery", () => {
const childRootStatus = (child: OrchestrationV2ThreadProjection | undefined) =>
child?.nodes.find((node) => node.kind === "root_turn" && node.runId === null)?.status;
+ const snapshotPath = path.join(tempDir, "restart-state.sqlite");
+ const beforeScenario = {
+ name: `${transcript.scenario}:cancelled-first-runtime`,
+ transcript,
+ commands: phase1Commands,
+ steps: phase1Steps,
+ projectionThreadIds: materialized.projectionThreadIds,
+ runtimePolicyOverride: { cwd: workspace },
+ };
const before = yield* Effect.scoped(
- runOrchestratorV2ProviderReplayScenario(
- {
- name: `${transcript.scenario}:cancelled-first-runtime`,
- transcript,
- commands: phase1Commands,
- steps: phase1Steps,
- projectionThreadIds: materialized.projectionThreadIds,
- runtimePolicyOverride: { cwd: workspace },
- },
- harness,
- options,
+ Effect.gen(function* () {
+ const result = yield* runOrchestratorV2Scenario(beforeScenario);
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
+ yield* worker.drain();
+ // Preserve the orphan before scoped teardown settles its provider work.
+ const sql = yield* SqlClient.SqlClient;
+ yield* sql`VACUUM INTO ${snapshotPath}`;
+ return result;
+ }).pipe(
+ Effect.provide(
+ Layer.merge(
+ layerProviderReplay(beforeScenario, harness, options),
+ options.databaseLayer,
+ ),
+ ),
),
);
const settled = projectionFor(before, transcript.scenario);
@@ -555,7 +580,13 @@ describe("orchestrator replay recovery", () => {
runtimePolicyOverride: { cwd: workspace },
},
harness,
- { ...options, recoverOnStartup: true, continueThreadsAfterServerUpdate: false },
+ {
+ databaseLayer: SqlitePersistence.layerFromPath(snapshotPath).pipe(
+ Layer.provide(NodeServices.layer),
+ ),
+ recoverOnStartup: true,
+ continueThreadsAfterServerUpdate: false,
+ },
),
);
yield* assertComplete;
diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRestartBackgroundNote.integration.test.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRestartBackgroundNote.integration.test.ts
index fdcba4c0a8d..4adc098ba6d 100644
--- a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRestartBackgroundNote.integration.test.ts
+++ b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayRestartBackgroundNote.integration.test.ts
@@ -1,10 +1,12 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
-import { ProviderDriverKind, type ProviderReplayEntry } from "@t3tools/contracts";
+import { EventId, ProviderDriverKind, type ProviderReplayEntry } from "@t3tools/contracts";
+import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
+import * as SqlClient from "effect/sql/SqlClient";
import {
ClaudeOrchestratorReplayHarness,
@@ -12,6 +14,8 @@ import {
} from "../Adapters/ClaudeAdapterV2.testkit.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as EffectWorker from "../EffectWorker.ts";
+import * as EventSink from "../EventSink.ts";
+import * as Orchestrator from "../Orchestrator.ts";
import * as SqlitePersistence from "../../persistence/Sqlite.ts";
import { provideDeterministicTestRuntime } from "./DeterministicRuntime.ts";
import { CLAUDE_BACKGROUND_SUBAGENT_AFTER_ROOT_PROMPT } from "./fixtures/claude_background_subagent_after_root/input.ts";
@@ -113,8 +117,7 @@ const readRestartTranscript = Effect.fn("readRestartTranscript")(function* (
...recorded,
entries: [
...recorded.entries.slice(0, rootResult + 1),
-
- { type: "runtime_exit", status: "success" },
+ // Keep the query alive until the crash snapshot is captured.
{
type: "expect_outbound",
label: "query.open:resume",
@@ -157,6 +160,7 @@ const runRestart = Effect.fn("runRestart")(function* (input: {
const layerDatabase = SqlitePersistence.layerFromPath(path.join(tempDir, "state.sqlite")).pipe(
Layer.provide(NodeServices.layer),
);
+ const snapshotPath = path.join(tempDir, "restart-state.sqlite");
const scenario = (name: string, steps: typeof materialized.steps) => ({
name: `${SCENARIO}:${name}`,
transcript,
@@ -166,10 +170,54 @@ const runRestart = Effect.fn("runRestart")(function* (input: {
runtimePolicyOverride: { cwd: workspace },
});
+ const beforeScenario = scenario("before-restart", phase1Steps);
const before = yield* Effect.scoped(
- runOrchestratorV2ProviderReplayScenario(scenario("before-restart", phase1Steps), harness, {
- databaseLayer: layerDatabase,
- }),
+ Effect.gen(function* () {
+ const result = yield* runOrchestratorV2Scenario(beforeScenario);
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
+ yield* worker.drain();
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const eventSink = yield* EventSink.EventSinkV2;
+ const threadId = materialized.projectionThreadIds[0];
+ if (threadId === undefined) {
+ return yield* Effect.die("restart scenario has no projection thread");
+ }
+ const projection = yield* orchestrator.getThreadProjection(threadId);
+ const session = projection.providerSessions[0];
+ if (session === undefined) {
+ return yield* Effect.die("restart scenario has no provider session");
+ }
+ // Snapshot the legacy running task before exit cleanup settles it, then
+ // seed the stopped session that older runtimes could leave after a crash.
+ const now = yield* DateTime.now;
+ yield* eventSink.write({
+ events: [
+ {
+ id: EventId.make("event:restart-background-note:stopped-provider-session"),
+ type: "provider-session.updated",
+ threadId,
+ providerInstanceId: session.providerInstanceId,
+ occurredAt: now,
+ payload: { ...session, status: "stopped", updatedAt: now, lastError: null },
+ },
+ ],
+ });
+ const sql = yield* SqlClient.SqlClient;
+ yield* sql`VACUUM INTO ${snapshotPath}`;
+ return result;
+ }).pipe(
+ Effect.provide(
+ Layer.merge(
+ ProviderReplayHarness.layerProviderReplay(beforeScenario, harness, {
+ databaseLayer: layerDatabase,
+ }),
+ layerDatabase,
+ ),
+ ),
+ ),
+ );
+ const snapshotDatabase = SqlitePersistence.layerFromPath(snapshotPath).pipe(
+ Layer.provide(NodeServices.layer),
);
const settled = projectionFor(before, SCENARIO);
assert.equal(settled.runs[0]?.status, "completed");
@@ -184,7 +232,7 @@ const runRestart = Effect.fn("runRestart")(function* (input: {
}).pipe(
Effect.provide(
ProviderReplayHarness.layerProviderReplay(restartScenario, harness, {
- databaseLayer: layerDatabase,
+ databaseLayer: snapshotDatabase,
recoverOnStartup: true,
continueThreadsAfterServerUpdate: input.continueThreadsAfterServerUpdate,
}),
@@ -201,7 +249,7 @@ const runRestart = Effect.fn("runRestart")(function* (input: {
const after = yield* Effect.scoped(
runOrchestratorV2ProviderReplayScenario(scenario("after-restart", phase2Steps), harness, {
- databaseLayer: layerDatabase,
+ databaseLayer: snapshotDatabase,
continueThreadsAfterServerUpdate: input.continueThreadsAfterServerUpdate,
}),
);