Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Migrations.ts

370 lines19.8 KB

1import * as Migrator from "effect/sql/Migrator";
2import * as Effect from "effect/Effect";
3import * as SqlClient from "effect/sql/SqlClient";
4import {
5 DATABASE_MIGRATION_PROGRESS_MESSAGE,
6 DATABASE_MIGRATIONS_FINISHED_MESSAGE,
7 DATABASE_MIGRATIONS_STARTED_MESSAGE,
8} from "@t3tools/shared/databaseMigrationLog";
9import { reconcileV2PreviewMigration } from "./reconcileV2PreviewMigration.ts";
10​
11import Migration0001 from "./Migrations/001_OrchestrationEvents.ts";
12import Migration0002 from "./Migrations/002_OrchestrationCommandReceipts.ts";
13import Migration0003 from "./Migrations/003_CheckpointDiffBlobs.ts";
14import Migration0004 from "./Migrations/004_ProviderSessionRuntime.ts";
15import Migration0005 from "./Migrations/005_Projections.ts";
16import Migration0006 from "./Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts";
17import Migration0007 from "./Migrations/007_ProjectionThreadMessageAttachments.ts";
18import Migration0008 from "./Migrations/008_ProjectionThreadActivitySequence.ts";
19import Migration0009 from "./Migrations/009_ProviderSessionRuntimeMode.ts";
20import Migration0010 from "./Migrations/010_ProjectionThreadsRuntimeMode.ts";
21import Migration0011 from "./Migrations/011_OrchestrationThreadCreatedRuntimeMode.ts";
22import Migration0012 from "./Migrations/012_ProjectionThreadsInteractionMode.ts";
23import Migration0013 from "./Migrations/013_ProjectionThreadProposedPlans.ts";
24import Migration0014 from "./Migrations/014_ProjectionThreadProposedPlanImplementation.ts";
25import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts";
26import Migration0016 from "./Migrations/016_CanonicalizeModelSelections.ts";
27import Migration0017 from "./Migrations/017_ProjectionThreadsArchivedAt.ts";
28import Migration0018 from "./Migrations/018_ProjectionThreadsArchivedAtIndex.ts";
29import Migration0019 from "./Migrations/019_ProjectionSnapshotLookupIndexes.ts";
30import Migration0020 from "./Migrations/020_AuthAccessManagement.ts";
31import Migration0021 from "./Migrations/021_AuthSessionClientMetadata.ts";
32import Migration0022 from "./Migrations/022_AuthSessionLastConnectedAt.ts";
33import Migration0023 from "./Migrations/023_ProjectionThreadShellSummary.ts";
34import Migration0024 from "./Migrations/024_BackfillProjectionThreadShellSummary.ts";
35import Migration0025 from "./Migrations/025_CleanupInvalidProjectionPendingApprovals.ts";
36import Migration0026 from "./Migrations/026_CanonicalizeModelSelectionOptions.ts";
37import Migration0027 from "./Migrations/027_ProviderSessionRuntimeInstanceId.ts";
38import Migration0028 from "./Migrations/028_ProjectionThreadSessionInstanceId.ts";
39import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexes.ts";
40import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.ts";
41import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
42import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
43import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
44import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";
45import Migration0035 from "./Migrations/035_ProjectionThreadTitleRegeneration.ts";
46import Migration0036 from "./Migrations/036_ProjectionThreadsPinned.ts";
47import Migration0037 from "./Migrations/037_ProjectionTurnsKeysetIndex.ts";
48import Migration0038 from "./Migrations/038_ProjectionThreadsPinOrderKey.ts";
49import Migration0039 from "./Migrations/039_ProjectionProjectsDefaultThreadEnvMode.ts";
50import Migration0040 from "./Migrations/040_ProjectionProjectFaviconPath.ts";
51import Migration0041 from "./Migrations/041_AuthSessionClientConnection.ts";
52import Migration0042 from "./Migrations/042_ProjectionThreadLinkedPullRequest.ts";
53import Migration0043 from "./Migrations/043_ProjectionThreadsUnsettledAt.ts";
54import Migration0044 from "./Migrations/044_ClearAutomaticProjectModelDefaults.ts";
55import Migration0045 from "./Migrations/045_ProjectionProjectsAutoPull.ts";
56import Migration0046 from "./Migrations/046_RepairAutomaticSettlementTimestamps.ts";
57import Migration0047 from "./Migrations/047_ProjectionProjectIcon.ts";
58import Migration0048 from "./Migrations/048_ProjectionThreadBranchPullRequest.ts";
59import Migration0049 from "./Migrations/049_ProjectionThreadsActiveOrderKey.ts";
60import Migration0050 from "./Migrations/050_ProjectionThreadPullRequests.ts";
61import Migration0051 from "./Migrations/051_ProjectionThreadMessageContext.ts";
62import Migration0052 from "./Migrations/052_ProjectionThreadTitleState.ts";
63import Migration0053 from "./Migrations/053_PullRequestFilesViewed.ts";
64import Migration0054 from "./Migrations/054_ProjectionThreadsAutoSettleDisabledAt.ts";
65import Migration0055 from "./Migrations/055_OrchestrationV2.ts";
66import Migration0056 from "./Migrations/056_RemoveRedundantProjectionIndexes.ts";
67import Migration0057 from "./Migrations/057_ScheduledTaskWebhooks.ts";
68import Migration0058 from "./Migrations/058_WebhookRelayDeliveries.ts";
69import Migration0059 from "./Migrations/059_McpAppModelContext.ts";
70import Migration0060 from "./Migrations/060_ThreadSnapshotWindowIndexes.ts";
71import Migration0061 from "./Migrations/061_PullRequestReviewGuides.ts";
72import Migration0062 from "./Migrations/062_ThreadFailureLookupIndex.ts";
73import Migration0063 from "./Migrations/063_DropUnusedV1Projections.ts";
74import Migration0064 from "./Migrations/064_CanonicalizeThreadPullRequestLinks.ts";
75import Migration0065 from "./Migrations/065_CodexUsageNativeTurnIndex.ts";
76import Migration0066 from "./Migrations/066_RepairClientSettlementTimestamps.ts";
77import Migration0067 from "./Migrations/067_WebhookDedupe.ts";
78import Migration0068 from "./Migrations/068_ShellStopRequestIndex.ts";
79import Migration0069 from "./Migrations/069_ThreadMessageSearch.ts";
80import Migration0070 from "./Migrations/070_PeerLinks.ts";
81import Migration0071 from "./Migrations/071_PeerLinkFence.ts";
82import Migration0072 from "./Migrations/072_WaitingLinkRequestIndex.ts";
83import Migration0073 from "./Migrations/073_ActiveTurnItemIndexes.ts";
84import Migration0074 from "./Migrations/074_ExcludeAttachmentPlaceholdersFromSearch.ts";
85import Migration0075 from "./Migrations/075_SubagentDeliveryState.ts";
86import Migration0076 from "./Migrations/076_ProjectionProjectsPinArchive.ts";
87import Migration0077 from "./Migrations/077_RepairBooleanSettledOverride.ts";
88import Migration0078 from "./Migrations/078_DropOrchestrationEventCorrelationIndex.ts";
89import Migration0079 from "./Migrations/079_DelegatedRecoveryIndexes.ts";
90import Migration0080 from "./Migrations/080_ScheduledTaskThreadMode.ts";
91import Migration0081 from "./Migrations/081_ProjectionMessageSearchText.ts";
92import Migration0082 from "./Migrations/082_TurnItemConversationIndex.ts";
93import Migration0083 from "./Migrations/083_CommandReadIndexes.ts";
94import Migration0084 from "./Migrations/084_LastExecutedRunIndex.ts";
95import Migration0085 from "./Migrations/085_TurnItemCounts.ts";
96import Migration0086 from "./Migrations/086_QueuedTurnInputIndex.ts";
97import Migration0087 from "./Migrations/087_ProjectionProjectsCustomTitle.ts";
98import Migration0088 from "./Migrations/088_TurnItemTypeStatusIndex.ts";
99import Migration0089 from "./Migrations/089_ShellThreadReadIndexes.ts";
100import Migration0090 from "./Migrations/090_AuthConnectDevices.ts";
101import Migration0091 from "./Migrations/091_AuthConnectDeniedRequests.ts";
102import Migration0092 from "./Migrations/092_QueuedTurnInputIndexJsonValid.ts";
103import Migration0093 from "./Migrations/093_ProviderTurnAttemptIndex.ts";
104import Migration0094 from "./Migrations/094_TurnItemMessageOrdinalIndex.ts";
105import Migration0095 from "./Migrations/095_TurnItemInlineWorkOutput.ts";
106import Migration0096 from "./Migrations/096_RepairStaleTitleRegeneration.ts";
107import Migration0097 from "./Migrations/097_IssueTrackerBindings.ts";
108import Migration0098 from "./Migrations/098_ActiveShellIndexIndexes.ts";
109import Migration0099 from "./Migrations/099_BackgroundRecoveryIndexes.ts";
110import Migration0100 from "./Migrations/100_TurnStartReadIndexes.ts";
111import Migration0101 from "./Migrations/101_DelegatedTaskReadIndexes.ts";
112import Migration0102 from "./Migrations/102_ThreadItemCounts.ts";
113import Migration0103 from "./Migrations/103_IssueTrackerAdditionalScopes.ts";
114​
115const migrationEntries = [
116 [1, "OrchestrationEvents", Migration0001],
117 [2, "OrchestrationCommandReceipts", Migration0002],
118 [3, "CheckpointDiffBlobs", Migration0003],
119 [4, "ProviderSessionRuntime", Migration0004],
120 [5, "Projections", Migration0005],
121 [6, "ProjectionThreadSessionRuntimeModeColumns", Migration0006],
122 [7, "ProjectionThreadMessageAttachments", Migration0007],
123 [8, "ProjectionThreadActivitySequence", Migration0008],
124 [9, "ProviderSessionRuntimeMode", Migration0009],
125 [10, "ProjectionThreadsRuntimeMode", Migration0010],
126 [11, "OrchestrationThreadCreatedRuntimeMode", Migration0011],
127 [12, "ProjectionThreadsInteractionMode", Migration0012],
128 [13, "ProjectionThreadProposedPlans", Migration0013],
129 [14, "ProjectionThreadProposedPlanImplementation", Migration0014],
130 [15, "ProjectionTurnsSourceProposedPlan", Migration0015],
131 [16, "CanonicalizeModelSelections", Migration0016],
132 [17, "ProjectionThreadsArchivedAt", Migration0017],
133 [18, "ProjectionThreadsArchivedAtIndex", Migration0018],
134 [19, "ProjectionSnapshotLookupIndexes", Migration0019],
135 [20, "AuthAccessManagement", Migration0020],
136 [21, "AuthSessionClientMetadata", Migration0021],
137 [22, "AuthSessionLastConnectedAt", Migration0022],
138 [23, "ProjectionThreadShellSummary", Migration0023],
139 [24, "BackfillProjectionThreadShellSummary", Migration0024],
140 [25, "CleanupInvalidProjectionPendingApprovals", Migration0025],
141 [26, "CanonicalizeModelSelectionOptions", Migration0026],
142 [27, "ProviderSessionRuntimeInstanceId", Migration0027],
143 [28, "ProjectionThreadSessionInstanceId", Migration0028],
144 [29, "ProjectionThreadDetailOrderingIndexes", Migration0029],
145 [30, "ProjectionThreadShellArchiveIndexes", Migration0030],
146 [31, "AuthAuthorizationScopes", Migration0031],
147 [32, "AuthPairingProofKeyThumbprint", Migration0032],
148 [33, "ProjectionThreadsSettled", Migration0033],
149 [34, "ProjectionThreadsSnoozed", Migration0034],
150 [35, "ProjectionThreadTitleRegeneration", Migration0035],
151 [36, "ProjectionThreadsPinned", Migration0036],
152 [37, "ProjectionTurnsKeysetIndex", Migration0037],
153 [38, "ProjectionThreadsPinOrderKey", Migration0038],
154 [39, "ProjectionProjectsDefaultThreadEnvMode", Migration0039],
155 [40, "ProjectionProjectFaviconPath", Migration0040],
156 [41, "AuthSessionClientConnection", Migration0041],
157 [42, "ProjectionThreadLinkedPullRequest", Migration0042],
158 [43, "ProjectionThreadsUnsettledAt", Migration0043],
159 [44, "ClearAutomaticProjectModelDefaults", Migration0044],
160 [45, "ProjectionProjectsAutoPull", Migration0045],
161 [46, "RepairAutomaticSettlementTimestamps", Migration0046],
162 [47, "ProjectionProjectIcon", Migration0047],
163 [48, "ProjectionThreadBranchPullRequest", Migration0048],
164 [49, "ProjectionThreadsActiveOrderKey", Migration0049],
165 [50, "ProjectionThreadPullRequests", Migration0050],
166 [51, "ProjectionThreadMessageContext", Migration0051],
167 [52, "ProjectionThreadTitleState", Migration0052],
168 [53, "PullRequestFilesViewed", Migration0053],
169 [54, "ProjectionThreadsAutoSettleDisabledAt", Migration0054],
170 // Preserve this migration's schema. Future V2 schema changes need new migrations.
171 [55, "OrchestrationV2", Migration0055],
172 [56, "RemoveRedundantProjectionIndexes", Migration0056],
173 [57, "ScheduledTaskWebhooks", Migration0057],
174 [58, "WebhookRelayDeliveries", Migration0058],
175 [59, "McpAppModelContext", Migration0059],
176 [60, "ThreadSnapshotWindowIndexes", Migration0060],
177 [61, "PullRequestReviewGuides", Migration0061],
178 [62, "ThreadFailureLookupIndex", Migration0062],
179 [63, "DropUnusedV1Projections", Migration0063],
180 [64, "CanonicalizeThreadPullRequestLinks", Migration0064],
181 [65, "CodexUsageNativeTurnIndex", Migration0065],
182 [66, "RepairClientSettlementTimestamps", Migration0066],
183 [67, "WebhookDedupe", Migration0067],
184 [68, "ShellStopRequestIndex", Migration0068],
185 [69, "ThreadMessageSearch", Migration0069],
186 [70, "PeerLinks", Migration0070],
187 [71, "PeerLinkFence", Migration0071],
188 [72, "WaitingLinkRequestIndex", Migration0072],
189 [73, "ActiveTurnItemIndexes", Migration0073],
190 [74, "ExcludeAttachmentPlaceholdersFromSearch", Migration0074],
191 [75, "SubagentDeliveryState", Migration0075],
192 [76, "ProjectionProjectsPinArchive", Migration0076],
193 [77, "RepairBooleanSettledOverride", Migration0077],
194 [78, "DropOrchestrationEventCorrelationIndex", Migration0078],
195 [79, "DelegatedRecoveryIndexes", Migration0079],
196 [80, "ScheduledTaskThreadMode", Migration0080],
197 [81, "ProjectionMessageSearchText", Migration0081],
198 [82, "TurnItemConversationIndex", Migration0082],
199 [83, "CommandReadIndexes", Migration0083],
200 [84, "LastExecutedRunIndex", Migration0084],
201 [85, "TurnItemCounts", Migration0085],
202 [86, "QueuedTurnInputIndex", Migration0086],
203 [87, "ProjectionProjectsCustomTitle", Migration0087],
204 [88, "TurnItemTypeStatusIndex", Migration0088],
205 [89, "ShellThreadReadIndexes", Migration0089],
206 [90, "AuthConnectDevices", Migration0090],
207 [91, "AuthConnectDeniedRequests", Migration0091],
208 [92, "QueuedTurnInputIndexJsonValid", Migration0092],
209 [93, "ProviderTurnAttemptIndex", Migration0093],
210 [94, "TurnItemMessageOrdinalIndex", Migration0094],
211 [95, "TurnItemInlineWorkOutput", Migration0095],
212 [96, "RepairStaleTitleRegeneration", Migration0096],
213 [97, "IssueTrackerBindings", Migration0097],
214 [98, "ActiveShellIndexIndexes", Migration0098],
215 [99, "BackgroundRecoveryIndexes", Migration0099],
216 [100, "TurnStartReadIndexes", Migration0100],
217 [101, "DelegatedTaskReadIndexes", Migration0101],
218 [102, "ThreadItemCounts", Migration0102],
219 [103, "IssueTrackerAdditionalScopes", Migration0103],
220] as const;
221​
222export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
223​
224const makeMigrationLoader = (throughId?: number) =>
225 Migrator.fromRecord(
226 Object.fromEntries(
227 migrationEntries
228 .filter(([id]) => throughId === undefined || id <= throughId)
229 .map(([id, name, migration]) => [`${id}_${name}`, migration]),
230 ),
231 );
232​
233const FIRST_V2_MIGRATION_ID = 55;
234​
235export function skippedV2Migrations(
236 recorded: ReadonlyArray<{ readonly id: number; readonly name: string }>,
237 throughId?: number,
238): string[] {
239 const latestRecordedId = Math.max(0, ...recorded.map((row) => row.id));
240 const recordedNames = new Map(recorded.map((row) => [row.id, row.name]));
241 return migrationManifest.flatMap(([id, name]) => {
242 if (
243 id < FIRST_V2_MIGRATION_ID ||
244 id > latestRecordedId ||
245 (throughId !== undefined && id > throughId)
246 )
247 return [];
248 const recordedName = recordedNames.get(id);
249 return recordedName === name ? [] : [`${id}_${name} (recorded: ${recordedName ?? "nothing"})`];
250 });
252​
253// Migrators skip ids up to the highest recorded; reject collisions that would skip V2 schema.
254const assertV2MigrationsCanRun = Effect.fn("assertV2MigrationsCanRun")(function* (
255 throughId?: number,
256) {
257 const sql = yield* SqlClient.SqlClient;
258 const tables = yield* sql`
259 SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'effect_sql_migrations'
260 `;
261 if (tables.length === 0) return;
262 const recorded = yield* sql<{
263 readonly migration_id: number;
264 readonly name: string;
265 }>`SELECT migration_id, name FROM effect_sql_migrations`;
266 const skipped = skippedV2Migrations(
267 recorded.map((row) => ({ id: row.migration_id, name: row.name })),
268 throughId,
269 );
270 const latestRecordedId = Math.max(0, ...recorded.map((row) => row.migration_id));
271 if (skipped.length === 0) return;
272 return yield* new Migrator.MigrationError({
273 kind: "BadState",
274 message: `This database's migration history would skip required schema migrations: ${skipped.join(", ")}. The migrator skips every id up to the highest recorded id (${latestRecordedId}), regardless of name. It was probably written by a different build. Start the build that wrote it, or report this migration history so an upgrade path can be added.`,
275 });
276});
277​
278const latestMigrationId = Math.max(...migrationEntries.map(([id]) => id));
279​
280// Mirrors the Migrator, which runs only ids above the highest recorded, plus the V2-preview reconciliation.
281export const hasPendingMigrations = Effect.fn("hasPendingMigrations")(function* () {
282 const sql = yield* SqlClient.SqlClient;
283 const tables = yield* sql`
284 SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'effect_sql_migrations'
285 `;
286 if (tables.length === 0) return true;
287 const rows = yield* sql<{ readonly latestId: number | null; readonly previewRows: number }>`
288 SELECT
289 MAX(migration_id) AS latestId,
290 SUM(name = 'OrchestrationV2' AND migration_id IN (53, 54)) AS previewRows
291 FROM effect_sql_migrations
292 `;
293 const row = rows[0];
294 return (row?.latestId ?? 0) < latestMigrationId || (row?.previewRows ?? 0) > 0;
295});
296​
297const run = Migrator.make({});
298​
299export interface RunMigrationsOptions {
300 readonly toMigrationInclusive?: number | undefined;
302​
303export const runMigrations = Effect.fn("runMigrations")(function* ({
304 toMigrationInclusive,
305}: RunMigrationsOptions = {}) {
306 // The desktop waits past its readiness budget until the finished line follows this one.
307 const hasPending = yield* hasPendingMigrations();
308 if (hasPending) yield* Effect.log(DATABASE_MIGRATIONS_STARTED_MESSAGE);
309 const includesV2 =
310 toMigrationInclusive === undefined || toMigrationInclusive >= FIRST_V2_MIGRATION_ID;
311 // The reconcile takes the write lock; CLI startup must not contend with the server for a no-op.
312 const previewMigrations = includesV2 && hasPending ? yield* reconcileV2PreviewMigration() : [];
313 if (includesV2) {
314 yield* assertV2MigrationsCanRun(toMigrationInclusive);
315 }
316 const sql = yield* SqlClient.SqlClient;
317 const ledger = yield* sql`
318 SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'effect_sql_migrations'
319 `;
320 const [latest] =
321 ledger.length === 0
322 ? []
323 : yield* sql<{
324 readonly id: number | null;
325 }>`SELECT MAX(migration_id) AS id FROM effect_sql_migrations`;
326 const latestRecordedId = latest?.id ?? 0;
327 const pending = migrationEntries.filter(
328 ([id]) =>
329 id > latestRecordedId && (toMigrationInclusive === undefined || id <= toMigrationInclusive),
330 );
331 // One transaction per migration: an index build on a large database can take minutes, and a
332 // restart then resumes after the last finished migration instead of rolling all of them back.
333 const executedMigrations: Array<readonly [id: number, name: string]> = [...previewMigrations];
334 for (const [index, [id, name]] of pending.entries()) {
335 if (latestRecordedId > 0) {
336 yield* Effect.log(DATABASE_MIGRATION_PROGRESS_MESSAGE).pipe(
337 Effect.annotateLogs({
338 migration: `${id}_${name}`,
339 progress: `${index + 1} of ${pending.length}`,
340 }),
341 );
342 }
343 executedMigrations.push(...(yield* run({ loader: makeMigrationLoader(id) })));
344 }
345 const migrations = executedMigrations.map(([id, name]) => `${id}_${name}`);
346 yield* migrations.length === 0
347 ? Effect.logDebug("Database schema is current")
348 : Effect.log(DATABASE_MIGRATIONS_FINISHED_MESSAGE).pipe(Effect.annotateLogs({ migrations }));
349​
350 const recorded = yield* sql<{
351 readonly migration_id: number;
352 readonly name: string;
353 }>`SELECT migration_id, name FROM effect_sql_migrations`;
354 const manifestNames = new Map<number, string>(migrationEntries.map(([id, name]) => [id, name]));
355 const divergent = recorded.flatMap((row) => {
356 const expected = manifestNames.get(row.migration_id);
357 if (expected === undefined) {
358 return [`${row.migration_id}:${row.name} (unknown to this build)`];
359 }
360 return expected === row.name
361 ? []
362 : [`${row.migration_id}:${row.name} (this build: ${expected})`];
363 });
364 if (divergent.length > 0) {
365 yield* Effect.logWarning(
366 "Database migration history diverges from this build; recorded migration ids are skipped, not reconciled by name.",
367 ).pipe(Effect.annotateLogs({ divergent }));
368 }
369 return executedMigrations;
370});