Skip to content

Commit 2d33979

Browse files
fix(server): keep session crons pinned after a failed Claude turn
A result-driven failed turn (usage limit, overload, error subtype) leaves the Claude CLI running with its session crons, and the SDK fires StopFailure, not Stop. Clearing the cron count on every non-completed finalization let the idle release drop the session and lose the job. Clear it only when the process ends or is replaced: on query exit and in the process reset. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 49a57cd commit 2d33979

2 files changed

Lines changed: 99 additions & 63 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts‎

Lines changed: 82 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -6411,32 +6411,42 @@ describe("ClaudeAdapterV2 background wake turns", () => {
64116411
),
64126412
);
64136413

6414+
// The SDK reports CronCreate, ScheduleWakeup and /loop jobs only through the Stop hook,
6415+
// which fires just before the turn's result.
6416+
const runStopHook = (
6417+
harness: Effect.Success<typeof makeWakeHarness>,
6418+
sessionCrons: ReadonlyArray<SessionCronSummary>,
6419+
) =>
6420+
Effect.promise(async () => {
6421+
const matchers = harness.getOpenedOptions()?.hooks?.Stop ?? [];
6422+
for (const hook of matchers.flatMap((matcher) => matcher.hooks)) {
6423+
await hook(
6424+
{
6425+
hook_event_name: "Stop",
6426+
session_id: WAKE_NATIVE_SESSION,
6427+
transcript_path: "/tmp/transcript.jsonl",
6428+
cwd: "/tmp",
6429+
stop_hook_active: false,
6430+
background_tasks: [],
6431+
session_crons: [...sessionCrons],
6432+
},
6433+
undefined,
6434+
{ signal: new AbortController().signal },
6435+
);
6436+
}
6437+
});
6438+
const pendingSessionCron: SessionCronSummary = {
6439+
id: "4e805017",
6440+
schedule: "20 12 22 10 *",
6441+
recurring: false,
6442+
prompt: "Append `date -u` to /tmp/cron.txt",
6443+
};
6444+
64146445
it.effect("keeps a session with a pending session cron alive until no cron remains", () =>
64156446
Effect.scoped(
64166447
Effect.gen(function* () {
64176448
const harness = yield* makeWakeHarness;
64186449
const now = yield* DateTime.now;
6419-
// The SDK reports CronCreate, ScheduleWakeup and /loop jobs only through the Stop hook,
6420-
// which fires just before the turn's result.
6421-
const stop = (sessionCrons: ReadonlyArray<SessionCronSummary>) =>
6422-
Effect.promise(async () => {
6423-
const matchers = harness.getOpenedOptions()?.hooks?.Stop ?? [];
6424-
for (const hook of matchers.flatMap((matcher) => matcher.hooks)) {
6425-
await hook(
6426-
{
6427-
hook_event_name: "Stop",
6428-
session_id: WAKE_NATIVE_SESSION,
6429-
transcript_path: "/tmp/transcript.jsonl",
6430-
cwd: "/tmp",
6431-
stop_hook_active: false,
6432-
background_tasks: [],
6433-
session_crons: [...sessionCrons],
6434-
},
6435-
undefined,
6436-
{ signal: new AbortController().signal },
6437-
);
6438-
}
6439-
});
64406450
const turn = (ordinal: number, text: string) =>
64416451
makeClaudeTestTurnInput({
64426452
threadId: harness.threadId,
@@ -6449,14 +6459,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
64496459
});
64506460

64516461
yield* harness.runtime.startTurn(turn(1, "At 12:20 append the date to a file."));
6452-
yield* stop([
6453-
{
6454-
id: "4e805017",
6455-
schedule: "20 12 22 10 *",
6456-
recurring: false,
6457-
prompt: "Append `date -u` to /tmp/cron.txt",
6458-
},
6459-
]);
6462+
yield* runStopHook(harness, [pendingSessionCron]);
64606463
yield* harness.offerAndWait(turnOneResult);
64616464
yield* harness.awaitTerminal(1);
64626465
assert.isTrue(
@@ -6465,7 +6468,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
64656468
);
64666469

64676470
yield* harness.runtime.startTurn(turn(2, "Cancel that job."));
6468-
yield* stop([]);
6471+
yield* runStopHook(harness, []);
64696472
yield* harness.offerAndWait(turnOneResult);
64706473
yield* harness.awaitTerminal(2);
64716474
assert.isFalse(yield* harness.hasPendingBackgroundWork);
@@ -6497,31 +6500,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
64976500
});
64986501

64996502
yield* harness.runtime.startTurn(turn(1, "At 12:20 append the date to a file."));
6500-
yield* Effect.promise(async () => {
6501-
const matchers = harness.getOpenedOptions()?.hooks?.Stop ?? [];
6502-
for (const hook of matchers.flatMap((matcher) => matcher.hooks)) {
6503-
await hook(
6504-
{
6505-
hook_event_name: "Stop",
6506-
session_id: WAKE_NATIVE_SESSION,
6507-
transcript_path: "/tmp/transcript.jsonl",
6508-
cwd: "/tmp",
6509-
stop_hook_active: false,
6510-
background_tasks: [],
6511-
session_crons: [
6512-
{
6513-
id: "4e805017",
6514-
schedule: "20 12 22 10 *",
6515-
recurring: false,
6516-
prompt: "Append `date -u` to /tmp/cron.txt",
6517-
},
6518-
],
6519-
},
6520-
undefined,
6521-
{ signal: new AbortController().signal },
6522-
);
6523-
}
6524-
});
6503+
yield* runStopHook(harness, [pendingSessionCron]);
65256504
yield* harness.offerAndWait(turnOneResult);
65266505
yield* harness.awaitTerminal(1);
65276506
assert.isTrue(yield* harness.hasPendingBackgroundWork);
@@ -6547,6 +6526,54 @@ describe("ClaudeAdapterV2 background wake turns", () => {
65476526
),
65486527
);
65496528

6529+
it.effect("keeps session crons pinned when the next turn fails without closing the CLI", () =>
6530+
Effect.scoped(
6531+
Effect.gen(function* () {
6532+
const harness = yield* makeWakeHarness;
6533+
const now = yield* DateTime.now;
6534+
const turn = (ordinal: number, text: string) =>
6535+
makeClaudeTestTurnInput({
6536+
threadId: harness.threadId,
6537+
providerThread: harness.providerThread,
6538+
now,
6539+
attemptId: RunAttemptId.make(`attempt-claude-session-cron-failed:${ordinal}`),
6540+
text,
6541+
attachments: [],
6542+
providerTurnOrdinal: ordinal,
6543+
});
6544+
6545+
yield* harness.runtime.startTurn(turn(1, "At 12:20 append the date to a file."));
6546+
yield* runStopHook(harness, [pendingSessionCron]);
6547+
yield* harness.offerAndWait(turnOneResult);
6548+
yield* harness.awaitTerminal(1);
6549+
assert.isTrue(yield* harness.hasPendingBackgroundWork);
6550+
6551+
// A usage limit fails the turn through StopFailure, which carries no crons, and the
6552+
// CLI keeps running with the job still scheduled.
6553+
yield* harness.runtime.startTurn(turn(2, "Keep going."));
6554+
yield* harness.offerAndWait(
6555+
makeResultFrame({
6556+
uuid: "00000000-0000-4000-8000-000000013439",
6557+
result: "Usage limit reached.",
6558+
isError: true,
6559+
apiErrorStatus: 429,
6560+
terminalReason: "api_error",
6561+
}),
6562+
);
6563+
yield* harness.awaitTerminal(2);
6564+
assert.equal(harness.terminalEvents()[1]?.status, "failed");
6565+
assert.isTrue(
6566+
yield* harness.hasPendingBackgroundWork,
6567+
"a failed turn must not forget crons the live CLI still holds",
6568+
);
6569+
}).pipe(
6570+
Effect.provide(
6571+
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
6572+
),
6573+
),
6574+
),
6575+
);
6576+
65506577
it.effect("stops background work after the turn settled", () =>
65516578
Effect.scoped(
65526579
Effect.gen(function* () {

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4688,17 +4688,24 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
46884688
updated.delete(nativeThreadId);
46894689
return updated;
46904690
});
4691-
yield* Ref.update(pendingSessionCronCountByNativeThread, (current) => {
4692-
if (!current.has(nativeThreadId)) {
4693-
return current;
4694-
}
4695-
const updated = new Map(current);
4696-
updated.delete(nativeThreadId);
4697-
return updated;
4698-
});
46994691
yield* endClaudeMonitorTasks((_taskId, task) => task.nativeThreadId === nativeThreadId);
47004692
});
47014693

4694+
// Session crons live in the CLI process: only its exit or replacement drops them. A failed
4695+
// result (usage limit, overload) leaves the process and its crons running.
4696+
const clearSessionCronCountForNativeThread = Effect.fnUntraced(function* (
4697+
nativeThreadId: string,
4698+
) {
4699+
yield* Ref.update(pendingSessionCronCountByNativeThread, (current) => {
4700+
if (!current.has(nativeThreadId)) {
4701+
return current;
4702+
}
4703+
const updated = new Map(current);
4704+
updated.delete(nativeThreadId);
4705+
return updated;
4706+
});
4707+
});
4708+
47024709
const clearWakeStateForNativeThread =
47034710
/* Provider events include streaming deltas; avoid a span for each update. */
47044711
Effect.fnUntraced(function* (nativeThreadId: string) {
@@ -4752,6 +4759,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
47524759
const preservedOpaqueTombstones = [...priorOpaqueTombstones].filter((taskId) =>
47534760
bufferedTaskNotificationIds.has(taskId),
47544761
);
4762+
yield* clearSessionCronCountForNativeThread(nativeThreadId);
47554763
yield* clearPendingBackgroundTasksForNativeThread(nativeThreadId);
47564764
yield* clearNativeThreadTaskIdSet(
47574765
wakeEligibleBackgroundTasksByNativeThread,
@@ -6963,6 +6971,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
69636971
closedQuery: ClaudeLiveQueryContext,
69646972
cause?: Cause.Cause<ClaudeAgentSdkQueryRunnerError>,
69656973
) {
6974+
yield* clearSessionCronCountForNativeThread(closedQuery.nativeThreadId);
69666975
const current = yield* Ref.get(activeTurn);
69676976
// A replacement query can reuse the native thread id; only this query's turn is ours.
69686977
const context = closedQuery.lastTurn;

0 commit comments

Comments
 (0)