Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(search): the index walk probes named page columns; JIT-off ratchet marker on its declaration (LHF wave 2 items 7, 1)

garrytan9e455dfe5992
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 09d88a58b0..cc5ee40b2c 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -2651,8 +2651,7 @@ export interface BrainEngine {
* transaction the option is ignored (a `SET LOCAL` there would change the
* enclosing transaction). PGLite ignores it: one in-process connection has
* no other session to wait on. `deadlineAt` (#6696, epoch ms) recomputes the bound after the pool wait.
- * `jitOff` runs the statement with `jit = off` when the server has JIT on (postgres-engine/jit-off-statement.ts); PGLite ignores it.
- * `prepare: false` plans the statement for its actual parameters on every call instead of a cached generic plan.
+ * `jitOff` runs it with `jit = off` when the server has JIT on (postgres-engine/jit-off-statement.ts; PGLite ignores it); `prepare: false` plans it for its actual parameters on every call.
*/
executeRaw<T = Record<string, unknown>>(
sql: string,
diff --git a/src/core/postgres-engine/jit-off-statement.ts b/src/core/postgres-engine/jit-off-statement.ts
index 67dc05dbd4..98d6a7bc65 100644
--- a/src/core/postgres-engine/jit-off-statement.ts
+++ b/src/core/postgres-engine/jit-off-statement.ts
@@ -29,11 +29,11 @@ type Sql = ReturnType<typeof postgres>;
const serverJit = new WeakMap<object, Promise<boolean>>();
/** Whether a statement on this pool needs the JIT-off envelope; a failed read counts as on, since the envelope is always correct. */
+// engine-sql-ok: jit is a Postgres server setting; PGLite has no JIT provider
export function needsJitOff(pool: Sql, nested: boolean): Promise<boolean> {
if (nested) return Promise.resolve(true);
let known = serverJit.get(pool);
if (!known) {
- // engine-sql-ok: jit is a Postgres server setting; PGLite has no JIT provider
known = pool.unsafe(`SELECT current_setting('jit') AS jit`).then(rows => (rows[0] as { jit?: string } | undefined)?.jit !== 'off');
serverJit.set(pool, known);
known.catch(() => { if (serverJit.get(pool) === known) serverJit.delete(pool); });
diff --git a/src/core/search/vector-statement.ts b/src/core/search/vector-statement.ts
index 5084978e89..c664040bd0 100644
--- a/src/core/search/vector-statement.ts
+++ b/src/core/search/vector-statement.ts
@@ -103,6 +103,14 @@ export interface VectorSearchStatement {
scopeScanSql?: string;
}
+/**
+ * The page columns the index walk's candidates, page filters and visibility
+ * read, probed by key per ANN row. Named, never `*`: the body columns stay out
+ * of the probe (a segmented page has no body string).
+ */
+export const INDEX_WALK_PAGE_COLUMNS = ['id', 'slug', 'source_id', 'title', 'type', 'frontmatter', 'deleted_at', 'updated_at', 'effective_date',
+ 'effective_date_source', 'trust_tier', 'body_generation', 'chunker_version', 'knowledge_revision', 'text_projection_revision'] as const;
+
/** Raw rows the index walk orders per window slot, so page filters can drop some and still fill the window. */
export const INDEX_WALK_OVERFETCH = 2;
@@ -381,7 +389,7 @@ export function buildVectorSearchStatement(input: VectorSearchStatementInput): V
-- materialize the whole scope's chunk-page join under the ANN loop
-- and rescan it per row, spilling past work_mem on large scopes (#6728).
CROSS JOIN LATERAL (SELECT * FROM content_chunks c WHERE c.id = ann.id OFFSET 0) cc
- CROSS JOIN LATERAL (SELECT * FROM pages pg WHERE pg.id = cc.page_id OFFSET 0) p
+ CROSS JOIN LATERAL (SELECT ${INDEX_WALK_PAGE_COLUMNS.map(c => `pg.${c}`).join(', ')} FROM pages pg WHERE pg.id = cc.page_id OFFSET 0) p
CROSS JOIN LATERAL (SELECT src.archived FROM sources src WHERE src.id = p.source_id OFFSET 0) s
WHERE true
${pageFilters.join('\n ')}
diff --git a/test/search/vector-statement.test.ts b/test/search/vector-statement.test.ts
index a7706ccd40..d3f90c684f 100644
--- a/test/search/vector-statement.test.ts
+++ b/test/search/vector-statement.test.ts
@@ -7,9 +7,10 @@
* timeline `stale` column.
*/
import { afterEach, describe, expect, spyOn, test } from 'bun:test';
-import { buildVectorSearchStatement, INDEX_WALK_MIN_SCOPE_SHARE, indexWalkOverfetch, SCOPE_SCAN_FIRST_MAX_CHUNKS, SCOPE_SCAN_MAX_CHUNKS, SCOPE_SCAN_MAX_SHARE, sourceScope, sourceScopeShare, vectorScopeLoader, type PageSourceStats, type VectorSearchStatementInput } from '../../src/core/search/vector-statement.ts';
+import { buildVectorSearchStatement, INDEX_WALK_MIN_SCOPE_SHARE, INDEX_WALK_PAGE_COLUMNS, indexWalkOverfetch, SCOPE_SCAN_FIRST_MAX_CHUNKS, SCOPE_SCAN_MAX_CHUNKS, SCOPE_SCAN_MAX_SHARE, sourceScope, sourceScopeShare, vectorScopeLoader, type PageSourceStats, type VectorSearchStatementInput } from '../../src/core/search/vector-statement.ts';
import { _resetVectorLegacyGuardForTests, readVectorLegacyGuard, resolveVectorLegacyGuard } from '../../src/core/search/vector-legacy-guard.ts';
import { withEnv } from '../helpers/with-env.ts';
+import { TRUST_TIERS } from '../../src/core/trust/tier.ts';
const MD5 = 'md5(cc.chunk_text)';
const indexedColumn = { name: 'embedding', type: 'vector' as const, dimensions: 1536, embeddingModel: 'openai:text-embedding-3-large' };
@@ -115,7 +116,7 @@ describe('vector index walk statement', () => {
expect(ann).toContain(`LIMIT $${stmt.innerLimitIdx + 1}::int * 2`);
const candidates = walk.slice(walk.indexOf('hnsw_candidates AS ('), walk.indexOf('scored AS ('));
expect(candidates).toContain('CROSS JOIN LATERAL (SELECT * FROM content_chunks c WHERE c.id = ann.id OFFSET 0) cc');
- expect(candidates).toContain('CROSS JOIN LATERAL (SELECT * FROM pages pg WHERE pg.id = cc.page_id OFFSET 0) p');
+ expect(candidates).toContain(`CROSS JOIN LATERAL (SELECT ${INDEX_WALK_PAGE_COLUMNS.map(c => `pg.${c}`).join(', ')} FROM pages pg WHERE pg.id = cc.page_id OFFSET 0) p`);
expect(candidates).toContain('AND p.slug != ALL($2::text[])');
expect(candidates).toContain('AND p.source_id = ANY($4::text[])');
expect(candidates).toContain(`COALESCE(p.frontmatter->>'visibility'`);
@@ -124,6 +125,21 @@ describe('vector index walk statement', () => {
expect(scoredCte(walk)).toContain('WHERE $5::text IS NULL OR hash_current');
});
+ test('the page probe projects every page column the candidates read, and no body column', () => {
+ const variants = [{}, { excludePrivate: true }, { sourceIds: ['a', 'b'] }, { exclude_slugs: ['x'] },
+ { exclude_slug_prefixes: ['x/'] }, { include_slug_prefixes: ['y/'] }, { detail: 'low' as const }, { language: 'typescript', symbolKind: 'function' }, { minTrust: TRUST_TIERS[TRUST_TIERS.length - 1] }, { suppressFlagged: true },
+ { excludePrivate: true, sourceIds: ['a', 'b'], exclude_slug_prefixes: ['x/'], detail: 'low' as const }];
+ const read = new Set<string>();
+ for (const dialect of ['postgres', 'pglite'] as const) for (const v of variants) {
+ const walk = build(v, dialect).indexWalkSql!;
+ const candidates = walk.slice(walk.indexOf('hnsw_candidates AS ('), walk.indexOf('ORDER BY ann.distance'));
+ for (const m of candidates.matchAll(/\bp\.(\w+)/g)) read.add(m[1]!);
+ }
+ expect([...read].filter(c => !(INDEX_WALK_PAGE_COLUMNS as readonly string[]).includes(c))).toEqual([]);
+ expect(INDEX_WALK_PAGE_COLUMNS).not.toContain('compiled_truth');
+ expect(INDEX_WALK_PAGE_COLUMNS).not.toContain('timeline');
+ });
+
test('exists only for the relaxed variant without a type or date filter, and binds the same parameters', () => {
expect(build({ vectorLegacyGuard: true }).indexWalkSql).toBeUndefined();
expect(build({ embeddingColumn: wideColumn }).indexWalkSql).toBeUndefined();