Skip to content
TypeScript

fix(server): queued messages land after a resume that ran before them (#17773)

Lakshmi Tanmay529d8063cc43
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index 1499ca975de..589fc7e5cb4 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -380,8 +380,9 @@ export class OrchestratorV2 extends Context.Service<OrchestratorV2, Orchestrator
"t3/orchestration-v2/Orchestrator/OrchestratorV2",
) {}
+/** Run ordinals can skip values: a queued run moves past newer runs when it starts. */
function nextRunOrdinal(projection: Pick<OrchestrationV2ThreadProjection, "runs">): number {
- return projection.runs.length + 1;
+ return projection.runs.reduce((max, run) => Math.max(max, run.ordinal), 0) + 1;
}
/**
@@ -1341,6 +1342,21 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
);
return;
}
+ // Run ordinals order the transcript, checkpoints, and the latest run. A
+ // run that started while this one waited (a resume of a held queue, a
+ // reorder, a delivery that jumps the queue) has a newer ordinal, so this
+ // run moves after it. A started run has its prompt in the transcript (a
+ // wake's prompt is a notification); a message cancelled from the queue has none.
+ const newerRunIds = projection.runs
+ .filter((run) => run.status !== "queued" && run.ordinal > queuedRun.ordinal)
+ .map((run) => run.id);
+ const startedAhead =
+ newerRunIds.length > 0 &&
+ (yield* projectionStore.getThreadRecords(threadId, ["turnItems"], {
+ turnItemTypes: ["user_message", "notification"],
+ turnItemRunIds: newerRunIds,
+ })).turnItems.length > 0;
+ const ordinal = startedAhead ? nextRunOrdinal(projection) : queuedRun.ordinal;
const rootNodeId = queuedRun.rootNodeId;
const attemptId = queuedRun.activeAttemptId;
const providerThreadId = queuedRun.providerThreadId;
@@ -1614,8 +1630,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
...deliveryProviderThread,
providerSessionId,
status: "not_loaded",
- firstRunOrdinal: queuedProviderThread.firstRunOrdinal ?? queuedRun.ordinal,
- lastRunOrdinal: queuedRun.ordinal,
+ firstRunOrdinal: queuedProviderThread.firstRunOrdinal ?? ordinal,
+ lastRunOrdinal: ordinal,
handoffIds: appendContextHandoffId(
appendContextHandoffId(queuedProviderThread.handoffIds, handoff?.id ?? null),
legacyImportRecoveryHandoff?.id ?? null,
@@ -1624,6 +1640,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
};
const startingRun: OrchestrationV2Run = {
...queuedRun,
+ ordinal,
status: "starting",
queuePosition: null,
startedAt: null,
@@ -1644,7 +1661,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
- ordinal: queuedRun.ordinal * 100,
+ ordinal: ordinal * 100,
status: "completed",
title: null,
type: "user_message",
@@ -1681,7 +1698,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
- ordinal: queuedRun.ordinal * 100 - 1,
+ ordinal: ordinal * 100 - 1,
status: "completed",
title: handoff === null ? "Imported context" : "Provider handoff",
startedAt: now,
diff --git a/apps/server/src/orchestration-v2/ThreadStop.test.ts b/apps/server/src/orchestration-v2/ThreadStop.test.ts
index 1f86d0ddb5a..d49ca40e2ba 100644
--- a/apps/server/src/orchestration-v2/ThreadStop.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadStop.test.ts
@@ -520,8 +520,9 @@ it.effect.each(["thread.stop", "run.interrupt"] as const)(
creationSource: "server",
restartContinuationOfRunId: source.id,
});
+ // The held run resumed after the cancelled source ran, so it sorts after it.
assert.deepEqual(yield* threadState(threadId), {
- runs: ["completed", "interrupted", "cancelled"],
+ runs: ["completed", "cancelled", "interrupted"],
watched: [],
});
}).pipe(Effect.provide(layerTest.pipe(Layer.provideMerge(TestClock.layer())))),
diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
index 086c52296e9..7dc367bdfe2 100644
--- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts
+++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
@@ -3972,6 +3972,16 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
yield* settle("queued", queuedStartedAt);
assert.equal(yield* Queue.take(startedRunIds), (yield* runFor("late-wake")).id);
assert.equal(millis((yield* runFor("late-wake")).workStartedAt), millis(queuedStartedAt));
+
+ // Runs sort in the order they started, including after a wake that ran ahead.
+ const ordinals = yield* Effect.forEach(
+ ["prompt", "early-wake", "queued", "late-wake"],
+ (key) => Effect.map(runFor(key), (run) => run.ordinal),
+ );
+ assert.deepEqual(
+ ordinals,
+ ordinals.toSorted((left, right) => left - right),
+ );
}),
);
@@ -4164,6 +4174,115 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
}),
);
+ it.effect("places held queued messages after a continuation that started first", () =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const eventSink = yield* EventSink.EventSinkV2;
+ const threadId = ThreadId.make("runtime-layer-continuation-before-queue");
+ const messageId = (key: string) => MessageId.make(`${threadId}:${key}`);
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make(`${threadId}:create`),
+ threadId,
+ projectId: ProjectId.make(`${threadId}:project`),
+ title: "Continuation before queue",
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: process.cwd(),
+ });
+ const dispatch = (key: string, start: boolean) =>
+ orchestrator.dispatch({
+ type: "message.dispatch",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make(`${threadId}:message:${key}`),
+ threadId,
+ messageId: messageId(key),
+ text: key,
+ attachments: [],
+ modelSelection,
+ dispatchMode: { type: start ? "start_immediately" : "queue_after_active" },
+ });
+ const runFor = (key: string) =>
+ Effect.map(orchestrator.getThreadProjection(threadId), ({ runs }) => {
+ const run = runs.find((candidate) => candidate.userMessageId === messageId(key));
+ assert.isDefined(run);
+ return run;
+ });
+ yield* dispatch("active", true);
+ yield* dispatch("first-queued", false);
+ yield* dispatch("second-queued", false);
+ yield* orchestrator.dispatch({
+ type: "run.interrupt",
+ commandId: CommandId.make(`${threadId}:interrupt`),
+ threadId,
+ runId: (yield* runFor("active")).id,
+ holdQueue: true,
+ });
+ // The continuation starts while the older messages wait in the held queue.
+ yield* dispatch("continue", true);
+ yield* orchestrator.dispatch({
+ type: "queue.resume",
+ commandId: CommandId.make(`${threadId}:resume`),
+ threadId,
+ });
+
+ const startedRunIds = yield* Queue.unbounded<RunId>();
+ const afterSequence = yield* orchestrator.getThreadEventSequence(threadId);
+ yield* eventSink.stream({ threadId, afterSequence }).pipe(
+ Stream.runForEach((stored) =>
+ stored.event.type === "run.updated" && stored.event.payload.status === "starting"
+ ? Queue.offer(startedRunIds, stored.event.payload.id)
+ : Effect.void,
+ ),
+ Effect.forkScoped,
+ );
+ yield* Effect.yieldNow;
+ const complete = (key: string) =>
+ Effect.gen(function* () {
+ const run = yield* runFor(key);
+ const now = yield* DateTime.now;
+ yield* eventSink.write({
+ events: [
+ {
+ id: EventId.make(`${threadId}:${key}:completed`),
+ type: "run.updated",
+ threadId,
+ runId: run.id,
+ ...(run.rootNodeId === null ? {} : { nodeId: run.rootNodeId }),
+ providerInstanceId: run.providerInstanceId,
+ occurredAt: now,
+ payload: { ...run, status: "completed", startedAt: now, completedAt: now },
+ },
+ ],
+ });
+ });
+
+ yield* complete("continue");
+ assert.equal(yield* Queue.take(startedRunIds), (yield* runFor("first-queued")).id);
+ yield* complete("first-queued");
+ assert.equal(yield* Queue.take(startedRunIds), (yield* runFor("second-queued")).id);
+
+ const keys = ["active", "continue", "first-queued", "second-queued"];
+ const runs = yield* Effect.forEach(keys, runFor);
+ const ordinals = runs.map((run) => run.ordinal);
+ assert.deepEqual(
+ ordinals,
+ ordinals.toSorted((left, right) => left - right),
+ );
+ const { turnItems } = yield* orchestrator.getThreadProjection(threadId);
+ const userItems = turnItems.filter((item) => item.type === "user_message");
+ assert.deepEqual(
+ userItems.map((item) => item.messageId),
+ keys.map(messageId),
+ );
+ }),
+ );
+
it.effect.each(["startup", "shutdown"] as const)(
"preserves and holds queued messages across %s until explicitly resumed",
(trigger) =>
@@ -5698,8 +5817,9 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
: 0),
);
if (scenario === "queued-resume") {
- assert.equal(after.runs[1]?.status, "queued");
- assert.isTrue(after.runs[1]?.queueHeld);
+ const held = after.runs[1]!;
+ assert.equal(held.status, "queued");
+ assert.isTrue(held.queueHeld);
const continuation = after.runs[2]!;
const completedAt = yield* DateTime.now;
yield* events.write({
@@ -5720,8 +5840,13 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
threadId,
});
const resumed = yield* orchestrator.getThreadProjection(threadId);
- assert.equal(resumed.runs[1]?.status, "starting");
- assert.isFalse(resumed.runs[1]?.queueHeld);
+ // The held message ran after the continuation, so it now sorts after it.
+ assert.deepEqual(
+ resumed.runs.map((run) => run.id),
+ [run.id, continuation.id, held.id],
+ );
+ assert.equal(resumed.runs[2]?.status, "starting");
+ assert.isFalse(resumed.runs[2]?.queueHeld);
}
}),
);