Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(search): the adjacency read inlines its integer page ids instead of a session-wide custom-plan setting, which slowed cascading deletes; the sixth search no longer stalls on a generic plan

garrytan9aa88eb316cb
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index ac6ee42def..9d83f5a962 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -20,7 +20,7 @@ src/core/engine.ts 2678 ratchet grown v0.46.26.0 megawave: relational/visibility
src/core/import-file.ts 2232 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts)
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 332 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line)
-src/core/pglite-engine.ts 3120 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); +3 fix wave 8: PGLite sessions force custom plans (generic-plan adjacency stall)
+src/core/pglite-engine.ts 3117 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108)
src/core/postgres-engine.ts 3130 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133)
src/core/search/hybrid.ts 1584 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key
src/core/types.ts 2112 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field)
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 215a9e0187..4661899cc8 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -864,9 +864,6 @@ export class PGLiteEngine implements BrainEngine {
const runtimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
await this._db.query(`SELECT set_config('TimeZone', $1, false)`, [runtimeZone]);
}
- // Without planner statistics the generic plan Postgres adopts after five executions of a
- // prepared statement can be a pages x links nested loop (6th search: ~7 s vs ~45 ms at 2k pages).
- await this._db?.query(`SELECT set_config('plan_cache_mode', 'force_custom_plan', false)`);
// Healthy open: close any repair episode left open by a prior failed
// attempt (red-team: episodes otherwise stayed open forever — doctor
// kept reporting corruption-likely and a weeks-stale episode backup
diff --git a/src/core/search/read-enrichment.ts b/src/core/search/read-enrichment.ts
index 9edb5497ca..58d7dc58d7 100644
--- a/src/core/search/read-enrichment.ts
+++ b/src/core/search/read-enrichment.ts
@@ -98,7 +98,15 @@ export async function readBacklinkCounts(query: ReadQuery, ids: number[], scope?
export async function readAdjacencyBoosts(query: ReadQuery, ids: number[], scope?: PageReadScope): Promise<Map<number, AdjacencyRow>> {
if (!ids.length) return new Map();
- const params: unknown[] = [ids];
+ // The candidate ids are inlined (integers only), never a bound parameter: once a
+ // statement has run five times Postgres may reuse a generic plan, and without
+ // planner statistics (PGLite) the generic plan of this read walks pages against
+ // links (~7 s per search at 2k pages instead of ~45 ms).
+ const idArray = `ARRAY[${ids.map(id => {
+ if (!Number.isSafeInteger(id)) throw new TypeError(`readAdjacencyBoosts: page id ${String(id)} is not an integer`);
+ return id;
+ }).join(',')}]::int[]`;
+ const params: unknown[] = [];
const from = pageReadFilter('p', scope, params, !!scope);
const to = pageReadFilter('t', scope, params, !!scope);
const origin = originFilter(scope, params);
@@ -107,7 +115,7 @@ export async function readAdjacencyBoosts(query: ReadQuery, ids: number[], scope
COUNT(DISTINCT CASE WHEN p.source_id <> t.source_id THEN p.source_id END)::int AS cross_source_hits
FROM links l JOIN pages p ON p.id = l.from_page_id AND p.deleted_at IS NULL
JOIN pages t ON t.id = l.to_page_id AND t.deleted_at IS NULL
- WHERE l.from_page_id = ANY($1::int[]) AND l.to_page_id = ANY($1::int[])
+ WHERE l.from_page_id = ANY(${idArray}) AND l.to_page_id = ANY(${idArray})
AND ${from} AND ${to} AND ${origin}
GROUP BY l.to_page_id HAVING COUNT(DISTINCT l.from_page_id) >= 1`, params);
return new Map(rows.map(row => [Number(row.to_page_id), { hits: Number(row.hits), cross_source_hits: Number(row.cross_source_hits) }]));
diff --git a/test/pglite-custom-plans.test.ts b/test/pglite-custom-plans.test.ts
deleted file mode 100644
index 958054d3d7..0000000000
--- a/test/pglite-custom-plans.test.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-/**
- * PGLite plans every parameterized execution for its own values. After five
- * executions Postgres may switch a prepared statement to a generic plan, and
- * without planner statistics the generic plan of the search adjacency read is
- * a pages x links nested loop: on a 2,000-page brain the sixth MCP search of a
- * process took about 7 s instead of about 45 ms.
- */
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
-import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-
-let engine: PGLiteEngine;
-beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);
-afterAll(async () => { await engine.disconnect(); });
-
-describe('PGLite session planning', () => {
- test('repeated parameterized queries never switch to a generic plan', async () => {
- const [row] = await engine.executeRaw<{ mode: string }>("SELECT current_setting('plan_cache_mode') AS mode");
- expect(row!.mode).toBe('force_custom_plan');
- });
-});
diff --git a/test/search/adjacency-generic-plan.test.ts b/test/search/adjacency-generic-plan.test.ts
new file mode 100644
index 0000000000..670f2d09b7
--- /dev/null
+++ b/test/search/adjacency-generic-plan.test.ts
@@ -0,0 +1,43 @@
+/**
+ * The search adjacency read stays on a per-call plan. Once a statement has run
+ * five times Postgres may reuse a generic plan, and without planner statistics
+ * (PGLite has no autovacuum) the generic plan of this read walked pages against
+ * links: on a 2,000-page brain every MCP search after the fifth in a process
+ * took about 7 s instead of about 45 ms.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+
+let engine: PGLiteEngine;
+let ids: number[] = [];
+const PAGES = 1500;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw(`INSERT INTO pages (source_id, slug, type, title, compiled_truth)
+ SELECT 'default', 'notes/adjacency-' || g, 'note', 'Adjacency ' || g, 'Body ' || g FROM generate_series(1, ${PAGES}) g`);
+ await engine.executeRaw(`INSERT INTO links (from_page_id, to_page_id, link_type, link_source)
+ SELECT a.id, b.id, 'mentions', 'markdown' FROM pages a JOIN pages b ON b.id IN (a.id + 1, a.id + 7, a.id + 31)
+ ON CONFLICT DO NOTHING`);
+ ids = (await engine.executeRaw<{ id: number }>('SELECT id FROM pages ORDER BY id LIMIT 40')).map(row => Number(row.id));
+}, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+
+describe('search adjacency read', () => {
+ test('the sixth and later calls in one process stay as fast as the first five', async () => {
+ const scope = { sourceIds: ['default'] };
+ const times: number[] = [];
+ let result = new Map();
+ for (let i = 0; i < 9; i++) {
+ const started = performance.now();
+ result = await engine.getAdjacencyBoosts(ids, scope);
+ times.push(performance.now() - started);
+ }
+ expect(result.size).toBeGreaterThan(0);
+ const early = Math.max(...times.slice(1, 5));
+ const late = Math.max(...times.slice(5));
+ expect({ times: times.map(Math.round), slow: late > Math.max(50, early * 10) }).toMatchObject({ slow: false });
+ }, 120_000);
+});