Skip to content
TypeScript

fix(server): Claude background-task wakes start when the queue is held (#17885)

fireboltdude1357531cee6f1695
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
index 1d6b4c8586b..9fe028089f3 100644
--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
@@ -4880,6 +4880,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
threadId: context.projectionThreadId,
providerThreadId: context.providerThread.id,
driver: CODEX_PROVIDER,
+ // Codex starts a new turn from this text, so nothing is buffered.
+ delivery: "message_text",
detail: codexBackgroundCommandDetail(payload.item),
notification: {
...backgroundWorkNotification([
diff --git a/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts b/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts
index e59ad3da7cd..ffe8203c8cb 100644
--- a/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts
+++ b/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts
@@ -35,6 +35,7 @@ const instanceId = ProviderInstanceId.make("codex");
const modelSelection = { instanceId, model: "test-model" };
const stopEarlierBackgroundWork = ({
+ wakeAfterStop = false,
failedStart = false,
stopWithQueue,
olderStart = false,
@@ -42,6 +43,7 @@ const stopEarlierBackgroundWork = ({
stalledRun,
workflowMember = false,
}: {
+ readonly wakeAfterStop?: boolean;
readonly failedStart?: boolean;
readonly backgroundWorkAfterStop?: "running" | "unknown";
readonly stopWithQueue?: "thread.stop" | "run.interrupt";
@@ -192,6 +194,46 @@ const stopEarlierBackgroundWork = ({
});
yield* worker.drain();
yield* Fiber.join(running);
+ if (wakeAfterStop) {
+ const send = (id: string, provider = false) =>
+ orchestrator.dispatch({
+ type: "message.dispatch",
+ commandId: CommandId.make(id),
+ threadId,
+ messageId: MessageId.make(`message:${id}`),
+ text: id,
+ attachments: [],
+ dispatchMode: { type: "queue_after_active" },
+ createdBy: provider ? "agent" : "user",
+ creationSource: provider ? "provider" : "web",
+ });
+ yield* send("follow-up");
+ yield* orchestrator.dispatch({
+ type: "thread.stop",
+ commandId: CommandId.make("stop"),
+ threadId,
+ });
+ // Stop is committed, but its provider interrupt has not run yet.
+ yield* send("Background task completed.", true);
+ const [stopped, followUp, wake] = (yield* orchestrator.getThreadProjection(threadId))
+ .runs;
+ assert.equal(stopped?.status, "running");
+ assert.isTrue(followUp?.queueHeld);
+ assert.isTrue(wake?.queueHeld);
+
+ yield* worker.drain();
+ yield* orchestrator.resumeQueuedRuns;
+ yield* worker.drain();
+ const after = yield* orchestrator.getThreadProjection(threadId);
+ assert.deepEqual(
+ after.runs.map((run) => run.status),
+ ["interrupted", "queued", "queued"],
+ );
+ assert.isTrue(after.runs.find((run) => run.id === followUp?.id)?.queueHeld);
+ assert.isTrue(after.runs.find((run) => run.id === wake?.id)?.queueHeld);
+ assert.lengthOf(started, 1);
+ return;
+ }
const first = started[0]!;
const codexTurn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
const devServerId = TurnItemId.make("turn-item:dev-server");
@@ -1016,3 +1058,7 @@ it.effect.each(["missing-session-terminal", "returned-interrupt", "superseded-at
"Stop recovers a stalled run after %s without changing a newer attempt",
(stalledRun) => stopEarlierBackgroundWork({ stalledRun }),
);
+
+it.effect("Stop holds a provider wake that queues before the stopped turn ends", () =>
+ stopEarlierBackgroundWork({ wakeAfterStop: true }),
+);
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index eb65522fff9..f9bf293eb9f 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -729,7 +729,7 @@ function delegatedTaskTerminalStatus(
function nextQueuedRun(
projection: Pick<OrchestrationV2ThreadProjection, "runs" | "messages">,
): OrchestrationV2Run | undefined {
- return queuedRunsInDeliveryOrder(projection)[0];
+ return queuedRunsInDeliveryOrder(projection).find((run) => run.queueHeld !== true);
}
function followsCurrentConversation(
@@ -1491,8 +1491,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
if (
projection.thread.archivedAt !== null ||
projection.thread.deletedAt !== null ||
- projection.runs.some(isBlockingRun) ||
- projection.runs.some((run) => run.status === "queued" && run.queueHeld === true)
+ projection.runs.some(isBlockingRun)
) {
return;
}
@@ -5612,6 +5611,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
}),
),
);
+ const queueIsHeld = projection.runs.some(
+ (candidate) => candidate.status === "queued" && candidate.queueHeld === true,
+ );
+ // Buffered wakes need a T3 run for output the CLI already started producing.
+ // Stop still holds wakes that arrive before the active run settles.
+ const wakeSkipsHold =
+ !worktreeSetupUnresolved &&
+ activeRun !== undefined &&
+ queueIsHeld &&
+ command.createdBy === "agent" &&
+ command.creationSource === "provider" &&
+ !(yield* stopReachedRun(command, command.threadId, activeRun.id));
const run: OrchestrationV2Run = {
id: runId,
threadId: command.threadId,
@@ -5624,10 +5635,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
activeAttemptId: attemptId,
status: "queued",
...(worktreeMissingRun !== undefined ||
- (heldRunsToRelease.length === 0 &&
- projection.runs.some(
- (candidate) => candidate.status === "queued" && candidate.queueHeld === true,
- ))
+ (heldRunsToRelease.length === 0 && queueIsHeld && !wakeSkipsHold)
? { queueHeld: true }
: {}),
queuePosition:
@@ -12673,7 +12681,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
});
}
}
- const nextRun = selectedRun ?? nextQueuedRun(projection);
+ const nextRun = selectedRun ?? queuedRunsInDeliveryOrder(projection)[0];
if (
usageLimitHoldsQueue(
projection,
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts
index 288378d09fe..06a7b8b651e 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts
@@ -186,6 +186,41 @@ const addRolledBackRecoveryCandidate = Effect.fn("addRolledBackRecoveryCandidate
return threadId;
});
+it.effect.each([
+ ["memory", ProjectionStore.layerMemory],
+ ["SQL", layerTest],
+] as const)("%s queue readiness skips held runs without bypassing active work", ([, layer]) =>
+ Effect.gen(function* () {
+ const store = yield* ProjectionStore.ProjectionStoreV2;
+ const threadId = yield* addRolledBackRecoveryCandidate("held-queue");
+ const { runs } = yield* store.getThreadProjection(threadId);
+ const run = runs[0]!;
+ const now = yield* DateTime.now;
+ const held = { ...run, status: "queued" as const, queueHeld: true };
+ yield* store.apply({
+ id: EventId.make("held-queue:held"),
+ type: "run.updated",
+ threadId,
+ occurredAt: now,
+ payload: held,
+ });
+ assert.isFalse(yield* store.canStartQueuedRun(threadId));
+
+ const wake = { ...run, id: RunId.make("held-queue:wake"), ordinal: 2 };
+ for (const status of ["running", "queued", "completed"] as const) {
+ yield* store.apply({
+ id: EventId.make(`held-queue:wake:${status}`),
+ type: "run.updated",
+ threadId,
+ occurredAt: now,
+ payload: { ...wake, status },
+ });
+ assert.equal(yield* store.canStartQueuedRun(threadId), status === "queued");
+ }
+ assert.deepEqual((yield* store.getThreadProjection(threadId)).runs[0], held);
+ }).pipe(Effect.provide(layer)),
+);
+
it.effect.each([
["memory", ProjectionStore.layerMemory],
["SQL", layerTest],
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts
index a10710a2cc3..3651fc3f455 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts
@@ -5313,11 +5313,11 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
SELECT 1 AS ready FROM orchestration_v2_projection_threads AS thread
WHERE thread.thread_id = ${threadId} AND thread.archived_at IS NULL AND thread.deleted_at IS NULL
AND EXISTS (SELECT 1 FROM orchestration_v2_projection_runs
- WHERE thread_id = ${threadId} AND status = 'queued')
+ WHERE thread_id = ${threadId} AND status = 'queued'
+ AND json_extract(payload_json, '$.queueHeld') IS NOT 1)
AND NOT EXISTS (SELECT 1 FROM orchestration_v2_projection_runs
WHERE thread_id = ${threadId}
- AND (status IN ('preparing', 'starting', 'running', 'waiting')
- OR (status = 'queued' AND json_extract(payload_json, '$.queueHeld') = 1)))`;
+ AND status IN ('preparing', 'starting', 'running', 'waiting'))`;
return rows.length > 0;
}),
)
@@ -7604,14 +7604,13 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
return (
projection.thread.archivedAt === null &&
projection.thread.deletedAt === null &&
- projection.runs.some((run) => run.status === "queued") &&
+ projection.runs.some((run) => run.status === "queued" && run.queueHeld !== true) &&
!projection.runs.some(
(run) =>
run.status === "preparing" ||
run.status === "starting" ||
run.status === "running" ||
- run.status === "waiting" ||
- (run.status === "queued" && run.queueHeld === true),
+ run.status === "waiting",
)
);
}),
diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
index 1e3fd1a8b36..88fc87d3bc0 100644
--- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
@@ -1320,6 +1320,21 @@ it.effect.each(["failed", "interrupted"] as const)(
createdBy: "user",
creationSource: "web",
});
+ yield* threads.dispatch({
+ type: "message.dispatch",
+ commandId: CommandId.make(`command:launch:late-queued-follow-up-${ending}:wake`),
+ threadId: launched.threadId,
+ messageId: MessageId.make(`message:launch:late-queued-follow-up-${ending}:wake`),
+ text: "Background task completed.",
+ attachments: [],
+ dispatchMode: { type: "queue_after_active" },
+ createdBy: "agent",
+ creationSource: "provider",
+ });
+ const wake = (yield* threads.getThreadProjection(launched.threadId)).runs.at(-1)!;
+ assert.equal(wake.status, "queued");
+ assert.isTrue(wake.queueHeld);
+
// Nor does the next one, though the run that message started is now the
// latest and carries no workspace preparation.
yield* threads.sendToThread({
diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
index 87da6479adb..c77837094b2 100644
--- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts
+++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
@@ -4904,6 +4904,23 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
threadId,
runId: limited.id,
});
+ yield* eventSink.write({
+ events: [
+ {
+ id: EventId.make(`${threadId}:hold-available`),
+ type: "run.updated",
+ threadId,
+ runId: available.id,
+ occurredAt: now,
+ payload: { ...available, queueHeld: true },
+ },
+ ],
+ });
+ yield* orchestrator.dispatch({
+ type: "queue.resume",
+ commandId: CommandId.make(`${threadId}:resume-available`),
+ threadId,
+ });
yield* orchestrator.resumeQueuedRuns;
const after = yield* orchestrator.getThreadProjection(threadId);
const started = after.runs.find((run) => run.id === available.id);
@@ -5286,6 +5303,80 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
}),
);
+ it.effect("starts a provider wake queued beside a held queue", () =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const recovery = yield* ProviderRuntimeRecoveryService.ProviderRuntimeRecoveryService;
+ const events = yield* EventSink.EventSinkV2;
+ const threadId = ThreadId.make("queue-hold-provider-wake");
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make(`${threadId}:create`),
+ threadId,
+ projectId: ProjectId.make(`${threadId}:project`),
+ title: "Wake beside a held queue",
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: process.cwd(),
+ });
+ const send = (index: number, text: string, source: "web" | "provider" | "server" = "web") =>
+ orchestrator.dispatch({
+ type: "message.dispatch",
+ createdBy: source === "web" ? "user" : "agent",
+ creationSource: source,
+ commandId: CommandId.make(`${threadId}:message:${index}`),
+ threadId,
+ messageId: MessageId.make(`${threadId}:message:${index}`),
+ text,
+ attachments: [],
+ modelSelection,
+ dispatchMode: { type: index === 0 ? "start_immediately" : "queue_after_active" },
+ });
+ yield* send(0, "Active");
+ yield* send(1, "Queued before the restart");
+ yield* recovery.reconcile("startup");
+ yield* send(2, "First background task completed.", "provider");
+ yield* send(3, "Background task completed.", "provider");
+ yield* send(4, "Continue after the command completed.", "server");
+ const queued = yield* orchestrator.getThreadProjection(threadId);
+ const [held, active, wake] = [queued.runs[1]!, queued.runs[2]!, queued.runs[3]!];
+ assert.equal(active.status, "starting");
+ assert.isTrue(held.queueHeld);
+ assert.equal(wake.status, "queued");
+ assert.notEqual(wake.queueHeld, true);
+ const textContinuation = queued.runs[4]!;
+ assert.isTrue(textContinuation.queueHeld);
+ const now = yield* DateTime.now;
+ yield* events.write({
+ events: [
+ {
+ id: EventId.make(`${threadId}:active-done`),
+ type: "run.updated",
+ threadId,
+ runId: active.id,
+ occurredAt: now,
+ payload: { ...active, status: "completed", completedAt: now },
+ },
+ ],
+ });
+ yield* orchestrator.resumeQueuedRuns;
+ const after = yield* orchestrator.getThreadProjection(threadId);
+ assert.equal(after.runs.find((run) => run.id === wake.id)?.status, "starting");
+ assert.deepEqual(
+ after.runs.find((run) => run.id === held.id),
+ held,
+ );
+ assert.deepEqual(
+ after.runs.find((run) => run.id === textContinuation.id),
+ textContinuation,
+ );
+ }),
+ );
+
it.effect("edits and removes queued runs", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;