Skip to content
TypeScript

fix(server): delegated completions preserve finished parent runs (#20025)

Scott Nortemane27de4ead0d5
diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
index c188d60d4b7..6de4e537b1f 100644
--- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
+++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
@@ -1,8 +1,9 @@
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as NodeServices from "@effect/platform-node/NodeServices";
-import { assert, it } from "@effect/vitest";
+import { assert, it, vi } from "@effect/vitest";
import {
+ CheckpointId,
CommandId,
EventId,
MessageId,
@@ -1070,6 +1071,146 @@ const seedRestartCancelledChild = (input: {
it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))(
"subagent follow-ups",
(it) => {
+ it.effect("keeps a checkpoint completion committed between finalize's read and write", () =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const sink = yield* EventSink.EventSinkV2;
+ const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
+ const now = yield* DateTime.now;
+ const threadId = ThreadId.make("thread:completion-capture-race");
+ const projectId = ProjectId.make("project:completion-capture-race");
+ const runId = RunId.make("run:completion-capture-race");
+ const rootNodeId = NodeId.make("node:completion-capture-race");
+ const checkpointId = CheckpointId.make("checkpoint:completion-capture-race");
+ yield* seedParentWithTerminalTask({
+ threadId,
+ projectId,
+ runId,
+ rootNodeId,
+ taskId: NodeId.make("node:completion-capture-seed"),
+ deliveryState: "acknowledged",
+ now,
+ });
+ const parent = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
+ const waiting = { ...parent, status: "waiting" as const };
+ yield* sink.write({
+ events: [
+ {
+ id: EventId.make("event:completion-capture-waiting"),
+ type: "run.updated",
+ threadId,
+ runId,
+ occurredAt: now,
+ payload: waiting,
+ },
+ ],
+ });
+ const child = yield* seedRestartCancelledChild({
+ parentThreadId: threadId,
+ projectId,
+ parentRunId: runId,
+ rootNodeId,
+ name: "completion-capture-child",
+ completionWake: "always",
+ continuationPending: false,
+ runStatus: "completed",
+ now,
+ });
+ const write = sink.writeWithEffects;
+ let captured = false;
+ const committedParentRuns: Array<OrchestrationV2Run> = [];
+ yield* Effect.acquireUseRelease(
+ Effect.sync(() =>
+ vi.spyOn(sink, "writeWithEffects").mockImplementation((input) =>
+ Effect.gen(function* () {
+ if (
+ !captured &&
+ input.events.some(
+ (event) =>
+ event.type === "run.updated" &&
+ event.payload.id === runId &&
+ event.payload.delegatedCompletion?.delivery != null,
+ )
+ ) {
+ captured = true;
+ // Commit capture after finalize planned its stale waiting snapshot.
+ const { delegatedCompletion: _cohort, ...captureRun } = waiting;
+ yield* sink.commitCommand({
+ commandId: CommandId.make("command:completion-capture-race"),
+ threadId,
+ commandType: "checkpoint.capture",
+ acceptedAt: now,
+ effects: [],
+ events: [
+ {
+ id: EventId.make("event:completion-capture-completed"),
+ type: "run.updated",
+ threadId,
+ runId,
+ occurredAt: now,
+ payload: {
+ ...captureRun,
+ status: "completed",
+ completedAt: now,
+ checkpointId,
+ },
+ },
+ ],
+ });
+ }
+ const stored = yield* write(input);
+ for (const { event } of stored) {
+ if (event.type === "run.updated" && event.payload.id === runId) {
+ committedParentRuns.push(event.payload);
+ }
+ }
+ return stored;
+ }),
+ ),
+ ),
+ () => orchestrator.recoverDelegatedTasks,
+ (spy) => Effect.sync(() => spy.mockRestore()),
+ );
+ assert.isTrue(captured);
+ assert.equal(committedParentRuns.length, 1);
+ const committedParentRun = committedParentRuns[0];
+ assert.equal(committedParentRun?.status, "completed");
+ assert.deepEqual(committedParentRun?.completedAt, now);
+ assert.equal(committedParentRun?.checkpointId, checkpointId);
+ assert.deepEqual(committedParentRun?.delegatedCompletion?.delivery?.taskIds, [
+ child.taskId,
+ ]);
+ const finished = yield* orchestrator.getThreadProjection(threadId);
+ const completed = finished.runs.find((run) => run.id === runId)!;
+ assert.equal(completed.status, "completed");
+ assert.deepEqual(completed.completedAt, now);
+ assert.equal(completed.checkpointId, checkpointId);
+ assert.deepEqual(completed.delegatedCompletion?.delivery?.taskIds, [child.taskId]);
+ const wake = yield* requests.take;
+ assert.equal(wake.delegatedCompletion?.parentRunId, runId);
+ const delivery = completed.delegatedCompletion!.delivery!;
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ createdBy: "agent",
+ creationSource: "server",
+ commandId: CommandId.make("command:completion-capture-delivery"),
+ threadId,
+ messageId: delivery.messageId,
+ text: "Child finished",
+ attachments: [],
+ delegatedCompletion: {
+ parentRunId: runId,
+ generation: delivery.generation,
+ taskIds: delivery.taskIds,
+ },
+ dispatchMode: { type: "queue_after_active" },
+ });
+ const delivered = yield* orchestrator.getThreadProjection(threadId);
+ const deliveryRun = delivered.runs.find((run) => run.userMessageId === delivery.messageId);
+ assert.isDefined(deliveryRun);
+ assert.notEqual(deliveryRun?.status, "queued");
+ }),
+ );
it.effect("pauses queued follow-up cards and resumes them", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
diff --git a/apps/server/src/orchestration-v2/EventSink.ts b/apps/server/src/orchestration-v2/EventSink.ts
index 6294638a9b0..d2bd8a7ac03 100644
--- a/apps/server/src/orchestration-v2/EventSink.ts
+++ b/apps/server/src/orchestration-v2/EventSink.ts
@@ -77,6 +77,11 @@ export interface EventSinkV2Shape {
readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
}) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
readonly writeWithEffects: (input: {
+ /**
+ * Rebuilds each run.updated from the stored row with only its delegatedCompletion replaced.
+ * The batch must not also change that run's lifecycle.
+ */
+ readonly updateDelegatedCompletionOnly?: boolean;
readonly unlessNativeThreadOwned?: Pick<
OrchestrationV2ProviderThread,
"driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef"
@@ -395,10 +400,34 @@ const layerBase: Layer.Layer<
`;
if (owners.length > 0) return [];
}
+ // Checkpoint capture can finish after a cohort writer reads its parent run.
+ // Merge in this transaction so the event log and projection keep that completion.
+ const events = input.updateDelegatedCompletionOnly
+ ? yield* Effect.forEach(input.events, (event) =>
+ Effect.gen(function* () {
+ if (event.type !== "run.updated") return event;
+ const { runs } = yield* projectionStore.getThreadRecords(
+ event.threadId,
+ ["runs"],
+ { runIds: [event.payload.id] },
+ );
+ const current = runs[0];
+ return current === undefined
+ ? event
+ : {
+ ...event,
+ payload: {
+ ...current,
+ delegatedCompletion: event.payload.delegatedCompletion,
+ },
+ };
+ }),
+ )
+ : input.events;
const normalized = yield* normalizeEvents(
input.guardPendingUserInputCancellations === true
- ? yield* guardUserInputCancellations(input.events)
- : input.events,
+ ? yield* guardUserInputCancellations(events)
+ : events,
);
const committed = yield* eventStore.append({
...(input.commandId === undefined ? {} : { commandId: input.commandId }),
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index dbe9f9b9cd5..10fd37dc501 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -1047,11 +1047,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
Effect.fnUntraced(function* (
events: ReadonlyArray<Omit<OrchestrationV2DomainEvent, "id">>,
effects: ReadonlyArray<PendingOrchestrationEffectV2> = [],
+ options: { readonly updateDelegatedCompletionOnly?: boolean } = {},
) {
const withIds = yield* Effect.forEach(events, (event) =>
makeSystemEvent(event as Omit<OrchestrationV2DomainEvent, "id">),
);
- yield* eventSink.writeWithEffects({ events: withIds, effects });
+ yield* eventSink.writeWithEffects({ events: withIds, effects, ...options });
});
const completionDeliveryRun = (
@@ -10551,7 +10552,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
consumedAt: now,
};
- yield* writeSystemEvents([
+ const completionEvents: ReadonlyArray<Omit<OrchestrationV2DomainEvent, "id">> = [
{
type: "subagent.updated",
threadId: parentThreadId,
@@ -10652,7 +10653,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
occurredAt: now,
payload: resultTransfer,
},
- ]);
+ ];
+ yield* writeSystemEvents(completionEvents, [], { updateDelegatedCompletionOnly: true });
if (completionPlan.offer && completionPlan.parentRun !== undefined) {
yield* offerDelegatedCompletionDelivery(parentThreadId, completionPlan.parentRun.id);