Repository navigation
feat(ai-vault-search): session search query engine over the index - #19750
Conversation
78d007a to
d5f8096
Compare
Review round 1 → 85a5816, c342b47, 6015d3c, c918f64, d5f8096 (rebased onto PR 2
|
Review round 2 → 669b53f, f5a7c7dSecond 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.
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. |
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 Three LOWs closed in
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. |
4fb5174 to
b9393b4
Compare
Round 4: rebased onto the simplified PR 2 (abeccc5) → b9393b4PR 2 replaced its staged-publish store with one transaction per file, dropped its visibility views and ratchet, dropped
Latency, 105 MB corpus, two runs, 20 queries per rung, p50 / p95 ms:
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 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. |
Round 5: final review, three HIGHs fixed → 5ba6243cf3 (stop rule: HIGH-only, reproduced; the rest is in the plan doc's follow-ups)
Held under attack: 36 FTS5 syntax inputs across both scopes (no throws, no tool-only hits, no tool text in a conversation-scope snippet); 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 Verification (rerun by the lead): tc; ai-vault, ai-vault-search, shared, right-sidebar renderer (10453 tests); both changed-code gates; native audit; |
There was a problem hiding this comment.
✅ 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,
conversationas a column filter whose parentheses bind the entire expression. - Generation fence — three triggers on
filesplus an orphan-reclaim trigger onmessages, 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 —
splitAiVaultSearchQueryis the sole reading ofrepo:/path:; the panel'sparseVaultQuerydelegates to it and the engine appliesmatchesAiVaultQueryOperatorsover 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:1still credits the now-removed privatetokenizeQuery("tokenizeQuery gained quoted repo:/path: operator values"). It names nothing after this PR; a one-line rewrite tosplitAiVaultSearchQuerywould keep it honest.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
5ba6243 to
5dc7b78
Compare
…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.
… trigger after a replace cuts loose
5dc7b78 to
95b36be
Compare
📝 WalkthroughWalkthroughAdds 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 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)
✅ Passed checks (3 passed)
Full details: Docstring CoverageExplanation 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 checkExplanation 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 Resolution Restructure the description using the repository template. Add an ELI5 explanation, clear What Changed and Why sections, a valid
✨ Finishing Touches 💡 2📝 Generate docstrings 💡
🛠️ Fix failing CI checks 💡
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (2)
src/main/ai-vault-search/session-search-engine.ts (1)
114-114: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winValidate
sessionCandidateLimitbefore you store it.
??only replacesnullandundefined. If a caller passes0, every search returns no hits. If a caller passes a negative number, SQLite treats theLIMITas unbounded, somatchgroups 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_DEFAULTsrc/main/ai-vault-search/session-search-fts5-contract.test.ts (1)
19-28: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winClose 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.removeTreethen 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.tsalready tracks handles in an array and closes them inafterEach. 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
📒 Files selected for processing (35)
.gitignoreconfig/scripts/session-search-query-benchmark.tsconfig/scripts/session-search-scope-benchmark.tsconfig/scripts/session-search-tool-heavy-corpus.tsdocs/reference/agent-session-search-query-tuning.mdsrc/main/ai-vault-search/session-search-engine-test-fixture.tssrc/main/ai-vault-search/session-search-engine-types.tssrc/main/ai-vault-search/session-search-engine.test.tssrc/main/ai-vault-search/session-search-engine.tssrc/main/ai-vault-search/session-search-fts5-contract.test.tssrc/main/ai-vault-search/session-search-hit-ranking.test.tssrc/main/ai-vault-search/session-search-hit-ranking.tssrc/main/ai-vault-search/session-search-index-generation.test.tssrc/main/ai-vault-search/session-search-index-generation.tssrc/main/ai-vault-search/session-search-orphan-rows.test.tssrc/main/ai-vault-search/session-search-page-cursor.tssrc/main/ai-vault-search/session-search-paging.test.tssrc/main/ai-vault-search/session-search-query-log.test.tssrc/main/ai-vault-search/session-search-query-log.tssrc/main/ai-vault-search/session-search-query-planner.test.tssrc/main/ai-vault-search/session-search-query-planner.tssrc/main/ai-vault-search/session-search-query-schema.tssrc/main/ai-vault-search/session-search-retrieval.tssrc/main/ai-vault-search/session-search-row-filter.test.tssrc/main/ai-vault-search/session-search-row-filter.tssrc/main/ai-vault-search/session-search-sidebar-parity.test.tssrc/main/ai-vault-search/session-search-snippet-marks.test.tssrc/main/ai-vault-search/session-search-snippet.tssrc/main/ai-vault-search/session-search-source-presence.tssrc/main/ai-vault-search/session-search-typo-policy.test.tssrc/main/ai-vault-search/session-search-typo-repair.tssrc/main/ai-vault-search/session-search-typo-scope.test.tssrc/shared/ai-vault-search-query-operators.test.tssrc/shared/ai-vault-search-query-operators.tssrc/shared/ai-vault-session-filters.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.
| } catch (error) { | ||
| await rm(wide.corpus.root, { recursive: true, force: true }) | ||
| throw error |
There was a problem hiding this comment.
🩺 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 })
}| // 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) | ||
| ) |
There was a problem hiding this comment.
🎯 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) |
There was a problem hiding this comment.
🩺 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.
| 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 |
There was a problem hiding this comment.
📐 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 |
There was a problem hiding this comment.
🎯 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.
| 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) { |
There was a problem hiding this comment.
🎯 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')| const MARK_OPEN = '\uE000' | ||
| const MARK_CLOSE = '\uE001' |
There was a problem hiding this comment.
🎯 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().

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 tomainwhen that merges. Rebased onto PR 2 headabeccc5905. 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
conversationismessages_fts MATCH '{user_text assistant_text}: (…)'with bm25 weights that zero the other two columns,allis 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 bbinds only the first term and searches tool output for the rest.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 neitherfilesnorsessionsis retention's orphan drain, which is exactly the one that must not bump. The increment is oneON CONFLICT DO UPDATE … + 1running inside the writer's ownBEGIN 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 frommetaon every search and never cached. A cursor from another generation is refused with a typedSessionSearchCursorError, never silently re-run.present/unverifiable/missing) comes from thefilestable.docs/reference/agent-session-search-query-tuning.md.truncated.candidatesis 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, andtruncated.queryis set when the 48-term planner cap or the 512-character slice cut the query itself.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.matchesAiVaultQueryOperatorslives insrc/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 (thecwd_keyprefix range). The panel'sparseVaultQuerynow parses throughsplitAiVaultSearchQuery, so there is one parser.session-search-sidebar-parity.test.tsruns 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:""andpath:""drop the empty operator instead of filtering on the two characters and emptying the list;"" emptyand'' emptyread as an empty term instead of the characters. The original branch's WSL distro qualification is gone (PR 2's decision).SessionSearchStore.connection, which PR 2 now exposes, with the two rules it documents: no read transaction across anawait, and no.iterate()outliving its statement. Every retrieval here is one synchronous statement.openSessionSearchDatabaserather 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-searchsqlite_masterprobe finds an object missing, so a dropped one heals instead of degrading. The one it cannot re-create is the vocabulary's source:messages_ftsis 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.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.tsplants 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, andgeneration.Benchmark
Synthetic corpus, 10.5 MB / 40 sessions / 9,600 messages (
config/scripts/session-search-query-benchmark.ts), re-measured on this base: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_ftsis 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).allp50 / p95conversationp50 / p95The 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
andrung 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 formessages_ftsalone 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 tcand each oftc:node/tc:cli/tc:webdirectly;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.src/main/ai-vault-searchsuite (262 tests):AFTER DELETE ON filesgeneration trigger removedAFTER INSERT ON filesgeneration trigger removedAFTER UPDATE ON filesgeneration trigger removedsessions1.0, 1.0instead of0.0, 0.0matchLEFT JOINssessionsinstead of INNEREarlier 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_textandidentifiers, so1.0, 1.0returns the same numbers. They are kept as a statement of what the scope means;scopedExpressionis the fence, and it is the one with kills against it.The surviving mutation, honestly. Loosening retrieval's join to
sessionskills nothing, and the orphan test cannot be made to kill it, because a hit is a session row: the ranked list is loadedFROM 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 ittruncated.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.
unavailablecan 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 HEADover PR 2's ten files is empty.visible_sessions/visible_messagesbecamesessions/messages. Retention now leaves message rows with no session row, so the snippet read gained a join tosessionsand the typo repair stopped trustingmessages_vocab's document count; both are pinned insession-search-orphan-rows.test.tsand both mutations are killed.filesthat 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.idis AUTOINCREMENT. A cursor holds an offset and no ids, so nothing here assumed reuse and nothing was deleted; the cursor payload now says so.indexedFilereturning a nullbyteOffsetdoes not reach this PR: nothing on the query path readsfiles.byte_offset. Source presence readsfiles.session_row_idonly.BEGIN, no.iterate(), andsearchis synchronous end to end.Round 5: rebase onto the one-table schema
git rebase --onto abeccc5905 b0c07f0e8e, no conflicts.git diff abeccc5905 HEADover PR 2's files is empty.ftsTableForis gone. A scope is nowscopedExpressionplusscopedWeightsovermessages_fts, and the table name no longer travels through the engine, the snippet builder or a hit.SessionSearchStore.connectionis what the engine and both benchmarks read through.messages_ftsis 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.Round 5: three defects from the final review
Each reproduced against
b9393b44b2before it was fixed, and each repro kept as a test.HIGH: typo repair answered from a scope the search would not.
hasPostingsand 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 inrepairedTermsa 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 amessages_fts MATCHunder the same filter retrieval uses, joined tosessions. 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
messagesalone and moved no generation, on the argument that those rows answer nothing. True of retrieval; false of the engine, becausemessages_vocabis 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'sdocis 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. ItsWHENclause is why it is affordable: a replace and aremoveFiledelete rows while the session row still stands, so neither fires and both already bump throughfiles. The contract changes: a cursor outstanding while a purge runs is refused once per batch, reported asstale-generationso 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 bashif [[ -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)issliceAtCodeUnitLimitnow, though a lone surrogate is not a token character so the planner drops it either way.loadSessionsreads 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 sortdoc DESCneeded.Round 5 mutations (275 tests in
src/main/ai-vault-search)AFTER DELETE ON filesgeneration trigger removedWHENclauseloadSessionsbinds every id in one statement