Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Wave B PR 4 interface round 2: inventories, embed lease vs writer admin state, v265 VALIDATE bounds

garrytanb724c90d5c67
diff --git a/src/core/migrate.ts b/src/core/migrate.ts
index 1588896d07..d6f583eee0 100644
--- a/src/core/migrate.ts
+++ b/src/core/migrate.ts
@@ -1,10 +1,10 @@
import type { BrainEngine } from './engine.ts';
import type { Migration } from './schema-migrations/types.ts';
import { isLockTimeoutError } from './retry-matcher.ts';
-import { resolveSchemaLockTimeoutMs, schemaLockBlockedError, withSchemaLockTimeout } from './postgres-engine/schema-lock-timeout.ts';
+import { resolveSchemaLockTimeoutMs, schemaLockBlockedError } from './postgres-engine/schema-lock-timeout.ts';
import { MIGRATIONS } from './schema-migrations/registry.generated.ts';
import { hasPendingMigrations } from './migrate-pending.ts';
-import { setQuietMigrationNotices } from './schema-migrations/helpers.ts';
+import { runMigrationStatement, setQuietMigrationNotices } from './schema-migrations/helpers.ts';
import { MIGRATION_PRELUDES, runMigrationPrelude } from './migration-preludes.ts';
import { clearMigrationTimeout, migrationStatementTimeoutMs, recordMigrationTimeout } from './migration-timeout.ts';
// runMigrations executes while an initialized engine is live. Keep its helper
@@ -232,35 +232,7 @@ export async function runMigrationSQL(
throw error;
}
} else {
- // Postgres + transaction:false → can't use SET LOCAL (needs a txn),
- // can't use plain SET on the pooled connection (leaks to other
- // queries). Instead: reserve a dedicated backend, set session-level
- // statement_timeout on just that connection, run the DDL there.
- //
- // On Supabase (both PgBouncer 6543 and direct 5432) a server-level
- // statement_timeout of ~2 min is enforced. Without this override a
- // CREATE INDEX CONCURRENTLY on a large table (e.g. 500K pages) hits
- // the timeout and aborts. SET on the reserved connection cleanly
- // overrides because the GUC scope is connection-local (session-scope
- // is fine when nobody else uses the connection).
- //
- // The reserved-connection primitive is new in PR #356. See
- // BrainEngine.withReservedConnection.
- await engine.withReservedConnection(async (conn) => {
- try {
- await conn.executeRaw(`SET statement_timeout = '${migrationStatementTimeoutMs()}'`);
- } catch {
- // Non-fatal: some managed Postgres may restrict this GUC.
- // Falling through means the DDL runs with the server default.
- }
- // #5227 (W14 P1.6): no transaction here, so the lock bound is session-level on this reserved backend and restored after.
- // #6543 (A4): the raised statement_timeout is restored too, so the connection does not carry this migration's budget back to the pool.
- try {
- await withSchemaLockTimeout({ unsafe: (query: string) => conn.executeRaw(query) }, () => conn.executeRaw(sql), { step: `migration v${m.version}` });
- } finally {
- await conn.executeRaw('RESET statement_timeout').catch(() => {});
- }
- }, { selfContained: true });
+ await runMigrationStatement(engine, m.version, sql);
}
}
diff --git a/src/core/page-embedding-lease.ts b/src/core/page-embedding-lease.ts
index a584c3d003..55f95a0850 100644
--- a/src/core/page-embedding-lease.ts
+++ b/src/core/page-embedding-lease.ts
@@ -27,8 +27,11 @@ const LEASE_WAIT_MAX_MS = 1_000;
/** Test seam: called each time a path finds a page's lease held by another path, before it waits. */
export const pageEmbeddingLeaseProbe: { contended?: (pageId: number) => void } = {};
+/** Every page embedding lease id starts with this; the writer admin fingerprint leaves these rows out (admin-intent.ts). */
+export const PAGE_EMBEDDING_LEASE_PREFIX = 'embed-page:';
+
export function pageEmbeddingLeaseId(pageId: number): string {
- return `embed-page:${pageId}`;
+ return `${PAGE_EMBEDDING_LEASE_PREFIX}${pageId}`;
}
function pause(ms: number, signal?: AbortSignal): Promise<void> {
diff --git a/src/core/persistence/admin-intent.ts b/src/core/persistence/admin-intent.ts
index f02f299e8d..3a07a6e0d4 100644
--- a/src/core/persistence/admin-intent.ts
+++ b/src/core/persistence/admin-intent.ts
@@ -1,9 +1,11 @@
import type { SqlEngine } from './model.ts';
import { OperationError } from '../ops/contract.ts';
import { sha256 } from './digest.ts';
+import { PAGE_EMBEDDING_LEASE_PREFIX } from '../page-embedding-lease.ts';
export const WRITER_INSPECTION_HINT = 'Inspect gbrain sources writer status --json on the selected brain host first to identify the designated owner and any recovery. Routine repair must not claim, activate, or transfer ownership. Ask the operator to review docs/architecture/topologies.md before a deliberate topology change.';
+/** A page embedding lease is per-page vector work, not writer topology, so it never invalidates a reviewed state. */
export async function writerAdminState(engine: SqlEngine): Promise<string> {
const [row] = await engine.executeRaw<{ state: string }>(`SELECT jsonb_build_object(
'brain', (SELECT jsonb_build_object('id',brain_id,'enabled',enabled,
@@ -15,8 +17,9 @@ export async function writerAdminState(engine: SqlEngine): Promise<string> {
'worktrees', (SELECT jsonb_agg(jsonb_build_array(id,owner_host_id,owner_epoch::text,topology_generation::text,state,manifest) ORDER BY id) FROM persistence_worktrees),
'bindings', (SELECT jsonb_agg(jsonb_build_array(source_id,source_incarnation,worktree_id,relative_path,topology_generation::text) ORDER BY source_id) FROM persistence_source_bindings),
'hosts', (SELECT jsonb_agg(jsonb_build_array(worktree_id,host_id,local_path,coordination_path,git_durability) ORDER BY worktree_id,host_id) FROM persistence_host_bindings),
- 'legacy_locks', (SELECT jsonb_agg(jsonb_build_array(id,holder_pid,holder_host,acquisition_token,acquired_at) ORDER BY id) FROM gbrain_cycle_locks)
- )::text AS state`);
+ 'legacy_locks', (SELECT jsonb_agg(jsonb_build_array(id,holder_pid,holder_host,acquisition_token,acquired_at) ORDER BY id) FROM gbrain_cycle_locks
+ WHERE NOT starts_with(id, $1))
+ )::text AS state`, [PAGE_EMBEDDING_LEASE_PREFIX]);
return sha256(row.state);
}
diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.ts
index 02383b0f2a..9bf9771fe9 100644
--- a/src/core/persistence/graduation-inventory.ts
+++ b/src/core/persistence/graduation-inventory.ts
@@ -120,6 +120,7 @@ export const GRADUATION_INVENTORY: Inventory = {
carry('page_projection_jobs', 'operational', 'Pending page projection work (derived side table, verified equal).'),
carry('page_purges', 'user_data', 'Text-free page purge tombstones (#5575); dropping them would let purged pages re-import.'),
carry('page_retrievals', 'operational', 'Retrieval telemetry: when a user-facing read last surfaced each page (stale-page bias, volunteer usage stats).'),
+ carry('page_segment_derivations', 'operational', 'Per-segment derivation watermarks (links, mentions, timeline, fences, conversation facts, atoms, backstop, synopsis) keyed by manifest occurrence; without them the next pass re-derives every segment, including paid conversation-facts windows.'),
carry('page_segment_texts', 'user_data', 'Segment texts of segmented page bodies, stored once per source; without them a large page has no body.'),
carry('page_versions', 'user_data', 'Page revision history with attribution.'),
carry('page_write_guards', 'user_data', 'Page write guards per source incarnation and slug.'),
diff --git a/src/core/schema-migrations/helpers.ts b/src/core/schema-migrations/helpers.ts
index f748f45a0f..64afa59e86 100644
--- a/src/core/schema-migrations/helpers.ts
+++ b/src/core/schema-migrations/helpers.ts
@@ -7,6 +7,8 @@
*/
import type { BrainEngine } from '../engine.ts';
import { analyzeDeferred, lockTableForAnalyze } from '../analyze-lock.ts';
+import { migrationStatementTimeoutMs } from '../migration-timeout.ts';
+import { withSchemaLockTimeout } from '../postgres-engine/schema-lock-timeout.ts';
/**
* When true, per-migration explanatory notices (e.g. the v123/v124 "here is
@@ -70,6 +72,37 @@ export async function dropInvalidConcurrentIndex(
return isInvalid;
}
+/**
+ * Runs one migration statement outside a transaction: a `transaction: false` migration's SQL (runMigrationSQL), or a
+ * statement its handler runs on its own, such as a VALIDATE CONSTRAINT that must not hold the ALTER's lock. PGLite
+ * runs it as is.
+ *
+ * Postgres can't use SET LOCAL without a transaction or a plain SET on the
+ * pooled connection (it leaks to other queries), so this reserves a dedicated
+ * backend and sets session-level statement_timeout on just that connection.
+ * On Supabase (both PgBouncer 6543 and direct 5432) a server-level
+ * statement_timeout of ~2 min is enforced; without this override a CREATE
+ * INDEX CONCURRENTLY or a VALIDATE on a large table hits it and aborts.
+ * #5227 (W14 P1.6): the lock wait is bounded session-level on the same backend
+ * and restored after. #6543 (A4): the raised statement_timeout is restored too,
+ * so the connection does not carry the migration's budget back to the pool.
+ */
+export async function runMigrationStatement(engine: BrainEngine, version: number, sql: string): Promise<void> {
+ if (engine.kind !== 'postgres') { await engine.runMigration(version, sql); return; }
+ await engine.withReservedConnection(async (conn) => {
+ try {
+ await conn.executeRaw(`SET statement_timeout = '${migrationStatementTimeoutMs()}'`);
+ } catch {
+ // Non-fatal: some managed Postgres may restrict this GUC; the statement then runs with the server default.
+ }
+ try {
+ await withSchemaLockTimeout({ unsafe: (query: string) => conn.executeRaw(query) }, () => conn.executeRaw(sql), { step: `migration v${version}` });
+ } finally {
+ await conn.executeRaw('RESET statement_timeout').catch(() => {});
+ }
+ }, { selfContained: true });
+}
+
export type OnlineIndexOutcome = 'present' | 'created' | 'rebuilt' | 'building';
/**
diff --git a/src/core/schema-migrations/v265-segment-derivations.ts b/src/core/schema-migrations/v265-segment-derivations.ts
index d4031e1e20..49a237c944 100644
--- a/src/core/schema-migrations/v265-segment-derivations.ts
+++ b/src/core/schema-migrations/v265-segment-derivations.ts
@@ -1,5 +1,6 @@
import type { Migration } from './types.ts';
import { PAGE_SEGMENT_DERIVATIONS_SQL } from '../page-body/schema.ts';
+import { runMigrationStatement } from './helpers.ts';
// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
@@ -21,7 +22,8 @@ import { PAGE_SEGMENT_DERIVATIONS_SQL } from '../page-body/schema.ts';
// Nothing to backfill. facts_source_window_chk keeps a malformed anchor (a
// double-encoded JSON string included) out; it is added NOT VALID and
// validated in its own statement, so no facts scan runs under the exclusive
-// lock of the ALTER. Per-page window reads use the existing
+// lock of the ALTER; that statement gets the same statement budget and bounded
+// lock wait as the migration's SQL (runMigrationStatement). Per-page window reads use the existing
// (source_id, source_markdown_slug, row_num) index.
export const v265: Migration = {
version: 265,
@@ -43,6 +45,6 @@ export const v265: Migration = {
END $do$;
`,
handler: async engine => {
- await engine.runMigration(265, 'ALTER TABLE facts VALIDATE CONSTRAINT facts_source_window_chk;');
+ await runMigrationStatement(engine, 265, 'ALTER TABLE facts VALIDATE CONSTRAINT facts_source_window_chk;');
},
};
diff --git a/test/fixtures/goldens/rls-scope-inventory.json b/test/fixtures/goldens/rls-scope-inventory.json
index c4452a8752..c0656697f4 100644
--- a/test/fixtures/goldens/rls-scope-inventory.json
+++ b/test/fixtures/goldens/rls-scope-inventory.json
@@ -3734,6 +3734,7 @@
"readManifest": "none",
"readPageSnapshot": "direct",
"readPageSnapshotsBatch": "direct",
+ "readSegmentDerivations": "none",
"readSegmentTexts": "none",
"reconnect": "none",
"refreshPageBody": "none",
@@ -3753,6 +3754,7 @@
"resolveSlugsByPaths": "none",
"resolveTake": "none",
"restorePage": "none",
+ "retireSegmentDerivations": "none",
"revertToVersion": "none",
"rewriteLinks": "none",
"rlsScopeBindingEnabled": "none",
@@ -3798,6 +3800,7 @@
"upsertChunks": "via:_upsertChunksOnce",
"upsertEventProjection": "none",
"upsertFile": "none",
+ "upsertSegmentDerivations": "none",
"vectorIterativeScanSupported": "none",
"withReservedConnection": "none",
"withScopedReadTransaction": "none",
diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.ts
index 0f1cfbc62c..ec8367079b 100644
--- a/test/graduation-inventory.test.ts
+++ b/test/graduation-inventory.test.ts
@@ -60,7 +60,7 @@ describe('graduation inventory', () => {
expect(new Set(names).size).toBe(names.length);
const counts: Record<string, number> = {};
for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;
- expect(counts).toEqual({ carry: 136, rebind: 2, rebuild: 3, discard: 9, schema_owned: 4 });
+ expect(counts).toEqual({ carry: 137, rebind: 2, rebuild: 3, discard: 9, schema_owned: 4 });
for (const e of GRADUATION_INVENTORY.entries) {
expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres })
.toEqual({ relation: e.relation, reason: true, present: true });
diff --git a/test/migrate.test.ts b/test/migrate.test.ts
index 87b18ee563..937105705d 100644
--- a/test/migrate.test.ts
+++ b/test/migrate.test.ts
@@ -1454,8 +1454,15 @@ describe('PR #356 — non-transactional DDL runs via reserved connection', () =>
const runFnIdx = source.indexOf('async function runMigrationSQL(');
expect(runFnIdx).toBeGreaterThan(-1);
const fnBody = source.slice(runFnIdx, runFnIdx + 2500);
- expect(fnBody).toContain('withReservedConnection');
- expect(fnBody).toContain("SET statement_timeout = '${migrationStatementTimeoutMs()}'");
+ // The else-branch runs through schema-migrations/helpers.ts runMigrationStatement, which a handler's own
+ // statement (v265's VALIDATE CONSTRAINT) shares.
+ expect(fnBody).toContain('await runMigrationStatement(engine, m.version, sql);');
+ const helpers = surfaceFileSource('migrate', 'src/core/schema-migrations/helpers.ts');
+ const helperIdx = helpers.indexOf('export async function runMigrationStatement(');
+ expect(helperIdx).toBeGreaterThan(-1);
+ const helperBody = helpers.slice(helperIdx, helperIdx + 1500);
+ expect(helperBody).toContain('withReservedConnection');
+ expect(helperBody).toContain("SET statement_timeout = '${migrationStatementTimeoutMs()}'");
expect(migrationStatementTimeoutMs()).toBe(600_000);
});
});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 530f912ff4..5305b901e4 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -444,9 +444,11 @@ test/trust-held-removals.test.ts
test/trust-owner-actions.test.ts
test/unbound-source-6536.test.ts
test/unindexed-files.test.ts
+test/v265-validate-timeouts.test.ts
test/vector-manifest-probe-bound.test.ts
test/withdrawal-overlay-concurrency.test.ts
test/withdrawal-publication-file.test.ts
test/worktree-refresh-recovery-row-gbra130.test.ts
+test/writer-admin-state-embed-lease.test.ts
test/writer-status-movement-not-read-gbra130.test.ts
test/writer-status-owner-backends.test.ts
diff --git a/test/v265-validate-timeouts.test.ts b/test/v265-validate-timeouts.test.ts
new file mode 100644
index 0000000000..241d2687b0
--- /dev/null
+++ b/test/v265-validate-timeouts.test.ts
@@ -0,0 +1,68 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import postgres from '#postgres';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { setMigrationStatementTimeoutMs } from '../src/core/migration-timeout.ts';
+import { v265 } from '../src/core/schema-migrations/v265-segment-derivations.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+// v265 adds facts_source_window_chk NOT VALID in its SQL and validates it in the handler's own statement. That
+// statement gets the migration's bounds: the schema lock wait (GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS) and the
+// migration statement budget, on a dedicated backend. Before, it ran on the pool with neither, so a session
+// holding facts waited the VALIDATE out (forever, or until a server statement_timeout).
+for (const kind of testBackends()) describe(`v265 facts_source_window_chk validation (${kind})`, () => {
+ let engine: BrainEngine, databaseUrl = '', close: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, databaseUrl, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
+ }, 120_000);
+ afterAll(async () => { if (close) await close(); else await engine.disconnect(); });
+ const validated = async () => (await engine.executeRaw<{ convalidated: boolean }>(
+ `SELECT convalidated FROM pg_constraint WHERE conname = 'facts_source_window_chk' AND conrelid = 'facts'::regclass`)).map(row => row.convalidated);
+ beforeEach(async () => {
+ await engine.executeRaw('ALTER TABLE facts DROP CONSTRAINT facts_source_window_chk');
+ await engine.runMigration(265, v265.sql);
+ expect(await validated()).toEqual([false]);
+ });
+
+ test('the handler validates the constraint', async () => {
+ await v265.handler!(engine);
+ expect(await validated()).toEqual([true]);
+ });
+
+ if (kind !== 'postgres') return;
+ /** Holds facts in SHARE mode (conflicts with VALIDATE's SHARE UPDATE EXCLUSIVE) on its own session until `release`. */
+ async function holdFacts() {
+ const sql = postgres(databaseUrl, { max: 1, prepare: false, onnotice: () => {} });
+ const conn = await sql.reserve();
+ await conn.unsafe('BEGIN');
+ await conn.unsafe('LOCK TABLE facts IN SHARE MODE');
+ const release = async () => { await conn.unsafe('COMMIT'); conn.release(); await sql.end(); };
+ const timer = setTimeout(() => { void release(); }, 3_000);
+ return async () => { clearTimeout(timer); await release().catch(() => {}); };
+ }
+
+ test('a session holding facts makes the VALIDATE refuse at the schema lock bound, and a rerun validates', async () => {
+ const release = await holdFacts();
+ try {
+ await withEnv({ GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS: '0.2' }, () =>
+ expect(v265.handler!(engine)).rejects.toMatchObject({ code: 'schema_lock_blocked' }));
+ expect(await validated()).toEqual([false]);
+ } finally { await release(); }
+ await v265.handler!(engine);
+ expect(await validated()).toEqual([true]);
+ }, 30_000);
+
+ test('the VALIDATE runs under the migration statement budget', async () => {
+ const release = await holdFacts();
+ setMigrationStatementTimeoutMs(300);
+ try {
+ await expect(v265.handler!(engine)).rejects.toMatchObject({ code: '57014' });
+ expect(await validated()).toEqual([false]);
+ } finally { setMigrationStatementTimeoutMs(null); await release(); }
+ await v265.handler!(engine);
+ expect(await validated()).toEqual([true]);
+ }, 30_000);
+});
diff --git a/test/writer-admin-state-embed-lease.test.ts b/test/writer-admin-state-embed-lease.test.ts
new file mode 100644
index 0000000000..5ee5b7aebe
--- /dev/null
+++ b/test/writer-admin-state-embed-lease.test.ts
@@ -0,0 +1,40 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { tryAcquireDbLock } from '../src/core/db-lock.ts';
+import { acquirePageEmbeddingLease } from '../src/core/page-embedding-lease.ts';
+import { assertWriterAdminState, writerAdminState } from '../src/core/persistence/admin-intent.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+for (const kind of testBackends()) describe(`writer admin state and page embedding leases (${kind})`, () => {
+ let engine: BrainEngine, close: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
+ }, 120_000);
+ afterAll(async () => { if (close) await close(); else await engine.disconnect(); });
+ const lockIds = async () => (await engine.executeRaw<{ id: string }>('SELECT id FROM gbrain_cycle_locks ORDER BY id')).map(row => row.id);
+
+ test('an embedding lease taken and released between review and apply leaves the reviewed state valid', async () => {
+ const reviewed = await writerAdminState(engine);
+ {
+ await using _lease = await acquirePageEmbeddingLease(engine, 1);
+ expect(await lockIds()).toEqual(['embed-page:1']);
+ expect(await writerAdminState(engine)).toBe(reviewed);
+ }
+ expect(await lockIds()).toEqual([]);
+ await assertWriterAdminState(engine, reviewed, false);
+ });
+
+ test('a writer lock row taken after review still refuses the reviewed state', async () => {
+ const reviewed = await writerAdminState(engine);
+ const lock = await tryAcquireDbLock(engine, 'gbrain-sync');
+ expect(lock).not.toBeNull();
+ try {
+ expect(await lockIds()).toEqual(['gbrain-sync']);
+ await expect(assertWriterAdminState(engine, reviewed, false)).rejects.toMatchObject({ code: 'writer_admin_state_changed' });
+ } finally { await lock!.release(); }
+ await assertWriterAdminState(engine, reviewed, false);
+ });
+});