fix(claude): Settle positive task-notification results

A Claude V2 turn whose terminal SDK result carried origin.kind
"task-notification" had that result discarded, so the run stayed running
forever and every run queued behind it stalled. The drop is now limited to
results reporting zero model turns, which is what the stale debris the guard
was written for actually looks like.

ClaudeAdapterV2 dropped any task-notification-origin result unless the turn was
an agent/provider continuation. An app-owned delegated-task wake run is
agent/server, so its terminal results were discarded and finalizeActiveTurn
never ran. Any turn whose final result carries that origin hangs, not just
wakes. Observed in production against a real session: three terminal success
results with num_turns 154, 60 and 7 were all dropped, the session went silent
for 8h27m, and five queued runs behind it never dispatched.

The guard could not simply be deleted. After interrupt recovery a stale stopped
task_notification and its origin result interleave ahead of the real root
assistant stream and must not terminalize the turn or leak their text.
Zero-turn results are still dropped, so that path is unchanged: this drops
strictly fewer results than before, so no previously working path can regress.

num_turns separates the two cases cleanly. The existing stale fixture sets
numTurns 0 explicitly, makeResultFrame defaults to 1, and the production
results all carried positive turns. The predicate is num_turns === 0 rather
than < 1 or a truthiness check on purpose: num_turns is required on both result
variants in 0.3.205, but if an older emitter ever omitted it, undefined === 0
is false, so the result is accepted rather than dropped. That fails toward
terminalizing rather than toward the hang class this fixes.

Both drops and accepts are logged with num_turns, stop_reason, terminal_reason,
result uuid, session id and message provenance. The drop is debug level because
interrupt recovery produces it routinely; the accept is info, because a
positive-turn task-notification result settling a non-continuation turn is both
the hang fix working and the exact shape a stale positive-turn result would
take.

Co-authored-by: codex <[email protected]>
This commit is contained in:
Mike Olsonandcodex authored and maria-rcks committed 2026-08-03 11:45:11 -04:00
1 parent 5ee040a06e
commit b244cc81ce
2 files changed
+462 -87

No files matched your search

@@ -25,6 +25,7 @@ import {
import { assert, describe, it } from "@effect/vitest";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
@@ -1122,18 +1123,43 @@ describe("ClaudeAdapterV2 background wake turns", () => {
uuid: "00000000-0000-4000-8000-000000000101",
session_id: WAKE_NATIVE_SESSION,
});
const makeAssistantTextFrame = (input: { readonly uuid: string; readonly text: string }) =>
claudeSdkFrame({
type: "assistant",
message: {
model: "claude-sonnet-4-6",
id: `msg_${input.uuid}`,
type: "message",
role: "assistant",
content: [{ type: "text", text: input.text }],
stop_reason: null,
stop_sequence: null,
usage: {
input_tokens: 1,
output_tokens: 1,
cache_creation_input_tokens: 0,
cache_read_input_tokens: 0,
},
},
parent_tool_use_id: null,
uuid: input.uuid,
session_id: WAKE_NATIVE_SESSION,
});
const makeResultFrame = (input: {
readonly uuid: string;
readonly result: string;
readonly numTurns?: number;
readonly origin?: { readonly kind: "task-notification" };
readonly subtype?: string;
readonly isError?: boolean;
readonly errors?: ReadonlyArray<string>;
}) =>
claudeSdkFrame({
type: "result",
subtype: "success",
subtype: input.subtype ?? "success",
duration_ms: 10,
duration_api_ms: 10,
is_error: false,
is_error: input.isError ?? false,
num_turns: input.numTurns ?? 1,
result: input.result,
stop_reason: "end_turn",
@@ -1149,6 +1175,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
uuid: input.uuid,
session_id: WAKE_NATIVE_SESSION,
...(input.origin === undefined ? {} : { origin: input.origin }),
...(input.errors === undefined ? {} : { errors: input.errors }),
});
const turnOneResult = makeResultFrame({
uuid: "00000000-0000-4000-8000-000000000102",
@@ -1189,87 +1216,92 @@ describe("ClaudeAdapterV2 background wake turns", () => {
return yield* Effect.die(`Timed out waiting for ${label}.`);
});
const makeWakeHarness = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const idAllocator = yield* IdAllocatorV2;
const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-claude-v2-wake-",
});
const sdkMessages = yield* Queue.unbounded<SDKMessage>();
const offeredMessages: Array<SDKUserMessage> = [];
const continuationRequests: Array<ProviderContinuationRequest> = [];
const adapter = makeClaudeAdapterV2({
instanceId: CLAUDE_DEFAULT_INSTANCE_ID,
settings: DEFAULT_CLAUDE_SETTINGS,
environment: {},
attachmentsDir,
fileSystem,
idAllocator,
continuationRequests: {
offer: (request) =>
const makeWakeHarnessWithOptions = (options?: {
readonly close?: (sdkMessages: Queue.Queue<SDKMessage>) => Effect.Effect<void>;
readonly interrupt?: Effect.Effect<void>;
}) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const idAllocator = yield* IdAllocatorV2;
const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-claude-v2-wake-",
});
const sdkMessages = yield* Queue.unbounded<SDKMessage>();
const offeredMessages: Array<SDKUserMessage> = [];
const continuationRequests: Array<ProviderContinuationRequest> = [];
const adapter = makeClaudeAdapterV2({
instanceId: CLAUDE_DEFAULT_INSTANCE_ID,
settings: DEFAULT_CLAUDE_SETTINGS,
environment: {},
attachmentsDir,
fileSystem,
idAllocator,
continuationRequests: {
offer: (request) =>
Effect.sync(() => {
continuationRequests.push(request);
}),
},
queryRunner: {
allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION),
open: () =>
Effect.succeed({
messages: Stream.fromQueue(sdkMessages),
offer: (message) =>
Effect.sync(() => {
offeredMessages.push(message);
}),
setModel: () => Effect.void,
interrupt: options?.interrupt ?? Effect.void,
close: options?.close?.(sdkMessages) ?? Effect.void,
}),
forkSession: () => Effect.die("unused forkSession"),
assertComplete: Effect.void,
},
});
const threadId = ThreadId.make("thread-claude-wake");
const runtime = yield* adapter.openSession({
threadId,
providerSessionId: ProviderSessionId.make("provider-session-claude-wake"),
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
});
const providerThread = yield* runtime.ensureThread({
threadId,
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
});
const events: Array<ProviderAdapterV2Event> = [];
yield* runtime.events.pipe(
Stream.runForEach((event) =>
Effect.sync(() => {
continuationRequests.push(request);
events.push(event);
}),
},
queryRunner: {
allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION),
open: () =>
Effect.succeed({
messages: Stream.fromQueue(sdkMessages),
offer: (message) =>
Effect.sync(() => {
offeredMessages.push(message);
}),
setModel: () => Effect.void,
interrupt: Effect.void,
close: Effect.void,
}),
forkSession: () => Effect.die("unused forkSession"),
assertComplete: Effect.void,
},
});
const threadId = ThreadId.make("thread-claude-wake");
const runtime = yield* adapter.openSession({
threadId,
providerSessionId: ProviderSessionId.make("provider-session-claude-wake"),
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
});
const providerThread = yield* runtime.ensureThread({
threadId,
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
});
const events: Array<ProviderAdapterV2Event> = [];
yield* runtime.events.pipe(
Stream.runForEach((event) =>
Effect.sync(() => {
events.push(event);
}),
),
Effect.forkScoped,
);
if (runtime.hasPendingBackgroundWork === undefined) {
throw new Error("Claude adapter runtime must expose hasPendingBackgroundWork.");
}
const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
const terminalEvents = () =>
events.filter(
(event): event is Extract<ProviderAdapterV2Event, { type: "turn.terminal" }> =>
event.type === "turn.terminal",
),
Effect.forkScoped,
);
return {
runtime,
providerThread,
threadId,
sdkMessages,
offeredMessages,
continuationRequests,
events,
terminalEvents,
hasPendingBackgroundWork,
};
});
if (runtime.hasPendingBackgroundWork === undefined) {
throw new Error("Claude adapter runtime must expose hasPendingBackgroundWork.");
}
const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
const terminalEvents = () =>
events.filter(
(event): event is Extract<ProviderAdapterV2Event, { type: "turn.terminal" }> =>
event.type === "turn.terminal",
);
return {
runtime,
providerThread,
threadId,
sdkMessages,
offeredMessages,
continuationRequests,
events,
terminalEvents,
hasPendingBackgroundWork,
};
});
const makeWakeHarness = makeWakeHarnessWithOptions();
it.effect("buffers wake output and requests a single continuation run", () =>
Effect.scoped(
@@ -1456,7 +1488,107 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
it.effect("ignores a live task-notification origin result during a normal user turn", () =>
it.effect("terminalizes an agent server wake from a positive task-notification result", () =>
Effect.scoped(
Effect.gen(function* () {
const harness = yield* makeWakeHarness;
const now = yield* DateTime.now;
const wakeText = "The background command completed.";
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now,
attemptId: RunAttemptId.make("attempt-claude-agent-server-wake"),
text: "Background task completed.",
attachments: [],
messageCreatedBy: "agent",
messageCreationSource: "server",
}),
);
yield* Queue.offer(
harness.sdkMessages,
makeAssistantTextFrame({
uuid: "00000000-0000-4000-8000-00000000010b",
text: wakeText,
}),
);
yield* Queue.offer(
harness.sdkMessages,
makeResultFrame({
uuid: "00000000-0000-4000-8000-00000000010c",
result: wakeText,
numTurns: 154,
origin: { kind: "task-notification" },
}),
);
yield* awaitUntil(() => harness.terminalEvents().length === 1, "server wake terminal");
assert.equal(harness.terminalEvents()[0]?.status, "completed");
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now,
attemptId: RunAttemptId.make("attempt-claude-agent-server-next"),
text: "What finished?",
attachments: [],
providerTurnOrdinal: 2,
}),
);
yield* Queue.offer(
harness.sdkMessages,
makeResultFrame({
uuid: "00000000-0000-4000-8000-00000000010d",
result: "The background command finished.",
}),
);
yield* awaitUntil(() => harness.terminalEvents().length === 2, "queued turn terminal");
assert.equal(harness.terminalEvents()[1]?.status, "completed");
}).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))),
),
);
it.effect("terminalizes a user mobile turn from a positive task-notification result", () =>
Effect.scoped(
Effect.gen(function* () {
const harness = yield* makeWakeHarness;
const now = yield* DateTime.now;
const fallbackText = "The ordinary mobile turn completed.";
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now,
attemptId: RunAttemptId.make("attempt-claude-mobile-notif-origin"),
text: "Complete this task.",
attachments: [],
messageCreationSource: "mobile",
}),
);
yield* Queue.offer(
harness.sdkMessages,
makeResultFrame({
uuid: "00000000-0000-4000-8000-00000000010e",
result: fallbackText,
numTurns: 60,
origin: { kind: "task-notification" },
}),
);
yield* awaitUntil(() => harness.terminalEvents().length === 1, "mobile turn terminal");
assert.equal(harness.terminalEvents()[0]?.status, "completed");
assert.isTrue(
harness.events.some(
(event) => event.type === "message.updated" && event.message.text === fallbackText,
),
);
}).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))),
),
);
it.effect("ignores a zero-turn task-notification origin result during a normal user turn", () =>
Effect.scoped(
Effect.gen(function* () {
const harness = yield* makeWakeHarness;
@@ -1550,6 +1682,208 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
it.effect("terminalizes a zero-turn task-notification result in a provider continuation", () =>
Effect.scoped(
Effect.gen(function* () {
const harness = yield* makeWakeHarness;
const now = yield* DateTime.now;
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now,
attemptId: RunAttemptId.make("attempt-claude-zero-continuation-1"),
text: "Run the build in the background.",
attachments: [],
}),
);
yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
yield* Queue.offer(harness.sdkMessages, turnOneResult);
yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
yield* Queue.offer(harness.sdkMessages, wakeNotification);
yield* Queue.offer(
harness.sdkMessages,
makeResultFrame({
uuid: "00000000-0000-4000-8000-00000000010f",
result: "Wake result with no model turns.",
numTurns: 0,
origin: { kind: "task-notification" },
}),
);
yield* awaitUntil(() => harness.continuationRequests.length === 1, "continuation request");
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now,
attemptId: RunAttemptId.make("attempt-claude-zero-continuation-2"),
text: "Background task completed.",
attachments: [],
providerTurnOrdinal: 2,
messageCreatedBy: "agent",
messageCreationSource: "provider",
}),
);
yield* awaitUntil(() => harness.terminalEvents().length === 2, "continuation terminal");
assert.equal(harness.terminalEvents()[1]?.status, "completed");
}).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))),
),
);
it.effect(
"emits one interrupted terminal for a positive task-notification result racing interrupt",
() =>
Effect.scoped(
Effect.gen(function* () {
const closeGate = yield* Deferred.make<void>();
const testScope = yield* Scope.Scope;
yield* Scope.addFinalizer(testScope, Deferred.succeed(closeGate, undefined));
const interruptStarted = yield* Deferred.make<void>();
const harness = yield* makeWakeHarnessWithOptions({
close: (sdkMessages) =>
Deferred.await(closeGate).pipe(Effect.andThen(Queue.shutdown(sdkMessages))),
interrupt: Deferred.succeed(interruptStarted, undefined),
});
const idAllocator = yield* IdAllocatorV2;
const now = yield* DateTime.now;
const attemptId = RunAttemptId.make("attempt-claude-interrupt-positive-notif");
const providerTurnId = idAllocator.derive.providerTurn({
driver: CLAUDE_PROVIDER,
nativeTurnId: `turn:${attemptId}`,
});
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now,
attemptId,
text: "Stop this task.",
attachments: [],
}),
);
yield* harness.runtime
.interruptTurn({ providerThread: harness.providerThread, providerTurnId })
.pipe(Effect.forkScoped);
yield* Deferred.await(interruptStarted);
yield* Queue.offer(
harness.sdkMessages,
makeResultFrame({
uuid: "00000000-0000-4000-8000-000000000115",
result: "Late result after interrupt.",
numTurns: 7,
origin: { kind: "task-notification" },
}),
);
const terminalized = Exit.isSuccess(
yield* awaitUntil(
() => harness.terminalEvents().length === 1,
"interrupted terminal",
).pipe(Effect.exit),
);
yield* Deferred.succeed(closeGate, undefined);
assert.isTrue(terminalized);
assert.equal(harness.terminalEvents()[0]?.status, "interrupted");
assert.lengthOf(harness.terminalEvents(), 1);
}).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))),
),
);
it.effect("drops zero-turn task-notification debris racing interrupt", () =>
Effect.scoped(
Effect.gen(function* () {
const closeGate = yield* Deferred.make<void>();
const testScope = yield* Scope.Scope;
yield* Scope.addFinalizer(testScope, Deferred.succeed(closeGate, undefined));
const interruptStarted = yield* Deferred.make<void>();
const harness = yield* makeWakeHarnessWithOptions({
close: (sdkMessages) =>
Deferred.await(closeGate).pipe(Effect.andThen(Queue.shutdown(sdkMessages))),
interrupt: Deferred.succeed(interruptStarted, undefined),
});
const idAllocator = yield* IdAllocatorV2;
const now = yield* DateTime.now;
const attemptId = RunAttemptId.make("attempt-claude-interrupt-zero-notif");
const providerTurnId = idAllocator.derive.providerTurn({
driver: CLAUDE_PROVIDER,
nativeTurnId: `turn:${attemptId}`,
});
const staleText = "Zero-turn debris must not leak.";
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now,
attemptId,
text: "Stop this task.",
attachments: [],
}),
);
yield* harness.runtime
.interruptTurn({ providerThread: harness.providerThread, providerTurnId })
.pipe(Effect.forkScoped);
yield* Deferred.await(interruptStarted);
yield* Queue.offer(
harness.sdkMessages,
makeResultFrame({
uuid: "00000000-0000-4000-8000-000000000116",
result: staleText,
numTurns: 0,
origin: { kind: "task-notification" },
}),
);
let debrisYields = 0;
yield* awaitUntil(() => debrisYields++ >= 50, "zero-turn debris consumed");
yield* Deferred.succeed(closeGate, undefined);
yield* awaitUntil(() => harness.terminalEvents().length === 1, "interrupted terminal");
assert.lengthOf(harness.terminalEvents(), 1);
assert.equal(harness.terminalEvents()[0]?.status, "interrupted");
assert.isFalse(
harness.events.some(
(event) => event.type === "message.updated" && event.message.text === staleText,
),
);
}).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))),
),
);
it.effect("fails a positive task-notification error result", () =>
Effect.scoped(
Effect.gen(function* () {
const harness = yield* makeWakeHarness;
const now = yield* DateTime.now;
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now,
attemptId: RunAttemptId.make("attempt-claude-positive-notif-error"),
text: "Run the task.",
attachments: [],
}),
);
yield* Queue.offer(
harness.sdkMessages,
makeResultFrame({
uuid: "00000000-0000-4000-8000-000000000117",
result: "The task failed.",
numTurns: 7,
origin: { kind: "task-notification" },
subtype: "error_during_execution",
isError: true,
errors: ["The task failed."],
}),
);
yield* awaitUntil(() => harness.terminalEvents().length === 1, "failed terminal");
assert.equal(harness.terminalEvents()[0]?.status, "failed");
}).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))),
),
);
it.effect("terminalizes a continuation turn from a task-notification origin wake result", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -3279,16 +3279,57 @@ export function makeClaudeAdapterV2(
return;
}
// Task-notification-origin results can interleave during a normal
// user turn (for example a stale background stop after interrupt
// recovery). They must not finalize that turn or supply fallback
// assistant text. Provider continuation turns still consume them
// when draining buffered wake messages.
// A zero-turn task-notification-origin result is almost always
// lifecycle debris, so it must not finalize a normal turn or supply
// fallback assistant text. Provider continuation turns still consume
// it when draining buffered wake messages.
//
// "Almost always" is the honest word: num_turns is a workload count,
// not a causal link to the prompt this turn is waiting on. A genuine
// wake that fails before any model turn also reports zero, and is
// dropped here, so that turn hangs until query exit. Narrowing the
// drop to zero-turn results only shrinks a pre-existing drop; closing
// the residue needs a correlation id on the result, which the wire
// does not carry today.
if (
isClaudeTaskNotificationOriginResult(message) &&
!isClaudeProviderContinuationTurn(context.input) &&
message.num_turns === 0
) {
// Routine lifecycle noise, so debug rather than warning: interrupt
// recovery produces this every time.
yield* Effect.logDebug("orchestration-v2.claude-task-notification-result-dropped", {
providerTurnId: context.providerTurnId,
num_turns: message.num_turns,
stop_reason: message.stop_reason,
terminal_reason: message.terminal_reason,
uuid: message.uuid,
session_id: message.session_id,
createdBy: context.input.message.createdBy,
creationSource: context.input.message.creationSource,
});
return;
}
// The converse of the drop above, and the case actually worth
// watching: a positive-turn task-notification result settling a turn
// T3 did not mark as a continuation. That is the hang fix working,
// but it is also the shape a stale result would take if one ever
// carried model turns, which nothing on the wire lets us rule out.
if (
isClaudeTaskNotificationOriginResult(message) &&
!isClaudeProviderContinuationTurn(context.input)
) {
return;
yield* Effect.logInfo("orchestration-v2.claude-task-notification-result-accepted", {
providerTurnId: context.providerTurnId,
num_turns: message.num_turns,
stop_reason: message.stop_reason,
terminal_reason: message.terminal_reason,
uuid: message.uuid,
session_id: message.session_id,
createdBy: context.input.message.createdBy,
creationSource: context.input.message.creationSource,
});
}
// An is_error result's text is the error message; it belongs on the