Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(links): share one basename index per source and look link endpoints up by (source_id, slug)

garrytan5dd83f6e3254
diff --git a/scripts/bench/link-preparation.ts b/scripts/bench/link-preparation.ts
new file mode 100644
index 0000000000..2e00954a36
--- /dev/null
+++ b/scripts/bench/link-preparation.ts
@@ -0,0 +1,133 @@
+#!/usr/bin/env bun
+/**
+ * Per-page cost of automatic link preparation (prepareAutomaticLinks), the
+ * step every managed sync drain and put_page publication runs for each page.
+ *
+ * bun scripts/bench/link-preparation.ts --engine pglite --pages 1000,3000,10000
+ * DATABASE_URL=postgresql://... bun scripts/bench/link-preparation.ts --engine postgres
+ *
+ * Seeds a synthetic source of N pages (dir-qualified and bare wikilinks,
+ * markdown links, frontmatter refs, plus links to slugs that exist only in a
+ * second source), then times prepareAutomaticLinks over a sample of pages in
+ * two loops: `read_only` (nothing changes between pages, like a re-derive of
+ * stale pages) and `with_writes` (a new page is inserted into the source
+ * before every preparation, like a first-sync drain). Statements are counted
+ * on the PGLite connection, or with pg_stat_statements on Postgres (the
+ * server must preload it). Writes JSON to --out.
+ */
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { dirname } from 'node:path';
+import postgres from '#postgres';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { prepareAutomaticLinks } from '../../src/core/persistence/links-preparation.ts';
+
+const BENCH_SQL = '/* gbrain-bench */';
+const args = new Map<string, string>();
+for (let i = 2; i < process.argv.length; i += 2) args.set(process.argv[i]!.replace(/^--/, ''), process.argv[i + 1] ?? '');
+const engineKind = (args.get('engine') ?? 'pglite') as 'pglite' | 'postgres';
+const sizes = (args.get('pages') ?? '1000,3000,10000').split(',').map(Number);
+const samples = Number(args.get('samples') ?? 200);
+const label = args.get('label') ?? 'run';
+const out = args.get('out') ?? `${process.env.HOME}/.capy/work/bench/link-preparation-${engineKind}-${label}.json`;
+const pad = (i: number) => String(i).padStart(5, '0');
+
+function body(i: number, n: number): { compiled_truth: string; frontmatter: Record<string, unknown> } {
+ const a = (i * 7 + 3) % n, b = (i * 13 + 5) % n, c = (i * 31 + 11) % n;
+ return {
+ frontmatter: { title: `Note ${i}`, related: [`notes/n${pad(c)}`] },
+ compiled_truth: `Observation ${i} about routine work. See [[notes/n${pad(a)}]] and [[Note ${b}]].\n`
+ + `Background in [the earlier note](notes/n${pad(b)}) and [[shared/s${pad(i % 50)}]], which lives in another source.\n`
+ + `An unwritten idea: [[ideas/i${pad(i)}]].\n`,
+ };
+}
+
+async function seed(engine: BrainEngine, n: number) {
+ await engine.executeRaw(`INSERT INTO sources(id,name,config) VALUES('other','other','{}') ON CONFLICT (id) DO NOTHING`);
+ const rows = Array.from({ length: n }, (_, i) => ({ slug: `notes/n${pad(i)}`, title: `Note ${i}`, ...body(i, n) }));
+ for (let i = 0; i < rows.length; i += 500) {
+ const chunk = rows.slice(i, i + 500);
+ await engine.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth,frontmatter)
+ SELECT 'default', r->>'slug', 'note', r->>'title', r->>'compiled_truth', r->'frontmatter' FROM jsonb_array_elements($1::text::jsonb) r`, [JSON.stringify(chunk)]);
+ }
+ await engine.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth)
+ SELECT 'other', 'shared/s' || lpad(g::text, 5, '0'), 'note', 'Shared ' || g, 'shared' FROM generate_series(0, 49) g`);
+ await engine.executeRaw('ANALYZE pages');
+}
+
+interface Counter { reset: () => Promise<void>; read: () => Promise<number>; close: () => Promise<void> }
+
+function pgliteCounter(engine: PGLiteEngine): Counter {
+ const db = (engine as unknown as { _db: Record<'query' | 'exec', (...a: unknown[]) => Promise<unknown>> })._db;
+ const original = { query: db.query, exec: db.exec };
+ let n = 0;
+ db.query = (...a) => { n++; return original.query.apply(db, a); };
+ db.exec = (...a) => { n++; return original.exec.apply(db, a); };
+ return { reset: async () => { n = 0; }, read: async () => n, close: async () => { db.query = original.query; db.exec = original.exec; } };
+}
+
+function postgresCounter(url: string): Counter {
+ const sql = postgres(url, { max: 1, onnotice: () => {} });
+ const db = new URL(url).pathname.slice(1);
+ return {
+ reset: async () => { await sql.unsafe(`${BENCH_SQL} SELECT pg_stat_statements_reset(0, (SELECT oid FROM pg_database WHERE datname=$1), 0)`, [db]); },
+ read: async () => {
+ const [row] = await sql.unsafe(`${BENCH_SQL} SELECT coalesce(sum(calls),0)::int AS n FROM pg_stat_statements
+ WHERE dbid=(SELECT oid FROM pg_database WHERE datname=$1) AND query NOT LIKE '%gbrain-bench%'`, [db]);
+ return Number(row!.n);
+ },
+ close: async () => { await sql.end(); },
+ };
+}
+
+async function measure(engine: BrainEngine, counter: Counter, n: number, writes: boolean) {
+ const picks = Array.from({ length: samples }, (_, k) => Math.floor((k * n) / samples));
+ const snapshots = [];
+ for (const i of picks) snapshots.push((await engine.readPageSnapshot(`notes/n${pad(i)}`, { sourceId: 'default' }))!);
+ let ms = 0, statements = 0, keys = 0, extra = 0;
+ for (const snapshot of snapshots) {
+ if (writes) await engine.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth) VALUES('default',$1,'note',$2,'new')`,
+ [`notes/new-${label}-${n}-${extra}`, `New ${extra++}`]);
+ await counter.reset();
+ const started = performance.now();
+ const prepared = await prepareAutomaticLinks(engine, snapshot.page.slug, { ...snapshot.page, frontmatter: snapshot.page.frontmatter ?? {} }, 'default');
+ ms += performance.now() - started;
+ statements += await counter.read();
+ keys += prepared.pageKeys.length;
+ }
+ const r2 = (x: number) => Math.round(x * 100) / 100;
+ return { ms_per_page: r2(ms / samples), statements_per_page: r2(statements / samples), page_keys_total: keys };
+}
+
+const results: Record<string, unknown>[] = [];
+for (const n of sizes) {
+ let engine: BrainEngine, counter: Counter, close: () => Promise<void>;
+ if (engineKind === 'pglite') {
+ const e = new PGLiteEngine(); await e.connect({}); await e.initSchema();
+ engine = e; counter = pgliteCounter(e); close = async () => { await counter.close(); await e.disconnect(); };
+ } else {
+ const base = process.env.DATABASE_URL;
+ if (!base) throw new Error('DATABASE_URL is required for --engine postgres');
+ const db = `gbrain_bench_links_${n}_${Date.now()}`;
+ const admin = postgres(base, { max: 1, onnotice: () => {} });
+ await admin.unsafe(`CREATE DATABASE ${db}`);
+ const url = new URL(base); url.pathname = `/${db}`;
+ const e = new PostgresEngine(); await e.connect({ database_url: url.toString(), poolSize: 4 }); await e.initSchema();
+ await e.executeRaw('CREATE EXTENSION IF NOT EXISTS pg_stat_statements');
+ engine = e; counter = postgresCounter(url.toString());
+ close = async () => { await counter.close(); await e.disconnect(); await admin.unsafe(`DROP DATABASE ${db} WITH (FORCE)`); await admin.end(); };
+ }
+ try {
+ await seed(engine, n);
+ await measure(engine, counter, n, false);
+ const readOnly = await measure(engine, counter, n, false);
+ const withWrites = await measure(engine, counter, n, true);
+ const row = { engine: engineKind, label, pages: n, samples, read_only: readOnly, with_writes: withWrites };
+ console.log(JSON.stringify(row));
+ results.push(row);
+ } finally { await close(); }
+}
+mkdirSync(dirname(out), { recursive: true });
+writeFileSync(out, JSON.stringify({ engine: engineKind, label, bun: Bun.version, results }, null, 2) + '\n');
+console.log(`wrote ${out}`);
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index eca6853315..37ed8e816c 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -31,7 +31,7 @@ src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle re
src/commands/bootstrap.ts 2134 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags)
src/core/minions/worker.ts 1774 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler)
src/commands/sources.ts 2042 ratchet +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts)
-src/core/link-extraction.ts 2204 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at
+src/core/link-extraction.ts 2210 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +6 link-preparation shared index: makeResolver basenameIndex provider + per-resolver basename-match memo
src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify; +17 #5334: smoke check samples one representative chunk per distinct page (bounded index-ordered batch walk, longest chunk re-read under the page lock, title-prefixed bounded query); +1 #5334: the smoke-query length limits are shared with the worst-case budget
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1916 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts)
diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.ts
index 7ad71f6629..4e557be2bb 100644
--- a/src/core/link-extraction.ts
+++ b/src/core/link-extraction.ts
@@ -1473,9 +1473,8 @@ function basenameSort(a: string, b: string): number {
return (a.length - b.length) || a.localeCompare(b);
}
-/** Build a `key → slug[]` index over a slug collection. Keys: raw/lower/slugified tail. */
-export function buildBasenameIndex(slugs: Iterable<string>): Map<string, string[]> {
- const idx = new Map<string, string[]>();
+/** Build a `key → slug[]` index over a slug collection, or add the slugs to `idx`. Keys: raw/lower/slugified tail. */
+export function buildBasenameIndex(slugs: Iterable<string>, idx = new Map<string, string[]>()): Map<string, string[]> {
const addKey = (key: string, slug: string) => {
const existing = idx.get(key);
if (existing) { if (!existing.includes(slug)) existing.push(slug); }
@@ -1518,9 +1517,10 @@ export function queryBasenameIndex(idx: Map<string, string[]>, name: string): st
*/
export function makeResolver(
engine: BrainEngine,
- opts: { mode: 'batch' | 'live'; sourceId?: string } = { mode: 'live' },
+ opts: { mode: 'batch' | 'live'; sourceId?: string; basenameIndex?: () => Promise<Map<string, string[]>> } = { mode: 'live' },
): SlugResolver {
const cache = new Map<string, string | null>();
+ const basenameMatches = new Map<string, string[]>();
const attendanceCache = new Map<string, string | null>();
const attendanceCacheLimit = 256;
@@ -1535,6 +1535,10 @@ export function makeResolver(
async function ensureBasenameIndex(): Promise<Map<string, string[]>> {
if (basenameIndex !== null) return basenameIndex;
const idx = new Map<string, string[]>();
+ if (opts.basenameIndex) {
+ basenameIndex = await opts.basenameIndex().catch(() => idx);
+ return basenameIndex;
+ }
if (typeof engine.getAllSlugs !== 'function') {
basenameIndex = idx;
return idx;
@@ -1583,8 +1587,10 @@ export function makeResolver(
},
async resolveBasenameMatches(name: string): Promise<string[]> {
// Issue #972 (codex [P2] DRY): shared query so resolver + FS + doctor
- // return the same matches in the same stable order.
- return queryBasenameIndex(await ensureBasenameIndex(), name);
+ // return the same matches in the same stable order. Memoized per
+ // resolver: a shared opts.basenameIndex may grow while a page extracts.
+ if (!basenameMatches.has(name)) basenameMatches.set(name, queryBasenameIndex(await ensureBasenameIndex(), name));
+ return [...basenameMatches.get(name)!];
},
async resolve(name: string, dirHint?: string | string[], resolveOpts?: ResolveOptions): Promise<string | null> {
diff --git a/src/core/persistence/links-preparation.ts b/src/core/persistence/links-preparation.ts
index a0ed1b4d53..950c0c99d3 100644
--- a/src/core/persistence/links-preparation.ts
+++ b/src/core/persistence/links-preparation.ts
@@ -1,7 +1,7 @@
import type { BrainEngine } from '../engine.ts';
import { isUndefinedTableError } from '../utils.ts';
import type { ParsedPage } from '../import-file.ts';
-import { extractPageLinks, isGlobalBasenameEnabled, makeResolver, resolvedLinkCandidate } from '../link-extraction.ts';
+import { buildBasenameIndex, extractPageLinks, isGlobalBasenameEnabled, makeResolver, resolvedLinkCandidate } from '../link-extraction.ts';
import { loadActivePackForLocalEngine } from '../schema-pack/best-effort.ts';
import { DerivedLinkEndpointChangedError } from '../derived-links.ts';
import { capturedLinkEndpoints, indexLinkSources, loadLinkSourcePolicy, resolveCandidateSources } from '../link-reconciliation.ts';
@@ -23,9 +23,58 @@ async function liveSlugAliases(engine: BrainEngine, sourceId: string, targets: s
}
}
+interface SourceSlugIndex { count: number; hash: bigint; maxId: number; index: Map<string, string[]> }
+const sourceSlugIndexes = new WeakMap<BrainEngine, Map<string, Promise<SourceSlugIndex | null>>>();
+const SLUG_FINGERPRINT = 'count(*)::int AS n, coalesce(sum(hashtextextended(slug, 0)), 0)::text AS h, coalesce(max(id), 0)::int AS m';
+
+async function refreshSourceSlugIndex(engine: BrainEngine, sourceId: string, state: SourceSlugIndex | null): Promise<SourceSlugIndex> {
+ if (state) {
+ const [probe] = await engine.executeRaw<{ n: number; h: string; m: number; added: string[]; added_h: string }>(`SELECT ${SLUG_FINGERPRINT},
+ coalesce(array_agg(slug) FILTER (WHERE id > $2), '{}') AS added, coalesce(sum(hashtextextended(slug, 0)) FILTER (WHERE id > $2), 0)::text AS added_h
+ FROM pages WHERE source_id=$1`, [sourceId, state.maxId]);
+ const hash = BigInt(probe!.h);
+ if (!probe!.added.length && probe!.n === state.count && hash === state.hash) return state;
+ if (probe!.n === state.count + probe!.added.length && hash === state.hash + BigInt(probe!.added_h)) {
+ return { count: probe!.n, hash, maxId: probe!.m, index: buildBasenameIndex(probe!.added, state.index) };
+ }
+ }
+ const [all] = await engine.executeRaw<{ n: number; h: string; m: number; slugs: string[] }>(
+ `SELECT ${SLUG_FINGERPRINT}, coalesce(array_agg(slug), '{}') AS slugs FROM pages WHERE source_id=$1`, [sourceId]);
+ return { count: all!.n, hash: BigInt(all!.h), maxId: all!.m, index: buildBasenameIndex(all!.slugs) };
+}
+
+/**
+ * The basename index of every slug in a source (getAllSlugs' set), kept per
+ * engine and source across link preparations. Each call fingerprints the
+ * source's slugs (count, hash sum, max id) and reuses the index when nothing
+ * changed, adds the new rows when only inserts happened, else rebuilds; so a
+ * write from any process is seen exactly as the per-page slug read saw it.
+ */
+async function sourceBasenameIndex(engine: BrainEngine, sourceId: string): Promise<Map<string, string[]>> {
+ const bySource = sourceSlugIndexes.get(engine) ?? new Map<string, Promise<SourceSlugIndex | null>>();
+ sourceSlugIndexes.set(engine, bySource);
+ const next = (bySource.get(sourceId) ?? Promise.resolve(null)).then(state => refreshSourceSlugIndex(engine, sourceId, state));
+ bySource.set(sourceId, next.catch(() => null));
+ return (await next).index;
+}
+
+/**
+ * Link endpoints by slug: every live page in the origin source, plus other
+ * sources' pages for the slugs the origin lacks or a link names elsewhere ($3).
+ * The origin read and each source's residual read use (source_id, slug).
+ */
+export const LINK_ENDPOINTS_SQL = `WITH own AS (
+ SELECT slug, source_id, type, knowledge_revision FROM pages WHERE source_id=$1 AND slug=ANY($2::text[]) AND deleted_at IS NULL),
+ elsewhere AS (SELECT array_agg(k) AS refs FROM unnest($2::text[]) k WHERE k=ANY($3::text[]) OR NOT EXISTS (SELECT 1 FROM own WHERE own.slug=k))
+ SELECT slug, source_id, type, knowledge_revision FROM own
+ UNION ALL
+ SELECT p.slug, p.source_id, p.type, p.knowledge_revision FROM elsewhere e, sources s, LATERAL (SELECT slug, source_id, type, knowledge_revision
+ FROM pages WHERE source_id=s.id AND slug=ANY(e.refs) AND deleted_at IS NULL OFFSET 0) p
+ WHERE s.id<>$1`;
+
export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,
page: Pick<ParsedPage, 'type' | 'compiled_truth' | 'timeline' | 'frontmatter'>, sourceId: string) {
- const resolver = makeResolver(engine, { mode: 'live', sourceId });
+ const resolver = makeResolver(engine, { mode: 'live', sourceId, basenameIndex: () => sourceBasenameIndex(engine, sourceId) });
const opts = { globalBasename: await isGlobalBasenameEnabled(engine), lineGrammar: await lineGrammarOptions(engine),
pack: (await loadActivePackForLocalEngine(engine, { sourceId }))?.manifest ?? null };
if (!opts.pack) return { pageKeys: [{ sourceId, slug }], attendanceComplete: true,
@@ -39,8 +88,9 @@ export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,
const retarget = <T extends { targetSlug: string; targetSourceId?: string }>(c: T): T =>
aliases.has(c.targetSlug) && (c.targetSourceId ?? sourceId) === sourceId ? { ...c, targetSlug: aliases.get(c.targetSlug)! } : c;
const keys = [...new Set([...referenced, ...initial.candidates.map(retarget).flatMap(c => [c.targetSlug, c.fromSlug ?? slug])])].sort();
- const endpointRows = await engine.executeRaw<{ slug: string; source_id: string; type: string; knowledge_revision: string }>(
- 'SELECT slug, source_id, type, knowledge_revision FROM pages WHERE slug=ANY($1::text[]) AND deleted_at IS NULL', [keys]);
+ // Another source's same-slug page only decides a slug the origin lacks (a counted cross_source drop) or one a link names there.
+ const endpointRows = await engine.executeRaw<{ slug: string; source_id: string; type: string; knowledge_revision: string }>(LINK_ENDPOINTS_SQL,
+ [sourceId, keys, [...new Set(initial.candidates.filter(c => c.targetSourceId && c.targetSourceId !== sourceId).map(c => c.targetSlug))]]);
const endpoints = indexLinkSources(endpointRows);
const policy = await loadLinkSourcePolicy(engine, sourceId);
const metadata = new Map(endpointRows.map(row => [`${row.source_id}\0${row.slug}`, row]));
diff --git a/test/attendance-retrieval.test.ts b/test/attendance-retrieval.test.ts
index 520bd823f3..e70443b0ce 100644
--- a/test/attendance-retrieval.test.ts
+++ b/test/attendance-retrieval.test.ts
@@ -5,7 +5,7 @@ import { dirname, join } from 'node:path';
import type { BrainEngine } from '../src/core/engine.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { extractLinksForSlugs, runExtract, runExtractCore } from '../src/commands/extract.ts';
-import { prepareAutomaticLinks } from '../src/core/persistence/links-preparation.ts';
+import { LINK_ENDPOINTS_SQL, prepareAutomaticLinks } from '../src/core/persistence/links-preparation.ts';
import { disposePersistenceConsumer, persistenceConsumerStatus } from '../src/core/persistence/service.ts';
import { runMaintenanceSweep } from '../src/core/sweep.ts';
import { buildRelationalArm } from '../src/core/search/relational-recall.ts';
@@ -517,7 +517,7 @@ for (const kind of testBackends()) {
let armed = true;
const race = spyOn(engine, 'executeRaw').mockImplementation(async function<T>(this: BrainEngine, sql: string, params?: unknown[], opts?: { signal?: AbortSignal }) {
const result = await executeRaw.bind(this)<T>(sql, params, opts);
- if (armed && sql === 'SELECT slug, source_id, type, knowledge_revision FROM pages WHERE slug=ANY($1::text[]) AND deleted_at IS NULL') {
+ if (armed && sql === LINK_ENDPOINTS_SQL) {
armed = false;
if (change === 'delete') await engine.softDeletePage(person, { sourceId });
else await engine.putPage(person, { type: change === 'retype' ? 'company' : 'person', title: 'Alice Example', compiled_truth: 'A concurrent edit.' }, { sourceId });
@@ -596,7 +596,7 @@ for (const kind of testBackends()) {
const snapshot = (await engine.readPageSnapshot(meeting, { sourceId }))!;
const executeRaw = engine.executeRaw;
const metadata = spyOn(engine, 'executeRaw').mockImplementation(function<T>(this: BrainEngine, sql: string, params?: unknown[], opts?: { signal?: AbortSignal }) {
- return sql === 'SELECT slug, source_id, type, knowledge_revision FROM pages WHERE slug=ANY($1::text[]) AND deleted_at IS NULL'
+ return sql === LINK_ENDPOINTS_SQL
? Promise.resolve<T[]>([]) : executeRaw.bind(this)<T>(sql, params, opts);
});
try {
diff --git a/test/link-preparation-shared-index.test.ts b/test/link-preparation-shared-index.test.ts
new file mode 100644
index 0000000000..68cfbc4e93
--- /dev/null
+++ b/test/link-preparation-shared-index.test.ts
@@ -0,0 +1,153 @@
+/**
+ * Automatic link preparation shares one basename index per engine and source
+ * and looks endpoints up in the origin source first.
+ *
+ * Protects: (1) two sources holding the same slugs, with cross-source links
+ * off, on (`link_resolution.cross_source`) and through a federated origin,
+ * keep exactly the edges, drop reasons (`cross_source` vs `missing_target`),
+ * unresolved counts and wanted rows that the per-page slug read and the
+ * slug-only endpoint query produced, for frontmatter, dir-qualified and bare
+ * wikilink, markdown, source-qualified and renamed-slug forms; (2) the shared
+ * index sees every page written after it was built (insert, rename, delete),
+ * whether or not the write went through a page write path, and is reused
+ * without a full slug read while the source is unchanged.
+ * Fails when: the endpoint lookup is restricted to the origin source (cross
+ * source drops turn into missing targets), or the index is served stale.
+ * Seams: resolveCandidateSources is wrapped to record each candidate's
+ * resolution; PGLite always, Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import * as reconciliation from '../src/core/link-reconciliation.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { prepareAutomaticLinks } from '../src/core/persistence/links-preparation.ts';
+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const resolveCandidateSources = reconciliation.resolveCandidateSources;
+const ENV = { GBRAIN_LINK_RESOLUTION_GLOBAL_BASENAME: '1', GBRAIN_LINK_RESOLUTION_CROSS_SOURCE: undefined };
+
+async function page(engine: BrainEngine, sourceId: string, slug: string, body = 'A page.', frontmatter: Record<string, unknown> = {}) {
+ await engine.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth,frontmatter) VALUES($1,$2,'note',$3,$4,$5::jsonb)`,
+ [sourceId, slug, slug.split('/').pop(), body, JSON.stringify(frontmatter)]);
+}
+
+/** Prepares and applies one page's automatic links, the way put_page's auto-link does. */
+async function derive(engine: BrainEngine, sourceId: string, slug: string) {
+ const resolutions: string[] = [];
+ const spy = spyOn(reconciliation, 'resolveCandidateSources').mockImplementation((...args) => {
+ const result = resolveCandidateSources(...args);
+ resolutions.push([args[0].targetSlug, args[0].targetSourceId ?? '', result.ok ? `${result.fromSourceId}>${result.toSourceId}` : result.reason].join(' '));
+ return result;
+ });
+ try {
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;
+ const prepared = await prepareAutomaticLinks(engine, slug, { ...snapshot.page, frontmatter: snapshot.page.frontmatter ?? {} }, sourceId);
+ const applied = await engine.transaction(async tx => { await tx.lockPageKeys(prepared.pageKeys); return prepared.apply(tx); });
+ const edges = await engine.executeRaw<{ edge: string }>(`SELECT f.source_id||':'||f.slug||' > '||t.source_id||':'||t.slug||' '||l.link_type||' '||l.link_source AS edge
+ FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id
+ WHERE (f.source_id=$1 AND f.slug=$2) OR (t.source_id=$1 AND t.slug=$2) ORDER BY 1`, [sourceId, slug]);
+ return { edges: edges.map(row => row.edge), resolutions: [...new Set(resolutions)].sort(),
+ unresolved: applied.unresolved_count, wanted: 'wanted' in applied ? applied.wanted : [] };
+ } finally { spy.mockRestore(); }
+}
+
+const ORIGIN = [
+ 'Shared topic [[topics/shared]], qualified [[beta:topics/shared]] and [[beta:topics/beta-only]].',
+ 'Beta-only by wikilink [[topics/beta-only]] and by markdown [link](topics/beta-only).',
+ 'Basename forms: [[alice-example]], [[shared]], [[bob-example]].',
+ 'Renamed: [[projects/gadget]]. Missing: [[ideas/unwritten]].',
+].join('\n');
+
+async function crossSourceFixture(engine: BrainEngine) {
+ await engine.executeRaw(`INSERT INTO sources(id,name,config) VALUES('alpha','alpha','{}'),('beta','beta','{}')`);
+ for (const source of ['alpha', 'beta']) await page(engine, source, 'topics/shared');
+ await page(engine, 'alpha', 'people/alice-example');
+ await page(engine, 'alpha', 'projects/widget');
+ await engine.executeRaw(`INSERT INTO slug_aliases(source_id,alias_slug,canonical_slug) VALUES('alpha','projects/gadget','projects/widget')`);
+ await page(engine, 'beta', 'topics/beta-only');
+ await page(engine, 'beta', 'people/bob-example');
+ await page(engine, 'alpha', 'notes/origin', ORIGIN, { related: ['topics/shared', 'topics/beta-only', 'beta:topics/beta-only', 'projects/gadget'] });
+}
+
+const EDGES = [
+ 'alpha:notes/origin > alpha:people/alice-example wikilink_basename wikilink-resolved',
+ 'alpha:notes/origin > alpha:projects/widget mentions markdown',
+ 'alpha:notes/origin > alpha:projects/widget related_to frontmatter',
+ 'alpha:notes/origin > alpha:topics/shared mentions markdown',
+ 'alpha:notes/origin > alpha:topics/shared related_to frontmatter',
+ 'alpha:notes/origin > alpha:topics/shared wikilink_basename wikilink-resolved',
+];
+const resolutions = (betaOnly: string, betaOnlyQualified: string, sharedQualified: string) => [
+ 'alice-example missing_target', 'bob-example missing_target', 'ideas/unwritten missing_target', 'people/alice-example alpha>alpha',
+ 'projects/gadget missing_target', 'projects/widget alpha>alpha', 'shared missing_target', `topics/beta-only ${betaOnly}`,
+ `topics/beta-only beta ${betaOnlyQualified}`, 'topics/shared alpha>alpha', `topics/shared beta ${sharedQualified}`,
+];
+const wanted = (...rows: string[]) => rows.map(row => ({ slug: row.split(':')[1], source_id: row.split(':')[0] }));
+const POLICIES = [
+ { name: 'cross-source links off', env: {}, federated: false, expected: { edges: EDGES, unresolved: 2,
+ resolutions: resolutions('cross_source', 'cross_source', 'cross_source'),
+ wanted: wanted('alpha:topics/beta-only', 'alpha:bob-example', 'alpha:ideas/unwritten', 'alpha:topics/beta-only') } },
+ { name: 'link_resolution.cross_source on', env: { GBRAIN_LINK_RESOLUTION_CROSS_SOURCE: '1' }, federated: false, expected: { edges: EDGES, unresolved: 2,
+ resolutions: resolutions('alpha>beta', 'alpha>beta', 'alpha>beta'),
+ wanted: wanted('alpha:bob-example', 'alpha:ideas/unwritten', 'alpha:topics/beta-only', 'beta:topics/beta-only') } },
+ { name: 'federated origin source', env: {}, federated: true, expected: { edges: EDGES, unresolved: 2,
+ resolutions: resolutions('cross_source', 'alpha>beta', 'alpha>beta'),
+ wanted: wanted('alpha:topics/beta-only', 'alpha:bob-example', 'alpha:ideas/unwritten', 'alpha:topics/beta-only', 'beta:topics/beta-only') } },
+];
+
+/** Basename-resolved targets of a page whose body is `body`, and how many full slug reads the preparation issued. */
+async function basenameTargets(engine: BrainEngine, slug: string, body: string) {
+ await engine.executeRaw(`UPDATE pages SET compiled_truth=$2 WHERE source_id='default' AND slug=$1`, [slug, body]);
+ const reads = spyOn(engine, 'executeRaw');
+ try {
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ const prepared = await prepareAutomaticLinks(engine, slug, { ...snapshot.page, frontmatter: snapshot.page.frontmatter ?? {} }, 'default');
+ return { targets: prepared.pageKeys.map(key => key.slug).filter(key => key !== slug).sort(),
+ fullReads: reads.mock.calls.filter(([sql]) => String(sql).includes('AS slugs FROM pages')).length };
+ } finally { reads.mockRestore(); }
+}
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+
+ describe(`${backend}: cross-source link preparation`, () => {
+ let engine: BrainEngine; let close: () => Promise<void>;
+ beforeAll(async () => { ({ engine, close } = await isolatedSharedSkillsEngine(databaseUrl)); await crossSourceFixture(engine); }, 120_000);
+ afterAll(async () => { await close(); });
+
+ for (const policy of POLICIES) {
+ test(`${policy.name}: edges, drop reasons, unresolved count and wanted rows`, () => withEnv({ ...ENV, ...policy.env }, async () => {
+ await engine.executeRaw(`UPDATE sources SET config=$1::jsonb WHERE id='alpha'`, [JSON.stringify(policy.federated ? { federated: true } : {})]);
+ expect(await derive(engine, 'alpha', 'notes/origin')).toEqual(policy.expected);
+ }), 60_000);
+ }
+ });
+
+ describe(`${backend}: the shared basename index`, () => {
+ let engine: BrainEngine; let close: () => Promise<void>;
+ beforeAll(async () => {
+ ({ engine, close } = await isolatedSharedSkillsEngine(databaseUrl));
+ for (const slug of ['notes/first', 'notes/second', 'notes/third', 'topics/known']) await page(engine, 'default', slug);
+ }, 120_000);
+ afterAll(async () => { await close(); });
+
+ test('a page written by this process after the index was built resolves by basename on the next preparation', () => withEnv(ENV, async () => {
+ expect(await basenameTargets(engine, 'notes/first', 'See [[known]] and [[later-target]].')).toEqual({ targets: ['topics/known'], fullReads: 1 });
+ expect(await basenameTargets(engine, 'notes/second', 'See [[known]].')).toEqual({ targets: ['topics/known'], fullReads: 0 });
+ await importFromContent(engine, 'ideas/later-target', '---\ntitle: Later target\n---\nWritten after the index.\n', { noEmbed: true });
+ expect(await basenameTargets(engine, 'notes/third', 'See [[later-target]].')).toEqual({ targets: ['ideas/later-target'], fullReads: 0 });
+ }), 60_000);
+
+ test('a write outside the page write paths, a rename and a hard delete are seen too', () => withEnv(ENV, async () => {
+ await page(engine, 'default', 'ideas/raw-insert');
+ expect(await basenameTargets(engine, 'notes/first', 'See [[raw-insert]].')).toEqual({ targets: ['ideas/raw-insert'], fullReads: 0 });
+ await engine.updateSlug('ideas/raw-insert', 'ideas/renamed-insert', { sourceId: 'default' });
+ expect(await basenameTargets(engine, 'notes/second', 'See [[raw-insert]] and [[renamed-insert]].'))
+ .toEqual({ targets: ['ideas/renamed-insert'], fullReads: 1 });
+ await engine.executeRaw(`DELETE FROM pages WHERE source_id='default' AND slug='ideas/renamed-insert'`);
+ expect(await basenameTargets(engine, 'notes/third', 'See [[renamed-insert]] and [[known]].')).toEqual({ targets: ['topics/known'], fullReads: 1 });
+ }), 60_000);
+ });
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 56369fdc79..a81520e741 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -37,6 +37,7 @@ test/harness-skills-epoch.test.ts
test/held-read-signals.test.ts
test/import-frontmatter-key-order-5158.test.ts
test/import-revision-concurrency.test.ts
+test/link-preparation-shared-index.test.ts
test/links-attendance-blocked.test.ts
test/managed-cycle-pull-upstream.test.ts
test/managed-lint.test.ts