Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(get_page): exact-slug snapshot before the alias lookup; fix the SIGTERM lockfile race in bounded-child-exec
time-attack84addd2e1815
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 23f6601294..82073cca4e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,9 +12,9 @@ identifiers and attribution are available in the pre-removal Git revision## [0.60.123.0] - 2026-10-09-**Postgres search, list and backlink reads stop taking the slow plan: vector search walks the vector index first, and remote reads stop compiling every statement before running it.**+**Postgres search, list, page and backlink reads stop taking the slow plan: vector search walks the vector index first, remote reads stop compiling every statement before running it, and `get_page` looks up the exact page before trying aliases.**-Three plan problems showed up while profiling synthetic brains shaped like a real 5,000-page brain. First, vector search often skipped the vector index. On a 25,000-chunk brain it read and sorted every chunk instead, at a 50-result limit and on some remote reads. Second, the rule that hides private pages looked so expensive to Postgres that it compiled any statement using it to machine code first, at 40 to 570 ms a call, then ran it in about one. That rule covers listing pages, backlink counts and the search legs. Third, the hold lookup that `get_page` and every search run could only join pages by text-casting every page id. Results don't change: the same rows come back in the same order.+Three plan problems showed up while profiling synthetic brains shaped like a real 5,000-page brain. First, vector search often skipped the vector index. On a 25,000-chunk brain it read and sorted every chunk instead, at a 50-result limit and on some remote reads. Second, the rule that hides private pages looked so expensive to Postgres that it compiled any statement using it to machine code first, at 40 to 570 ms a call, then ran it in about one. That rule covers listing pages, backlink counts and the search legs. Third, the hold lookup that `get_page` and every search run could only join pages by text-casting every page id. Fourth, `get_page` matched the page or any alias in one statement, which scans the source's pages. Results don't change: the same rows come back in the same order.### What you'd see@@ -27,6 +27,7 @@ Warm reads on a 4 vCPU box, Postgres 16 + pgvector 0.8.7, synthetic brains (5,00| Vector search, remote reader, 50 results | 93 (1.00) | 33 (0.995) | 52 (0.63) | 58 (0.79) || Vector search, remote reader, type filter | 239 | 256 | 8,091 (2.8 of 20 results) | 1,064 (20 of 20) || `list_pages` over MCP | 70 | 11 | 52 | 12 |+| `get_page` over MCP | 18 | 12 | 15 | 9 || Backlink count statement (search and query) | 265 | 4 | 571 | 8 || `search` over MCP (includes the embedding call) | 880 | 668 | 866 | 715 |@@ -40,12 +41,14 @@ Warm reads on a 4 vCPU box, Postgres 16 + pgvector 0.8.7, synthetic brains (5,00- **Vector index walk.** `buildVectorSearchStatement` adds `indexWalkSql`. Its `ann` CTE orders `content_chunks` alone with only the chunk-level filters (modality, model, `detail`, language, symbol kind) over twice the candidate window. It then joins pages and sources by key and applies every page filter, visibility and the private-page rule to those rows, keeping the nearest `innerLimit`. Both engines run it first with `enable_sort = off` (the HNSW scan is then the only ordered path) and `hnsw.ef_search` sized for the doubled window. They accept it when the window is full and fills the limit; otherwise they run the joined statement and its escalation exactly as before. Type and date filters, the legacy guard and non-indexed columns skip it. Doctor `vector_plan` and `explainVectorSearch` explain the walk.- **Private-page rule.** `privatePagesFilterFragment` matches `derived_from` slugs with `= ANY(ARRAY(...))` instead of `IN (SELECT ... jsonb_array_elements_text(...))`. The rows are the same, but the planner stopped pricing a 100-row semi-join per page, which kept `list_pages`, backlink counts and remote search legs past `jit_above_cost`. No read needs a JIT-off wrapper.- **Held-page read.** `readHeldPages` joins `pages` on `p.id = (page_id)::int`, so the page lookup is a primary-key probe whatever the small-table statistics say.+- **Page snapshot.** An alias-resolving `readPageSnapshot` (`get_page`, `fetch`) runs the exact-slug statement first and the `slug = $1 OR EXISTS (alias)` statement only on a miss: an exact match outranks every alias match there, so the row is the same. An ambiguity check (`requireUnambiguous`) still runs the alias statement alone. The statement drops from 3.8 to 0.7 ms at 5k and 1.8 to 0.8 ms at 50k.### For contributors- `test/search/vector-index-walk.test.ts` (PGLite) checks that a full walk window returns the joined statement's rows in the same order across a filter matrix (private-page rules, archived and quarantined pages, deleted pages, stale hashes). It also checks that a short window falls back to the joined result. `test/search/vector-statement.test.ts` pins the walk's shape.- `test/e2e/private-visibility-plan-postgres.test.ts` proves both spellings of the private-page rule hide exactly the same pages, and that the planner's cost per page now stays under `jit_above_cost / 500`. A precondition fails if the old spelling would also pass.-- `test/e2e/vector-plan-real-column-postgres.test.ts` checks the walk uses `idx_chunks_embedding` for remote readers and 50- and 200-result windows. `test/held-read-signals.test.ts` checks the held-page read probes `pages_pkey` (it fails on the text-cast join).+- `test/e2e/vector-plan-real-column-postgres.test.ts` checks the walk uses `idx_chunks_embedding` for remote readers and 50- and 200-result windows. `test/held-read-signals.test.ts` checks the held-page read probes `pages_pkey` (it fails on the text-cast join). `test/page-snapshot-exact-first.test.ts` covers exact hits, alias fallback, an exact page in another source, deleted and private exact pages, the ambiguity check and a miss.+- `test/bounded-child-exec.test.ts`: the SIGTERM test installs the child's trap before it writes the lockfile and waits for the lockfile instead of sleeping 200 ms; on a loaded runner the child had not started yet (forced probe: delaying the child 0.5 s fails the old test and passes the new one).## [0.60.122.0] - 2026-10-09diff --git a/src/core/page-state/snapshot.ts b/src/core/page-state/snapshot.tsindex f552219feb..54a7d70e4b 100644--- a/src/core/page-state/snapshot.ts+++ b/src/core/page-state/snapshot.ts@@ -17,8 +17,25 @@ export async function overlayCanonicalBodies(query: ReadQuery, body: string, timtimeline: overlayWithdrawalBody(timeline, normalized.timeline ?? '', withdrawals) };}-/** One MVCC statement binds content, tags, identity and withdrawals to one revision. */+/**+ * One MVCC statement binds content, tags, identity and withdrawals to one revision.+ *+ * An alias-resolving read first runs the exact-slug statement: an exact match+ * outranks every alias match, so a hit is the row the alias statement would+ * pick. Only a miss runs the alias statement, whose `slug = $1 OR EXISTS+ * (alias)` disjunction scans the source's pages (23-80 ms at 50k pages, under+ * 1 ms for the exact lookup). An ambiguity check counts alias matches too, so+ * it always runs the alias statement.+ */export async function readPageSnapshot(query: ReadQuery, slug: string, opts?: PageSnapshotOptions): Promise<PageSnapshot | null> {+ if (opts?.resolveAlias === true && opts.requireUnambiguous !== true) {+ const exact = await readSnapshotStatement(query, slug, { ...opts, resolveAlias: false });+ if (exact) return exact;+ }+ return readSnapshotStatement(query, slug, opts);+}++async function readSnapshotStatement(query: ReadQuery, slug: string, opts?: PageSnapshotOptions): Promise<PageSnapshot | null> {const params: unknown[] = [slug];// Alias resolution is part of the statement text, not a parameter, so a// cached plan for an exact-slug read keeps using the slug index.diff --git a/test/bounded-child-exec.test.ts b/test/bounded-child-exec.test.tsindex 907ee14c11..5e009208d5 100644--- a/test/bounded-child-exec.test.ts+++ b/test/bounded-child-exec.test.ts@@ -104,10 +104,11 @@ test('bounded execution stops a running child on abort and at its deadline', asytest('a stopped child gets SIGTERM first so it can remove its lockfile, then SIGKILL after the grace period', async () => {const lock = join(dir, 'index.lock');- const script = `touch '${lock}'; trap "rm -f '${lock}'; exit 143" TERM; while :; do sleep 0.05; done`;+ const script = `trap "rm -f '${lock}'; exit 143" TERM; touch '${lock}'; while :; do sleep 0.05; done`;const abort = new AbortController();const running = execFileBounded('sh', ['-c', script], { timeout: 60_000, signal: abort.signal });- await Bun.sleep(200);+ // The lock appears once the child's trap is installed; on a loaded runner that can take longer than any fixed sleep.+ for (const deadline = performance.now() + 10_000; !(await Bun.file(lock).exists()) && performance.now() < deadline;) await Bun.sleep(20);expect(await Bun.file(lock).exists()).toBe(true);abort.abort();expect((await running).error).toMatchObject({ code: 'ABORT_ERR', killed: true });diff --git a/test/page-snapshot-exact-first.test.ts b/test/page-snapshot-exact-first.test.tsnew file mode 100644index 0000000000..70ac547e1b--- /dev/null+++ b/test/page-snapshot-exact-first.test.ts@@ -0,0 +1,97 @@+/**+ * An alias-resolving page read runs the exact-slug statement first and the+ * alias statement only on a miss (src/core/page-state/snapshot.ts). An exact+ * match outranks every alias match in the alias statement's ORDER BY, so the+ * two-step read returns the same row; an ambiguity check still counts alias+ * matches, so it runs the alias statement alone.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { readPageSnapshot } from '../src/core/page-state/snapshot.ts';+import { PageSnapshotAmbiguousError, type PageSnapshotOptions } from '../src/core/page-state/types.ts';++let engine: PGLiteEngine;++/** Reads through the canonical snapshot function and records each statement it sends. */+async function read(slug: string, opts: PageSnapshotOptions) {+ const statements: string[] = [];+ const snapshot = await readPageSnapshot(async (sql, params) => {+ statements.push(sql);+ return engine.executeRaw(sql, params) as never;+ }, slug, opts);+ return { snapshot, statements, aliasStatements: statements.filter(sql => sql.includes('slug_aliases')).length };+}++const page = (body: string, frontmatter: Record<string, unknown> = {}) => ({ type: 'note' as const, title: body, compiled_truth: body, frontmatter });++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ for (const id of ['alpha', 'beta']) {+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING`, [id]);+ }+ await engine.putPage('notes/canonical', page('alpha canonical'), { sourceId: 'alpha' });+ await engine.putPage('notes/old-name', page('beta page at the alias slug'), { sourceId: 'beta' });+ await engine.putPage('notes/gone', page('deleted exact'), { sourceId: 'alpha' });+ await engine.putPage('notes/gone-canonical', page('live canonical'), { sourceId: 'alpha' });+ await engine.putPage('notes/private-exact', page('private exact', { visibility: 'private' }), { sourceId: 'alpha' });+ await engine.putPage('notes/world-canonical', page('world canonical'), { sourceId: 'alpha' });+ await engine.executeRaw(`UPDATE pages SET deleted_at = now() WHERE slug = 'notes/gone'`);+ await engine.executeRaw(`INSERT INTO slug_aliases (source_id, alias_slug, canonical_slug, notes) VALUES+ ('alpha', 'notes/old-name', 'notes/canonical', 'test'),+ ('alpha', 'legacy/canonical', 'notes/canonical', 'test'),+ ('alpha', 'notes/gone', 'notes/gone-canonical', 'test'),+ ('alpha', 'notes/private-exact', 'notes/world-canonical', 'test')`);+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+}, 60_000);++describe('alias-resolving page read: exact slug first', () => {+ test('an exact hit is one statement and skips the alias lookup', async () => {+ const { snapshot, statements, aliasStatements } = await read('notes/canonical', { resolveAlias: true });+ expect(snapshot?.page.slug).toBe('notes/canonical');+ expect(statements).toHaveLength(1);+ expect(aliasStatements).toBe(0);+ });++ test('an alias-only slug falls back to the alias statement and returns the canonical page', async () => {+ const { snapshot, statements, aliasStatements } = await read('legacy/canonical', { resolveAlias: true });+ expect(snapshot?.page.slug).toBe('notes/canonical');+ expect(snapshot?.page.source_id).toBe('alpha');+ expect(statements).toHaveLength(2);+ expect(aliasStatements).toBe(1);+ });++ test('an exact page in another source still outranks an alias in this one, as the alias statement orders it', async () => {+ const both = await read('notes/old-name', { resolveAlias: true });+ expect([both.snapshot?.page.slug, both.snapshot?.page.source_id]).toEqual(['notes/old-name', 'beta']);+ expect(both.aliasStatements).toBe(0);+ const scoped = await read('notes/old-name', { resolveAlias: true, sourceId: 'alpha' });+ expect([scoped.snapshot?.page.slug, scoped.snapshot?.page.source_id]).toEqual(['notes/canonical', 'alpha']);+ });++ test('filters apply to the exact lookup: a deleted or private exact page misses and the alias resolves', async () => {+ expect((await read('notes/gone', { resolveAlias: true })).snapshot?.page.slug).toBe('notes/gone-canonical');+ expect((await read('notes/gone', { resolveAlias: true, includeDeleted: true })).snapshot?.page.slug).toBe('notes/gone');+ expect((await read('notes/private-exact', { resolveAlias: true, excludePrivate: true })).snapshot?.page.slug).toBe('notes/world-canonical');+ expect((await read('notes/private-exact', { resolveAlias: true })).snapshot?.page.slug).toBe('notes/private-exact');+ });++ test('an ambiguity check runs the alias statement alone and still sees alias matches', async () => {+ const run = read('notes/old-name', { resolveAlias: true, requireUnambiguous: true });+ await expect(run).rejects.toBeInstanceOf(PageSnapshotAmbiguousError);+ const single = await read('notes/canonical', { resolveAlias: true, requireUnambiguous: true });+ expect(single.snapshot?.page.slug).toBe('notes/canonical');+ expect(single.statements).toHaveLength(1);+ expect(single.aliasStatements).toBe(1);+ });++ test('a missing slug returns null after both statements', async () => {+ const { snapshot, statements } = await read('notes/never', { resolveAlias: true });+ expect(snapshot).toBeNull();+ expect(statements).toHaveLength(2);+ });+});