File size: 25,537 Bytes
ad2afbf
 
a4836dc
b01d539
a4836dc
ad2afbf
 
 
 
 
 
 
 
 
 
 
 
 
 
b01d539
ad2afbf
 
 
 
 
 
 
 
 
 
 
 
 
 
b01d539
ad2afbf
 
 
 
 
b01d539
 
 
 
ad2afbf
 
 
 
 
b01d539
ad2afbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b01d539
 
 
 
ad2afbf
 
 
b01d539
 
 
ad2afbf
 
 
 
 
 
 
 
 
 
 
a4836dc
 
ad2afbf
 
 
 
 
 
b01d539
ad2afbf
 
a4836dc
ad2afbf
 
 
 
 
 
 
 
 
 
 
b01d539
 
ad2afbf
 
 
 
 
 
a4836dc
b01d539
a4836dc
 
b01d539
 
 
 
 
 
 
a4836dc
ad2afbf
 
 
 
 
 
 
a4836dc
 
ad2afbf
b01d539
ad2afbf
 
 
 
a4836dc
ad2afbf
 
 
27329ef
ad2afbf
27329ef
ad2afbf
 
 
27329ef
 
 
ad2afbf
27329ef
 
 
 
 
4df94cd
 
 
 
439a2ff
 
 
 
ac3e800
 
 
 
146ca6d
 
 
 
ad2afbf
 
 
 
 
 
b01d539
 
ad2afbf
 
 
 
 
 
 
 
 
 
 
a4836dc
 
 
b01d539
a4836dc
ad2afbf
 
 
 
 
 
 
 
 
 
 
 
 
 
b01d539
 
 
 
 
 
ad2afbf
 
a4836dc
 
ad2afbf
a4836dc
b01d539
 
a4836dc
 
 
 
 
 
 
ad2afbf
439a2ff
 
 
 
 
ad2afbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27329ef
ad2afbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27329ef
 
146ca6d
27329ef
 
 
 
 
 
 
 
 
 
4df94cd
 
 
 
 
 
 
 
 
 
 
 
 
439a2ff
 
 
 
 
 
 
 
 
 
 
 
 
 
ac3e800
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146ca6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27329ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad2afbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27329ef
 
 
ad2afbf
27329ef
ad2afbf
 
 
 
27329ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad2afbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27329ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4df94cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
439a2ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac3e800
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146ca6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad2afbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27329ef
4df94cd
439a2ff
ac3e800
146ca6d
ad2afbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4836dc
b01d539
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
import { access, mkdir, readFile, stat } from "node:fs/promises";
import { dirname, join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { performance } from "node:perf_hooks";
import { fileURLToPath } from "node:url";
import type { Clock } from "../kernel/clock.js";
import { SystemClock } from "../kernel/clock.js";
import { sha256Hex } from "../kernel/canonical-json.js";
import type { IdGenerator } from "../kernel/id-generator.js";
import { UuidIdGenerator } from "../kernel/id-generator.js";
import {
  PersistenceBusyError,
  type DatabaseReadiness,
  type SystemDatabase,
  type TransactionContext,
  type TransactionMode,
  type TransactionRunner,
} from "./database.js";
import { createPreMigrationBackup } from "./pre-migration-backup.js";
import type { OperationalMetrics } from "../observability/operational-metrics.js";

interface MigrationAsset {
  version: number;
  name: string;
  sql: string;
  checksum: string;
}

export interface SqliteConnectionOptions {
  appBuildSha?: string;
  appKey?: Uint8Array;
  backupRoot?: string;
  clock?: Clock;
  idGenerator?: IdGenerator;
  metrics?: OperationalMetrics;
}

class SqliteTransactionRunner implements TransactionRunner {
  private activeMode: TransactionMode | undefined;

  constructor(
    private readonly database: DatabaseSync,
    private readonly metrics?: OperationalMetrics,
  ) {}

  run<T>(
    mode: TransactionMode,
    operation: (context: TransactionContext) => T,
  ): T {
    const startedAt = performance.now();
    if (this.activeMode !== undefined) {
      if (mode !== "read") {
        throw new Error("Nested write transactions are not allowed");
      }
      return this.invoke(operation);
    }

    this.activeMode = mode;
    const begin = mode === "immediate" ? "BEGIN IMMEDIATE" : "BEGIN DEFERRED";
    try {
      this.database.exec(begin);
      const result = this.invoke(operation);
      this.database.exec(mode === "read" ? "ROLLBACK" : "COMMIT");
      return result;
    } catch (error) {
      if (this.database.isTransaction) this.database.exec("ROLLBACK");
      if (isSqliteBusy(error)) {
        this.metrics?.recordSqliteBusy();
        throw new PersistenceBusyError({ cause: error });
      }
      throw error;
    } finally {
      this.activeMode = undefined;
      const durationMs = performance.now() - startedAt;
      this.metrics?.observe("transaction", durationMs);
      this.metrics?.observe("databaseOperation", durationMs);
    }
  }

  private invoke<T>(operation: (context: TransactionContext) => T): T {
    const result = operation({ database: this.database });
    if (isThenable(result)) {
      throw new TypeError("Transaction callbacks must be synchronous");
    }
    return result;
  }
}

export class SqliteSystemDatabase implements SystemDatabase {
  readonly transactions: TransactionRunner;
  private readonly clock: Clock;
  private readonly appBuildSha: string;
  private readonly appKey: Uint8Array | undefined;
  private readonly backupRoot: string;
  private readonly idGenerator: IdGenerator;
  private readonly metrics: OperationalMetrics | undefined;
  private migrationFailure: string | undefined;
  private expectedMigrationChecksums = new Map<number, string>();

  private constructor(
    private readonly database: DatabaseSync,
    private readonly databasePath: string,
    options: SqliteConnectionOptions,
  ) {
    this.clock = options.clock ?? new SystemClock();
    this.appBuildSha = options.appBuildSha ?? "local";
    this.appKey = options.appKey;
    this.backupRoot =
      options.backupRoot ?? join(dirname(databasePath), "..", "backups");
    this.idGenerator = options.idGenerator ?? new UuidIdGenerator();
    this.metrics = options.metrics;
    this.transactions = new SqliteTransactionRunner(database, options.metrics);
  }

  static async connect(
    databaseUrl: string,
    options: SqliteConnectionOptions = {},
  ): Promise<SqliteSystemDatabase> {
    if (!databaseUrl.startsWith("file:")) {
      throw new Error("The SQLite adapter requires a file URL");
    }
    const databasePath = fileURLToPath(databaseUrl);
    try {
      const existing = await stat(databasePath);
      if (!existing.isFile()) throw new Error("Database path is not a file");
      if (existing.size === 0) throw new Error("Database file is zero bytes");
    } catch (error) {
      if (!isFileNotFound(error)) throw error;
    }
    await mkdir(dirname(databasePath), { recursive: true });
    const instance = new SqliteSystemDatabase(
      new DatabaseSync(databasePath),
      databasePath,
      options,
    );
    instance.applyConnectionPragmas();
    return instance;
  }

  async migrate(): Promise<void> {
    const startedAt = performance.now();
    try {
      const migrations = await loadMigrationAssets();
      this.expectedMigrationChecksums = new Map(
        migrations.map((migration) => [migration.version, migration.checksum]),
      );
      const tables = this.listApplicationTables();
      const isFreshDatabase = tables.length === 0;
      if (isFreshDatabase) this.applyFoundationMigration(migrations[0]);
      this.assertKnownSchemaBeforeMigration(migrations);

      let currentVersion = this.currentSchemaVersion();
      if (currentVersion > migrations.length) {
        throw new Error("Database schema is newer than this application build");
      }
      if (!isFreshDatabase && currentVersion < migrations.length) {
        await this.createPendingMigrationBackup(currentVersion, migrations);
      }
      if (currentVersion === 1) {
        this.applyPersistenceKernelMigration(migrations[1]);
        currentVersion = 2;
      }
      if (currentVersion === 2) {
        this.applyIdentityAndApprovalMigration(migrations[2]);
        currentVersion = 3;
      }
      if (currentVersion === 3) {
        this.applyCanonicalProjectMigration(migrations[3]);
        currentVersion = 4;
      }
      if (currentVersion === 4) {
        this.applyPrivateAssetsMigration(migrations[4]);
        currentVersion = 5;
      }
      if (currentVersion === 5) {
        this.applyDurableJobKernelMigration(migrations[5]);
        currentVersion = 6;
      }
      if (currentVersion === 6) {
        this.applyCompositionsPreviewMigration(migrations[6]);
      }
      this.verifyAppliedMigrations(migrations);
      this.migrationFailure = undefined;
    } catch (error) {
      this.migrationFailure = "Database migration verification failed";
      throw error;
    } finally {
      this.metrics?.observe("migration", performance.now() - startedAt);
    }
  }

  listApplicationTables(): string[] {
    return (
      this.database
        .prepare(
          "SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name",
        )
        .all() as { name: string }[]
    ).map(({ name }) => name);
  }

  checkReadiness(): Promise<DatabaseReadiness> {
    const startedAt = performance.now();
    try {
      if (this.migrationFailure !== undefined) {
        return Promise.resolve({
          status: "not_ready",
          message: this.migrationFailure,
        });
      }
      this.verifyConnectionPragmas();
      this.verifyAppliedMigrationsAgainstExpected();
      const foreignKeyFailures = this.database
        .prepare("PRAGMA foreign_key_check")
        .all();
      if (foreignKeyFailures.length > 0) {
        throw new Error("Foreign key verification failed");
      }
      const quickCheck = this.database.prepare("PRAGMA quick_check").get() as
        | Record<string, string>
        | undefined;
      if (quickCheck === undefined || Object.values(quickCheck)[0] !== "ok") {
        throw new Error("SQLite quick integrity check failed");
      }
      return Promise.resolve({ status: "ready" });
    } catch {
      return Promise.resolve({
        status: "not_ready",
        message: "Database integrity verification failed",
      });
    } finally {
      this.metrics?.observe("databaseOperation", performance.now() - startedAt);
    }
  }

  close(): Promise<void> {
    this.database.close();
    return Promise.resolve();
  }

  /** Checkpoint WAL pages before a filesystem-level database snapshot. */
  checkpoint(): void {
    this.database.exec("PRAGMA wal_checkpoint(TRUNCATE)");
  }

  private applyConnectionPragmas(): void {
    this.database.exec(
      "PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000;",
    );
    this.verifyConnectionPragmas();
  }

  private verifyConnectionPragmas(): void {
    const scalar = (pragma: string): number | string | undefined => {
      const row = this.database.prepare(pragma).get() as
        | Record<string, number | string>
        | undefined;
      return row === undefined ? undefined : Object.values(row)[0];
    };
    if (
      scalar("PRAGMA foreign_keys") !== 1 ||
      String(scalar("PRAGMA journal_mode")).toLowerCase() !== "wal" ||
      scalar("PRAGMA synchronous") !== 2 ||
      scalar("PRAGMA busy_timeout") !== 5000
    ) {
      throw new Error("Required SQLite connection PRAGMAs are not active");
    }
  }

  private applyFoundationMigration(
    migration: MigrationAsset | undefined,
  ): void {
    if (migration?.version !== 1)
      throw new Error("Foundation migration is missing");
    this.transactions.run("immediate", ({ database }) =>
      database.exec(migration.sql),
    );
  }

  private assertKnownSchemaBeforeMigration(migrations: MigrationAsset[]): void {
    const tables = this.listApplicationTables();
    if (!tables.includes("schema_migrations")) {
      throw new Error("Unrecognized database without a migration ledger");
    }
    const version = this.currentSchemaVersion();
    if (version === 1) {
      const allowed = ["schema_migrations", "system_metadata"];
      if (tables.some((table) => !allowed.includes(table))) {
        throw new Error("Foundation v1 database contains unknown tables");
      }
      const row = this.database
        .prepare("SELECT version, name FROM schema_migrations")
        .all() as { version: number; name: string }[];
      if (
        row.length !== 1 ||
        row[0]?.version !== 1 ||
        row[0].name !== "foundation_system_tables"
      ) {
        throw new Error("Foundation v1 migration identity is invalid");
      }
      this.assertExactFoundationColumns();
      return;
    }
    if (version >= 2 && version <= 7) {
      const expectedTables =
        version === 2
          ? [
              "audit_events",
              "idempotency_records",
              "outbox_events",
              "schema_migrations",
              "system_metadata",
              "users",
            ]
          : version === 3
            ? [
                "audit_events",
                "idempotency_records",
                "oauth_identities",
                "oauth_transactions",
                "outbox_events",
                "provider_credential_references",
                "schema_migrations",
                "sessions",
                "system_metadata",
                "users",
              ]
            : version === 4
              ? [
                  "audit_events",
                  "idempotency_records",
                  "oauth_identities",
                  "oauth_transactions",
                  "outbox_events",
                  "projects",
                  "provider_credential_references",
                  "schema_migrations",
                  "sessions",
                  "system_metadata",
                  "users",
                ]
              : version === 5
                ? [
                    "assets",
                    "audit_events",
                    "delivery_capabilities",
                    "idempotency_records",
                    "oauth_identities",
                    "oauth_transactions",
                    "outbox_events",
                    "projects",
                    "provider_credential_references",
                    "schema_migrations",
                    "sessions",
                    "system_metadata",
                    "upload_sessions",
                    "users",
                  ]
                : version === 6
                  ? [
                      "assets",
                      "audit_events",
                      "delivery_capabilities",
                      "idempotency_records",
                      "job_events",
                      "job_steps",
                      "jobs",
                      "oauth_identities",
                      "oauth_transactions",
                      "outbox_events",
                      "projects",
                      "provider_credential_references",
                      "quota_policies",
                      "quota_reservations",
                      "schema_migrations",
                      "sessions",
                      "system_metadata",
                      "upload_sessions",
                      "users",
                    ]
                  : [
                      "assets",
                      "audit_events",
                      "composition_asset_references",
                      "composition_versions",
                      "delivery_capabilities",
                      "idempotency_records",
                      "job_events",
                      "job_steps",
                      "jobs",
                      "oauth_identities",
                      "oauth_transactions",
                      "outbox_events",
                      "preview_artifacts",
                      "projects",
                      "provider_credential_references",
                      "quota_policies",
                      "quota_reservations",
                      "schema_migrations",
                      "sessions",
                      "system_metadata",
                      "upload_sessions",
                      "users",
                    ];
      const applicationTables = tables.filter(
        (table) => !table.startsWith("_litestream_"),
      );
      if (
        JSON.stringify(applicationTables) !== JSON.stringify(expectedTables)
      ) {
        throw new Error(
          `Schema v${version} contains unknown application tables`,
        );
      }
      const rows = this.database
        .prepare(
          "SELECT version, name, checksum_sha256 FROM schema_migrations ORDER BY version",
        )
        .all() as Array<{
        version: number;
        name: string;
        checksum_sha256: string;
      }>;
      if (
        rows.length !== version ||
        rows.some((row, index) => {
          const migration = migrations[index];
          return (
            migration === undefined ||
            row.version !== migration.version ||
            row.name !== migration.name ||
            row.checksum_sha256 !== migration.checksum
          );
        })
      ) {
        throw new Error(`Schema v${version} migration identity is invalid`);
      }
    }
  }

  private assertExactFoundationColumns(): void {
    const columns = (table: string) =>
      (
        this.database.prepare(`PRAGMA table_info(${table})`).all() as Array<{
          name: string;
          type: string;
          notnull: number;
          pk: number;
        }>
      ).map(({ name, type, notnull, pk }) => ({ name, type, notnull, pk }));
    const expectedLedger = [
      { name: "version", type: "INTEGER", notnull: 0, pk: 1 },
      { name: "name", type: "TEXT", notnull: 1, pk: 0 },
      { name: "applied_at", type: "TEXT", notnull: 1, pk: 0 },
    ];
    const expectedMetadata = [
      { name: "key", type: "TEXT", notnull: 0, pk: 1 },
      { name: "value", type: "TEXT", notnull: 1, pk: 0 },
      { name: "updated_at", type: "TEXT", notnull: 1, pk: 0 },
    ];
    if (
      JSON.stringify(columns("schema_migrations")) !==
        JSON.stringify(expectedLedger) ||
      JSON.stringify(columns("system_metadata")) !==
        JSON.stringify(expectedMetadata)
    ) {
      throw new Error("Foundation v1 table shape is invalid");
    }
  }

  private currentSchemaVersion(): number {
    const row = this.database
      .prepare("SELECT MAX(version) AS version FROM schema_migrations")
      .get() as { version: number | null };
    return row.version ?? 0;
  }

  private async createPendingMigrationBackup(
    currentVersion: number,
    migrations: MigrationAsset[],
  ): Promise<void> {
    if (this.appKey === undefined) {
      throw new Error(
        "An application key is required for pre-migration backup",
      );
    }
    await createPreMigrationBackup({
      database: this.database,
      backupRoot: this.backupRoot,
      applicationKey: this.appKey,
      appBuildSha: this.appBuildSha,
      clock: this.clock,
      idGenerator: this.idGenerator,
      sourceSchemaVersion: currentVersion,
      targetSchemaVersion: migrations.length,
      migrationVersionsPending: migrations
        .filter(({ version }) => version > currentVersion)
        .map(({ version }) => version),
    });
  }

  private applyPersistenceKernelMigration(
    migration: MigrationAsset | undefined,
  ): void {
    if (migration?.version !== 2)
      throw new Error("Persistence migration is missing");
    const metadataCount = this.database
      .prepare("SELECT COUNT(*) AS count FROM system_metadata")
      .get() as { count: number };
    if (metadataCount.count !== 0) {
      throw new Error("Legacy system metadata cannot be safely normalized");
    }
    const startedAt = this.clock.now();
    this.transactions.run("immediate", ({ database }) => {
      database.exec(migration.sql);
      database
        .prepare(
          `INSERT INTO schema_migrations
            (version, name, checksum_sha256, applied_at, execution_ms, app_build_sha)
           VALUES (?, ?, ?, ?, ?, ?)`,
        )
        .run(
          migration.version,
          migration.name,
          migration.checksum,
          this.clock.now(),
          Math.max(0, this.clock.now() - startedAt),
          this.appBuildSha,
        );
    });
  }

  private applyIdentityAndApprovalMigration(
    migration: MigrationAsset | undefined,
  ): void {
    if (migration?.version !== 3)
      throw new Error("Identity and approval migration is missing");
    const startedAt = this.clock.now();
    this.transactions.run("immediate", ({ database }) => {
      database.exec(migration.sql);
      database
        .prepare(
          `INSERT INTO schema_migrations
            (version, name, checksum_sha256, applied_at, execution_ms, app_build_sha)
           VALUES (?, ?, ?, ?, ?, ?)`,
        )
        .run(
          migration.version,
          migration.name,
          migration.checksum,
          this.clock.now(),
          Math.max(0, this.clock.now() - startedAt),
          this.appBuildSha,
        );
    });
  }

  private applyCanonicalProjectMigration(
    migration: MigrationAsset | undefined,
  ): void {
    if (migration?.version !== 4)
      throw new Error("Canonical Project migration is missing");
    const startedAt = this.clock.now();
    this.transactions.run("immediate", ({ database }) => {
      database.exec(migration.sql);
      database
        .prepare(
          `INSERT INTO schema_migrations
            (version, name, checksum_sha256, applied_at, execution_ms, app_build_sha)
           VALUES (?, ?, ?, ?, ?, ?)`,
        )
        .run(
          migration.version,
          migration.name,
          migration.checksum,
          this.clock.now(),
          Math.max(0, this.clock.now() - startedAt),
          this.appBuildSha,
        );
    });
  }

  private applyPrivateAssetsMigration(
    migration: MigrationAsset | undefined,
  ): void {
    if (migration?.version !== 5)
      throw new Error("Private Asset migration is missing");
    const startedAt = this.clock.now();
    this.transactions.run("immediate", ({ database }) => {
      database.exec(migration.sql);
      database
        .prepare(
          `INSERT INTO schema_migrations
            (version, name, checksum_sha256, applied_at, execution_ms, app_build_sha)
           VALUES (?, ?, ?, ?, ?, ?)`,
        )
        .run(
          migration.version,
          migration.name,
          migration.checksum,
          this.clock.now(),
          Math.max(0, this.clock.now() - startedAt),
          this.appBuildSha,
        );
    });
  }

  private applyDurableJobKernelMigration(
    migration: MigrationAsset | undefined,
  ): void {
    if (migration?.version !== 6)
      throw new Error("Durable Job kernel migration is missing");
    const startedAt = this.clock.now();
    this.transactions.run("immediate", ({ database }) => {
      database.exec(migration.sql);
      database
        .prepare(
          `INSERT INTO schema_migrations
            (version, name, checksum_sha256, applied_at, execution_ms, app_build_sha)
           VALUES (?, ?, ?, ?, ?, ?)`,
        )
        .run(
          migration.version,
          migration.name,
          migration.checksum,
          this.clock.now(),
          Math.max(0, this.clock.now() - startedAt),
          this.appBuildSha,
        );
    });
  }

  private applyCompositionsPreviewMigration(
    migration: MigrationAsset | undefined,
  ): void {
    if (migration?.version !== 7)
      throw new Error("Compositions and preview migration is missing");
    const startedAt = this.clock.now();
    this.database.exec("PRAGMA foreign_keys=OFF; PRAGMA legacy_alter_table=ON");
    try {
      this.database.exec("BEGIN IMMEDIATE");
      this.database.exec(migration.sql);
      this.database
        .prepare(
          `INSERT INTO schema_migrations
            (version, name, checksum_sha256, applied_at, execution_ms, app_build_sha)
           VALUES (?, ?, ?, ?, ?, ?)`,
        )
        .run(
          migration.version,
          migration.name,
          migration.checksum,
          this.clock.now(),
          Math.max(0, this.clock.now() - startedAt),
          this.appBuildSha,
        );
      this.database.exec("COMMIT");
    } catch (error) {
      if (this.database.isTransaction) this.database.exec("ROLLBACK");
      throw error;
    } finally {
      this.database.exec(
        "PRAGMA legacy_alter_table=OFF; PRAGMA foreign_keys=ON",
      );
    }
    const foreignKeyFailures = this.database
      .prepare("PRAGMA foreign_key_check")
      .all();
    if (foreignKeyFailures.length > 0)
      throw new Error("Migration v7 foreign key qualification failed");
  }

  private verifyAppliedMigrations(migrations: MigrationAsset[]): void {
    const rows = this.database
      .prepare(
        "SELECT version, name, checksum_sha256 FROM schema_migrations ORDER BY version",
      )
      .all() as { version: number; name: string; checksum_sha256: string }[];
    if (rows.length !== migrations.length) {
      throw new Error("Migration ledger has a version gap");
    }
    for (const [index, migration] of migrations.entries()) {
      const row = rows[index];
      if (
        row?.version !== migration.version ||
        row.name !== migration.name ||
        row.checksum_sha256 !== migration.checksum
      ) {
        throw new Error("Applied migration checksum or identity mismatch");
      }
    }
  }

  private verifyAppliedMigrationsAgainstExpected(): void {
    const rows = this.database
      .prepare(
        "SELECT version, checksum_sha256 FROM schema_migrations ORDER BY version",
      )
      .all() as { version: number; checksum_sha256: string }[];
    if (rows.length !== this.expectedMigrationChecksums.size) {
      throw new Error("Migration count mismatch");
    }
    for (const row of rows) {
      if (
        this.expectedMigrationChecksums.get(row.version) !== row.checksum_sha256
      ) {
        throw new Error("Migration checksum mismatch");
      }
    }
  }
}

async function loadMigrationAssets(): Promise<MigrationAsset[]> {
  const definitions = [
    [1, "foundation_system_tables", "0001-foundation-system-tables.sql"],
    [2, "persistence-kernel", "0002-persistence-kernel.sql"],
    [3, "identity-and-approval", "0003-identity-and-approval.sql"],
    [4, "canonical-project", "0004-canonical-project.sql"],
    [5, "private-assets", "0005-private-assets.sql"],
    [6, "durable-job-kernel", "0006-durable-job-kernel.sql"],
    [7, "compositions-preview", "0007-compositions-preview.sql"],
  ] as const;
  return Promise.all(
    definitions.map(async ([version, name, filename]) => {
      const url = new URL(`../../migrations/${filename}`, import.meta.url);
      await access(url);
      const bytes = await readFile(url);
      const details = await stat(url);
      if (!details.isFile() || bytes.length === 0) {
        throw new Error(`Migration asset ${version} is invalid`);
      }
      return {
        version,
        name,
        sql: bytes.toString("utf8"),
        checksum: sha256Hex(bytes),
      };
    }),
  );
}

function isThenable(value: unknown): value is PromiseLike<unknown> {
  return (
    ((typeof value === "object" && value !== null) ||
      typeof value === "function") &&
    "then" in value
  );
}

function isSqliteBusy(error: unknown): boolean {
  return (
    error instanceof Error &&
    "code" in error &&
    (error as Error & { code?: string }).code === "ERR_SQLITE_ERROR" &&
    /busy|locked/i.test(error.message)
  );
}

function isFileNotFound(error: unknown): boolean {
  return (
    error instanceof Error &&
    "code" in error &&
    (error as NodeJS.ErrnoException).code === "ENOENT"
  );
}