Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 127 additions & 4 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3788,10 +3788,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
session_id: WAKE_NATIVE_SESSION,
}),
);
if (outcome === "release-before") {
yield* Deferred.succeed(release, undefined);
yield* Fiber.join(pending);
}
if (outcome === "release-before") yield* Deferred.succeed(release, undefined);
yield* harness.offerAndWait(
claudeSdkFrame({
type: "system",
Expand All @@ -3801,6 +3798,8 @@ describe("ClaudeAdapterV2 background wake turns", () => {
session_id: WAKE_NATIVE_SESSION,
}),
);
// Ready while compacting, the steer is held until the boundary.
if (outcome === "release-before") yield* Fiber.join(pending);
if (outcome === "cancel-after") {
yield* Fiber.interrupt(pending);
assert.isTrue(Exit.hasInterrupts(yield* Fiber.await(pending)));
Expand Down Expand Up @@ -5418,6 +5417,130 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);

// regression: #25796 a steer offered while Claude compacts aborts the
// compaction, which then starts over.
it.effect.each(["compact_result", "compact_boundary", "turn end"] as const)(
"holds steers sent during compaction until it ends: %s",
(ending) =>
Effect.gen(function* () {
const harness = yield* makeWakeHarness;
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const attemptId = RunAttemptId.make("attempt-steer-compacting");
const input = makeClaudeTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now: yield* DateTime.now,
attemptId,
text: "Summarize the long log.",
attachments: [],
});
yield* harness.runtime.startTurn(input);
yield* harness.offerAndWait(
claudeSdkFrame({
...makeAssistantTextFrame({
uuid: "00000000-0000-4000-8000-000000025796",
text: "Reading.",
}),
user_message_uuids: [harness.promptUuid(0)],
}),
);
yield* harness.offerAndWait(
claudeSdkFrame({
type: "system",
subtype: "status",
status: "compacting",
uuid: "00000000-0000-4000-8000-000000025797",
session_id: WAKE_NATIVE_SESSION,
}),
);
const steer = (id: string) =>
harness.runtime.steerTurn({
threadId: harness.threadId,
runId: input.runId,
providerThread: harness.providerThread,
providerTurnId: idAllocator.derive.providerTurn({
driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
nativeTurnId: `turn:${attemptId}`,
}),
message: {
createdBy: "user",
creationSource: "web",
messageId: MessageId.make(id),
text: `Steer ${id}`,
attachments: [],
},
});
const steerStatus = (id: string) =>
harness.events
.flatMap((event) =>
event.type === "steer.updated" && event.messageId === id ? [event.status] : [],
)
.at(-1);
// One after the other, as the effect outbox runs a thread's steers.
const steers = yield* Effect.forkScoped(
Effect.exit(steer("held-first").pipe(Effect.andThen(steer("held-second")))),
);
yield* harness.until(() => steerStatus("held-first") !== undefined);
assert.lengthOf(harness.offeredMessages, 1);
assert.isUndefined(steers.pollUnsafe());

yield* harness.offerAndWait(
ending === "compact_result"
? claudeSdkFrame({
type: "system",
subtype: "status",
status: null,
compact_result: "success",
uuid: "00000000-0000-4000-8000-000000025798",
session_id: WAKE_NATIVE_SESSION,
})
: ending === "compact_boundary"
? claudeSdkFrame({
type: "system",
subtype: "compact_boundary",
compact_metadata: { trigger: "auto", pre_tokens: 1500, post_tokens: 400 },
uuid: "00000000-0000-4000-8000-000000025798",
session_id: WAKE_NATIVE_SESSION,
})
: claudeSdkFrame({
...makeResultFrame({
uuid: "00000000-0000-4000-8000-000000025798",
result: "Summarized.",
}),
user_message_uuid: harness.promptUuid(0),
}),
);
const exit = yield* Fiber.join(steers);
const steered = harness.offeredMessages
.slice(1)
.map((message) => `${message.priority}:${JSON.stringify(message.message.content)}`);
if (ending === "turn end") {
// Failing, not succeeding unsent, is what makes the orchestrator send it as a follow-up.
assert.match(
Exit.isFailure(exit) ? Cause.pretty(exit.cause) : "sent",
/ended before the steer was sent/,
);
assert.deepEqual(steered, []);
yield* harness.until(() => steerStatus("held-first") === "completed");
return;
}
assert.isTrue(Exit.isSuccess(exit));
assert.lengthOf(steered, 2);
assert.match(steered[0] ?? "", /^now:.*Steer held-first/);
assert.match(steered[1] ?? "", /^now:.*Steer held-second/);
}).pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(
IdAllocator.layer,
McpProviderSessions.layer,
NodeServices.layer,
NodeCrypto.layer,
),
),
),
);

// Claude can answer a steer while its offer is still being logged.
it.effect("settles a turn whose result echoes only a steer before the offer returns", () =>
Effect.gen(function* () {
Expand Down
36 changes: 32 additions & 4 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4755,6 +4755,8 @@ interface ActiveClaudeTurnContext {
readonly toolCalls: Map<string, ActiveClaudeToolCall>;
// A successful status can precede the boundary that supplies its token counts.
compaction: Extract<OrchestrationV2TurnItem, { type: "compaction" }> | null;
// Set while a compaction runs. A steer offered then aborts it and Claude starts it over.
compactionEnded: Deferred.Deferred<void> | null;
readonly ignoredTaskIds: Set<string>;
readonly announcedUsageLimits: Set<string>;
authenticationFailureMessage: string | undefined;
Expand Down Expand Up @@ -8636,6 +8638,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
status,
});

const endCompactionHold = (context: ActiveClaudeTurnContext) =>
Effect.suspend(() => {
const ended = context.compactionEnded;
context.compactionEnded = null;
return ended === null ? Effect.void : Deferred.succeed(ended, undefined);
});

const markSteersAccepted = Effect.fnUntraced(function* (
context: ActiveClaudeTurnContext,
message: SDKMessage,
Expand Down Expand Up @@ -8669,6 +8678,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
readonly result?: SDKResultMessage;
}) {
input.context.steersClosed = true;
yield* endCompactionHold(input.context);
yield* reasoningDeltas.flushTurn(input.context.nativeTurnId);
if (input.status === "completed") {
yield* assistantDeltas.flushTurn(input.context.nativeTurnId);
Expand Down Expand Up @@ -10290,6 +10300,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
context.compactionFailure = failed ? { message: message.compact_error } : null;
}
if (context.compaction?.status === "running") {
yield* endCompactionHold(context);
const now = yield* DateTime.now;
context.compaction = {
...context.compaction,
Expand Down Expand Up @@ -10363,13 +10374,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
// removes. Pending reservations must survive its boundary too.
if (budget !== undefined) budget.compacting = { ...budget.committed };
context.compaction = compaction;
context.compactionEnded ??= yield* Deferred.make<void>();
yield* emitProviderEvent({
type: "turn_item.updated",
driver: CLAUDE_PROVIDER,
turnItem: compaction,
});
return;
}
yield* endCompactionHold(context);
const budget = pdfBudgets.get(context.nativeThreadId);
if (budget !== undefined) {
// Aggregate persisted usage cannot identify attachments in a
Expand Down Expand Up @@ -12507,6 +12520,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
compactionFailure: null,
steeredSegmentUsage: [],
steersClosed: false,
compactionEnded: null,
steeredLedgerUsage: { inputTokens: 0, outputTokens: 0 },
rootModels: new Set(),
subagentsByTaskId: new Map(),
Expand Down Expand Up @@ -12964,22 +12978,36 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
if (liveSteerSelection !== undefined) {
yield* applySelectionLive(existing, liveSteerSelection);
}
// The turn can end while the moves or the selection change are answered.
// A steer offered then would start a new turn the orchestrator never
// asked for, so the steer fails and the orchestrator starts the follow-up turn.
const messageId = turnInput.message.messageId;
// Held here, not acknowledged: the steer succeeds only once Claude has it.
const held = currentTurn.compactionEnded !== null;
if (held) {
yield* emitSteerStatus(currentTurn, messageId, "pending");
yield* Effect.gen(function* () {
while (currentTurn.compactionEnded !== null) {
yield* Deferred.await(currentTurn.compactionEnded);
}
}).pipe(
Effect.onInterrupt(() => emitSteerStatus(currentTurn, messageId, "completed")),
);
}
// The turn can end while the moves or the selection change are answered, or
// while the steer is held. A steer offered then would start a new turn the
// orchestrator never asked for, so the steer fails and the orchestrator
// starts the follow-up turn.
if (
(yield* Ref.get(activeTurn))?.providerTurnId !== turnInput.providerTurnId ||
(yield* Ref.get(queryContext)) !== existing ||
// No yield between this check and the set below.
currentTurn.steersClosed
) {
if (held) yield* emitSteerStatus(currentTurn, messageId, "completed");
return yield* new ProviderAdapter.ProviderAdapterProtocolError({
driver: CLAUDE_PROVIDER,
detail: `Claude provider turn ${turnInput.providerTurnId} ended before the steer was sent.`,
});
}
// Register before offering: Claude can start the steer and end the turn before offer returns.
const messageId = turnInput.message.messageId;
currentTurn.steerUuids.add(steerUuid);
currentTurn.pendingSteers.set(steerUuid, {
messageId,
Expand Down
23 changes: 23 additions & 0 deletions apps/server/src/orchestration-v2/EffectOutbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,10 @@ export interface EffectOutboxV2Shape {
readonly listByCommandId: (
commandId: CommandId,
) => Effect.Effect<ReadonlyArray<OrchestrationEffectV2>, EffectOutboxError>;
readonly listUnsettled: (input: {
readonly threadId: ThreadId;
readonly effectTypes: ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
}) => Effect.Effect<ReadonlyArray<OrchestrationEffectV2>, EffectOutboxError>;
readonly cancelUnsettled: (input: {
readonly threadId: ThreadId;
readonly effectTypes: ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
Expand Down Expand Up @@ -464,6 +468,25 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
: new EffectOutboxError({ operation: "list", cause }),
),
),
listUnsettled: ({ threadId, effectTypes }) =>
(effectTypes.length === 0
? Effect.succeed<ReadonlyArray<EffectRow>>([])
: sql<EffectRow>`
SELECT *
FROM orchestration_v2_effect_outbox
WHERE thread_id = ${threadId}
AND status IN ('pending', 'running')
AND effect_type IN ${sql.in(effectTypes)}
ORDER BY rowid ASC
`.pipe(NodeSqliteClient.readOnly)
).pipe(
Effect.flatMap((rows) => decodeRows("list-unsettled", rows)),
Effect.mapError((cause) =>
isEffectOutboxError(cause)
? cause
: new EffectOutboxError({ operation: "list-unsettled", cause }),
),
),
cancelUnsettled: Effect.fn("EffectOutbox.cancelUnsettled")(
function* ({ threadId, effectTypes, reason }) {
if (effectTypes.length === 0) return [];
Expand Down
58 changes: 56 additions & 2 deletions apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12856,6 +12856,50 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
});

const emitEvent = emit(events, command);
// A thread's effects run in order, so a steer still waiting to reach the provider
// (Claude holds steers while it compacts) would keep this interrupt waiting behind it.
const cancelUndeliveredSteers = Effect.gen(function* () {
const undeliveredSteers = yield* effectOutbox
.listUnsettled({ threadId: command.threadId, effectTypes: ["provider-turn.steer"] })
.pipe(
Effect.mapError(
(cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
),
);
for (const { request, status, attemptCount } of undeliveredSteers) {
if (request.type !== "provider-turn.steer") continue;
const item = yield* projectionStore
.getTurnItem({
threadId: command.threadId,
itemId: idAllocator.derive.userTurnItem({ messageId: request.messageId }),
})
.pipe(
Effect.mapError(
(cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
),
);
// An unsettled effect is not an unread steer: a provider can confirm one before its
// call returns. Only a steer the provider still reports pending, or one whose effect
// never ran, is known not to have been read.
const neverSent = status === "pending" && attemptCount === 0;
if (
item?.type !== "user_message" ||
!(item.status === "pending" || (neverSent && item.status === "completed"))
) {
continue;
}
yield* emitEvent({
type: "turn-item.updated",
threadId: command.threadId,
...(item.runId === null ? {} : { runId: item.runId }),
...(item.nodeId === null ? {} : { nodeId: item.nodeId }),
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now },
});
}
return undeliveredSteers.length > 0;
});
const interruptRequestItem: OrchestrationV2TurnItem = {
id: idAllocator.derive.runSignalTurnItem({
runId: run.id,
Expand Down Expand Up @@ -13074,9 +13118,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
}
}
yield* stopRemainingWork();
yield* cancelUndeliveredSteers;
yield* Ref.update(effects, (existing) => [...existing, ...otherProviderInterrupts]);
return {
effectTypes: ["provider-turn.start", "provider-turn.restart"],
effectTypes: ["provider-turn.start", "provider-turn.restart", "provider-turn.steer"],
reason: `Run ${run.id} was interrupted before its provider turn started.`,
} satisfies {
readonly effectTypes: ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
Expand Down Expand Up @@ -13154,6 +13199,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
payload: interruptRequestItem,
});
yield* stopRemainingWork();
const steersCancelled = yield* cancelUndeliveredSteers;
yield* Ref.update(effects, (existing) => [
...existing,
{
Expand All @@ -13169,7 +13215,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
} satisfies PendingOrchestrationEffectV2,
...otherProviderInterrupts,
]);
return undefined;
return !steersCancelled
? undefined
: ({
effectTypes: ["provider-turn.steer"],
reason: `Run ${run.id} was stopped before the steer reached its provider.`,
} satisfies {
readonly effectTypes: ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
readonly reason: string;
});
});

/** Writes a parent's app-owned task, and sets its node and turn items to the task's status. */
Expand Down
Loading
Loading