Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip: jit-off backlink counts + getHealth, octet-bounded extract backlog

time-attackd1dc99210345
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index d63e871ce8..0452064629 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -138,6 +138,16 @@ const SYNTHESIS_OUTPUT_TYPES = new Set<string>(['atom', 'concept']);
const PAGE_DISCOVERY_BUDGET = 50;
const MIN_PAGE_CHARS_FOR_EXTRACTION = 500;
+/**
+ * `compiled_truth` holds at least `param` characters (NULL counts as empty),
+ * without detoasting most bodies: octet_length reads a TOASTed value's raw
+ * size from its header, and a character takes 1-4 bytes in every server
+ * encoding, so only a body between param and 4x param bytes is decompressed
+ * to count its characters. At 50k pages a plain length() decompressed every
+ * body (1.3 s per count).
+ */
+const minCompiledTruthChars = (param: string) =>
+ `(octet_length(p.compiled_truth) >= 4 * ${param} OR (octet_length(p.compiled_truth) >= ${param} AND length(p.compiled_truth) >= ${param}))`;
// Source pages whose frontmatter declares a `raw` payload pointer hold raw
// import data, not extractable prose. Extraction on them yields zero atoms,
// so no atom row is ever written and they re-enter discovery + the doctor
@@ -410,7 +420,7 @@ export async function discoverExtractablePages(
AND COALESCE(p.frontmatter->>'imported_from', '') <> 'markdown-greenfield'
AND COALESCE(p.frontmatter->>'dream_generated', '') <> 'true'
${RAW_SOURCE_HOLDER_EXCLUSION_SQL}
- AND length(COALESCE(p.compiled_truth, '')) >= $3
+ AND ${minCompiledTruthChars('$3')}
${MANAGED_ATOM_DISCOVERY_SQL}
${PAGE_SCAN_STATE_EXCLUSION_SQL}
${connectorExclusion}
@@ -494,7 +504,7 @@ export async function countExtractAtomsBacklog(
AND COALESCE(p.frontmatter->>'imported_from', '') <> 'markdown-greenfield'
AND COALESCE(p.frontmatter->>'dream_generated', '') <> 'true'
${RAW_SOURCE_HOLDER_EXCLUSION_SQL}
- AND length(COALESCE(p.compiled_truth, '')) >= $3
+ AND ${minCompiledTruthChars('$3')}
${MANAGED_ATOM_DISCOVERY_SQL}
${PAGE_SCAN_STATE_EXCLUSION_SQL}
${connectorExclusion}
@@ -512,7 +522,7 @@ export async function countExtractAtomsBacklog(
AND COALESCE(p.frontmatter->>'imported_from', '') <> 'markdown-greenfield'
AND COALESCE(p.frontmatter->>'dream_generated', '') <> 'true'
${RAW_SOURCE_HOLDER_EXCLUSION_SQL}
- AND length(COALESCE(p.compiled_truth, '')) >= $2
+ AND ${minCompiledTruthChars('$2')}
${MANAGED_ATOM_DISCOVERY_SQL}
${PAGE_SCAN_STATE_EXCLUSION_SQL}
${connectorExclusion}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 86185853ec..1a2fbdbb75 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -1690,7 +1690,12 @@ export class PostgresEngine implements BrainEngine {
}
async getBacklinkCounts(pageIds: number[], opts?: PageReadScope): Promise<Map<number, number>> {
- return readBacklinkCounts(this.executeRaw.bind(this), pageIds, opts);
+ // An expanded query's ~370 candidate ids push this grouped links join past jit_above_cost; at 50k pages
+ // LLVM compilation was ~140 ms of a ~140 ms statement on every call (search-settings.ts).
+ if (!pageIds.length) return readBacklinkCounts(this.executeRaw.bind(this), pageIds, opts);
+ return this.withScopedReadTransaction(undefined, undefined, tx =>
+ readBacklinkCounts(async (query, params) => Array.from(await tx.unsafe(query, params as never, { prepare: true })) as never, pageIds, opts),
+ { alwaysTransaction: true, jitOff: true });
}
async getAdjacencyBoosts(pageIds: number[], opts?: PageReadScope): Promise<Map<number, import('./types.ts').AdjacencyRow>> {
@@ -2443,7 +2448,12 @@ export class PostgresEngine implements BrainEngine {
}
async getHealth(opts?: { sourceId?: string; sourceIds?: string[] }): Promise<BrainHealth> {
- return healthImpl.getHealth(unscopedExecutor(this.engineSql, 'health: unscoped on master (EO4 inventory)'), opts, {
+ // Each health statement runs in its own JIT-off transaction: at 50k pages the aggregate and linkable-scope
+ // statements each spent ~0.5 s of ~0.56 s in LLVM compilation (search-settings.ts). The deps below stay
+ // on the pool, outside those transactions.
+ const exec: SqlExecutor = { ...this.engineSql, run: (fragment, runOpts) => this.withScopedReadTransaction(undefined, undefined,
+ tx => this.engineSqlOn(tx).run(fragment, runOpts), { alwaysTransaction: true, jitOff: true }) };
+ return healthImpl.getHealth(unscopedExecutor(exec, 'health: unscoped on master (EO4 inventory)'), opts, {
embeddingColumn: async () => (await resolveActiveEmbeddingColumnFromEngine(this, { fallbackToLegacy: true })).name,
countStalePagesForExtraction: (o) => this.countStalePagesForExtraction(o),
getConfig: (key) => this.getConfig(key),
diff --git a/test/doctor-extract-atoms-backlog.test.ts b/test/doctor-extract-atoms-backlog.test.ts
index bebf2bdba0..1c4a409176 100644
--- a/test/doctor-extract-atoms-backlog.test.ts
+++ b/test/doctor-extract-atoms-backlog.test.ts
@@ -71,6 +71,23 @@ describe('countExtractAtomsBacklog (issue #1678)', () => {
expect(await countExtractAtomsBacklog(engine)).toBe(0);
});
+ it('counts by characters at the 500-character edge for 1- to 4-byte text', async () => {
+ const bodies: Record<string, string> = {
+ 'ascii-499': 'x'.repeat(499), 'ascii-500': 'x'.repeat(500),
+ 'latin-499': '\u00e9'.repeat(499), 'latin-500': '\u00e9'.repeat(500),
+ 'han-499': '\u6f22'.repeat(499), 'han-500': '\u6f22'.repeat(500),
+ 'emoji-499': '\u{1f600}'.repeat(499), 'emoji-500': '\u{1f600}'.repeat(500),
+ 'emoji-1999-bytes': '\u{1f600}'.repeat(499) + 'xyz', 'toasted': '\u6f22 granite '.repeat(4000),
+ };
+ for (const [slug, body] of Object.entries(bodies)) await engine.putPage(`article-${slug}`, { type: 'article', title: slug, compiled_truth: body });
+ const expected = Object.values(bodies).filter(body => [...body].length >= 500).length;
+ const [reference] = await engine.executeRaw<{ cnt: number }>(
+ `SELECT COUNT(*)::int AS cnt FROM pages WHERE type = 'article' AND length(COALESCE(compiled_truth, '')) >= 500`);
+ expect(reference!.cnt).toBe(expected);
+ expect(await countExtractAtomsBacklog(engine)).toBe(expected);
+ expect(await countExtractAtomsBacklog(engine, 'default')).toBe(expected);
+ });
+
it('ignores short pages and dream-generated pages', async () => {
await engine.putPage('article-short', { type: 'article', title: 's', compiled_truth: 'too short' });
await engine.putPage('article-dream', {
diff --git a/test/e2e/jit-off-reads-postgres.test.ts b/test/e2e/jit-off-reads-postgres.test.ts
index a9fe07d329..7110e7c5c7 100644
--- a/test/e2e/jit-off-reads-postgres.test.ts
+++ b/test/e2e/jit-off-reads-postgres.test.ts
@@ -65,4 +65,36 @@ describe.skipIf(!url)('JIT off for statements past the JIT cost thresholds (#627
} finally { watch.restore(); }
}, { databaseUrl: url });
}, 180_000);
+
+ test('search backlink counts run with JIT off, alone and inside a caller transaction that keeps its setting', async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ await put(ctx, 'notes/jit-target', 'JIT target');
+ const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug='notes/jit-target'", []);
+ const watch = watchJit(/COUNT\(DISTINCT l\.from_page_id\)/);
+ try {
+ expect((await engine.getBacklinkCounts([page!.id])).get(page!.id)).toBe(0);
+ expect(watch.seen).toEqual(['off']);
+ const after = await engine.transaction(async tx => {
+ await tx.getBacklinkCounts([page!.id]);
+ return ((await tx.executeRaw("SELECT current_setting('jit') AS jit", [])) as Array<{ jit: string }>)[0]!.jit;
+ });
+ expect(watch.seen).toEqual(['off', 'off']);
+ expect(after).toBe('on');
+ expect(((await engine.executeRaw("SELECT current_setting('jit') AS jit", [])) as Array<{ jit: string }>)[0]!.jit).toBe('on');
+ } finally { watch.restore(); }
+ }, { databaseUrl: url });
+ }, 180_000);
+
+ test('getHealth runs its aggregate, linkable-scope and most-connected statements with JIT off', async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ await put(ctx, 'people/jit-person', 'JIT person');
+ const watch = watchJit(/WITH entity_pages AS|WITH linkable_pages AS MATERIALIZED|AS link_count/);
+ try {
+ expect((await engine.getHealth()).page_count).toBeGreaterThan(0);
+ expect(watch.seen.length).toBeGreaterThanOrEqual(3);
+ expect(watch.seen.every(jit => jit === 'off')).toBe(true);
+ expect(((await engine.executeRaw("SELECT current_setting('jit') AS jit", [])) as Array<{ jit: string }>)[0]!.jit).toBe('on');
+ } finally { watch.restore(); }
+ }, { databaseUrl: url });
+ }, 180_000);
});