Skip to content

feat(ai-vault-search): session search query engine over the index - #19750

Merged
Jinwoo-H merged 26 commits into
mainfrom
session-search-pr4-query
Sep 11, 2026
Merged

Jinwoo-H merged 26 commits into
mainfrom
session-search-pr4-query

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 14 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2361 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2361
Prod 21 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2773 $\color{#cf222e}{\Huge{\mathbf{−}}}$​61 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2712

Summary

PR 4 of the agent-session-search stack (plan: docs/reference/agent-session-search-pr-split.md). Stacked on #19687 (PR 2); the base moves to main when that merges. Rebased onto PR 2 head abeccc5905. Diff against #19687 is 34 files and zero lines in any file PR 2 owns.

The query engine as a library: new SessionSearchEngine(db, options).search({ query, scope, limit, cursor, filters }) over the PR 2 index. No timers, no settings, no IPC, no Electron, nothing constructs it in production. PR 5 decides which of its outputs cross the wire.

What it does

  • Route ladder (phrase → AND → typo repair → OR) with BM25 weights and session aggregation; forks fold to one session.
  • Scope is explicit and is a column filter, not a second table: conversation is messages_fts MATCH '{user_text assistant_text}: (…)' with bm25 weights that zero the other two columns, all is the same table unfiltered. No "switch corpus while typing" logic here; that is UI policy (PR 7). The filter is parenthesised, which is load-bearing — {cols}: a AND b binds only the first term and searches tool output for the rest.
  • Generation-fenced cursors (reviewer F11), as three triggers this PR installs on files. Every transaction the store opens that can change what a search returns writes that table — a committed read, a chunk of a long read, removeFile, retention cutting a session loose — and the one write path that touches neither files nor sessions is retention's orphan drain, which is exactly the one that must not bump. The increment is one ON CONFLICT DO UPDATE … + 1 running inside the writer's own BEGIN IMMEDIATE, so it commits with the change it describes and two connections cannot mint one value twice. The triggers live in the database file, so PR 3's indexer in the scanner child moves the generation without knowing a reader exists. The value is read from meta on every search and never cached. A cursor from another generation is refused with a typed SessionSearchCursorError, never silently re-run.
  • No filesystem on the query path (F11): source presence (present / unverifiable / missing) comes from the files table.
  • Per-hit snippet truncation flagged on the hit (F5).
  • Candidate limit as a tunable default (F13), with the measurements in docs/reference/agent-session-search-query-tuning.md. truncated.candidates is decided by retrieval, the only layer that knows whether a cap ended the walk: an operator-only search that gave up at its scan ceiling reports truncated even with zero hits, and truncated.query is set when the 48-term planner cap or the 512-character slice cut the query itself.
  • A refused cursor names both generations (expectedGeneration, actualGeneration) so PR 5 can tell a moved index from a bad cursor and re-issue page 1. A backfill's per-file publishes DO refuse outstanding cursors, by design: a cursor is a promise about one generation.
  • repo: / path: mean one thing in the list and the index. matchesAiVaultQueryOperators lives in src/shared/ai-vault-session-filters.ts; the sessions panel calls it and the engine applies it over retrieved rows, with SQL keeping only what it can express exactly (the cwd_key prefix range). The panel's parseVaultQuery now parses through splitAiVaultSearchQuery, so there is one parser. session-search-sidebar-parity.test.ts runs 13 queries through both. The shared parser had a rule refusing a quoted span whose closing quote was not followed by a space; its justification was wrong (a span only opens at a token start) and it regressed six panel shapes, so it is dropped and those shapes are restored byte-for-byte. Four panel shapes change on purpose, each pinned: repo:"" and path:"" drop the empty operator instead of filtering on the two characters and emptying the list; "" empty and '' empty read as an empty term instead of the characters. The original branch's WSL distro qualification is gone (PR 2's decision).
  • The engine reads through SessionSearchStore.connection, which PR 2 now exposes, with the two rules it documents: no read transaction across an await, and no .iterate() outliving its statement. Every retrieval here is one synchronous statement.
  • The engine carries its own schema, created on top of openSessionSearchDatabase rather than inside it: messages_vocab (fts5vocab, a view over the FTS b-tree, no write cost), search_log (off unless asked; stores the query as typed, per PR 2's decision), and the three generation triggers. Nothing on the write path reads any of them, so under the stack's YAGNI rule they are not PR 2's, and an index built by a process that never opens an engine carries none of their cost. No schema version of its own either: every object is derived from what PR 2 already holds, so re-creating them over any of its files is correct, while a version bump would throw a whole index away to add a view over its own b-tree. The install is idempotent and re-runs whenever a per-search sqlite_master probe finds an object missing, so a dropped one heals instead of degrading. The one it cannot re-create is the vocabulary's source: messages_fts is the store's, and an index in the middle of a rebuild is named as unable to serve typo repair and still answers from the conversation table.
  • A message row can outlive its session row. Retention deletes the session in one small transaction and reclaims its messages in batches, so every read that returns content INNER JOINs sessions — retrieval, the session load, the snippet, and the typo repair, which asks for a live posting instead of trusting the vocabulary's document count. session-search-orphan-rows.test.ts plants that state and walks every route over it.
  • warm() is not re-added. The measurement behind it was on a 4 GB index; removing it moves this PR's corpora by less than the run-to-run spread, and a cancellable background pass needs a lifecycle a query library does not have. It belongs with the indexer in PR 3b. See the tuning doc.

Kept internal (PR 5 decides)

planner.route, repairedTerms, tier, the row types, page-key hashing, the cursor rejection reason, logQueries. PR 5 will need to lift: the hit shape, scope, the presence vocabulary, snippet marks, the cursor as an opaque string, truncated, and generation.

Benchmark

Synthetic corpus, 10.5 MB / 40 sessions / 9,600 messages (config/scripts/session-search-query-benchmark.ts), re-measured on this base:

Scope p50 p95
all 6.13 ms 8.50 ms
conversation 3.88 ms 5.18 ms

Candidate-limit sweep over 2,500 all-matching sessions (p50 / p95 ms): 200 → 5.82 / 6.12; 600 → 6.92 / 7.39; 1200 → 8.43 / 9.18; 2400 → 11.30 / 12.18.

Scope latency on the shipping schema

conversation_fts is gone; PR 2 deleted it on the strength of this PR's shoot-out (the column filter came in at 1.16–1.36x the dedicated table's p95, under the 2x bar, while the table cost a tenth of the index). These are the numbers for what actually ships, on the same 105 MB corpus, after the table went and PR 2 capped an indexed tool row at 3,072 characters. Twenty queries per rung, both scopes interleaved query by query, warm cache, two runs (config/scripts/session-search-scope-benchmark.ts).

Tool share Rung all p50 / p95 conversation p50 / p95
86% phrase 16.69 / 17.48 13.08 / 13.52
86% or 31.91 / 35.74 22.25 / 23.87
86% and 70.04 / 74.00 53.47 / 59.39
93% phrase 9.14 / 13.36 7.23 / 8.51
93% or 16.46 / 18.70 12.34 / 14.88
93% and 39.65 / 43.44 31.05 / 32.92

The filter is a win, not a cost: every rung is 1.2–1.4x faster narrow than wide. The shoot-out measured it against a table built for exactly that query; against the wide table it replaces, it reads fewer postings, which is what the second table was for.

Two caveats stated rather than buried. The and rung uses eight-term queries, chosen so no ordered run that long occurs and the phrase rung has to miss; a real two-term AND sits nearer the phrase row, and this rung is the noisy one (a second-run p95 reached 140 ms on one bucket, which is what 20 samples of a 70 ms query buys). And the index is now 57 MB at 93% tool output against roughly 150 MB for messages_fts alone before the tool-row cap, so most of a tool-heavy transcript is not indexed at all; that moves every number here and is the larger of the two effects.

The one behavioural difference the filter carries. FTS5's bm25 normalises by the whole row's length and has no per-column length, so two rows with identical prose do not score identically when one of them also holds tool output. A two-column table scored them the same. The rowid set is unchanged, which is what the deletion was decided on; the order within it can move. Pinned in session-search-engine.test.ts.

Verification (rerun by the lead)

  • pnpm tc and each of tc:node / tc:cli / tc:web directly; pnpm test src/main/ai-vault src/main/ai-vault-search src/shared src/renderer/src/components/right-sidebar (10,425 passed, 116 skipped; 247 in ai-vault-search); check:code-quality:changed; check:react-doctor:changed; audit:code-quality:native. All pass.
  • Mutations, each against the whole src/main/ai-vault-search suite (262 tests):
mutation tests failed
the conversation filter loses its parentheses, binding only the first term 2
the conversation scope reads every column 5
the snippet ignores the scope's column filter 1
the AFTER DELETE ON files generation trigger removed 6
the AFTER INSERT ON files generation trigger removed 3
the AFTER UPDATE ON files generation trigger removed 2
the engine caches the generation it opened at 4
the schema is probed once in the constructor, not per search 1
the vocabulary's source is never checked 2
the typo repair trusts the vocabulary's document count 2
the snippet read drops its join to sessions 1
the conversation bm25 weights are 1.0, 1.0 instead of 0.0, 0.0 0 — inert, see below
match LEFT JOINs sessions instead of INNER 0 — survived, see below

Earlier rounds' mutations still hold: accepting a stale-generation cursor fails 1; skipping the phrase rung fails 1; the engine bypassing the shared operator predicate fails 11 of 13 parity cases; ignoring the operator walk's scan ceiling fails 1; dropping the generations from the cursor error fails 1; removing the operator-value trim fails 3; silencing the planner's term-cap flag fails 1.

The zeroed weights change no score, measured. FTS5's bm25 sums over the columns the query matched, and the column filter has already kept the match out of tool_text and identifiers, so 1.0, 1.0 returns the same numbers. They are kept as a statement of what the scope means; scopedExpression is the fence, and it is the one with kills against it.

The surviving mutation, honestly. Loosening retrieval's join to sessions kills nothing, and the orphan test cannot be made to kill it, because a hit is a session row: the ranked list is loaded FROM sessions, so a message row with no session is dropped one step later whatever the join says. What the join still buys is the candidate set — an orphan inflates it, and with it truncated.candidates — and that is the whole of the difference. The two reads that could really leak an orphan are the snippet and the typo repair, and each is killed above.

Not in this PR

Anything that constructs the engine, IPC, relay, CLI, settings, the wire contract. Which process may open, unlink and rebuild the index is PR 3b's decision: a second handle that finds an older schema version replaces the file while a live store keeps answering from the unlinked inode, and this PR is the first thing that reads, so it is what first makes that reachable. PR 4 only refuses to make it worse (see docs/reference/agent-session-search-query-tuning.md, "Not settled here").

One question for PR 5. With a single FTS table there is no second corpus to fall back to, so an engine over an index mid-rebuild names typo repair as unavailable and then fails on the table it cannot read. unavailable can no longer be reported alongside a successful search. It is kept because it becomes reachable again the day something opens the index read-only, but whether the field survives into the wire contract is PR 5's call.

Round 4: rebase onto the simplified PR 2

git rebase --onto b0c07f0e8e c88985b817, resolving every conflict in PR 2's favour, then absorbing the six changes the rewrite owed this PR. git diff b0c07f0e8e HEAD over PR 2's ten files is empty.

  • The views are gone. visible_sessions / visible_messages became sessions / messages. Retention now leaves message rows with no session row, so the snippet read gained a join to sessions and the typo repair stopped trusting messages_vocab's document count; both are pinned in session-search-orphan-rows.test.ts and both mutations are killed.
  • The generation moved from the store to three triggers on files that this PR installs. It is the one change with a decision behind it: the store's per-file commit and its retention delete are the visibility-changing transactions now, this PR may not edit either, and a trigger is also the only form that fences a writer in another process. The round-1 two-handle test still passes, and every earlier non-bump (open, removing an unheld path, draining rows nothing can reach) still holds.
  • warm() dropped, with the reasoning in the tuning doc.
  • sessions.id is AUTOINCREMENT. A cursor holds an offset and no ids, so nothing here assumed reuse and nothing was deleted; the cursor payload now says so.
  • indexedFile returning a null byteOffset does not reach this PR: nothing on the query path reads files.byte_offset. Source presence reads files.session_row_id only.
  • The WAL rule is stated at the engine's own doc comment, with PR 2's 9.9 MB against 266 MB beside it. Every read is a single statement; there is no BEGIN, no .iterate(), and search is synchronous end to end.

Round 5: rebase onto the one-table schema

git rebase --onto abeccc5905 b0c07f0e8e, no conflicts. git diff abeccc5905 HEAD over PR 2's files is empty.

  • ftsTableFor is gone. A scope is now scopedExpression plus scopedWeights over messages_fts, and the table name no longer travels through the engine, the snippet builder or a hit.
  • The snippet keeps one guard where it had two. Its column list and its scoped expression were each hiding the other's mistakes: a tool-only row was unreachable through either, so neither had a mutation against it. The list is the same four columns for every scope now, and the expression is what makes a conversation snippet impossible to draw out of tool output.
  • SessionSearchStore.connection is what the engine and both benchmarks read through.
  • The degrade path narrowed. There is no second corpus, so an index whose messages_fts is gone can no longer be answered from; the engine names the feature and fails on the table rather than returning an empty page that reads as an answer.
  • Both benchmarks re-measured against the shipping schema, including the tool-row cap.

Round 5: three defects from the final review

Each reproduced against b9393b44b2 before it was fixed, and each repro kept as a test.

HIGH: typo repair answered from a scope the search would not. hasPostings and the vocabulary both read every column, so tool output decided whether a conversation-scoped query was repaired — in both directions. A tool row carrying the misspelling made the query look correctly spelled and suppressed the repair; a tool row carrying a rare word became the suggestion, naming in repairedTerms a string from a column the scope will never show. Both reproduced against a control index differing by exactly one row. The vocabulary proposes and a scoped count disposes now: fts5vocab is per table and cannot be column-filtered, so every decision that reaches the plan comes from a messages_fts MATCH under the same filter retrieval uses, joined to sessions. The cost is one bounded count per candidate examined, at most eight per prefix, only for a term the scope has no posting for.

HIGH: retention's orphan drain changed answers with the fence standing still. The drain deletes from messages alone and moved no generation, on the argument that those rows answer nothing. True of retrieval; false of the engine, because messages_vocab is a view over the FTS b-tree and listed them. A drain between two pages swapped which word a query was repaired to, under a cursor that was still honoured, and a search that had answered stopped answering. Fixed at both ends. The vocabulary's doc is out of the ranking, so the common case cannot happen; and a fourth trigger fences the rest, because the vocabulary still decides which candidates survive its scan limit. Its WHEN clause is why it is affordable: a replace and a removeFile delete rows while the session row still stands, so neither fires and both already bump through files. The contract changes: a cursor outstanding while a purge runs is refused once per batch, reported as stale-generation so a caller re-issues page one.

HIGH: a transcript's own brackets were read as a highlight. The snippet builder showed the first of four columns whose text contained [[, and transcripts contain [[ — a bash if [[ -f … ]], numpy's [[1, 2], [3, 4]]. A row matching only in tool output was shown its user turn with nothing highlighted in it. Which column matched is the difference between two renderings of the same text now, which content cannot forge. The marks FTS5 inserts are private-use code points, rewritten to [[ and ]] once at the end, for the other decision that has to tell a mark from content: the truncation refuses to cut between an open mark and its close.

Two one-line fixes from the not-routed list, both with honest framing rather than a kill they cannot have. query.slice(0, 512) is sliceAtCodeUnitLimit now, though a lone surrogate is not a token character so the planner drops it either way. loadSessions reads ids in batches of 500, though no SQLite this stack runs refuses 1,100 of them — 32,766 has been the floor since 3.32 — so the batch owns the ceiling here rather than rescuing a reachable failure. The other six review items are recorded in the split plan's follow-ups, with the repair's cost re-measured: 387 ms for a 39-unknown-term query at 1.6 M terms, down from 737 ms, because ordering the vocabulary scan by term drops the sort doc DESC needed.

Round 5 mutations (275 tests in src/main/ai-vault-search)

mutation tests failed
the repair tie-break uses the vocabulary's doc count 11
the AFTER DELETE ON files generation trigger removed 5
the engine caches the generation it opened at 5
typo repair probes unscoped again 2
the repair is not told the scope 2
the drain does not bump the generation 2
the conversation filter loses its parentheses 2
the orphan trigger loses its WHEN clause 1
the snippet picks a column by substring-matching content 1
the public marks go into the SQL again 1
the query cap slices without a code-point boundary 0 — not observable, see above
loadSessions binds every id in one statement 0 — not reachable, see above

@Jinwoo-H

Jinwoo-H commented Sep 9, 2026

Copy link
Copy Markdown
Contributor Author

Review round 1 → 85a5816, c342b47, 6015d3c, c918f64, d5f8096 (rebased onto PR 2 c88985b817)

An Opus adversarial review of the first head found one HIGH and several MEDIUM. All fixed.

  • HIGH: the generation fence did not fence a second store (reproduced). The store cached the generation in memory and bumped it read-then-write outside any transaction, so a reader on another handle saw a writer's deletions but its generation never moved; a stale cursor was honoured and a session skipped, which is the exact failure F11 exists to prevent. Two writers could also mint the same generation. Now the getter reads meta every time and the bump is one ON CONFLICT DO UPDATE … + 1 inside the visibility-changing transaction. Bumps on open, on removing an unheld path, and per tombstone-drain batch are gone, so pagination stays usable while indexing.
  • Page key fields unpinned: since, agents, scopePaths each had no test; each now has one.
  • repo: / path: diverged from the sidebar four ways (reproduced both directions): substring over cwd + filePath vs cwd_key only, two-segment vs one-segment folder label, Unicode vs ASCII case fold, and two parsers. Fixed by construction: the sidebar's own predicate is exported and the engine applies it over retrieved rows; one parser for both; a 13-query parity test. Operators are now conjunctive in the engine as in the panel.
  • Engine threw on a version-1 file: now probes once and reports typo repair unavailable. Multi-process rebuild ownership stays PR 3b's.
  • Typo repair dropped stop words silently: the re-plan is now told what the original decided; repairedTerms is the whole body that ran.
  • Rebase fallout: the query log imported PR 2's deleted redaction module; it now stores the query as typed.

Verification (rerun by the lead): tc; ai-vault, ai-vault-search, shared, right-sidebar renderer (10394 tests); both changed-code gates; native audit. Mutations rerun by the lead: caching the generation fails 6 (including the two-handle fence); bypassing the shared operator predicate fails 11 of 13 parity cases.

What held under attack: 96 FTS5 injection inputs with zero throws or cross-column matches; ranking determinism across pages and sorts; snippet scope and session pinning; fts5vocab has no write cost.

@Jinwoo-H

Jinwoo-H commented Sep 9, 2026

Copy link
Copy Markdown
Contributor Author

Review round 2 → 669b53f, f5a7c7d

Second Opus round confirmed the generation fence (every visibility-changing transaction bumps inside itself, none outside; the integer cast is safe on missing and garbage rows) and found what round 1 left.

  • Operator-only search reported "not truncated" after giving up (reproduced). The newest-first walk stops at a scan ceiling, but truncation was derived from the hit count, so a sparse match beyond the ceiling returned zero hits and truncated.candidates: false. Retrieval now reports why it stopped, not how much it read.
  • Per-publish cursor refusal vs a comment claiming pagination survives a backfill. Decision: keep the fence, fix the claim. SessionSearchCursorError now carries expectedGeneration / actualGeneration so PR 5 can re-issue page 1 on a moved index instead of treating it as a bad cursor. The row-delete loop's deliberate non-bump is commented as sound only because every read joins visible_sessions, which the PR 2 ratchet enforces.
  • The v1 capability probe was unreachable (every open rebuilds a stale file). Kept as the degrade path for a rebuild racing a live handle, now re-probed per search; a test that drops messages_vocab under a live engine and another that brings it back caught that error-path-only re-probing recovered in one direction only.
  • Parity refactor had changed 9 of 20 probed panel shapes, not 3. Six were regressions from one rule (refusing a quoted span whose closing quote is not followed by a space) whose justification was wrong; dropped, six shapes restored. Four are kept as improvements and each is pinned with old vs new behavior (see body).

Verification (rerun by the lead): tc; ai-vault, ai-vault-search, shared, right-sidebar renderer (10405 tests); both changed-code gates; native audit. Mutations rerun by the lead: ignoring the scan ceiling fails 1; dropping the generations from the cursor error fails 1.

@Jinwoo-H

Jinwoo-H commented Sep 9, 2026

Copy link
Copy Markdown
Contributor Author

Review round 3 → 4fb5174. Converged.

Third Opus round rebuilt the pre-unification panel tokenizer and diffed both parsers over 81,468 generated queries: operator recognition never diverges except for the pinned repo:"" decision and 321 cases where the OLD parser lifted an operator out of a quoted span (" repo:x "), which the new reading correctly refuses. The per-search capability probe costs 0.004 ms against a 3.6 ms search. Text-path truncation is reported at every cap. Four mutations, four kills.

Three LOWs closed in 4fb517495d rather than deferred:

  • repo:" " and repo:" x " were not trimmed, so a whitespace-only value silently emptied the list, the exact failure the repo:"" fix stops. Trimmed.
  • The 48-term planner cap and the 512-character slice were unreported: a 56-term query whose only match was the 56th returned zero hits with truncated.candidates: false. New truncated.query.
  • actualGeneration is now populated on all six cursor-refusal paths; expectedGeneration wherever it survived parsing.

Verification (rerun by the lead): tc; ai-vault, ai-vault-search, shared, right-sidebar renderer (10412 tests; the panel's 29 unchanged); both changed-code gates; native audit. Mutations rerun by the lead: removing the trim fails 3; silencing the planner cap flag fails 1.

Ready for a human read. Stays a draft until PR 2 merges and this rebases onto main.

@Jinwoo-H
Jinwoo-H force-pushed the session-search-pr4-query branch from 4fb5174 to b9393b4 Compare September 10, 2026 20:13
@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

Round 4: rebased onto the simplified PR 2 (abeccc5) → b9393b4

PR 2 replaced its staged-publish store with one transaction per file, dropped its visibility views and ratchet, dropped conversation_fts, made sessions.id AUTOINCREMENT, and capped tool rows at 3,072 chars. This round absorbs all of it; git diff abeccc5905 HEAD over PR 2's files is empty.

  • Views gone. Every read joins sessions and messages directly. Retention deletes the session row first and reclaims message rows later, so an orphan message row can exist briefly: every hit-returning read INNER JOINs sessions. New test plants an orphan row and asserts no route, the snippet, or typo-repair vocabulary returns it. The typo repair now asks for a live posting instead of trusting the vocabulary's document count.
  • Generation fence re-homed: there is no publish transaction any more, so PR 4 installs three triggers on files (insert/update/delete bump meta.generation). Every store transaction that changes an answer writes files; the orphan drain writes neither files nor sessions and is the one that must not bump. The round-1 two-handle test passes.
  • conversation_fts replaced by a column filter. ftsTableFor(scope) → scopedExpression ({user_text assistant_text}: (…), the parentheses are load-bearing) + scopedWeights (bm25(messages_fts, w_user, w_assistant, 0, 0)). The table parameter no longer travels through the engine, snippet builder or hit types. Snippet lost one of two masking guards; the expression is now the fence.
  • warm() dropped. Removing it moved the 10.5 MB corpus by less than run-to-run spread.
  • Cursor holds an offset, no ids, so AUTOINCREMENT needed no code change. byteOffset: null never reaches the query path. WAL rule stated at the engine entry: never hold a read transaction across an await.

Latency, 105 MB corpus, two runs, 20 queries per rung, p50 / p95 ms:

Tool share Rung all conversation (column filter)
86 % phrase 16.7 / 17.5 13.1 / 13.5
86 % or 31.9 / 35.7 22.3 / 23.9
86 % and 70.0 / 74.0 53.5 / 59.4
93 % phrase 9.1 / 13.4 7.2 / 8.5
93 % or 16.5 / 18.7 12.3 / 14.9
93 % and 39.7 / 43.4 31.1 / 32.9

The filter is faster than the wide table at every rung; the tool-row cap (index 150 → 57 MB at 93 % tool) moves every number more than the table deletion did. Open decision 3 is closed.

Two things for PR 5: the conversation scope now ranks a row down for tool output it will not show (bm25 normalises by whole-row length; rowid set unchanged, order within it can move; a test pins the direction). And typo-repair unavailable can no longer be reported beside a successful search since there is no second corpus; PR 5 decides whether the field survives.

Verification (rerun by the lead): tc; ai-vault, ai-vault-search, shared, right-sidebar renderer (10440 tests); both changed-code gates; native audit. Mutations rerun by the lead: filter unparenthesised fails 2; conversation scope reading every column fails 5; snippet ignoring the filter fails 1; delete trigger disabled fails 6.

@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

Round 5: final review, three HIGHs fixed → 5ba6243cf3 (stop rule: HIGH-only, reproduced; the rest is in the plan doc's follow-ups)

  • Typo repair read a different world than retrieval (reproduced two ways). Its vocabulary and posting probe were unscoped and counted orphan rows. In conversation scope, tool output containing a misspelling verbatim suppressed a repair and turned one hit into zero; a token that existed only inside a tool-output secret was offered as a correction. Now the vocabulary proposes and a scoped, session-joined messages_fts MATCH disposes: every decision reaching the plan is made in the scope that will answer it, and the vocabulary's doc count is out of the ranking.
  • The retention drain changed answers with the generation standing still (reproduced). Reclaiming orphan rows moved vocabulary counts, which flipped a repaired query from hits to none and re-labelled page 2 under an accepted cursor. A fourth trigger now bumps the generation on a delete whose session row is already gone (replace and removeFile do not fire it). Contract change, stated: a cursor outstanding during a purge is refused once per batch as stale-generation, which PR 5 handles by re-issuing page 1. The comment claiming the drain changed no answer is corrected.
  • The snippet chose a column by substring-matching [[ (reproduced). Shell tests and numpy output contain [[, so a column with no match could win and highlight user content. Marks are now private-use code points, translated to [[/]] after selection; column choice is the difference between a marked and an unmarked rendering, which content cannot forge.
  • Two one-liners: the query cut is surrogate-safe; session-id binds are batched under SQLITE_MAX_VARIABLE_NUMBER. Neither is observable in a test on this stack's SQLite, stated as such in the body.

Held under attack: 36 FTS5 syntax inputs across both scopes (no throws, no tool-only hits, no tool text in a conversation-scope snippet); snippet() honours the column filter; retention's two-step delete bumps the generation and refuses the pre-delete cursor; no BEGIN and no .iterate() on the query path.

Not routed (plan doc follow-ups): repair cost at a 1.6 M-term vocabulary; LCS before slicing; schema heal outside a transaction; generation read before retrieval; per-statement consistency; fixed RECENT_* constants.

Verification (rerun by the lead): tc; ai-vault, ai-vault-search, shared, right-sidebar renderer (10453 tests); both changed-code gates; native audit; git diff abeccc5905 HEAD over PR 2's files is empty. Mutations rerun by the lead: drain trigger disabled fails 2; probe unscoped fails 2; public marks in SQL fails 1.

@Jinwoo-H
Jinwoo-H marked this pull request as ready for review September 10, 2026 20:45

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

Reviewed the full session-search query engine stack (35 files, 25 commits) against its base: the SessionSearchEngine library and its route ladder, generation-fenced cursors, typo repair, snippets, and the shared repo:/path: operator parser, plus the two benchmark scripts and the tuning doc. I also read the write-path modules it fences (session-search-store, session-search-index-writer, session-search-retention-delete, session-search-message-rows, session-search-file-records) to check the generation fence for gaps.

  • SessionSearchEngine — a synchronous, pageable ranked search over the PR 2 index; a library with no production constructor (PR 5 wires it).
  • Route ladder — phrase → AND → scoped typo repair → OR with BM25 weights, forks folded to one session, conversation as a column filter whose parentheses bind the entire expression.
  • Generation fence — three triggers on files plus an orphan-reclaim trigger on messages, so any writer (in-process or the scanner child) that changes what a search returns moves the generation; stale / different-query / malformed cursors are refused with a typed error naming both generations.
  • One operator parser — splitAiVaultSearchQuery is the sole reading of repo:/path:; the panel's parseVaultQuery delegates to it and the engine applies matchesAiVaultQueryOperators over retrieved rows.
  • Scoped typo repair — the fts5vocab vocabulary proposes and a bounded live-row count under the same column filter disposes, so orphan rows and tool output cannot steer a repair.
  • Snippet generation — private-use marks rewritten to [[/]] once at the end; the shown column is chosen by comparing marked vs unmarked renderings.

I verified the one invariant the author flagged as hardest to hold — that the generation fence advances on every visibility-changing write — against every store write path, and found no writer that mutates what a search returns without touching files/sessions or firing the orphan trigger. The scope binding, orphan reads, snippet marks, and cursor refusal each have exact live-SQLite coverage, not just tautological assertions.

ℹ️ Nitpicks

  • Stale comment: the re-export shim at src/renderer/src/components/right-sidebar/ai-vault-session-filters.ts:1 still credits the now-removed private tokenizeQuery ("tokenizeQuery gained quoted repo:/path: operator values"). It names nothing after this PR; a one-line rewrite to splitAiVaultSearchQuery would keep it honest.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@Jinwoo-H
Jinwoo-H force-pushed the session-search-pr4-query branch from 5ba6243 to 5dc7b78 Compare September 10, 2026 21:12
…be fenced by

A search page is a slice of one ranked list, so a cursor only means anything
against the snapshot that produced it. The store now keeps a monotone
generation in `meta`, bumped by every mutation that can change which rows a
read returns, and starts a new one on open so a write whose bump never landed
cannot leave a cursor pointing at content that is already gone.

Schema version 2 adds the two tables the query layer needs: `messages_vocab`
(fts5vocab over messages_fts, the typo repair's whole dictionary) and
`search_log`. Both are pure additions and the index is a cache, so a version-1
file is dropped and rebuilt exactly as any other mismatch is.
The planner unfolds the tokenizer contract instead of asking SQLite: same
boundaries as `unicode61 tokenchars '_.-/+'`, pinned against real fts5vocab
output so a query can be planned without a round trip. It decides the route
ladder's first rung (literal shape), strips stop words from prose but never
from a literal, and fans an identifier out into its pieces for the OR fallback.

Typo repair uses the index's own vocabulary as its dictionary, so it can never
suggest a term the index does not hold. Its exact-match probe now joins
`visible_messages`: `messages_vocab` is a view over the FTS b-tree and still
lists staged and tombstoned terms, and the PR 2 read ratchet is right to
demand the join.

`splitAiVaultSearchQuery` is the index's reading of repo: / path:. It keeps
operator case, which the panel folds and cwd_key must not; a census test pins
the two parsers to the same answer about what is an operator until PR 7 moves
the panel onto this one.
Every caller-supplied narrowing in one place, so retrieval, the operator-only
page and the session load cannot drift apart: agents, an updated-at floor, the
retention cutoff, scope paths, and the repo: / path: operators.

Scope keying goes through PR 2's `cwdKey`, which is the sidebar's
`folderGroupKey` without its prefix, rather than the original branch's second
spelling. That drops the branch's WSL distro qualification, which PR 2 removed
on purpose, and it makes the filesystem root a key that already ends in a
separator, so the child-prefix range is built from the key rather than by
appending one; `//` sorts below every real child and would scope the root to
nothing.

Engine types land here too, under src/main and not src/shared: nothing in this
PR is a wire type, and PR 5 lifts what a caller may receive.
`SessionSearchEngine.search()` over the PR 2 store: route ladder (phrase, AND,
typo repair, OR), BM25 weights per corpus, one hit per session, fork folding,
and a page.

- `scope` picks the corpus and the engine never second-guesses it.
  `conversation` is user and assistant turns; `all` adds tool output and the
  identifier shadow column. Switching corpus while typing is PR 7's policy; an
  engine that widened on a miss would make a result impossible to reproduce
  from its own request.
- Pagination is an offset into one ranked list, fenced by the index generation
  and by a hash of everything that changes the ranking. A cursor from another
  generation or another query is refused with a typed error rather than
  silently re-run. Ranking breaks every tie by session id, because a cursor
  indexes into that order and retrieval does not promise one.
- Snippets and source presence are paid for by the page, not the list. A
  snippet past the per-hit ceiling is cut on a code point, never between `[[`
  and its `]]`, and flagged on the hit.
- Source presence is read from the `files` table. No stat on the query path,
  and no `missing`: only a proven deletion may claim one, and this read cannot
  prove it.
- `SESSION_SEARCH_CANDIDATE_LIMIT_DEFAULT` is an option, not a constant, and
  the result says when the limit was what cut the answer.
- The engine is the only caller of `store.warm()`, on first search.

Library only: no IPC, no settings, no Electron, nothing constructs it in
production.
…ate limit buys

Two corpora, because they answer different questions. The 10.5 MB / 40-session
corpus is what the scope split costs a reader: conversation is about 1.6x
faster at p50 and 3.4x at p95 than the full corpus, which is the argument for
the second FTS table being the one a keystroke can afford.

The candidate limit needs more sessions than the limit before it costs
anything, so it is swept over 2,500 one-turn transcripts with every session
matching. Limits are interleaved sample by sample: run back to back, the first
configuration pays for every page the OS cache had not seen and the ordering
alone moved p95 further than the limit did.

The doc says plainly what these numbers do not cover. They are cost, not
relevance; the MRR figures quoted beside the BM25 weights and the identifier
shadow column come from a shoot-out over real transcripts and cannot be
reproduced from this repository.
…chable pages honestly

The page key was hashed twice per search, once to decode the incoming cursor
and once to mint the outgoing one. The benchmark's reachable-page figure was
clamped against a constant that could never bind; it is the limit over the page
size and nothing else.
The warm wiring and the query-length cap were both written and neither was
observable. A spy pins that a search is what warms the store, and the cap is
pinned through the one input the planner's own term limit does not already
bound: a single enormous token, where the cut is what decides whether the term
matches the indexed one at all.
…ss cannot see

The generation was cached in memory and moved only on this store's own writes,
and the bump itself was a read-then-write outside any transaction. Two handles
on one file is the normal case once PR 3 lands: the indexer writes in the
scanner child while an engine reads elsewhere. A reader would see that writer's
deletions while its own generation stood still, honour a stale cursor, and skip
a session; two writers could mint one generation for two snapshots.

`generation` now reads `meta` on every call, and the bump is a single
`ON CONFLICT DO UPDATE ... + 1` inside the transaction that makes the change.
That closes the crash hole the bump-on-open existed for, so opening a store no
longer invalidates anyone's cursor.

Only a change to what a read returns counts. Retiring a path the index never
held hides nothing, and the row deletes that drain a tombstone take away rows
that were already invisible: bumping there would refuse a cursor every 256 rows
and leave pagination unusable for as long as indexing ran.

Also drops redaction from the query log, following PR 2's decision to store
transcript content as written; the module it called no longer exists.
…red literal whole

Two smaller findings.

An engine can be handed a connection to a version-1 file that another handle is
still answering from, and this PR is what first makes that reachable. It now
probes once for the two tables version 2 added and names what it cannot serve
on every result, instead of throwing at the first query that reaches for a
vocabulary that is not there. The route ladder simply skips its repair rung.
Which process may unlink and rebuild the index is PR 3b's decision and is not
solved here.

Typo repair re-planned the corrected query from scratch, and a corrected
spelling can read as prose even when what was typed was a literal:
`parseJsonn(the, data)` has the punctuation, `parsejson the data` does not, so
the re-plan dropped `the` as a stop word. The repaired query searched for less
than was asked and `repairedTerms` reported a body nobody typed. The re-plan is
now told what the original decided, because a repair changes spellings, not the
query's character.

`repairedTerms` is documented as the whole body the repaired plan ran, with the
index's own case-folded spelling for the terms it corrected.
… and the index

The engine said `repo:` and `path:` a second time, in SQL, and SQL cannot say
them. LIKE folds ASCII and nothing else, so `path:CAFÉ` missed `café`; the
engine searched `cwd_key` while the panel searches the working directory and
the transcript path, so `path:jsonl` matched every session in the panel and
none in the index; and the engine compared one path segment where the panel
compares the last two, so `repo:orca/session-search` missed. All four
reproduce in both directions.

So there is one definition now, not two that resemble each other.
`matchesAiVaultQueryOperators` moves into the shared filter module beside the
panel that already owned the semantics, the panel calls it, and the engine
applies it over the rows it retrieved. SQL keeps only what it can express
exactly: the `cwd_key` prefix range for `scopePaths`.

`parseVaultQuery` now parses through `splitAiVaultSearchQuery`, so one parser
decides what an operator is. Its existing tests pass unchanged; four degenerate
shapes do answer differently and are pinned as decisions rather than left to be
discovered.

Two consequences worth stating. The operators are conjunctive now, because that
is what the panel has always done, where the engine had been ORing within a
key. And the operator-only page walks newest sessions in bounded pages applying
the predicate, rather than taking one cut of the newest N and filtering it,
which would have answered `repo:x` with nothing on a busy index.
…tor change

repo: and path: moved out of SQL, so the operator-only row measures something
different now and the note that it is a range seek was wrong. The rest of the
table is re-measured on an idle machine: the previous run's p95 column was
mostly contention, which is why conversation looked 3.4x faster at p95 rather
than the 1.7x it actually is.

Adds what this PR does not settle: which process may unlink and rebuild the
index is PR 3b's, and PR 4 is only the first thing that makes reading it
reachable.
…h that finished

The operator-only walk stops at a scan ceiling as well as at a full candidate
set, and only the first of those reached the result. A query whose one match
sat past the ceiling came back with no hits and truncated.candidates false,
which is the engine claiming there is nothing to find when what happened is
that it stopped looking. Retrieval now says why it stopped, because it is the
only layer that knows, and the count it used to return could not distinguish
the two cases.

The cursor fence stays as it is: any published read moves the generation, so an
outstanding cursor is refused, and that is what F11 asked for. What was wrong
was the claim next to the row-delete skip that pagination stays usable through
indexing. It does not, and the engine now says so. The rejection carries the
generation the cursor was minted in and the one the index is at, so a caller
can tell a moved index from a bad cursor and re-issue page one without showing
anyone an error.

The capability probe was nearly dead code, since every store opens through a
function that rebuilds a stale file. It is not dead, because two handles can be
open on one file, so the claim is corrected rather than the probe deleted. It
now runs per search: a verdict cached in the constructor is wrong in both
directions once another handle rebuilds the index.

Also says why the row-delete loop may skip the bump: those messages keep
batch_id NULL and stay in visible_messages, so what makes them unreachable is
their session's tombstone, and the read ratchet is what keeps every reader
joining the view that applies it.
…s not end a word

Unifying the two parsers changed panel behaviour on nine of twenty probed
shapes, not the three previously pinned. Six of the nine were regressions, all
from one rule: the shared parser refused a quoted span whose closing quote was
not followed by a space, so `"a b"c` and `repo:"a"b` became single terms
carrying their own quote characters, which match nothing.

The rule was justified as what stops the apostrophes in `it's a repo:orca
thing's` from swallowing the operator between them. It is not: a span only ever
opens at a token start, and the quote in `it's` is not at one. Dropping the
rule restores all six shapes to what the panel has always done and leaves that
protection intact.

Three changes remain and are kept because the old answer was worse in each: an
operator with an empty quoted value is dropped rather than filtering on `""`
and silently emptying the list, and a bare pair of quotes reads as an empty
term rather than as the two characters. Each is pinned with a test that says
which behaviour it is and why.
…gine had to cut

Three lows.

`repo:"  "` survived as a term and matched no label, silently emptying the
list, which is the exact defect the empty-value drop exists to prevent wearing
different clothes. Operator values are trimmed, and a whitespace-only one drops
like an empty one. The substring matcher's copy of a free-text term is trimmed
too, so `"  "` reads as the empty term already does; the span kept for FTS is
still the query verbatim.

Two caps upstream of retrieval fired silently: the planner searches at most 48
terms, and the engine cuts the query at 512 characters. A 56-term query whose
only match was the 56th came back with no hits and nothing truncated, which
claims there is nothing to find. `truncated.query` now says when either fired,
alongside the candidate and snippet flags that already did.

Every cursor refusal now carries the generation the index is at, which the
engine knows before it looks at the cursor, and the generation the cursor
claimed wherever that survived parsing. The doc says exactly when each is
present instead of leaving absence unexplained.
…s, and own the fence

PR 2 deleted the visibility views, the staging tables and the store's
generation, so this reads `sessions` and `messages` directly and carries the
three schema objects only a query needs — the vocabulary, the query log, and
the triggers that move the generation — as its own extension over the store's
schema.

The fence is now three triggers on `files`, because every transaction the store
opens that can change what a search returns writes that table and nothing else
does; retention's orphan drain is the one write path that touches neither, and
it is the one that must not bump. The triggers live in the file, so a writer in
another process moves the generation without knowing a reader exists.

A message row can now outlive its session row until the drain reaches it, so
the snippet read joins `sessions` and the typo repair asks for a live posting
instead of trusting the vocabulary's document count.

The engine takes a connection rather than a store: PR 2's store keeps its
connection private, and which process may open or rebuild the index file is
PR 3b's decision, not a query engine's.
…hout warmup

Open decision 3. A column filter over `messages_fts` returns the identical
rowid set as `conversation_fts` — checked here per query rather than assumed —
so the table exists for latency alone. On a 105 MB corpus at both ends of the
tool-output band, the column-filtered form costs 1.16-1.42x at p95, against a
bar of 2x, so the recommendation is to delete it.

The shoot-out writes its own corpus because the answer turns on the one
property the shared generator fixes: how much of a transcript is tool output.
Half the tokens in that output are words the conversation also uses, which is
deliberately generous to the table under question.

The doc records the number that argues the other way. PR 2 priced the table at
about a quarter of the index on a corpus whose tool output is 56% of its
message text; on a tool-heavy one it is 6.7-11%, because `messages_fts` grows
with the tool text and the second table does not.

Page warmup is not re-added. The measurement behind it was on a 4 GB index,
removing it moves this corpus by less than the run-to-run spread, and a
cancellable background pass needs a lifecycle a query library does not have.
…n filter

PR 2 deleted `conversation_fts` on the strength of this PR's shoot-out, so the
scope is a column filter over the one FTS table now. `ftsTableFor` is gone; a
scope is a pair of `scopedExpression` and `scopedWeights`, and the table name
no longer travels through the engine, the snippet builder or a hit.

The filter is parenthesised, and that is the whole of it: `{cols}: (a AND b)`
binds both terms, while `{cols}: a AND b` binds only the first and searches
tool output for the rest. A test drives an AND whose second term lives only in
tool output through both scopes.

The snippet keeps one guard, not two. Its column list and its expression were
each hiding the other's mistakes — a tool-only row was unreachable through
either — so the list is the same four columns for every scope and the scoped
expression is what makes a conversation snippet impossible to draw out of tool
output. Dropping it now leaks that row, which a test catches.

One behaviour the deleted table did not have, pinned rather than wished away:
bm25 normalises by the whole row's length and has no per-column length, so two
rows with identical prose score differently when one also holds tool output.
The rowid set is unchanged; the order within it can move.

Re-measured on the shipping schema. The conversation scope is 1.2-1.4x faster
than `all` at every rung, and the index is 57 MB rather than about 150 MB at
93% tool output, because a tool row is now capped at 3,072 characters.
…swer it

Typo repair read `messages_vocab` and probed `messages_fts` with no column
filter, so tool output decided whether a conversation-scoped query was
repaired, in both directions. A tool row carrying the misspelling made the
query look correctly spelled and suppressed the repair; a tool row carrying a
rare word became the suggestion, naming in `repairedTerms` a string from a
column the scope will never show. Both reproduced against a control index that
differs by exactly that one row.

The vocabulary proposes and a scoped count disposes. fts5vocab is per table and
cannot be column-filtered, so every decision that reaches the plan — already
spelled right, eligible, and which of two equally close candidates wins — now
comes from a `messages_fts MATCH` under the same filter retrieval uses, joined
to `sessions`.

That also takes the vocabulary's `doc` out of the ranking, which is the half of
the drain defect that belongs here: `doc` counts rows whose session a purge has
already cut loose, so reclaiming them changed which word a query was repaired
to. Candidates are ordered by term now, because the ordering decides which of
them survive the scan limit, and ties on similarity go to the more common word
counted live rather than to the vocabulary's number.

The cost is one bounded count per candidate examined, at most eight per prefix,
and only for a term the scope has no posting for at all.
… session loose

Retention's second half deletes from `messages` alone and touched neither
`files` nor `sessions`, so it moved no generation. The argument was that those
rows answer nothing, which was true of retrieval and not of the engine: the
typo repair's dictionary is a view over the FTS b-tree and listed them, so a
drain running between two pages swapped the repair under a cursor that was
still honoured, and a search that had answered stopped answering.

The commit before this one fixes that at its source by counting live rows. It
does not make the drain provably inert — the vocabulary still decides which
candidates survive its scan limit, and reclaiming a term's last row moves where
that limit cuts — so the fence is what covers the rest.

A fourth trigger, on `messages`, with a `WHEN` clause that is the whole reason
it is affordable: a replace and a `removeFile` delete a session's rows while
its `sessions` row still stands, so neither fires, and both already bump
through `files`. Only the drain deletes a row whose session is gone.

The price is named rather than avoided: a cursor outstanding while a purge runs
is now refused once per batch, which `SessionSearchCursorError` reports as
`stale-generation` so a caller re-issues page one. The test that pinned the old
contract is replaced by one for the new one, and by one proving a replace still
does not fire it.
…s brackets

The snippet builder asked each of a row's four columns for a marked snippet and
showed the first whose text contained `[[`. Transcripts contain `[[`: a bash
`if [[ -f … ]]`, numpy's `[[1, 2], [3, 4]]`. A row matching only in tool output
was shown its user turn instead, with nothing highlighted in it, and the
any-column fallback an identifier-only match depends on was unreachable behind
the same collision.

Whether a column matched is now the difference between two renderings of the
same text: `snippet(…, MARK, MARK, …)` beside `snippet(…, '', '', …)`. Content
cannot forge a difference between those two, because it is the same content
either way.

The marks FTS5 inserts are private-use code points, rewritten to the public
`[[` and `]]` once, at the end. That is for the other decision that has to tell
a mark from content: the truncation refuses to cut between an open mark and its
close, and a transcript's own bracket used to move that cut.
…ches

Two small ones from the review's not-routed list.

`query.slice(0, 512)` can land between the halves of a surrogate pair, leaving
a lone half that matches nothing and that a caller cannot echo back. The reader
already has `sliceAtCodeUnitLimit` for exactly this.

`loadSessions` bound one parameter per candidate id in a single statement. The
list is as long as the candidate limit, the tuning doc invites a host to raise
that limit, and SQLite's `SQLITE_MAX_VARIABLE_NUMBER` is 999 on builds older
than 3.32 — so one settings change away from `too many SQL variables`. Read in
batches of 500, leaving room for the filter's own bound values.
… open

Typo repair is the one rung whose cost tracks the vocabulary rather than the
result, and it only runs for a term the scope has no posting for. Measured over
1.6 M distinct terms: 10 ms for one unknown term, 387 ms for a 480-character
query of thirty-nine of them.

The scoped-count fix made that cheaper rather than dearer, from 737 ms, because
ordering the vocabulary scan by term drops the sort `doc DESC` needed and the
counts it adds are at most eight bounded probes per prefix. A cap on unknown
terms per query is a follow-up in the split plan, with the five other items the
final review raised and did not route.
…self

Two mechanisms landed together and hid each other: choosing a column by
comparing a marked rendering against an unmarked one, and marking with
private-use code points instead of `[[`. Either alone fixed the bracket repro,
so neither had a mutation against it — the same masking the snippet's two
column guards had a round ago.

They do different jobs, so both stay and each gets the test that needs it. A
transcript holding a private-use code point of its own is what the comparison
is for; agent output carries Nerd Font glyphs from that block. A snippet past
the character ceiling with a bracket after its last real mark is what the
private-use marks are for, because the truncation has to find that mark by
searching the text.

The two one-line fixes get honest framing rather than a mutation neither can
have. A lone surrogate is not a token character, so the planner drops it either
way and the safe cut is hygiene. And no SQLite this stack runs refuses 1,100
bound ids — 32,766 has been the floor since 3.32 — so the batch is about
owning the ceiling here rather than rescuing a reachable failure.
… expressions

Making the typo repair ask its questions in the search's own scope put an
import from retrieval into it, and retrieval already owns the repair — a cycle
the native audit catches. `scopedExpression` belongs beside `phraseExpression`,
`andExpression` and `orExpression` anyway: it builds a MATCH expression, and
two callers now need it. The bm25 weights stay in retrieval, where the SQL that
uses them is.
@Jinwoo-H
Jinwoo-H force-pushed the session-search-pr4-query branch from 5dc7b78 to 95b36be Compare September 11, 2026 03:32
@Jinwoo-H
Jinwoo-H changed the base branch from session-search-pr2-index to main September 11, 2026 03:32
@coderabbitai

coderabbitai Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

Adds a complete indexed session search engine with query planning, scoped FTS retrieval, typo repair, ranking, fork folding, pagination, generation fencing, snippets, source metadata, filters, and optional query logging. Adds extensive SQLite, integration, and parity tests. Adds synthetic corpus generators, benchmark scripts, and query-tuning documentation.

Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to 95b36

Searches can return sessions outside an invalid requested scope or produce unstable fork representatives across pages. These correctness issues should be fixed before merge; benchmark and snippet defects are narrower but still actionable.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 45.45% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 88 functions across 33 files. (2 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description provides extensive technical context, implementation details, benchmarks, testing results, and scope boundaries. However, it does not follow the required template and omits required se… Restructure the description using the repository template. Add an ELI5 explanation, clear What Changed and Why sections, a valid Fixes #... issue reference, Visual Proof with attachments or N/A plus a reason, Testing checklist status an…
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the primary change: adding a session search query engine over the AI Vault index.
Full details: Docstring Coverage

Explanation

Docstring coverage is 45.45% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 88 functions across 33 files. (2 skipped: 2 unsupported.)

Full details: Description check

Explanation

The description provides extensive technical context, implementation details, benchmarks, testing results, and scope boundaries. However, it does not follow the required template and omits required sections or explicit entries for ELI5, What Changed, Why, Linked Issue, Visual Proof, AI Disclosure, Review, Agent skill upstream boundary, Notes, and the Checklist. It also does not provide the required issue reference or a visual-proof statement such as N/A for the behavior changes.

Resolution

Restructure the description using the repository template. Add an ELI5 explanation, clear What Changed and Why sections, a valid Fixes #... issue reference, Visual Proof with attachments or N/A plus a reason, Testing checklist status and tested platforms, AI Disclosure if applicable, Review, Agent skill upstream boundary, Notes, and the remaining checklist items.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Nitpick comments (2)
src/main/ai-vault-search/session-search-engine.ts (1)

114-114: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Validate sessionCandidateLimit before you store it.

?? only replaces null and undefined. If a caller passes 0, every search returns no hits. If a caller passes a negative number, SQLite treats the LIMIT as unbounded, so match groups and returns every matching session. Clamp the option to a positive integer.

♻️ Proposed change
-    this.candidateLimit = options.sessionCandidateLimit ?? SESSION_SEARCH_CANDIDATE_LIMIT_DEFAULT
+    const requested = options.sessionCandidateLimit
+    this.candidateLimit =
+      typeof requested === 'number' && Number.isInteger(requested) && requested > 0
+        ? requested
+        : SESSION_SEARCH_CANDIDATE_LIMIT_DEFAULT
src/main/ai-vault-search/session-search-fts5-contract.test.ts (1)

19-28: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Close the database handles in afterEach.

Each test calls db.close() as its last statement. If an assertion fails before that line, the handle stays open. removeTree then runs against an open SQLite file, which can fail on Windows and mask the original assertion failure.

src/main/ai-vault-search/session-search-index-generation.test.ts already tracks handles in an array and closes them in afterEach. Use the same pattern here.

♻️ Proposed refactor
 let tempRoots: string[] = []
+let handles: SyncDatabase[] = []
 
 afterEach(async () => {
+  for (const handle of handles) {
+    handle.close()
+  }
+  handles = []
   await Promise.all(tempRoots.map((root) => removeTree(root)))
   tempRoots = []
 })
 
 async function openDatabase(): Promise<SyncDatabase> {
   const root = await mkdtemp(join(tmpdir(), 'orca-fts5-contract-'))
   tempRoots.push(root)
-  return openSessionSearchDatabase(join(root, 'index.sqlite'))
+  const db = openSessionSearchDatabase(join(root, 'index.sqlite'))
+  handles.push(db)
+  return db
 }

The per-test db.close() calls can then be removed.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 0133eb55-be25-4e33-9e9c-15f8d1a33182

📥 Commits

Reviewing files that changed from the base of the PR and between 2c984bc and 95b36be.

📒 Files selected for processing (35)
  • .gitignore
  • config/scripts/session-search-query-benchmark.ts
  • config/scripts/session-search-scope-benchmark.ts
  • config/scripts/session-search-tool-heavy-corpus.ts
  • docs/reference/agent-session-search-query-tuning.md
  • src/main/ai-vault-search/session-search-engine-test-fixture.ts
  • src/main/ai-vault-search/session-search-engine-types.ts
  • src/main/ai-vault-search/session-search-engine.test.ts
  • src/main/ai-vault-search/session-search-engine.ts
  • src/main/ai-vault-search/session-search-fts5-contract.test.ts
  • src/main/ai-vault-search/session-search-hit-ranking.test.ts
  • src/main/ai-vault-search/session-search-hit-ranking.ts
  • src/main/ai-vault-search/session-search-index-generation.test.ts
  • src/main/ai-vault-search/session-search-index-generation.ts
  • src/main/ai-vault-search/session-search-orphan-rows.test.ts
  • src/main/ai-vault-search/session-search-page-cursor.ts
  • src/main/ai-vault-search/session-search-paging.test.ts
  • src/main/ai-vault-search/session-search-query-log.test.ts
  • src/main/ai-vault-search/session-search-query-log.ts
  • src/main/ai-vault-search/session-search-query-planner.test.ts
  • src/main/ai-vault-search/session-search-query-planner.ts
  • src/main/ai-vault-search/session-search-query-schema.ts
  • src/main/ai-vault-search/session-search-retrieval.ts
  • src/main/ai-vault-search/session-search-row-filter.test.ts
  • src/main/ai-vault-search/session-search-row-filter.ts
  • src/main/ai-vault-search/session-search-sidebar-parity.test.ts
  • src/main/ai-vault-search/session-search-snippet-marks.test.ts
  • src/main/ai-vault-search/session-search-snippet.ts
  • src/main/ai-vault-search/session-search-source-presence.ts
  • src/main/ai-vault-search/session-search-typo-policy.test.ts
  • src/main/ai-vault-search/session-search-typo-repair.ts
  • src/main/ai-vault-search/session-search-typo-scope.test.ts
  • src/shared/ai-vault-search-query-operators.test.ts
  • src/shared/ai-vault-search-query-operators.ts
  • src/shared/ai-vault-session-filters.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.

Comment on lines +181 to +183
} catch (error) {
await rm(wide.corpus.root, { recursive: true, force: true })
throw error

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Release wide when scope benchmarking fails.

If scopeReport throws before Line 153, this catch removes the corpus without closing SessionSearchStore or unregistering its consumers. The open SQLite handle can make rm fail and replace the original benchmark error.

Move release and removal into a finally block around the wide-corpus work.

Proposed cleanup structure
 const wide = await indexCorpus({ sessions: Number(process.env.SESSIONS ?? 40) })
 let report: string
 try {
   const scope = {
     all: scopeReport(wide.db, 'all'),
     conversation: scopeReport(wide.db, 'conversation')
   }
-  wide.release()
-  await rm(wide.corpus.root, { recursive: true, force: true })
+  // Continue with the candidate corpus.
+} finally {
+  wide.release()
+  await rm(wide.corpus.root, { recursive: true, force: true })
 }

Comment on lines +93 to +98
// Tool and prose words are not the same length, so the share is over bytes.
const proseBytesPerTurn = proseWordsPerTurn * 6
const toolWordCount = Math.max(
1,
Math.round((proseBytesPerTurn * args.toolShare) / (1 - args.toolShare) / 22)
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Calculate the requested tool share from generated byte counts.

The function states that toolShare is a byte ratio. It derives the tool word count from fixed estimates of 6 and 22 bytes instead. The generated vocabularies have different token lengths, so a configured value such as 0.93 does not reliably create a 93% tool-output corpus. This invalidates benchmark labels and comparisons that depend on the configured share.

const proseBytesPerTurn = proseWordsPerTurn * 6
const toolWordCount = Math.max(
1,
Math.round((proseBytesPerTurn * args.toolShare) / (1 - args.toolShare) / 22)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Validate toolShare before this calculation.

If toolShare is 1, this division produces Infinity. words() then loops forever because its count is infinite. Reject non-finite values and require 0 <= toolShare < 1 before generating the corpus.

Comment on lines +27 to +29
The `conversation_fts` shoot-out below runs the same way, importing
`config/scripts/session-search-conversation-fts-benchmark` instead, with
`CORPUS_MB` and `TOOL_SHARE` to size and shape its corpus. `config/scripts` is

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Use the current scope benchmark module name.

config/scripts/session-search-conversation-fts-benchmark is not the benchmark added by this PR. The runnable script is config/scripts/session-search-scope-benchmark. Update this command and its surrounding wording so the documented procedure works.


function isNewer(entry: RankedSession, best: RankedSession): boolean {
const order = (entry.session.updated_at ?? '').localeCompare(best.session.updated_at ?? '')
return order === 0 ? entry.score > best.score : order > 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Add a session-ID tie-break when selecting the fork representative.

If two forks have the same updated_at and score, reduce keeps the first entry. The session query does not guarantee that input order. The selected session and message can therefore change while the cursor generation remains unchanged.

Use the session ID as the final tie-break. Add a regression test that reverses equal fork inputs.

Proposed fix
 function isNewer(entry: RankedSession, best: RankedSession): boolean {
   const order = (entry.session.updated_at ?? '').localeCompare(best.session.updated_at ?? '')
-  return order === 0 ? entry.score > best.score : order > 0
+  if (order !== 0) {
+    return order > 0
+  }
+  return entry.score !== best.score
+    ? entry.score > best.score
+    : entry.session.id < best.session.id
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return order === 0 ? entry.score > best.score : order > 0
if (order !== 0) {
return order > 0
}
return entry.score !== best.score
? entry.score > best.score
: entry.session.id < best.session.id

const present = filters.scopePaths
.map((scope) => scopeCondition(filter, scope))
.filter((condition) => condition !== null)
if (present.length > 0) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Return no rows when all requested scopes are invalid.

For scopePaths: [''], scopeCondition returns null and present is empty. This branch then adds no condition, so the search returns sessions from every path. This contradicts the contract at Line 63.

Add a false condition when the caller supplied scopes but none can be keyed.

Proposed fix
-    if (present.length > 0) {
-      filter.conditions.push(`(${present.join(' OR ')})`)
-    }
+    filter.conditions.push(present.length > 0 ? `(${present.join(' OR ')})` : '0')

Comment on lines +19 to +20
const MARK_OPEN = '\uE000'
const MARK_CLOSE = '\uE001'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use per-call markers that cannot collide with transcript content.

publicMarks() converts every U+E000 and U+E001 in the selected snippet into [[ and ]]. truncateSnippet() treats a literal U+E000 before the character limit as an opening mark and may discard the remaining text. The regression test places U+E000 in a non-selected column, so it checks column selection but not preservation in returned text. Generate per-call markers and bind them to snippet(), publicMarks(), and truncateSnippet().

@Jinwoo-H
Jinwoo-H merged commit cf7408a into main Sep 11, 2026
51 of 67 checks passed
Jinwoo-H added a commit that referenced this pull request Sep 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant