Skip to content
TypeScript

fix(server): threads swept by old desktop builds show their real settled time again (#15948)

shivam9257b1006069
diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts
index 10206ded383..9a0dff47736 100644
--- a/apps/server/src/persistence/Migrations.ts
+++ b/apps/server/src/persistence/Migrations.ts
@@ -68,6 +68,7 @@ import Migration0062 from "./Migrations/062_ThreadFailureLookupIndex.ts";
import Migration0063 from "./Migrations/063_DropUnusedV1Projections.ts";
import Migration0064 from "./Migrations/064_CanonicalizeThreadPullRequestLinks.ts";
import Migration0065 from "./Migrations/065_CodexUsageNativeTurnIndex.ts";
+import Migration0066 from "./Migrations/066_RepairClientSettlementTimestamps.ts";
export const migrationEntries = [
[1, "OrchestrationEvents", Migration0001],
@@ -136,6 +137,7 @@ export const migrationEntries = [
[63, "DropUnusedV1Projections", Migration0063],
[64, "CanonicalizeThreadPullRequestLinks", Migration0064],
[65, "CodexUsageNativeTurnIndex", Migration0065],
+ [66, "RepairClientSettlementTimestamps", Migration0066],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
diff --git a/apps/server/src/persistence/Migrations/055_OrchestrationV2.test.ts b/apps/server/src/persistence/Migrations/055_OrchestrationV2.test.ts
index 3f9461779c7..cd926c899d9 100644
--- a/apps/server/src/persistence/Migrations/055_OrchestrationV2.test.ts
+++ b/apps/server/src/persistence/Migrations/055_OrchestrationV2.test.ts
@@ -15,7 +15,7 @@ layer("055_OrchestrationV2", (it) => {
Effect.sync(() => {
assert.deepStrictEqual(
migrationEntries.map(([id]) => id),
- Array.from({ length: 65 }, (_, index) => index + 1),
+ Array.from({ length: 66 }, (_, index) => index + 1),
);
}),
);
@@ -39,6 +39,7 @@ layer("055_OrchestrationV2", (it) => {
[63, "DropUnusedV1Projections"],
[64, "CanonicalizeThreadPullRequestLinks"],
[65, "CodexUsageNativeTurnIndex"],
+ [66, "RepairClientSettlementTimestamps"],
]);
assert.deepStrictEqual(yield* runMigrations(), []);
@@ -70,6 +71,7 @@ layer("055_OrchestrationV2", (it) => {
{ migration_id: 63, name: "DropUnusedV1Projections" },
{ migration_id: 64, name: "CanonicalizeThreadPullRequestLinks" },
{ migration_id: 65, name: "CodexUsageNativeTurnIndex" },
+ { migration_id: 66, name: "RepairClientSettlementTimestamps" },
]);
const tables = yield* sql<{ readonly name: string }>`
diff --git a/apps/server/src/persistence/Migrations/064_CanonicalizeThreadPullRequestLinks.test.ts b/apps/server/src/persistence/Migrations/064_CanonicalizeThreadPullRequestLinks.test.ts
index cb9cc0aed2a..69eb8eff570 100644
--- a/apps/server/src/persistence/Migrations/064_CanonicalizeThreadPullRequestLinks.test.ts
+++ b/apps/server/src/persistence/Migrations/064_CanonicalizeThreadPullRequestLinks.test.ts
@@ -123,11 +123,10 @@ layer("064_CanonicalizeThreadPullRequestLinks", (it) => {
'user', ${v1Payload}, '{}', 1)
`;
- assert.deepEqual(yield* runMigrations(), [
+ assert.deepEqual(yield* runMigrations({ toMigrationInclusive: 64 }), [
[64, "CanonicalizeThreadPullRequestLinks"],
- [65, "CodexUsageNativeTurnIndex"],
]);
- assert.deepEqual(yield* runMigrations(), []);
+ assert.deepEqual(yield* runMigrations({ toMigrationInclusive: 64 }), []);
const rows = yield* sql<{ readonly thread_id: string; readonly payload_json: string }>`
SELECT thread_id, payload_json FROM orchestration_v2_projection_threads
`;
diff --git a/apps/server/src/persistence/Migrations/066_RepairClientSettlementTimestamps.test.ts b/apps/server/src/persistence/Migrations/066_RepairClientSettlementTimestamps.test.ts
new file mode 100644
index 00000000000..f30289cb92d
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/066_RepairClientSettlementTimestamps.test.ts
@@ -0,0 +1,371 @@
+import { assert, it } from "@effect/vitest";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
+import * as DateTime from "effect/DateTime";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as SqlClient from "effect/sql/SqlClient";
+
+import * as EventStore from "../../orchestration-v2/EventStore.ts";
+import * as ProjectionMaintenance from "../../orchestration-v2/ProjectionMaintenance.ts";
+import * as ProjectionStore from "../../orchestration-v2/ProjectionStore.ts";
+import { runMigrations } from "../Migrations.ts";
+import Migration0066 from "./066_RepairClientSettlementTimestamps.ts";
+
+const layer = it.layer(
+ ProjectionMaintenance.layer.pipe(
+ Layer.provideMerge(
+ Layer.mergeAll(EventStore.layer, ProjectionStore.layer).pipe(
+ Layer.provideMerge(NodeSqliteClient.layer({ filename: ":memory:" })),
+ ),
+ ),
+ ),
+);
+const createdAt = "2026-03-01T00:00:00.000Z";
+const sweptAt = "2026-09-04T13:33:00.000Z";
+const userMessageAt = "2026-04-01T00:00:00.000Z";
+const finishedAt = "2026-06-01T00:05:00.000Z";
+const manualAt = "2026-10-01T00:00:00.000Z";
+const plusSeconds = (iso: string, seconds: number) =>
+ DateTime.makeUnsafe(iso).pipe(DateTime.add({ seconds }), DateTime.formatIso);
+
+layer("066_RepairClientSettlementTimestamps", (it) => {
+ it.effect("repairs only sweep stamps, preserves overrides, and survives a V2 rebuild", () =>
+ Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ yield* runMigrations({ toMigrationInclusive: 64 });
+ assert.deepEqual(
+ yield* sql`SELECT name FROM sqlite_master WHERE name = 'projection_turns'`,
+ [],
+ );
+ let eventNumber = 0;
+ const insertEvent = (
+ threadId: string,
+ eventType: string,
+ occurredAt: string,
+ payload: Record<string, unknown>,
+ applicationVersion = 1,
+ actor = "client",
+ appVersion: string | null = "0.0.37",
+ ) => {
+ const version = eventNumber++;
+ return sql`
+ INSERT INTO orchestration_events (
+ event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at,
+ command_id, actor_kind, payload_json, metadata_json, application_event_version
+ ) VALUES (
+ ${`event-${version}`}, 'thread', ${threadId}, ${version}, ${eventType}, ${occurredAt},
+ ${`command-${version}`}, ${actor}, ${JSON.stringify(payload)},
+ ${JSON.stringify({ origin: { appVersion } })}, ${applicationVersion}
+ )
+ `;
+ };
+ const insertSettlement = Effect.fnUntraced(function* (
+ id: string,
+ at: string,
+ appVersion: string | null = "0.0.37",
+ actor = "client",
+ ) {
+ yield* sql`
+ INSERT INTO projection_threads (
+ thread_id, project_id, title, model_selection_json, created_at, updated_at,
+ settled_override, settled_at
+ ) VALUES (
+ ${id}, 'project-1', ${id}, '{"instanceId":"codex","model":"gpt-5.4"}',
+ ${createdAt}, ${at}, 'settled', ${at}
+ )
+ `;
+ yield* insertEvent(
+ id,
+ "thread.settled",
+ at,
+ { threadId: id, settledAt: at, updatedAt: at },
+ 1,
+ actor,
+ appVersion,
+ );
+ });
+
+ // A finished turn must come from retained events after 063 drops projection_turns.
+ for (const [at, status, activeTurnId] of [
+ ["2026-06-01T00:00:00.000Z", "running", "turn-1"],
+ [finishedAt, "ready", null],
+ ["2026-06-03T00:00:00.000Z", "stopped", null],
+ ] as const) {
+ yield* insertEvent(
+ "sweep-2",
+ "thread.session-set",
+ at,
+ {
+ threadId: "sweep-2",
+ session: { status, activeTurnId, updatedAt: at },
+ },
+ 1,
+ "server",
+ );
+ if (status === "running") {
+ for (let index = 0; index < 500; index++) {
+ yield* insertEvent(
+ "sweep-2",
+ "thread.turn-start-requested",
+ "invalid",
+ {
+ createdAt: "invalid",
+ },
+ 1,
+ "server",
+ );
+ }
+ }
+ }
+ for (let index = 0; index < 10; index++) {
+ yield* insertSettlement(
+ `sweep-${index}`,
+ plusSeconds(sweptAt, index * 2),
+ `0.0.${35 + (index % 4)}`,
+ );
+ }
+ // Completed or reverted turns must not be finished again by an idle restart.
+ for (const [id, eventType, at, payload] of [
+ [
+ "sweep-5",
+ "thread.message-sent",
+ userMessageAt,
+ {
+ turnId: "finished",
+ role: "assistant",
+ streaming: true,
+ createdAt: userMessageAt,
+ },
+ ],
+ [
+ "sweep-5",
+ "thread.message-sent",
+ finishedAt,
+ {
+ turnId: "finished",
+ role: "assistant",
+ streaming: false,
+ createdAt: userMessageAt,
+ updatedAt: finishedAt,
+ },
+ ],
+ [
+ "sweep-6",
+ "thread.session-set",
+ "invalid",
+ {
+ session: { status: "running", activeTurnId: "invalid-start", updatedAt: "invalid" },
+ },
+ ],
+ [
+ "sweep-6",
+ "thread.session-set",
+ finishedAt,
+ {
+ session: { status: "ready", activeTurnId: null, updatedAt: "invalid" },
+ },
+ ],
+ [
+ "sweep-7",
+ "thread.session-set",
+ userMessageAt,
+ {
+ session: { status: "running", activeTurnId: "discarded", updatedAt: userMessageAt },
+ },
+ ],
+ ["sweep-7", "thread.reverted", finishedAt, { turnCount: 0 }],
+ ] as const) {
+ yield* insertEvent(id, eventType, at, payload, 1, "server");
+ }
+ for (const id of ["sweep-5", "sweep-6", "sweep-7"]) {
+ yield* insertEvent(
+ id,
+ "thread.session-set",
+ "2026-06-03T00:00:00.000Z",
+ {
+ session: {
+ status: "stopped",
+ activeTurnId: null,
+ updatedAt: "2026-06-03T00:00:00.000Z",
+ },
+ },
+ 1,
+ "server",
+ );
+ }
+ yield* sql`
+ INSERT INTO projection_thread_messages (
+ message_id, thread_id, role, text, is_streaming, created_at, updated_at
+ ) VALUES
+ ('before', 'sweep-0', 'user', 'Prompt', 0, ${userMessageAt}, ${userMessageAt}),
+ ('after', 'sweep-0', 'user', 'Later prompt', 0, ${manualAt}, ${manualAt})
+ `;
+ yield* insertEvent(
+ "sweep-2",
+ "thread.turn-start-requested",
+ manualAt,
+ {
+ threadId: "sweep-2",
+ createdAt: manualAt,
+ },
+ 1,
+ "server",
+ );
+ yield* sql`UPDATE projection_threads SET settled_at = ${manualAt} WHERE thread_id = 'sweep-3'`;
+ yield* sql`UPDATE projection_threads SET settled_override = 'active', settled_at = NULL WHERE thread_id = 'sweep-4'`;
+
+ // This manual settle is within two minutes, but outside the sweep's 30-second gap.
+ yield* insertSettlement("manual", plusSeconds(sweptAt, 18 + 45));
+ // Ten events for nine distinct threads must not qualify.
+ for (let index = 0; index < 9; index++) {
+ yield* insertSettlement(
+ `small-${index}`,
+ plusSeconds("2026-09-03T00:00:00.000Z", index * 2),
+ );
+ }
+ const repeatedAt = "2026-09-03T00:00:18.000Z";
+ yield* insertEvent("small-8", "thread.settled", repeatedAt, { settledAt: repeatedAt });
+ yield* sql`UPDATE projection_threads SET settled_at = ${repeatedAt} WHERE thread_id = 'small-8'`;
+ for (let index = 0; index < 10; index++) {
+ yield* insertSettlement(
+ `spread-${index}`,
+ plusSeconds("2026-09-03T01:00:00.000Z", index * 15),
+ );
+ yield* insertSettlement(
+ `late-${index}`,
+ plusSeconds("2026-09-05T00:00:00.000Z", index * 2),
+ );
+ }
+ yield* insertSettlement("wrong-version", sweptAt, "0.0.40");
+ yield* insertSettlement("missing-version", sweptAt, null);
+ yield* insertSettlement("server", sweptAt, "0.0.37", "server");
+ yield* insertSettlement("different-stamp", sweptAt);
+ yield* sql`
+ UPDATE orchestration_events SET payload_json = json_set(payload_json, '$.settledAt', ${createdAt})
+ WHERE stream_id = 'different-stamp'
+ `;
+ const untouched = sql`
+ SELECT * FROM projection_threads WHERE thread_id NOT LIKE 'sweep-%' ORDER BY thread_id
+ `;
+ const untouchedBefore = yield* untouched;
+
+ for (const index of [0, 2, 3, 4]) {
+ const id = `sweep-${index}`;
+ const badStamp = plusSeconds(sweptAt, index * 2);
+ const thread = {
+ id,
+ projectId: "project-1",
+ title: id,
+ providerInstanceId: "codex",
+ modelSelection: { instanceId: "codex", model: "gpt-5.4" },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ createdBy: "user",
+ creationSource: "web",
+ branch: null,
+ worktreePath: null,
+ activeProviderThreadId: null,
+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: id },
+ forkedFrom: null,
+ createdAt,
+ updatedAt: badStamp,
+ archivedAt: null,
+ deletedAt: null,
+ settledOverride: "settled",
+ settledAt: badStamp,
+ };
+ yield* insertEvent(id, "thread.created", badStamp, thread, 2);
+ const current = {
+ ...thread,
+ settledOverride: index === 4 ? "active" : "settled",
+ settledAt: index === 4 ? null : index === 3 ? manualAt : badStamp,
+ };
+ if (index === 4) {
+ yield* insertEvent(
+ id,
+ "thread.metadata-updated",
+ badStamp,
+ {
+ ...thread,
+ settledOverride: "active",
+ },
+ 2,
+ );
+ }
+ if (index !== 2) yield* insertEvent(id, "thread.metadata-updated", manualAt, current, 2);
+ yield* sql`
+ INSERT INTO orchestration_v2_projection_threads (
+ thread_id, project_id, title, default_provider, runtime_mode, interaction_mode,
+ created_at, updated_at, payload_json
+ ) VALUES (
+ ${id}, 'project-1', ${id}, 'codex', 'full-access', 'default',
+ ${createdAt}, ${badStamp}, ${JSON.stringify(current)}
+ )
+ `;
+ }
+ const v1History = sql`
+ SELECT * FROM orchestration_events WHERE application_event_version = 1 ORDER BY sequence
+ `;
+ const v1Before = yield* v1History;
+ const overrides = sql`
+ SELECT * FROM orchestration_events
+ WHERE application_event_version = 2 AND event_type = 'thread.metadata-updated'
+ AND stream_id IN ('sweep-3', 'sweep-4') ORDER BY sequence
+ `;
+ const overridesBefore = yield* overrides;
+
+ yield* runMigrations({ toMigrationInclusive: 66 });
+ const legacy = yield* sql`
+ SELECT thread_id, settled_override, settled_at FROM projection_threads
+ WHERE thread_id LIKE 'sweep-%' ORDER BY thread_id
+ `;
+ assert.deepEqual(
+ legacy,
+ Array.from({ length: 10 }, (_, index) => ({
+ thread_id: `sweep-${index}`,
+ settled_override: index === 4 ? "active" : "settled",
+ settled_at:
+ index === 4
+ ? null
+ : ([
+ userMessageAt,
+ createdAt,
+ finishedAt,
+ manualAt,
+ null,
+ finishedAt,
+ finishedAt,
+ userMessageAt,
+ ][index] ?? createdAt),
+ })),
+ );
+ assert.deepEqual(yield* untouched, untouchedBefore);
+ assert.deepEqual(yield* v1History, v1Before);
+ assert.deepEqual(yield* overrides, overridesBefore);
+ const imported = sql`
+ SELECT thread_id,
+ json_extract(payload_json, '$.settledAt') AS settled_at,
+ json_extract(payload_json, '$.settledOverride') AS settled_override,
+ json_extract(payload_json, '$.title') AS title
+ FROM orchestration_v2_projection_threads ORDER BY thread_id
+ `;
+ const expectedImported = legacy
+ .filter((_, index) => [0, 2, 3, 4].includes(index))
+ .map((row) => ({ ...row, title: row.thread_id }));
+ assert.deepEqual(yield* imported, expectedImported);
+ const snapshot = Effect.all([
+ sql`SELECT * FROM projection_threads ORDER BY thread_id`,
+ sql`SELECT * FROM orchestration_v2_projection_threads ORDER BY thread_id`,
+ sql`SELECT * FROM orchestration_events ORDER BY sequence`,
+ ]);
+ const repaired = yield* snapshot;
+ assert.deepEqual(yield* runMigrations({ toMigrationInclusive: 66 }), []);
+ yield* Migration0066;
+ assert.deepEqual(yield* snapshot, repaired);
+
+ const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
+ assert.isTrue((yield* maintenance.rebuild).valid);
+ assert.deepEqual(yield* imported, expectedImported);
+ }),
+ );
+});
diff --git a/apps/server/src/persistence/Migrations/066_RepairClientSettlementTimestamps.ts b/apps/server/src/persistence/Migrations/066_RepairClientSettlementTimestamps.ts
new file mode 100644
index 00000000000..6f5be097465
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/066_RepairClientSettlementTimestamps.ts
@@ -0,0 +1,284 @@
+import * as DateTime from "effect/DateTime";
+import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
+import * as SqlClient from "effect/sql/SqlClient";
+
+const timestamp = (value: string | null) =>
+ value === null ? undefined : Option.getOrUndefined(DateTime.make(value));
+
+export default Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ // Manual settles have the same shape; only the affected builds' dense sweeps qualify.
+ const settlements = yield* sql<{ readonly thread_id: string; readonly occurred_at: string }>`
+ WITH
+ legacy_settlements AS (
+ SELECT
+ stream_id AS thread_id,
+ occurred_at,
+ unixepoch(occurred_at, 'subsec') AS occurred_seconds
+ FROM orchestration_events
+ WHERE aggregate_kind = 'thread'
+ AND event_type = 'thread.settled'
+ AND actor_kind = 'client'
+ AND application_event_version = 1
+ AND json_type(payload_json, '$.settledAt') = 'text'
+ AND json_extract(payload_json, '$.settledAt') = occurred_at
+ AND json_extract(metadata_json, '$.origin.appVersion') IN ('0.0.35', '0.0.36', '0.0.37', '0.0.38')
+ AND julianday(occurred_at) < julianday('2026-09-05T00:00:00.000Z')
+ ),
+ ordered AS (
+ SELECT
+ thread_id,
+ occurred_at,
+ occurred_seconds,
+ occurred_seconds - LAG(occurred_seconds) OVER (ORDER BY occurred_seconds, thread_id)
+ AS gap_seconds
+ FROM legacy_settlements
+ ),
+ clustered AS (
+ SELECT
+ thread_id,
+ occurred_at,
+ occurred_seconds,
+ SUM(CASE WHEN gap_seconds IS NULL OR gap_seconds > 30 THEN 1 ELSE 0 END)
+ OVER (ORDER BY occurred_seconds, thread_id) AS cluster_id
+ FROM ordered
+ ),
+ burst_clusters AS (
+ SELECT
+ cluster_id,
+ COUNT(DISTINCT thread_id) AS distinct_thread_count,
+ MAX(occurred_seconds) - MIN(occurred_seconds) AS span_seconds
+ FROM clustered
+ GROUP BY cluster_id
+ ),
+ automatic_settlements AS (
+ SELECT clustered.thread_id, clustered.occurred_at
+ FROM clustered
+ JOIN burst_clusters ON burst_clusters.cluster_id = clustered.cluster_id
+ WHERE burst_clusters.distinct_thread_count >= 10
+ AND burst_clusters.span_seconds <= 120
+ )
+ SELECT DISTINCT thread_id, occurred_at FROM automatic_settlements
+ ORDER BY thread_id, occurred_at
+ `;
+ const byThread = Map.groupBy(settlements, (settlement) => settlement.thread_id);
+
+ for (const [threadId, sweeps] of byThread) {
+ const repairs = sweeps.map((sweep) => ({
+ occurredAt: sweep.occurred_at,
+ cutoff: DateTime.toEpochMillis(DateTime.makeUnsafe(sweep.occurred_at)),
+ activityAt: null as string | null,
+ activityTime: -Infinity,
+ }));
+ const recordActivity = (value: string | null) => {
+ const date = timestamp(value);
+ if (date === undefined) return;
+ const time = DateTime.toEpochMillis(date);
+ for (const repair of repairs) {
+ if (time <= repair.cutoff && time > repair.activityTime) {
+ repair.activityAt = value;
+ repair.activityTime = time;
+ }
+ }
+ };
+
+ for (const repair of repairs) {
+ const messages = yield* sql<{ readonly created_at: string }>`
+ SELECT created_at FROM projection_thread_messages
+ WHERE thread_id = ${threadId} AND role = 'user'
+ AND julianday(created_at) <= julianday(${repair.occurredAt})
+ ORDER BY julianday(created_at) DESC LIMIT 1
+ `;
+ recordActivity(messages[0]?.created_at ?? null);
+ }
+
+ // 063 dropped projection_turns. Track open turns from retained V1 events so an
+ // idle session stopping cannot masquerade as a turn finishing.
+ const turns = new Map<
+ string,
+ { state: "running" | "completed" | "interrupted" | "error"; checkpoint: number | null }
+ >();
+ const runningTurnIds = new Set<string>();
+ let activeTurnId: string | null = null;
+ let afterSequence = 0;
+ const pageSize = 500;
+ while (true) {
+ const events = yield* sql<{
+ readonly sequence: number;
+ readonly event_type: string;
+ readonly occurred_at: string;
+ readonly turn_id: string | null;
+ readonly created_at: string | null;
+ readonly updated_at: string | null;
+ readonly completed_at: string | null;
+ readonly role: string | null;
+ readonly streaming: number | null;
+ readonly status: string | null;
+ readonly session_turn_id: string | null;
+ readonly session_updated_at: string | null;
+ readonly checkpoint: number | null;
+ readonly turn_count: number | null;
+ }>`
+ SELECT sequence, event_type, occurred_at,
+ json_extract(payload_json, '$.turnId') AS turn_id,
+ json_extract(payload_json, '$.createdAt') AS created_at,
+ json_extract(payload_json, '$.updatedAt') AS updated_at,
+ json_extract(payload_json, '$.completedAt') AS completed_at,
+ json_extract(payload_json, '$.role') AS role,
+ json_extract(payload_json, '$.streaming') AS streaming,
+ json_extract(payload_json, '$.session.status') AS status,
+ json_extract(payload_json, '$.session.activeTurnId') AS session_turn_id,
+ json_extract(payload_json, '$.session.updatedAt') AS session_updated_at,
+ json_extract(payload_json, '$.checkpointTurnCount') AS checkpoint,
+ json_extract(payload_json, '$.turnCount') AS turn_count
+ FROM orchestration_events INDEXED BY idx_orch_events_stream_sequence
+ WHERE aggregate_kind = 'thread' AND stream_id = ${threadId}
+ AND application_event_version = 1 AND sequence > ${afterSequence}
+ AND event_type IN (
+ 'thread.created', 'thread.turn-start-requested', 'thread.session-set',
+ 'thread.message-sent', 'thread.turn-interrupt-requested',
+ 'thread.turn-diff-completed', 'thread.reverted'
+ )
+ ORDER BY sequence LIMIT ${pageSize}
+ `;
+ for (const event of events) {
+ const turn = event.turn_id === null ? undefined : turns.get(event.turn_id);
+ switch (event.event_type) {
+ case "thread.created":
+ turns.clear();
+ runningTurnIds.clear();
+ activeTurnId = null;
+ break;
+ case "thread.turn-start-requested":
+ recordActivity(event.created_at);
+ break;
+ case "thread.session-set": {
+ activeTurnId = event.status === "running" ? event.session_turn_id : null;
+ const endedAt = timestamp(event.session_updated_at)
+ ? event.session_updated_at
+ : event.occurred_at;
+ if (activeTurnId !== null) {
+ for (const id of runningTurnIds) {
+ if (id !== activeTurnId) {
+ turns.get(id)!.state = "completed";
+ runningTurnIds.delete(id);
+ recordActivity(endedAt);
+ }
+ }
+ const active = turns.get(activeTurnId);
+ if (active === undefined) {
+ turns.set(activeTurnId, { state: "running", checkpoint: null });
+ runningTurnIds.add(activeTurnId);
+ recordActivity(event.occurred_at);
+ } else if (active.state === "interrupted") {
+ active.state = "running";
+ runningTurnIds.add(activeTurnId);
+ }
+ } else if (
+ event.status === "idle" ||
+ event.status === "ready" ||
+ event.status === "error" ||
+ event.status === "interrupted" ||
+ event.status === "stopped"
+ ) {
+ for (const id of runningTurnIds) {
+ const running = turns.get(id)!;
+ running.state =
+ event.status === "error"
+ ? "error"
+ : event.status === "interrupted" || event.status === "stopped"
+ ? "interrupted"
+ : "completed";
+ recordActivity(endedAt);
+ }
+ runningTurnIds.clear();
+ }
+ break;
+ }
+ case "thread.message-sent":
+ if (event.role !== "assistant" || event.turn_id === null) break;
+ recordActivity(event.created_at);
+ if (event.streaming === 0 && activeTurnId !== event.turn_id) {
+ if (turn === undefined || turn.state === "running") recordActivity(event.updated_at);
+ if (turn === undefined) {
+ turns.set(event.turn_id, { state: "completed", checkpoint: null });
+ } else if (turn.state === "running") {
+ turn.state = "completed";
+ }
+ runningTurnIds.delete(event.turn_id);
+ } else if (turn === undefined) {
+ turns.set(event.turn_id, { state: "running", checkpoint: null });
+ runningTurnIds.add(event.turn_id);
+ }
+ break;
+ case "thread.turn-interrupt-requested":
+ if (event.turn_id === null) break;
+ recordActivity(event.created_at);
+ turns.set(event.turn_id, {
+ state: "interrupted",
+ checkpoint: turn?.checkpoint ?? null,
+ });
+ runningTurnIds.delete(event.turn_id);
+ break;
+ case "thread.turn-diff-completed":
+ if (event.turn_id === null) break;
+ recordActivity(event.completed_at);
+ turns.set(event.turn_id, {
+ state:
+ activeTurnId === event.turn_id
+ ? (turn?.state ?? "running")
+ : turn?.state === "interrupted"
+ ? "interrupted"
+ : "completed",
+ checkpoint: event.checkpoint,
+ });
+ if (turns.get(event.turn_id)!.state === "running") {
+ runningTurnIds.add(event.turn_id);
+ } else {
+ runningTurnIds.delete(event.turn_id);
+ }
+ break;
+ case "thread.reverted":
+ for (const [id, previous] of turns) {
+ if (previous.checkpoint === null || previous.checkpoint > (event.turn_count ?? 0)) {
+ turns.delete(id);
+ runningTurnIds.delete(id);
+ }
+ }
+ break;
+ }
+ }
+ if (events.length < pageSize) break;
+ afterSequence = events.at(-1)!.sequence;
+ }
+
+ for (const repair of repairs) {
+ yield* sql`
+ UPDATE projection_threads
+ SET settled_at = COALESCE(${repair.activityAt}, created_at)
+ WHERE thread_id = ${threadId} AND settled_override = 'settled'
+ AND settled_at = ${repair.occurredAt}
+ `;
+ yield* sql`
+ UPDATE orchestration_v2_projection_threads
+ SET payload_json = json_set(payload_json, '$.settledAt',
+ COALESCE(${repair.activityAt}, json_extract(payload_json, '$.createdAt')))
+ WHERE thread_id = ${threadId}
+ AND json_extract(payload_json, '$.settledOverride') = 'settled'
+ AND json_extract(payload_json, '$.settledAt') = ${repair.occurredAt}
+ `;
+ // V2 snapshots must retain the repair after a rebuild; V1 history stays immutable.
+ yield* sql`
+ UPDATE orchestration_events
+ SET payload_json = json_set(payload_json, '$.settledAt',
+ COALESCE(${repair.activityAt}, json_extract(payload_json, '$.createdAt'),
+ json_extract(payload_json, '$.settledAt')))
+ WHERE aggregate_kind = 'thread' AND stream_id = ${threadId}
+ AND application_event_version = 2
+ AND json_extract(payload_json, '$.settledOverride') = 'settled'
+ AND json_extract(payload_json, '$.settledAt') = ${repair.occurredAt}
+ `;
+ }
+ }
+});
diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
index dc1f48c9c40..f1495d1e62a 100644
--- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
+++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
@@ -45,6 +45,7 @@ describe("V2 preview upgrade", () => {
[63, "DropUnusedV1Projections"],
[64, "CanonicalizeThreadPullRequestLinks"],
[65, "CodexUsageNativeTurnIndex"],
+ [66, "RepairClientSettlementTimestamps"],
]);
assert.deepStrictEqual(yield* runMigrations(), []);
assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);
@@ -133,6 +134,7 @@ describe("V2 preview upgrade", () => {
[63, "DropUnusedV1Projections"],
[64, "CanonicalizeThreadPullRequestLinks"],
[65, "CodexUsageNativeTurnIndex"],
+ [66, "RepairClientSettlementTimestamps"],
]);
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
);