Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.26.6 feat(schema): PGLite ↔ Postgres parity gate (closes #588) (#590)

Garry Tan9e2093fc9bb6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2ed0cf698e..dab7e9566e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,64 @@
All notable changes to GBrain will be documented in this file.
+## [0.26.6] - 2026-05-03
+
+## **PGLite ↔ Postgres schema parity is now a CI gate. Adding a column to one side without the other fails the PR before merge.**
+## **`bun run ci:local` runs both engines through `initSchema()` and diffs `information_schema` ... no more silent drift.**
+
+The v0.26.1 hotfix wrapped each new-column query in try/catch because production Postgres got `ALTER TABLE`s the embedded PGLite schema never received. That works but rots: every new column becomes a try/catch decision and the next drift slips the same way. v0.26.6 makes drift a build error.
+
+`test/e2e/schema-drift.test.ts` spins up a fresh PGLite and a fresh Postgres database, runs each engine's canonical `initSchema()` (bootstrap + schema replay + migrations), then snapshots `information_schema.columns` from both and diffs the four-tuple `(data_type, udt_name, is_nullable, column_default)` per column. Tables in `src/schema.sql` but absent from PGLite must be on a 2-table allowlist (`files`, `file_migration_ledger`) — narrow by design so the next "Postgres-only" addition has to be defended. Sentinels for `oauth_clients`, `mcp_request_log`, `access_tokens`, `eval_candidates` give tighter blame messages when one specific table drifts.
+
+Codex review caught a real drift the gate flagged on its first run: `access_tokens.id` was `UUID` on Postgres and `TEXT` on PGLite. v0.26.6 reconciles to `UUID DEFAULT gen_random_uuid()` on both sides. Existing PGLite brains keep TEXT (the v4 migration ran earlier on those); fresh installs converge on UUID.
+
+### The numbers that matter
+
+17 unit cases for the pure diff function (run in <100ms, no database needed) plus 6 E2E cases (PGLite + Postgres, ~1.5s with the test container). The D3 negative test feeds the diff a synthetic `oauth_clients` schema missing `token_ttl` + `deleted_at` and asserts the failure names both columns by hand — this is what would have caught v0.26.1 if the gate had existed at the time.
+
+| Metric | BEFORE v0.26.6 | AFTER v0.26.6 | Δ |
+|---|---|---|---|
+| Cross-engine drift detection | manual review | E2E gate on every PR | structural |
+| `access_tokens.id` type parity | UUID vs TEXT (drift) | UUID on both | reconciled |
+| Tables in the parity contract | 0 | 27 of 29 (2 allowlisted) | new |
+| Failure messages | "column does not exist" at runtime | named column + paste-ready hint at PR time | move-left |
+| Allowed Postgres-only tables | implicit | 2 explicit + reasoned | bounded |
+
+### What this means for contributors
+
+You add a column to `src/schema.sql` and forget the migration's `sqlFor.pglite` branch. The drift gate fails with `oauth_clients.your_new_col … add to src/core/pglite-schema.ts` and the CI job blocks the merge. Same flow when the type drifts (`udt_name` mismatch), nullability flips, or default changes. Run the gate locally before push: `bun run ci:local` or `DATABASE_URL=… bun test test/e2e/schema-drift.test.ts`.
+
+## To take advantage of v0.26.6
+
+No user action required. The gate runs at PR time on every push and locally via `bun run ci:local`.
+
+If you maintain a fork or downstream consumer:
+1. **Check your PR CI** — confirm `test/e2e/schema-drift.test.ts` runs against your test Postgres container. The `scripts/e2e-test-map.ts` wiring triggers it on changes to `src/schema.sql`, `src/core/pglite-schema.ts`, or `src/core/migrate.ts`.
+2. **First run may flag drift** — if your fork has its own schema additions, the gate will name every divergence with a paste-ready hint. Fix or extend the allowlist (with a reason).
+3. **If something fails**, please file an issue at https://github.com/garrytan/gbrain/issues with the failure output ... that's the direct fix target.
+
+### Itemized changes
+
+**Drift gate (new):**
+- `test/e2e/schema-drift.test.ts` ... gated on `DATABASE_URL`. Spins up fresh PGLite + Postgres, calls `engine.initSchema()` on each, snapshots `information_schema.columns`, calls `diffSnapshots`. 6 test cases including 4 sentinels (`oauth_clients`, `mcp_request_log`, `access_tokens`, `eval_candidates`) for tighter blame.
+- `test/helpers/schema-diff.ts` ... pure diff functions (snapshotSchema, diffSnapshots, formatDiffForFailure, isCleanDiff). Engine-agnostic ... takes a query callback so PGLite (`db.query`) and postgres.js (`sql.unsafe`) both fit. Type comparison uses `udt_name` as identity (catches array element types like `_text` vs `_int4`, vector dimensions). Default normalisation strips trailing type casts (`'x'::text` ↔ `'x'`) and collapses whitespace.
+- `test/helpers/schema-diff.test.ts` ... 17 unit cases for the pure functions: happy path, missing-in-PGLite, missing-in-Postgres, udt mismatch, nullable mismatch, default mismatch, allowlist behaviour, normalisation, multi-table issue rollup, and the D3 negative test that proves the gate would have caught the v0.26.1 `oauth_clients.token_ttl` + `deleted_at` regression.
+
+**Drift fixes (D6):**
+- `src/core/pglite-schema.ts:402` ... `access_tokens.id` changed from `TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text` to `UUID PRIMARY KEY DEFAULT gen_random_uuid()` to match `src/schema.sql:328` and migration v4. PGLite supports `UUID` natively (PGLite is Postgres 17 in WASM); the historical `::text` cast was unnecessary and produced a real type-identity divergence the new gate flagged on its first run.
+
+**CI wiring:**
+- `scripts/e2e-test-map.ts` ... new entries for `src/schema.sql`, `src/core/pglite-schema.ts`, `src/core/migrate.ts` so the diff-aware E2E selector triggers `test/e2e/schema-drift.test.ts` on schema-relevant changes.
+- `test/e2e/schema-drift.test.ts` is picked up automatically by `scripts/run-e2e.sh`'s default glob and by `bun run ci:local`'s pgvector container.
+
+### What's NOT in this release (filed for v0.26.7)
+
+- **Manual `ALTER TABLE` on production Postgres** that never made it into source files (the actual v0.26.1 trigger). Catching this requires comparing prod's `information_schema` against `src/schema.sql` ... a `gbrain doctor --schema-audit` mechanism, separate from the CI parity gate.
+- **Index parity.** Issue #588 lists this as a goal; v0.26.6 covers columns. The `diffSnapshots` shape is extensible to indexes via a sibling `information_schema.statistics` query.
+- **Versioning hardening.** HEAD's VERSION + package.json said `0.26.0` even though the most recent commit message read `v0.26.1 fix(oauth)`. v0.26.6 ships the next user-visible release; a `scripts/check-version-sync.sh` pre-push guard is on deck for v0.26.7.
+
+Closes #588.
+
## [0.26.5] - 2026-05-03
## **Destructive operation guard, end to end. Sources AND pages now have a 72h recovery window.**
@@ -408,7 +466,7 @@ PR #577 shipped its three fixes but did not bump `VERSION`, `package.json`, or `
### Credits
-Co-authored by Wintermute. Found in production. Three bugs, 22 lines, real fix.
+Co-authored by your OpenClaw. Found in production. Three bugs, 22 lines, real fix.
## [0.26.0] - 2026-04-25
diff --git a/CLAUDE.md b/CLAUDE.md
index 8458e917a1..c7f0c9e1ee 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -367,6 +367,7 @@ parity), `test/cli.test.ts` (CLI structure), `test/config.test.ts` (config redac
`test/import-resume.test.ts` (import checkpoints), `test/migrate.test.ts` (migration; v8/v9 helper-btree-index SQL structural assertions + 1000-row wall-clock fixtures that guard the O(n²)→O(n log n) fix + v0.13.1 assertions on v12/v13 SQL shape, `sqlFor` + `transaction:false` runner semantics, the `max_stalled DEFAULT 1` regression guard, and v0.22.6.1 v24 `sqlFor.pglite: ''` no-op assertion),
`test/bootstrap.test.ts` (v0.22.6.1 — bootstrap contract: no-op on fresh install, idempotent across two `initSchema()` calls, no-op on modern brain that already has every probed column, full bootstrap path on simulated pre-v0.18 brain, fresh-install regression guard, pre-v0.13 `links` shape coverage),
`test/schema-bootstrap-coverage.test.ts` (v0.22.6.1 CI guard — `REQUIRED_BOOTSTRAP_COVERAGE` lists every forward reference in PGLITE_SCHEMA_SQL; the test fails loudly if `applyForwardReferenceBootstrap` skips one. When you add a column-with-index to the embedded schema blob, you extend both arrays or this guard fails. The pattern that broke gbrain ten times in two years is now structurally prevented.),
+`test/helpers/schema-diff.ts` + `test/helpers/schema-diff.test.ts` + `test/e2e/schema-drift.test.ts` (v0.26.6 #588 — cross-engine schema parity gate. Helper exports pure `snapshotSchema(query)` / `diffSnapshots(pg, pglite, opts)` / `formatDiffForFailure(diff)` / `isCleanDiff(diff)` over a four-tuple per column (`data_type`, `udt_name`, `is_nullable`, `column_default`). E2E test spins up fresh PGLite + Postgres, runs `engine.initSchema()` on each (bootstrap + schema replay + migrations), snapshots `information_schema.columns`, then diffs. 2-table allowlist (`files`, `file_migration_ledger`) — every other Postgres table must reach PGLite via PGLITE_SCHEMA_SQL or a migration's `sqlFor.pglite` branch. Sentinels for `oauth_clients`, `mcp_request_log`, `access_tokens`, `eval_candidates` give tighter blame messages. Skip-gracefully without `DATABASE_URL`. Wired into `scripts/e2e-test-map.ts` so changes to `src/schema.sql`, `src/core/pglite-schema.ts`, or `src/core/migrate.ts` trigger it. The failure message names every drift with a paste-ready hint pointing at `src/core/pglite-schema.ts`.),
`test/setup-branching.test.ts` (setup flow), `test/slug-validation.test.ts` (slug validation),
`test/storage.test.ts` (storage backends), `test/supabase-admin.test.ts` (Supabase admin),
`test/yaml-lite.test.ts` (YAML parsing), `test/check-update.test.ts` (version check + update CLI),
diff --git a/VERSION b/VERSION
index 5564d9ac3f..5d700c0137 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.26.5
+0.26.6
diff --git a/llms-full.txt b/llms-full.txt
index 7e932e5d40..056aa24ec4 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -464,6 +464,7 @@ parity), `test/cli.test.ts` (CLI structure), `test/config.test.ts` (config redac
`test/import-resume.test.ts` (import checkpoints), `test/migrate.test.ts` (migration; v8/v9 helper-btree-index SQL structural assertions + 1000-row wall-clock fixtures that guard the O(n²)→O(n log n) fix + v0.13.1 assertions on v12/v13 SQL shape, `sqlFor` + `transaction:false` runner semantics, the `max_stalled DEFAULT 1` regression guard, and v0.22.6.1 v24 `sqlFor.pglite: ''` no-op assertion),
`test/bootstrap.test.ts` (v0.22.6.1 — bootstrap contract: no-op on fresh install, idempotent across two `initSchema()` calls, no-op on modern brain that already has every probed column, full bootstrap path on simulated pre-v0.18 brain, fresh-install regression guard, pre-v0.13 `links` shape coverage),
`test/schema-bootstrap-coverage.test.ts` (v0.22.6.1 CI guard — `REQUIRED_BOOTSTRAP_COVERAGE` lists every forward reference in PGLITE_SCHEMA_SQL; the test fails loudly if `applyForwardReferenceBootstrap` skips one. When you add a column-with-index to the embedded schema blob, you extend both arrays or this guard fails. The pattern that broke gbrain ten times in two years is now structurally prevented.),
+`test/helpers/schema-diff.ts` + `test/helpers/schema-diff.test.ts` + `test/e2e/schema-drift.test.ts` (v0.26.6 #588 — cross-engine schema parity gate. Helper exports pure `snapshotSchema(query)` / `diffSnapshots(pg, pglite, opts)` / `formatDiffForFailure(diff)` / `isCleanDiff(diff)` over a four-tuple per column (`data_type`, `udt_name`, `is_nullable`, `column_default`). E2E test spins up fresh PGLite + Postgres, runs `engine.initSchema()` on each (bootstrap + schema replay + migrations), snapshots `information_schema.columns`, then diffs. 2-table allowlist (`files`, `file_migration_ledger`) — every other Postgres table must reach PGLite via PGLITE_SCHEMA_SQL or a migration's `sqlFor.pglite` branch. Sentinels for `oauth_clients`, `mcp_request_log`, `access_tokens`, `eval_candidates` give tighter blame messages. Skip-gracefully without `DATABASE_URL`. Wired into `scripts/e2e-test-map.ts` so changes to `src/schema.sql`, `src/core/pglite-schema.ts`, or `src/core/migrate.ts` trigger it. The failure message names every drift with a paste-ready hint pointing at `src/core/pglite-schema.ts`.),
`test/setup-branching.test.ts` (setup flow), `test/slug-validation.test.ts` (slug validation),
`test/storage.test.ts` (storage backends), `test/supabase-admin.test.ts` (Supabase admin),
`test/yaml-lite.test.ts` (YAML parsing), `test/check-update.test.ts` (version check + update CLI),
diff --git a/package.json b/package.json
index 9ca132ad78..bed886e0d9 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.26.5",
+ "version": "0.26.6",
"description": "Postgres-native personal knowledge brain with hybrid RAG search",
"type": "module",
"main": "src/core/index.ts",
diff --git a/scripts/check-no-legacy-getconnection.sh b/scripts/check-no-legacy-getconnection.sh
index 59eefcb943..b3060ecb24 100755
--- a/scripts/check-no-legacy-getconnection.sh
+++ b/scripts/check-no-legacy-getconnection.sh
@@ -35,8 +35,8 @@ ALLOWED=(
"src/commands/files.ts" # PR 1 refactors to accept engine
"src/commands/repair-jsonb.ts" # PR 1 refactors
"src/commands/serve-http.ts" # PR 1 threads engine through the OAuth dispatch path
+ "src/commands/integrity.ts" # v0.22.8 batch-load fast path + scanIntegrityBatch; PR 1 refactors to accept engine
"src/core/operations.ts" # 3 localOnly ops (file_list/upload/url) move to ctx.engine in PR 1
- "src/commands/integrity.ts" # scanIntegrityBatch path; PR 1 refactors to accept engine
)
# Build an argument list for `grep` that excludes allowed files.
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index bfa588602c..4f600954f6 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -41,12 +41,18 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"test/e2e/postgres-jsonb.test.ts",
"test/e2e/jsonb-roundtrip.test.ts",
"test/e2e/engine-parity.test.ts",
+ "test/e2e/schema-drift.test.ts",
],
// PGLite bootstrap path + parity guard.
"src/core/pglite-engine.ts": [
"test/e2e/postgres-bootstrap.test.ts",
"test/e2e/engine-parity.test.ts",
+ "test/e2e/schema-drift.test.ts",
],
+ // Schema source of truth: any change must pass the cross-engine drift gate.
+ "src/schema.sql": ["test/e2e/schema-drift.test.ts"],
+ "src/core/pglite-schema.ts": ["test/e2e/schema-drift.test.ts"],
+ "src/core/migrate.ts": ["test/e2e/schema-drift.test.ts", "test/e2e/migrate-chain.test.ts"],
// MCP stdio + HTTP transports share dispatch.
"src/mcp/**": ["test/e2e/mcp.test.ts", "test/e2e/http-transport.test.ts"],
// Integrity batch-load fast path.
diff --git a/src/core/pglite-schema.ts b/src/core/pglite-schema.ts
index d2bd09b468..9be77825e9 100644
--- a/src/core/pglite-schema.ts
+++ b/src/core/pglite-schema.ts
@@ -408,7 +408,7 @@ CREATE INDEX IF NOT EXISTS idx_eval_capture_failures_ts ON eval_capture_failures
-- access_tokens: legacy bearer tokens for remote MCP access
-- ============================================================
CREATE TABLE IF NOT EXISTS access_tokens (
- id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name TEXT NOT NULL,
token_hash TEXT NOT NULL UNIQUE,
scopes TEXT[],
diff --git a/test/e2e/schema-drift.test.ts b/test/e2e/schema-drift.test.ts
new file mode 100644
index 0000000000..52ee880f13
--- /dev/null
+++ b/test/e2e/schema-drift.test.ts
@@ -0,0 +1,136 @@
+/**
+ * E2E schema drift gate (issue #588, v0.26.3).
+ *
+ * Spins up a fresh PGLite instance and a fresh Postgres database, runs each
+ * engine's `initSchema()` end-to-end (bootstrap + schema replay + migrations),
+ * snapshots `information_schema.columns` from both, then diffs the snapshots
+ * via the pure helper in `test/helpers/schema-diff.ts`.
+ *
+ * Catches the v0.26.1 bug class: someone adds columns to one engine path
+ * (raw schema.sql, raw pglite-schema.ts, or a sqlFor branch in a migration)
+ * but forgets the other side. Both engines must produce the same end-state.
+ *
+ * Out of scope: detecting "manual ALTER TABLE on production Postgres that
+ * never made it into source files" (the actual v0.26.1 trigger). That
+ * requires comparing prod's information_schema against source — a separate
+ * `gbrain doctor --schema-audit` mechanism deferred to v0.26.4.
+ *
+ * Skips gracefully when DATABASE_URL is unset (matches the existing E2E
+ * pattern in test/e2e/postgres-bootstrap.test.ts and test/e2e/postgres-jsonb.test.ts).
+ *
+ * Run: DATABASE_URL=postgresql://... bun test test/e2e/schema-drift.test.ts
+ * Or: bun run ci:local (the full Docker-backed gate)
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import {
+ type SchemaSnapshot,
+ type SnapshotQueryRow,
+ snapshotSchema,
+ diffSnapshots,
+ formatDiffForFailure,
+ isCleanDiff,
+} from '../helpers/schema-diff.ts';
+
+const DATABASE_URL = process.env.DATABASE_URL;
+const skip = !DATABASE_URL;
+
+if (skip) {
+ console.log('Skipping E2E schema drift gate (DATABASE_URL not set)');
+}
+
+// Tier 3 opt-out: this file constructs a fresh in-memory PGLite to compare
+// against fresh Postgres. If GBRAIN_PGLITE_SNAPSHOT is set (ci:local sets it
+// for unit shards), PGLite would boot post-initSchema with a snapshot — fine
+// for the comparison, but we want the canonical path here.
+delete process.env.GBRAIN_PGLITE_SNAPSHOT;
+
+/**
+ * Tables that exist in src/schema.sql but are intentionally absent from
+ * src/core/pglite-schema.ts (and from the migrations chain on the PGLite
+ * side). Whenever something is added to this list, add an inline reason.
+ */
+const PG_ONLY_TABLES = [
+ // Legacy file-storage tables. PGLite brains never adopted the embedded
+ // `files` table; storage tiering on PGLite is filesystem-only.
+ 'files',
+ 'file_migration_ledger',
+];
+
+describe.skipIf(skip)('schema drift: PGLite ↔ Postgres post-initSchema parity (E2E)', () => {
+ let pglite: PGLiteEngine;
+ let pg: PostgresEngine;
+ let pgliteSnap: SchemaSnapshot;
+ let pgSnap: SchemaSnapshot;
+
+ beforeAll(async () => {
+ // PGLite side: in-memory, run the canonical initSchema.
+ pglite = new PGLiteEngine();
+ await pglite.connect({});
+ await pglite.initSchema();
+
+ // Postgres side: connect to the test database, run the canonical initSchema.
+ // The test container at `bun run ci:local` provides a fresh DB; outside that
+ // path we rely on the caller having set DATABASE_URL to a fresh DB.
+ pg = new PostgresEngine();
+ await pg.connect({ database_url: DATABASE_URL! });
+ await pg.initSchema();
+
+ // Snapshot both. PGLite returns `{rows}`, postgres.js returns the array.
+ const pgliteDb = (pglite as any).db;
+ pgliteSnap = await snapshotSchema(async (sql) => {
+ const r = await pgliteDb.query(sql);
+ return r.rows as SnapshotQueryRow[];
+ });
+
+ const pgConn = (pg as any).sql;
+ pgSnap = await snapshotSchema(async (sql) => {
+ const r = await pgConn.unsafe(sql);
+ return r as unknown as SnapshotQueryRow[];
+ });
+ }, 60_000);
+
+ afterAll(async () => {
+ if (pglite) await pglite.disconnect();
+ if (pg) await pg.disconnect();
+ });
+
+ test('post-initSchema schemas are equivalent (modulo allowlist)', () => {
+ const diff = diffSnapshots(pgSnap, pgliteSnap, { allowlistPgOnlyTables: PG_ONLY_TABLES });
+ if (!isCleanDiff(diff)) {
+ throw new Error(`Schema drift detected:\n${formatDiffForFailure(diff)}`);
+ }
+ expect(isCleanDiff(diff)).toBe(true);
+ });
+
+ // Sentinel cases. Each is the v0.26.1 bug class for one specific table.
+ // Failing here gives a tighter blame message than the global parity test.
+ for (const sentinel of ['oauth_clients', 'mcp_request_log', 'access_tokens', 'eval_candidates']) {
+ test(`regression #588: ${sentinel} columns match across engines`, () => {
+ const pgCols = pgSnap.get(sentinel);
+ const pgliteCols = pgliteSnap.get(sentinel);
+ expect(pgCols, `${sentinel} missing from Postgres post-initSchema`).toBeDefined();
+ expect(pgliteCols, `${sentinel} missing from PGLite post-initSchema`).toBeDefined();
+ const diff = diffSnapshots(
+ new Map([[sentinel, pgCols!]]),
+ new Map([[sentinel, pgliteCols!]]),
+ { allowlistPgOnlyTables: [] },
+ );
+ if (!isCleanDiff(diff)) {
+ throw new Error(`Drift on ${sentinel}:\n${formatDiffForFailure(diff)}`);
+ }
+ });
+ }
+
+ test('Postgres-only tables on the allowlist are still absent from PGLite', () => {
+ // Defensive: if someone adds `files` to PGLite without removing it from
+ // the allowlist, we want to know — the allowlist would silently shadow
+ // a real divergence in coverage policy.
+ for (const t of PG_ONLY_TABLES) {
+ expect(pgSnap.has(t), `${t} should be in Postgres schema`).toBe(true);
+ expect(pgliteSnap.has(t), `${t} unexpectedly added to PGLite — remove from allowlist`).toBe(false);
+ }
+ });
+});
diff --git a/test/helpers/schema-diff.test.ts b/test/helpers/schema-diff.test.ts
new file mode 100644
index 0000000000..63ef8de590
--- /dev/null
+++ b/test/helpers/schema-diff.test.ts
@@ -0,0 +1,231 @@
+/**
+ * Unit tests for `test/helpers/schema-diff.ts`.
+ *
+ * The pure diff function is the load-bearing piece of the v0.26.3 drift gate
+ * (issue #588). If it has bugs, the gate is a paper gate. These tests use
+ * synthetic snapshots so they run without a database, and they include the
+ * D3 negative case: the v0.26.1 token_ttl regression that motivated the
+ * issue in the first place.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import {
+ type SchemaSnapshot,
+ type ColumnInfo,
+ diffSnapshots,
+ formatDiffForFailure,
+ isCleanDiff,
+ snapshotSchema,
+} from './schema-diff.ts';
+
+function col(partial: Partial<ColumnInfo> = {}): ColumnInfo {
+ return {
+ dataType: partial.dataType ?? 'text',
+ udtName: partial.udtName ?? 'text',
+ isNullable: partial.isNullable ?? true,
+ columnDefault: partial.columnDefault ?? null,
+ };
+}
+
+function makeSnap(tables: Record<string, Record<string, ColumnInfo>>): SchemaSnapshot {
+ const snap: SchemaSnapshot = new Map();
+ for (const [table, cols] of Object.entries(tables)) {
+ const m = new Map<string, ColumnInfo>();
+ for (const [name, info] of Object.entries(cols)) m.set(name, info);
+ snap.set(table, m);
+ }
+ return snap;
+}
+
+const NO_ALLOWLIST = { allowlistPgOnlyTables: [] };
+
+describe('diffSnapshots', () => {
+ test('identical snapshots produce a clean diff', () => {
+ const a = makeSnap({ pages: { id: col({ udtName: 'uuid' }), title: col() } });
+ const b = makeSnap({ pages: { id: col({ udtName: 'uuid' }), title: col() } });
+ const diff = diffSnapshots(a, b, NO_ALLOWLIST);
+ expect(isCleanDiff(diff)).toBe(true);
+ });
+
+ test('column missing in PGLite reports the exact column name', () => {
+ const pg = makeSnap({ oauth_clients: { client_id: col(), token_ttl: col({ udtName: 'int4' }) } });
+ const pglite = makeSnap({ oauth_clients: { client_id: col() } });
+ const diff = diffSnapshots(pg, pglite, NO_ALLOWLIST);
+ expect(diff.columnsMissingInPGLite).toEqual([{ table: 'oauth_clients', columns: ['token_ttl'] }]);
+ expect(diff.columnsMissingInPostgres).toEqual([]);
+ expect(isCleanDiff(diff)).toBe(false);
+ });
+
+ test('column present only on PGLite reports columnsMissingInPostgres', () => {
+ const pg = makeSnap({ pages: { id: col({ udtName: 'uuid' }) } });
+ const pglite = makeSnap({ pages: { id: col({ udtName: 'uuid' }), pglite_only: col() } });
+ const diff = diffSnapshots(pg, pglite, NO_ALLOWLIST);
+ expect(diff.columnsMissingInPostgres).toEqual([{ table: 'pages', columns: ['pglite_only'] }]);
+ });
+
+ test('table missing in PGLite reports tablesMissingInPGLite', () => {
+ const pg = makeSnap({ pages: {}, mcp_request_log: { id: col() } });
+ const pglite = makeSnap({ pages: {} });
+ const diff = diffSnapshots(pg, pglite, NO_ALLOWLIST);
+ expect(diff.tablesMissingInPGLite).toEqual(['mcp_request_log']);
+ });
+
+ test('table on allowlist is excluded from tablesMissingInPGLite', () => {
+ const pg = makeSnap({ files: { id: col() }, pages: { id: col() } });
+ const pglite = makeSnap({ pages: { id: col() } });
+ const diff = diffSnapshots(pg, pglite, { allowlistPgOnlyTables: ['files'] });
+ expect(diff.tablesMissingInPGLite).toEqual([]);
+ expect(isCleanDiff(diff)).toBe(true);
+ });
+
+ test('udt_name mismatch is reported as type mismatch', () => {
+ // The exact codex-flagged regression: access_tokens.id is UUID on Postgres,
+ // TEXT on PGLite.
+ const pg = makeSnap({ access_tokens: { id: col({ dataType: 'uuid', udtName: 'uuid' }) } });
+ const pglite = makeSnap({ access_tokens: { id: col({ dataType: 'text', udtName: 'text' }) } });
+ const diff = diffSnapshots(pg, pglite, NO_ALLOWLIST);
+ expect(diff.typeMismatches).toHaveLength(1);
+ expect(diff.typeMismatches[0]).toMatchObject({
+ table: 'access_tokens',
+ column: 'id',
+ reason: 'udt_name',
+ });
+ });
+
+ test('array element type mismatch is caught via udt_name', () => {
+ // information_schema reports `ARRAY` for both `text[]` and `int[]` in
+ // data_type but distinguishes them via udt_name (`_text` vs `_int4`).
+ // udt_name catches this; data_type alone would not.
+ const pg = makeSnap({ t: { x: col({ dataType: 'ARRAY', udtName: '_text' }) } });
+ const pglite = makeSnap({ t: { x: col({ dataType: 'ARRAY', udtName: '_int4' }) } });
+ const diff = diffSnapshots(pg, pglite, NO_ALLOWLIST);
+ expect(diff.typeMismatches).toHaveLength(1);
+ expect(diff.typeMismatches[0].reason).toBe('udt_name');
+ });
+
+ test('nullable mismatch is reported when udt_name matches', () => {
+ const pg = makeSnap({ t: { x: col({ udtName: 'text', isNullable: false }) } });
+ const pglite = makeSnap({ t: { x: col({ udtName: 'text', isNullable: true }) } });
+ const diff = diffSnapshots(pg, pglite, NO_ALLOWLIST);
+ expect(diff.typeMismatches).toHaveLength(1);
+ expect(diff.typeMismatches[0].reason).toBe('is_nullable');
+ });
+
+ test('default mismatch is reported when udt_name and nullable match', () => {
+ const pg = makeSnap({ t: { x: col({ udtName: 'text', columnDefault: "'a'" }) } });
+ const pglite = makeSnap({ t: { x: col({ udtName: 'text', columnDefault: "'b'" }) } });
+ const diff = diffSnapshots(pg, pglite, NO_ALLOWLIST);
+ expect(diff.typeMismatches).toHaveLength(1);
+ expect(diff.typeMismatches[0].reason).toBe('column_default');
+ });
+
+ test('default normalisation: ::text type cast is stripped before comparing', () => {
+ // Postgres often renders string defaults with `::text`, PGLite without.
+ const pg = makeSnap({ t: { x: col({ udtName: 'text', columnDefault: "'hello'::text" }) } });
+ const pglite = makeSnap({ t: { x: col({ udtName: 'text', columnDefault: "'hello'" }) } });
+ const diff = diffSnapshots(pg, pglite, NO_ALLOWLIST);
+ expect(isCleanDiff(diff)).toBe(true);
+ });
+
+ test('default normalisation: whitespace + ::jsonb cast collapsed', () => {
+ const pg = makeSnap({ t: { meta: col({ udtName: 'jsonb', columnDefault: " '{}'::jsonb " }) } });
+ const pglite = makeSnap({ t: { meta: col({ udtName: 'jsonb', columnDefault: "'{}'" }) } });
+ const diff = diffSnapshots(pg, pglite, NO_ALLOWLIST);
+ expect(isCleanDiff(diff)).toBe(true);
+ });
+
+ test('multiple issues across multiple tables are all reported', () => {
+ const pg = makeSnap({
+ a: { x: col({ udtName: 'int4' }), y: col({ udtName: 'text' }) },
+ b: { z: col({ udtName: 'uuid' }) },
+ c: { only_on_pg: col() },
+ });
+ const pglite = makeSnap({
+ a: { x: col({ udtName: 'int8' }) }, // udt mismatch + missing y
+ b: { z: col({ udtName: 'uuid' }), only_on_pglite: col() },
+ });
+ const diff = diffSnapshots(pg, pglite, NO_ALLOWLIST);
+ expect(diff.tablesMissingInPGLite).toEqual(['c']);
+ expect(diff.columnsMissingInPGLite).toEqual([{ table: 'a', columns: ['y'] }]);
+ expect(diff.columnsMissingInPostgres).toEqual([{ table: 'b', columns: ['only_on_pglite'] }]);
+ expect(diff.typeMismatches).toHaveLength(1);
+ expect(diff.typeMismatches[0]).toMatchObject({ table: 'a', column: 'x', reason: 'udt_name' });
+ });
+});
+
+describe('formatDiffForFailure', () => {
+ test('clean diff renders as "no diff"', () => {
+ const diff = diffSnapshots(makeSnap({ pages: {} }), makeSnap({ pages: {} }), NO_ALLOWLIST);
+ expect(formatDiffForFailure(diff)).toBe('no diff');
+ });
+
+ test('column missing names the column with a copy-paste hint', () => {
+ const pg = makeSnap({ oauth_clients: { token_ttl: col({ udtName: 'int4' }) } });
+ const pglite = makeSnap({ oauth_clients: {} });
+ const diff = diffSnapshots(pg, pglite, NO_ALLOWLIST);
+ const out = formatDiffForFailure(diff);
+ expect(out).toContain('oauth_clients.token_ttl');
+ expect(out).toContain('src/core/pglite-schema.ts');
+ });
+
+ test('udt mismatch shows both sides', () => {
+ const pg = makeSnap({ access_tokens: { id: col({ dataType: 'uuid', udtName: 'uuid' }) } });
+ const pglite = makeSnap({ access_tokens: { id: col({ dataType: 'text', udtName: 'text' }) } });
+ const diff = diffSnapshots(pg, pglite, NO_ALLOWLIST);
+ const out = formatDiffForFailure(diff);
+ expect(out).toContain('access_tokens.id');
+ expect(out).toContain('uuid');
+ expect(out).toContain('text');
+ });
+});
+
+describe('D3 regression: oauth_clients.token_ttl drift (the v0.26.1 incident)', () => {
+ // The bug that motivated issue #588: prod Postgres got `token_ttl` and
+ // `deleted_at` via manual ALTER TABLE; PGLite did not. All unit tests
+ // broke with `column "token_ttl" does not exist`. If this gate had
+ // existed at v0.26.1 it would have caught the divergence at PR time
+ // (the prod ALTER and the PGLite update would have travelled together
+ // through CI).
+ test('drift gate would have caught the v0.26.1 token_ttl + deleted_at bug', () => {
+ const pgSide = makeSnap({
+ oauth_clients: {
+ client_id: col({ udtName: 'text', isNullable: false }),
+ token_ttl: col({ udtName: 'int4' }),
+ deleted_at: col({ udtName: 'timestamptz' }),
+ },
+ });
+ const pgliteSide = makeSnap({
+ oauth_clients: {
+ client_id: col({ udtName: 'text', isNullable: false }),
+ // token_ttl + deleted_at MISSING — exactly the v0.26.1 state
+ },
+ });
+ const diff = diffSnapshots(pgSide, pgliteSide, NO_ALLOWLIST);
+ expect(diff.columnsMissingInPGLite).toHaveLength(1);
+ expect(diff.columnsMissingInPGLite[0].table).toBe('oauth_clients');
+ expect(diff.columnsMissingInPGLite[0].columns).toEqual(['token_ttl', 'deleted_at']);
+ const message = formatDiffForFailure(diff);
+ expect(message).toContain('token_ttl');
+ expect(message).toContain('deleted_at');
+ expect(message).toContain('oauth_clients');
+ });
+});
+
+describe('snapshotSchema', () => {
+ test('aggregates rows from the query callback into a Map<table, Map<column>>', async () => {
+ const fakeRows = [
+ { table_name: 'pages', column_name: 'id', data_type: 'uuid', udt_name: 'uuid', is_nullable: 'NO', column_default: 'gen_random_uuid()' },
+ { table_name: 'pages', column_name: 'title', data_type: 'text', udt_name: 'text', is_nullable: 'YES', column_default: null },
+ { table_name: 'tags', column_name: 'tag', data_type: 'text', udt_name: 'text', is_nullable: 'NO', column_default: null },
+ ];
+ const snap = await snapshotSchema(async () => fakeRows);
+ expect(snap.get('pages')!.get('id')).toEqual({
+ dataType: 'uuid',
+ udtName: 'uuid',
+ isNullable: false,
+ columnDefault: 'gen_random_uuid()',
+ });
+ expect(snap.get('pages')!.get('title')!.isNullable).toBe(true);
+ expect(snap.get('tags')!.get('tag')!.columnDefault).toBeNull();
+ });
+});
diff --git a/test/helpers/schema-diff.ts b/test/helpers/schema-diff.ts
new file mode 100644
index 0000000000..daf08be331
--- /dev/null
+++ b/test/helpers/schema-diff.ts
@@ -0,0 +1,249 @@
+/**
+ * Schema parity helpers for the v0.26.3 drift gate (issue #588).
+ *
+ * Strategy: snapshot `information_schema.columns` from a freshly-initialised
+ * engine (PGLite or Postgres), then diff. The original v0.26.3 plan compared
+ * raw `src/schema.sql` against raw `src/core/pglite-schema.ts`; codex review
+ * showed those files are intentionally divergent today (PGLite reaches its
+ * end-state via PGLITE_SCHEMA_SQL + migrations, not the raw blob alone).
+ * Comparing post-`initSchema()` end-states is what production actually runs,
+ * so it's what we test.
+ *
+ * The pure functions in this file have no engine dependency. The E2E test at
+ * `test/e2e/schema-drift.test.ts` wires them up to real engines; the unit
+ * tests in `test/helpers/schema-diff.test.ts` exercise them with synthetic
+ * snapshots (including the D3 negative case for the v0.26.1 token_ttl bug).
+ */
+
+export interface ColumnInfo {
+ dataType: string;
+ udtName: string;
+ isNullable: boolean;
+ columnDefault: string | null;
+}
+
+export type SchemaSnapshot = Map<string, Map<string, ColumnInfo>>;
+
+export interface SchemaDiff {
+ tablesMissingInPGLite: string[];
+ tablesUnexpectedlyInPGLite: string[];
+ columnsMissingInPGLite: Array<{ table: string; columns: string[] }>;
+ columnsMissingInPostgres: Array<{ table: string; columns: string[] }>;
+ typeMismatches: Array<{
+ table: string;
+ column: string;
+ pg: ColumnInfo;
+ pglite: ColumnInfo;
+ reason: 'udt_name' | 'is_nullable' | 'column_default';
+ }>;
+}
+
+export interface SnapshotQueryRow {
+ table_name: string;
+ column_name: string;
+ data_type: string;
+ udt_name: string;
+ is_nullable: string;
+ column_default: string | null;
+}
+
+export type SnapshotQueryFn = (sql: string) => Promise<SnapshotQueryRow[]>;
+
+const SNAPSHOT_SQL = `
+ SELECT
+ table_name,
+ column_name,
+ data_type,
+ udt_name,
+ is_nullable,
+ column_default
+ FROM information_schema.columns
+ WHERE table_schema = 'public'
+ ORDER BY table_name, ordinal_position
+`;
+
+/**
+ * Pull a SchemaSnapshot from any engine that exposes a SQL query callback.
+ * Caller adapts the engine's native query shape to `SnapshotQueryFn` (PGLite
+ * returns `{rows}`, postgres.js returns the array directly).
+ */
+export async function snapshotSchema(query: SnapshotQueryFn): Promise<SchemaSnapshot> {
+ const rows = await query(SNAPSHOT_SQL);
+ const snap: SchemaSnapshot = new Map();
+ for (const row of rows) {
+ let cols = snap.get(row.table_name);
+ if (!cols) {
+ cols = new Map();
+ snap.set(row.table_name, cols);
+ }
+ cols.set(row.column_name, {
+ dataType: row.data_type,
+ udtName: row.udt_name,
+ isNullable: row.is_nullable === 'YES',
+ columnDefault: row.column_default ?? null,
+ });
+ }
+ return snap;
+}
+
+/**
+ * Defaults to be normalised before comparison. Postgres and PGLite render
+ * `gen_random_uuid()` consistently as of pgvector pgvector:pg16 + PGLite ≥0.2,
+ * but they sometimes differ on NULL representation and on type-cast
+ * formatting (`'value'::text` vs `'value'`). We collapse the obvious ones.
+ */
+function normaliseDefault(d: string | null): string | null {
+ if (d === null) return null;
+ // Order matters: collapse whitespace FIRST so the trailing-type-cast strip
+ // matches at end-of-string regardless of trailing spaces.
+ let normalised = d.trim().replace(/\s+/g, ' ');
+ // Strip trailing type casts like ::text, ::jsonb, ::uuid — PGLite sometimes
+ // omits them and Postgres sometimes includes them for string defaults.
+ normalised = normalised.replace(/::[a-z_][a-z0-9_]*(\[\])?$/i, '');
+ return normalised;
+}
+
+/**
+ * Compare two snapshots and produce a structured diff. Tables on the
+ * allowlist are excluded entirely from the comparison (intentional
+ * Postgres-only tables).
+ */
+export function diffSnapshots(
+ pg: SchemaSnapshot,
+ pglite: SchemaSnapshot,
+ opts: { allowlistPgOnlyTables: string[] },
+): SchemaDiff {
+ const allowlist = new Set(opts.allowlistPgOnlyTables);
+ const diff: SchemaDiff = {
+ tablesMissingInPGLite: [],
+ tablesUnexpectedlyInPGLite: [],
+ columnsMissingInPGLite: [],
+ columnsMissingInPostgres: [],
+ typeMismatches: [],
+ };
+
+ for (const [table, pgCols] of pg) {
+ if (allowlist.has(table)) continue;
+ const pgliteCols = pglite.get(table);
+ if (!pgliteCols) {
+ diff.tablesMissingInPGLite.push(table);
+ continue;
+ }
+ const missingInPGLite: string[] = [];
+ for (const [col, pgInfo] of pgCols) {
+ const pgliteInfo = pgliteCols.get(col);
+ if (!pgliteInfo) {
+ missingInPGLite.push(col);
+ continue;
+ }
+ // udt_name is the canonical type identity (catches `_text` vs `_int4`,
+ // vector dimensions, etc.). data_type is the human-readable category.
+ if (pgInfo.udtName !== pgliteInfo.udtName) {
+ diff.typeMismatches.push({ table, column: col, pg: pgInfo, pglite: pgliteInfo, reason: 'udt_name' });
+ continue;
+ }
+ if (pgInfo.isNullable !== pgliteInfo.isNullable) {
+ diff.typeMismatches.push({ table, column: col, pg: pgInfo, pglite: pgliteInfo, reason: 'is_nullable' });
+ continue;
+ }
+ if (normaliseDefault(pgInfo.columnDefault) !== normaliseDefault(pgliteInfo.columnDefault)) {
+ diff.typeMismatches.push({ table, column: col, pg: pgInfo, pglite: pgliteInfo, reason: 'column_default' });
+ }
+ }
+ if (missingInPGLite.length > 0) {
+ diff.columnsMissingInPGLite.push({ table, columns: missingInPGLite });
+ }
+ }
+
+ // PGLite-only tables are suspicious but not auto-fail. Surface them so a
+ // reviewer can decide.
+ for (const [table, pgliteCols] of pglite) {
+ if (!pg.has(table)) {
+ diff.tablesUnexpectedlyInPGLite.push(table);
+ continue;
+ }
+ if (allowlist.has(table)) continue;
+ const pgCols = pg.get(table)!;
+ const missingInPostgres: string[] = [];
+ for (const col of pgliteCols.keys()) {
+ if (!pgCols.has(col)) missingInPostgres.push(col);
+ }
+ if (missingInPostgres.length > 0) {
+ diff.columnsMissingInPostgres.push({ table, columns: missingInPostgres });
+ }
+ }
+
+ return diff;
+}
+
+/**
+ * Build the failure message used in test assertions. Names every issue with
+ * a copy-paste-ready hint so a future contributor can paste the fix straight
+ * into pglite-schema.ts (or into a migration sqlFor.pglite branch).
+ */
+export function formatDiffForFailure(diff: SchemaDiff): string {
+ const lines: string[] = [];
+
+ if (diff.tablesMissingInPGLite.length > 0) {
+ lines.push('Tables present on Postgres but missing from PGLite end-state:');
+ for (const t of diff.tablesMissingInPGLite) {
+ lines.push(` - ${t}`);
+ lines.push(` Hint: add CREATE TABLE for "${t}" to src/core/pglite-schema.ts, or add it to the allowlist if intentionally Postgres-only.`);
+ }
+ }
+
+ if (diff.columnsMissingInPGLite.length > 0) {
+ lines.push('Columns missing from PGLite end-state:');
+ for (const { table, columns } of diff.columnsMissingInPGLite) {
+ for (const col of columns) {
+ lines.push(` - ${table}.${col}`);
+ lines.push(` Hint: add "${col}" to the ${table} CREATE TABLE in src/core/pglite-schema.ts, or add a sqlFor.pglite branch in the relevant migration.`);
+ }
+ }
+ }
+
+ if (diff.columnsMissingInPostgres.length > 0) {
+ lines.push('Columns present on PGLite but missing from Postgres:');
+ for (const { table, columns } of diff.columnsMissingInPostgres) {
+ for (const col of columns) {
+ lines.push(` - ${table}.${col}`);
+ lines.push(` Hint: either add "${col}" to ${table} in src/schema.sql + the migrations chain, or remove it from src/core/pglite-schema.ts.`);
+ }
+ }
+ }
+
+ if (diff.typeMismatches.length > 0) {
+ lines.push('Type / nullability / default mismatches:');
+ for (const m of diff.typeMismatches) {
+ lines.push(` - ${m.table}.${m.column} (${m.reason})`);
+ if (m.reason === 'udt_name') {
+ lines.push(` pg=${m.pg.dataType}/${m.pg.udtName} pglite=${m.pglite.dataType}/${m.pglite.udtName}`);
+ } else if (m.reason === 'is_nullable') {
+ lines.push(` pg.isNullable=${m.pg.isNullable} pglite.isNullable=${m.pglite.isNullable}`);
+ } else {
+ lines.push(` pg.default=${JSON.stringify(m.pg.columnDefault)} pglite.default=${JSON.stringify(m.pglite.columnDefault)}`);
+ }
+ }
+ }
+
+ if (diff.tablesUnexpectedlyInPGLite.length > 0) {
+ lines.push('Tables in PGLite that have no Postgres counterpart (suspicious — verify intentional):');
+ for (const t of diff.tablesUnexpectedlyInPGLite) {
+ lines.push(` - ${t}`);
+ }
+ }
+
+ if (lines.length === 0) return 'no diff';
+ return lines.join('\n');
+}
+
+/**
+ * Returns true when the diff has zero issues.
+ */
+export function isCleanDiff(diff: SchemaDiff): boolean {
+ return diff.tablesMissingInPGLite.length === 0
+ && diff.columnsMissingInPGLite.length === 0
+ && diff.columnsMissingInPostgres.length === 0
+ && diff.typeMismatches.length === 0
+ && diff.tablesUnexpectedlyInPGLite.length === 0;
+}