Skip to content

Commit 6dabc1e

Browse files
feat(queue): clear a thread's queue, or every queue at once
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent ef21659 commit 6dabc1e

18 files changed

Lines changed: 425 additions & 54 deletions

File tree

‎apps/server/src/auth/RpcAuthorization.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ export const RPC_REQUIRED_SCOPES = {
5555
[ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: AuthOrchestrationReadScope,
5656
[ORCHESTRATION_V2_WS_METHODS.getTurnItem]: AuthOrchestrationReadScope,
5757
[ORCHESTRATION_V2_WS_METHODS.launchThread]: AuthOrchestrationOperateScope,
58+
[ORCHESTRATION_V2_WS_METHODS.clearAllQueues]: AuthOrchestrationOperateScope,
5859
[ORCHESTRATION_V2_WS_METHODS.subscribeArchivedShell]: AuthOrchestrationReadScope,
5960
[ORCHESTRATION_V2_WS_METHODS.subscribeShell]: AuthOrchestrationReadScope,
6061
[ORCHESTRATION_V2_WS_METHODS.subscribeThread]: AuthOrchestrationReadScope,

‎apps/server/src/observability/RpcInstrumentation.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ const RPC_AGGREGATES = {
2626
[ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: "orchestration",
2727
[ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: "orchestrationV2",
2828
[ORCHESTRATION_V2_WS_METHODS.launchThread]: "orchestration",
29+
[ORCHESTRATION_V2_WS_METHODS.clearAllQueues]: "orchestration",
2930
[ORCHESTRATION_V2_WS_METHODS.subscribeArchivedShell]: "orchestration",
3031
[ORCHESTRATION_V2_WS_METHODS.subscribeShell]: "orchestrationV2",
3132
[ORCHESTRATION_V2_WS_METHODS.subscribeThread]: "orchestrationV2",

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 138 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,12 @@ export interface OrchestratorV2DispatchResult {
276276

277277
export interface OrchestratorV2Shape {
278278
readonly resumeQueuedRuns: Effect.Effect<number, OrchestratorV2Error>;
279+
/**
280+
* Threads that may have messages waiting in their queue: every thread whose
281+
* queue stands with nothing running, plus every thread with a run under way.
282+
* The second group is a superset; ask the thread's records to be sure.
283+
*/
284+
readonly queuedThreadCandidates: Effect.Effect<ReadonlyArray<ThreadId>, OrchestratorV2Error>;
279285
/** Startup pass that settles delegated-task results and deliveries runs left behind. */
280286
readonly recoverDelegatedTasks: Effect.Effect<void>;
281287
/** Settles a delegated child whose restart continuation of `sourceRunId` declined or failed. */
@@ -471,6 +477,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId {
471477
case "queued-message.promote-to-steer":
472478
case "queue.resume":
473479
case "queue.hold":
480+
case "queue.clear":
474481
case "queued-run.reorder":
475482
case "queued-run.cancel":
476483
case "queued-run.edit":
@@ -1930,6 +1937,26 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
19301937
),
19311938
);
19321939

1940+
const queuedThreadCandidates = Effect.gen(function* () {
1941+
const standing = yield* projectionStore.getRecoveryThreadIds("queued-runs");
1942+
const shell = yield* projectionStore.getShellSnapshot();
1943+
const working = shell.threads
1944+
.filter(
1945+
(thread) => thread.activeRunId !== null || (thread.activityRunStatus ?? null) !== null,
1946+
)
1947+
.map((thread) => thread.id);
1948+
return [...new Set([...standing, ...working])];
1949+
}).pipe(
1950+
Effect.mapError(
1951+
(cause) =>
1952+
new OrchestratorDispatchError({
1953+
commandId: CommandId.make("command:system:queued-thread-candidates"),
1954+
commandType: "queue.clear",
1955+
cause,
1956+
}),
1957+
),
1958+
);
1959+
19331960
const dispatchDelegatedTaskCompletionDeliveryResolution = (
19341961
command: Extract<
19351962
OrchestrationV2Command,
@@ -7791,6 +7818,111 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
77917818
);
77927819
});
77937820

7821+
/** Marks one queued run, its attempt and its root node cancelled. */
7822+
const cancelQueuedRun = (input: {
7823+
readonly command: Extract<
7824+
OrchestrationV2Command,
7825+
{ readonly type: "queued-run.cancel" | "queue.clear" }
7826+
>;
7827+
readonly events: Ref.Ref<Array<OrchestrationV2DomainEvent>>;
7828+
readonly projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "attempts">;
7829+
readonly queuedRun: OrchestrationV2ThreadProjection["runs"][number];
7830+
readonly now: DateTime.Utc;
7831+
}) =>
7832+
Effect.gen(function* () {
7833+
const queuedRootNode =
7834+
input.queuedRun.rootNodeId === null
7835+
? undefined
7836+
: input.projection.nodes.find((candidate) => candidate.id === input.queuedRun.rootNodeId);
7837+
const queuedAttempt =
7838+
input.queuedRun.activeAttemptId === null
7839+
? undefined
7840+
: input.projection.attempts.find(
7841+
(candidate) => candidate.id === input.queuedRun.activeAttemptId,
7842+
);
7843+
7844+
const emitEvent = emit(input.events, input.command);
7845+
yield* emitEvent({
7846+
type: "run.updated",
7847+
threadId: input.command.threadId,
7848+
runId: input.queuedRun.id,
7849+
...(input.queuedRun.rootNodeId === null ? {} : { nodeId: input.queuedRun.rootNodeId }),
7850+
providerInstanceId: input.queuedRun.providerInstanceId,
7851+
occurredAt: input.now,
7852+
payload: {
7853+
...input.queuedRun,
7854+
status: "cancelled",
7855+
queuePosition: null,
7856+
completedAt: input.now,
7857+
},
7858+
});
7859+
if (queuedAttempt !== undefined && queuedRootNode !== undefined) {
7860+
yield* emitEvent({
7861+
type: "run-attempt.updated",
7862+
threadId: input.command.threadId,
7863+
runId: input.queuedRun.id,
7864+
nodeId: queuedRootNode.id,
7865+
providerInstanceId: input.queuedRun.providerInstanceId,
7866+
occurredAt: input.now,
7867+
payload: {
7868+
...queuedAttempt,
7869+
status: "cancelled",
7870+
completedAt: input.now,
7871+
},
7872+
});
7873+
}
7874+
if (queuedRootNode !== undefined) {
7875+
yield* emitEvent({
7876+
type: "node.updated",
7877+
threadId: input.command.threadId,
7878+
runId: input.queuedRun.id,
7879+
nodeId: queuedRootNode.id,
7880+
providerInstanceId: input.queuedRun.providerInstanceId,
7881+
occurredAt: input.now,
7882+
payload: {
7883+
...queuedRootNode,
7884+
status: "cancelled",
7885+
completedAt: input.now,
7886+
},
7887+
});
7888+
}
7889+
});
7890+
7891+
const dispatchQueueClear = (
7892+
command: Extract<OrchestrationV2Command, { readonly type: "queue.clear" }>,
7893+
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
7894+
) =>
7895+
Effect.gen(function* () {
7896+
const projection = yield* projectionStore
7897+
.getThreadRecords(command.threadId, ["runs", "messages", "nodes", "attempts"], {
7898+
messageRoles: ["user"],
7899+
})
7900+
.pipe(
7901+
Effect.mapError(() => new OrchestratorProjectionError({ threadId: command.threadId })),
7902+
);
7903+
const delegatedMessageIds = new Set(
7904+
projection.messages
7905+
.filter((message) => message.delegatedCompletion !== undefined)
7906+
.map((message) => message.id),
7907+
);
7908+
const clearable = projection.runs.filter(
7909+
(run) =>
7910+
run.status === "queued" &&
7911+
(run.userMessageId === null || !delegatedMessageIds.has(run.userMessageId)),
7912+
);
7913+
if (clearable.length === 0) {
7914+
return yield* new OrchestratorDispatchError({
7915+
commandId: command.commandId,
7916+
commandType: command.type,
7917+
cause: "Nothing is queued in this thread.",
7918+
});
7919+
}
7920+
const now = yield* DateTime.now;
7921+
for (const queuedRun of clearable) {
7922+
yield* cancelQueuedRun({ command, events, projection, queuedRun, now });
7923+
}
7924+
});
7925+
77947926
const dispatchQueuedRunCancel = (
77957927
command: Extract<OrchestrationV2Command, { readonly type: "queued-run.cancel" }>,
77967928
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
@@ -7828,61 +7960,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
78287960
});
78297961
return;
78307962
}
7831-
const queuedRootNode =
7832-
queuedRun.rootNodeId === null
7833-
? undefined
7834-
: projection.nodes.find((candidate) => candidate.id === queuedRun.rootNodeId);
7835-
const queuedAttempt =
7836-
queuedRun.activeAttemptId === null
7837-
? undefined
7838-
: projection.attempts.find((candidate) => candidate.id === queuedRun.activeAttemptId);
7839-
78407963
const now = yield* DateTime.now;
7841-
const emitEvent = emit(events, command);
7842-
yield* emitEvent({
7843-
type: "run.updated",
7844-
threadId: command.threadId,
7845-
runId: queuedRun.id,
7846-
...(queuedRun.rootNodeId === null ? {} : { nodeId: queuedRun.rootNodeId }),
7847-
providerInstanceId: queuedRun.providerInstanceId,
7848-
occurredAt: now,
7849-
payload: {
7850-
...queuedRun,
7851-
status: "cancelled",
7852-
queuePosition: null,
7853-
completedAt: now,
7854-
},
7855-
});
7856-
if (queuedAttempt !== undefined && queuedRootNode !== undefined) {
7857-
yield* emitEvent({
7858-
type: "run-attempt.updated",
7859-
threadId: command.threadId,
7860-
runId: queuedRun.id,
7861-
nodeId: queuedRootNode.id,
7862-
providerInstanceId: queuedRun.providerInstanceId,
7863-
occurredAt: now,
7864-
payload: {
7865-
...queuedAttempt,
7866-
status: "cancelled",
7867-
completedAt: now,
7868-
},
7869-
});
7870-
}
7871-
if (queuedRootNode !== undefined) {
7872-
yield* emitEvent({
7873-
type: "node.updated",
7874-
threadId: command.threadId,
7875-
runId: queuedRun.id,
7876-
nodeId: queuedRootNode.id,
7877-
providerInstanceId: queuedRun.providerInstanceId,
7878-
occurredAt: now,
7879-
payload: {
7880-
...queuedRootNode,
7881-
status: "cancelled",
7882-
completedAt: now,
7883-
},
7884-
});
7885-
}
7964+
yield* cancelQueuedRun({ command, events, projection, queuedRun, now });
78867965
});
78877966

78887967
const dispatchQueuedRunEdit = (
@@ -10848,6 +10927,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1084810927
case "queued-run.reorder":
1084910928
yield* dispatchQueuedRunReorder(command, events);
1085010929
break;
10930+
case "queue.clear":
10931+
yield* dispatchQueueClear(command, events);
10932+
break;
1085110933
case "queued-run.cancel":
1085210934
yield* dispatchQueuedRunCancel(command, events);
1085310935
break;
@@ -11338,6 +11420,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1133811420

1133911421
return OrchestratorV2.of({
1134011422
resumeQueuedRuns,
11423+
queuedThreadCandidates,
1134111424
recoverDelegatedTasks,
1134211425
recoverDelegatedTask,
1134311426
delegatedTaskResultPending,
@@ -11478,6 +11561,7 @@ export const layer: Layer.Layer<
1147811561
const layerUnavailable: Layer.Layer<OrchestratorV2> = Layer.succeed(
1147911562
OrchestratorV2,
1148011563
OrchestratorV2.of({
11564+
queuedThreadCandidates: Effect.succeed([]),
1148111565
resumeQueuedRuns: Effect.fail(
1148211566
new OrchestratorDispatchError({
1148311567
commandId: CommandId.make("command:system:resume-queued-runs"),

‎apps/server/src/orchestration-v2/ThreadManagementService.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,14 @@ export interface ThreadManagementServiceShape {
293293
readonly dispatch: (
294294
command: OrchestrationV2ServerCommand,
295295
) => Effect.Effect<Orchestrator.OrchestratorV2DispatchResult, Orchestrator.OrchestratorV2Error>;
296+
/**
297+
* Cancels the messages waiting in every thread's queue and reports how many
298+
* threads had some. Runs under way are not touched. `commandId` makes a
299+
* retry safe: each thread's clear derives its own id from it.
300+
*/
301+
readonly clearAllQueues: (input: {
302+
readonly commandId: CommandId;
303+
}) => Effect.Effect<{ readonly threads: number }, Orchestrator.OrchestratorV2Error>;
296304
readonly getThreadHistoryPage: Orchestrator.OrchestratorV2["Service"]["getThreadHistoryPage"];
297305
readonly getTimelinePage: Orchestrator.OrchestratorV2["Service"]["getTimelinePage"];
298306
readonly getMessageCount: Orchestrator.OrchestratorV2["Service"]["getMessageCount"];
@@ -595,6 +603,28 @@ const make = Effect.gen(function* () {
595603
Effect.flatMap((routed) => orchestrator.dispatch(routed)),
596604
);
597605

606+
const clearAllQueues: ThreadManagementServiceShape["clearAllQueues"] = (input) =>
607+
Effect.gen(function* () {
608+
const candidates = yield* orchestrator.queuedThreadCandidates;
609+
let threads = 0;
610+
for (const threadId of candidates) {
611+
// A candidate with nothing queued rejects the clear; that is not a failure here.
612+
const cleared = yield* orchestrator
613+
.dispatch({
614+
type: "queue.clear",
615+
commandId: CommandId.make(`${input.commandId}:clear:${threadId}`),
616+
threadId,
617+
})
618+
.pipe(
619+
Effect.as(true),
620+
Effect.catch(() => Effect.succeed(false)),
621+
);
622+
if (cleared) threads += 1;
623+
}
624+
yield* Effect.logInfo("Thread queues cleared", { threads });
625+
return { threads };
626+
});
627+
598628
const getProjectThread: ThreadManagementServiceShape["getProjectThread"] = (input) =>
599629
getThreadProjection(input.threadId).pipe(
600630
Effect.mapError(
@@ -995,6 +1025,7 @@ const make = Effect.gen(function* () {
9951025

9961026
return ThreadManagementService.of({
9971027
ensureLegacyTranscript,
1028+
clearAllQueues,
9981029
searchThreadStream: (input) =>
9991030
Stream.unwrap(
10001031
ensureProjectionTranscript(input.threadId).pipe(

‎apps/server/src/orchestration-v2/runtimeLayer.test.ts‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3596,6 +3596,79 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
35963596
}),
35973597
);
35983598

3599+
it.effect("clears a queue without touching the run under way", () =>
3600+
Effect.gen(function* () {
3601+
const orchestrator = yield* Orchestrator.OrchestratorV2;
3602+
const threadId = ThreadId.make("runtime-layer-clear-queue-thread");
3603+
3604+
yield* orchestrator.dispatch({
3605+
type: "thread.create",
3606+
createdBy: "user",
3607+
creationSource: "web",
3608+
commandId: CommandId.make("runtime-layer-clear-queue-create"),
3609+
threadId,
3610+
projectId: ProjectId.make("runtime-layer-clear-queue-project"),
3611+
title: "Clear the queue",
3612+
modelSelection,
3613+
runtimeMode: "full-access",
3614+
interactionMode: "default",
3615+
branch: null,
3616+
worktreePath: "/tmp/runtime-layer-clear-queue",
3617+
});
3618+
const empty = yield* Effect.exit(
3619+
orchestrator.dispatch({
3620+
type: "queue.clear",
3621+
commandId: CommandId.make("runtime-layer-clear-queue-empty"),
3622+
threadId,
3623+
}),
3624+
);
3625+
assert.equal(empty._tag, "Failure");
3626+
3627+
yield* orchestrator.dispatch({
3628+
type: "message.dispatch",
3629+
createdBy: "user",
3630+
creationSource: "web",
3631+
commandId: CommandId.make("runtime-layer-clear-queue-active-message"),
3632+
threadId,
3633+
messageId: MessageId.make("runtime-layer-clear-queue-active-message"),
3634+
text: "Keep the provider occupied.",
3635+
attachments: [],
3636+
modelSelection,
3637+
dispatchMode: { type: "start_immediately" },
3638+
});
3639+
for (const name of ["first", "second"]) {
3640+
yield* orchestrator.dispatch({
3641+
type: "message.dispatch",
3642+
createdBy: "user",
3643+
creationSource: "web",
3644+
commandId: CommandId.make(`runtime-layer-clear-queue-${name}-message`),
3645+
threadId,
3646+
messageId: MessageId.make(`runtime-layer-clear-queue-${name}-message`),
3647+
text: `Queued ${name}.`,
3648+
attachments: [],
3649+
modelSelection,
3650+
dispatchMode: { type: "queue_after_active" },
3651+
});
3652+
}
3653+
const before = yield* orchestrator.getThreadProjection(threadId);
3654+
const activeRun = before.runs.find((run) => run.status === "starting");
3655+
assert.isDefined(activeRun);
3656+
assert.equal(before.runs.filter((run) => run.status === "queued").length, 2);
3657+
// A thread with a run under way is a candidate for the clear-all pass.
3658+
assert.include(yield* orchestrator.queuedThreadCandidates, threadId);
3659+
3660+
yield* orchestrator.dispatch({
3661+
type: "queue.clear",
3662+
commandId: CommandId.make("runtime-layer-clear-queue-clear"),
3663+
threadId,
3664+
});
3665+
const cleared = yield* orchestrator.getThreadProjection(threadId);
3666+
assert.equal(cleared.runs.filter((run) => run.status === "queued").length, 0);
3667+
assert.equal(cleared.runs.filter((run) => run.status === "cancelled").length, 2);
3668+
assert.equal(cleared.runs.find((run) => run.id === activeRun.id)?.status, activeRun.status);
3669+
}),
3670+
);
3671+
35993672
it.effect("holds a queue without touching the run under way, and resumes it", () =>
36003673
Effect.gen(function* () {
36013674
const orchestrator = yield* Orchestrator.OrchestratorV2;

0 commit comments

Comments
 (0)