From 288fe5d29deb36fd976b01dba016251f6f614a47 Mon Sep 17 00:00:00 2001 From: Ben Davis <45952064+bmdavis419@users.noreply.github.com> Date: Sun, 26 Jul 2026 19:47:50 -0700 Subject: [PATCH] fix: a session ending a turn erased the thread's latest turn MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `thread.session-set` wrote `session.activeTurnId` straight through to `projection_threads.latest_turn_id`. A session clearing `activeTurnId` means the turn ENDED, not that the thread never had one — so the end of every turn nulled the pointer to the turn that had just finished. For workspace providers the damage was invisible: `thread.turn-diff-completed` fires moments later and re-writes the id. A provider with no workspace (Hermes) emits no diff, so nothing restored it. The evidence is stark — the same database has 1315 turn-diff events across codex/claudeAgent threads and zero across Hermes ones, and every Hermes thread carried a null pointer despite having completed turns. With `latest_turn_id` null, `latestTurn` never resolves, and the settle guard reads a completed turn as its opposite: a user message newer than every turn timestamp is that guard's signature for a turn requested but never adopted. Settling was refused with "This thread still needs attention" for the whole two-minute adoption grace window, then started working on its own — which is why it looked intermittent rather than broken. Migration 038 repairs rows already written, since projections resume from their stored sequence rather than replaying. It is deliberately conservative: only threads whose pointer is currently null are touched, so a correct value is never overwritten by the heuristic, and a thread with no turn row stays null rather than being given a turn it never ran. Co-Authored-By: Claude Opus 5 (1M context) --- .../Layers/ProjectionPipeline.test.ts | 15 ++ .../Layers/ProjectionPipeline.ts | 12 +- apps/server/src/persistence/Migrations.ts | 2 + ...ackfillProjectionThreadsLatestTurn.test.ts | 134 ++++++++++++++++++ ...038_BackfillProjectionThreadsLatestTurn.ts | 51 +++++++ 5 files changed, 213 insertions(+), 1 deletion(-) create mode 100644 apps/server/src/persistence/Migrations/038_BackfillProjectionThreadsLatestTurn.test.ts create mode 100644 apps/server/src/persistence/Migrations/038_BackfillProjectionThreadsLatestTurn.ts diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts index c795ae4557..075008a0a2 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts @@ -1429,6 +1429,21 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { assert.deepEqual(settledRows, [ { state: "completed", completedAt: "2026-01-01T00:01:00.000Z" }, ]); + + // The session cleared `activeTurnId` because the turn ENDED, not + // because the thread never had one — the pointer must survive. + // + // Nulling it here used to be masked by `thread.turn-diff-completed`, + // which re-writes the id moments later. A workspaceless provider + // (Hermes) emits no diff, so the id stayed null forever, `latestTurn` + // never resolved, and every completed turn read as a queued-but- + // unadopted turn start — which blocks settling for the grace window. + const latestTurnRows = yield* sql<{ readonly latestTurnId: string | null }>` + SELECT latest_turn_id AS "latestTurnId" + FROM projection_threads + WHERE thread_id = ${threadId} + `; + assert.deepEqual(latestTurnRows, [{ latestTurnId: turnId }]); }), ); diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index e40bde7a39..89e13e82cc 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -831,9 +831,19 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti if (Option.isNone(existingRow)) { return; } + // A session clearing `activeTurnId` means the turn ENDED, not that + // the thread never had one — so retain the last known turn instead + // of nulling it. Nulling was survivable only for providers that + // emit `thread.turn-diff-completed`, which re-writes this field + // moments later. A workspaceless provider (Hermes) emits no diff, + // so the id stayed null forever and `latestTurn` never resolved — + // leaving every completed turn looking like a queued-but-unadopted + // turn start, which blocks settling for the whole grace window. + const nextLatestTurnId = + event.payload.session.activeTurnId ?? existingRow.value.latestTurnId; yield* projectionThreadRepository.upsert({ ...existingRow.value, - latestTurnId: event.payload.session.activeTurnId, + latestTurnId: nextLatestTurnId, updatedAt: event.occurredAt, }); yield* refreshThreadShellSummary(event.payload.threadId); diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 5d7fed78cc..6e2a7efff4 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -50,6 +50,7 @@ import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts"; import Migration0035 from "./Migrations/035_ProjectionProjectsAgentInstance.ts"; import Migration0036 from "./Migrations/036_ProjectionThreadMessageNotification.ts"; import Migration0037 from "./Migrations/037_ProjectionThreadsLatestNotification.ts"; +import Migration0038 from "./Migrations/038_BackfillProjectionThreadsLatestTurn.ts"; /** * Migration loader with all migrations defined inline. @@ -99,6 +100,7 @@ export const migrationEntries = [ [35, "ProjectionProjectsAgentInstance", Migration0035], [36, "ProjectionThreadMessageNotification", Migration0036], [37, "ProjectionThreadsLatestNotification", Migration0037], + [38, "BackfillProjectionThreadsLatestTurn", Migration0038], ] as const; export const makeMigrationLoader = (throughId?: number) => diff --git a/apps/server/src/persistence/Migrations/038_BackfillProjectionThreadsLatestTurn.test.ts b/apps/server/src/persistence/Migrations/038_BackfillProjectionThreadsLatestTurn.test.ts new file mode 100644 index 0000000000..c2095d337f --- /dev/null +++ b/apps/server/src/persistence/Migrations/038_BackfillProjectionThreadsLatestTurn.test.ts @@ -0,0 +1,134 @@ +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; +import * as NodeSqliteClient from "../NodeSqliteClient.ts"; + +const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory())); + +const insertThread = (sql: SqlClient.SqlClient, threadId: string, latestTurnId: string | null) => + sql` + INSERT INTO projection_threads ( + thread_id, + project_id, + title, + model_selection_json, + runtime_mode, + interaction_mode, + branch, + worktree_path, + latest_turn_id, + created_at, + updated_at, + deleted_at + ) + VALUES ( + ${threadId}, + 'project-038', + 'Thread', + '{"instanceId":"hermes-local","model":"hermes"}', + 'full-access', + 'default', + NULL, + NULL, + ${latestTurnId}, + '2026-07-01T00:00:00.000Z', + '2026-07-01T00:00:00.000Z', + NULL + ) + `; + +const insertTurn = ( + sql: SqlClient.SqlClient, + threadId: string, + turnId: string, + requestedAt: string, +) => + sql` + INSERT INTO projection_turns ( + thread_id, + turn_id, + pending_message_id, + assistant_message_id, + state, + requested_at, + started_at, + completed_at, + checkpoint_files_json + ) + VALUES ( + ${threadId}, + ${turnId}, + NULL, + NULL, + 'completed', + ${requestedAt}, + ${requestedAt}, + ${requestedAt}, + '[]' + ) + `; + +const readLatestTurnId = (sql: SqlClient.SqlClient, threadId: string) => + sql<{ readonly latestTurnId: string | null }>` + SELECT latest_turn_id AS "latestTurnId" + FROM projection_threads + WHERE thread_id = ${threadId} + `; + +layer("038_BackfillProjectionThreadsLatestTurn", (it) => { + it.effect("restores the newest turn on a thread whose pointer was nulled at turn end", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 37 }); + + yield* insertThread(sql, "thread-hermes", null); + yield* insertTurn(sql, "thread-hermes", "hermes-turn-old", "2026-07-01T00:00:00.000Z"); + yield* insertTurn(sql, "thread-hermes", "hermes-turn-new", "2026-07-01T00:05:00.000Z"); + + yield* runMigrations({ toMigrationInclusive: 38 }); + + assert.deepStrictEqual(yield* readLatestTurnId(sql, "thread-hermes"), [ + { latestTurnId: "hermes-turn-new" }, + ]); + }), + ); + + it.effect("never overwrites a pointer that is already set", () => + Effect.gen(function* () { + // A correct pointer must survive: the backfill is a heuristic, and the + // projector's own value is authoritative wherever it exists. + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 37 }); + + yield* insertThread(sql, "thread-codex", "turn-kept"); + yield* insertTurn(sql, "thread-codex", "turn-kept", "2026-07-01T00:00:00.000Z"); + yield* insertTurn(sql, "thread-codex", "turn-newer", "2026-07-01T00:09:00.000Z"); + + yield* runMigrations({ toMigrationInclusive: 38 }); + + assert.deepStrictEqual(yield* readLatestTurnId(sql, "thread-codex"), [ + { latestTurnId: "turn-kept" }, + ]); + }), + ); + + it.effect("leaves a thread that has never run a turn at null", () => + Effect.gen(function* () { + // Inventing a turn here would make a fresh thread look like it had + // already run one. + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 37 }); + + yield* insertThread(sql, "thread-empty", null); + + yield* runMigrations({ toMigrationInclusive: 38 }); + + assert.deepStrictEqual(yield* readLatestTurnId(sql, "thread-empty"), [ + { latestTurnId: null }, + ]); + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/038_BackfillProjectionThreadsLatestTurn.ts b/apps/server/src/persistence/Migrations/038_BackfillProjectionThreadsLatestTurn.ts new file mode 100644 index 0000000000..ddf3fc36dc --- /dev/null +++ b/apps/server/src/persistence/Migrations/038_BackfillProjectionThreadsLatestTurn.ts @@ -0,0 +1,51 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as Effect from "effect/Effect"; + +/** + * Repairs `projection_threads.latest_turn_id` rows that were nulled at turn end. + * + * The `thread.session-set` projector wrote `session.activeTurnId` straight + * through, so the session going back to `ready` (activeTurnId `null`) at the + * end of a turn erased the pointer to the turn that had just finished. For + * workspace providers that damage was invisible: `thread.turn-diff-completed` + * fires moments later and re-writes the id. A provider with no workspace + * (Hermes) emits no diff, so the id stayed null permanently — `latestTurn` + * never resolved, and the settle guard read every completed turn as a + * queued-but-unadopted turn start, refusing to settle the thread for the + * length of the adoption grace window. + * + * The projector no longer nulls the field, but rows already written keep the + * stale null: projections resume from their stored sequence rather than + * replaying, so nothing re-derives them. + * + * Restores the newest turn per thread by `requested_at`, matching what the + * projector would have retained. Deliberately conservative: + * + * - Only threads whose `latest_turn_id` is currently null are touched, so a + * correct pointer is never overwritten by this heuristic. + * - Only threads that actually have a turn row are updated; the `WHERE + * EXISTS` keeps a thread that has never run a turn at null rather than + * inventing one. + * - Ties on `requested_at` (possible when a turn is steered within the same + * millisecond) break on `row_id`, which is monotonic per insert. + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + UPDATE projection_threads + SET latest_turn_id = ( + SELECT turns.turn_id + FROM projection_turns turns + WHERE turns.thread_id = projection_threads.thread_id + ORDER BY turns.requested_at DESC, turns.row_id DESC + LIMIT 1 + ) + WHERE projection_threads.latest_turn_id IS NULL + AND EXISTS ( + SELECT 1 + FROM projection_turns turns + WHERE turns.thread_id = projection_threads.thread_id + ) + `; +});