Skip to content
Merged
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
54 changes: 50 additions & 4 deletions apps/server/src/orchestration-v2/ProjectionStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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") =>
Expand Down Expand Up @@ -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"),
Expand Down
20 changes: 18 additions & 2 deletions apps/server/src/orchestration-v2/ProjectionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3785,7 +3785,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
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``
Expand Down Expand Up @@ -7436,7 +7436,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
)
)`;
};
// 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
Expand All @@ -7445,6 +7445,22 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
17 changes: 17 additions & 0 deletions packages/shared/src/orchestrationV2ThreadError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<OrchestrationV2Run>,
): 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),
);
}
Loading