Skip to content

Commit fbc6a08

Browse files
shivamhwpPR Batch Testerclaude
authored
fix(server): Stop stops a thread's subagents again (#23886)
Co-authored-by: PR Batch Tester <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent cccb78c commit fbc6a08

6 files changed

Lines changed: 140 additions & 51 deletions

File tree

‎apps/server/src/mcp/OrchestratorMcpService.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2385,6 +2385,7 @@ const make = Effect.gen(function* () {
23852385
type: "thread.stop",
23862386
commandId,
23872387
threadId: current.childThreadId,
2388+
stopDelegatedTasks: false,
23882389
...(reason === undefined ? {} : { reason }),
23892390
})
23902391
.pipe(

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -661,7 +661,12 @@ const layerBase: Layer.Layer<
661661
commandId: input.commandId,
662662
events: normalized,
663663
});
664-
const sequence = storedEvents.at(-1)?.sequence;
664+
// A Stop that changes nothing can still queue the stop of its delegated tasks.
665+
const sequence =
666+
storedEvents.at(-1)?.sequence ??
667+
(input.effects.length === 0
668+
? undefined
669+
: yield* eventStore.latestSequence({ threadId: input.threadId }));
665670
if (sequence === undefined) {
666671
return yield* Effect.die(
667672
new Error(`Command ${input.commandId} produced no orchestration events.`),

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

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -535,6 +535,22 @@ function pendingThreadTitleGenerationEffect(
535535
};
536536
}
537537

538+
function delegatedTasksStopEffect(command: {
539+
readonly commandId: CommandId;
540+
readonly threadId: ThreadId;
541+
readonly reason?: string | undefined;
542+
}): PendingOrchestrationEffectV2 {
543+
return {
544+
id: `effect:${command.commandId}:delegated-tasks.stop`,
545+
commandId: command.commandId,
546+
threadId: command.threadId,
547+
request: {
548+
type: "delegated-tasks.stop",
549+
...(command.reason === undefined ? {} : { reason: command.reason }),
550+
},
551+
};
552+
}
553+
538554
const WORKSPACE_PREPARATION_INPUT = "Preparing workspace";
539555

540556
function withoutPreparationResult(
@@ -10150,6 +10166,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1015010166
),
1015110167
);
1015210168
if (projection.thread.deletedAt !== null) return undefined;
10169+
// Queued after the interrupt, since a thread's effects run in order.
10170+
const stopDelegatedTasks =
10171+
command.stopDelegatedTasks === false ||
10172+
!projection.subagents.some(
10173+
(task) => task.origin === "app_owned" && task.childThreadId !== null,
10174+
)
10175+
? Effect.void
10176+
: Ref.update(effects, (existing) => [...existing, delegatedTasksStopEffect(command)]);
1015310177
const latestRun = projection.runs.findLast((run) => run.status !== "queued");
1015410178
const target =
1015510179
projection.runs.findLast(
@@ -10189,6 +10213,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1018910213
yield* Ref.update(events, (existing) => [...existing, ...written]);
1019010214
yield* Ref.update(effects, (existing) => [...existing, ...enqueued]);
1019110215
yield* cancelIdleOrphans({ command, events, projection });
10216+
yield* stopDelegatedTasks;
1019210217
return interrupted.value;
1019310218
}
1019410219
yield* Effect.logWarning("thread.stop could not interrupt the running turn", {
@@ -10209,6 +10234,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1020910234
}
1021010235
yield* holdStoppedThread({ command, events, projection, cohortRunIds: [], now });
1021110236
yield* cancelIdleOrphans({ command, events, projection });
10237+
yield* stopDelegatedTasks;
1021210238
return undefined;
1021310239
});
1021410240

@@ -11509,15 +11535,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1150911535
});
1151011536
yield* Ref.update(effects, (existing) => [
1151111537
...existing,
11512-
{
11513-
id: `effect:${command.commandId}:delegated-tasks.stop`,
11514-
commandId: command.commandId,
11515-
threadId: command.threadId,
11516-
request: {
11517-
type: "delegated-tasks.stop",
11518-
...(command.reason === undefined ? {} : { reason: command.reason }),
11519-
},
11520-
} satisfies PendingOrchestrationEffectV2,
11538+
delegatedTasksStopEffect(command),
1152111539
]);
1152211540
}
1152311541
break;
@@ -11787,7 +11805,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1178711805
),
1178811806
);
1178911807

11790-
if (plan.events.length === 0) {
11808+
if (plan.events.length === 0 && plan.effects.length === 0) {
1179111809
// A settle that ended nothing still records its receipt: a replayed Stop
1179211810
// effect then finds it instead of settling work that appeared since.
1179311811
const resultSequence = yield* Effect.gen(function* () {

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1115,6 +1115,7 @@ const make = Effect.gen(function* () {
11151115
type: "thread.stop",
11161116
commandId: CommandId.make(`${input.commandId}:stop:${threadId}`),
11171117
threadId,
1118+
stopDelegatedTasks: false,
11181119
...(input.reason === undefined ? {} : { reason: input.reason }),
11191120
}).pipe(
11201121
Effect.andThen(stopDelegatedTasks({ ...input, threadId })),

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

Lines changed: 99 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -530,65 +530,124 @@ it.effect("Stop still stops the thread when a delegated child cannot be read", (
530530
}).pipe(Effect.provide(layerTest)),
531531
);
532532

533-
it.effect("Stop ends watches, holds queues, and stops the delegated tasks under the thread", () =>
533+
it.effect.each(["run.interrupt", "thread.stop"] as const)(
534+
"%s Stop ends watches, holds queues, and stops the delegated tasks under the thread",
535+
(type) =>
536+
Effect.gen(function* () {
537+
const orchestrator = yield* Orchestrator.OrchestratorV2;
538+
const projections = yield* ProjectionStore.ProjectionStoreV2;
539+
const threads = yield* ThreadManagementService.ThreadManagementService;
540+
const sql = yield* SqlClient.SqlClient;
541+
const parentThreadId = ThreadId.make("thread:stop-parent");
542+
yield* createWatchingThread(parentThreadId, 1);
543+
yield* send(parentThreadId, "first", "start_immediately");
544+
const childThreadId = yield* delegate(parentThreadId, "child task");
545+
assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(childThreadId, 2))));
546+
const grandchildThreadId = yield* delegate(childThreadId, "grandchild task");
547+
yield* send(childThreadId, "child follow-up", "queue_after_active");
548+
549+
const now = yield* DateTime.now;
550+
const firstRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!;
551+
yield* projections.apply({
552+
id: EventId.make("event:stop-parent:first-run-completed"),
553+
type: "run.updated",
554+
threadId: parentThreadId,
555+
runId: firstRun.id,
556+
occurredAt: now,
557+
payload: { ...firstRun, status: "completed", completedAt: now },
558+
});
559+
yield* send(parentThreadId, "second", "start_immediately");
560+
const secondRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs.at(-1)!;
561+
562+
const stopCommandId = CommandId.make("stop-parent");
563+
yield* orchestrator.dispatch(
564+
type === "thread.stop"
565+
? { type, commandId: stopCommandId, threadId: parentThreadId }
566+
: {
567+
type,
568+
commandId: stopCommandId,
569+
threadId: parentThreadId,
570+
runId: secondRun.id,
571+
holdQueue: true,
572+
},
573+
);
574+
575+
assert.deepEqual(yield* threadState(parentThreadId), {
576+
runs: ["completed", "interrupted"],
577+
watched: [],
578+
});
579+
const parent = yield* orchestrator.getThreadProjection(parentThreadId);
580+
assert.equal(parent.subagents[0]?.completionDelivery?.state, "disposed");
581+
const effects = yield* sql<{ readonly effect_type: string }>`
582+
SELECT effect_type FROM orchestration_v2_effect_outbox WHERE command_id = ${stopCommandId}
583+
`;
584+
assert.include(
585+
effects.map((row) => row.effect_type),
586+
"delegated-tasks.stop",
587+
);
588+
589+
yield* threads.stopDelegatedTasks({ threadId: parentThreadId, commandId: stopCommandId });
590+
assert.deepEqual(yield* threadState(childThreadId), {
591+
runs: ["interrupted", "queued:held"],
592+
watched: [],
593+
});
594+
assert.deepEqual((yield* threadState(grandchildThreadId)).runs, ["interrupted"]);
595+
596+
yield* threads.stopDelegatedTasks({ threadId: parentThreadId, commandId: stopCommandId });
597+
assert.deepEqual((yield* threadState(childThreadId)).runs, ["interrupted", "queued:held"]);
598+
// The walk stops each level itself, so the child stops it sends queue no walk of their own.
599+
const walks = yield* sql<{ readonly command_id: string }>`
600+
SELECT command_id FROM orchestration_v2_effect_outbox
601+
WHERE effect_type = 'delegated-tasks.stop'
602+
`;
603+
assert.deepEqual(
604+
walks.map((row) => row.command_id),
605+
[stopCommandId],
606+
);
607+
}).pipe(Effect.provide(layerTest)),
608+
);
609+
610+
it.effect("a repeated Stop that changes nothing still stops the delegated tasks", () =>
534611
Effect.gen(function* () {
535612
const orchestrator = yield* Orchestrator.OrchestratorV2;
536613
const projections = yield* ProjectionStore.ProjectionStoreV2;
537-
const threads = yield* ThreadManagementService.ThreadManagementService;
538614
const sql = yield* SqlClient.SqlClient;
539-
const parentThreadId = ThreadId.make("thread:stop-parent");
615+
const parentThreadId = ThreadId.make("thread:stop-again");
540616
yield* createWatchingThread(parentThreadId, 1);
541617
yield* send(parentThreadId, "first", "start_immediately");
542-
const childThreadId = yield* delegate(parentThreadId, "child task");
543-
assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(childThreadId, 2))));
544-
const grandchildThreadId = yield* delegate(childThreadId, "grandchild task");
545-
yield* send(childThreadId, "child follow-up", "queue_after_active");
546-
618+
yield* delegate(parentThreadId, "stop-again child");
547619
const now = yield* DateTime.now;
548-
const firstRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!;
620+
const run = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!;
549621
yield* projections.apply({
550-
id: EventId.make("event:stop-parent:first-run-completed"),
622+
id: EventId.make("event:stop-again:run-completed"),
551623
type: "run.updated",
552624
threadId: parentThreadId,
553-
runId: firstRun.id,
625+
runId: run.id,
554626
occurredAt: now,
555-
payload: { ...firstRun, status: "completed", completedAt: now },
627+
payload: { ...run, status: "completed", completedAt: now },
556628
});
557-
yield* send(parentThreadId, "second", "start_immediately");
558-
const secondRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs.at(-1)!;
559-
560-
const stopCommandId = CommandId.make("stop-parent");
561629
yield* orchestrator.dispatch({
562-
type: "run.interrupt",
563-
commandId: stopCommandId,
630+
type: "thread.stop",
631+
commandId: CommandId.make("stop-again:first"),
564632
threadId: parentThreadId,
565-
runId: secondRun.id,
566-
holdQueue: true,
567633
});
568634

569-
assert.deepEqual(yield* threadState(parentThreadId), {
570-
runs: ["completed", "interrupted"],
571-
watched: [],
635+
// The first Stop already disposed the delivery and ended the watch, so this one writes no
636+
// events, like Stop on a thread an older server stopped without stopping its children.
637+
const again = yield* orchestrator.dispatch({
638+
type: "thread.stop",
639+
commandId: CommandId.make("stop-again:second"),
640+
threadId: parentThreadId,
572641
});
573-
const parent = yield* orchestrator.getThreadProjection(parentThreadId);
574-
assert.equal(parent.subagents[0]?.completionDelivery?.state, "disposed");
575-
const effects = yield* sql<{ readonly effect_type: string }>`
576-
SELECT effect_type FROM orchestration_v2_effect_outbox WHERE command_id = ${stopCommandId}
642+
assert.lengthOf(again.storedEvents, 0);
643+
const walks = yield* sql<{ readonly command_id: string }>`
644+
SELECT command_id FROM orchestration_v2_effect_outbox
645+
WHERE effect_type = 'delegated-tasks.stop'
577646
`;
578-
assert.include(
579-
effects.map((row) => row.effect_type),
580-
"delegated-tasks.stop",
647+
assert.deepEqual(
648+
walks.map((row) => row.command_id),
649+
["stop-again:first", "stop-again:second"],
581650
);
582-
583-
yield* threads.stopDelegatedTasks({ threadId: parentThreadId, commandId: stopCommandId });
584-
assert.deepEqual(yield* threadState(childThreadId), {
585-
runs: ["interrupted", "queued:held"],
586-
watched: [],
587-
});
588-
assert.deepEqual((yield* threadState(grandchildThreadId)).runs, ["interrupted"]);
589-
590-
yield* threads.stopDelegatedTasks({ threadId: parentThreadId, commandId: stopCommandId });
591-
assert.deepEqual((yield* threadState(childThreadId)).runs, ["interrupted", "queued:held"]);
592651
}).pipe(Effect.provide(layerTest)),
593652
);
594653

‎packages/contracts/src/orchestrationV2.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2577,6 +2577,11 @@ export const OrchestrationV2Command = Schema.Union([
25772577
commandId: CommandId,
25782578
threadId: ThreadId,
25792579
reason: Schema.optional(Schema.String),
2580+
/**
2581+
* False when the caller stops the thread's delegated tasks itself, as the server's tree walks
2582+
* do under their caller's dispatch limit. Otherwise Stop also stops every task under the thread.
2583+
*/
2584+
stopDelegatedTasks: Schema.optional(Schema.Boolean),
25802585
}),
25812586
Schema.Struct({
25822587
type: Schema.Literal("thread.create"),

0 commit comments

Comments
 (0)