Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
graduation G2b: copy through G1 digest plans and inventory transforms; dangling OAuth binding blocker
garrytan017acd817546
diff --git a/src/core/persistence/engine-graduation.types.ts b/src/core/persistence/engine-graduation.types.tsindex 9e657a6f96..6779d516c6 100644--- a/src/core/persistence/engine-graduation.types.ts+++ b/src/core/persistence/engine-graduation.types.ts@@ -247,7 +247,7 @@ export interface Tombstone {export interface GraduationBlocker {kind: 'request' | 'topology_recovery' | 'writer_admin_lock' | 'effect_recovery' | 'foreign_host_binding'| 'writer_held' | 'env_override' | 'embedding_dimension' | 'unclassified_relation' | 'target_not_empty'- | 'target_unsupported' | 'unsupported_platform' | 'source_doctor';+ | 'target_unsupported' | 'unsupported_platform' | 'source_doctor' | 'dangling_reference';id: string;detail: string;/** Exact command or MCP call that clears it, with real values filled in. */diff --git a/src/core/persistence/graduation-copy.ts b/src/core/persistence/graduation-copy.tsindex 479c48a640..4ba24b74f1 100644--- a/src/core/persistence/graduation-copy.ts+++ b/src/core/persistence/graduation-copy.ts@@ -6,21 +6,21 @@* - Per-column contract: source and target columns must match by name, type* and typmod (`format_type`) and generation expression, outside the* inventory entry's `columnAllowlist`; generated columns are never inserted.+ * - Source rows are read with the digest's own plan (`digestPlan` with+ * transforms applied, every value as `::text`, the entry's `rowFilter`,+ * keyset order by primary key with COLLATE "C" under the digest session+ * settings), so what is copied is exactly what verify digests.* - Each table copies in one target transaction that carries the run's fence* identity (`gbrain.graduation_run`), bypasses user triggers* (`session_replication_role = replica`, or DISABLE/ENABLE TRIGGER by name* inside the same transaction, never the fence), deletes the target's rows- * for that table (initSchema seed rows included; config keeps its- * target-owned keys) and inserts the source rows.- * - Values travel as canonical text and are cast back with the column's own- * type, one jsonb parameter per batch (far below the 65,535 bind-parameter- * limit), batches sized by bytes. Source batches are keyset-ordered by- * primary key with `COLLATE "C"` under UTC/ISO rendering settings.+ * for that table (initSchema seed rows included) and inserts the source rows.+ * - Values travel as text in one jsonb array per batch (bound `$1::text::jsonb`,+ * far below the 65,535 bind-parameter limit) and are cast back with each+ * column's own `format_type`; batches are sized by bytes.* - Self-referencing FKs copy in one pass under replica mode (no FK triggers)* and in two passes (insert with NULL, then update) under DISABLE TRIGGER,* where FK checks stay active.- * - Inventory transforms (lease and claim resets) are applied from- * `COPY_TRANSFORMS`; the digest applies the same expressions to the source.* - Sequences are set to the source's exact position, raised to the target* column maximum when that is higher.* - HNSW and GIN indexes are dropped before the copy and rebuilt after it; the@@ -28,130 +28,63 @@*/import type { BrainEngine } from '../engine.ts';import { ANN_BUILD_MESSAGE, buildDeferredAnnIndexes, type DeferredAnnIndex } from '../embedding-ann-build.ts';-import type { GraduationEngines, InventoryEntry, TriggerBypass } from './engine-graduation.types.ts';+import type { ColumnMeta, GraduationEngines, InventoryEntry, TriggerBypass } from './engine-graduation.types.ts';+import { digestPlan, quoteIdent, tableColumns, withDigestSession, type DigestPlan } from './graduation-digest.ts';import { graduationError } from './graduation-target.ts';+/** Target-owned config row holding the deferred index list; the config copy never deletes it. */export const GRADUATION_DEFERRED_INDEXES_KEY = 'graduation.deferred_indexes';-/** Config keys each engine owns: the target keeps its own values and the copy never writes them. */-export const TARGET_OWNED_CONFIG_KEYS: readonly string[] = ['engine', 'version', GRADUATION_DEFERRED_INDEXES_KEY];/** Default copy batch size in bytes of canonical text. */export const DEFAULT_COPY_BATCH_BYTES = 4 * 1024 * 1024;const MAX_BATCH_ROWS = 5000;const FENCE_TRIGGER_PREFIX = 'gbrain_graduation_fence';-const RENDER_SETTINGS = ["SET LOCAL TimeZone = 'UTC'", "SET LOCAL DateStyle = 'ISO'", 'SET LOCAL extra_float_digits = 3', "SET LOCAL IntervalStyle = 'postgres'", "SET LOCAL bytea_output = 'hex'"];--/** Rows of a carried table that are not copied (and not digested): the target-owned config keys. */-export function carryRowFilter(relation: string): string | null {- if (relation !== 'config') return null;- return `NOT (key = ANY (ARRAY[${TARGET_OWNED_CONFIG_KEYS.map(k => `'${k.replace(/'/g, "''")}'`).join(', ')}]::text[]))`;-}--export interface CopyTransform {- rule: string;- /** SQL over the typed source values; `col(name)` renders another column of the same row. */- sql: (col: (name: string) => string) => string;-}--const activeJob = (col: (name: string) => string, column: string) => `CASE WHEN ${col('status')} = 'active' THEN NULL ELSE ${col(column)} END`;-const claimedEffect = (col: (name: string) => string, column: string) => `CASE WHEN ${col('state')} IN ('running', 'queued') THEN NULL ELSE ${col(column)} END`;--/**- * Every column transform graduation may apply, keyed `relation.column`. An- * inventory entry lists the ones it uses; verify applies the same SQL to the- * source snapshot, so nothing else may differ.- */-export const COPY_TRANSFORMS: Readonly<Record<string, CopyTransform>> = {- 'minion_jobs.status': { rule: 'active -> waiting', sql: col => `CASE WHEN ${col('status')} = 'active' THEN 'waiting' ELSE ${col('status')} END` },- 'minion_jobs.lock_token': { rule: 'cleared on active jobs', sql: col => activeJob(col, 'lock_token') },- 'minion_jobs.lock_until': { rule: 'cleared on active jobs', sql: col => activeJob(col, 'lock_until') },- 'minion_jobs.timeout_at': { rule: 'cleared on active jobs', sql: col => activeJob(col, 'timeout_at') },- 'minion_jobs.started_at': { rule: 'cleared on active jobs', sql: col => activeJob(col, 'started_at') },- 'persistence_worktrees.heartbeat_at': { rule: 'reset', sql: () => 'NULL' },- 'persistence_effects.state': { rule: 'running -> queued', sql: col => `CASE WHEN ${col('state')} = 'running' THEN 'queued' ELSE ${col('state')} END` },- 'persistence_effects.execution_token': { rule: 'cleared on running and queued effects', sql: col => claimedEffect(col, 'execution_token') },- 'persistence_effects.claim_expires_at': { rule: 'cleared on running and queued effects', sql: col => claimedEffect(col, 'claim_expires_at') },- 'persistence_brain.enabled': { rule: 'false until cutover', sql: () => 'false' },-};--export function transformFor(relation: string, column: string): CopyTransform {- const transform = COPY_TRANSFORMS[`${relation}.${column}`];- if (!transform) throw new Error(`graduation inventory lists a transform for ${relation}.${column} that the copier does not implement`);- return transform;-}--export interface ColumnMeta {- name: string;- ident: string;- type: string;- generated: boolean;- generationExpr: string | null;- collatable: boolean;-}type Sql = Pick<BrainEngine, 'executeRaw'>;-async function relationIdent(engine: Sql, relation: string): Promise<string> {- const [row] = await engine.executeRaw<{ ident: string; exists: boolean }>(- "SELECT format('%I', $1::text) AS ident, to_regclass(format('public.%I', $1::text)) IS NOT NULL AS exists", [relation]);- if (!row?.exists) throw new Error(`relation ${relation} does not exist`);- return row.ident;-}--export async function tableColumns(engine: Sql, relation: string): Promise<ColumnMeta[]> {- const rows = await engine.executeRaw<{ name: string; ident: string; type: string; generated: boolean; generation_expr: string | null; collatable: boolean }>(- `SELECT a.attname AS name, format('%I', a.attname) AS ident, format_type(a.atttypid, a.atttypmod) AS type,- a.attgenerated <> '' AS generated, CASE WHEN a.attgenerated <> '' THEN pg_get_expr(d.adbin, d.adrelid) END AS generation_expr,- t.typcollation <> 0 AS collatable- FROM pg_attribute a JOIN pg_type t ON t.oid = a.atttypid- LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum- WHERE a.attrelid = to_regclass(format('public.%I', $1::text)) AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum`, [relation]);- return rows.map(r => ({ name: r.name, ident: r.ident, type: r.type, generated: r.generated === true, generationExpr: r.generation_expr, collatable: r.collatable === true }));+/** Generation expressions of a table's generated columns, keyed by column name. */+export async function generationExpressions(engine: Sql, relation: string): Promise<Map<string, string>> {+ const rows = await engine.executeRaw<{ name: string; expr: string }>(`SELECT a.attname AS name, pg_get_expr(d.adbin, d.adrelid) AS expr+ FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid JOIN pg_namespace n ON n.oid = c.relnamespace+ JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum+ WHERE n.nspname = current_schema() AND c.relname = $1 AND a.attnum > 0 AND NOT a.attisdropped AND a.attgenerated::text = 's'`, [relation]);+ return new Map(rows.map(r => [r.name, r.expr.replace(/\s+/g, ' ').trim()]));}-async function constraintColumns(engine: Sql, relation: string, kind: 'p' | 'f-self'): Promise<string[]> {- const rows = await engine.executeRaw<{ name: string }>(kind === 'p'- ? `SELECT a.attname AS name FROM pg_constraint k CROSS JOIN LATERAL unnest(k.conkey) WITH ORDINALITY AS u(attnum, ord)- JOIN pg_attribute a ON a.attrelid = k.conrelid AND a.attnum = u.attnum- WHERE k.contype = 'p' AND k.conrelid = to_regclass(format('public.%I', $1::text)) ORDER BY u.ord`- : `SELECT DISTINCT a.attname AS name FROM pg_constraint k CROSS JOIN LATERAL unnest(k.conkey) AS u(attnum)- JOIN pg_attribute a ON a.attrelid = k.conrelid AND a.attnum = u.attnum- WHERE k.contype = 'f' AND k.conrelid = k.confrelid AND k.conrelid = to_regclass(format('public.%I', $1::text)) ORDER BY 1`, [relation]);- return rows.map(r => r.name);-}--const normalizeExpr = (expr: string | null) => (expr ?? '').replace(/\s+/g, ' ').trim();-/*** The per-column contract: every non-allowlisted column must exist on both* sides with the same type and typmod, and generated columns must carry the- * same expression. Returns the columns the copy inserts (source order).+ * same expression. Returns the names of the columns the copy inserts.*/-export function columnContract(entry: Pick<InventoryEntry, 'relation' | 'columnAllowlist'>, source: readonly ColumnMeta[], target: readonly ColumnMeta[]): ColumnMeta[] {+export function columnContract(entry: Pick<InventoryEntry, 'relation' | 'columnAllowlist'>,+ source: { columns: readonly ColumnMeta[]; generated: ReadonlyMap<string, string> },+ target: { columns: readonly ColumnMeta[]; generated: ReadonlyMap<string, string> }): string[] {const allow = entry.columnAllowlist ?? {};- const targetByName = new Map(target.map(c => [c.name, c]));- const sourceNames = new Set(source.map(c => c.name));+ const targetByName = new Map(target.columns.map(c => [c.name, c]));+ const sourceNames = new Set(source.columns.map(c => c.name));const problems: string[] = [];- const copied: ColumnMeta[] = [];- for (const column of source) {+ const copied: string[] = [];+ for (const column of source.columns) {const other = targetByName.get(column.name);- if (column.name in allow) { if (other && !other.generated && !column.generated && other.type === column.type) copied.push(column); continue; }+ if (column.name in allow) { if (other && !other.generated && !column.generated && other.type === column.type) copied.push(column.name); continue; }if (!other) { problems.push(`${column.name} (${column.type}) is missing on the target`); continue; }if (other.type !== column.type) { problems.push(`${column.name} is ${column.type} on the source but ${other.type} on the target`); continue; }- if (other.generated !== column.generated || normalizeExpr(other.generationExpr) !== normalizeExpr(column.generationExpr)) {- problems.push(`${column.name} generation differs (source ${column.generationExpr ?? 'not generated'}, target ${other.generationExpr ?? 'not generated'})`);+ const sourceExpr = source.generated.get(column.name) ?? null;+ const targetExpr = target.generated.get(column.name) ?? null;+ if (other.generated !== column.generated || sourceExpr !== targetExpr) {+ problems.push(`${column.name} generation differs (source ${sourceExpr ?? 'not generated'}, target ${targetExpr ?? 'not generated'})`);continue;}- if (!column.generated) copied.push(column);+ if (!column.generated) copied.push(column.name);}- for (const column of target) {+ for (const column of target.columns) {if (!sourceNames.has(column.name) && !(column.name in allow)) problems.push(`${column.name} (${column.type}) exists only on the target`);}if (problems.length) {throw graduationError('graduation_target_unsupported', `The target's ${entry.relation} columns do not match the source.`,'Use an empty target database created by this gbrain version; the column contract never copies into a different shape.',{ why: `Graduation copies every column verbatim; ${entry.relation}: ${problems.join('; ')}.`, detail: problems.join('; '),- fix: { argv: ['gbrain', 'migrate', '--plan', '--json'], consent: [], actor: 'agent', requires_exclusive: false,- why: 'Re-plans after the target is replaced or its schema is upgraded.', verify: { argv: ['gbrain', 'migrate', '--plan', '--json'] } } });+ fix: { argv: ['gbrain', 'migrate', '--to', 'postgres', '--url-env', 'GBRAIN_TARGET_URL', '--plan', '--json'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Re-plans after the target is replaced or its schema is upgraded.' } });}return copied;}@@ -191,87 +124,86 @@ async function userTriggers(tx: Sql, relation: string, enabledOnly: boolean): Prconst ENABLE_BY_MODE: Readonly<Record<string, string>> = { O: 'ENABLE TRIGGER', A: 'ENABLE ALWAYS TRIGGER', R: 'ENABLE REPLICA TRIGGER' };+/** Keyset-paged source rows from the digest plan: raw primary-key texts and transformed column texts. */+async function readSourceBatch(source: BrainEngine, plan: DigestPlan, extraWhere: string | null, afterKey: readonly string[] | null, limit: number):+ Promise<Array<{ key: string[]; values: Array<string | null> }>> {+ const collate = (c: ColumnMeta, expr: string) => c.collatable ? `${expr} COLLATE "C"` : expr;+ const order = plan.key.map(k => collate(k, quoteIdent(k.name))).join(', ');+ const where = [+ plan.filter ? `(${plan.filter})` : '',+ extraWhere ? `(${extraWhere})` : '',+ afterKey ? `(${order}) > (${plan.key.map((k, i) => collate(k, `$${i + 1}::text::${k.type}`)).join(', ')})` : '',+ ].filter(Boolean);+ const rows = await withDigestSession(source, tx => tx.executeRaw<Record<string, string | null>>(+ `${plan.select}${where.length ? ` WHERE ${where.join(' AND ')}` : ''} ORDER BY ${order} LIMIT ${limit}`, afterKey ? [...afterKey] : []));+ return rows.map(r => ({ key: plan.key.map((_, i) => r[`k${i}`] as string), values: plan.columns.map((_, i) => r[`c${i}`] ?? null) }));+}+/*** Copies one carried (or rebind) table into the fenced target in a single- * transaction and returns the number of source rows copied.+ * transaction and returns the number of source rows copied. Catalog reads+ * happen before any transaction opens (PGLite serializes its one connection).*/export async function copyTable(e: GraduationEngines, entry: InventoryEntry,opts: { bypass: TriggerBypass; batchBytes?: number; onBatch?: (rows: number) => void; runId: string }): Promise<{ rows: number }> {if (entry.class !== 'carry' && entry.class !== 'rebind') throw new Error(`copyTable: ${entry.relation} is ${entry.class}, not carried`);const relation = entry.relation;- const sourceColumns = await tableColumns(e.source, relation);- const targetColumns = await tableColumns(e.target, relation);- if (!sourceColumns.length) throw new Error(`copyTable: ${relation} does not exist on the source`);- const columns = columnContract(entry, sourceColumns, targetColumns);- const pk = await constraintColumns(e.source, relation, 'p');- if (!pk.length) throw new Error(`copyTable: ${relation} has no primary key; the keyset copy needs one`);- const transforms = new Map(entry.transforms.map(t => [t.column, transformFor(relation, t.column)]));- const selfFk = opts.bypass === 'disable_trigger' ? (await constraintColumns(e.target, relation, 'f-self')).filter(c => columns.some(col => col.name === c)) : [];- const sourceIdent = await relationIdent(e.source, relation);- const targetIdent = await relationIdent(e.target, relation);- const filter = carryRowFilter(relation);- const index = new Map(columns.map((c, i) => [c.name, i]));- const pkColumns = pk.map(name => {- const column = columns.find(c => c.name === name);- if (!column) throw new Error(`copyTable: primary key column ${relation}.${name} is not copied`);- return column;- });- const typed = (name: string) => {- const i = index.get(name);- if (i === undefined) throw new Error(`copyTable: ${relation}.${name} is not a copied column`);- return `((r.v->>${i})::${columns[i]!.type})`;- };- const insertExprs = columns.map(c => selfFk.includes(c.name) ? 'NULL' : transforms.get(c.name)?.sql(typed) ?? typed(c.name));- const insertSql = `INSERT INTO ${targetIdent} (${columns.map(c => c.ident).join(', ')}) SELECT ${insertExprs.join(', ')} FROM jsonb_array_elements($1::text::jsonb) AS r(v)`;- const orderBy = pkColumns.map(c => c.collatable ? `${c.ident} COLLATE "C"` : c.ident).join(', ');- const keyset = `(${orderBy}) > (${pkColumns.map((c, j) => `$${j + 1}::${c.type}${c.collatable ? ' COLLATE "C"' : ''}`).join(', ')})`;+ const plan = await digestPlan(e.source, entry, true);+ const [targetColumns, sourceGenerated, targetGenerated] = await Promise.all([+ tableColumns(e.target, relation), generationExpressions(e.source, relation), generationExpressions(e.target, relation)]);+ if (!targetColumns.length) throw new Error(`copyTable: ${relation} does not exist on the target`);+ const copied = new Set(columnContract(entry, { columns: plan.columns, generated: sourceGenerated }, { columns: targetColumns, generated: targetGenerated }));+ const selfFk = opts.bypass === 'disable_trigger'+ ? (await e.target.executeRaw<{ name: string }>(`SELECT DISTINCT a.attname AS name FROM pg_constraint k CROSS JOIN LATERAL unnest(k.conkey) AS u(attnum)+ JOIN pg_attribute a ON a.attrelid = k.conrelid AND a.attnum = u.attnum JOIN pg_class c ON c.oid = k.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE k.contype = 'f' AND k.conrelid = k.confrelid AND n.nspname = current_schema() AND c.relname = $1`, [relation])).map(r => r.name).filter(name => copied.has(name))+ : [];+ const table = quoteIdent(relation);+ const inserted = plan.columns.map((c, i) => ({ c, i })).filter(({ c }) => copied.has(c.name));+ const insertSql = `INSERT INTO ${table} (${inserted.map(({ c }) => quoteIdent(c.name)).join(', ')}) SELECT ${inserted+ .map(({ c, i }) => selfFk.includes(c.name) ? 'NULL' : `(r.v->>${i})::${c.type}`).join(', ')} FROM jsonb_array_elements($1::text::jsonb) AS r(v)`;const batchBytes = opts.batchBytes ?? DEFAULT_COPY_BATCH_BYTES;+ const deleteFilter = [entry.rowFilter ? `(${entry.rowFilter})` : '', relation === 'config' ? `key <> '${GRADUATION_DEFERRED_INDEXES_KEY}'` : ''].filter(Boolean);+ const disabled = opts.bypass === 'disable_trigger' ? await userTriggers(e.target, relation, true) : [];- const selectList = columns.map((c, i) => `${c.ident}::text AS c${i}`).join(', ');const scan = async (extraWhere: string | null, visit: (rows: Array<Array<string | null>>) => Promise<void>) => {let limit = 100;- let last: Array<string | null> | null = null;+ let after: string[] | null = null;for (;;) {- const where: string[] = [filter, extraWhere, last ? keyset : null].filter((w): w is string => !!w);- const sql: string = `SELECT ${selectList} FROM ${sourceIdent}${where.length ? ` WHERE ${where.join(' AND ')}` : ''} ORDER BY ${orderBy} LIMIT ${limit}`;- const params: Array<string | null> = last ? pkColumns.map(c => last![index.get(c.name)!]!) : [];- const rows: Array<Record<string, string | null>> = await e.source.transaction(async tx => {- for (const setting of RENDER_SETTINGS) await tx.executeRaw(setting);- return tx.executeRaw<Record<string, string | null>>(sql, params);- });+ const rows = await readSourceBatch(e.source, plan, extraWhere, after, limit);if (!rows.length) return;- const values: Array<Array<string | null>> = rows.map(row => columns.map((_, i) => row[`c${i}`] ?? null));+ const values = rows.map(r => r.values);await visit(values);if (rows.length < limit) return;- last = values[values.length - 1]!;- const bytes = values.reduce((sum, row) => sum + row.reduce((s, v) => s + (v?.length ?? 4) + 3, 2), 0);+ after = rows[rows.length - 1]!.key;+ const bytes = values.reduce((sum, row) => sum + row.reduce((n, v) => n + (v?.length ?? 4) + 3, 2), 0);limit = Math.max(1, Math.min(MAX_BATCH_ROWS, Math.floor(batchBytes * rows.length / Math.max(1, bytes))));}};return e.target.transaction(async tx => {await setFence(tx, opts.runId);- const disabled = opts.bypass === 'disable_trigger' ? await userTriggers(tx, relation, true) : [];if (opts.bypass === 'session_replication_role') await tx.executeRaw('SET LOCAL session_replication_role = replica');- for (const trigger of disabled) await tx.executeRaw(`ALTER TABLE ${targetIdent} DISABLE TRIGGER ${trigger.ident}`);- await tx.executeRaw(`DELETE FROM ${targetIdent}${filter ? ` WHERE ${filter}` : ''}`);- let copied = 0;- await scan(null, async rows => {- await tx.executeRaw(insertSql, [JSON.stringify(rows)]);- copied += rows.length;- opts.onBatch?.(rows.length);+ for (const trigger of disabled) await tx.executeRaw(`ALTER TABLE ${table} DISABLE TRIGGER ${trigger.ident}`);+ await tx.executeRaw(`DELETE FROM ${table}${deleteFilter.length ? ` WHERE ${deleteFilter.join(' AND ')}` : ''}`);+ let rows = 0;+ await scan(null, async batch => {+ await tx.executeRaw(insertSql, [JSON.stringify(batch)]);+ rows += batch.length;+ opts.onBatch?.(batch.length);});if (selfFk.length) {- const fkColumns = selfFk.map(name => columns[index.get(name)!]!);- const updateSql = `UPDATE ${targetIdent} AS t SET ${fkColumns.map((c, j) => `${c.ident} = (r.v->>${pkColumns.length + j})::${c.type}`).join(', ')}- FROM jsonb_array_elements($1::text::jsonb) AS r(v) WHERE ${pkColumns.map((c, j) => `t.${c.ident} = (r.v->>${j})::${c.type}`).join(' AND ')}`;- await scan(`(${fkColumns.map(c => `${c.ident} IS NOT NULL`).join(' OR ')})`, async rows => {- const payload = rows.map(row => [...pkColumns.map(c => row[index.get(c.name)!]), ...fkColumns.map(c => row[index.get(c.name)!] ?? null)]);+ const fk = selfFk.map(name => ({ c: plan.columns.find(c => c.name === name)!, i: plan.columns.findIndex(c => c.name === name) }));+ const keyIndex = plan.key.map(k => plan.columns.findIndex(c => c.name === k.name));+ const updateSql = `UPDATE ${table} AS t SET ${fk.map(({ c }, j) => `${quoteIdent(c.name)} = (r.v->>${plan.key.length + j})::${c.type}`).join(', ')}+ FROM jsonb_array_elements($1::text::jsonb) AS r(v) WHERE ${plan.key.map((k, j) => `t.${quoteIdent(k.name)} = (r.v->>${j})::${k.type}`).join(' AND ')}`;+ await scan(fk.map(({ c }) => `${quoteIdent(c.name)} IS NOT NULL`).join(' OR '), async batch => {+ const payload = batch.map(row => [...keyIndex.map(i => row[i] ?? null), ...fk.map(({ i }) => row[i] ?? null)]);await tx.executeRaw(updateSql, [JSON.stringify(payload)]);});}- for (const trigger of disabled) await tx.executeRaw(`ALTER TABLE ${targetIdent} ${ENABLE_BY_MODE[trigger.enabled] ?? 'ENABLE TRIGGER'} ${trigger.ident}`);- return { rows: copied };+ for (const trigger of disabled) await tx.executeRaw(`ALTER TABLE ${table} ${ENABLE_BY_MODE[trigger.enabled] ?? 'ENABLE TRIGGER'} ${trigger.ident}`);+ return { rows };});}@@ -415,7 +347,7 @@ export async function reenableTriggers(target: BrainEngine, relations: readonlyfor (const relation of relations) {const [present] = await tx.executeRaw<{ present: boolean }>("SELECT to_regclass(format('public.%I', $1::text)) IS NOT NULL AS present", [relation]);if (!present?.present) continue;- const ident = await relationIdent(tx, relation);+ const ident = quoteIdent(relation);for (const trigger of await userTriggers(tx, relation, false)) {await tx.executeRaw(`ALTER TABLE ${ident} ENABLE TRIGGER ${trigger.ident}`);enabled.push(`${relation}.${trigger.ident}`);diff --git a/src/core/persistence/graduation-drain.ts b/src/core/persistence/graduation-drain.tsindex b5970fa18e..9b65f113bf 100644--- a/src/core/persistence/graduation-drain.ts+++ b/src/core/persistence/graduation-drain.ts@@ -29,7 +29,8 @@ type PendingRequest = { request_id: string; source_id: string; operation: string* host are `request` blockers the drain itself clears (recovering ones carry* the retry command for when the drain cannot finish them); requests and host* bindings owned by another host, recovering topology changes, recovering- * effects and the writer admin lock need someone else to act first.+ * effects, the writer admin lock and OAuth clients bound to a missing source+ * (an FK only Postgres enforces) need someone else to act first.*/export async function graduationBlockers(source: BrainEngine, hostId: string): Promise<readonly GraduationBlocker[]> {const blockers: GraduationBlocker[] = [];@@ -72,6 +73,17 @@ export async function graduationBlockers(source: BrainEngine, hostId: string): Pblockers.push({ kind: 'foreign_host_binding', id: `${b.worktree_id}:${b.host_id}`, detail: `worktree ${b.worktree_id} has a binding on host ${b.host_id}`,argv: ['gbrain', 'sources', 'writer', 'transfer', 'prepare', b.source_id ?? b.worktree_id], needsUser: true });}+ const [boundColumn] = await source.executeRaw<{ present: boolean }>(`SELECT EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'oauth_clients' AND column_name = 'bound_source_id') AS present`);+ if (boundColumn?.present) {+ const dangling = await source.executeRaw<{ client_id: string; client_name: string; bound_source_id: string }>(`SELECT c.client_id, c.client_name, c.bound_source_id+ FROM oauth_clients c WHERE c.bound_source_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM sources s WHERE s.id = c.bound_source_id) ORDER BY c.client_id`);+ for (const c of dangling) {+ blockers.push({ kind: 'dangling_reference', id: `oauth_clients.${c.client_id}`,+ detail: `OAuth client ${c.client_name} is bound to source ${c.bound_source_id}, which no longer exists; Postgres enforces this binding, and clearing it would widen the client's access. Restore the source, or revoke the client and register a replacement`,+ argv: ['gbrain', 'auth', 'revoke-client', c.client_id], needsUser: true });+ }+ }return blockers;}diff --git a/src/core/persistence/graduation-target.ts b/src/core/persistence/graduation-target.tsindex 7275819969..62505e90ad 100644--- a/src/core/persistence/graduation-target.ts+++ b/src/core/persistence/graduation-target.ts@@ -49,7 +49,7 @@ function parsePostgresUrl(url: string): URL {{ why: 'Graduation moves a PGLite brain into a Postgres database; the given value is not a Postgres connection URL.',fix: { argv: targetPlanArgv({}), consent: ['credentials'], actor: 'agent', requires_exclusive: false,why: 'Re-plans against a URL held in an environment variable, so the password never appears in argv.',- user_message: `Set ${DEFAULT_TARGET_URL_ENV} to the Postgres URL of the target database (postgres://user:password@host:5432/db).`,+ user_message: `Set ${DEFAULT_TARGET_URL_ENV} to the Postgres connection URL of the target database (user, password, host, port and database).`,verify: { argv: targetPlanArgv({}) } } });}return new URL(url.replace(/^postgres(?:ql)?:\/\//i, 'http://'));diff --git a/test/e2e/graduation-copy.test.ts b/test/e2e/graduation-copy.test.tsindex 922bf6091b..40809a872f 100644--- a/test/e2e/graduation-copy.test.ts+++ b/test/e2e/graduation-copy.test.ts@@ -6,9 +6,9 @@* under the DISABLE TRIGGER fallback behind a database fence.** Protects: verbatim copy with primary keys preserved (every carried table's- * canonical snapshot, transforms applied to the source side, equals the- * target), initSchema seed rows replaced, exact sequence positions, every FK- * satisfied, user triggers enabled after the copy, deferred HNSW/GIN indexes+ * canonical digest from graduation-digest.ts, transforms applied to the+ * source side, equals the target's, in the inventory's copy order),+ * initSchema seed rows replaced, exact sequence positions, every FK satisfied, user triggers enabled after the copy, deferred HNSW/GIN indexes* rebuilt, and the fence still refusing writes that lack the run identity.* Fails when: a column, key, sequence position, trigger state or index set* differs, or the copy needs a session the fence would refuse.@@ -30,7 +30,8 @@ import { buildHistoryFixture, HISTORY_FIXTURE_TABLES, type HistoryFixture } fromimport { copySequences, deferIndexes, buildDeferredIndexes, detectTriggerBypass } from '../../src/core/persistence/graduation-copy.ts';import { drainForGraduation, freezeSource } from '../../src/core/persistence/graduation-drain.ts';import { embeddingColumns } from '../../src/core/persistence/graduation-target.ts';-import { copyAll, firstDifference, localCopyInventory, tableSnapshot } from '../helpers/graduation-copy-harness.ts';+import { copiedEntries, copyAll, digestMismatches } from '../helpers/graduation-copy-harness.ts';+import { assertRelationSet } from '../../src/core/persistence/graduation-inventory.ts';import { requirePostgresTestDatabase } from '../helpers/test-backends.ts';const databaseUrl = requirePostgresTestDatabase();@@ -97,7 +98,7 @@ async function installTestFence(target: BrainEngine, runId: string): Promise<voiasync function graduateInto(target: PostgresEngine, bypass: TriggerBypass, runId: string, label: string): Promise<InventoryEntry[]> {const e = { source, target };- const entries = await localCopyInventory(e);+ const entries = [...await copiedEntries(e)];const before = await indexSet(target);let t = performance.now();const deferred = await deferIndexes(target, { runId });@@ -120,14 +121,7 @@ async function graduateInto(target: PostgresEngine, bypass: TriggerBypass, runId}async function assertEqualCopy(target: PostgresEngine, entries: readonly InventoryEntry[]): Promise<void> {- const differences: string[] = [];- for (const entry of entries) {- const [a, b] = [await tableSnapshot(source, entry, { applyTransforms: true }), await tableSnapshot(target, entry)];- const diff = firstDifference(a, b);- if (diff) differences.push(diff);- if (!diff) expect(b.keys).toEqual(a.keys);- }- expect(differences).toEqual([]);+ expect(await digestMismatches({ source, target }, entries)).toEqual([]);expect(await fkOrphans(target)).toEqual([]);const disabled = await target.executeRaw(`SELECT tgrelid::regclass::text AS relation, tgname FROM pg_trigger WHERE NOT tgisinternal AND tgenabled = 'D'`);expect(disabled).toEqual([]);@@ -156,6 +150,7 @@ beforeAll(async () => {expect(result.blockers).toEqual([]);drained = result.drained;await freezeSource(source);+ await assertRelationSet(source, 'pglite');}, 1_800_000);afterAll(async () => {@@ -177,6 +172,7 @@ describe(`graduation copy of a ${PAGES}-page history brain`, () => {try {expect(await embeddingColumns((sql, p) => target.executeRaw(sql, p))).toEqual(await embeddingColumns((sql, p) => source.executeRaw(sql, p)));expect(await detectTriggerBypass(target)).toBe('session_replication_role');+ await assertRelationSet(target, 'postgres');const entries = await graduateInto(target, 'session_replication_role', randomUUID(), 'replica');await assertEqualCopy(target, entries);const [brain] = await target.executeRaw<{ brain_id: string; enabled: boolean }>('SELECT brain_id::text AS brain_id, enabled FROM persistence_brain');diff --git a/test/graduation-copy.test.ts b/test/graduation-copy.test.tsindex 59cd949bd1..da5d24d740 100644--- a/test/graduation-copy.test.ts+++ b/test/graduation-copy.test.ts@@ -19,33 +19,30 @@import { afterEach, beforeEach, describe, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';import type { BrainEngine } from '../src/core/engine.ts';-import type { InventoryEntry, TriggerBypass } from '../src/core/persistence/engine-graduation.types.ts';+import type { ColumnMeta, TriggerBypass } from '../src/core/persistence/engine-graduation.types.ts';import {- buildDeferredIndexes, carryRowFilter, columnContract, COPY_TRANSFORMS, copySequences, copyTable, deferIndexes, detectTriggerBypass,- GRADUATION_DEFERRED_INDEXES_KEY, reenableTriggers, tableColumns, transformFor, type ColumnMeta,+ buildDeferredIndexes, columnContract, copySequences, copyTable, deferIndexes, detectTriggerBypass, GRADUATION_DEFERRED_INDEXES_KEY, reenableTriggers,} from '../src/core/persistence/graduation-copy.ts';-import { firstDifference, LOCAL_TRANSFORMS, tableSnapshot } from './helpers/graduation-copy-harness.ts';+import { tableColumns } from '../src/core/persistence/graduation-digest.ts';+import { GRADUATION_INVENTORY } from '../src/core/persistence/graduation-inventory.ts';+import { digestMismatches, inventoryEntry as entry, rowCount } from './helpers/graduation-copy-harness.ts';import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';-function entry(relation: string, extra: Partial<InventoryEntry> = {}): InventoryEntry {- return { relation, kind: 'table', class: 'carry', engines: { pglite: true, postgres: true }, lossKind: 'user_data', reason: 'test',- transforms: (LOCAL_TRANSFORMS[relation] ?? []).map(column => ({ column, rule: transformFor(relation, column).rule })), ...extra };-}-const col = (name: string, type: string, extra: Partial<ColumnMeta> = {}): ColumnMeta =>- ({ name, ident: name, type, generated: false, generationExpr: null, collatable: type === 'text', ...extra });+ ({ name, type, category: type === 'text' ? 'S' : 'N', generated: false, collatable: type === 'text', ...extra });+const side = (columns: ColumnMeta[], generated: Record<string, string> = {}) => ({ columns, generated: new Map(Object.entries(generated)) });describe('column contract', () => {test('copies matching columns and never inserts generated ones', () => {- const source = [col('id', 'integer'), col('a', 'text'), col('n', 'integer', { generated: true, generationExpr: 'length(a)' })];- const target = [col('a', 'text'), col('id', 'integer'), col('n', 'integer', { generated: true, generationExpr: 'length(a)' })];- expect(columnContract(entry('t'), source, target).map(c => c.name)).toEqual(['id', 'a']);+ const source = side([col('id', 'integer'), col('a', 'text'), col('n', 'integer', { generated: true })], { n: 'length(a)' });+ const target = side([col('a', 'text'), col('id', 'integer'), col('n', 'integer', { generated: true })], { n: 'length(a)' });+ expect(columnContract(entry('t'), source, target)).toEqual(['id', 'a']);});test('refuses missing, retyped, target-only and differently generated columns, naming each', () => {- const source = [col('id', 'integer'), col('a', 'text'), col('emb', 'vector(1536)'), col('n', 'integer', { generated: true, generationExpr: 'length(a)' })];- const target = [col('id', 'integer'), col('emb', 'vector(768)'), col('extra', 'text'), col('n', 'integer', { generated: true, generationExpr: 'length(a) + 1' })];+ const source = side([col('id', 'integer'), col('a', 'text'), col('emb', 'vector(1536)'), col('n', 'integer', { generated: true })], { n: 'length(a)' });+ const target = side([col('id', 'integer'), col('emb', 'vector(768)'), col('extra', 'text'), col('n', 'integer', { generated: true })], { n: '(length(a) + 1)' });let error: unknown;try { columnContract(entry('t'), source, target); } catch (e) { error = e; }const json = (error as { toJSON(): Record<string, unknown> }).toJSON();@@ -54,20 +51,19 @@ describe('column contract', () => {expect(String(json.detail)).toContain('emb is vector(1536) on the source but vector(768) on the target');expect(String(json.detail)).toContain('extra (text) exists only on the target');expect(String(json.detail)).toContain('n generation differs');- expect((json.fix as { argv: string[] }).argv).toEqual(['gbrain', 'migrate', '--plan', '--json']);+ expect((json.fix as { argv: string[] }).argv).toContain('--plan');});test('an allowlisted column may differ', () => {- const source = [col('id', 'integer'), col('legacy', 'text')];- const target = [col('id', 'integer'), col('added', 'text')];- expect(columnContract(entry('t', { columnAllowlist: { legacy: 'dropped upstream', added: 'nullable, defaulted' } }), source, target).map(c => c.name)).toEqual(['id']);+ const source = side([col('id', 'integer'), col('legacy', 'text')]);+ const target = side([col('id', 'integer'), col('added', 'text')]);+ expect(columnContract(entry('t', { columnAllowlist: { legacy: 'dropped upstream', added: 'nullable, defaulted' } }), source, target)).toEqual(['id']);});- test('transforms and row filters', () => {- expect(() => transformFor('pages', 'title')).toThrow(/does not implement/);- for (const [relation, columns] of Object.entries(LOCAL_TRANSFORMS)) for (const c of columns) expect(COPY_TRANSFORMS[`${relation}.${c}`]).toBeDefined();- expect(carryRowFilter('pages')).toBeNull();- expect(carryRowFilter('config')).toContain(GRADUATION_DEFERRED_INDEXES_KEY);+ test('every inventory transform carries the SQL the copier selects', () => {+ const transforms = GRADUATION_INVENTORY.entries.flatMap(e => e.transforms.map(t => ({ relation: e.relation, ...t })));+ expect(transforms.length).toBeGreaterThan(0);+ expect(transforms.filter(t => !t.expression)).toEqual([]);});});@@ -121,12 +117,10 @@ for (const backend of testBackends()) {const batches: number[] = [];for (const relation of relations) {const { rows } = await copyTable(e, entry(relation), { bypass, runId, batchBytes: 64, onBatch: n => batches.push(n) });- expect(rows).toBe((await tableSnapshot(source, entry(relation))).rows);+ expect(rows).toBe(await rowCount(source, entry(relation)));}expect(Math.max(...batches)).toBeLessThan(10);- for (const relation of relations) {- expect(firstDifference(await tableSnapshot(source, entry(relation), { applyTransforms: true }), await tableSnapshot(target, entry(relation)))).toBeNull();- }+ expect(await digestMismatches(e, relations.map(r => entry(r)))).toEqual([]);const keys = (await target.executeRaw<{ k: string }>('SELECT k FROM graduation_test_types ORDER BY k COLLATE "C"')).map(r => r.k);expect(keys).toEqual(['1', 'B', 'Zeta', 'a-b', 'a_b', 'alpha', 'b', 'é']);expect(await target.executeRaw("SELECT id FROM sources WHERE id = 'default' AND name = 'renamed default'")).toHaveLength(1);diff --git a/test/graduation-drain.test.ts b/test/graduation-drain.test.tsindex cceb0f999e..ea5e273428 100644--- a/test/graduation-drain.test.ts+++ b/test/graduation-drain.test.ts@@ -6,7 +6,8 @@* terminal state through a request-only consumer that runs no effects (the* drained request's effects stay queued for the target's worker), no resident* service is left running, the blocker taxonomy (queued request drained;- * foreign host binding, writer admin lock and recovering effect refuse up+ * foreign host binding, writer admin lock, recovering effect and (PGLite) an+ * OAuth client bound to a missing source refuse up* front with their structured actions and the drain starts nothing), the* `--drain-timeout` refusal shape, and the frozen source (writes fail,* custody writes through `withSourceWritable` succeed).@@ -67,6 +68,7 @@ for (const backend of testBackends()) {await tx.executeRaw(`INSERT INTO config (key, value) VALUES ($1, '{"locked": true, "set_at": "2026-10-04T00:00:00Z"}')ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`, [WRITER_ADMIN_LOCK_KEY]);await tx.executeRaw(`UPDATE persistence_effects SET recovery = '{"kind": "test"}'::jsonb WHERE id = $1`, [fixture.delayedEffectId]);+ if (engine.kind === 'pglite') await tx.executeRaw("UPDATE oauth_clients SET bound_source_id = 'removed-source' WHERE client_id = $1", [fixture.oauthClientId]);});const blocked = await drainForGraduation(engine, { timeoutMs: 1000, hostId, config: config(engine.kind) });expect(blocked.drained).toEqual([]);@@ -76,6 +78,10 @@ for (const backend of testBackends()) {argv: expect.arrayContaining(['gbrain', 'sources', 'writer', 'transfer', 'prepare']) }),expect.objectContaining({ kind: 'effect_recovery', id: String(fixture.delayedEffectId), needsUser: false }),]));+ if (engine.kind === 'pglite') {+ expect(blocked.blockers).toContainEqual(expect.objectContaining({ kind: 'dangling_reference', id: `oauth_clients.${fixture.oauthClientId}`,+ argv: ['gbrain', 'auth', 'revoke-client', fixture.oauthClientId], needsUser: true }));+ }if (engine.kind === 'pglite') {await freezeSource(engine);diff --git a/test/graduation-target.test.ts b/test/graduation-target.test.tsindex e6ee4da3f9..6ede0b9815 100644--- a/test/graduation-target.test.ts+++ b/test/graduation-target.test.ts@@ -134,7 +134,8 @@ describe.skipIf(!databaseUrl)('Postgres probes and the route cross-check', () =>expect(empty.vector.halfvec).toBe(true);expect(targetProbeBlockers(empty, routes)).toEqual([]);const db = postgres(routes.mainUrl, { max: 1, onnotice: () => {} });- expect(await db.unsafe("SELECT count(*)::int AS n FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'public'")).toEqual([{ n: 0 }]);+ const [relations] = await db.unsafe("SELECT count(*)::int AS n FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'public'");+ expect(relations!.n).toBe(0);await db.end();const engine = new PostgresEngine();diff --git a/test/helpers/graduation-copy-harness.ts b/test/helpers/graduation-copy-harness.tsindex ed393b684e..60f20859cb 100644--- a/test/helpers/graduation-copy-harness.ts+++ b/test/helpers/graduation-copy-harness.ts@@ -1,57 +1,24 @@/**- * Test-only stand-ins for the graduation inventory lane: a local inventory- * derived from information_schema (every base table present on both engines,- * with the plan's non-carry classes and transforms), an FK topological order,- * and canonical per-table snapshots for comparing a source with its copy.+ * Test helpers for the graduation copier: inventory entries from the real+ * GRADUATION_INVENTORY (a default carry entry for test-only tables), the+ * whole-brain copy in `copyOrder`, and digest comparison between a source+ * (transforms applied) and its copy, through the same `digestTable` verify uses.*/-import { createHash } from 'node:crypto';import type { BrainEngine } from '../../src/core/engine.ts';-import type { GraduationEngines, InventoryClass, InventoryEntry, TriggerBypass } from '../../src/core/persistence/engine-graduation.types.ts';-import { carryRowFilter, copyTable, tableColumns, transformFor } from '../../src/core/persistence/graduation-copy.ts';--export const LOCAL_NON_CARRY: Readonly<Record<string, InventoryClass>> = {- planner_stats_deltas: 'discard', planner_stats_state: 'discard', gbrain_cycle_locks: 'discard', budget_reservations: 'discard',- subagent_rate_leases: 'discard', oauth_codes: 'discard', query_cache: 'rebuild', code_traversal_cache: 'rebuild',- file_migration_ledger: 'schema_owned', persistence_graduation: 'schema_owned',-};--export const LOCAL_TRANSFORMS: Readonly<Record<string, readonly string[]>> = {- minion_jobs: ['status', 'lock_token', 'lock_until', 'timeout_at', 'started_at'],- persistence_worktrees: ['heartbeat_at'],- persistence_effects: ['state', 'execution_token', 'claim_expires_at'],- persistence_brain: ['enabled'],-};--async function baseTables(engine: BrainEngine): Promise<string[]> {- const rows = await engine.executeRaw<{ name: string }>(- "SELECT table_name AS name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE' ORDER BY 1");- return rows.map(r => r.name);+import type { GraduationEngines, InventoryEntry, TriggerBypass } from '../../src/core/persistence/engine-graduation.types.ts';+import { copyTable } from '../../src/core/persistence/graduation-copy.ts';+import { digestPlan, readDigestRows, withDigestSession, digestTable } from '../../src/core/persistence/graduation-digest.ts';+import { copyOrder, GRADUATION_INVENTORY, listRelations } from '../../src/core/persistence/graduation-inventory.ts';++export function inventoryEntry(relation: string, extra: Partial<InventoryEntry> = {}): InventoryEntry {+ const known = GRADUATION_INVENTORY.entries.find(e => e.relation === relation);+ return { ...(known ?? { relation, kind: 'table', class: 'carry', engines: { pglite: true, postgres: true }, lossKind: 'user_data', transforms: [], reason: 'test table' }), ...extra };}-/** Carry and rebind entries for every table present on both engines, in FK topological order. */-export async function localCopyInventory(e: GraduationEngines): Promise<InventoryEntry[]> {- const target = new Set(await baseTables(e.target));- const tables = (await baseTables(e.source)).filter(t => target.has(t) && !(t in LOCAL_NON_CARRY));- const edges = await e.source.executeRaw<{ child: string; parent: string }>(`SELECT c.relname AS child, p.relname AS parent- FROM pg_constraint k JOIN pg_class c ON c.oid = k.conrelid JOIN pg_class p ON p.oid = k.confrelid- WHERE k.contype = 'f' AND k.conrelid <> k.confrelid`);- const parents = new Map(tables.map(t => [t, new Set<string>()]));- for (const edge of edges) if (parents.has(edge.child) && parents.has(edge.parent)) parents.get(edge.child)!.add(edge.parent);- const ordered: string[] = [];- const seen = new Set<string>();- const visit = (t: string, path: Set<string>) => {- if (seen.has(t)) return;- if (path.has(t)) throw new Error(`FK cycle at ${t}`);- path.add(t);- for (const p of [...parents.get(t)!].sort()) visit(p, path);- path.delete(t); seen.add(t); ordered.push(t);- };- for (const t of tables) visit(t, new Set());- return ordered.map(relation => ({- relation, kind: 'table', class: relation === 'persistence_brain' ? 'rebind' : 'carry', engines: { pglite: true, postgres: true },- lossKind: 'user_data', transforms: (LOCAL_TRANSFORMS[relation] ?? []).map(column => ({ column, rule: transformFor(relation, column).rule })),- reason: 'test inventory',- }));+/** Carried and rebound entries present on both engines, parents first. */+export async function copiedEntries(e: GraduationEngines): Promise<readonly InventoryEntry[]> {+ const onTarget = new Set((await listRelations(e.target)).map(r => r.relation));+ return (await copyOrder(e.source)).filter(entry => onTarget.has(entry.relation));}export async function copyAll(e: GraduationEngines, entries: readonly InventoryEntry[], opts: { bypass: TriggerBypass; runId: string; batchBytes?: number }):@@ -61,40 +28,27 @@ export async function copyAll(e: GraduationEngines, entries: readonly InventoryEreturn counts;}-export interface TableSnapshot { relation: string; rows: number; sha256: string; keys: string[]; lines: string[] }--/**- * Canonical snapshot: every column (generated ones included, in name order, since- * the engines' physical column order differs) as text under- * UTC/ISO rendering, ordered by primary key with COLLATE "C". With- * `applyTransforms` the entry's transforms are applied, so a source snapshot- * compares equal to its copy.- */-export async function tableSnapshot(engine: BrainEngine, entry: InventoryEntry, opts: { applyTransforms?: boolean } = {}): Promise<TableSnapshot> {- const columns = (await tableColumns(engine, entry.relation)).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);- const transforms = new Map(opts.applyTransforms ? entry.transforms.map(t => [t.column, transformFor(entry.relation, t.column)]) : []);- const identOf = (name: string) => columns.find(c => c.name === name)!.ident;- const pk = await engine.executeRaw<{ name: string }>(`SELECT a.attname AS name FROM pg_constraint k CROSS JOIN LATERAL unnest(k.conkey) WITH ORDINALITY AS u(attnum, ord)- JOIN pg_attribute a ON a.attrelid = k.conrelid AND a.attnum = u.attnum WHERE k.contype = 'p' AND k.conrelid = to_regclass(format('public.%I', $1::text)) ORDER BY u.ord`, [entry.relation]);- const order = pk.map(p => { const c = columns.find(col => col.name === p.name)!; return c.collatable ? `${c.ident} COLLATE "C"` : c.ident; }).join(', ');- const select = columns.map((c, i) => `(${transforms.get(c.name)?.sql(identOf) ?? c.ident})::text AS c${i}`).join(', ');- const filter = carryRowFilter(entry.relation);- const [{ ident }] = await engine.executeRaw<{ ident: string }>("SELECT format('%I', $1::text) AS ident", [entry.relation]);- const rows = await engine.transaction(async tx => {- for (const s of ["SET LOCAL TimeZone = 'UTC'", "SET LOCAL DateStyle = 'ISO'", 'SET LOCAL extra_float_digits = 3']) await tx.executeRaw(s);- return tx.executeRaw<Record<string, string | null>>(`SELECT ${select} FROM ${ident}${filter ? ` WHERE ${filter}` : ''} ORDER BY ${order}`);- });- const pkIndex = pk.map(p => columns.findIndex(c => c.name === p.name));- const lines = rows.map(r => JSON.stringify(columns.map((_, i) => r[`c${i}`] ?? null)));- const keys = rows.map(r => JSON.stringify(pkIndex.map(i => r[`c${i}`] ?? null)));- return { relation: entry.relation, rows: rows.length, sha256: createHash('sha256').update(lines.join('\n')).digest('hex'), keys, lines };+/** First row whose canonical text differs (bounded scan for a readable message). */+async function firstDifference(e: GraduationEngines, entry: InventoryEntry): Promise<string> {+ const [a, b] = [await digestPlan(e.source, entry, true), await digestPlan(e.target, entry, false)];+ const rowsA = await withDigestSession(e.source, tx => readDigestRows(tx, a, null, 100_000));+ const rowsB = await withDigestSession(e.target, tx => readDigestRows(tx, b, null, 100_000));+ for (let i = 0; i < Math.max(rowsA.length, rowsB.length); i++) {+ if (rowsA[i]?.text !== rowsB[i]?.text) return `${entry.relation} row ${i}: source ${rowsA[i]?.text ?? '<none>'} target ${rowsB[i]?.text ?? '<none>'}`.slice(0, 2000);+ }+ return `${entry.relation}: digests differ`;}-/** First differing row between two snapshots, for a readable assertion message. */-export function firstDifference(a: TableSnapshot, b: TableSnapshot): string | null {- if (a.sha256 === b.sha256) return null;- for (let i = 0; i < Math.max(a.lines.length, b.lines.length); i++) {- if (a.lines[i] !== b.lines[i]) return `${a.relation} row ${i}: source ${a.lines[i] ?? '<none>'} target ${b.lines[i] ?? '<none>'}`.slice(0, 2000);+/** Relations whose transformed source digest differs from the target digest, with the first differing row. */+export async function digestMismatches(e: GraduationEngines, entries: readonly InventoryEntry[]): Promise<string[]> {+ const mismatches: string[] = [];+ for (const entry of entries) {+ const [a, b] = [await digestTable(e.source, entry, { applyTransforms: true }), await digestTable(e.target, entry)];+ if (a.rows !== b.rows || a.rootSha256 !== b.rootSha256) mismatches.push(await firstDifference(e, entry));}- return `${a.relation}: digests differ`;+ return mismatches;+}++export async function rowCount(engine: BrainEngine, entry: InventoryEntry): Promise<number> {+ return (await digestTable(engine, entry, { applyTransforms: true })).rows;}