Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(schema): bootstrap derived_generation_items.pending so v265 brains upgrade (#7645)
garrytane0c8cd1b777d
diff --git a/scripts/capture-schema-history-fixture.ts b/scripts/capture-schema-history-fixture.tsnew file mode 100644index 0000000000..d21ab6ebf5--- /dev/null+++ b/scripts/capture-schema-history-fixture.ts@@ -0,0 +1,290 @@+#!/usr/bin/env bun+/**+ * Captures a schema-history fixture: the schema and rows of a brain created by+ * an older gbrain release, as gzipped plain SQL, so the schema-history upgrade tests+ * can upgrade it with today's code (#7645: a v265 brain could not reach v266).+ *+ * git worktree add --detach /tmp/gbrain-v270 <release commit>+ * ln -s "$PWD/node_modules" /tmp/gbrain-v270/node_modules+ * bun scripts/capture-schema-history-fixture.ts --tree /tmp/gbrain-v270 --engine pglite+ * DATABASE_URL=postgresql://... bun scripts/capture-schema-history-fixture.ts --tree /tmp/gbrain-v270 --engine postgres+ *+ * The release's own engine runs initSchema (bootstrap, schema blob and every+ * migration of that release) on an empty database. The dump is then restored+ * into a second empty database through today's engine connect, and the script+ * refuses to write the fixture unless the restored catalog, function bodies and+ * rows equal the original's. Generated secrets are blanked before the dump.+ */+import { mkdirSync, writeFileSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { randomUUID } from 'node:crypto';+import postgres from '#postgres';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { LEGACY_EMBEDDING_CONFIG } from '../test/helpers/legacy-embedding-config.ts';+import { diffCatalogSnapshots, formatCatalogDiffForFailure, snapshotCatalog, type CatalogQueryFn } from '../test/helpers/schema-diff.ts';+import { FUNCTION_BODIES_SQL } from '../test/helpers/schema-catalog.ts';++type Query = (sql: string) => Promise<Array<Record<string, any>>>;+type Engine = 'pglite' | 'postgres';++const NOT_EXTENSION_MEMBER = (classid: string, objid: string) =>+ `NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = '${classid}'::regclass AND d.objid = ${objid} AND d.deptype = 'e')`;+const ident = (name: string) => '"' + name.replace(/"/g, '""') + '"';++/** Plain SQL that recreates the public schema and its rows, in pg_dump's dependency order. */+export async function dumpBrainSchema(query: Query, version: number): Promise<string> {+ const out: string[] = [+ `-- gbrain schema-history fixture: a fresh brain at schema v${version}.`,+ '-- Generated by scripts/capture-schema-history-fixture.ts; do not edit.',+ 'SET check_function_bodies = false;',+ ];+ for (const r of await query(`SELECT extname FROM pg_extension WHERE extname <> 'plpgsql' ORDER BY extname`)) {+ out.push(`CREATE EXTENSION IF NOT EXISTS ${ident(r.extname)};`);+ }+ const sequences = await query(`+ SELECT c.relname AS name, format_type(s.seqtypid, NULL) AS type, s.seqstart AS start, s.seqincrement AS inc,+ s.seqmin AS min, s.seqmax AS max, s.seqcache AS cache, s.seqcycle AS cycle,+ (SELECT t.relname || '.' || a.attname FROM pg_depend d JOIN pg_class t ON t.oid = d.refobjid+ JOIN pg_attribute a ON a.attrelid = d.refobjid AND a.attnum = d.refobjsubid+ WHERE d.classid = 'pg_class'::regclass AND d.objid = c.oid AND d.deptype = 'a') AS owned_by+ FROM pg_sequence s JOIN pg_class c ON c.oid = s.seqrelid JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = 'public'+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_class'::regclass AND d.objid = c.oid AND d.deptype = 'i')+ AND ${NOT_EXTENSION_MEMBER('pg_class', 'c.oid')}+ ORDER BY c.oid`);+ for (const s of sequences) {+ out.push(`CREATE SEQUENCE ${ident(s.name)} AS ${s.type} INCREMENT BY ${s.inc} MINVALUE ${s.min} MAXVALUE ${s.max} START WITH ${s.start} CACHE ${s.cache}${s.cycle ? ' CYCLE' : ''};`);+ }+ for (const f of await query(`+ SELECT pg_get_functiondef(p.oid) AS def FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace+ WHERE n.nspname = 'public' AND p.prokind IN ('f', 'p') AND ${NOT_EXTENSION_MEMBER('pg_proc', 'p.oid')}+ ORDER BY p.oid`)) {+ out.push(`${String(f.def).trimEnd()};`);+ }+ const columns = await query(`+ SELECT c.relname AS table_name, c.relpersistence AS persistence,+ a.attname AS name, format_type(a.atttypid, a.atttypmod) AS type, a.attnotnull AS not_null,+ a.attidentity AS identity, a.attgenerated AS generated, pg_get_expr(ad.adbin, ad.adrelid) AS default_expr,+ CASE WHEN a.attcollation <> ty.typcollation THEN (SELECT collname FROM pg_collation WHERE oid = a.attcollation) END AS collation+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ LEFT JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped+ LEFT JOIN pg_type ty ON ty.oid = a.atttypid+ LEFT JOIN pg_attrdef ad ON ad.adrelid = c.oid AND ad.adnum = a.attnum+ WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p') AND ${NOT_EXTENSION_MEMBER('pg_class', 'c.oid')}+ ORDER BY c.oid, a.attnum`);+ const tables = new Map<string, { persistence: string; cols: string[]; insertable: string[] }>();+ for (const c of columns) {+ let t = tables.get(c.table_name);+ if (!t) tables.set(c.table_name, t = { persistence: c.persistence, cols: [], insertable: [] });+ if (c.name == null) continue;+ let col = `${ident(c.name)} ${c.type}`;+ if (c.collation) col += ` COLLATE ${ident(c.collation)}`;+ if (c.generated === 's') col += ` GENERATED ALWAYS AS (${c.default_expr}) STORED`;+ else if (c.identity === 'a' || c.identity === 'd') col += ` GENERATED ${c.identity === 'a' ? 'ALWAYS' : 'BY DEFAULT'} AS IDENTITY`;+ else if (c.default_expr != null) col += ` DEFAULT ${c.default_expr}`;+ if (c.not_null) col += ' NOT NULL';+ t.cols.push(col);+ if (c.generated !== 's') t.insertable.push(ident(c.name));+ }+ for (const [name, t] of tables) {+ out.push(`CREATE ${t.persistence === 'u' ? 'UNLOGGED ' : ''}TABLE ${ident(name)} (\n ${t.cols.join(',\n ')}\n);`);+ }+ for (const s of sequences) {+ if (!s.owned_by) continue;+ const [table, column] = String(s.owned_by).split('.');+ out.push(`ALTER SEQUENCE ${ident(s.name)} OWNED BY ${ident(table)}.${ident(column)};`);+ }+ for (const [name, t] of tables) {+ const [{ rows }] = await query(`SELECT COALESCE(json_agg(x), '[]'::json)::text AS rows FROM ${ident(name)} x`);+ if (rows === '[]' || t.insertable.length === 0) continue;+ const tag = '$gbrain_fixture$';+ if (String(rows).includes(tag)) throw new Error(`row data of ${name} contains ${tag}`);+ out.push(`INSERT INTO ${ident(name)} (${t.insertable.join(', ')}) OVERRIDING SYSTEM VALUE\n SELECT ${t.insertable.join(', ')} FROM json_populate_recordset(NULL::${ident(name)}, ${tag}${rows}${tag});`);+ }+ for (const s of sequences) {+ const [{ last_value, is_called }] = await query(`SELECT last_value::text AS last_value, is_called FROM ${ident(s.name)}`);+ out.push(`SELECT setval('${ident(s.name)}', ${last_value}, ${is_called ? 'true' : 'false'});`);+ }+ const constraints = await query(`+ SELECT t.relname AS table_name, con.conname AS name, con.contype AS type, pg_get_constraintdef(con.oid) AS def+ FROM pg_constraint con JOIN pg_class t ON t.oid = con.conrelid JOIN pg_namespace n ON n.oid = t.relnamespace+ WHERE n.nspname = 'public' AND con.contype IN ('p', 'u', 'c', 'x', 'f') AND ${NOT_EXTENSION_MEMBER('pg_class', 't.oid')}+ ORDER BY con.oid`);+ for (const c of constraints.filter((c) => c.type !== 'f')) {+ out.push(`ALTER TABLE ${ident(c.table_name)} ADD CONSTRAINT ${ident(c.name)} ${c.def};`);+ }+ for (const i of await query(`+ SELECT pg_get_indexdef(idx.indexrelid) AS def FROM pg_index idx+ JOIN pg_class t ON t.oid = idx.indrelid JOIN pg_namespace n ON n.oid = t.relnamespace+ WHERE n.nspname = 'public' AND idx.indisvalid AND ${NOT_EXTENSION_MEMBER('pg_class', 't.oid')}+ AND NOT EXISTS (SELECT 1 FROM pg_constraint con WHERE con.conindid = idx.indexrelid AND con.contype IN ('p', 'u', 'x'))+ ORDER BY idx.indexrelid`)) {+ out.push(`${i.def};`);+ }+ for (const c of constraints.filter((c) => c.type === 'f')) {+ out.push(`ALTER TABLE ${ident(c.table_name)} ADD CONSTRAINT ${ident(c.name)} ${c.def};`);+ }+ for (const v of await query(`+ SELECT c.relname AS name, c.relkind AS kind, pg_get_viewdef(c.oid) AS def,+ COALESCE(array_to_string(c.reloptions, ', '), '') AS options+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = 'public' AND c.relkind IN ('v', 'm') AND ${NOT_EXTENSION_MEMBER('pg_class', 'c.oid')}+ ORDER BY c.oid`)) {+ const options = v.options ? ` WITH (${v.options})` : '';+ out.push(`CREATE ${v.kind === 'm' ? 'MATERIALIZED ' : ''}VIEW ${ident(v.name)}${options} AS\n${String(v.def).trim().replace(/;$/, '')};`);+ }+ for (const t of await query(`+ SELECT pg_get_triggerdef(tg.oid) AS def, tg.tgenabled AS enabled, tg.tgname AS name, t.relname AS table_name+ FROM pg_trigger tg JOIN pg_class t ON t.oid = tg.tgrelid JOIN pg_namespace n ON n.oid = t.relnamespace+ WHERE n.nspname = 'public' AND NOT tg.tgisinternal ORDER BY tg.oid`)) {+ out.push(`${t.def};`);+ if (t.enabled === 'D') out.push(`ALTER TABLE ${ident(t.table_name)} DISABLE TRIGGER ${ident(t.name)};`);+ }+ for (const r of await query(`+ SELECT c.relname AS name, c.relrowsecurity AS rls, c.relforcerowsecurity AS force+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p') AND (c.relrowsecurity OR c.relforcerowsecurity)+ ORDER BY c.oid`)) {+ if (r.rls) out.push(`ALTER TABLE ${ident(r.name)} ENABLE ROW LEVEL SECURITY;`);+ if (r.force) out.push(`ALTER TABLE ${ident(r.name)} FORCE ROW LEVEL SECURITY;`);+ }+ for (const p of await query(`+ SELECT tablename AS table_name, policyname AS name, permissive, array_to_string(roles, ', ') AS roles,+ cmd, qual, with_check FROM pg_policies WHERE schemaname = 'public' ORDER BY tablename, policyname`)) {+ const roles = String(p.roles).split(', ').map((r) => (r === 'public' ? 'PUBLIC' : ident(r))).join(', ');+ let sql = `CREATE POLICY ${ident(p.name)} ON ${ident(p.table_name)} AS ${p.permissive} FOR ${p.cmd} TO ${roles}`;+ if (p.qual != null) sql += ` USING (${p.qual})`;+ if (p.with_check != null) sql += ` WITH CHECK (${p.with_check})`;+ out.push(`${sql};`);+ }+ for (const e of await query(`+ SELECT e.evtname AS name, e.evtevent AS event, e.evtfoid::regproc::text AS fn, e.evtenabled AS enabled,+ COALESCE(array_to_string(e.evttags, ''', '''), '') AS tags+ FROM pg_event_trigger e WHERE ${NOT_EXTENSION_MEMBER('pg_event_trigger', 'e.oid')} ORDER BY e.oid`)) {+ const when = e.tags ? ` WHEN TAG IN ('${e.tags}')` : '';+ out.push(`CREATE EVENT TRIGGER ${ident(e.name)} ON ${e.event}${when} EXECUTE FUNCTION ${e.fn}();`);+ if (e.enabled === 'D') out.push(`ALTER EVENT TRIGGER ${ident(e.name)} DISABLE;`);+ }+ out.push('RESET check_function_bodies;');+ return out.join('\n\n') + '\n';+}++/** Blank every secret a fresh brain generates (e.g. shared_skill_state.token_secret) so no fixture carries one. */+async function blankSecrets(query: Query): Promise<void> {+ for (const c of await query(`+ SELECT table_name, column_name FROM information_schema.columns+ WHERE table_schema = 'public' AND column_name LIKE '%secret%' AND data_type IN ('text', 'character varying')+ AND table_name IN (SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE')+ ORDER BY 1, 2`)) {+ await query(`UPDATE ${ident(c.table_name)} SET ${ident(c.column_name)} = repeat('0', length(${ident(c.column_name)})) WHERE ${ident(c.column_name)} IS NOT NULL`);+ }+}++/** Every public table's rows, ordered, for the round-trip check. */+async function tableRows(query: Query): Promise<Record<string, string>> {+ const out: Record<string, string> = {};+ for (const t of await query(`+ SELECT c.relname AS name FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p') AND ${NOT_EXTENSION_MEMBER('pg_class', 'c.oid')} ORDER BY 1`)) {+ const [{ rows }] = await query(`SELECT COALESCE(json_agg(x ORDER BY x::text), '[]'::json)::text AS rows FROM ${ident(t.name)} x`);+ out[t.name] = rows;+ }+ return out;+}++async function fidelity(original: Query, restored: Query): Promise<string[]> {+ const problems: string[] = [];+ // A trigger's WHEN clause deparses its OR chain flattened once restored; same expression, fewer parentheses.+ const unparenthesized = (value: unknown) => JSON.stringify(value).replace(/[()]/g, '');+ const catalogDiff = diffCatalogSnapshots(await snapshotCatalog(original as CatalogQueryFn), await snapshotCatalog(restored as CatalogQueryFn), { compareOrdinals: true })+ .filter((d) => !(d.section === 'triggers' && d.kind === 'changed' && unparenthesized(d.expected) === unparenthesized(d.actual)));+ if (catalogDiff.length > 0) problems.push(formatCatalogDiffForFailure(catalogDiff));+ const [a, b] = [await original(FUNCTION_BODIES_SQL), await restored(FUNCTION_BODIES_SQL)];+ if (JSON.stringify(a) !== JSON.stringify(b)) problems.push('function bodies differ');+ const [ra, rb] = [await tableRows(original), await tableRows(restored)];+ for (const name of new Set([...Object.keys(ra), ...Object.keys(rb)])) {+ if (ra[name] !== rb[name]) problems.push(`rows of ${name} differ`);+ }+ return problems;+}++function parseArgs(argv: string[]): { tree: string; engine: Engine; out?: string } {+ const get = (flag: string) => { const i = argv.indexOf(flag); return i >= 0 ? argv[i + 1] : undefined; };+ const tree = get('--tree');+ const engine = get('--engine');+ if (!tree || (engine !== 'pglite' && engine !== 'postgres')) {+ throw new Error('Usage: capture-schema-history-fixture.ts --tree <release worktree> --engine pglite|postgres [--out <file>]');+ }+ return { tree: resolve(tree), engine, out: get('--out') };+}++function withDatabase(url: string, name: string): string {+ const u = new URL(url);+ u.pathname = `/${name}`;+ return u.toString();+}++async function main(): Promise<void> {+ const { tree, engine, out } = parseArgs(process.argv.slice(2));+ delete process.env.GBRAIN_PGLITE_SNAPSHOT;+ const { LATEST_SCHEMA_VERSION: version } = await import(join(tree, 'src/core/schema-migrations/latest.generated.ts'));+ const gateway = await import(join(tree, 'src/core/ai/gateway.ts'));+ gateway.configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: { ...process.env } });+ const file = out ?? join('test/fixtures/schema-history', engine, `v${version}.sql.gz`);+ let dump: string;+ let problems: string[];+ if (engine === 'pglite') {+ const { PGLiteEngine: ReleaseEngine } = await import(join(tree, 'src/core/pglite-engine.ts'));+ const release = new ReleaseEngine();+ const restored = new PGLiteEngine();+ try {+ await release.connect({});+ await release.initSchema();+ const original: Query = async (sql) => (await release.db.query(sql)).rows;+ await blankSecrets(original);+ dump = await dumpBrainSchema(original, version);+ await restored.connect({});+ await restored.db.exec(dump);+ problems = await fidelity(original, async (sql) => (await restored.db.query(sql)).rows as Array<Record<string, any>>);+ } finally {+ await release.disconnect();+ await restored.disconnect();+ }+ } else {+ const admin = process.env.DATABASE_URL;+ if (!admin) throw new Error('--engine postgres needs DATABASE_URL (a disposable test server)');+ const suffix = randomUUID().replace(/-/g, '');+ const names = [`gbrain_fixture_release_${suffix}`, `gbrain_fixture_restored_${suffix}`];+ const adminSql = postgres(admin, { max: 1, prepare: false, onnotice: () => {} });+ const { PostgresEngine: ReleaseEngine } = await import(join(tree, 'src/core/postgres-engine.ts'));+ const release = new ReleaseEngine();+ let restored: ReturnType<typeof postgres> | undefined;+ try {+ for (const name of names) await adminSql.unsafe(`CREATE DATABASE ${name}`);+ await release.connect({ database_url: withDatabase(admin, names[0]), poolSize: 2 });+ await release.initSchema();+ const original: Query = async (sql) => await release.sql.unsafe(sql);+ await blankSecrets(original);+ dump = await dumpBrainSchema(original, version);+ restored = postgres(withDatabase(admin, names[1]), { max: 1, prepare: false, onnotice: () => {} });+ await restored.unsafe(dump);+ problems = await fidelity(original, async (sql) => await restored!.unsafe(sql));+ } finally {+ await release.disconnect();+ await restored?.end({ timeout: 5 });+ for (const name of names) await adminSql.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`);+ await adminSql.end({ timeout: 5 });+ }+ }+ if (problems.length > 0) throw new Error(`restored v${version} ${engine} fixture differs from the release's brain:\n${problems.join('\n')}`);+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, Bun.gzipSync(Buffer.from(dump), { level: 9 }));+ process.stdout.write(`wrote ${file} (schema v${version}, ${engine}, ${dump.length} bytes)\n`);+}++if (import.meta.main) {+ main().then(() => process.exit(0), (err) => {+ process.stderr.write(`${err instanceof Error ? err.stack ?? err.message : String(err)}\n`);+ process.exit(1);+ });+}diff --git a/src/core/engine-sql/bootstrap.ts b/src/core/engine-sql/bootstrap.tsindex 5be754ec76..e0dfea7532 100644--- a/src/core/engine-sql/bootstrap.ts+++ b/src/core/engine-sql/bootstrap.ts@@ -165,6 +165,8 @@ const FORWARD_REFERENCE_PROBES: readonly Probe[] = [['facts_exists', 'facts'],['facts_embedding_model_exists', 'facts', 'embedding_model'],['facts_embedded_text_hash_exists', 'facts', 'embedded_text_hash'],+ ['derived_generation_items_exists', 'derived_generation_items'],+ ['derived_generation_items_pending_exists', 'derived_generation_items', 'pending'],];// Probed only where `dreamVerdictsForwardReference` (the Postgres blob).@@ -307,6 +309,11 @@ export function forwardReferenceGaps(probe: ProbeRow, dialect: ForwardReferenceB&& probe.dream_verdicts_exists && !probe.dream_verdicts_expires_at_exists;const needsFactEmbeddingIdentity = probe.facts_exists&& (!probe.facts_embedding_model_exists || !probe.facts_embedded_text_hash_exists);+ // v266 (#7645): the blob's partial index derived_generation_items_pending+ // (`WHERE pending`) references a column only v266 adds, so a brain at v265+ // (the table exists since v265) wedged on the replay before any migration ran.+ const needsDerivedGenerationItemsPending = probe.derived_generation_items_exists+ && !probe.derived_generation_items_pending_exists;return {needsPagesBootstrap, needsLinksBootstrap, needsChunksBootstrap, needsPagesDeletedAt,needsMcpLogBootstrap, needsSubagentProviderId, needsChunksEmbeddingImage, needsPagesRecency,@@ -315,7 +322,7 @@ export function forwardReferenceGaps(probe: ProbeRow, dialect: ForwardReferenceBneedsContextualRetrievalColumns, needsPagesGeneration, needsPagesEmbeddingSignature,needsPagesLinksExtractedAt, needsTimelineEventPageId, needsMinionJobsTimeoutAt,needsMinionJobsIdempotencyKey, needsMinionJobsPrivateQueue, needsMinionJobsAuthority,- needsDreamVerdictsExpiresAt, needsFactEmbeddingIdentity,+ needsDreamVerdictsExpiresAt, needsFactEmbeddingIdentity, needsDerivedGenerationItemsPending,};}@@ -332,7 +339,7 @@ export async function applyForwardReferenceBootstrap(target: ForwardReferenceBooneedsContextualRetrievalColumns, needsPagesGeneration, needsPagesEmbeddingSignature,needsPagesLinksExtractedAt, needsTimelineEventPageId, needsMinionJobsTimeoutAt,needsMinionJobsIdempotencyKey, needsMinionJobsPrivateQueue, needsMinionJobsAuthority,- needsDreamVerdictsExpiresAt, needsFactEmbeddingIdentity,+ needsDreamVerdictsExpiresAt, needsFactEmbeddingIdentity, needsDerivedGenerationItemsPending,} = gaps;if (!needsPagesBootstrap && !needsLinksBootstrap && !needsChunksBootstrap@@ -349,7 +356,8 @@ export async function applyForwardReferenceBootstrap(target: ForwardReferenceBoo&& !needsTimelineEventPageId&& !needsMinionJobsTimeoutAt && !needsMinionJobsIdempotencyKey&& !needsMinionJobsPrivateQueue && !needsMinionJobsAuthority- && !needsDreamVerdictsExpiresAt && !needsFactEmbeddingIdentity) return;+ && !needsDreamVerdictsExpiresAt && !needsFactEmbeddingIdentity+ && !needsDerivedGenerationItemsPending) return;process.stderr.write(' Schema forward-reference gap detected, applying bootstrap\n');@@ -582,6 +590,7 @@ async function applyLaterColumnGaps(target: ForwardReferenceBootstrapTarget, gapneedsPagesGeneration, needsPagesEmbeddingSignature, needsPagesLinksExtractedAt,needsTimelineEventPageId, needsMinionJobsTimeoutAt, needsMinionJobsIdempotencyKey,needsDreamVerdictsExpiresAt, needsMinionJobsPrivateQueue, needsMinionJobsAuthority,+ needsDerivedGenerationItemsPending,} = gaps;if (needsPagesLastRetrievedAt) {@@ -713,4 +722,12 @@ async function applyLaterColumnGaps(target: ForwardReferenceBootstrapTarget, gapALTER TABLE minion_jobs ADD COLUMN IF NOT EXISTS claim_generation BIGINT NOT NULL DEFAULT 0;`);}++ if (needsDerivedGenerationItemsPending) {+ // Column only, exactly as v266 adds it (existing items are not pending);+ // v266 still runs and owns the index and the activations table.+ await exec(`+ ALTER TABLE derived_generation_items ADD COLUMN IF NOT EXISTS pending BOOLEAN NOT NULL DEFAULT false;+ `);+ }}diff --git a/test/e2e/schema-history-upgrade.test.ts b/test/e2e/schema-history-upgrade.test.tsnew file mode 100644index 0000000000..eb6d5914ea--- /dev/null+++ b/test/e2e/schema-history-upgrade.test.ts@@ -0,0 +1,87 @@+/**+ * #7645 class closure, Postgres half (the PGLite half and the rationale are in+ * test/schema-history-upgrade.test.ts): a Postgres brain created by any release+ * since v260 upgrades to the latest schema through initSchema and ends with the+ * catalog a fresh install has. Each fixture loads into its own throwaway+ * database. Skips without DATABASE_URL.+ */+import { describe, expect, test } from 'bun:test';+import postgres from '#postgres';+import { randomUUID } from 'node:crypto';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { LATEST_VERSION } from '../../src/core/migrate.ts';+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';+import { CATALOG_CONFIGS, FUNCTION_BODIES_SQL, postgresCatalogQuery, withCatalogConfig } from '../helpers/schema-catalog.ts';+import { snapshotCatalog } from '../helpers/schema-diff.ts';+import { schemaHistoryDrift, schemaHistorySql, schemaHistoryVersions, type InstalledSchema } from '../helpers/schema-history.ts';++const DATABASE_URL = process.env.DATABASE_URL;+const skip = !DATABASE_URL;++function withDatabase(url: string, name: string): string {+ const u = new URL(url);+ u.pathname = `/${name}`;+ return u.toString();+}++async function withFreshDatabase<T>(fn: (url: string) => Promise<T>): Promise<T> {+ assertSafeE2eDatabaseUrl(DATABASE_URL!);+ const name = `gbrain_test_history_${randomUUID().replace(/-/g, '')}`;+ const admin = postgres(DATABASE_URL!, { max: 1, prepare: false, onnotice: () => {} });+ try {+ await admin.unsafe(`CREATE DATABASE ${name}`);+ try {+ return await fn(withDatabase(DATABASE_URL!, name));+ } finally {+ await admin.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`);+ }+ } finally {+ await admin.end({ timeout: 5 });+ }+}++async function installedSchema(engine: PostgresEngine): Promise<InstalledSchema> {+ const bodies = await engine.sql.unsafe(FUNCTION_BODIES_SQL) as Array<{ key: string; body: string }>;+ return {+ catalog: await snapshotCatalog(postgresCatalogQuery(engine.sql)),+ functionBodies: new Map(bodies.map((r) => [r.key, r.body])),+ };+}++describe.skipIf(skip)('Postgres brains created by older releases upgrade to the latest schema (#7645, E2E)', () => {+ let fresh: InstalledSchema | undefined;+ for (const version of skip ? [] : schemaHistoryVersions('postgres')) {+ test(`v${version} brain reaches v${LATEST_VERSION} through initSchema`, async () => {+ await withCatalogConfig(CATALOG_CONFIGS[0], async () => {+ fresh ??= await withFreshDatabase(async (url) => {+ const engine = new PostgresEngine();+ try {+ await engine.connect({ database_url: url, poolSize: 2 });+ await engine.initSchema();+ return await installedSchema(engine);+ } finally {+ await engine.disconnect();+ }+ });+ await withFreshDatabase(async (url) => {+ const loader = postgres(url, { max: 1, prepare: false, onnotice: () => {} });+ try {+ await loader.unsafe(schemaHistorySql('postgres', version));+ } finally {+ await loader.end({ timeout: 5 });+ }+ const engine = new PostgresEngine();+ try {+ await engine.connect({ database_url: url, poolSize: 2 });+ expect(await engine.getConfig('version')).toBe(String(version));+ await engine.initSchema();+ expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION));+ expect(schemaHistoryDrift(fresh!, await installedSchema(engine))).toBe('');+ } finally {+ await engine.disconnect();+ }+ });+ });+ }, 180_000);+ }+});diff --git a/test/fixtures/schema-history/README.md b/test/fixtures/schema-history/README.mdnew file mode 100644index 0000000000..f52c9eb67d--- /dev/null+++ b/test/fixtures/schema-history/README.md@@ -0,0 +1,20 @@+# Schema-history fixtures++The schema blob replays before any migration, so on an existing brain each blob+statement meets the tables of whatever release created the brain. A blob index+or reference to a column that a later migration adds wedges those brains (#7645)+unless `src/core/engine-sql/bootstrap.ts` adds the column first.++Each `<engine>/v<N>.sql.gz` here is a fresh brain as the release that shipped+schema v`N` created it: gzipped SQL with the schema and the rows a fresh install+writes. `test/schema-history-upgrade.slow.test.ts` (PGLite) and+`test/e2e/schema-history-upgrade.test.ts` (Postgres) load each one, run+`initSchema`, and require the latest schema version and a fresh install's+catalog. The PGLite test also requires a fixture for every version from v260 to+the newest one here.++`scripts/capture-schema-history-fixture.ts` writes a fixture from the release's+own engine and refuses to write one that does not restore to that release's+exact catalog, function bodies and rows. Generated secrets are blanked. When a+release ships a new schema version, capture both engines from that release's+commit (usage in the script header) and commit the two files.diff --git a/test/fixtures/schema-history/pglite/v260.sql.gz b/test/fixtures/schema-history/pglite/v260.sql.gznew file mode 100644index 0000000000..d16c705123Binary files /dev/null and b/test/fixtures/schema-history/pglite/v260.sql.gz differdiff --git a/test/fixtures/schema-history/pglite/v261.sql.gz b/test/fixtures/schema-history/pglite/v261.sql.gznew file mode 100644index 0000000000..b39e6edad6Binary files /dev/null and b/test/fixtures/schema-history/pglite/v261.sql.gz differdiff --git a/test/fixtures/schema-history/pglite/v262.sql.gz b/test/fixtures/schema-history/pglite/v262.sql.gznew file mode 100644index 0000000000..48c11848d1Binary files /dev/null and b/test/fixtures/schema-history/pglite/v262.sql.gz differdiff --git a/test/fixtures/schema-history/pglite/v263.sql.gz b/test/fixtures/schema-history/pglite/v263.sql.gznew file mode 100644index 0000000000..d9c2d4706dBinary files /dev/null and b/test/fixtures/schema-history/pglite/v263.sql.gz differdiff --git a/test/fixtures/schema-history/pglite/v264.sql.gz b/test/fixtures/schema-history/pglite/v264.sql.gznew file mode 100644index 0000000000..911025de5aBinary files /dev/null and b/test/fixtures/schema-history/pglite/v264.sql.gz differdiff --git a/test/fixtures/schema-history/pglite/v265.sql.gz b/test/fixtures/schema-history/pglite/v265.sql.gznew file mode 100644index 0000000000..0152c41c5cBinary files /dev/null and b/test/fixtures/schema-history/pglite/v265.sql.gz differdiff --git a/test/fixtures/schema-history/pglite/v266.sql.gz b/test/fixtures/schema-history/pglite/v266.sql.gznew file mode 100644index 0000000000..71fd2580d7Binary files /dev/null and b/test/fixtures/schema-history/pglite/v266.sql.gz differdiff --git a/test/fixtures/schema-history/pglite/v267.sql.gz b/test/fixtures/schema-history/pglite/v267.sql.gznew file mode 100644index 0000000000..e850ef249aBinary files /dev/null and b/test/fixtures/schema-history/pglite/v267.sql.gz differdiff --git a/test/fixtures/schema-history/pglite/v268.sql.gz b/test/fixtures/schema-history/pglite/v268.sql.gznew file mode 100644index 0000000000..8b9420381eBinary files /dev/null and b/test/fixtures/schema-history/pglite/v268.sql.gz differdiff --git a/test/fixtures/schema-history/pglite/v269.sql.gz b/test/fixtures/schema-history/pglite/v269.sql.gznew file mode 100644index 0000000000..91f0063a5dBinary files /dev/null and b/test/fixtures/schema-history/pglite/v269.sql.gz differdiff --git a/test/fixtures/schema-history/pglite/v270.sql.gz b/test/fixtures/schema-history/pglite/v270.sql.gznew file mode 100644index 0000000000..89f1c695dbBinary files /dev/null and b/test/fixtures/schema-history/pglite/v270.sql.gz differdiff --git a/test/fixtures/schema-history/pglite/v271.sql.gz b/test/fixtures/schema-history/pglite/v271.sql.gznew file mode 100644index 0000000000..5e33c109b9Binary files /dev/null and b/test/fixtures/schema-history/pglite/v271.sql.gz differdiff --git a/test/fixtures/schema-history/pglite/v272.sql.gz b/test/fixtures/schema-history/pglite/v272.sql.gznew file mode 100644index 0000000000..2b6c1ed24fBinary files /dev/null and b/test/fixtures/schema-history/pglite/v272.sql.gz differdiff --git a/test/fixtures/schema-history/pglite/v273.sql.gz b/test/fixtures/schema-history/pglite/v273.sql.gznew file mode 100644index 0000000000..54a411ebbcBinary files /dev/null and b/test/fixtures/schema-history/pglite/v273.sql.gz differdiff --git a/test/fixtures/schema-history/pglite/v274.sql.gz b/test/fixtures/schema-history/pglite/v274.sql.gznew file mode 100644index 0000000000..081c0d1becBinary files /dev/null and b/test/fixtures/schema-history/pglite/v274.sql.gz differdiff --git a/test/fixtures/schema-history/pglite/v275.sql.gz b/test/fixtures/schema-history/pglite/v275.sql.gznew file mode 100644index 0000000000..d6a68ed1d1Binary files /dev/null and b/test/fixtures/schema-history/pglite/v275.sql.gz differdiff --git a/test/fixtures/schema-history/postgres/v260.sql.gz b/test/fixtures/schema-history/postgres/v260.sql.gznew file mode 100644index 0000000000..40d3199a4eBinary files /dev/null and b/test/fixtures/schema-history/postgres/v260.sql.gz differdiff --git a/test/fixtures/schema-history/postgres/v261.sql.gz b/test/fixtures/schema-history/postgres/v261.sql.gznew file mode 100644index 0000000000..8acb12d8efBinary files /dev/null and b/test/fixtures/schema-history/postgres/v261.sql.gz differdiff --git a/test/fixtures/schema-history/postgres/v262.sql.gz b/test/fixtures/schema-history/postgres/v262.sql.gznew file mode 100644index 0000000000..c0ff673c1eBinary files /dev/null and b/test/fixtures/schema-history/postgres/v262.sql.gz differdiff --git a/test/fixtures/schema-history/postgres/v263.sql.gz b/test/fixtures/schema-history/postgres/v263.sql.gznew file mode 100644index 0000000000..fed8dc4faaBinary files /dev/null and b/test/fixtures/schema-history/postgres/v263.sql.gz differdiff --git a/test/fixtures/schema-history/postgres/v264.sql.gz b/test/fixtures/schema-history/postgres/v264.sql.gznew file mode 100644index 0000000000..a2918634ddBinary files /dev/null and b/test/fixtures/schema-history/postgres/v264.sql.gz differdiff --git a/test/fixtures/schema-history/postgres/v265.sql.gz b/test/fixtures/schema-history/postgres/v265.sql.gznew file mode 100644index 0000000000..09180efeb6Binary files /dev/null and b/test/fixtures/schema-history/postgres/v265.sql.gz differdiff --git a/test/fixtures/schema-history/postgres/v266.sql.gz b/test/fixtures/schema-history/postgres/v266.sql.gznew file mode 100644index 0000000000..241286d223Binary files /dev/null and b/test/fixtures/schema-history/postgres/v266.sql.gz differdiff --git a/test/fixtures/schema-history/postgres/v267.sql.gz b/test/fixtures/schema-history/postgres/v267.sql.gznew file mode 100644index 0000000000..557fa36c4cBinary files /dev/null and b/test/fixtures/schema-history/postgres/v267.sql.gz differdiff --git a/test/fixtures/schema-history/postgres/v268.sql.gz b/test/fixtures/schema-history/postgres/v268.sql.gznew file mode 100644index 0000000000..e30f7d5063Binary files /dev/null and b/test/fixtures/schema-history/postgres/v268.sql.gz differdiff --git a/test/fixtures/schema-history/postgres/v269.sql.gz b/test/fixtures/schema-history/postgres/v269.sql.gznew file mode 100644index 0000000000..50377a2cc2Binary files /dev/null and b/test/fixtures/schema-history/postgres/v269.sql.gz differdiff --git a/test/fixtures/schema-history/postgres/v270.sql.gz b/test/fixtures/schema-history/postgres/v270.sql.gznew file mode 100644index 0000000000..dfb67a8b87Binary files /dev/null and b/test/fixtures/schema-history/postgres/v270.sql.gz differdiff --git a/test/fixtures/schema-history/postgres/v271.sql.gz b/test/fixtures/schema-history/postgres/v271.sql.gznew file mode 100644index 0000000000..5925e7d0ddBinary files /dev/null and b/test/fixtures/schema-history/postgres/v271.sql.gz differdiff --git a/test/fixtures/schema-history/postgres/v272.sql.gz b/test/fixtures/schema-history/postgres/v272.sql.gznew file mode 100644index 0000000000..984c65fd37Binary files /dev/null and b/test/fixtures/schema-history/postgres/v272.sql.gz differdiff --git a/test/fixtures/schema-history/postgres/v273.sql.gz b/test/fixtures/schema-history/postgres/v273.sql.gznew file mode 100644index 0000000000..f557aad47fBinary files /dev/null and b/test/fixtures/schema-history/postgres/v273.sql.gz differdiff --git a/test/fixtures/schema-history/postgres/v274.sql.gz b/test/fixtures/schema-history/postgres/v274.sql.gznew file mode 100644index 0000000000..7baa495108Binary files /dev/null and b/test/fixtures/schema-history/postgres/v274.sql.gz differdiff --git a/test/fixtures/schema-history/postgres/v275.sql.gz b/test/fixtures/schema-history/postgres/v275.sql.gznew file mode 100644index 0000000000..d16149b612Binary files /dev/null and b/test/fixtures/schema-history/postgres/v275.sql.gz differdiff --git a/test/helpers/schema-history.ts b/test/helpers/schema-history.tsnew file mode 100644index 0000000000..6d80f77673--- /dev/null+++ b/test/helpers/schema-history.ts@@ -0,0 +1,57 @@+/**+ * Schema-history fixtures (#7645): a fresh brain as each release since v260+ * created it, captured by scripts/capture-schema-history-fixture.ts from that+ * release's own engine and stored as gzipped SQL under+ * test/fixtures/schema-history/<engine>/v<N>.sql.gz.+ */+import { readdirSync, readFileSync } from 'node:fs';+import { join, resolve } from 'node:path';+import { diffCatalogSnapshots, formatCatalogDiffForFailure, type CatalogSnapshot } from './schema-diff.ts';++export type SchemaHistoryEngine = 'pglite' | 'postgres';++/** The first schema version with a fixture; every later shipped version has one. */+export const FIRST_SCHEMA_HISTORY_VERSION = 260;++export const SCHEMA_HISTORY_DIR = resolve(import.meta.dir, '..', 'fixtures', 'schema-history');++export function schemaHistoryVersions(engine: SchemaHistoryEngine): number[] {+ return readdirSync(join(SCHEMA_HISTORY_DIR, engine))+ .map((name) => /^v(\d+)\.sql\.gz$/.exec(name)?.[1])+ .filter((v): v is string => v !== undefined)+ .map(Number)+ .sort((a, b) => a - b);+}++export function schemaHistorySql(engine: SchemaHistoryEngine, version: number): string {+ return Buffer.from(Bun.gunzipSync(readFileSync(join(SCHEMA_HISTORY_DIR, engine, `v${version}.sql.gz`)))).toString('utf8');+}++export interface InstalledSchema {+ catalog: CatalogSnapshot;+ /** Raw function bodies keyed like the catalog (`name(identity args)`). */+ functionBodies: Map<string, string>;+}++const collapseWhitespace = (body: string | undefined) => (body ?? '').replace(/\s+/g, ' ').trim();+const withoutParentheses = (value: unknown) => JSON.stringify(value).replace(/[()]/g, '');++/**+ * The catalog difference between a fresh install and an upgraded brain, '' when+ * none. Two differences are not drift: a function body that differs only in+ * whitespace (the blob and the migration that last replaced it indent it+ * differently), and a constraint trigger's WHEN clause, whose OR chain the+ * fixture's restore deparses with fewer parentheses (same expression).+ */+export function schemaHistoryDrift(fresh: InstalledSchema, upgraded: InstalledSchema): string {+ const drift = diffCatalogSnapshots(fresh.catalog, upgraded.catalog).filter((d) => {+ if (d.kind !== 'changed') return true;+ if (d.section === 'triggers') return withoutParentheses(d.expected) !== withoutParentheses(d.actual);+ if (d.section !== 'functions') return true;+ const { bodySha256: _e, ...expected } = d.expected as Record<string, unknown>;+ const { bodySha256: _a, ...actual } = d.actual as Record<string, unknown>;+ return JSON.stringify(expected) !== JSON.stringify(actual)+ || collapseWhitespace(fresh.functionBodies.get(d.key)) !== collapseWhitespace(upgraded.functionBodies.get(d.key));+ });+ return drift.length === 0 ? '' : formatCatalogDiffForFailure(drift);+}diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.tsindex fa68c3976c..d84396e245 100644--- a/test/schema-bootstrap-coverage.test.ts+++ b/test/schema-bootstrap-coverage.test.ts@@ -611,8 +611,12 @@ function parseBaseTableColumns(sql: string): Map<string, Set<string>> {* to their inner identifier; literal-only expressions like `(slug, NULLS LAST)`* keep the bare column.*- * Out of scope: WHERE-clause columns in partial indexes (rare in our schema;- * those columns are always also referenced in the index column list itself).+ * Partial-index WHERE predicates and INCLUDE lists count too: replaying+ * `CREATE INDEX ... WHERE pending` on a brain whose table predates the+ * `pending` column fails exactly like an indexed column does (#7645, the+ * v266 `derived_generation_items_pending` wedge). Predicate identifiers are+ * every bare word that is not a SQL keyword, a function name, a string+ * literal or a cast's type.* Trigger function bodies are out of scope (they reference NEW.col / OLD.col* which the existing test file's strip-list handles separately).*/@@ -677,6 +681,19 @@ function parseIndexColumnReferences(sql: string): Array<{ table: string; column:result.push({ table, column: col.toLowerCase() });}}++ const statementEnd = sql.indexOf(';', i);+ const tail = sql.slice(i, statementEnd < 0 ? undefined : statementEnd);+ const predicate = tail.match(/\bWHERE\b([\s\S]*)$/i)?.[1];+ const include = tail.match(/\bINCLUDE\s*\(([^)]*)\)/i)?.[1];+ for (const expr of [predicate, include]) {+ if (!expr) continue;+ const bare = expr.replace(/'(?:[^']|'')*'/g, ' ').replace(/::\s*\w+(?:\s*\[\])?/g, ' ');+ for (const word of bare.matchAll(/\b([a-z_]\w*)\b(?!\s*\()/gi)) {+ if (/^(and|or|not|is|null|true|false|in|like|ilike|between|any|all|distinct|from)$/i.test(word[1])) continue;+ result.push({ table, column: word[1].toLowerCase() });+ }+ }}return result;}diff --git a/test/schema-history-upgrade.slow.test.ts b/test/schema-history-upgrade.slow.test.tsnew file mode 100644index 0000000000..99bb4bb29e--- /dev/null+++ b/test/schema-history-upgrade.slow.test.ts@@ -0,0 +1,69 @@+/**+ * #7645 class closure (PGLite half; the Postgres half is+ * test/e2e/schema-history-upgrade.test.ts): a brain created by any release+ * since v260 upgrades to the latest schema through the production path,+ * initSchema (forward-reference bootstrap, schema blob replay, migrations),+ * and ends with the catalog a fresh install has.+ *+ * The existing replay tests rewind schema_version on a LATEST-shaped brain,+ * so a blob statement that needs a column a later migration adds never meets+ * a table without it. That is how a v265 brain wedged on+ * derived_generation_items_pending (`WHERE pending`, a v266 column) while+ * every test stayed green. These fixtures are real older brains, captured+ * from each release's own engine, so the next missing forward reference+ * fails here.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { LATEST_VERSION } from '../src/core/migrate.ts';+import { CATALOG_CONFIGS, capturePgliteFreshInstall, pgliteCatalogQuery, pgliteFunctionBodies, withCatalogConfig } from './helpers/schema-catalog.ts';+import { snapshotCatalog } from './helpers/schema-diff.ts';+import { withColdPglite } from './helpers/with-snapshot.ts';+import {+ FIRST_SCHEMA_HISTORY_VERSION, schemaHistoryDrift, schemaHistorySql, schemaHistoryVersions, type InstalledSchema,+} from './helpers/schema-history.ts';++const versions = schemaHistoryVersions('pglite');+let fresh: InstalledSchema;++beforeAll(async () => {+ fresh = await withCatalogConfig(CATALOG_CONFIGS[0], () => capturePgliteFreshInstall());+}, 120_000);++test('a schema-history fixture exists for every schema version from v260 to the newest captured one', () => {+ const newest = versions[versions.length - 1];+ expect(versions[0]).toBe(FIRST_SCHEMA_HISTORY_VERSION);+ expect(newest).toBeLessThanOrEqual(LATEST_VERSION);+ expect(versions).toEqual(Array.from({ length: newest - FIRST_SCHEMA_HISTORY_VERSION + 1 }, (_, i) => FIRST_SCHEMA_HISTORY_VERSION + i));+});++for (const version of versions) {+ describe(`PGLite brain created at v${version} (#7645)`, () => {+ let engine: PGLiteEngine;+ let upgrade: Promise<void>;++ beforeAll(async () => {+ engine = new PGLiteEngine();+ // Cold: a snapshot-restored engine would already hold the latest schema.+ upgrade = withCatalogConfig(CATALOG_CONFIGS[0], () => withColdPglite(async () => {+ await engine.connect({});+ await engine.db.exec(schemaHistorySql('pglite', version));+ await engine.initSchema();+ }));+ await upgrade.catch(() => {});+ }, 120_000);++ afterAll(async () => {+ await engine.disconnect();+ });++ test(`reaches v${LATEST_VERSION} through initSchema with a fresh install's catalog`, async () => {+ await upgrade;+ expect(await engine.getConfig('version')).toBe(String(LATEST_VERSION));+ expect(schemaHistoryDrift(fresh, {+ catalog: await snapshotCatalog(pgliteCatalogQuery(engine)),+ functionBodies: await pgliteFunctionBodies(engine),+ })).toBe('');+ });+ });+}