diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index ce28610f09735..250b41dd798a4 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -5039,8 +5039,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { ), ); - // A steer cancels the queued run before it starts while the steered run keeps writing, so - // the queued message leaves the window but its run is still the shell's latest run. + // A steer moves the cancelled queued message outside the window. const steeredItemId = "turn-item:bounded-sql-history:steered-output"; const steeredRunId = RunId.make("run:bounded-sql-history:1000"); yield* sql` @@ -5078,7 +5077,14 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { assert.isFalse( steeredSnapshot.projection.turnItems.some((item) => item.runId === cancelledRunId), ); - assert.isTrue(steeredSnapshot.projection.runs.some((run) => run.id === cancelledRunId)); + const latestRunId = (yield* projectionStore.getShellSnapshot()).threads.find( + (thread) => thread.id === threadId, + )?.latestRunId; + assert.equal(latestRunId, hiddenRunId); + assert.isFalse( + steeredSnapshot.projection.turnItems.some((item) => item.runId === latestRunId), + ); + assert.isTrue(steeredSnapshot.projection.runs.some((run) => run.id === latestRunId)); yield* sql`DELETE FROM orchestration_v2_projection_turn_items WHERE turn_item_id = ${steeredItemId}`; const interruptRunId = RunId.make("run:bounded-sql-history:interrupt"); @@ -7395,6 +7401,28 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { silent ? hidden : visible, ]); + // A follow-up removed before it started stays latest unless a visible run outlives it. + const removedRunId = RunId.make(`run:projection-shell-silent:${key}:removed`); + yield* projectionStore.apply({ + id: EventId.make(`event:projection-shell-silent:${key}:removed`), + type: "run.updated", + threadId, + occurredAt: now, + payload: { + ...(yield* projectionStore.getThreadProjection(threadId)).runs[0]!, + id: removedRunId, + ordinal: 2, + userMessageId: MessageId.make(`message:projection-shell-silent:${key}:removed`), + status: "cancelled", + startedAt: null, + completedAt: now, + }, + }); + assert.deepStrictEqual( + (yield* presented).map((shell) => shell.latestRunId), + silent ? [removedRunId, removedRunId] : [runId, runId], + ); + // A run that fails outright, e.g. on a provider error, needs the user too. const running = (yield* projectionStore.getThreadProjection(threadId)).runs[0]!; const setRunStatus = (status: "failed" | "running") => @@ -7633,9 +7661,27 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { value == null ? null : DateTime.toEpochMillis(value); assert.equal(timestamp(sqlShell.activityRunStartedAt), expected); assert.equal(timestamp(memoryShell.activityRunStartedAt), expected); - assert.equal(sqlShell.latestRunId, "run:clock:newer"); + // A queued message steered or removed before it started never ran, so the run that did presents. + for (const shell of [sqlShell, memoryShell]) { + assert.equal(shell.latestRunId, status === "cancelled" ? runId : "run:clock:newer"); + } } } + // Removing a message after the earlier run ended leaves the cancelled run as the latest. + yield* projectionStore.apply({ + id: EventId.make("event:clock:ended-before-cancel"), + type: "run.updated", + threadId, + occurredAt: later, + payload: { ...run, status: "completed", startedAt: now, completedAt: now }, + }); + const endedBeforeCancelProjection = yield* projectionStore.getThreadProjection(threadId); + for (const shell of [ + (yield* projectionStore.getShellSnapshot()).threads.find((row) => row.id === threadId)!, + ProjectionStore.threadShellFromProjection(endedBeforeCancelProjection), + ]) { + assert.equal(shell.latestRunId, "run:clock:newer"); + } yield* projectionStore.apply({ id: EventId.make("event:clock:newer:held"), diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index c67f245349bbf..0c1ba9abfe24c 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -3785,7 +3785,7 @@ export const layer: Layer.Layer = OR run_id IN (SELECT value FROM json_each(${cohortRunIds})) OR run_id = ${window.requiredRunId ?? null} ${ - // The shell's latest run, even a steer-cancelled one outside the newest window. + // Keep the shell's latest run even when its items are outside the newest window. window.anchorItemId === undefined && window.requiredRunId === undefined ? sql`OR run_id = ${presentedShellRunId(sql`${threadId}`)}` : sql`` @@ -7436,7 +7436,7 @@ export const layer: Layer.Layer = ) )`; }; - // The newest run not waiting in a held queue, matching latestUnheldRun. + // The newest run not held or outlived before it started, matching latestUnheldRun. const presentedShellRunId = (threadId: Statement.Fragment) => sql`( SELECT candidate.run_id FROM orchestration_v2_projection_runs candidate @@ -7445,6 +7445,22 @@ export const layer: Layer.Layer = candidate.status = 'queued' AND json_extract(candidate.payload_json, '$.queueHeld') IS 1 ) + AND NOT ( + candidate.status = 'cancelled' + AND json_extract(candidate.payload_json, '$.startedAt') IS NULL + AND candidate.completed_at IS NOT NULL + AND EXISTS ( + SELECT 1 FROM orchestration_v2_projection_runs earlier + WHERE earlier.thread_id = candidate.thread_id + AND earlier.ordinal < candidate.ordinal + AND earlier.status <> 'queued' + AND NOT ${isSilentShellRun("earlier")} + AND ( + earlier.completed_at IS NULL + OR julianday(earlier.completed_at) >= julianday(candidate.completed_at) + ) + ) + ) AND NOT ${isSilentShellRun("candidate")} ORDER BY candidate.ordinal DESC, candidate.run_id DESC LIMIT 1 diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/queued_cancelled_while_active/codex_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/queued_cancelled_while_active/codex_output.ts index b0d6a44ef45ea..7ab76f9e5a7d4 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/queued_cancelled_while_active/codex_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/queued_cancelled_while_active/codex_output.ts @@ -34,8 +34,9 @@ export function assertQueuedCancelledWhileActiveOutput( .get(ACTIVE_RUN_SHELL_SNAPSHOT_KEY) ?.threads.find((thread) => thread.id === projection.thread.id); assert.isDefined(capturedShell); - assert.equal(capturedShell.latestRunId, cancelledRun.id); - assert.equal(capturedShell.status, "cancelled"); + // The cancelled queued run never started, so the active run presents as the latest. + assert.equal(capturedShell.latestRunId, activeRun.id); + assert.equal(capturedShell.status, "running"); assert.equal(capturedShell.activeRunId, activeRun.id); assert.equal(capturedShell.activityRunStatus, "running"); assert.deepEqual( diff --git a/packages/shared/src/orchestrationV2ThreadError.ts b/packages/shared/src/orchestrationV2ThreadError.ts index 3ba3ba2bf3247..141d73f402540 100644 --- a/packages/shared/src/orchestrationV2ThreadError.ts +++ b/packages/shared/src/orchestrationV2ThreadError.ts @@ -122,7 +122,24 @@ export function latestUnheldRun( let latest: OrchestrationV2Run | null = null; for (const run of runs) { if (run.status === "queued" && run.queueHeld === true) continue; + if (outlivedBeforeStart(run, runs)) continue; if (latest === null || run.ordinal > latest.ordinal) latest = run; } return latest; } + +// Steering a queued message cancels its run before it starts and hands the message to the +// earlier run, which outlives the cancellation; that earlier run then presents as latest. +function outlivedBeforeStart( + run: OrchestrationV2Run, + runs: ReadonlyArray, +): boolean { + if (run.status !== "cancelled" || run.startedAt !== null || !run.completedAt) return false; + const cancelledAt = DateTime.toEpochMillis(run.completedAt); + return runs.some( + (earlier) => + earlier.ordinal < run.ordinal && + earlier.status !== "queued" && + (!earlier.completedAt || DateTime.toEpochMillis(earlier.completedAt) >= cancelledAt), + ); +}