The best way to control Claude Code, Codex and more from any computer or phone
fix(server): block incompatible migration history in preflight (#34773)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Tanav Poswal committed
Nov 12, 2026 at 11:59 UTC
a25654c39663d6d84ee78a1c16950e36872f111a
4 files changed
+115
-38
apps/server/src/cloud/servicePreflight.test.ts
+31
@@ -67,6 +67,37 @@ it.layer(NodeServices.layer)("service preflight database", (it) => {
67
expect(preflight().status).toBe("ready");
68
expect(databaseMigrationHead(databasePath)).toBe(BUILD_MIGRATION_HEAD);
69
70
+ db.prepare("UPDATE effect_sql_migrations SET name = ? WHERE migration_id = ?").run(
71
+ "ForkMigration",
72
+ BUILD_MIGRATION_HEAD,
73
+ );
74
+ const conflict = preflight();
75
+ expect(conflict.status).toBe("blocked");
76
+ expect(conflict.status === "blocked" ? conflict.reason : "").toContain("ForkMigration");
77
+ db.prepare("UPDATE effect_sql_migrations SET name = ? WHERE migration_id = ?").run(
78
+ migrationManifest.at(-1)![1],
79
+ BUILD_MIGRATION_HEAD,
80
+ );
81
+
82
+ // Startup reconciles this V2 preview history, so it must not block an update.
83
+ const preview = path.join(path.dirname(databasePath), "preview.sqlite");
84
+ const previewDb = new NodeSqlite.DatabaseSync(preview);
85
+ previewDb.exec(
86
+ "CREATE TABLE effect_sql_migrations (migration_id INTEGER PRIMARY KEY, name TEXT)",
87
+ );
88
+ const insertPreview = previewDb.prepare("INSERT INTO effect_sql_migrations VALUES (?, ?)");
89
+ for (const [id, name] of migrationManifest.filter(([id]) => id < 53)) {
90
+ insertPreview.run(id, name);
91
+ }
92
+ insertPreview.run(53, "PullRequestFilesViewed");
93
+ insertPreview.run(54, "OrchestrationV2");
94
+ insertPreview.run(55, "RemoveRedundantProjectionIndexes");
95
+ previewDb.close();
96
+ expect(
97
+ runServicePreflight({ databasePath: preview, launcherProtocol: SERVICE_LAUNCHER_PROTOCOL })
98
+ .status,
99
+ ).toBe("ready");
100
+
101
const newerId = Math.max(...migrationManifest.map(([id]) => id)) + 1;
102
insert.run(newerId, "FromNightly");
103
db.close();
apps/server/src/cloud/servicePreflight.ts
+19
-11
@@ -1,5 +1,7 @@
1
import packageJson from "../../package.json" with { type: "json" };
2
import { BUILD_MIGRATION_HEAD, recordedMigrations } from "../persistence/databaseMigrationHead.ts";
3
+import { skippedV2Migrations } from "../persistence/Migrations.ts";
4
+import { reconciledV2PreviewHistory } from "../persistence/reconcileV2PreviewMigration.ts";
5
import {
6
isSupportedLauncherProtocol,
7
SERVICE_LAUNCHER_PROTOCOL,
@@ -41,14 +43,17 @@ export function runServicePreflight(input: {
43
};
44
}
45
44
- const newer = newerRecordedMigrations(input.databasePath);
45
- if (newer === null) {
46
+ const recorded = recordedMigrations(input.databasePath);
47
+ if (recorded === null) {
48
return {
49
status: "blocked",
50
version,
51
reason: `Could not read this database to confirm t3@${version} supports it.`,
52
};
53
}
54
+ const newer = recorded
55
+ .filter(({ id }) => id > BUILD_MIGRATION_HEAD)
56
+ .map(({ id, name }) => `${id}_${name}`);
57
if (newer.length > 0) {
58
return {
59
status: "blocked",
@@ -57,16 +62,19 @@ export function runServicePreflight(input: {
62
};
63
}
64
60
- return { status: "ready", version, launcherProtocol };
61
-}
65
+ // Startup reconciles V2 preview ids before it checks the history, so check what it will see.
66
+ const reconciled = reconciledV2PreviewHistory(recorded);
67
+ const incompatible =
68
+ reconciled === null ? ["an unexpected V2 preview history"] : skippedV2Migrations(reconciled);
69
+ if (incompatible.length > 0) {
70
+ return {
71
+ status: "blocked",
72
+ version,
73
+ reason: `This database has incompatible migration history: ${incompatible.join(", ")}. Start the build that wrote it, or report this migration history so an upgrade path can be added.`,
74
+ };
75
+ }
76
63
-/** Migrations a newer build recorded, or null when the database exists but cannot be read.
64
- * Startup already handles renamed ids this build knows. */
65
-function newerRecordedMigrations(databasePath: string): ReadonlyArray<string> | null {
66
- const recorded = recordedMigrations(databasePath);
67
- return recorded === null
68
- ? null
69
- : recorded.filter(({ id }) => id > BUILD_MIGRATION_HEAD).map(({ id, name }) => `${id}_${name}`);
77
+ return { status: "ready", version, launcherProtocol };
78
}
79
80
export function decodeServicePreflightResult(
apps/server/src/persistence/Migrations.ts
+22
-12
@@ -185,6 +185,24 @@ const makeMigrationLoader = (throughId?: number) =>
185
186
const FIRST_V2_MIGRATION_ID = 55;
187
188
+export function skippedV2Migrations(
189
+ recorded: ReadonlyArray<{ readonly id: number; readonly name: string }>,
190
+ throughId?: number,
191
+): string[] {
192
+ const latestRecordedId = Math.max(0, ...recorded.map((row) => row.id));
193
+ const recordedNames = new Map(recorded.map((row) => [row.id, row.name]));
194
+ return migrationManifest.flatMap(([id, name]) => {
195
+ if (
196
+ id < FIRST_V2_MIGRATION_ID ||
197
+ id > latestRecordedId ||
198
+ (throughId !== undefined && id > throughId)
199
+ )
200
+ return [];
201
+ const recordedName = recordedNames.get(id);
202
+ return recordedName === name ? [] : [`${id}_${name} (recorded: ${recordedName ?? "nothing"})`];
203
+ });
204
+}
205
+
206
// Migrators skip ids up to the highest recorded; reject collisions that would skip V2 schema.
207
const assertV2MigrationsCanRun = Effect.fn("assertV2MigrationsCanRun")(function* (
208
throughId?: number,
@@ -198,19 +216,11 @@ const assertV2MigrationsCanRun = Effect.fn("assertV2MigrationsCanRun")(function*
216
readonly migration_id: number;
217
readonly name: string;
218
}>`SELECT migration_id, name FROM effect_sql_migrations`;
219
+ const skipped = skippedV2Migrations(
220
+ recorded.map((row) => ({ id: row.migration_id, name: row.name })),
221
+ throughId,
222
+ );
223
const latestRecordedId = Math.max(0, ...recorded.map((row) => row.migration_id));
202
- const recordedNames = new Map(recorded.map((row) => [row.migration_id, row.name]));
203
- const skipped = migrationEntries.flatMap(([id, name]) => {
204
- if (
205
- id < FIRST_V2_MIGRATION_ID ||
206
- id > latestRecordedId ||
207
- (throughId !== undefined && id > throughId)
208
- )
209
- return [];
210
- const recordedName = recordedNames.get(id);
211
- if (recordedName === name) return [];
212
- return [`${id}_${name} (recorded: ${recordedName ?? "nothing"})`];
213
- });
224
if (skipped.length === 0) return;
225
return yield* new Migrator.MigrationError({
226
kind: "BadState",
apps/server/src/persistence/reconcileV2PreviewMigration.ts
+43
-15
@@ -5,7 +5,43 @@ import * as SqlClient from "effect/sql/SqlClient";
5
import PullRequestFilesViewed from "./Migrations/053_PullRequestFilesViewed.ts";
6
import AutoSettleDisabledAt from "./Migrations/054_ProjectionThreadsAutoSettleDisabledAt.ts";
7
8
+type MigrationRow = { readonly id: number; readonly name: string };
9
+
10
// Previews used V2 ids 53/54; preserve their schema and import progress while reserving main's ids.
11
+function v2PreviewId(history: ReadonlyArray<MigrationRow>): number | "invalid" | undefined {
12
+ const later = history.filter((row) => row.id >= 53);
13
+ const legacy = later.find(
14
+ (row) => row.name === "OrchestrationV2" && (row.id === 53 || row.id === 54),
15
+ );
16
+ if (!legacy) return undefined;
17
+ const valid = later.every(
18
+ (row) =>
19
+ row === legacy ||
20
+ (legacy.id === 54 &&
21
+ ((row.id === 53 && row.name === "PullRequestFilesViewed") ||
22
+ (row.id === 55 && row.name === "RemoveRedundantProjectionIndexes"))),
23
+ );
24
+ return valid ? legacy.id : "invalid";
25
+}
26
+
27
+/** The history as startup's preview reconciliation leaves it, or null when startup rejects it. */
28
+export function reconciledV2PreviewHistory(
29
+ history: ReadonlyArray<MigrationRow>,
30
+): ReadonlyArray<MigrationRow> | null {
31
+ const previewId = v2PreviewId(history);
32
+ if (previewId === undefined) return history;
33
+ if (previewId === "invalid") return null;
34
+ return [
35
+ ...history.filter((row) => row.id < 53),
36
+ { id: 53, name: "PullRequestFilesViewed" },
37
+ { id: 54, name: "ProjectionThreadsAutoSettleDisabledAt" },
38
+ { id: 55, name: "OrchestrationV2" },
39
+ ...(history.some((row) => row.id === 55)
40
+ ? [{ id: 56, name: "RemoveRedundantProjectionIndexes" }]
41
+ : []),
42
+ ];
43
+}
44
+
45
export const reconcileV2PreviewMigration = Effect.fn("reconcileV2PreviewMigration")(function* () {
46
const sql = yield* SqlClient.SqlClient;
47
return yield* sql.withTransaction(
@@ -17,26 +53,18 @@ export const reconcileV2PreviewMigration = Effect.fn("reconcileV2PreviewMigratio
53
const history = yield* sql<{ readonly migration_id: number; readonly name: string }>`
54
SELECT migration_id, name FROM effect_sql_migrations WHERE migration_id >= 53
55
`;
20
- const legacy = history.find(
21
- (row) =>
22
- row.name === "OrchestrationV2" && (row.migration_id === 53 || row.migration_id === 54),
23
- );
24
- if (!legacy) return [];
25
- const valid = history.every(
26
- (row) =>
27
- row === legacy ||
28
- (legacy.migration_id === 54 &&
29
- ((row.migration_id === 53 && row.name === "PullRequestFilesViewed") ||
30
- (row.migration_id === 55 && row.name === "RemoveRedundantProjectionIndexes"))),
56
+ const previewId = v2PreviewId(
57
+ history.map((row) => ({ id: row.migration_id, name: row.name })),
58
);
32
- if (!valid) {
59
+ if (previewId === undefined) return [];
60
+ if (previewId === "invalid") {
61
return yield* new Migrator.MigrationError({
62
kind: "BadState",
63
message: "Cannot upgrade V2 preview with unexpected later migrations.",
64
});
65
}
66
const executed: Array<readonly [number, string]> = [];
39
- if (legacy.migration_id === 53) {
67
+ if (previewId === 53) {
68
yield* PullRequestFilesViewed;
69
executed.push([53, "PullRequestFilesViewed"]);
70
}
@@ -44,8 +72,8 @@ export const reconcileV2PreviewMigration = Effect.fn("reconcileV2PreviewMigratio
72
executed.push([54, "ProjectionThreadsAutoSettleDisabledAt"]);
73
// Move the later entry first to avoid a primary-key collision.
74
yield* sql`UPDATE effect_sql_migrations SET migration_id = 56 WHERE migration_id = 55 AND name = 'RemoveRedundantProjectionIndexes'`;
47
- yield* sql`UPDATE effect_sql_migrations SET migration_id = 55 WHERE migration_id = ${legacy.migration_id} AND name = 'OrchestrationV2'`;
48
- if (legacy.migration_id === 53) {
75
+ yield* sql`UPDATE effect_sql_migrations SET migration_id = 55 WHERE migration_id = ${previewId} AND name = 'OrchestrationV2'`;
76
+ if (previewId === 53) {
77
yield* sql`INSERT INTO effect_sql_migrations (migration_id, name) VALUES (53, 'PullRequestFilesViewed')`;
78
}
79
yield* sql`INSERT INTO effect_sql_migrations (migration_id, name) VALUES (54, 'ProjectionThreadsAutoSettleDisabledAt')`;