Skip to content

Commit 1458495

Browse files
committed
fix(server): keep unstarted forks on the source's real home and let orphaned latest-turn forks start
An unstarted fork now follows the source's live session, else the source's persisted provider binding, else the selection it inherited. The source's stored modelSelection alone no longer retargets the fork, so a stopped source whose selection moved cannot strand the fork on an instance that never held the conversation. When the source did move, the fork takes the source's current model too, and the pre-start model lock only accepts that exact selection instead of any model on the moved instance. The latest-turn boundary check reads the source head through a query that ignores archive state and treats a deleted source as "cannot have advanced", so side chats that outlive their parent start normally. The first-thread lookup and message search share one top-level predicate: a side chat counts as top-level once its parent is deleted or archived. threadProviderInstanceId in contracts is the single rule for "which instance holds this thread", shared by the normalizer, reactor, and clients.
1 parent a0a1df8 commit 1458495

14 files changed

Lines changed: 612 additions & 63 deletions

‎apps/server/src/checkpointing/CheckpointDiffQuery.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ describe("CheckpointDiffQuery.layer", () => {
108108
}),
109109
getThreadShellById: () => Effect.succeed(Option.none()),
110110
getThreadTurnState: () => Effect.die("unused"),
111+
getForkSourceHead: () => Effect.die("unused"),
111112
getThreadDetailById: () => Effect.succeed(Option.none()),
112113
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
113114
searchThreads: () => Effect.succeed({ matches: [] }),
@@ -204,6 +205,7 @@ describe("CheckpointDiffQuery.layer", () => {
204205
getFullThreadDiffContext: () => Effect.die("unused"),
205206
getThreadShellById: () => Effect.succeed(Option.none()),
206207
getThreadTurnState: () => Effect.die("unused"),
208+
getForkSourceHead: () => Effect.die("unused"),
207209
getThreadDetailById: () => Effect.succeed(Option.none()),
208210
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
209211
searchThreads: () => Effect.succeed({ matches: [] }),
@@ -290,6 +292,7 @@ describe("CheckpointDiffQuery.layer", () => {
290292
getFullThreadDiffContext: () => Effect.die("unused"),
291293
getThreadShellById: () => Effect.succeed(Option.none()),
292294
getThreadTurnState: () => Effect.die("unused"),
295+
getForkSourceHead: () => Effect.die("unused"),
293296
getThreadDetailById: () => Effect.succeed(Option.none()),
294297
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
295298
searchThreads: () => Effect.succeed({ matches: [] }),
@@ -361,6 +364,7 @@ describe("CheckpointDiffQuery.layer", () => {
361364
getFullThreadDiffContext: () => Effect.die("unused"),
362365
getThreadShellById: () => Effect.succeed(Option.none()),
363366
getThreadTurnState: () => Effect.die("unused"),
367+
getForkSourceHead: () => Effect.die("unused"),
364368
getThreadDetailById: () => Effect.succeed(Option.none()),
365369
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
366370
searchThreads: () => Effect.succeed({ matches: [] }),
@@ -417,6 +421,7 @@ describe("CheckpointDiffQuery.layer", () => {
417421
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
418422
getThreadShellById: () => Effect.succeed(Option.none()),
419423
getThreadTurnState: () => Effect.die("unused"),
424+
getForkSourceHead: () => Effect.die("unused"),
420425
getThreadDetailById: () => Effect.succeed(Option.none()),
421426
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
422427
searchThreads: () => Effect.succeed({ matches: [] }),

‎apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,7 @@ describe("OrchestrationEngine", () => {
214214
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
215215
getThreadShellById: () => Effect.succeed(Option.none()),
216216
getThreadTurnState: () => Effect.die("unused"),
217+
getForkSourceHead: () => Effect.die("unused"),
217218
getThreadDetailById: () => Effect.succeed(Option.none()),
218219
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
219220
searchThreads: () => Effect.succeed({ matches: [] }),

‎apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts‎

Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1034,6 +1034,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
10341034
interaction_mode,
10351035
branch,
10361036
worktree_path,
1037+
fork_json,
10371038
side_chat,
10381039
latest_turn_id,
10391040
created_at,
@@ -1050,6 +1051,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
10501051
'default',
10511052
NULL,
10521053
NULL,
1054+
'{"sourceThreadId":"thread-first","sourceTurnId":null,"sourceMessageId":null,"forkedAt":"2026-03-01T00:00:04.000Z"}',
10531055
1,
10541056
NULL,
10551057
'2026-03-01T00:00:04.000Z',
@@ -1067,6 +1069,183 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
10671069
assert.equal(firstThreadId.value, ThreadId.make("thread-first"));
10681070
assert.notEqual(firstThreadId.value, ThreadId.make("thread-side-chat-first"));
10691071
}
1072+
1073+
// A side chat whose parent is gone is an ordinary thread again and
1074+
// counts as the project's first thread when it is the oldest.
1075+
yield* sql`
1076+
INSERT INTO projection_threads (
1077+
thread_id,
1078+
project_id,
1079+
title,
1080+
model_selection_json,
1081+
runtime_mode,
1082+
interaction_mode,
1083+
branch,
1084+
worktree_path,
1085+
fork_json,
1086+
side_chat,
1087+
latest_turn_id,
1088+
created_at,
1089+
updated_at,
1090+
archived_at,
1091+
deleted_at
1092+
)
1093+
VALUES (
1094+
'thread-orphan-side-chat-first',
1095+
'project-active',
1096+
'Orphaned Side Chat',
1097+
'{"provider":"codex","model":"gpt-5-codex"}',
1098+
'full-access',
1099+
'default',
1100+
NULL,
1101+
NULL,
1102+
'{"sourceThreadId":"thread-deleted","sourceTurnId":null,"sourceMessageId":null,"forkedAt":"2026-03-01T00:00:03.000Z"}',
1103+
1,
1104+
NULL,
1105+
'2026-03-01T00:00:03.000Z',
1106+
'2026-03-01T00:00:03.000Z',
1107+
NULL,
1108+
NULL
1109+
)
1110+
`;
1111+
1112+
const orphanFirst = yield* snapshotQuery.getFirstActiveThreadIdByProjectId(
1113+
asProjectId("project-active"),
1114+
);
1115+
assert.deepStrictEqual(
1116+
Option.getOrUndefined(orphanFirst),
1117+
ThreadId.make("thread-orphan-side-chat-first"),
1118+
);
1119+
}),
1120+
);
1121+
1122+
it.effect(
1123+
"reads a fork source's head across archive state and reports deleted sources as gone",
1124+
() =>
1125+
Effect.gen(function* () {
1126+
const snapshotQuery = yield* ProjectionSnapshotQuery;
1127+
const sql = yield* SqlClient.SqlClient;
1128+
1129+
yield* sql`DELETE FROM projection_threads`;
1130+
yield* sql`DELETE FROM projection_turns`;
1131+
yield* sql`
1132+
INSERT INTO projection_threads (
1133+
thread_id,
1134+
project_id,
1135+
title,
1136+
model_selection_json,
1137+
runtime_mode,
1138+
interaction_mode,
1139+
branch,
1140+
worktree_path,
1141+
latest_turn_id,
1142+
created_at,
1143+
updated_at,
1144+
archived_at,
1145+
deleted_at
1146+
)
1147+
VALUES
1148+
(
1149+
'thread-archived-source',
1150+
'project-fork',
1151+
'Archived Source',
1152+
'{"provider":"codex","model":"gpt-5-codex"}',
1153+
'full-access',
1154+
'default',
1155+
NULL,
1156+
NULL,
1157+
'turn-archived-head',
1158+
'2026-09-03T12:00:00.000Z',
1159+
'2026-09-03T12:00:02.000Z',
1160+
'2026-09-03T12:00:03.000Z',
1161+
NULL
1162+
),
1163+
(
1164+
'thread-headless-source',
1165+
'project-fork',
1166+
'Headless Source',
1167+
'{"provider":"codex","model":"gpt-5-codex"}',
1168+
'full-access',
1169+
'default',
1170+
NULL,
1171+
NULL,
1172+
NULL,
1173+
'2026-09-03T12:00:00.000Z',
1174+
'2026-09-03T12:00:00.000Z',
1175+
NULL,
1176+
NULL
1177+
),
1178+
(
1179+
'thread-deleted-source',
1180+
'project-fork',
1181+
'Deleted Source',
1182+
'{"provider":"codex","model":"gpt-5-codex"}',
1183+
'full-access',
1184+
'default',
1185+
NULL,
1186+
NULL,
1187+
NULL,
1188+
'2026-09-03T12:00:00.000Z',
1189+
'2026-09-03T12:00:04.000Z',
1190+
NULL,
1191+
'2026-09-03T12:00:04.000Z'
1192+
)
1193+
`;
1194+
yield* sql`
1195+
INSERT INTO projection_turns (
1196+
thread_id,
1197+
turn_id,
1198+
pending_message_id,
1199+
source_proposed_plan_thread_id,
1200+
source_proposed_plan_id,
1201+
assistant_message_id,
1202+
state,
1203+
requested_at,
1204+
started_at,
1205+
completed_at,
1206+
checkpoint_turn_count,
1207+
checkpoint_ref,
1208+
checkpoint_status,
1209+
checkpoint_files_json
1210+
)
1211+
VALUES (
1212+
'thread-archived-source',
1213+
'turn-archived-head',
1214+
NULL,
1215+
NULL,
1216+
NULL,
1217+
'message-archived-head',
1218+
'completed',
1219+
'2026-09-03T12:00:01.000Z',
1220+
'2026-09-03T12:00:01.000Z',
1221+
'2026-09-03T12:00:02.000Z',
1222+
NULL,
1223+
NULL,
1224+
NULL,
1225+
'[]'
1226+
)
1227+
`;
1228+
1229+
assert.deepStrictEqual(
1230+
Option.getOrUndefined(
1231+
yield* snapshotQuery.getForkSourceHead(ThreadId.make("thread-archived-source")),
1232+
),
1233+
{ latestTurn: { turnId: TurnId.make("turn-archived-head"), state: "completed" } },
1234+
);
1235+
assert.deepStrictEqual(
1236+
Option.getOrUndefined(
1237+
yield* snapshotQuery.getForkSourceHead(ThreadId.make("thread-headless-source")),
1238+
),
1239+
{ latestTurn: null },
1240+
);
1241+
assert.isTrue(
1242+
Option.isNone(
1243+
yield* snapshotQuery.getForkSourceHead(ThreadId.make("thread-deleted-source")),
1244+
),
1245+
);
1246+
assert.isTrue(
1247+
Option.isNone(yield* snapshotQuery.getForkSourceHead(ThreadId.make("thread-missing"))),
1248+
);
10701249
}),
10711250
);
10721251

‎apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts‎

Lines changed: 66 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,10 @@ const ProjectionThreadTurnStateRowSchema = Schema.Struct({
172172
state: ProjectionTurnState,
173173
assistantMessageId: Schema.NullOr(MessageId),
174174
});
175+
const ProjectionForkSourceHeadRowSchema = Schema.Struct({
176+
latestTurnId: Schema.NullOr(TurnId),
177+
latestTurnState: Schema.NullOr(ProjectionTurnState),
178+
});
175179
const ThreadActivityKindsLookupInput = Schema.Struct({
176180
threadId: ThreadId,
177181
activityKinds: Schema.Array(Schema.String),
@@ -410,6 +414,22 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
410414
const threadBackgroundLiveness = yield* ThreadBackgroundLivenessService;
411415
const threadPlanProgress = yield* ThreadPlanProgressService;
412416
const sql = yield* SqlClient.SqlClient;
417+
418+
// A thread is top-level unless it is a side chat whose parent is still
419+
// active. Side chats outlive a deleted or archived parent as ordinary
420+
// threads, so every "which threads does this project show" read shares
421+
// this predicate. Expects the outer query to alias projection_threads as
422+
// `threads`.
423+
const topLevelThreadPredicate = sql`(
424+
threads.side_chat = 0
425+
OR NOT EXISTS (
426+
SELECT 1
427+
FROM projection_threads AS parents
428+
WHERE parents.thread_id = json_extract(threads.fork_json, '$.sourceThreadId')
429+
AND parents.deleted_at IS NULL
430+
AND parents.archived_at IS NULL
431+
)
432+
)`;
413433
const repositoryIdentityResolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
414434
const repositoryIdentityResolutionConcurrency = 4;
415435
const resolveRepositoryIdentitiesForProjects = Effect.fn(
@@ -896,16 +916,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
896916
ON projects.project_id = threads.project_id
897917
WHERE threads.deleted_at IS NULL
898918
AND threads.archived_at IS NULL
899-
AND (
900-
threads.side_chat = 0
901-
OR NOT EXISTS (
902-
SELECT 1
903-
FROM projection_threads AS parents
904-
WHERE parents.thread_id = json_extract(threads.fork_json, '$.sourceThreadId')
905-
AND parents.deleted_at IS NULL
906-
AND parents.archived_at IS NULL
907-
)
908-
)
919+
AND ${topLevelThreadPredicate}
909920
AND projects.deleted_at IS NULL
910921
AND messages.is_streaming = 0
911922
AND (
@@ -994,13 +1005,13 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
9941005
execute: ({ projectId }) =>
9951006
sql`
9961007
SELECT
997-
thread_id AS "threadId"
998-
FROM projection_threads
999-
WHERE project_id = ${projectId}
1000-
AND deleted_at IS NULL
1001-
AND archived_at IS NULL
1002-
AND side_chat = 0
1003-
ORDER BY created_at ASC, thread_id ASC
1008+
threads.thread_id AS "threadId"
1009+
FROM projection_threads threads
1010+
WHERE threads.project_id = ${projectId}
1011+
AND threads.deleted_at IS NULL
1012+
AND threads.archived_at IS NULL
1013+
AND ${topLevelThreadPredicate}
1014+
ORDER BY threads.created_at ASC, threads.thread_id ASC
10041015
LIMIT 1
10051016
`,
10061017
});
@@ -1290,6 +1301,25 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
12901301
`,
12911302
});
12921303

1304+
// Archived sources keep their head; only a deleted row disappears.
1305+
const getForkSourceHeadRow = SqlSchema.findOneOption({
1306+
Request: ThreadIdLookupInput,
1307+
Result: ProjectionForkSourceHeadRowSchema,
1308+
execute: ({ threadId }) =>
1309+
sql`
1310+
SELECT
1311+
threads.latest_turn_id AS "latestTurnId",
1312+
turns.state AS "latestTurnState"
1313+
FROM projection_threads threads
1314+
LEFT JOIN projection_turns turns
1315+
ON turns.thread_id = threads.thread_id
1316+
AND turns.turn_id = threads.latest_turn_id
1317+
WHERE threads.thread_id = ${threadId}
1318+
AND threads.deleted_at IS NULL
1319+
LIMIT 1
1320+
`,
1321+
});
1322+
12931323
const listCheckpointRowsByThread = SqlSchema.findAll({
12941324
Request: ThreadIdLookupInput,
12951325
Result: ProjectionCheckpointDbRowSchema,
@@ -2784,6 +2814,24 @@ pending_approval_requests AS (
27842814
} satisfies OrchestrationThreadShell);
27852815
});
27862816

2817+
const getForkSourceHead: ProjectionSnapshotQueryShape["getForkSourceHead"] = (threadId) =>
2818+
getForkSourceHeadRow({ threadId }).pipe(
2819+
Effect.mapError(
2820+
toPersistenceSqlOrDecodeError(
2821+
"ProjectionSnapshotQuery.getForkSourceHead:query",
2822+
"ProjectionSnapshotQuery.getForkSourceHead:decodeRow",
2823+
),
2824+
),
2825+
Effect.map(
2826+
Option.map((row) => ({
2827+
latestTurn:
2828+
row.latestTurnId !== null && row.latestTurnState !== null
2829+
? { turnId: row.latestTurnId, state: row.latestTurnState }
2830+
: null,
2831+
})),
2832+
),
2833+
);
2834+
27872835
const getThreadTurnState: ProjectionSnapshotQueryShape["getThreadTurnState"] = (
27882836
threadId,
27892837
turnId,
@@ -3235,6 +3283,7 @@ pending_approval_requests AS (
32353283
getFullThreadDiffContext,
32363284
getThreadShellById,
32373285
getThreadTurnState,
3286+
getForkSourceHead,
32383287
getThreadDetailById,
32393288
getThreadDetailSnapshot,
32403289
} satisfies ProjectionSnapshotQueryShape;

0 commit comments

Comments
 (0)