Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(postgres): issue the capacity forecast, extraction-lag and connect-time config reads together; reuse the source listing for the default path (GBRA-133)

garrytan98c175f6cd66
diff --git a/src/cli/db-plane-config.ts b/src/cli/db-plane-config.ts
new file mode 100644
index 0000000000..38e850610f
--- /dev/null
+++ b/src/cli/db-plane-config.ts
@@ -0,0 +1,60 @@
+/**
+ * The connect-time re-merge of DB-plane config into the selected config and the AI gateway, run by the CLI's
+ * completeEngineStartup (main.ts) after migrations. GBRA-133: one config snapshot serves the merge and the gateway
+ * re-stamp, which each read the whole config table.
+ */
+import { buildGatewayConfig } from '../core/ai/build-gateway-config.ts';
+import { configureGateway, reconfigureGatewayWithEngine } from '../core/ai/gateway.ts';
+import { loadConfigWithEngine, type GBrainConfig } from '../core/config.ts';
+import { withRequestConfigSnapshot } from '../core/config-snapshot.ts';
+import type { BrainEngine } from '../core/engine.ts';
+
+export async function mergeDbPlaneConfig(engine: BrainEngine, config: GBrainConfig, mergedByEngine: WeakMap<BrainEngine, GBrainConfig>): Promise<void> {
+ // v0.27.1 (F3 fix): re-merge DB-plane config now that the engine is up.
+ // Flags like `embedding_multimodal` are user-mutable via `gbrain config set`
+ // (DB plane) and need to flow into the gateway after connect. Schema-sizing
+ // fields (embedding_dimensions etc.) keep their pre-connect file/env values
+ // — those drove initSchema and the merged config respects file/env first.
+ try {
+ // GBRA-133: the DB-plane merge and the gateway re-stamp each read the whole config table; one snapshot serves both.
+ await withRequestConfigSnapshot(engine, async () => {
+ const merged = await loadConfigWithEngine(engine, config);
+ if (merged) {
+ // #1475 — hand the merged config to makeContext instead of letting it
+ // re-derive one. See MERGED_CONFIG_BY_ENGINE (main.ts): the op-side gates read
+ // ctx.config, and re-running the merge there would double this
+ // function's per-key config reads on every command (the cost #3980 is
+ // about). Keyed on the engine so a mounted brain cannot be served the
+ // host brain's merge.
+ mergedByEngine.set(engine, merged);
+ // Stash gate flags on process.env for downstream readers (import-file.ts
+ // dispatches on GBRAIN_EMBEDDING_MULTIMODAL, gates OCR on GBRAIN_EMBEDDING_IMAGE_OCR).
+ // The OCR *model* reaches the gateway via the re-configure below (#4107); its
+ // env stash stays so subprocesses re-fold it through loadConfig's env merge.
+ if (merged.embedding_multimodal !== undefined) {
+ process.env.GBRAIN_EMBEDDING_MULTIMODAL = String(merged.embedding_multimodal);
+ }
+ if (merged.embedding_image_ocr !== undefined) {
+ process.env.GBRAIN_EMBEDDING_IMAGE_OCR = String(merged.embedding_image_ocr);
+ }
+ if (merged.embedding_image_ocr_model !== undefined) {
+ process.env.GBRAIN_EMBEDDING_IMAGE_OCR_MODEL = merged.embedding_image_ocr_model;
+ }
+ // Always re-configure with merged values when DB merge succeeded. The
+ // trigger used to be field-name-gated (only when embedding_multimodal_model
+ // was set); that coupled the gate to the field set and would silently
+ // miss future DB-mutable gateway fields. One extra cache+shrinkState
+ // clear per startup is microseconds, no hot path.
+ configureGateway(buildGatewayConfig(merged));
+ }
+ // v0.31.12: re-resolve gateway defaults through resolveModel so
+ // `models.tier.*` and `models.default` overrides apply to expansion +
+ // chat. Per Codex F3 — configureGateway is sync; this is the async
+ // re-stamp seam after engine.connect() makes config reads possible.
+ await reconfigureGatewayWithEngine(engine);
+ });
+ } catch {
+ // Non-fatal. Pre-v39 brains may not have a usable config table yet.
+ }
+}
+
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 787d104b7b..0c2e4b51e2 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -2872,50 +2872,7 @@ async function completeEngineStartup(engine: BrainEngine): Promise<void> {
// #5628: drop this host's markers of a retired managed epoch before any filesystem guard check.
try { await (await import('../core/persistence/deactivation.ts')).cleanupRetiredManagedMarkers(engine); } catch { /* status reports pending markers */ }
- // v0.27.1 (F3 fix): re-merge DB-plane config now that the engine is up.
- // Flags like `embedding_multimodal` are user-mutable via `gbrain config set`
- // (DB plane) and need to flow into the gateway after connect. Schema-sizing
- // fields (embedding_dimensions etc.) keep their pre-connect file/env values
- // — those drove initSchema and the merged config respects file/env first.
- try {
- const merged = await loadConfigWithEngine(engine, config);
- if (merged) {
- // #1475 — hand the merged config to makeContext instead of letting it
- // re-derive one. See MERGED_CONFIG_BY_ENGINE: the op-side gates read
- // ctx.config, and re-running the merge there would double this
- // function's per-key config reads on every command (the cost #3980 is
- // about). Keyed on the engine so a mounted brain cannot be served the
- // host brain's merge.
- MERGED_CONFIG_BY_ENGINE.set(engine, merged);
- // Stash gate flags on process.env for downstream readers (import-file.ts
- // dispatches on GBRAIN_EMBEDDING_MULTIMODAL, gates OCR on GBRAIN_EMBEDDING_IMAGE_OCR).
- // The OCR *model* reaches the gateway via the re-configure below (#4107); its
- // env stash stays so subprocesses re-fold it through loadConfig's env merge.
- if (merged.embedding_multimodal !== undefined) {
- process.env.GBRAIN_EMBEDDING_MULTIMODAL = String(merged.embedding_multimodal);
- }
- if (merged.embedding_image_ocr !== undefined) {
- process.env.GBRAIN_EMBEDDING_IMAGE_OCR = String(merged.embedding_image_ocr);
- }
- if (merged.embedding_image_ocr_model !== undefined) {
- process.env.GBRAIN_EMBEDDING_IMAGE_OCR_MODEL = merged.embedding_image_ocr_model;
- }
- // Always re-configure with merged values when DB merge succeeded. The
- // trigger used to be field-name-gated (only when embedding_multimodal_model
- // was set); that coupled the gate to the field set and would silently
- // miss future DB-mutable gateway fields. One extra cache+shrinkState
- // clear per startup is microseconds, no hot path.
- (await import('../core/ai/gateway.ts')).configureGateway(buildGatewayConfig(merged));
- }
- // v0.31.12: re-resolve gateway defaults through resolveModel so
- // `models.tier.*` and `models.default` overrides apply to expansion +
- // chat. Per Codex F3 — configureGateway is sync; this is the async
- // re-stamp seam after engine.connect() makes config reads possible.
- const { reconfigureGatewayWithEngine } = await import('../core/ai/gateway.ts');
- await reconfigureGatewayWithEngine(engine);
- } catch {
- // Non-fatal. Pre-v39 brains may not have a usable config table yet.
- }
+ await (await import('./db-plane-config.ts')).mergeDbPlaneConfig(engine, config, MERGED_CONFIG_BY_ENGINE);
// The one-time behavior-change disclosure on the CLI channel (stderr). `serve`
// delivers it per MCP channel; `doctor` reads it without marking it shown.
diff --git a/src/core/extraction-lag.ts b/src/core/extraction-lag.ts
index b4732a972c..337d165485 100644
--- a/src/core/extraction-lag.ts
+++ b/src/core/extraction-lag.ts
@@ -7,6 +7,7 @@
* cron default) plus the decision between both routes, with an estimate stated at its basis.
*/
import type { BrainEngine } from './engine.ts';
+import { withRequestConfigSnapshot } from './config-snapshot.ts';
import { AGENT_TOOL_LIMIT_MS, type Action, type Decision } from './agent-output.ts';
import { cliRouting, pinRouting, type FixRouting } from './fix-routing.ts';
import { extractionLagStatement, heldLinkExtractionStatement } from './engine-sql/pages.ts';
@@ -42,7 +43,20 @@ export interface ExtractionLag {
mention_last_pass_at: string | null;
}
+/**
+ * GBRA-133: one config snapshot answers the watermark, the mention policy and the schema pack (one statement instead
+ * of five), and the lag count and the mention preview are issued together, so the whole read is two round trips.
+ */
export async function readExtractionLag(engine: BrainEngine, opts: { sourceId?: string; timeoutMs?: number } = {}): Promise<ExtractionLag> {
+ return withRequestConfigSnapshot(engine, async () => {
+ const [row, mention] = await Promise.all([readLagRow(engine, opts),
+ readMentionPolicy(engine).then(policy => policy.enabled ? previewMentionPass(engine, opts.sourceId) : null)]);
+ return { total: Number(row?.total ?? 0), actionable: Number(row?.stale ?? 0), attendance_blocked: Number(row?.attendance_blocked ?? 0), held: Number(row?.held ?? 0),
+ mention_due: mention ? mention.due : null, mention_last_pass_at: mention?.last_pass_at ?? null };
+ });
+}
+
+async function readLagRow(engine: BrainEngine, opts: { sourceId?: string; timeoutMs?: number }) {
const versionTs = await effectiveLinkExtractorWatermark(engine);
const read = async (attendance: boolean, held: boolean) => {
const { text, params } = extractionLagStatement({ sourceId: opts.sourceId, versionTs, attendance, held });
@@ -57,9 +71,7 @@ export async function readExtractionLag(engine: BrainEngine, opts: { sourceId?:
else if (isMissingSchemaObject(e, 'column', 'links_attendance_blocked_revision')) row = await read(false, false);
else throw e;
}
- const mention = (await readMentionPolicy(engine)).enabled ? await previewMentionPass(engine, opts.sourceId) : null;
- return { total: Number(row?.total ?? 0), actionable: Number(row?.stale ?? 0), attendance_blocked: Number(row?.attendance_blocked ?? 0), held: Number(row?.held ?? 0),
- mention_due: mention ? mention.due : null, mention_last_pass_at: mention?.last_pass_at ?? null };
+ return row;
}
/**
diff --git a/src/core/mentions/stale.ts b/src/core/mentions/stale.ts
index c152beee9f..634b88c78b 100644
--- a/src/core/mentions/stale.ts
+++ b/src/core/mentions/stale.ts
@@ -20,15 +20,19 @@ export interface MentionPreview {
* doctor and post-upgrade.
*/
export async function previewMentionPass(engine: BrainEngine, sourceId?: string): Promise<MentionPreview> {
- const policy = await readMentionPolicy(engine);
- const [row] = await engine.executeRaw<{ last: string | null }>(
- `SELECT to_char(max(last_pass_at) AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS last FROM mention_index_status
- WHERE ($1::text IS NULL OR source_id = $1)`, [sourceId ?? null]);
- let due = 0;
- if (policy.enabled) {
- const sources = sourceId ? [sourceId] : (await engine.executeRaw<{ id: string }>('SELECT id FROM sources ORDER BY id')).map(r => r.id);
- for (const id of sources) due += await countIndexDuePages(engine, id, linkableTypesFor(await loadSourcePack(engine, id), policy));
- }
+ // GBRA-133: the newest pass time does not depend on the policy or the due counts, so it is issued with them.
+ const [[row], { policy, due }] = await Promise.all([
+ engine.executeRaw<{ last: string | null }>(
+ `SELECT to_char(max(last_pass_at) AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS last FROM mention_index_status
+ WHERE ($1::text IS NULL OR source_id = $1)`, [sourceId ?? null]),
+ readMentionPolicy(engine).then(async policy => {
+ let due = 0;
+ if (policy.enabled) {
+ const sources = sourceId ? [sourceId] : (await engine.executeRaw<{ id: string }>('SELECT id FROM sources ORDER BY id')).map(r => r.id);
+ for (const id of sources) due += await countIndexDuePages(engine, id, linkableTypesFor(await loadSourcePack(engine, id), policy));
+ }
+ return { policy, due };
+ })]);
return { due, last_pass_at: row?.last ?? null, enabled: policy.enabled };
}
diff --git a/src/core/persistence/capacity-forecast.ts b/src/core/persistence/capacity-forecast.ts
index 96a1b37664..5b65b6487f 100644
--- a/src/core/persistence/capacity-forecast.ts
+++ b/src/core/persistence/capacity-forecast.ts
@@ -117,28 +117,23 @@ export async function readCapacityThresholds(engine: SqlEngine): Promise<{ warnD
}
export async function readCapacityForecast(engine: SqlEngine & { kind?: string }, opts: { limits?: JournalLimits; light?: boolean } = {}): Promise<CapacityForecast> {
- const limits = opts.limits ?? await readJournalLimits(engine);
- const [{ warnDays, failDays }, retention] = await Promise.all([readCapacityThresholds(engine),
- readReceiptRetentionDays(engine).catch(() => DEFAULT_RECEIPT_RETENTION_DAYS)]);
- const counters = await engine.executeRaw<{ key: string; lifetime_ids: string; terminal_bytes: string }>(
+ // Every read below is independent of the others (the principal walks need only the counters), so they are issued together:
+ // one round trip for the lot instead of one each (GBRA-133).
+ const counterRead = engine.executeRaw<{ key: string; lifetime_ids: string; terminal_bytes: string }>(
"SELECT key,lifetime_ids::text,terminal_bytes::text FROM persistence_counters WHERE key='brain' OR key LIKE 'principal:%' ORDER BY key");
- const days: Day[] = [];
- for (const counter of counters) if (counter.key !== 'brain') days.push(...await principalDays(engine, counter.key, NET_SQL('w', 'e')));
- days.push(...(await engine.executeRaw<Record<string, string>>(`SELECT 'principal:local_cli:'||principal_id::text AS scope,to_char(created_at AT TIME ZONE 'UTC','YYYY-MM-DD') AS day,
+ const principals = counterRead.then(rows => Promise.all(rows.filter(counter => counter.key !== 'brain').map(counter => principalDays(engine, counter.key, NET_SQL('w', 'e')))));
+ const topology = engine.executeRaw<Record<string, string>>(`SELECT 'principal:local_cli:'||principal_id::text AS scope,to_char(created_at AT TIME ZONE 'UTC','YYYY-MM-DD') AS day,
count(*)::text AS ids,COALESCE(SUM(terminal_bytes),0)::text AS gross,COALESCE(SUM(terminal_bytes),0)::text AS net,
count(*) FILTER (WHERE created_at>now()-interval '1 day')::text AS recent_ids,
COALESCE(SUM(terminal_bytes) FILTER (WHERE created_at>now()-interval '1 day'),0)::text AS recent_gross,
COALESCE(SUM(terminal_bytes) FILTER (WHERE created_at>now()-interval '1 day'),0)::text AS recent_net
- FROM persistence_topology_changes WHERE created_at>now()-($1::double precision*interval '1 day') GROUP BY 1,2`, [WINDOW_DAYS])).map(toDay));
- const [history] = await engine.executeRaw<{ age_days: number | null; compaction_age_days: number | null }>(`SELECT
+ FROM persistence_topology_changes WHERE created_at>now()-($1::double precision*interval '1 day') GROUP BY 1,2`, [WINDOW_DAYS]);
+ const history = engine.executeRaw<{ age_days: number | null; compaction_age_days: number | null }>(`SELECT
(SELECT EXTRACT(EPOCH FROM now()-created_at)/86400 FROM persistence_requests ORDER BY sequence LIMIT 1)::float8 AS age_days,
(SELECT EXTRACT(EPOCH FROM now()-min(completed_at))/86400 FROM persistence_requests
WHERE recovery IS NULL AND NOT compacted AND state IN ('committed','conflict','failed','cancelled'))::float8 AS compaction_age_days`);
- const windowDays = Math.min(WINDOW_DAYS, Math.max(1, Number(history?.age_days ?? WINDOW_DAYS)));
- // Days until the oldest uncompacted receipt is compactable: until then every receipt keeps its gross reservation.
- const untilCompaction = Math.max(0, retention - Number(history?.compaction_age_days ?? 0));
// The uncompacted terminal receipts (the compactable partial index): what compaction would free, and the legacy under-reserved ones.
- const reclaim = opts.light ? [] : await engine.executeRaw<{ scope: string; bytes: string; under: string }>(`WITH r AS (SELECT * FROM persistence_requests
+ const reclaimRead = opts.light ? Promise.resolve([]) : engine.executeRaw<{ scope: string; bytes: string; under: string }>(`WITH r AS (SELECT * FROM persistence_requests
WHERE recovery IS NULL AND NOT compacted AND state IN ('committed','conflict','failed','cancelled')),
e AS (SELECT request_id,SUM(octet_length(data::text)+octet_length(kind)+1024) AS bytes,
bool_or(state IN ('queued','running')) AS unfinished FROM persistence_effects WHERE request_id IN (SELECT id FROM r) GROUP BY request_id)
@@ -146,7 +141,14 @@ export async function readCapacityForecast(engine: SqlEngine & { kind?: string }
COALESCE(SUM(r.terminal_reservation-${NET_SQL('r', 'e')}) FILTER (WHERE NOT COALESCE(e.unfinished,false)),0)::text AS bytes,
count(*) FILTER (WHERE COALESCE(octet_length(r.intent::text),0)+octet_length(r.authority::text)>r.terminal_reservation)::text AS under
FROM r LEFT JOIN e ON e.request_id=r.id GROUP BY 1`);
- const tableBytes = opts.light ? null : await engine.executeRaw<{ bytes: string }>("SELECT pg_total_relation_size('persistence_requests')::text AS bytes").then(r => Number(r[0]?.bytes), () => null);
+ const tableBytesRead = opts.light ? Promise.resolve(null) : engine.executeRaw<{ bytes: string }>("SELECT pg_total_relation_size('persistence_requests')::text AS bytes").then(r => Number(r[0]?.bytes), () => null);
+ const [limits, { warnDays, failDays }, retention, counters, principalRows, topologyRows, [historyRow], reclaim, tableBytes] = await Promise.all([
+ opts.limits ?? readJournalLimits(engine), readCapacityThresholds(engine), readReceiptRetentionDays(engine).catch(() => DEFAULT_RECEIPT_RETENTION_DAYS),
+ counterRead, principals, topology, history, reclaimRead, tableBytesRead]);
+ const days: Day[] = [...principalRows.flat(), ...topologyRows.map(toDay)];
+ const windowDays = Math.min(WINDOW_DAYS, Math.max(1, Number(historyRow?.age_days ?? WINDOW_DAYS)));
+ // Days until the oldest uncompacted receipt is compactable: until then every receipt keeps its gross reservation.
+ const untilCompaction = Math.max(0, retention - Number(historyRow?.compaction_age_days ?? 0));
const now = Date.now();
const rows: CapacityForecastRow[] = [];
for (const counter of counters) {
diff --git a/src/core/source-resolver.ts b/src/core/source-resolver.ts
index b3b5c2a880..75f584c364 100644
--- a/src/core/source-resolver.ts
+++ b/src/core/source-resolver.ts
@@ -115,10 +115,9 @@ function readDotfileWalk(startDir: string): string | null {
* `pickSoleNonDefaultSource` is already shared for tier 5.5).
*/
async function resolveRegisteredPathMatch(
- engine: BrainEngine,
+ registered: RegisteredSource[],
cwd: string,
): Promise<{ id: string; path: string; pathLen: number } | null> {
- const registered = await listRegisteredLocalPathSources(engine);
if (registered.length === 0) return null;
const [cwdResolved, resolvedPaths] = await Promise.all([
realpathOrResolveAsync(cwd),
@@ -158,11 +157,13 @@ export async function resolveSourceId(
return id;
}
+/** GBRA-133: `seen.registered` receives the tier-4 listing when the chain reached it, so a caller needs no second read of it. */
async function resolveSourceIdChain(
engine: BrainEngine,
explicit: string | null | undefined,
cwd: string,
opts: { skipLocalSignals?: boolean },
+ seen: { registered?: RegisteredSource[] } = {},
): Promise<string> {
// 1. Explicit flag wins. The __all__ sentinel passes through verbatim
// (#1712) — it is not a source id, so it skips both the regex and
@@ -199,7 +200,8 @@ 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.
- const best = await resolveRegisteredPathMatch(engine, cwd);
+ const registered = seen.registered = await listRegisteredLocalPathSources(engine);
+ const best = await resolveRegisteredPathMatch(registered, cwd);
if (best) {
// A local_path registration can outlive source archival. Treat landing in
// that tree as an explicit unavailable target, never as permission to
@@ -299,9 +301,11 @@ export function resolveSourceIdEngineFree(
* v34+ — fall back to the column-less query on older brains (rows then carry
* no `archived` key and are treated as active, the pre-v34 behavior).
*/
+type RegisteredSource = { id: string; local_path: string; archived?: boolean };
+
async function listRegisteredLocalPathSources(
engine: BrainEngine,
-): Promise<Array<{ id: string; local_path: string; archived?: boolean }>> {
+): Promise<RegisteredSource[]> {
try {
return await engine.executeRaw<{ id: string; local_path: string; archived?: boolean }>(
`SELECT id, local_path, archived FROM sources WHERE local_path IS NOT NULL`,
@@ -722,12 +726,15 @@ export async function getDefaultSourcePath(
engine: BrainEngine,
cwd: string = process.cwd(),
): Promise<string | null> {
- const sourceId = await resolveSourceId(engine, null, cwd);
- const rows = await engine.executeRaw<{ local_path: string | null }>(
- `SELECT local_path FROM sources WHERE id = $1`,
- [sourceId],
- );
- if (rows[0]?.local_path) return rows[0].local_path;
+ const seen: { registered?: RegisteredSource[] } = {};
+ const sourceId = await resolveSourceIdChain(engine, null, cwd, {}, seen);
+ noteResolvedSource(sourceId);
+ // GBRA-133: when the chain listed every source with a local_path, the resolved source's path is in that listing
+ // (absent means NULL), so it is not read again.
+ const localPath = seen.registered
+ ? seen.registered.find(r => r.id === sourceId)?.local_path ?? null
+ : (await engine.executeRaw<{ local_path: string | null }>(`SELECT local_path FROM sources WHERE id = $1`, [sourceId]))[0]?.local_path ?? null;
+ if (localPath) return localPath;
// Legacy fallback: pre-v0.18 brains stored the repo path in the global
// config table under sync.repo_path. The sources table exists but its
@@ -816,7 +823,7 @@ async function resolveSourceWithTierChain(
// 4. Registered source whose local_path contains CWD.
// #3880 active-over-archived tiering + parallel realpath both live in
// the shared resolveRegisteredPathMatch helper.
- const best = await resolveRegisteredPathMatch(engine, cwd);
+ const best = await resolveRegisteredPathMatch(await listRegisteredLocalPathSources(engine), cwd);
if (best) {
await assertSourceExists(engine, best.id);
return { source_id: best.id, tier: 'local_path', detail: best.path };
diff --git a/test/e2e/read-waves-gbra133-postgres.test.ts b/test/e2e/read-waves-gbra133-postgres.test.ts
new file mode 100644
index 0000000000..89c5cd7491
--- /dev/null
+++ b/test/e2e/read-waves-gbra133-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../read-waves-gbra133.test.ts'));
diff --git a/test/read-waves-gbra133.test.ts b/test/read-waves-gbra133.test.ts
new file mode 100644
index 0000000000..992003bbe8
--- /dev/null
+++ b/test/read-waves-gbra133.test.ts
@@ -0,0 +1,103 @@
+/**
+ * GBRA-133 lane C: reads a run issues back to back are dependent round trips at a remote database's RTT. Each case
+ * counts the waves a read issues (a call started while none is in flight opens a wave) and keeps the result the read
+ * returned before. Both backends; test/e2e/read-waves-gbra133-postgres.test.ts runs the Postgres arm in the E2E lane.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { readCapacityForecast } from '../src/core/persistence/capacity-forecast.ts';
+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 { freshBrainFactory, requestFixture } from './helpers/persistence-request-fixture.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { requestConfigRows, requestConfigValue } from '../src/core/config-snapshot.ts';
+
+/**
+ * Counts the statements \`fn\` sends and the waves they form (a statement started while none is in flight opens a wave);
+ * a config read a request snapshot answers sends nothing and is not counted. The engine's own methods are restored after.
+ */
+async function recordWaves<T>(engine: BrainEngine, fn: () => Promise<T>): Promise<{ result: T; waves: number; statements: string[] }> {
+ let inFlight = 0;
+ let waves = 0;
+ const statements: string[] = [];
+ const target = engine as unknown as Record<string, (...args: unknown[]) => Promise<unknown>>;
+ const send = (text: string, run: () => Promise<unknown>) => {
+ if (inFlight === 0) waves++;
+ inFlight++;
+ statements.push(text);
+ return run().finally(() => { inFlight--; });
+ };
+ const originals = { executeRaw: target.executeRaw!, getConfig: target.getConfig!, getAllConfig: target.getAllConfig! };
+ target.executeRaw = function (this: unknown, ...args: unknown[]) {
+ return send(String(args[0]).replace(/\s+/g, ' ').trim(), () => originals.executeRaw.apply(this, args));
+ };
+ target.getConfig = async function (this: unknown, ...args: unknown[]) {
+ if (await requestConfigValue(engine, String(args[0])) !== undefined) return originals.getConfig.apply(this, args);
+ return send('getConfig(' + String(args[0]) + ')', () => originals.getConfig.apply(this, args));
+ };
+ target.getAllConfig = async function (this: unknown, ...args: unknown[]) {
+ if (await requestConfigRows(engine) !== undefined) return originals.getAllConfig.apply(this, args);
+ return send('getAllConfig()', () => originals.getAllConfig.apply(this, args));
+ };
+ try {
+ return { result: await fn(), waves, statements };
+ } finally {
+ for (const name of Object.keys(originals)) delete target[name];
+ }
+}
+
+const databaseUrl = process.env.DATABASE_URL;
+
+for (const kind of testBackends()) {
+ describe('GBRA-133 read round trips (' + kind + ')', () => {
+ let factory: Awaited<ReturnType<typeof freshBrainFactory>>;
+ let scratch: string;
+ beforeAll(async () => {
+ scratch = mkdtempSync(join(tmpdir(), 'gbrain-read-waves-'));
+ factory = await freshBrainFactory(kind, databaseUrl);
+ }, 120_000);
+ afterAll(async () => {
+ await factory?.dispose();
+ if (scratch) rmSync(scratch, { recursive: true, force: true });
+ });
+ const check = (name: string, fn: (engine: BrainEngine) => Promise<void>) => test(name, async () => {
+ const engine = await factory.fresh();
+ await withEnv({ GBRAIN_HOME: scratch, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, () => fn(engine));
+ }, 120_000);
+
+ check('the capacity forecast issues its reads together: two waves with a principal counter, not one per read', async engine => {
+ const requests = await requestFixture(engine);
+ await requests.admit('gbra133-forecast');
+ const baseline = await readCapacityForecast(engine);
+ const { result, waves } = await recordWaves(engine, () => readCapacityForecast(engine));
+ expect(waves).toBeLessThanOrEqual(2);
+ expect(result).toEqual(baseline);
+ expect(result.rows.some(row => row.scope.startsWith('principal:'))).toBe(true);
+ });
+
+ check('the extraction lag reads config once and issues the lag count and the mention preview together: two waves', async engine => {
+ const { result, waves, statements } = await recordWaves(engine, () => readExtractionLag(engine, { sourceId: 'default' }));
+ expect(waves).toBeLessThanOrEqual(2);
+ expect(statements.filter(s => /^get(All)?Config\(|FROM config/.test(s)).length).toBe(1);
+ expect(result).toMatchObject({ total: 0, actionable: 0, attendance_blocked: 0, held: 0, mention_due: 0 });
+ });
+
+ check('the connect-time config merge reads the config table once for the merge and the gateway re-stamp', async engine => {
+ const { statements } = await recordWaves(engine, () => mergeDbPlaneConfig(engine, { engine: engine.kind } as never, new WeakMap()));
+ expect(statements.filter(s => s === 'getAllConfig()').length).toBe(1);
+ });
+
+ check('the default source path comes from the listing the resolution chain already read', async engine => {
+ const root = join(scratch, 'gbra133-src');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path) VALUES('gbra133-src','gbra133-src',$1) ON CONFLICT(id) DO UPDATE SET local_path=EXCLUDED.local_path", [root]);
+ const { result, statements } = await recordWaves(engine, () => getDefaultSourcePath(engine, tmpdir()));
+ expect(result).toBe(root);
+ expect(statements.filter(s => s.startsWith('SELECT local_path FROM sources WHERE id'))).toEqual([]);
+ });
+ });
+}