Skip to content
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ const cancelBackgroundOnlyTask = (
(event) =>
event.type === "run.updated" &&
event.payload.id === child.turn.runId &&
event.payload.status === "waiting",
event.payload.status === "completed",
);
const nativeSubagentEvents = [
{
Expand Down Expand Up @@ -560,7 +560,8 @@ const cancelBackgroundOnlyTask = (
}
const before = yield* service.taskStatus(scope, task.id);
assert.equal(before.status, "running");
assert.equal(before.workState, turnSettled ? "waiting_for_children" : "working");
// The child's run completes when its turn ends, before its checkpoint capture runs.
assert.equal(before.workState, cancelAt === "turn" ? "working" : "waiting_for_children");

const parentTask = Effect.map(orchestrator.getThreadProjection(parentThreadId), (parent) =>
parent.subagents.find((entry) => entry.id === task.id),
Expand Down Expand Up @@ -592,7 +593,8 @@ const cancelBackgroundOnlyTask = (
event.payload.type === "run_interrupt_request",
),
);
assert.equal((yield* parentTask)?.status, "running");
// The child's turn already ended, so the cancel settles its finished run in this commit.
assert.equal((yield* parentTask)?.status, "interrupted");
return { scope, taskId: task.id, settled: undefined };
}
if (cancelAt === "refused") {
Expand Down
12 changes: 5 additions & 7 deletions apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5515,7 +5515,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
);
const completed = yield* orchestrator.streamDomainEvents.pipe(
Stream.filter(
(event) => event.type === "run.updated" && event.payload.status === "waiting",
(event) => event.type === "run.updated" && event.payload.status === "completed",
),
Stream.runHead,
Effect.forkChild({ startImmediately: true }),
Expand Down Expand Up @@ -7342,9 +7342,9 @@ describe("CodexAdapterV2 post-settle continuation", () => {
createdBy: "user",
creationSource: "web",
});
const waiting = yield* orchestrator.streamDomainEvents.pipe(
const completed = yield* orchestrator.streamDomainEvents.pipe(
Stream.filter(
(event) => event.type === "run.updated" && event.payload.status === "waiting",
(event) => event.type === "run.updated" && event.payload.status === "completed",
),
Stream.runHead,
Effect.forkChild({ startImmediately: true }),
Expand All @@ -7362,7 +7362,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
});
yield* worker.drain();
assert.isNull((yield* Ref.get(replayDriver.state)).failure);
yield* Fiber.join(waiting);
yield* Fiber.join(completed);
yield* worker.drain();
const projection = yield* orchestrator.getThreadProjection(threadId);
const run = projection.runs.at(-1)!;
Expand Down Expand Up @@ -7465,9 +7465,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
});
const settled = yield* orchestrator.streamDomainEvents.pipe(
Stream.filter(
(event) =>
event.type === "run.updated" &&
(event.payload.status === "waiting" || event.payload.status === "completed"),
(event) => event.type === "run.updated" && event.payload.status === "completed",
),
Stream.runHead,
Effect.forkChild({ startImmediately: true }),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,7 @@ const stopEarlierBackgroundWork = ({
(event) =>
event.type === "run.updated" &&
event.payload.id === first.runId &&
event.payload.status === "waiting",
event.payload.status === "completed",
);
yield* Queue.offer(events, {
type: "provider_turn.updated",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,10 +103,10 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => {
userMessageId: MessageId.make("message:checkpoint-capture-user"),
rootNodeId,
activeAttemptId: null,
status: "waiting",
status: "completed",
requestedAt: now,
startedAt: now,
completedAt: null,
completedAt: now,
checkpointId: null,
contextHandoffId: null,
delegatedCompletion: staleDelegatedCompletion,
Expand All @@ -118,15 +118,15 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => {
parentNodeId: null,
rootNodeId,
kind: "root_turn" as const,
status: "waiting" as const,
status: "completed" as const,
countsForRun: true,
providerThreadId,
providerTurnId: null,
nativeItemRef: null,
runtimeRequestId: null,
checkpointScopeId: scopeId,
startedAt: now,
completedAt: null,
completedAt: now,
};
const scope = {
id: scopeId,
Expand Down Expand Up @@ -351,7 +351,10 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => {
if (runUpdated?.type !== "run.updated") {
return;
}
// The run completed when its provider turn ended; capture only attaches the checkpoint.
assert.equal(runUpdated.payload.status, "completed");
assert.deepEqual(runUpdated.payload.completedAt, now);
assert.isFalse(events.some((event) => event.type === "node.updated"));
const capturedEvent = events.find((event) => event.type === "checkpoint.captured");
assert.equal(
runUpdated.payload.checkpointId,
Expand Down
35 changes: 18 additions & 17 deletions apps/server/src/orchestration-v2/CheckpointCaptureService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,15 +76,12 @@ export const layer: Layer.Layer<
const context = yield* projections.getCheckpointCaptureContext(input.threadId, input);
const { run, rootNode, scope, providerThread, preservedCheckpointOrdinals, sideChat } =
context;
// Stopped runs remain terminal; their checkpoint is the next message's rollback point.
const stopped = run?.status === "interrupted" || run?.status === "cancelled";
// Runs settle before capture; `waiting` is a run persisted before captures ran after settling.
const settled =
run?.status === "completed" || run?.status === "interrupted" || run?.status === "cancelled";

// A checkpoint on a settled run proves this at-least-once effect already committed.
if (
run !== undefined &&
run.checkpointId !== null &&
(run.status === "completed" || stopped)
) {
if (run !== undefined && run.checkpointId !== null && settled) {
return;
}
// Rollback uses the same lane and can precede a capture retry; preserve the restored workspace and discarded run.
Expand All @@ -94,7 +91,7 @@ export const layer: Layer.Layer<

if (
run === undefined ||
(run.status !== "waiting" && !stopped) ||
(run.status !== "waiting" && !settled) ||
rootNode === undefined ||
scope === undefined ||
rootNode.checkpointScopeId !== scope.id ||
Expand All @@ -104,7 +101,7 @@ export const layer: Layer.Layer<
threadId: input.threadId,
runId: input.runId,
scopeId: input.scopeId,
cause: "The persisted checkpoint capture target is incomplete or no longer waiting.",
cause: "The persisted checkpoint capture target is incomplete or was discarded.",
});
}

Expand Down Expand Up @@ -254,9 +251,13 @@ export const layer: Layer.Layer<
if (currentRun === undefined || currentRun.activeAttemptId !== run.activeAttemptId) {
return;
}
const stoppedNow =
currentRun.status === "interrupted" || currentRun.status === "cancelled";
if (currentRun.status !== "waiting" && !stoppedNow) {
const legacyWaiting = currentRun.status === "waiting";
if (
!legacyWaiting &&
currentRun.status !== "completed" &&
currentRun.status !== "interrupted" &&
currentRun.status !== "cancelled"
) {
return;
}
// Omit delegatedCompletion to preserve cohort writes made after capture loaded the run.
Expand Down Expand Up @@ -336,16 +337,16 @@ export const layer: Layer.Layer<
nodeId: rootNode.id,
providerInstanceId: run.providerInstanceId,
occurredAt: capturedAt,
payload: stoppedNow
? { ...runWithoutDelegatedCompletion, checkpointId: checkpoint.id }
: {
payload: legacyWaiting
? {
...runWithoutDelegatedCompletion,
status: "completed",
completedAt: capturedAt,
checkpointId: checkpoint.id,
},
}
: { ...runWithoutDelegatedCompletion, checkpointId: checkpoint.id },
},
...(stoppedNow
...(!legacyWaiting
? []
: [
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ it.effect.each(deliveries)(
(event) =>
event.type === "run.updated" &&
event.payload.id === parent.id &&
event.payload.status === "waiting",
event.payload.status === "completed",
);
yield* Queue.offer(sdkMessages, toolResult("build", false));
for (const id of statusIds)
Expand All @@ -437,7 +437,7 @@ it.effect.each(deliveries)(
(event) =>
event.type === "run.updated" &&
event.payload.id === queued.id &&
event.payload.status === "waiting",
event.payload.status === "completed",
);
yield* Queue.offer(sdkMessages, result("notice-completed", false));
yield* Fiber.join(noticeFinished);
Expand Down Expand Up @@ -926,7 +926,7 @@ it.effect("offers a continuation for a later wake after a queued continuation is
});
yield* worker.drain();
yield* Fiber.join(running);
const waiting = yield* runUpdated(id, "waiting");
const waiting = yield* runUpdated(id, "completed");
yield* Queue.offer(sdkMessages, backgroundTaskStarted(taskId));
yield* Queue.offer(sdkMessages, result(`result-${id}`, false));
yield* Fiber.join(waiting);
Expand Down Expand Up @@ -1006,7 +1006,7 @@ it.effect("offers a continuation for a later wake after a queued continuation is
(event) =>
event.type === "run.updated" &&
event.payload.id === secondContinuation.id &&
event.payload.status === "waiting",
event.payload.status === "completed",
);
yield* offerAndWait(result("wake-2-result", false));
yield* Fiber.join(secondWaiting);
Expand Down Expand Up @@ -1108,7 +1108,7 @@ it.effect.each([
Stream.runDrain,
Effect.forkScoped,
);
const settled = (runId: RunId, status: "waiting") =>
const settled = (runId: RunId, status: "completed") =>
watch(
(event) =>
event.type === "run.updated" &&
Expand Down Expand Up @@ -1207,7 +1207,7 @@ it.effect.each([
);

if (outcome === "Claude cancels it twice") {
const ended = yield* settled(parent.id, "waiting");
const ended = yield* settled(parent.id, "completed");
const nextRunning = yield* watch(
(event) =>
event.type === "provider-turn.updated" &&
Expand Down Expand Up @@ -1249,7 +1249,7 @@ it.effect.each([
});
yield* worker.drain();
assert.equal(offers[3]?.priority, "next");
const beforeEnded = yield* settled(before.id, "waiting");
const beforeEnded = yield* settled(before.id, "completed");
const steerStarting = yield* watch(
(event) =>
event.type === "run.updated" &&
Expand Down Expand Up @@ -1513,9 +1513,7 @@ const exitWhileIdle = (options: {
yield* Fiber.join(awaitedRoster);
}
const settled = yield* watch(
(event) =>
event.type === "run.updated" &&
(event.payload.status === "waiting" || event.payload.status === "completed"),
(event) => event.type === "run.updated" && event.payload.status === "completed",
);
yield* Queue.offer(firstProcess, result("waiting-on-sleep", false));
yield* Fiber.join(settled);
Expand Down
69 changes: 67 additions & 2 deletions apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1280,6 +1280,15 @@ function queuedRunCancellationEvents(
return events;
}

function latestStartedRun(runs: ReadonlyArray<OrchestrationV2Run>): OrchestrationV2Run | undefined {
return runs
.filter((run) => run.status !== "queued")
.reduce<OrchestrationV2Run | undefined>(
(latest, run) => (latest === undefined || run.ordinal > latest.ordinal ? run : latest),
undefined,
);
}

function latestStableRun(
projection: Pick<OrchestrationV2ThreadProjection, "runs">,
): OrchestrationV2Run | null {
Expand Down Expand Up @@ -1873,9 +1882,25 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
visibleTurnItems: [],
updatedAt: records.thread.updatedAt,
})),
Effect.flatMap(holdRunAwaitingCapture),
Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })),
);

// Commands decide as if the latest run were still `waiting` until its turn-end capture commits:
// the capture keeps the thread's effect lane, and steers and queued turns must line up behind it.
const holdRunAwaitingCapture = Effect.fn("Orchestrator.holdRunAwaitingCapture")(function* (
projection: OrchestrationV2ThreadProjection,
) {
const latest = latestStartedRun(projection.runs);
if (latest === undefined || !(yield* awaitsCheckpointCapture(latest))) return projection;
return {
...projection,
runs: projection.runs.map((run) =>
run.id === latest.id ? { ...run, status: "waiting" as const, completedAt: null } : run,
),
};
});

// Command reads omit settled tasks, but a completion notice counts its whole cohort.
const notificationTasks = (
threadId: ThreadId,
Expand Down Expand Up @@ -3511,6 +3536,28 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio

// A steer still pending after its run ended was never read: the provider marks one it read
// completed, and one Stop dropped cancelled. It runs next, in its place among waiting messages.
// A run completes before its turn-end checkpoint capture. Steers and queued turns advance when
// the capture commits and repeats the update, after the deliveries ahead of it on the lane.
const awaitsCheckpointCapture = (run: OrchestrationV2Run) =>
run.status !== "completed" || run.checkpointId !== null
? Effect.succeed(false)
: effectOutbox.get(`effect:checkpoint.capture:${run.id}`).pipe(
Effect.map(
Option.exists((effect) => effect.status === "pending" || effect.status === "running"),
),
Effect.orElseSucceed(() => false),
);

const awaitLatestRunCapture = Effect.fn("Orchestrator.awaitLatestRunCapture")(
function* (threadId: ThreadId) {
const { runs } = yield* projectionStore.getThreadRecords(threadId, ["runs"]);
const latest = latestStartedRun(runs);
if (latest === undefined || !(yield* awaitsCheckpointCapture(latest))) return;
yield* effectOutbox.awaitSettled(`effect:checkpoint.capture:${latest.id}`);
},
(effect) => Effect.ignore(effect),
);

const requeueUnreadSteers = Effect.fn("Orchestrator.requeueUnreadSteers")(function* (
threadId: ThreadId,
runIds?: ReadonlyArray<RunId>,
Expand Down Expand Up @@ -3538,7 +3585,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
candidate.id === item.messageId &&
candidate.runId === item.runId,
);
if (run === undefined || message === undefined || isActiveRun(run)) continue;
if (
run === undefined ||
message === undefined ||
isActiveRun(run) ||
(yield* awaitsCheckpointCapture(run))
) {
continue;
}
// Stop drops a steer it reached; say so, as the adapter does for steers it still held.
if (yield* projectionStore.hasRunInterruptRequest(threadId, run.id)) {
const now = yield* DateTime.now;
Expand Down Expand Up @@ -16612,6 +16666,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio

// dispatchWithReceiptEffect owns the dispatch span; this wrapper selects the thread locks.
const dispatchWithReceipt = Effect.fnUntraced(function* (command: OrchestrationV2ServerCommand) {
// The latest stable run is the one with a checkpoint. Wait for a just-completed run's capture,
// outside the locks its commit takes, so a fork right after a turn starts from that turn.
if (
(command.type === "thread.fork" || command.type === "thread.merge_back") &&
command.sourcePoint.type === "latest_stable"
) {
yield* awaitLatestRunCapture(command.sourceThreadId);
}
const dispatch = threadDispatch.withLock(
commandThreadId(command),
dispatchWithReceiptEffect(command),
Expand Down Expand Up @@ -16726,7 +16788,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
// Take parent and child locks sequentially, never nested: delegation holds the parent
// while writing child events, so nesting parent inside child would invert the order.
// The keyed semaphores are neither reentrant nor deadlock-aware.
if (delegatedTaskTerminalStatus(run.status) !== null) {
if (
delegatedTaskTerminalStatus(run.status) !== null &&
!(yield* awaitsCheckpointCapture(run))
) {
// Before the parent hears of the failure: a pending continuation keeps the task open.
if (run.status === "failed" && run.restartContinuationOfRunId !== undefined) {
yield* threadDispatch.withLock(threadId, retryContinuationStart(threadId, run.id)).pipe(
Expand Down
Loading
Loading