Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(postgres): send the retired-marker reads and the default-source tier reads together (GBRA-133)
garrytan762ae71b9e4d
diff --git a/src/core/persistence/deactivation.ts b/src/core/persistence/deactivation.tsindex 2e724fca1f..466a715543 100644--- a/src/core/persistence/deactivation.ts+++ b/src/core/persistence/deactivation.ts@@ -320,9 +320,11 @@ export async function deactivatePersistence(engine: BrainEngine, opts: { dryRun?interface RetiredRecord { epochs: Set<number>; worktrees: Set<string>; roots: Set<string> }-async function readRetired(engine: BrainEngine, brainId: string): Promise<RetiredRecord> {- const rows = await engine.executeRaw<{ outcome: { brain_id?: string; retired_mode_epoch?: number; worktrees?: Array<{ id: string; roots: string[] }>; source_roots?: string[] } }>(+/** GBRA-133: `brain` is awaited only after the read is sent, so the caller's persistence_brain read shares its round trip. */+async function readRetired(engine: BrainEngine, brain: Promise<{ brain_id: string }>): Promise<RetiredRecord> {+ const rowsRead = engine.executeRaw<{ outcome: { brain_id?: string; retired_mode_epoch?: number; worktrees?: Array<{ id: string; roots: string[] }>; source_roots?: string[] } }>("SELECT outcome FROM persistence_topology_changes WHERE operation='writer_deactivate' AND state='committed'");+ const [rows, { brain_id: brainId }] = await Promise.all([rowsRead, brain]);const retired: RetiredRecord = { epochs: new Set(), worktrees: new Set(), roots: new Set() };const canonical = (path: string) => { try { return canonicalFilesystemPath(path); } catch { return path; } };for (const { outcome } of rows) {@@ -351,9 +353,9 @@ export async function cleanupRetiredManagedMarkers(engine: BrainEngine): Promiseconst report: LocalMarkerReport = { state: 'cleared', removed: [], pending: [] };const [present] = await engine.executeRaw<{ present: boolean }>("SELECT to_regclass('persistence_topology_changes') IS NOT NULL AS present");if (!present?.present) return report;- const brain = await readPersistenceBrain(engine);+ const brainRead = readPersistenceBrain(engine);+ const [brain, retired] = await Promise.all([brainRead, readRetired(engine, brainRead)]);const current = Number(brain.mode_epoch ?? 1);- const retired = await readRetired(engine, brain.brain_id);if (!retired.epochs.size && !retired.worktrees.size) return report;const activeRoots = new Set(brain.enabled ? (await engine.executeRaw<{ local_path: string }>('SELECT local_path FROM persistence_host_bindings')).map(row => { try { return canonicalFilesystemPath(row.local_path); } catch { return row.local_path; } }) : []);diff --git a/src/core/source-resolver.ts b/src/core/source-resolver.tsindex 75f584c364..fa42afd8b2 100644--- a/src/core/source-resolver.ts+++ b/src/core/source-resolver.ts@@ -200,6 +200,9 @@ async function resolveSourceIdChain(// gstack at ~/gstack + plans at ~/gstack/plans) pick the deepest.// #3880 active-over-archived tiering + parallel realpath both live in// the shared resolveRegisteredPathMatch helper.+ // GBRA-133: tier 5's config read is independent of the listing, so it is sent with it (unused when tier 4 wins).+ const defaultRead = engine.getConfig('sources.default');+ defaultRead.catch(() => {});const registered = seen.registered = await listRegisteredLocalPathSources(engine);const best = await resolveRegisteredPathMatch(registered, cwd);if (best) {@@ -214,7 +217,7 @@ async function resolveSourceIdChain(// Silent-fallback tier per codex P1-F: an invalid `sources.default` config// value (operator hand-edit gone wrong, legacy underscore id) falls through// to tier 6 rather than throwing. Resolver stays robust to bad config.- const globalDefault = await engine.getConfig('sources.default');+ const globalDefault = await defaultRead;if (globalDefault && isValidSourceId(globalDefault)) {await assertSourceExists(engine, globalDefault);return globalDefault;@@ -323,6 +326,11 @@ async function pickSoleNonDefaultSource(): Promise<string | null> {// archived column was added in v34 (v0.26.5). Older brains may not have// it — fall back to the un-archived query in that case via try/catch.+ // GBRA-133: the emptiness guard's read is sent with the listing (one round trip); it is used only for a sole candidate.+ const defaultPagesRead = engine.executeRaw<{ one: number }>(+ `SELECT 1 AS one FROM pages WHERE source_id = 'default' AND deleted_at IS NULL LIMIT 1`,+ );+ defaultPagesRead.catch(() => {});let rows: Array<{ id: string }>;try {rows = await engine.executeRaw<{ id: string }>(@@ -336,9 +344,7 @@ async function pickSoleNonDefaultSource(if (rows.length !== 1) return null;// #3070 emptiness guard: fire only when 'default' holds no active pages.try {- const defaultPages = await engine.executeRaw<{ one: number }>(- `SELECT 1 AS one FROM pages WHERE source_id = 'default' AND deleted_at IS NULL LIMIT 1`,- );+ const defaultPages = await defaultPagesRead;if (defaultPages.length > 0) {// The flip must not be silent: one stray page in 'default' reroutes// every bare command away from the sole side-source, and the userdiff --git a/test/read-waves-gbra133.test.ts b/test/read-waves-gbra133.test.tsindex 992003bbe8..6014fa48fb 100644--- a/test/read-waves-gbra133.test.ts+++ b/test/read-waves-gbra133.test.ts@@ -12,6 +12,7 @@ import { readCapacityForecast } from '../src/core/persistence/capacity-forecast.import { readExtractionLag } from '../src/core/extraction-lag.ts';import { getDefaultSourcePath } from '../src/core/source-resolver.ts';import { mergeDbPlaneConfig } from '../src/cli/db-plane-config.ts';+import { cleanupRetiredManagedMarkers } from '../src/core/persistence/deactivation.ts';import { freshBrainFactory, requestFixture } from './helpers/persistence-request-fixture.ts';import { testBackends } from './helpers/test-backends.ts';import { withEnv } from './helpers/with-env.ts';@@ -99,5 +100,18 @@ for (const kind of testBackends()) {expect(result).toBe(root);expect(statements.filter(s => s.startsWith('SELECT local_path FROM sources WHERE id'))).toEqual([]);});++ check('the default source resolution sends tier 5 with tier 4 and the emptiness guard with the sole-source listing: two waves', async engine => {+ await engine.executeRaw("INSERT INTO sources(id,name,local_path) VALUES('gbra133-sole','gbra133-sole','/nonexistent/gbra133-sole') ON CONFLICT(id) DO NOTHING");+ const { result, waves } = await recordWaves(engine, () => getDefaultSourcePath(engine, tmpdir()));+ expect(waves).toBeLessThanOrEqual(2);+ expect(result).toBe('/nonexistent/gbra133-sole');+ });++ check('the retired-marker cleanup reads the persistence row and the deactivations together', async engine => {+ const { result, waves } = await recordWaves(engine, () => cleanupRetiredManagedMarkers(engine));+ expect(waves).toBeLessThanOrEqual(2);+ expect(result).toEqual({ state: 'cleared', removed: [], pending: [] });+ });});}