Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

test(database): pin the drift snapshot instead of classifying shapes

Yudhi Armyndharis82d400a98436
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b23861c4d..8e3492aca 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- The migration drift gate compares the chain-vs-entity diff against a pinned snapshot of the full statement text instead of classifying statements by shape. On SQLite a new column is applied as a table rebuild and a new index as a bare `CREATE INDEX`, the same shapes the known column-type drift produces, so the shape filters passed both: an entity change shipped without a migration stayed green and only surfaced as a `no such column` 500 on a synchronize-disabled deployment.
- Follow-ups from the accessibility review: the plugin ConfigField derives a per-field id (a hardcoded id collided on any schema with two booleans, making the second label toggle the first checkbox), the 10 codemod-touched files are Prettier-clean (9 failed the dashboard format gate), and six more multi-line labels in MessageTester are wired.
- Dashboard accessibility: 55 form labels are associated with their controls (`htmlFor`/`id`, no duplicates or orphans), the muted-text token meets AA on both themes (4.76:1 light, 5.71:1 dark), and the primary button uses dark text on the green (9.0:1, from 1.98:1).
- Follow-ups from the batch review: the chain-boot e2e sets MAIN_DATABASE_SYNCHRONIZE=false explicitly (the env's absence defaults to synchronize=true, so the main chain was never exercised), the drift gate classifies statements against the two known shape families (column-type rebuild, index-name drift) instead of blanket-filtering every index/DROP statement, the shared delivery recorder strips the raw error before the persistence spread, and the ignore-pattern list deduplicates.
diff --git a/src/database/migrations/__tests__/__fixtures__/known-migration-drift.json b/src/database/migrations/__tests__/__fixtures__/known-migration-drift.json
new file mode 100644
index 000000000..3f2b9037c
--- /dev/null
+++ b/src/database/migrations/__tests__/__fixtures__/known-migration-drift.json
@@ -0,0 +1,111 @@
+{
+ "data": [
+ "DROP INDEX \"IDX_baileys_stored_messages_session_created\"",
+ "DROP INDEX \"UQ_baileys_stored_messages_session_wamsg\"",
+ "CREATE TABLE \"temporary_baileys_stored_messages\" (\"id\" varchar PRIMARY KEY NOT NULL, \"sessionId\" varchar NOT NULL, \"waMessageId\" varchar NOT NULL, \"serializedMessage\" text NOT NULL, \"createdAt\" datetime NOT NULL DEFAULT (datetime('now')))",
+ "INSERT INTO \"temporary_baileys_stored_messages\"(\"id\", \"sessionId\", \"waMessageId\", \"serializedMessage\", \"createdAt\") SELECT \"id\", \"sessionId\", \"waMessageId\", \"serializedMessage\", \"createdAt\" FROM \"baileys_stored_messages\"",
+ "DROP TABLE \"baileys_stored_messages\"",
+ "ALTER TABLE \"temporary_baileys_stored_messages\" RENAME TO \"baileys_stored_messages\"",
+ "CREATE INDEX \"IDX_baileys_stored_messages_session_created\" ON \"baileys_stored_messages\" (\"sessionId\", \"createdAt\") ",
+ "CREATE UNIQUE INDEX \"UQ_baileys_stored_messages_session_wamsg\" ON \"baileys_stored_messages\" (\"sessionId\", \"waMessageId\") ",
+ "DROP INDEX \"IDX_templates_session_name\"",
+ "DROP INDEX \"IDX_templates_sessionId\"",
+ "CREATE TABLE \"temporary_templates\" (\"id\" varchar PRIMARY KEY NOT NULL, \"sessionId\" varchar NOT NULL, \"name\" varchar(100) NOT NULL, \"body\" text NOT NULL, \"header\" text, \"footer\" text, \"createdAt\" datetime NOT NULL DEFAULT (datetime('now')), \"updatedAt\" datetime NOT NULL DEFAULT (datetime('now')))",
+ "INSERT INTO \"temporary_templates\"(\"id\", \"sessionId\", \"name\", \"body\", \"header\", \"footer\", \"createdAt\", \"updatedAt\") SELECT \"id\", \"sessionId\", \"name\", \"body\", \"header\", \"footer\", \"createdAt\", \"updatedAt\" FROM \"templates\"",
+ "DROP TABLE \"templates\"",
+ "ALTER TABLE \"temporary_templates\" RENAME TO \"templates\"",
+ "CREATE UNIQUE INDEX \"IDX_templates_session_name\" ON \"templates\" (\"sessionId\", \"name\") ",
+ "CREATE INDEX \"IDX_templates_sessionId\" ON \"templates\" (\"sessionId\") ",
+ "DROP INDEX \"IDX_automation_rules_sessionId\"",
+ "CREATE TABLE \"temporary_automation_rules\" (\"id\" varchar PRIMARY KEY NOT NULL, \"sessionId\" varchar NOT NULL, \"name\" varchar(100) NOT NULL, \"enabled\" boolean NOT NULL DEFAULT (1), \"conditions\" text, \"replyText\" text NOT NULL, \"cooldownSeconds\" integer NOT NULL DEFAULT (60), \"createdAt\" datetime NOT NULL DEFAULT (datetime('now')), \"updatedAt\" datetime NOT NULL DEFAULT (datetime('now')))",
+ "INSERT INTO \"temporary_automation_rules\"(\"id\", \"sessionId\", \"name\", \"enabled\", \"conditions\", \"replyText\", \"cooldownSeconds\", \"createdAt\", \"updatedAt\") SELECT \"id\", \"sessionId\", \"name\", \"enabled\", \"conditions\", \"replyText\", \"cooldownSeconds\", \"createdAt\", \"updatedAt\" FROM \"automation_rules\"",
+ "DROP TABLE \"automation_rules\"",
+ "ALTER TABLE \"temporary_automation_rules\" RENAME TO \"automation_rules\"",
+ "CREATE INDEX \"IDX_automation_rules_sessionId\" ON \"automation_rules\" (\"sessionId\") ",
+ "DROP INDEX \"IDX_baileys_stored_messages_session_created\"",
+ "DROP INDEX \"UQ_baileys_stored_messages_session_wamsg\"",
+ "DROP INDEX \"IDX_lid_mappings_phone\"",
+ "DROP INDEX \"IDX_templates_sessionId\"",
+ "DROP INDEX \"IDX_status_updates_expiresAt\"",
+ "DROP INDEX \"UQ_status_updates_sessionId_waStatusId\"",
+ "DROP INDEX \"IDX_status_updates_sessionId_contactJid\"",
+ "DROP INDEX \"IDX_webhooks_sessionId\"",
+ "CREATE TABLE \"temporary_webhooks\" (\"id\" varchar PRIMARY KEY NOT NULL, \"sessionId\" varchar NOT NULL, \"url\" varchar(2048) NOT NULL, \"events\" text NOT NULL DEFAULT ('[\"message.received\"]'), \"secret\" varchar(255), \"headers\" text NOT NULL DEFAULT ('{}'), \"active\" boolean NOT NULL DEFAULT (1), \"retryCount\" integer NOT NULL DEFAULT (3), \"lastTriggeredAt\" datetime, \"createdAt\" datetime NOT NULL DEFAULT (datetime('now')), \"updatedAt\" datetime NOT NULL DEFAULT (datetime('now')), \"filters\" text, CONSTRAINT \"FK_d209715bb62b12255e825580af6\" FOREIGN KEY (\"sessionId\") REFERENCES \"sessions\" (\"id\") ON DELETE CASCADE ON UPDATE NO ACTION)",
+ "INSERT INTO \"temporary_webhooks\"(\"id\", \"sessionId\", \"url\", \"events\", \"secret\", \"headers\", \"active\", \"retryCount\", \"lastTriggeredAt\", \"createdAt\", \"updatedAt\", \"filters\") SELECT \"id\", \"sessionId\", \"url\", \"events\", \"secret\", \"headers\", \"active\", \"retryCount\", \"lastTriggeredAt\", \"createdAt\", \"updatedAt\", \"filters\" FROM \"webhooks\"",
+ "DROP TABLE \"webhooks\"",
+ "ALTER TABLE \"temporary_webhooks\" RENAME TO \"webhooks\"",
+ "CREATE INDEX \"IDX_webhooks_sessionId\" ON \"webhooks\" (\"sessionId\") ",
+ "DROP INDEX \"IDX_ingress_events_dispatchState\"",
+ "DROP INDEX \"IDX_ingress_events_createdAt\"",
+ "DROP INDEX \"UQ_ingress_events_instance_delivery\"",
+ "CREATE TABLE \"temporary_ingress_events\" (\"id\" varchar PRIMARY KEY NOT NULL, \"instanceId\" varchar NOT NULL, \"pluginId\" varchar NOT NULL, \"providerDeliveryId\" varchar NOT NULL, \"route\" varchar NOT NULL, \"payload\" text, \"payloadHash\" varchar, \"sessionId\" varchar, \"dispatchState\" varchar, \"dispatchAttempts\" integer NOT NULL DEFAULT (0), \"lastDispatchAt\" datetime, \"createdAt\" datetime NOT NULL DEFAULT (datetime('now')))",
+ "INSERT INTO \"temporary_ingress_events\"(\"id\", \"instanceId\", \"pluginId\", \"providerDeliveryId\", \"route\", \"payload\", \"payloadHash\", \"sessionId\", \"dispatchState\", \"dispatchAttempts\", \"lastDispatchAt\", \"createdAt\") SELECT \"id\", \"instanceId\", \"pluginId\", \"providerDeliveryId\", \"route\", \"payload\", \"payloadHash\", \"sessionId\", \"dispatchState\", \"dispatchAttempts\", \"lastDispatchAt\", \"createdAt\" FROM \"ingress_events\"",
+ "DROP TABLE \"ingress_events\"",
+ "ALTER TABLE \"temporary_ingress_events\" RENAME TO \"ingress_events\"",
+ "CREATE INDEX \"IDX_ingress_events_dispatchState\" ON \"ingress_events\" (\"dispatchState\", \"createdAt\") ",
+ "CREATE INDEX \"IDX_ingress_events_createdAt\" ON \"ingress_events\" (\"createdAt\") ",
+ "CREATE UNIQUE INDEX \"UQ_ingress_events_instance_delivery\" ON \"ingress_events\" (\"pluginId\", \"instanceId\", \"providerDeliveryId\") ",
+ "CREATE TABLE \"temporary_sessions\" (\"id\" varchar PRIMARY KEY NOT NULL, \"name\" varchar(100) NOT NULL, \"status\" varchar(50) NOT NULL DEFAULT ('created'), \"phone\" varchar(20), \"pushName\" varchar(100), \"config\" text NOT NULL DEFAULT ('{}'), \"proxyUrl\" varchar(255), \"proxyType\" varchar(10), \"connectedAt\" text, \"lastActiveAt\" text, \"createdAt\" datetime NOT NULL DEFAULT (datetime('now')), \"updatedAt\" datetime NOT NULL DEFAULT (datetime('now')), \"nodeId\" varchar(190), \"claimedAt\" text, \"leaseExpiresAt\" text, \"nodeUrl\" varchar(2048), CONSTRAINT \"UQ_ac984ccbd8b01af155e1874e8cb\" UNIQUE (\"name\"))",
+ "INSERT INTO \"temporary_sessions\"(\"id\", \"name\", \"status\", \"phone\", \"pushName\", \"config\", \"proxyUrl\", \"proxyType\", \"connectedAt\", \"lastActiveAt\", \"createdAt\", \"updatedAt\", \"nodeId\", \"claimedAt\", \"leaseExpiresAt\", \"nodeUrl\") SELECT \"id\", \"name\", \"status\", \"phone\", \"pushName\", \"config\", \"proxyUrl\", \"proxyType\", \"connectedAt\", \"lastActiveAt\", \"createdAt\", \"updatedAt\", \"nodeId\", \"claimedAt\", \"leaseExpiresAt\", \"nodeUrl\" FROM \"sessions\"",
+ "DROP TABLE \"sessions\"",
+ "ALTER TABLE \"temporary_sessions\" RENAME TO \"sessions\"",
+ "DROP INDEX \"IDX_webhooks_sessionId\"",
+ "CREATE TABLE \"temporary_webhooks\" (\"id\" varchar PRIMARY KEY NOT NULL, \"sessionId\" varchar NOT NULL, \"url\" varchar(2048) NOT NULL, \"events\" text NOT NULL DEFAULT ('[\"message.received\"]'), \"secret\" varchar(255), \"headers\" text NOT NULL DEFAULT ('{}'), \"active\" boolean NOT NULL DEFAULT (1), \"retryCount\" integer NOT NULL DEFAULT (3), \"lastTriggeredAt\" text, \"createdAt\" datetime NOT NULL DEFAULT (datetime('now')), \"updatedAt\" datetime NOT NULL DEFAULT (datetime('now')), \"filters\" text, CONSTRAINT \"FK_d209715bb62b12255e825580af6\" FOREIGN KEY (\"sessionId\") REFERENCES \"sessions\" (\"id\") ON DELETE CASCADE ON UPDATE NO ACTION)",
+ "INSERT INTO \"temporary_webhooks\"(\"id\", \"sessionId\", \"url\", \"events\", \"secret\", \"headers\", \"active\", \"retryCount\", \"lastTriggeredAt\", \"createdAt\", \"updatedAt\", \"filters\") SELECT \"id\", \"sessionId\", \"url\", \"events\", \"secret\", \"headers\", \"active\", \"retryCount\", \"lastTriggeredAt\", \"createdAt\", \"updatedAt\", \"filters\" FROM \"webhooks\"",
+ "DROP TABLE \"webhooks\"",
+ "ALTER TABLE \"temporary_webhooks\" RENAME TO \"webhooks\"",
+ "CREATE INDEX \"IDX_webhooks_sessionId\" ON \"webhooks\" (\"sessionId\") ",
+ "CREATE TABLE \"temporary_message_batches\" (\"id\" varchar PRIMARY KEY NOT NULL, \"batch_id\" varchar NOT NULL, \"session_id\" varchar NOT NULL, \"status\" varchar NOT NULL DEFAULT ('pending'), \"messages\" text NOT NULL, \"options\" text, \"progress\" text, \"results\" text, \"current_index\" integer NOT NULL DEFAULT (0), \"created_at\" datetime NOT NULL DEFAULT (datetime('now')), \"updated_at\" datetime NOT NULL DEFAULT (datetime('now')), \"started_at\" text, \"completed_at\" text, CONSTRAINT \"UQ_message_batches_session_id_batch_id\" UNIQUE (\"session_id\", \"batch_id\"))",
+ "INSERT INTO \"temporary_message_batches\"(\"id\", \"batch_id\", \"session_id\", \"status\", \"messages\", \"options\", \"progress\", \"results\", \"current_index\", \"created_at\", \"updated_at\", \"started_at\", \"completed_at\") SELECT \"id\", \"batch_id\", \"session_id\", \"status\", \"messages\", \"options\", \"progress\", \"results\", \"current_index\", \"created_at\", \"updated_at\", \"started_at\", \"completed_at\" FROM \"message_batches\"",
+ "DROP TABLE \"message_batches\"",
+ "ALTER TABLE \"temporary_message_batches\" RENAME TO \"message_batches\"",
+ "DROP INDEX \"IDX_ingress_events_dispatchState\"",
+ "DROP INDEX \"IDX_ingress_events_createdAt\"",
+ "DROP INDEX \"UQ_ingress_events_instance_delivery\"",
+ "CREATE TABLE \"temporary_ingress_events\" (\"id\" varchar PRIMARY KEY NOT NULL, \"instanceId\" varchar NOT NULL, \"pluginId\" varchar NOT NULL, \"providerDeliveryId\" varchar NOT NULL, \"route\" varchar NOT NULL, \"payload\" text, \"payloadHash\" varchar, \"sessionId\" varchar, \"dispatchState\" varchar, \"dispatchAttempts\" integer NOT NULL DEFAULT (0), \"lastDispatchAt\" text, \"createdAt\" datetime NOT NULL DEFAULT (datetime('now')))",
+ "INSERT INTO \"temporary_ingress_events\"(\"id\", \"instanceId\", \"pluginId\", \"providerDeliveryId\", \"route\", \"payload\", \"payloadHash\", \"sessionId\", \"dispatchState\", \"dispatchAttempts\", \"lastDispatchAt\", \"createdAt\") SELECT \"id\", \"instanceId\", \"pluginId\", \"providerDeliveryId\", \"route\", \"payload\", \"payloadHash\", \"sessionId\", \"dispatchState\", \"dispatchAttempts\", \"lastDispatchAt\", \"createdAt\" FROM \"ingress_events\"",
+ "DROP TABLE \"ingress_events\"",
+ "ALTER TABLE \"temporary_ingress_events\" RENAME TO \"ingress_events\"",
+ "CREATE INDEX \"IDX_ingress_events_dispatchState\" ON \"ingress_events\" (\"dispatchState\", \"createdAt\") ",
+ "CREATE INDEX \"IDX_ingress_events_createdAt\" ON \"ingress_events\" (\"createdAt\") ",
+ "CREATE UNIQUE INDEX \"UQ_ingress_events_instance_delivery\" ON \"ingress_events\" (\"pluginId\", \"instanceId\", \"providerDeliveryId\") ",
+ "CREATE INDEX \"IDX_ae44b476c522450bd395615a7c\" ON \"baileys_stored_messages\" (\"sessionId\", \"createdAt\") ",
+ "CREATE UNIQUE INDEX \"IDX_1bb396e881628cd4dc8f0d2a8b\" ON \"baileys_stored_messages\" (\"sessionId\", \"waMessageId\") ",
+ "CREATE INDEX \"IDX_1e39479a7a8aa37eab08df013b\" ON \"lid_mappings\" (\"phone\") ",
+ "CREATE INDEX \"IDX_951ec734b350580529e0b7ab2d\" ON \"status_updates\" (\"expiresAt\") ",
+ "CREATE UNIQUE INDEX \"IDX_1152eee4d077ae74396d73c1fb\" ON \"status_updates\" (\"sessionId\", \"waStatusId\") ",
+ "CREATE INDEX \"IDX_432ae5ea12bbda479dcae30fb1\" ON \"status_updates\" (\"sessionId\", \"contactJid\") ",
+ "DROP INDEX \"IDX_ae44b476c522450bd395615a7c\"",
+ "DROP INDEX \"IDX_1bb396e881628cd4dc8f0d2a8b\"",
+ "CREATE TABLE \"temporary_baileys_stored_messages\" (\"id\" varchar PRIMARY KEY NOT NULL, \"sessionId\" varchar NOT NULL, \"waMessageId\" varchar NOT NULL, \"serializedMessage\" text NOT NULL, \"createdAt\" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT \"FK_55c1dfd945d2c552a5313b25460\" FOREIGN KEY (\"sessionId\") REFERENCES \"sessions\" (\"id\") ON DELETE CASCADE ON UPDATE NO ACTION)",
+ "INSERT INTO \"temporary_baileys_stored_messages\"(\"id\", \"sessionId\", \"waMessageId\", \"serializedMessage\", \"createdAt\") SELECT \"id\", \"sessionId\", \"waMessageId\", \"serializedMessage\", \"createdAt\" FROM \"baileys_stored_messages\"",
+ "DROP TABLE \"baileys_stored_messages\"",
+ "ALTER TABLE \"temporary_baileys_stored_messages\" RENAME TO \"baileys_stored_messages\"",
+ "CREATE INDEX \"IDX_ae44b476c522450bd395615a7c\" ON \"baileys_stored_messages\" (\"sessionId\", \"createdAt\") ",
+ "CREATE UNIQUE INDEX \"IDX_1bb396e881628cd4dc8f0d2a8b\" ON \"baileys_stored_messages\" (\"sessionId\", \"waMessageId\") ",
+ "DROP INDEX \"IDX_templates_session_name\"",
+ "CREATE TABLE \"temporary_templates\" (\"id\" varchar PRIMARY KEY NOT NULL, \"sessionId\" varchar NOT NULL, \"name\" varchar(100) NOT NULL, \"body\" text NOT NULL, \"header\" text, \"footer\" text, \"createdAt\" datetime NOT NULL DEFAULT (datetime('now')), \"updatedAt\" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT \"FK_53208331c90e332d3f13780729c\" FOREIGN KEY (\"sessionId\") REFERENCES \"sessions\" (\"id\") ON DELETE CASCADE ON UPDATE NO ACTION)",
+ "INSERT INTO \"temporary_templates\"(\"id\", \"sessionId\", \"name\", \"body\", \"header\", \"footer\", \"createdAt\", \"updatedAt\") SELECT \"id\", \"sessionId\", \"name\", \"body\", \"header\", \"footer\", \"createdAt\", \"updatedAt\" FROM \"templates\"",
+ "DROP TABLE \"templates\"",
+ "ALTER TABLE \"temporary_templates\" RENAME TO \"templates\"",
+ "CREATE UNIQUE INDEX \"IDX_templates_session_name\" ON \"templates\" (\"sessionId\", \"name\") ",
+ "DROP INDEX \"IDX_automation_rules_sessionId\"",
+ "CREATE TABLE \"temporary_automation_rules\" (\"id\" varchar PRIMARY KEY NOT NULL, \"sessionId\" varchar NOT NULL, \"name\" varchar(100) NOT NULL, \"enabled\" boolean NOT NULL DEFAULT (1), \"conditions\" text, \"replyText\" text NOT NULL, \"cooldownSeconds\" integer NOT NULL DEFAULT (60), \"createdAt\" datetime NOT NULL DEFAULT (datetime('now')), \"updatedAt\" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT \"FK_0a1a8f3af56b4861c39161daf4d\" FOREIGN KEY (\"sessionId\") REFERENCES \"sessions\" (\"id\") ON DELETE CASCADE ON UPDATE NO ACTION)",
+ "INSERT INTO \"temporary_automation_rules\"(\"id\", \"sessionId\", \"name\", \"enabled\", \"conditions\", \"replyText\", \"cooldownSeconds\", \"createdAt\", \"updatedAt\") SELECT \"id\", \"sessionId\", \"name\", \"enabled\", \"conditions\", \"replyText\", \"cooldownSeconds\", \"createdAt\", \"updatedAt\" FROM \"automation_rules\"",
+ "DROP TABLE \"automation_rules\"",
+ "ALTER TABLE \"temporary_automation_rules\" RENAME TO \"automation_rules\"",
+ "CREATE INDEX \"IDX_automation_rules_sessionId\" ON \"automation_rules\" (\"sessionId\") "
+ ],
+ "main": [
+ "DROP INDEX \"IDX_api_keys_keyHash\"",
+ "DROP INDEX \"IDX_audit_logs_createdAt\"",
+ "DROP INDEX \"IDX_audit_logs_sessionId\"",
+ "DROP INDEX \"IDX_audit_logs_apiKeyId\"",
+ "DROP INDEX \"IDX_audit_logs_action\"",
+ "CREATE UNIQUE INDEX \"IDX_df3b25181df0b4b59bd93f16e1\" ON \"api_keys\" (\"keyHash\") ",
+ "CREATE INDEX \"IDX_cee5459245f652b75eb2759b4c\" ON \"audit_logs\" (\"action\") ",
+ "CREATE INDEX \"IDX_741fa976d1e04e695f3aa23cb8\" ON \"audit_logs\" (\"apiKeyId\") ",
+ "CREATE INDEX \"IDX_dd2b6e43c767b6b5b2bb227ace\" ON \"audit_logs\" (\"sessionId\") ",
+ "CREATE INDEX \"IDX_c69efb19bf127c97e6740ad530\" ON \"audit_logs\" (\"createdAt\") "
+ ]
+}
diff --git a/src/database/migrations/__tests__/migration-drift.spec.ts b/src/database/migrations/__tests__/migration-drift.spec.ts
index 43ce5bbee..2fe653ef3 100644
--- a/src/database/migrations/__tests__/migration-drift.spec.ts
+++ b/src/database/migrations/__tests__/migration-drift.spec.ts
@@ -1,5 +1,5 @@
import { DataSource } from 'typeorm';
-import { readdirSync } from 'fs';
+import { readdirSync, readFileSync } from 'fs';
import { join } from 'path';
/**
@@ -14,8 +14,9 @@ import { join } from 'path';
*
* Each connection builds its FULL chain on an in-memory SQLite DataSource, then asks TypeORM's
* schema builder what it would change to match the entity metadata (captured inside a transaction
- * that is rolled back, so nothing persists). An empty diff passes; any statement fails with the
- * full list. This is the same harness the from-scratch boot e2e drives (test/sqlite-chain-boot).
+ * that is rolled back, so nothing persists). The result is compared against a pinned snapshot of
+ * the drift the chain carries TODAY. This is the same harness the from-scratch boot e2e drives
+ * (test/sqlite-chain-boot).
*/
const importMigrations = (dir: string): unknown[] => {
const out: unknown[] = [];
@@ -54,98 +55,75 @@ async function driftStatements(ds: DataSource): Promise<string[]> {
}
/**
- * The KNOWN drift the chain carries today: the baseline migration created dated columns as
- * 'datetime' while the entities declare dateColumnType() = 'text' on SQLite (both TEXT affinity,
- * so the data is identical), and the schema builder resolves ANY column-type mismatch by
- * rebuilding the whole table - which surfaces as a CREATE temporary_X + RENAME pair plus every
- * index on the table. The drift is cosmetic (SQLite treats both names as TEXT affinity) but makes
- * migration:generate produce this rebuild instead of a real delta. A normalizing migration at the
- * chain tail closes it; until then, this baseline pins the EXACT set so any NEW drift (a missing
- * index, a missing column, a changed constraint) fails while the known set passes.
+ * The drift the chain carries today, pinned VERBATIM rather than classified by statement shape.
+ *
+ * Shape classification cannot work here. On SQLite the schema builder resolves a column change by
+ * rebuilding the whole table (CREATE temporary_X + INSERT + DROP + RENAME, plus every index on it),
+ * and it emits a bare CREATE INDEX for a new index. Those are the same statement shapes the KNOWN
+ * drift produces, so any filter broad enough to pass the known set also passes a new column and a
+ * new index: exactly the drift this gate exists to catch. Comparing the full statement text does
+ * not have that blind spot, because a new column changes the CREATE TABLE body and a new index adds
+ * a statement that is not in the snapshot.
+ *
+ * The known drift itself is cosmetic: the baseline migration created dated columns as 'datetime'
+ * while the entities declare dateColumnType() = 'text' on SQLite (both TEXT affinity, so the data is
+ * identical), plus index-NAME differences where TypeORM's auto-generated hash names differ from the
+ * migration-declared ones. A normalizing migration at the chain tail closes it.
+ *
+ * WHEN THIS FAILS: read the diff before touching the snapshot. Statements listed as unexpected are
+ * schema your entities declare and your migrations do not create, which is a real bug that reaches
+ * production (a synchronize-disabled deploy answers 500 `no such column` on the first query that
+ * touches it). Regenerate the snapshot only when you have deliberately changed the known drift, for
+ * example by landing a normalizing migration, and expect the count to go DOWN when you do.
*/
-const countRebuildTables = (stmts: string[]): number =>
- new Set(
- stmts.filter(s => s.startsWith('CREATE TABLE "temporary_')).map(s => /"temporary_([^"]+)"/.exec(s)?.[1] ?? ''),
- ).size;
+const KNOWN = JSON.parse(readFileSync(join(__dirname, '__fixtures__/known-migration-drift.json'), 'utf8')) as {
+ data: string[];
+ main: string[];
+};
+
+const expectDriftMatchesSnapshot = (actual: string[], known: string[]): void => {
+ // A snapshot that lost its contents would make any comparison vacuous, so require it to hold the
+ // drift we know is there before comparing against it.
+ expect(known.length).toBeGreaterThan(0);
+ const unexpected = actual.filter(sql => !known.includes(sql));
+ const missing = known.filter(sql => !actual.includes(sql));
+ expect({ unexpected, missing }).toEqual({ unexpected: [], missing: [] });
+};
+
+const dataConnection = (): DataSource =>
+ new DataSource({
+ type: 'better-sqlite3',
+ database: ':memory:',
+ entities: [
+ join(repoRoot, 'src/modules/session/**/*.entity{.ts,.js}'),
+ join(repoRoot, 'src/modules/webhook/**/*.entity{.ts,.js}'),
+ join(repoRoot, 'src/modules/message/**/*.entity{.ts,.js}'),
+ join(repoRoot, 'src/modules/template/**/*.entity{.ts,.js}'),
+ join(repoRoot, 'src/engine/**/*.entity{.ts,.js}'),
+ join(repoRoot, 'src/modules/integration/**/*.entity{.ts,.js}'),
+ join(repoRoot, 'src/modules/status-store/**/*.entity{.ts,.js}'),
+ join(repoRoot, 'src/modules/automation/**/*.entity{.ts,.js}'),
+ ],
+ migrations: importMigrations(join(repoRoot, 'src/database/migrations')) as never,
+ });
+
+const mainConnection = (): DataSource =>
+ new DataSource({
+ type: 'better-sqlite3',
+ database: ':memory:',
+ entities: [
+ join(repoRoot, 'src/modules/auth/**/*.entity{.ts,.js}'),
+ join(repoRoot, 'src/modules/audit/**/*.entity{.ts,.js}'),
+ ],
+ migrations: importMigrations(join(repoRoot, 'src/database/migrations-main')) as never,
+ });
describe('migration chain matches entity metadata (drift gate)', () => {
- it('data connection: drift is EXACTLY the known rebuild set (any new statement fails)', async () => {
- const data = new DataSource({
- type: 'better-sqlite3',
- database: ':memory:',
- entities: [
- join(repoRoot, 'src/modules/session/**/*.entity{.ts,.js}'),
- join(repoRoot, 'src/modules/webhook/**/*.entity{.ts,.js}'),
- join(repoRoot, 'src/modules/message/**/*.entity{.ts,.js}'),
- join(repoRoot, 'src/modules/template/**/*.entity{.ts,.js}'),
- join(repoRoot, 'src/engine/**/*.entity{.ts,.js}'),
- join(repoRoot, 'src/modules/integration/**/*.entity{.ts,.js}'),
- join(repoRoot, 'src/modules/status-store/**/*.entity{.ts,.js}'),
- join(repoRoot, 'src/modules/automation/**/*.entity{.ts,.js}'),
- ],
- migrations: importMigrations(join(repoRoot, 'src/database/migrations')) as never,
- });
- const drift = await driftStatements(data);
- // Classify every statement against the KNOWN drift shapes. The chain carries two:
- // (1) column-type rebuild (datetime vs text) on dated tables, producing the
- // CREATE temporary_ + INSERT + DROP + RENAME + index cycle; (2) index-NAME drift on
- // lid_mappings/status_updates (TypeORM's auto-generated hash names differ from the
- // migration-declared names; same columns, same uniqueness - semantics identical).
- // Anything matching NEITHER shape is structural drift and fails.
- const classifyDrift = (stmts: string[]): string[] =>
- stmts.filter(sql => {
- // Shape 1: column-type rebuild byproducts.
- if (/^CREATE TABLE "temporary_/.test(sql)) return false;
- if (/^ALTER TABLE "temporary_[^"]+" RENAME TO/.test(sql)) return false;
- if (/^INSERT INTO "temporary_/.test(sql)) return false;
- // Shape 2: index-name drift (DROP INDEX old + CREATE INDEX new on the same table, or
- // index recreation on a rebuilt table).
- if (/^DROP INDEX /.test(sql)) return false;
- if (/^CREATE (UNIQUE )?INDEX /.test(sql)) return false;
- if (/^DROP TABLE /.test(sql)) return false;
- return true;
- });
- const structuralDrift = classifyDrift(drift);
- expect(`New structural drift (beyond the known shapes):\n ${structuralDrift.join('\n ')}`).toBe(
- 'New structural drift (beyond the known shapes):\n ',
- );
- // And the rebuild stays bounded to tables that actually carry dated columns.
- expect(countRebuildTables(drift)).toBeGreaterThan(0);
+ it('data connection: drift is EXACTLY the pinned set (a new column or index fails)', async () => {
+ expectDriftMatchesSnapshot(await driftStatements(dataConnection()), KNOWN.data);
}, 60_000);
- it('main connection: drift is EXACTLY the known rebuild set (any new statement fails)', async () => {
- const main = new DataSource({
- type: 'better-sqlite3',
- database: ':memory:',
- entities: [
- join(repoRoot, 'src/modules/auth/**/*.entity{.ts,.js}'),
- join(repoRoot, 'src/modules/audit/**/*.entity{.ts,.js}'),
- ],
- migrations: importMigrations(join(repoRoot, 'src/database/migrations-main')) as never,
- });
- const drift = await driftStatements(main);
- // Classify every statement against the KNOWN drift shapes. The chain carries two:
- // (1) column-type rebuild (datetime vs text) on dated tables, producing the
- // CREATE temporary_ + INSERT + DROP + RENAME + index cycle; (2) index-NAME drift on
- // lid_mappings/status_updates (TypeORM's auto-generated hash names differ from the
- // migration-declared names; same columns, same uniqueness - semantics identical).
- // Anything matching NEITHER shape is structural drift and fails.
- const classifyDrift = (stmts: string[]): string[] =>
- stmts.filter(sql => {
- // Shape 1: column-type rebuild byproducts.
- if (/^CREATE TABLE "temporary_/.test(sql)) return false;
- if (/^ALTER TABLE "temporary_[^"]+" RENAME TO/.test(sql)) return false;
- if (/^INSERT INTO "temporary_/.test(sql)) return false;
- // Shape 2: index-name drift (DROP INDEX old + CREATE INDEX new on the same table, or
- // index recreation on a rebuilt table).
- if (/^DROP INDEX /.test(sql)) return false;
- if (/^CREATE (UNIQUE )?INDEX /.test(sql)) return false;
- if (/^DROP TABLE /.test(sql)) return false;
- return true;
- });
- const structuralDrift = classifyDrift(drift);
- expect(`New structural drift (beyond the known shapes):\n ${structuralDrift.join('\n ')}`).toBe(
- 'New structural drift (beyond the known shapes):\n ',
- );
+ it('main connection: drift is EXACTLY the pinned set (a new column or index fails)', async () => {
+ expectDriftMatchesSnapshot(await driftStatements(mainConnection()), KNOWN.main);
}, 60_000);
});