Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(postgres): index-walk vector search, cheap private-page rule, keyed held-page join
time-attack5ffc70dc0797
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex cd9397a316..2a0fa9825a 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -54,7 +54,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/modes-report.ts` — `buildModesReport(engine)` → `SearchModesReport` (`schema_version: 2`), the read-only dashboard behind `gbrain search modes` and the `search_modes` MCP op: `active_mode` + validity, the per-knob `resolved` attribution (`attributeKnob` over `KNOB_DESCRIPTIONS`, including the five `reranker_*` knobs), the three frozen `bundles`, `config_keys`, and `reranker_readiness` — `{model, enabled, ready, required_key, key_present, self_hosted, fix}` from `rerankerReadinessForEngine` + `describeRerankerFix` (a thrown readiness check still yields a `ready: false` verdict whose `fix` says to run `gbrain doctor`; the block never vanishes silently). `redactReadinessForRemote(report)` is what the `search_modes` op returns when `ctx.remote !== false`: `required_key`, `key_present` and `fix` are dropped and `self_hosted` is forced false — which env vars exist on the host is fingerprinting data and the fix names them; `ready` stays because it is observable anyway (reranked results carry `rerank_score`). `src/commands/search.ts:formatModesText` renders the runtime `Reranker:` line (`off (resolved) — …` / `<model> (enabled) — <KEY> present` / `<model> (enabled but NOT running) — <fix>`) and a per-bundle `reranker=… topNIn=… autocut=…` line. Pinned by `test/modes-report-reranker.test.ts`. The CLI dashboard leads with command-specific expansion: `query` is on in every mode unless explicitly disabled, while `search` is off. It discloses provider prerequisites/text flow and distinguishes retained bundle configuration from effective command behavior.-- `src/core/search/private-visibility.ts` — shared page-visibility resolver and SQL predicates. Explicit local trust disables page filtering; operator env/config opt-outs keep their semantics; failed config reads enforce privacy. `privatePagesFilterFragment` authorizes concrete page rows and `isPrivatePage` is its row-side twin: explicit `private` hides a page, absent visibility is world for ordinary pages and private for extracted atoms (`type = 'atom'`) and synthesized concepts (`type = 'concept'` with `synthesized_by`), because their origin may be a private page or transcript. The page predicate also follows derived origins: an atom whose `source_slug` page is explicitly private, and a synthesized concept with a private input atom (or an input whose origin is private) over `concept-provenance` edges, are private whatever their own field says, so a later private flip of an origin reaches derived pages before any repair. Chronicle events follow `event.depth` (fail closed). `privateSnapshotFilterFragment` is the same rule on a row's own frontmatter for `page_versions`. `effectiveVisibility(origin)` (transcript or missing origin private, page origin per the read rule) and `strictestVisibility` are used by both `extract_atoms` paths, concept synthesis and `gbrain repair visibility`. Remote publication rechecks (`persistence/page-visibility.ts`) and the alias-inject recheck in `hybrid.ts` use the same rule. Tests: `test/private-visibility.test.ts`, `test/derived-page-visibility.test.ts` (PGLite and Postgres); link origins and timeline projections use independent ID-based predicates. Legacy slug-set helpers only enumerate names; they never authorize another row's data. `ops/context.ts:readPolicyOpts` combines canonical source precedence, resolved privacy and holder permissions. Both engines filter content/history/graph/identity/analytics before limits or aggregation; current and historical visibility are checked independently while page privacy is enforced. Semantic response caching remains disabled, so visibility-key folding alone never authorizes reuse.+- `src/core/search/private-visibility.ts` — shared page-visibility resolver and SQL predicates. Explicit local trust disables page filtering; operator env/config opt-outs keep their semantics; failed config reads enforce privacy. `privatePagesFilterFragment` authorizes concrete page rows and `isPrivatePage` is its row-side twin: explicit `private` hides a page, absent visibility is world for ordinary pages and private for extracted atoms (`type = 'atom'`) and synthesized concepts (`type = 'concept'` with `synthesized_by`), because their origin may be a private page or transcript. The page predicate also follows derived origins: an atom whose `source_slug` page is explicitly private, and a synthesized concept with a private input atom (or an input whose origin is private) over `concept-provenance` edges, are private whatever their own field says, so a later private flip of an origin reaches derived pages before any repair. Chronicle events follow `event.depth` (fail closed). Declared lineage matches `derived_from` slugs with `= ANY(ARRAY(...))`, not `IN (SELECT ... jsonb_array_elements_text(...))`: same rows, but the planner priced the IN form as a 100-row semi-join per page and pushed every read carrying the rule past `jit_above_cost` (`test/e2e/private-visibility-plan-postgres.test.ts`). `privateSnapshotFilterFragment` is the same rule on a row's own frontmatter for `page_versions`. `effectiveVisibility(origin)` (transcript or missing origin private, page origin per the read rule) and `strictestVisibility` are used by both `extract_atoms` paths, concept synthesis and `gbrain repair visibility`. Remote publication rechecks (`persistence/page-visibility.ts`) and the alias-inject recheck in `hybrid.ts` use the same rule. Tests: `test/private-visibility.test.ts`, `test/derived-page-visibility.test.ts` (PGLite and Postgres); link origins and timeline projections use independent ID-based predicates. Legacy slug-set helpers only enumerate names; they never authorize another row's data. `ops/context.ts:readPolicyOpts` combines canonical source precedence, resolved privacy and holder permissions. Both engines filter content/history/graph/identity/analytics before limits or aggregation; current and historical visibility are checked independently while page privacy is enforced. Semantic response caching remains disabled, so visibility-key folding alone never authorizes reuse.- `src/core/search/projection-readiness.ts` — EXISTS probe for unsealed text revisions in the visible scope: ready, projection_pending or unknown. Cached per scope by DB generation (page clock, `pages` filenode, archive flags, no open transaction); `GBRAIN_PROJECTION_READINESS_CACHE=0` disables.diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex c03f2ec2f4..a68279d688 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -22,9 +22,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/tune-recommendations.ts` — tuning recommendations never propose enabling or tuning unavailable semantic result caching. Mode-reduction suggestions describe payload size, not expansion savings: shipped commands pin expansion independently of the bundle.-- `src/core/search/vector-pool.ts` + `vector-settings.ts` — shared bounded candidate escalation and transaction-local scan settings. SQL output limits are independent of ef_search; scoped witnesses distinguish genuine exhaustion from ANN shortfall. Postgres has one server-cancelled exact fallback; PGLite reports incompleteness instead. Settings are restored even inside caller-owned transactions. A batch carries the raw `candidatePool` (exhaustion: a short window means the index ran dry) and an optional `eligiblePool` (candidates that passed the freshness filter outside the candidate CTE); `hasMore` receives the eligible count, defaulting to the raw one. `withVectorSettings(..., iterativeMode)` sets `hnsw.iterative_scan` to the caller's mode (default `relaxed_order`, `SearchOpts.hnswIterativeScan`).+- `src/core/search/vector-pool.ts` + `vector-settings.ts` — shared bounded candidate escalation and transaction-local scan settings. SQL output limits are independent of ef_search; scoped witnesses distinguish genuine exhaustion from ANN shortfall. Postgres has one server-cancelled exact fallback; PGLite reports incompleteness instead. Settings are restored even inside caller-owned transactions. A batch carries the raw `candidatePool` (exhaustion: a short window means the index ran dry) and an optional `eligiblePool` (candidates that passed the freshness filter outside the candidate CTE); `hasMore` receives the eligible count, defaulting to the raw one. `withVectorSettings(..., iterativeMode, indexWalk)` sets `hnsw.iterative_scan` to the caller's mode (default `relaxed_order`, `SearchOpts.hnswIterativeScan`); `indexWalk` adds `INDEX_WALK_SETTINGS` (and sizes `ef_search` for the over-fetched window when scans are not iterative). `searchIndexWalk(stmt, limit, run)` runs the statement's index walk before the pool and returns its rows only when its window is full and they fill the limit; otherwise (or past its 2 s budget) both engines run the pool unchanged.-- `src/core/search/vector-statement.ts` — `buildVectorSearchStatement({ dialect, embedding, limit, offset, opts })` builds the vector-search SQL once for both engines, doctor `vector_plan` and the plan-proof E2E: `{ sql, exactSql, hasMoreSql, params, innerLimitIdx, innerLimit, indexed, relaxed }`. On an HNSW-indexed `embedding` column (relaxed variant) the candidate CTE carries only the model check; content freshness (`embedded_text_hash = md5(chunk_text)` or NULL) is projected as `hash_current` and filtered in `scored`, because Postgres cannot estimate that expression and drops the index when it sits in the CTE (#5824). Non-indexed columns, the legacy guard, `exactSql` and `hasMoreSql` keep the full guard inside. The pool row reports `candidate_pool` (raw) and `eligible_pool` (fresh). Since/until bounds are spelled per column (`effective_date`, then `updated_at`, then `created_at`) so each arm has column statistics. PGLite adds the timeline `stale` column; everything else is byte-identical across dialects. Also exports the extension-version probe and the transaction-local `statement_timeout` SQL the Postgres engine runs. Pinned by `test/search/vector-statement.test.ts`, `test/search/vector-freshness.test.ts` and `test/e2e/vector-plan-real-column-postgres.test.ts`.+- `src/core/search/vector-statement.ts` — `buildVectorSearchStatement({ dialect, embedding, limit, offset, opts })` builds the vector-search SQL once for both engines, doctor `vector_plan` and the plan-proof E2E: `{ sql, exactSql, hasMoreSql, params, innerLimitIdx, innerLimit, indexed, relaxed, indexWalkSql? }`. On an HNSW-indexed `embedding` column (relaxed variant) the candidate CTE carries only the model check; content freshness (`embedded_text_hash = md5(chunk_text)` or NULL) is projected as `hash_current` and filtered in `scored`, because Postgres cannot estimate that expression and drops the index when it sits in the CTE (#5824). Non-indexed columns, the legacy guard, `exactSql` and `hasMoreSql` keep the full guard inside. The pool row reports `candidate_pool` (raw) and `eligible_pool` (fresh). Since/until bounds are spelled per column (`effective_date`, then `updated_at`, then `created_at`) so each arm has column statistics. `indexWalkSql` (relaxed variant only, same parameters) is the statement both engines run first: `ann` orders `content_chunks` alone with the chunk-level filters over twice the window, then pages and sources are joined by key and every page filter, visibility and the private-page rule apply to those rows, keeping the nearest `innerLimit`. Run with `enable_sort = off` (`INDEX_WALK_SETTINGS`) the HNSW scan is its only ordered path; the joined statement's plan sat on a cost knife edge (TOASTed vectors cost a sequential scan too little, the HNSW estimate grows with `ef_search`, the private-page rule's subplans priced every page lookup high) and flipped to a full scan and sort at a 50-row limit or on any remote read. A full walk window selects the same rows as the joined statement (`test/search/vector-index-walk.test.ts`); a short one falls back to it. PGLite adds the timeline `stale` column; everything else is byte-identical across dialects. Also exports the extension-version probe and the transaction-local `statement_timeout` SQL the Postgres engine runs. Pinned by `test/search/vector-statement.test.ts`, `test/search/vector-freshness.test.ts` and `test/e2e/vector-plan-real-column-postgres.test.ts`.- `src/core/search/vector-legacy-guard.ts` — one-release rollback for the #5824 statement change. `readVectorLegacyGuard(cfg, env)` reports the setting (`GBRAIN_VECTOR_LEGACY_GUARD` wins over `search.vector_legacy_guard`); `resolveVectorLegacyGuard(cfg)` latches it once per process for `hybrid/request.ts`, which passes `SearchOpts.vectorLegacyGuard` to the engines (they never read config), and prints `[gbrain] vector legacy guard active` to stderr once when on. A changed setting takes effect when the owning service restarts.diff --git a/src/core/persistence/held-reads.ts b/src/core/persistence/held-reads.tsindex 5c72b77afb..1bbfa82311 100644--- a/src/core/persistence/held-reads.ts+++ b/src/core/persistence/held-reads.ts@@ -76,7 +76,7 @@ export function readHeldPages(engine: Exec, pageIds: number[], request?: object)const rows = await engine.executeRaw<{ record: GitHoldRecord; revision: string | null }>(`SELECT h.completed_keys->0 AS record, p.knowledge_revision::text AS revisionFROM op_checkpoints hJOIN sources s ON s.id=h.completed_keys->0->>'source_id' AND s.incarnation::text=h.completed_keys->0->>'incarnation'- LEFT JOIN pages p ON p.id::text=h.completed_keys->0->>'page_id'+ LEFT JOIN pages p ON p.id=(h.completed_keys->0->>'page_id')::intWHERE h.op=$1 AND (h.completed_keys->0->>'page_id')=ANY($2::text[])ORDER BY h.fingerprint`, [GIT_HOLD_OP, ids.map(String)]);const out = new Map<number, HeldPage>();diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 069d01442c..ee0708e9dd 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -73,7 +73,7 @@ import {import { logBatchRetry as auditLogBatchRetry, logBatchExhausted as auditLogBatchExhausted } from './audit/batch-retry-audit.ts';import { runMigrations } from './migrate.ts';import { supportsHnswIterativeScan } from './vector-index.ts';-import { searchVectorPool, readVectorPool } from './search/vector-pool.ts';+import { searchIndexWalk, searchVectorPool, readVectorPool, type VectorPoolAttempt } from './search/vector-pool.ts';import { beforePlannerRead, plannerRead } from './planner-stats.ts';import { buildVectorSearchStatement, VECTOR_EXTENSION_VERSION_SQL } from './search/vector-statement.ts';import { withVectorSettings } from './search/vector-settings.ts';@@ -1692,14 +1692,14 @@ export class PGLiteEngine implements BrainEngine {if (this.vectorIterativeScan === probe) this.vectorIterativeScan = undefined;throw error;}- const rows = await searchVectorPool(limit, stmt.innerLimit, iterative, stmt.indexed, 'pglite',- async ({ innerLimit: requested, maxScanTuples }) => this.db.transaction(async tx => {- return withVectorSettings(async (sql, values) => (await tx.query<Record<string, unknown>>(sql, values)).rows, iterative, requested, maxScanTuples, async () => {- const bound = [...stmt.params];- bound[stmt.innerLimitIdx] = requested;- return readVectorPool((await tx.query<Record<string, unknown>>(stmt.sql, bound)).rows);- }, undefined, opts?.hnswIterativeScan);- }),+ const attempt = ({ innerLimit: requested, maxScanTuples, indexWalk }: VectorPoolAttempt) => this.db.transaction(async tx => withVectorSettings(+ async (sql, values) => (await tx.query<Record<string, unknown>>(sql, values)).rows, iterative, requested, maxScanTuples, async () => {+ const bound = [...stmt.params];+ bound[stmt.innerLimitIdx] = requested;+ return readVectorPool((await tx.query<Record<string, unknown>>(indexWalk && stmt.indexWalkSql || stmt.sql, bound)).rows);+ }, undefined, opts?.hnswIterativeScan, indexWalk && !!stmt.indexWalkSql));+ const rows = await searchIndexWalk(stmt, limit, attempt) ?? await searchVectorPool(limit, stmt.innerLimit, iterative, stmt.indexed, 'pglite',+ attempt,async pool => {const { rows } = await this.db.query<{ eligible: number }>(stmt.hasMoreSql, [...stmt.params.slice(0, stmt.innerLimitIdx), pool + 1]);return Number(rows[0].eligible) > pool;diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex ac0ae0be74..8d33f22cab 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -65,7 +65,7 @@ import { runMigrations } from './migrate.ts';import { SCHEMA_SQL } from './schema-embedded.generated.ts';import { verifySchema } from './schema-verify.ts';import { applyChunkEmbeddingIndexPolicy, dropZombieIndexes, supportsHnswIterativeScan } from './vector-index.ts';-import { searchVectorPool, readVectorPool, remainingVectorBudget, type VectorPoolAttempt } from './search/vector-pool.ts';+import { searchIndexWalk, searchVectorPool, readVectorPool, remainingVectorBudget, type VectorPoolAttempt } from './search/vector-pool.ts';import { buildVectorSearchStatement, SET_STATEMENT_TIMEOUT_SQL, VECTOR_EXTENSION_VERSION_SQL, type VectorSearchStatement } from './search/vector-statement.ts';import { withVectorSettings } from './search/vector-settings.ts';import {@@ -1324,6 +1324,8 @@ export class PostgresEngine implements BrainEngine {// live in search/vector-statement.ts, shared with PGLite and doctor.const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding, limit, offset: opts?.offset || 0, opts });const iterative = await this.vectorIterativeScanSupported();+ const walked = await searchIndexWalk(stmt, limit, async walk => readVectorPool(await this.runVectorAttempt(stmt, walk, iterative, opts, (tx, sql, bound) => tx.unsafe(sql, bound))));+ if (walked) return walked.map(rowToSearchResult);const rows = await searchVectorPool(limit, stmt.innerLimit, iterative, stmt.indexed, 'postgres',async attempt => {const batch = await this.runVectorAttempt(stmt, attempt, iterative, opts, (tx, sql, bound) => tx.unsafe(sql, bound));@@ -1345,8 +1347,8 @@ export class PostgresEngine implements BrainEngine {}/**- * EXPLAIN (no ANALYZE) of the first ANN attempt `searchVector` runs for- * these options: the same statement, bound parameters, scoped read+ * EXPLAIN (no ANALYZE) of the first ANN attempt `searchVector` runs (the index+ * walk when there is one): the same statement, bound parameters, scoped read* transaction and scan settings, through `tx.unsafe` (the vendored driver* never prepares it). Used by doctor `vector_plan` and the plan-proof E2E.*/@@ -1354,7 +1356,7 @@ export class PostgresEngine implements BrainEngine {const limit = clampSearchLimit(opts?.limit, 20, searchLimitCap());const stmt = buildVectorSearchStatement({ dialect: 'postgres', embedding, limit, offset: opts?.offset || 0, opts });const iterative = await this.vectorIterativeScanSupported();- const attempt = { innerLimit: stmt.innerLimit, maxScanTuples: 2_000, remainingMs: 8_000, exact: false };+ const attempt = { innerLimit: stmt.innerLimit, maxScanTuples: 2_000, remainingMs: 8_000, exact: false, indexWalk: !!stmt.indexWalkSql };const [row] = await this.runVectorAttempt(stmt, attempt, iterative, opts, (tx, sql, bound) => tx.unsafe(`EXPLAIN (FORMAT JSON) ${sql}`, bound));const plan = row?.['QUERY PLAN'];return (Array.isArray(plan) ? plan[0] : plan) as Record<string, unknown>;@@ -1373,19 +1375,20 @@ export class PostgresEngine implements BrainEngine {private runVectorAttempt(stmt: VectorSearchStatement,- { innerLimit, maxScanTuples, remainingMs, exact }: VectorPoolAttempt,+ { innerLimit, maxScanTuples, remainingMs, exact, indexWalk }: VectorPoolAttempt,iterative: boolean,opts: SearchOpts | undefined,run: (tx: ReturnType<typeof postgres>, sql: string, bound: Parameters<ReturnType<typeof postgres>['unsafe']>[1]) => Promise<Record<string, unknown>[]>,): Promise<Record<string, unknown>[]> {const deadline = performance.now() + remainingMs;return this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async tx => {+ const walk = indexWalk && stmt.indexWalkSql;return withVectorSettings((sql, values) => tx.unsafe(sql, values as Parameters<typeof tx.unsafe>[1]), iterative, innerLimit, maxScanTuples, async () => {const bound = [...stmt.params];bound[stmt.innerLimitIdx] = exact ? null : innerLimit;await tx.unsafe(SET_STATEMENT_TIMEOUT_SQL, [String(remainingVectorBudget(deadline))]);- return run(tx, exact ? stmt.exactSql : stmt.sql, bound as Parameters<typeof tx.unsafe>[1]);- }, deadline, opts?.hnswIterativeScan);+ return run(tx, walk || (exact ? stmt.exactSql : stmt.sql), bound as Parameters<typeof tx.unsafe>[1]);+ }, deadline, opts?.hnswIterativeScan, !!walk);}, { alwaysTransaction: true, jitOff: true });}diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.tsindex f8498839c4..82879643af 100644--- a/src/core/search/private-visibility.ts+++ b/src/core/search/private-visibility.ts@@ -73,10 +73,10 @@ function declaredLineagePrivateSql(p: string): string {SELECT 1 FROM pages declared_originWHERE declared_origin.source_id = ${p}.source_idAND declared_origin.frontmatter->>'visibility' = 'private'- AND declared_origin.slug IN (+ AND declared_origin.slug = ANY(ARRAY(SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text(CASE WHEN jsonb_typeof(${p}.frontmatter->'derived_from') = 'array' THEN ${p}.frontmatter->'derived_from'- ELSE jsonb_build_array(${p}.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)`;+ ELSE jsonb_build_array(${p}.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)`;}/**diff --git a/src/core/search/vector-pool.ts b/src/core/search/vector-pool.tsindex 36e05690d7..86a929e7c9 100644--- a/src/core/search/vector-pool.ts+++ b/src/core/search/vector-pool.ts@@ -1,4 +1,5 @@import type { SearchOpts } from '../types.ts';+import type { VectorSearchStatement } from './vector-statement.ts';export interface VectorPoolBatch {rows: Record<string, unknown>[];@@ -14,6 +15,28 @@ export interface VectorPoolAttempt {maxScanTuples: number;remainingMs: number;exact: boolean;+ /** Run the statement's `indexWalkSql` with INDEX_WALK_SETTINGS instead of `sql`. */+ indexWalk?: boolean;+}++/**+ * Runs the statement's index walk (when it has one) before the pool. Its rows+ * answer the search when its window is full and they fill the limit; otherwise,+ * or past its 2 s budget, this returns null and the caller runs the pool.+ */+export async function searchIndexWalk(+ stmt: Pick<VectorSearchStatement, 'indexWalkSql' | 'innerLimit'>,+ limit: number,+ run: (attempt: VectorPoolAttempt) => Promise<VectorPoolBatch>,+): Promise<Record<string, unknown>[] | null> {+ if (!stmt.indexWalkSql) return null;+ try {+ const batch = await run({ innerLimit: stmt.innerLimit, maxScanTuples: 2_000, remainingMs: 2_000, exact: false, indexWalk: true });+ return batch.candidatePool >= stmt.innerLimit && batch.rows.length >= limit ? batch.rows : null;+ } catch (error) {+ if ((error as { code?: string }).code === '57014') return null;+ throw error;+ }}export function remainingVectorBudget(deadline: number): number {diff --git a/src/core/search/vector-settings.ts b/src/core/search/vector-settings.tsindex 353df3d2e4..81319c24f9 100644--- a/src/core/search/vector-settings.ts+++ b/src/core/search/vector-settings.ts@@ -1,6 +1,13 @@import { hnswEfSearchFor, HNSW_EF_SEARCH_DEFAULT } from '../vector-index.ts';import { remainingVectorBudget } from './vector-pool.ts';import { HNSW_ITERATIVE_SCAN_DEFAULT, type HnswIterativeScanMode } from './hnsw-iterative-scan.ts';+import { INDEX_WALK_OVERFETCH, INDEX_WALK_SETTINGS } from './vector-statement.ts';++/**+ * `indexWalk` adds INDEX_WALK_SETTINGS; without iterative scans it also sizes+ * `hnsw.ef_search` for the walk's over-fetched window, which a non-iterative+ * scan cannot return past.+ */export async function withVectorSettings<T>(query: (sql: string, params: unknown[]) => Promise<Record<string, unknown>[]>,@@ -10,8 +17,10 @@ export async function withVectorSettings<T>(run: () => Promise<T>,deadline?: number,iterativeMode: HnswIterativeScanMode = HNSW_ITERATIVE_SCAN_DEFAULT,+ indexWalk = false,): Promise<T> {- const settings: Record<string, string> = { 'hnsw.ef_search': String(hnswEfSearchFor(candidateLimit)) };+ const window = indexWalk && !iterative ? candidateLimit * INDEX_WALK_OVERFETCH : candidateLimit;+ const settings: Record<string, string> = { 'hnsw.ef_search': String(hnswEfSearchFor(window)), ...(indexWalk ? INDEX_WALK_SETTINGS : {}) };const defaults: Record<string, string> = { 'hnsw.ef_search': String(HNSW_EF_SEARCH_DEFAULT), 'hnsw.iterative_scan': 'off', 'hnsw.max_scan_tuples': '20000' };if (iterative) {settings['hnsw.iterative_scan'] = iterativeMode;diff --git a/src/core/search/vector-statement.ts b/src/core/search/vector-statement.tsindex 4ebc46379f..dc1d98eb28 100644--- a/src/core/search/vector-statement.ts+++ b/src/core/search/vector-statement.ts@@ -17,6 +17,21 @@* `candidate_pool` counts raw candidate rows (a full raw window escalates, a* short one means the index ran dry); `eligible_pool` counts the fresh ones* and is what `hasMore` compares against its guarded count.+ *+ * `indexWalkSql` (relaxed variant only) runs first. Even with freshness out+ * of the CTE, the joined statement's plan sits on a cost knife edge: TOASTed+ * vectors make a sequential scan look cheap, the HNSW estimate grows with+ * `hnsw.ef_search` (the window), and the private-page rule's correlated+ * subplans price every page lookup so high that the planner filters all+ * pages up front. A 25k-chunk brain flips to a full scan, sort and+ * nested-loop join at a 50-row limit or on any remote read. The index walk+ * orders `content_chunks` alone (`ann`, chunk-level filters only, twice the+ * window), then joins pages and sources by key and applies every page filter+ * to those rows, keeping the nearest `innerLimit` eligible ones: the same set+ * the joined statement selects whenever that many survive. Callers run it+ * with sorting disabled so the HNSW scan is the only ordered path, accept it+ * when its window is full, and otherwise run the joined statement as before,+ * whose plans stay with the planner for selective filters.*/import type { SearchOpts } from '../types.ts';import { hnswIndexExpected } from '../vector-index.ts';@@ -49,8 +64,19 @@ export interface VectorSearchStatement {indexed: boolean;/** True when freshness moved out of the candidate CTE (indexed `embedding`, legacy guard off). */relaxed: boolean;+ /** Index-walk statement (relaxed variant only), same parameters as `sql`; trusted when `candidate_pool` reaches the window. */+ indexWalkSql?: string;}+/** 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;++/**+ * Session settings for the index-walk attempt: with sorting disabled, the+ * HNSW scan is the only path that delivers `ann` in distance order.+ */+export const INDEX_WALK_SETTINGS: Readonly<Record<string, string>> = { enable_sort: 'off' };+export function buildVectorSearchStatement(input: VectorSearchStatementInput): VectorSearchStatement {const { dialect, limit, offset, opts } = input;const resolvedCol = normalizeEngineColumn(opts?.embeddingColumn);@@ -65,13 +91,16 @@ export function buildVectorSearchStatement(input: VectorSearchStatementInput): Vconst params: unknown[] = ['[' + Array.from(input.embedding).join(',') + ']'];const bind = (value: unknown) => { params.push(value); return `$${params.length}`; };const filters: string[] = [];- if (opts?.detail === 'low') filters.push(`AND cc.chunk_source = 'compiled_truth'`);- if (opts?.type) filters.push(`AND p.type = ${bind(opts.type)}`);+ const chunkFilters: string[] = [];+ const pageFilters: string[] = [];+ const filter = (sql: string, onChunk = false) => { filters.push(sql); (onChunk ? chunkFilters : pageFilters).push(sql); };+ if (opts?.detail === 'low') filter(`AND cc.chunk_source = 'compiled_truth'`, true);+ if (opts?.type) filter(`AND p.type = ${bind(opts.type)}`);// v0.33: multi-type filter for whoknows, AND-applied with `type`.- if (opts?.types && opts.types.length > 0) filters.push(`AND p.type = ANY(${bind(opts.types)}::text[])`);- if (opts?.exclude_slugs?.length) filters.push(`AND p.slug != ALL(${bind(opts.exclude_slugs)}::text[])`);- if (opts?.language) filters.push(`AND cc.language = ${bind(opts.language)}`);- if (opts?.symbolKind) filters.push(`AND cc.symbol_type = ${bind(opts.symbolKind)}`);+ if (opts?.types && opts.types.length > 0) filter(`AND p.type = ANY(${bind(opts.types)}::text[])`);+ if (opts?.exclude_slugs?.length) filter(`AND p.slug != ALL(${bind(opts.exclude_slugs)}::text[])`);+ if (opts?.language) filter(`AND cc.language = ${bind(opts.language)}`, true);+ if (opts?.symbolKind) filter(`AND cc.symbol_type = ${bind(opts.symbolKind)}`, true);// v0.29.1: since/until filter by effective date, with import-time fallback.// Spelled per column rather than as COALESCE(effective_date, updated_at,// created_at) <op> $n: same rows, but each arm has column statistics. The@@ -81,12 +110,12 @@ export function buildVectorSearchStatement(input: VectorSearchStatementInput): Vconst bound = `${bind(value)}::text::timestamptz`;return `AND (p.effective_date ${op} ${bound} OR (p.effective_date IS NULL AND (p.updated_at ${op} ${bound} OR (p.updated_at IS NULL AND p.created_at ${op} ${bound}))))`;};- if (opts?.afterDate) filters.push(dateBound(opts.afterDateInclusive ? '>=' : '>', opts.afterDate));- if (opts?.beforeDate) filters.push(dateBound(opts.beforeDateInclusive ? '<=' : '<', opts.beforeDate));+ if (opts?.afterDate) filter(dateBound(opts.afterDateInclusive ? '>=' : '>', opts.afterDate));+ if (opts?.beforeDate) filter(dateBound(opts.beforeDateInclusive ? '<=' : '<', opts.beforeDate));// v0.34.1 (#861): source isolation in the INNER CTE narrows the HNSW// candidate set before re-rank. Array form wins over scalar.- if (opts?.sourceIds && opts.sourceIds.length > 0) filters.push(`AND p.source_id = ANY(${bind(opts.sourceIds)}::text[])`);- else if (opts?.sourceId) filters.push(`AND p.source_id = ${bind(opts.sourceId)}`);+ if (opts?.sourceIds && opts.sourceIds.length > 0) filter(`AND p.source_id = ANY(${bind(opts.sourceIds)}::text[])`);+ else if (opts?.sourceId) filter(`AND p.source_id = ${bind(opts.sourceId)}`);let modelParam: string | undefined;if (resolvedCol.name === 'embedding') modelParam = bind(resolvedCol.embeddingModel || null);@@ -119,25 +148,57 @@ export function buildVectorSearchStatement(input: VectorSearchStatementInput): V${visibilityClause}`;const freshFilter = `${modelParam}::text IS NULL OR hash_current`;- const statement = (exact: boolean) => {- const relax = relaxed && !exact;- return `- WITH hnsw_candidates AS (- SELECT- p.slug, p.id as page_id, p.title, p.type, p.source_id,${dialect === 'pglite' ? ' p.updated_at,' : ''}+ const candidateColumns = `p.slug, p.id as page_id, p.title, p.type, p.source_id,${dialect === 'pglite' ? ' p.updated_at,' : ''}p.effective_date, p.effective_date_source,CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULLTHEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id,CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULLTHEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject,cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,- (${unverifiedExtractionFragment('p')}) AS unverified_stub,${relax ? `+ (${unverifiedExtractionFragment('p')}) AS unverified_stub,`;++ const joinedCandidates = (exact: boolean) => {+ const relax = relaxed && !exact;+ return `+ WITH hnsw_candidates AS (+ SELECT+ ${candidateColumns}${relax ? `${hashCurrent} AS hash_current,` : ''}1 - (cc.${col} <=> ${castSql}) AS raw_score${candidateFrom(relax ? relaxedGeneration : guardedGeneration)}ORDER BY ${exact ? '(' : ''}cc.${col} <=> ${castSql}${exact ? ') + 0' : ''}LIMIT ${innerLimitParam}+ ),`;+ };++ const indexWalkCandidates = `+ WITH ann AS MATERIALIZED (+ SELECT cc.id, cc.${col} <=> ${castSql} AS distance+ FROM content_chunks cc+ WHERE cc.${col} IS NOT NULL ${modalityFilter}+ ${chunkFilters.join('\n ')}+ ${relaxedGeneration}+ ORDER BY cc.${col} <=> ${castSql}+ LIMIT ${innerLimitParam}::int * ${INDEX_WALK_OVERFETCH}),+ hnsw_candidates AS (+ SELECT+ ${candidateColumns}+ ${hashCurrent} AS hash_current,+ 1 - ann.distance AS raw_score+ FROM ann+ JOIN content_chunks cc ON cc.id = ann.id+ JOIN pages p ON p.id = cc.page_id+ CROSS JOIN LATERAL (SELECT src.archived FROM sources src WHERE src.id = p.source_id OFFSET 0) s+ WHERE true+ ${pageFilters.join('\n ')}+ ${hardExcludeClause}+ ${visibilityClause}+ ORDER BY ann.distance, ann.id+ LIMIT ${innerLimitParam}::int+ ),`;++ const statement = (candidates: string, relax: boolean) => `${candidates}-- score computed as a select-list expr (NOT in the inner ORDER BY, which-- must stay pure-distance so the HNSW index is usable).scored AS (@@ -170,11 +231,10 @@ export function buildVectorSearchStatement(input: VectorSearchStatementInput): VLEFT JOIN page_results ON trueORDER BY score DESC NULLS LAST, page_id ASC, chunk_id ASC`;- };return {- sql: statement(false),- exactSql: statement(true),+ sql: statement(joinedCandidates(false), relaxed),+ exactSql: statement(joinedCandidates(true), false),hasMoreSql: `SELECT count(*)::int AS eligible FROM (SELECT 1 ${candidateFrom(guardedGeneration)} AND $1::text IS NOT NULL LIMIT $${innerLimitIdx + 1}) eligible`,@@ -183,5 +243,6 @@ export function buildVectorSearchStatement(input: VectorSearchStatementInput): VinnerLimit,indexed,relaxed,+ ...(relaxed ? { indexWalkSql: statement(indexWalkCandidates, true) } : {}),};}diff --git a/test/e2e/private-visibility-plan-postgres.test.ts b/test/e2e/private-visibility-plan-postgres.test.tsnew file mode 100644index 0000000000..9dac0d9471--- /dev/null+++ b/test/e2e/private-visibility-plan-postgres.test.ts@@ -0,0 +1,99 @@+/**+ * The private-page rule (privatePagesFilterFragment) as Postgres plans it.+ *+ * Declared lineage matches `derived_from` slugs with `= ANY(ARRAY(...))`+ * instead of `IN (SELECT ... jsonb_array_elements_text(...))`. The two forms+ * select the same pages, but the planner priced the IN form as a 100-row+ * semi-join per page, so every read carrying the rule (list_pages, backlink+ * counts, search legs for remote callers) cost about 1,500 per page and+ * crossed `jit_above_cost`: Postgres then spent tens of milliseconds+ * compiling a statement that runs in under one.+ *+ * 1. both forms return the same pages, in the same order, over a fixture+ * holding every rule (explicit private, atoms with a private origin,+ * synthesized concepts, `derived_from` as string, array and `.md`, a+ * missing and a cross-source `derived_from`, life-chronicle events);+ * 2. precondition: the IN form's estimated cost per page is above+ * `jit_above_cost / 500`, so any read that checks 500 pages compiles;+ * 3. the emitted form's cost per page is below it.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts';+import { privatePagesFilterFragment } from '../../src/core/search/private-visibility.ts';++const PAGES = 3_000;++/** The pre-change declared-lineage spelling, rebuilt from the emitted fragment. */+function inSubqueryForm(fragment: string): string {+ const out = fragment.replaceAll('.slug = ANY(ARRAY(\n SELECT', '.slug IN (\n SELECT')+ .replaceAll('AS declared(slug)))) ELSE false END', 'AS declared(slug))) ELSE false END');+ if (out === fragment || out.includes('ANY(ARRAY(')) throw new Error('declared-lineage spelling changed; update inSubqueryForm');+ return out;+}++async function planCost(sql: string): Promise<number> {+ const [row] = await getEngine().executeRaw<{ 'QUERY PLAN': Array<{ Plan: { 'Total Cost': number } }> }>(`EXPLAIN (FORMAT JSON) ${sql}`);+ return row['QUERY PLAN'][0].Plan['Total Cost'];+}++(hasDatabase() ? describe : describe.skip)('private-page rule plan cost (Postgres)', () => {+ beforeAll(async () => {+ await setupDB();+ const engine = getEngine();+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('side', 'side') ON CONFLICT (id) DO NOTHING`);+ // Page i: offset i % 23 picks the rule; i - k names a page in the same block.+ await engine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, frontmatter)+ SELECT 'notes/n-' || i, CASE WHEN i % 23 = 9 THEN 'side' ELSE 'default' END,+ CASE i % 23 WHEN 2 THEN 'atom' WHEN 3 THEN 'atom' WHEN 4 THEN 'concept' WHEN 10 THEN 'event' WHEN 11 THEN 'event' WHEN 12 THEN 'event' ELSE 'note' END,+ 'Note ' || i, 'body',+ CASE i % 23+ WHEN 0 THEN '{"visibility": "private"}'::jsonb+ WHEN 1 THEN '{"visibility": "world"}'::jsonb+ WHEN 2 THEN jsonb_build_object('source_slug', 'notes/n-' || (i - 2), 'visibility', 'world')+ WHEN 3 THEN jsonb_build_object('source_slug', 'notes/n-' || (i - 2), 'visibility', 'world')+ WHEN 4 THEN '{"synthesized_by": "dream"}'::jsonb+ WHEN 5 THEN jsonb_build_object('derived_from', 'notes/n-' || (i - 5))+ WHEN 6 THEN jsonb_build_object('derived_from', jsonb_build_array('notes/n-' || (i - 5), 'notes/n-' || (i - 6)))+ WHEN 7 THEN jsonb_build_object('derived_from', 'notes/n-' || (i - 7) || '.md')+ WHEN 8 THEN jsonb_build_object('derived_from', jsonb_build_array('notes/n-' || (i - 7), 'notes/never-written'))+ WHEN 9 THEN jsonb_build_object('derived_from', 'notes/n-' || (i - 9))+ WHEN 10 THEN jsonb_build_object('captured_via', 'life-chronicle:meeting', 'event', jsonb_build_object('depth', 'notes/n-' || (i - 10)))+ WHEN 11 THEN jsonb_build_object('captured_via', 'life-chronicle:meeting', 'event', jsonb_build_object('depth', 'notes/n-' || (i - 6)))+ WHEN 12 THEN jsonb_build_object('captured_via', 'life-chronicle:meeting', 'event', jsonb_build_object('depth', 'notes/n-' || (i - 11)))+ ELSE '{}'::jsonb END+ FROM generate_series(0, ${PAGES - 1}) i`);+ await engine.executeRaw('ANALYZE pages');+ await engine.executeRaw('ANALYZE sources');+ }, 120_000);++ afterAll(async () => { await teardownDB(); });++ test('the ANY(ARRAY) and IN spellings hide exactly the same pages', async () => {+ const engine = getEngine();+ const fragment = privatePagesFilterFragment('p');+ const read = (predicate: string) => engine.executeRaw<{ slug: string }>(`SELECT p.slug FROM pages p WHERE ${predicate} ORDER BY p.slug`);+ const emitted = (await read(fragment)).map(row => row.slug);+ const before = (await read(inSubqueryForm(fragment))).map(row => row.slug);+ expect(emitted).toEqual(before);+ const hidden = PAGES - emitted.length;+ // Every rule fires on this fixture: explicit, atom origin, concept, string/array/.md lineage, events.+ expect(hidden).toBeGreaterThanOrEqual(Math.floor(PAGES / 23) * 8);+ for (const offset of [0, 2, 4, 5, 6, 7, 10, 11]) expect(emitted).not.toContain(`notes/n-${23 + offset}`);+ for (const offset of [1, 3, 8, 9, 12]) expect(emitted).toContain(`notes/n-${23 + offset}`);+ });++ test('the rule costs the planner little enough per page that a 500-page read stays under jit_above_cost', async () => {+ const engine = getEngine();+ const [{ jit_above_cost }] = await engine.executeRaw<{ jit_above_cost: string }>(`SELECT current_setting('jit_above_cost') AS jit_above_cost`);+ const budget = Number(jit_above_cost) / 500;+ const fragment = privatePagesFilterFragment('p');+ const scan = (predicate: string) => planCost(`SELECT count(*) FROM pages p WHERE ${predicate}`);+ const base = await scan('true');+ const perPage = async (predicate: string) => ((await scan(predicate)) - base) / PAGES;+ const before = await perPage(inSubqueryForm(fragment));+ const after = await perPage(fragment);+ console.info(JSON.stringify({ metric: 'private-visibility-cost-per-page', before, after, budget }));+ if (before <= budget) throw new Error(`Precondition failed: the IN spelling already costs ${before} per page (budget ${budget}); this check cannot discriminate.`);+ expect(after).toBeLessThan(budget);+ });+});diff --git a/test/e2e/vector-plan-real-column-postgres.test.ts b/test/e2e/vector-plan-real-column-postgres.test.tsindex ca3cf7fc20..1fe51165bf 100644--- a/test/e2e/vector-plan-real-column-postgres.test.ts+++ b/test/e2e/vector-plan-real-column-postgres.test.ts@@ -8,9 +8,10 @@* 1. precondition: the pre-fix guard placement (the legacy-guard variant,* byte-for-byte the guard 3a284ae emitted) does NOT use the index on this* fixture, so an undersized fixture fails loudly instead of passing;- * 2. the statement searchVector emits now uses idx_chunks_embedding, through- * the same tx.unsafe path, scoped read transaction and scan settings- * (PostgresEngine.explainVectorSearch), across a filter matrix incl. RLS;+ * 2. the statement searchVector emits first (the index walk) uses+ * idx_chunks_embedding, through the same tx.unsafe path, scoped read+ * transaction and scan settings (PostgresEngine.explainVectorSearch),+ * across a filter matrix incl. remote readers, wide windows and RLS;* 3. stale-heavy pools escalate or fall back exactly instead of underfilling;* 4. doctor `vector_plan` reports each outcome.*@@ -139,7 +140,7 @@ function axis(d: number): Float32Array {get(target, key) {if (key !== 'unsafe') return Reflect.get(target, key);return (sql: string, params: unknown[]) => {- if (sql.includes('WITH hnsw_candidates')) statements.push({ sql, params: [...params] });+ if (sql.includes('WITH hnsw_candidates') || sql.includes('WITH ann AS MATERIALIZED')) statements.push({ sql, params: [...params] });return target.unsafe(sql, params);};},@@ -222,7 +223,7 @@ function axis(d: number): Float32Array {const [explained, searched] = statements.slice(start);expect(explained.sql).toBe(`EXPLAIN (FORMAT JSON) ${searched.sql}`);expect(explained.params).toEqual(searched.params);- expect(searched.sql).toBe(buildVectorSearchStatement({ dialect: 'postgres', embedding: query, limit: 20, offset: 0, opts: { embeddingColumn: column } }).sql);+ expect(searched.sql).toBe(buildVectorSearchStatement({ dialect: 'postgres', embedding: query, limit: 20, offset: 0, opts: { embeddingColumn: column } }).indexWalkSql!);// Diagnostic only: the generic plan (no parameter values), PG16+.const generic = await engine.executeRaw(`EXPLAIN (GENERIC_PLAN, FORMAT JSON) ${searched.sql}`).catch(error => String(error));@@ -235,6 +236,9 @@ function axis(d: number): Float32Array {['sourceIds covering most rows', { sourceIds: ['default', 'side'] }],['common type', { type: 'note' }],['wide date range', { afterDate: '2000-01-01', beforeDate: '2100-01-01' }],+ ['remote reader (private-page rule)', { excludePrivate: true }],+ ['remote reader, 50-row limit', { excludePrivate: true, limit: 50 }],+ ['200-row limit', { limit: 200 }],];for (const [label, opts] of matrix) {const plan = await engine.explainVectorSearch(query, { limit: 20, embeddingColumn: column, ...opts });diff --git a/test/held-read-signals.test.ts b/test/held-read-signals.test.tsindex 2169e2d0e0..41290773c8 100644--- a/test/held-read-signals.test.ts+++ b/test/held-read-signals.test.ts@@ -21,7 +21,7 @@ import { performSync } from '../src/commands/sync.ts';import { NOTICE_CODES } from '../src/core/error-registry.ts';import { PER_CALL_NOTICE_CODES } from '../src/core/notice-ledger.ts';import { readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';-import { readHeldCoverage } from '../src/core/persistence/held-reads.ts';+import { readHeldCoverage, readHeldPages } from '../src/core/persistence/held-reads.ts';import { makeGitFixture } from './helpers/git-fixture.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { testBackends } from './helpers/test-backends.ts';@@ -110,6 +110,30 @@ async function countHoldReads<T>(run: () => Promise<T>): Promise<{ value: T; reafinally { delete (target as Partial<typeof target>).executeRaw; }}+test('the held-page read joins each hold to its page by key, not by a text cast of every page id', () => eachEngine(async () => {+ const s = await heldSource();+ const [page] = await engine.executeRaw<{ id: number; revision: string }>(`SELECT id, knowledge_revision::text AS revision FROM pages WHERE source_id=$1 AND slug='notes/a'`, [s.id]);+ const target = engine as unknown as { executeRaw: (this: unknown, sql: string, params?: unknown[]) => Promise<unknown> };+ const inherited = Object.getPrototypeOf(engine).executeRaw as typeof target.executeRaw;+ let read: { sql: string; params: unknown[] } | undefined;+ target.executeRaw = function (sql, params) {+ if (Array.isArray(params) && params[0] === 'sync-hold' && sql.includes('LEFT JOIN pages p')) read = { sql, params };+ return inherited.call(this, sql, params);+ };+ let held: Awaited<ReturnType<typeof readHeldPages>>;+ try { held = await readHeldPages(engine, [page.id, page.id + 100_000]); }+ finally { delete (target as Partial<typeof target>).executeRaw; }+ expect([...held.keys()]).toEqual([page.id]);+ expect(held.get(page.id)).toMatchObject({ revision: page.revision, record: { path: 'notes/a.md', page_id: page.id } });+ const plan = await engine.transaction(async tx => {+ await tx.executeRaw('SET LOCAL enable_seqscan = off');+ return tx.executeRaw<Record<string, string>>(`EXPLAIN ${read!.sql}`, read!.params);+ });+ const text = plan.map(row => Object.values(row)[0]).join('\n');+ expect(text).toContain('pages_pkey');+ expect(text).not.toMatch(/Seq Scan on pages/);+}), 120_000);+test('get_page carries file_held with the path for local callers and without it for remote ones; it clears once the file imports', () => eachEngine(async () => {const s = await heldSource();const local = await getPage.handler(call(s.id, false).ctx, { slug: 'notes/a' }) as Record<string, any>;diff --git a/test/search/vector-index-walk.test.ts b/test/search/vector-index-walk.test.tsnew file mode 100644index 0000000000..252e6da2b4--- /dev/null+++ b/test/search/vector-index-walk.test.ts@@ -0,0 +1,141 @@+/**+ * The vector index walk (`indexWalkSql`) returns exactly what the joined+ * candidate statement returns whenever its window is full, and searchVector+ * falls back to the joined statement when page filters leave the walk short.+ *+ * Fixture (PGLite, 8-dim): three sources (one archived), five page types,+ * pages that the private-page rule hides (explicit `visibility: private`,+ * atoms, synthesized concepts, `derived_from` a private page), quarantined+ * and soft-deleted pages, stale chunk hashes, and three chunks per page. Both+ * statements run with index scans disabled, so each computes its window+ * exactly and the comparison is row-for-row, order included. The Postgres+ * plan proof is test/e2e/vector-plan-real-column-postgres.test.ts.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { buildVectorSearchStatement } from '../../src/core/search/vector-statement.ts';+import type { SearchOpts } from '../../src/core/types.ts';++const MODEL = 'test:vector-index-walk';+const DIM = 8;+const column = { name: 'embedding', type: 'vector' as const, dimensions: DIM, embeddingModel: MODEL };+const PAGES = 600;++let engine: PGLiteEngine;++function vec(seed: number): Float32Array {+ return Float32Array.from({ length: DIM }, (_, d) => Math.sin(seed * (d + 1) * 0.37 + d));+}++/** Rows a statement returns with its window computed exactly (no index scans). */+async function exactRows(sql: string, params: unknown[]) {+ await engine.executeRaw('SET enable_indexscan = off');+ try {+ return await engine.executeRaw<Record<string, unknown>>(sql, params);+ } finally {+ await engine.executeRaw('RESET enable_indexscan');+ }+}++const shape = (rows: Record<string, unknown>[]) => rows.filter(row => row.page_id != null)+ .map(row => [row.slug, row.source_id, row.chunk_id, Number(row.score).toFixed(9)]);++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.executeRaw('DROP INDEX IF EXISTS idx_chunks_embedding');+ await engine.executeRaw(`ALTER TABLE content_chunks ALTER COLUMN embedding TYPE vector(${DIM})`);+ await engine.executeRaw('CREATE INDEX idx_chunks_embedding ON content_chunks USING hnsw (embedding vector_cosine_ops)');+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('side', 'side'), ('gone', 'gone') ON CONFLICT (id) DO NOTHING`);+ await engine.executeRaw(`UPDATE sources SET archived = true WHERE id = 'gone'`);+ // Page i sits in block i / 20, which sets its source; inside a block,+ // offsets 0-3 are hidden from remote readers by four private-page rules+ // (offset 3 is `derived_from` offset 0 of the same block and source).+ await engine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, frontmatter, knowledge_revision, text_projection_revision, chunker_version, deleted_at)+ SELECT 'notes/n-' || i,+ CASE WHEN (i / 20) % 5 = 0 THEN 'side' WHEN (i / 20) % 7 = 3 THEN 'gone' ELSE 'default' END,+ CASE WHEN i % 20 = 1 THEN 'atom' WHEN i % 20 = 2 THEN 'concept' ELSE (ARRAY['note', 'person', 'company', 'meeting', 'note'])[1 + i % 5] END,+ 'Note ' || i, 'body',+ CASE WHEN i % 20 = 0 THEN '{"visibility": "private"}'::jsonb+ WHEN i % 20 = 2 THEN '{"synthesized_by": "dream"}'::jsonb+ WHEN i % 20 = 3 THEN jsonb_build_object('derived_from', 'notes/n-' || (i - 3))+ WHEN i % 31 = 0 THEN '{"quarantine": {"reason": "junk_pattern"}}'::jsonb+ ELSE '{}'::jsonb END,+ '00000000-0000-4000-8000-000000000001'::uuid, '00000000-0000-4000-8000-000000000001'::uuid, 4,+ CASE WHEN i % 37 = 0 THEN now() END+ FROM generate_series(0, ${PAGES - 1}) i`);+ const pages = await engine.executeRaw<{ id: number; slug: string }>(`SELECT id, slug FROM pages ORDER BY id`);+ const ids: number[] = [], idx: number[] = [], texts: string[] = [], hashes: (string | null)[] = [], vectors: string[] = [];+ for (const page of pages) {+ const n = Number(page.slug.split('-').at(-1));+ for (let c = 0; c < 3; c++) {+ ids.push(page.id); idx.push(c);+ texts.push(`chunk ${n} ${c}`);+ hashes.push(n % 13 === 0 && c === 0 ? 'stale-hash' : null);+ vectors.push(`[${Array.from(vec(n * 3 + c)).join(',')}]`);+ }+ }+ await engine.executeRaw(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, model, embedded_text_hash, embedding)+ SELECT u.page_id, u.ci, u.t, 'compiled_truth', $6, COALESCE(u.h, md5(u.t)), u.v::vector+ FROM unnest($1::int[], $2::int[], $3::text[], $4::text[], $5::text[]) AS u(page_id, ci, t, h, v)`, [ids, idx, texts, hashes, vectors, MODEL]);+ await engine.executeRaw('ANALYZE');+}, 120_000);++afterAll(async () => {+ await engine.disconnect();+});++describe('vector index walk (PGLite)', () => {+ const matrix: Array<[string, SearchOpts]> = [+ ['default scope', {}],+ ['remote reader (private-page rule)', { excludePrivate: true }],+ ['remote reader, limit 50', { excludePrivate: true, limit: 50 }],+ ['granted sources', { excludePrivate: true, sourceIds: ['default', 'side'] }],+ ['common types', { types: ['note', 'person', 'company'] }],+ ['date range and slug exclusion', { afterDate: '2000-01-01', beforeDate: '2100-01-01', exclude_slugs: ['notes/n-5'] }],+ ['compiled truth only', { detail: 'low', excludePrivate: true }],+ ];++ for (const [label, opts] of matrix) {+ test(`${label}: a full walk window returns the joined statement's rows in the same order`, async () => {+ for (const seed of [11, 202, 3003]) {+ const stmt = buildVectorSearchStatement({ dialect: 'pglite', embedding: vec(seed), limit: opts.limit ?? 20, offset: 0, opts: { embeddingColumn: column, ...opts } });+ expect(stmt.indexWalkSql).toBeDefined();+ const params = [...stmt.params];+ const walked = await exactRows(stmt.indexWalkSql!, params);+ const joined = await exactRows(stmt.sql, params);+ expect(Number(walked[0].candidate_pool)).toBe(stmt.innerLimit);+ expect(shape(walked).length).toBe(opts.limit ?? 20);+ expect(shape(walked)).toEqual(shape(joined));+ expect([walked[0].candidate_pool, walked[0].eligible_pool]).toEqual([joined[0].candidate_pool, joined[0].eligible_pool]);+ }+ });+ }++ test('the walk keeps every page filter: no hidden, deleted, archived or out-of-scope page reaches results', async () => {+ const hits = await engine.searchVector(vec(42), { limit: 50, embeddingColumn: column, excludePrivate: true, sourceIds: ['default', 'side'] });+ expect(hits).toHaveLength(50);+ for (const hit of hits) {+ const n = Number(hit.slug.split('-').at(-1));+ expect([0, 1, 2, 3]).not.toContain(n % 20);+ expect(n % 37 === 0 || n % 31 === 0 || hit.source_id === 'gone').toBe(false);+ }+ });++ test('a selective filter leaves the walk short and searchVector returns the joined statement result', async () => {+ const opts: SearchOpts = { limit: 10, embeddingColumn: column, sourceId: 'side', excludePrivate: true };+ const stmt = buildVectorSearchStatement({ dialect: 'pglite', embedding: vec(7), limit: 10, offset: 0, opts });+ const walked = await exactRows(stmt.indexWalkSql!, [...stmt.params]);+ expect(Number(walked[0].candidate_pool)).toBeLessThan(stmt.innerLimit);+ const joined = await exactRows(stmt.sql, [...stmt.params]);+ await engine.executeRaw('SET enable_indexscan = off');+ try {+ const hits = await engine.searchVector(vec(7), opts);+ expect(hits).toHaveLength(10);+ expect(hits.map(hit => hit.slug)).toEqual(shape(joined).map(row => String(row[0])));+ } finally {+ await engine.executeRaw('RESET enable_indexscan');+ }+ });+});diff --git a/test/search/vector-statement.test.ts b/test/search/vector-statement.test.tsindex babea9b026..92902f0d23 100644--- a/test/search/vector-statement.test.ts+++ b/test/search/vector-statement.test.ts@@ -96,6 +96,46 @@ describe('vector statement freshness placement (#5824)', () => {});});+describe('vector index walk statement', () => {+ /** The `ann` CTE: the only part that touches the HNSW index. */+ function annCte(sql: string): string {+ return sql.slice(sql.indexOf('WITH ann AS MATERIALIZED ('), sql.indexOf('hnsw_candidates AS ('));+ }++ test('orders content_chunks alone and applies page filters and visibility after the key joins', () => {+ const stmt = build({ type: 'note', sourceIds: ['a'], afterDate: '2026-01-01', language: 'typescript', detail: 'low', excludePrivate: true });+ const walk = stmt.indexWalkSql!;+ const ann = annCte(walk);+ expect(ann).toContain('FROM content_chunks cc');+ expect(ann).not.toMatch(/JOIN|pages|sources|p\./);+ expect(ann).toContain(`AND cc.chunk_source = 'compiled_truth'`);+ expect(ann).toContain('AND cc.language = $3');+ expect(ann).toContain('AND (cc.model=$6 OR');+ expect(ann).not.toContain(MD5);+ 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('JOIN content_chunks cc ON cc.id = ann.id');+ expect(candidates).toContain('JOIN pages p ON p.id = cc.page_id');+ expect(candidates).toContain('AND p.type = $2');+ expect(candidates).toContain('AND p.source_id = ANY($5::text[])');+ expect(candidates).toContain(`COALESCE(p.frontmatter->>'visibility'`);+ expect(candidates).toContain('ORDER BY ann.distance, ann.id');+ expect(candidates).toContain(`LIMIT $${stmt.innerLimitIdx + 1}::int`);+ expect(scoredCte(walk)).toContain('WHERE $6::text IS NULL OR hash_current');+ });++ test('exists only for the relaxed variant and binds the same parameters', () => {+ expect(build({ vectorLegacyGuard: true }).indexWalkSql).toBeUndefined();+ expect(build({ embeddingColumn: wideColumn }).indexWalkSql).toBeUndefined();+ const pg = build({ excludePrivate: true });+ const lite = build({ excludePrivate: true }, 'pglite');+ const placeholders = (sql: string) => [...new Set(sql.match(/\$\d+/g))].sort();+ expect(placeholders(pg.indexWalkSql!)).toEqual(placeholders(pg.sql));+ expect(lite.indexWalkSql!.replace(' p.updated_at,', '').replace(/CASE WHEN bpp\.updated_at < \([\s\S]*?\) THEN true ELSE false END AS stale/, 'false AS stale'))+ .toBe(pg.indexWalkSql!);+ });+});+describe('vector legacy guard setting', () => {afterEach(() => _resetVectorLegacyGuardForTests());