Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

graduation G2b: FK-closure re-copy, KEY_FILES entries

garrytan85cccafa3bba
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index d6b38433ad..4aca6b3379 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -18,3 +18,6 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an
- `src/core/persistence/sync-waivers.ts` — managed-sync no-op waivers (#5470, #5984). `waiveNoopEntry` screens a frozen, unadmitted entry: an unchanged import (`unchangedSyncImport`, moved here from `sync-run.ts`, with the #5751 working-tree kernel waivers) or a delete whose page is already soft-deleted at the entry's frozen `expected_revision` with its file absent (never an unowned deletion or a rename). A candidate runs `validateSyncAuthority` first (a revoked grant throws before any waiver), then commits in one transaction with a fixed lock order: page guard (`lockPageKeys`), then the managed-sync cursor row `FOR UPDATE`; it re-reads the snapshot (and, for deletes, the origin and file absence) and refuses while `UNFINISHED_PAGE_REQUEST_SQL` finds an unfinished request for the page by slug, page id or a `renameFrom` naming it. That lookup is three `LIMIT 1` branches served by `persistence_requests_pending`, `persistence_requests_recovery` and the database-only pending index (EXPLAIN pinned in `test/persistence-managed-sync.test.ts`). A cursor that moved meanwhile is adopted instead of waived again, so `waived` counts only increment in the winning transaction. `GBRAIN_SYNC_WAIVE_NOOP=0` admits every entry. Tests: `test/persistence-managed-sync.test.ts` (#5984 waiver cases), `test/persistence-sync-legacy-files-5751.test.ts`.
- `src/core/persistence/accepted-pending.ts` — `acceptedPendingReceipt(error)`: the shared test for an accepted, not yet committed write, used by managed atom publication, extract_atoms, managed import and the connector budget.
- `src/core/persistence/connector-checkpoint-migration.ts` — migration 176 and orphan cleanup. The newest committed checkpoint receipt per source incarnation (found by slug, so a compacted one is still seen and re-walks) is copied to the stable key with `INSERT … ON CONFLICT DO NOTHING`; state rows are seeded; the cutoff is stored in `op_checkpoints` (`op=managed-connector-migration`, fingerprint `v2-cutoff`, excluded from the checkpoint purge). `orphanConnectorCheckpoints` keeps rows touched after the start, rows any registered source (archived included) can load, and rows referenced by a non-terminal request or a pending set; timestamps bind as text. `gbrain repair connector-checkpoints` (`src/core/repair/connector-checkpoints.ts`) and the `connector_checkpoints` doctor check reuse it with a 7-day floor. `connector-reset.ts` guards `gbrain sync --reset-checkpoint` to connector sources.
+- `src/core/persistence/graduation-target.ts` — engine graduation target side. `resolveTargetRoutes` reads the URL from `--url` or the `--url-env` variable and resolves the DDL route once (explicit `GBRAIN_DIRECT_DATABASE_URL`, else the Supabase direct derivation, else the main URL); `connectTargetEngines` hands that route to the connection manager as an explicit override, so no session-pooler fallback is chosen for the run. `targetIdentity` hashes host, port, database and user, never the password; `redactTargetUrl` is the only display form. `probeTarget` runs read-only probes in `BEGIN READ ONLY` sessions on both routes (server version, `vector` with halfvec, CREATE privilege, `session_replication_role` permission inside a savepoint, table ownership, seed-only emptiness, existing embedding columns); `targetProbeBlockers` and `assertTargetReachable` turn a probe into plan blockers and typed refusals. `crossCheckRoutes` proves both routes reach one database with a transaction-scoped advisory lock keyed by a fresh nonce, read back from `pg_locks` through the other route. Tests: `test/graduation-target.test.ts`.
+- `src/core/persistence/graduation-drain.ts` — engine graduation drain. `graduationBlockers` lists what keeps a brain from copying, each with its structured action: requests this host owns (drained), requests and host bindings owned by another host, recovering topology changes and effects, the writer admin lock, and OAuth clients bound to a missing source (an FK only Postgres enforces; never cleared silently, since unbinding widens access). `drainForGraduation` refuses up front on anything the drain cannot clear, then publishes this host's queued, running and recovering requests with a `requestsOnly` `PersistenceConsumer` bounded by the timeout and always runs its stop barrier before returning; `drainTimeoutError` is the `graduation_drain_timeout` refusal. `freezeSource` stops the resident consumer and sets the PGLite connection to read-only transactions; `withSourceWritable` runs one read-write transaction for custody writes. Tests: `test/graduation-drain.test.ts`.
+- `src/core/persistence/graduation-copy.ts` — engine graduation copier (in process). `copyTable` reads source rows through the digest's own plan (`digestPlan` with inventory transforms, `rowFilter`, `::text` values, COLLATE "C" keyset batches) and writes them in one target transaction per table that sets `gbrain.graduation_run`, bypasses user triggers (`session_replication_role = replica`, or DISABLE/ENABLE TRIGGER by name in the same transaction, never the `gbrain_graduation_fence` triggers), deletes the target's rows (seed rows included) and inserts byte-sized batches as one `$1::text::jsonb` array cast back per column type. The per-column contract (`columnContract`) refuses missing, retyped, target-only or differently generated columns outside the entry's `columnAllowlist`; generated columns are never inserted. Self-FKs take a second update pass under DISABLE TRIGGER. `copySequences` applies each source sequence's exact position, raised to the target column maximum. `deferIndexes`/`buildDeferredIndexes` drop and rebuild HNSW (through `buildDeferredAnnIndexes`) and GIN indexes, keeping the pending list in the target-owned `graduation.deferred_indexes` config row. Tests: `test/graduation-copy.test.ts`, `test/e2e/graduation-copy.test.ts`.
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index a13f08269b..c55b240a29 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -26,7 +26,7 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers
- `src/core/persistence/admission-retry.ts` — bounded retries for database-confirmed admission transaction aborts. Each retry reuses the UUID and normalized intent, rechecks guarded authority and reserves quota only on commitment. Standalone journal admission uses 100ms lock waits within the five-second retry budget to retain queue position behind short counter transactions; backoff occurs after rollback releases the connection so counter contention leaves pool capacity for reads. Ambiguous connection/commit errors are never classified as confirmed rollback. Real counter-lock, sustained-queue progress, read-capacity and after-insert rollback tests live in `test/persistence-journal.test.ts`. Withdrawal retries wrap its whole source-exclusive transaction with its existing lock policy; `admitWriteInTransaction` never backs off inside an existing unit of work. `test/persistence-withdrawal-retry.test.ts` verifies guard release, complete rollback and bounded contention.
-- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`.
+- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. #5984: `awaitWrite` (`waitForWrite` is its row-only form) receives a request this consumer publishes through the `onSettled` handoff with no request read, and skips polls while `holds(id)` says the consumer has it claimed; otherwise it polls the narrow `WRITE_PROGRESS_SQL` (first poll after min(200 ms, half the wait), then 50 ms backing off to 250 ms) and reads the full row once when terminal. Its own cancelled reads are not failures; a database read failure ends the wait as a classified `read_failed` (auth/permission failures at once), and a pending head with an intervention `blocked_reason` ends as `blocked`. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection from the ordinary pool, never the direct/session route (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. The rate-limited stderr line names the phase, the SQLSTATE or write-error code, a redacted one-line message of at most 200 characters, connection-wait evidence (`first_conn_ms`, or `checkout=not_observed conn_wait_ms`, attributed to the phase through AsyncLocalStorage over the engine's `onCheckout` seam) plus `loop_lag_ms`, a fix command and its docs anchor (`docs/ENGINES.md#persistence-consumer-log`); the trusted status `phase` carries the same fields. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. With `requestsOnly` (engine graduation's drain) the effect, projection, topology and maintenance workers never start; claim, recovery, expired-claim and publication run as usual and `stop()` remains the barrier. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-consumer-log.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`.
- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.
diff --git a/src/core/persistence/graduation-copy.ts b/src/core/persistence/graduation-copy.ts
index 4ba24b74f1..2a8f8d9813 100644
--- a/src/core/persistence/graduation-copy.ts
+++ b/src/core/persistence/graduation-copy.ts
@@ -28,8 +28,9 @@
*/
import type { BrainEngine } from '../engine.ts';
import { ANN_BUILD_MESSAGE, buildDeferredAnnIndexes, type DeferredAnnIndex } from '../embedding-ann-build.ts';
-import type { ColumnMeta, GraduationEngines, InventoryEntry, TriggerBypass } from './engine-graduation.types.ts';
+import type { ColumnMeta, GraduationEngines, Inventory, InventoryEntry, TriggerBypass } from './engine-graduation.types.ts';
import { digestPlan, quoteIdent, tableColumns, withDigestSession, type DigestPlan } from './graduation-digest.ts';
+import { fkClosure, GRADUATION_INVENTORY } from './graduation-inventory.ts';
import { graduationError } from './graduation-target.ts';
/** Target-owned config row holding the deferred index list; the config copy never deletes it. */
@@ -207,6 +208,39 @@ export async function copyTable(e: GraduationEngines, entry: InventoryEntry,
});
}
+/**
+ * Re-copies a table together with every table that references it
+ * transitively (its FK closure): all closure tables are emptied children
+ * first in one fenced transaction (a parent delete would otherwise cascade
+ * into, or be refused by, children still holding rows under DISABLE TRIGGER),
+ * then each carried closure table is copied parents first.
+ */
+export async function recopyClosure(e: GraduationEngines, relation: string,
+ opts: { bypass: TriggerBypass; runId: string; batchBytes?: number; inventory?: Inventory; onBatch?: (relation: string, rows: number) => void }): Promise<Record<string, number>> {
+ const inventory = opts.inventory ?? GRADUATION_INVENTORY;
+ const byName = new Map(inventory.entries.filter(x => x.class === 'carry' || x.class === 'rebind').map(x => [x.relation, x]));
+ const closure = (await fkClosure(e.target, relation)).filter(name => byName.has(name));
+ const disabled = new Map<string, Awaited<ReturnType<typeof userTriggers>>>();
+ if (opts.bypass === 'disable_trigger') for (const name of closure) disabled.set(name, await userTriggers(e.target, name, true));
+ await e.target.transaction(async tx => {
+ await setFence(tx, opts.runId);
+ if (opts.bypass === 'session_replication_role') await tx.executeRaw('SET LOCAL session_replication_role = replica');
+ for (const name of [...closure].reverse()) {
+ const table = quoteIdent(name);
+ const filter = [byName.get(name)!.rowFilter ? `(${byName.get(name)!.rowFilter})` : '', name === 'config' ? `key <> '${GRADUATION_DEFERRED_INDEXES_KEY}'` : ''].filter(Boolean);
+ for (const trigger of disabled.get(name) ?? []) await tx.executeRaw(`ALTER TABLE ${table} DISABLE TRIGGER ${trigger.ident}`);
+ await tx.executeRaw(`DELETE FROM ${table}${filter.length ? ` WHERE ${filter.join(' AND ')}` : ''}`);
+ for (const trigger of disabled.get(name) ?? []) await tx.executeRaw(`ALTER TABLE ${table} ${ENABLE_BY_MODE[trigger.enabled] ?? 'ENABLE TRIGGER'} ${trigger.ident}`);
+ }
+ });
+ const counts: Record<string, number> = {};
+ for (const name of closure) {
+ counts[name] = (await copyTable(e, byName.get(name)!, { bypass: opts.bypass, runId: opts.runId, batchBytes: opts.batchBytes,
+ onBatch: rows => opts.onBatch?.(name, rows) })).rows;
+ }
+ return counts;
+}
+
export interface SequencePosition { sequence: string; value: string; isCalled: boolean; raisedToColumnMax: boolean }
/**
diff --git a/test/graduation-copy.test.ts b/test/graduation-copy.test.ts
index da5d24d740..0eab157d30 100644
--- a/test/graduation-copy.test.ts
+++ b/test/graduation-copy.test.ts
@@ -21,10 +21,10 @@ import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../src/core/engine.ts';
import type { ColumnMeta, TriggerBypass } from '../src/core/persistence/engine-graduation.types.ts';
import {
- buildDeferredIndexes, columnContract, copySequences, copyTable, deferIndexes, detectTriggerBypass, GRADUATION_DEFERRED_INDEXES_KEY, reenableTriggers,
+ buildDeferredIndexes, columnContract, copySequences, copyTable, deferIndexes, detectTriggerBypass, GRADUATION_DEFERRED_INDEXES_KEY, recopyClosure, reenableTriggers,
} from '../src/core/persistence/graduation-copy.ts';
import { tableColumns } from '../src/core/persistence/graduation-digest.ts';
-import { GRADUATION_INVENTORY } from '../src/core/persistence/graduation-inventory.ts';
+import { fkClosure, 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';
@@ -146,6 +146,26 @@ for (const backend of testBackends()) {
}, 120_000);
}
+ for (const bypass of ['session_replication_role', 'disable_trigger'] as TriggerBypass[]) {
+ test(`${bypass}: a changed table is re-copied with its whole FK closure`, async () => {
+ const e = { source, target };
+ const first = await recopyClosure(e, 'sources', { bypass, runId: 'r' });
+ const closure = (await fkClosure(target, 'sources')).filter(name => name in first);
+ expect(Object.keys(first)).toEqual(closure);
+ expect(closure).toEqual(expect.arrayContaining(['sources', 'pages', 'facts']));
+ expect(closure.indexOf('sources')).toBeLessThan(closure.indexOf('pages'));
+ await source.transaction(async tx => {
+ await tx.executeRaw('SET LOCAL session_replication_role = replica');
+ await tx.executeRaw("UPDATE sources SET name = 'renamed again' WHERE id = 'history-a'");
+ await tx.executeRaw("INSERT INTO facts (id, fact, source, source_id, superseded_by) VALUES (9, 'later', 'test', 'history-a', 2)");
+ });
+ const second = await recopyClosure(e, 'sources', { bypass, runId: 'r' });
+ expect(second.facts).toBe(4);
+ expect(await digestMismatches(e, closure.map(name => entry(name)))).toEqual([]);
+ expect(await target.executeRaw("SELECT tgname FROM pg_trigger WHERE NOT tgisinternal AND tgenabled = 'D'")).toEqual([]);
+ }, 120_000);
+ }
+
test('a sequence behind the target column maximum is raised to it', async () => {
const e = { source, target };
await copyTable(e, entry('facts'), { bypass: 'session_replication_role', runId: 'r' });