Repository navigation
Index node.title in its own FTS5 table for entity lookup - #2845
Conversation
Adds `node_title_fts`, an FTS5 index over `node.title`, so a named entity in a message can be resolved to the node that IS it. This is the prerequisite the entity-resolution design needs; no routing behaviour changes here. A separate table, not a second column on `node_fts`. The two answer different questions — `node_fts` over `content` answers "which nodes *discuss* X?" (one long row per node), this one answers "which node *is* X?" (one short row per nameable node) — and sharing a table would rank every node whose body merely mentions a name alongside the named node. `node_fts` and `bm25_search_roots` are retained unchanged. They are not dead: `EmbeddingService::semantic_search` runs `bm25_search_roots` concurrently with the vector search and fuses both legs, and that backs `search_nodes` and agent context assembly. No call site outside tests spells the function name, which is why a name grep finds only test hits. Standalone rather than external-content, deliberately. FTS5 has no partial-index syntax, so "only when title IS NOT NULL" lives in the triggers — but an external-content table's `'rebuild'` re-derives every row from the content table, silently reinstating the NULL-title rows the triggers skip (verified: docsize goes 1 -> 2 across a rebuild). Since `backfill_fts_if_stale` issues exactly that rebuild for `node_fts`, an external-content title index would lose its partial shape on the first repair. A standalone table owns its rows, so the invariant holds. `backfill_title_fts_if_stale` mirrors the existing repair with the two differences the partial standalone shape forces: it compares against `count(*) WHERE title IS NOT NULL` (comparing against the plain node count would call a correct index stale on any database holding one child node), and it repairs by delete-and-refill since `'rebuild'` is both unavailable and unable to express the NULL skip. Six tests, each verified to fail without the code it pins. The null-skipping test asserts index membership rather than matchability: FTS5 stores a NULL title as a row with no terms, which no MATCH returns, so an id query alone still passes when the guard is dropped. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Review TypeInitial Review — no prior reviews or comments on PR #2845. Reviewed against issue #2841's corrected acceptance criteria (the Requirements CheckThe issue body's prerequisite was corrected twice in comments. Scoring against the final corrected version:
The Phase B deferral is well-justified. The issue's own Independent verification of the retention claim (the flagged critical risk)The PR claims
Had the issue body's original "delete it" instruction been followed, Code Review Findings🟢 Verified correct (recorded because these were the flagged risk areas)I executed the DDL against SQLite directly rather than trusting the description. All four transitions are correct:
Nothing bypasses the triggers. A full inventory of The repair restores the rowid mapping correctly — I verified that Open-time cost is negligible. Both staleness counts execute in ~2ms against 100k nodes. SQL injection: none. Every new statement is a static string literal; the only runtime values are bound via Standalone-vs-external-content reasoning holds. I confirmed the mechanism: FTS5's Test claim verified empirically. I removed the Doc-comment accuracy. Project standards: no lint suppression, no 🟡 [Improvement] The staleness signal is blind to equal-cardinality corruption📁 The repair triggers only when This requires an equal-and-opposite desync, so it is genuinely unlikely, and the pre-existing
Suggestion: either strengthen the signal (e.g. compare a cheap checksum, or verify the rowid sets agree), or narrow the doc comment so it does not claim VACUUM coverage it lacks. The principle is that a health check should not report healthy on a corruption mode its own documentation names. 🟡 [Improvement] The repair's DELETE and refill are not atomic📁
If the process dies or the INSERT errors between the two, the index is left empty — strictly worse than the partially-stale state it started from. The next open does repair it (0 ≠ titled count, so the signal fires), so this is self-healing rather than permanent, and the window is small. But the failure mode is "the repair made it worse," which is worth closing cheaply: conn.execute("BEGIN IMMEDIATE", ()).await?;
// DELETE + INSERT ... SELECT
conn.execute("COMMIT", ()).await?;Note the same argument applies to 🟢 [Nit] Redundant index churn on title-less UPDATEs📁 The I measured this: a properties-only sweep over 20,000 titled nodes costs 69ms of redundant delete+reinsert, and the index remains fully correct afterward. So this is cheap and safe, not a blocker. Scoping the trigger would remove the churn: CREATE TRIGGER ... AFTER UPDATE OF title ON node BEGIN ...However — 🟢 [Nit] Latent hazard worth a schema comment:
|
malibio
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.
#2841) Three findings from the pragmatic-code-review on #2845. Atomicity (the reviewer's one encouraged fix). The repair was a DELETE followed by a refill in autocommit — `backfill_fts_if_stale` runs after `create_schema` has committed — so a crash between them left the index EMPTY: not the stale state the repair was called to fix, but a strictly worse one where every entity lookup silently returns nothing. Now one `BEGIN IMMEDIATE`/`COMMIT` with unconditional rollback on failure, following `create_schema`'s reasoning (take the write lock up front; never leave an open transaction on the store's one long-lived writer). `node_fts` needs no equivalent — its `'rebuild'` is a single statement. Empty-string titles. `'' IS NOT NULL`, so a blank title was indexed as a term-less row: matched by nothing, but occupying the index and falsifying "every row is an entity". `compute_title()` reaches `Some("")` by two routes — a titleTemplate whose fields are all absent (unresolved tokens are skipped), and `strip_markdown("")` on an empty task or collection. Guards are now `nullif(title, '') IS NOT NULL`. The staleness predicate had to change in lockstep: if it and the triggers disagree about '', a healthy index reports stale and refills on every open. Two tests added. `title_fts_reindexes_a_renamed_node` covers the commonest real transition (a title-templated instance whose properties change), which no test exercised; it pins the update trigger's unconditional DELETE, without which a renamed node stays matchable under both its old and new names. `title_fts_skips_empty_string_titles` pins the '' guard in both directions. Both verified to fail without the code they pin, as were the original six. Also recorded in comments: the `unicode61` tokenizer's behaviour (folds diacritics, does not segment CJK), since it bounds what entity resolution can match; and that `REPLACE INTO node` would bypass these triggers (fires neither AFTER UPDATE nor, with recursive_triggers off, AFTER DELETE). None exists today. Not addressed, deliberately: the cardinality-only staleness signal cannot detect an index holding the right number of wrong rows. That is a pre-existing property shared with `backfill_fts_if_stale`, and giving this one table a stronger signal while the other keeps a weaker one is scope creep for Phase A. Documented as a known limit instead. Also left as-is: the update trigger fires on every column write rather than `AFTER UPDATE OF title` — measured at 69ms per 20k rows, and the narrower form would couple correctness to the convention that title writes name the column. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Review TypeRe-Review — scoped to Previous Review Summary
Counts: 3 addressed (1 with a new defect), 3 skipped soundly, 1 NEW blocker introduced. The author's own re-review decision — "RE-REVIEW NEEDED… the Code Review Findings🔴 [Critical/Blocker] The refill's predicate was not updated — the repair never converges and refills on every open📁 The // mod.rs:390 — staleness count (UPDATED ✅)
"SELECT count(*) FROM node WHERE nullif(title, '') IS NOT NULL"
// mod.rs:427 — refill INSERT (NOT UPDATED ❌)
"INSERT INTO node_title_fts(rowid, id, title) \
SELECT rowid, id, title FROM node WHERE title IS NOT NULL"This is precisely the failure the author's own comment six lines above warns about:
The comment guards the count and misses the refill, which needs the identical guarantee. Verified against sqlite3: The consequence is a non-terminating repair loop. Once any database holds one empty-title row and desyncs once, every subsequent open finds I pinned this with a proof test (added temporarily, tree restored): The fix is one line, and I verified it resolves the proof test while keeping all 8 existing tests green: SELECT rowid, id, title FROM node WHERE nullif(title, '') IS NOT NULLWhy the 8-test suite missed it. This is the more instructive part. Recommended: apply the one-line fix, and extend 🟢 Verified correct: the transaction handlingI scrutinised this hard, as requested. It is correct on all paths.
🟢 Verified correct: doc-comment factual claimsTested against sqlite3 rather than trusted:
The
So the empty-string case is genuinely reachable in production, not hypothetical. That makes the 🔴 above a live defect rather than a latent one. 🟢 Verified: the three skip justifications are sound
🟢 Tests otherwise verified
The remaining gap is the one named in the 🔴: no test puts an empty-title row and the repair path in the same database. 🟢 Project standardsClean. No lint suppression, no RecommendationREQUEST CHANGES One blocker, one line to fix, plus one test line to pin it. The atomicity work is genuinely well done — I checked both rollback paths against The defect is a missed third site in a change the author correctly identified as a coupled multi-file invariant — and then guarded with a comment that names the exact failure mode while sitting six lines above the site that violates it. That is worth calling out as a blocker rather than an improvement for two reasons: the empty-string case is reachable in production through both documented routes, and the atomicity fix amplifies the symptom, turning a cheap wrong count into a write-locking full rebuild on every startup. The author's judgment in requesting this re-review was correct, and the reasoning given for it — a coupled invariant spanning files, where passing tests are self-verification — identified precisely the class of bug that was present. To merge:
Both are small, and everything else in |
malibio
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review (re-review): REQUEST CHANGES (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.
Re-review caught a blocker in the previous commit. The `nullif` change needed three sites, not two: the triggers and the staleness count were updated, the refill INSERT inside `refill_title_fts` was not. The refill therefore indexed empty-title rows the staleness count did not expect, so the two never agreed. A database holding one empty title that desynced once would find the index stale on every subsequent open, repair it, and land back in the same disagreement — a non-terminating repair loop. The atomicity fix in the same commit made that worse rather than better: it turned a cheap wrong answer into a guaranteed write-locking full-table rebuild on every startup. Verified directly: with rows 'Northwind', NULL and '', the refill writes 2 rows while the count expects 1, permanently. `title_fts_backfill_repairs_a_desynced_index` now seeds an empty-title row and reopens the database after the repair, asserting the second open is a no-op. The gap was that the repair path and the '' case were each covered but never met — the healthy-path test seeds '' and never desyncs, and this test seeded only a real title and NULL, so a refill that wrongly indexed '' satisfied both. Reverting the predicate now fails this test (left: 2, right: 1). The comment warning that these predicates must agree sat six lines above the count it guarded and did not mention the refill; it now sits on the refill too. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018ePBsnfpieijs3XGXWDBfo
Review TypeRe-Review #2 — scoped to Previous Review Summary
The blocker is genuinely fixed. All other prior findings were already dispositioned in the last round. The blocker: verified fixed📁 I grepped every title predicate across both files exhaustively. There are four functional sites, not three — the prior review's "three sites" undercounted by folding the two triggers into one. All four now agree:
( The new test genuinely pins it — verified independentlyI did not take the author's word for the Exactly as claimed. The other 7 title tests stayed green, confirming the new coverage is what catches it and not an incidental break. Tree restored and verified byte-identical (md5 One observation worth recording: it fails at the first assertion ( Requirements Check
Code Review Findings🟡 [Improvement] The convergence assertion proves the repair produced the right answer, not that it stopped running📁 The reopen is a genuine second open — I verified this. But the assertion is weaker than the comment above it claims. It asserts That is not hypothetical. I mutation-tested the mirror-image mismatch — leave the refill narrow ( All eight tests pass on a database that rebuilds its entire title index under a write lock on every single startup, forever. The arithmetic, confirmed against sqlite3 with rows Each open sees So the fix is correct and the test does pin the specific regression that was fixed — but the convergence property the test claims to establish ("reopening a repaired database must leave the index alone") is not what it actually checks. It checks that the repair is idempotent, which is a strictly weaker property and one that held even in the broken Recommendation. Assert that the repair did not run, rather than that its output was stable. The cheapest honest version is to observe the index identity rather than its cardinality — dirty the index in a way a refill would erase, then assert the dirt survives the reopen: drop(store);
// Mark the index. A refill DELETEs every row, so if this marker survives
// the reopen, the staleness check found the index healthy and skipped the
// repair — which is the convergence property, as distinct from the repair
// merely being idempotent.
{
let probe = SqliteStore::new(db_path.clone()).await?;
probe.write().await.execute(
"INSERT INTO node_title_fts(rowid, id, title) VALUES (9999, 'sentinel', 'sentinel')",
(),
).await?;
}…though note that inserting a row itself changes the count and would induce a repair. The cleaner formulation is to compare // The convergence invariant itself: the refill's predicate and the staleness
// count's must select the same rows, or the repair re-runs on every open.
// Asserting equality of the two counts catches a mismatch in EITHER direction;
// asserting the index count alone catches only a refill that is too wide.
let reopened = Arc::new(SqliteStore::new(db_path).await?);
assert_eq!(
title_fts_row_count(&reopened).await?,
titled_node_count(&reopened).await?,
"the index count and the staleness count must agree, or the repair \
rebuilds the whole index under a write lock on every open"
);with a small One honest caveat: the helper hard-codes the predicate a third time, so it pins the intended shape rather than tracking whichever predicate the production code happens to hold. That is the right trade here — a test that reads its expectation from the code under test asserts nothing — but it means the helper's literal is itself part of the invariant and should be commented as such. Filed as 🟡 rather than 🔴: the code under review is correct, the suite is green, and this is a gap in what a future regression would be caught by, not a defect in the shipped behaviour. It is a small, self-contained test change. 🟢 Coverage intersections: which remaining ones are realThe prior review's framing — the defect lived in the intersection of two tests that never met — is worth applying to what is left. Concretely, of the three you asked about:
The one real intersection is the one in the 🟡 above: repair path × a predicate mismatch in the count direction, which no test distinguishes from health. 🟢 [Nit]
|
…tion (#2841) Re-review #2 approved the blocker fix but flagged that the convergence assertion was one-directional, and mutation testing confirmed it: with the refill left narrow and the staleness count widened, all eight tests passed on a database that rebuilds its entire title index under a write lock on every startup, forever. Same class as the original blocker, mirrored, and the suite could not see it. Row counts cannot detect this. A repair that runs needlessly still leaves a correct index behind, so the resulting rows are identical whether the database was healthy or had just been rebuilt. My first attempt at a fix compared the index against an independently computed expectation, which still passed the mirror mutation for exactly that reason — both sides agreed on the row count while the count and the refill disagreed with each other. What distinguishes them is only the repair's own verdict, so `backfill_title_fts_if_stale` now returns `TitleFtsRepair::{AlreadyHealthy, Refilled}` and the test asserts that a second open of a just-repaired database reports `AlreadyHealthy`. That is the convergence property stated directly: after a repair, the index must satisfy the check that triggered it. Both mutations now fail: refill wide (original blocker): left: 2, right: 1 count wide (the mirror): left: Refilled, right: AlreadyHealthy Not done, per the reviewer's own recommendation: hoisting the predicate into a shared const. Two of the four sites sit inside CREATE TRIGGER bodies referencing `new.title` and two reference bare `title` in different statement shapes, so sharing means a format string with a column-qualifier hole — which would make the predicate ungreppable, and grepping for `nullif` across all four sites is how both rounds of this bug were actually found. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018ePBsnfpieijs3XGXWDBfo
Phase A of #2841 — the FTS5 prerequisite entity resolution needs. No routing behaviour changes.
Adds
node_title_fts, an FTS5 index overnode.title, so a named entity in a message can be resolved to the node that is it.titleis already the system's own maintained answer to "is this a nameable thing":compute_title()sets it for title-templated schema instances, tasks, collections and root nodes, and leaves it NULL for child/body nodes.A separate table, not a second column
The two indexes answer different questions:
node_ftsovercontentnode_title_ftsovertitleSharing a table would rank every node whose body merely mentions "Northwind" alongside the Northwind node itself, degrading both.
The content index stays —
bm25_search_rootsis not deadThe issue's prerequisite proposed deleting
node_ftsandbm25_search_rootsif no production consumer existed. One exists, and it is load-bearing:No call site outside tests spells
bm25_search_roots, which is why a name grep returns only test hits — the wrong search for a single-caller function behind a public wrapper. Deleting it would have droppedsearch_nodesto KNN-only.node_fts, its triggers, andbm25_search_rootsare therefore untouched.Standalone, not external-content — the load-bearing detail
FTS5 has no partial-index syntax, so "only when
title IS NOT NULL" is trigger logic. That rules out an external-content table, because'rebuild're-derives every row from the content table and silently reinstates the NULL-title rows the triggers skip. Verified directly:backfill_fts_if_staleissues exactly that rebuild fornode_fts, so an external-content title index would lose its partial shape on the first repair. A standalone table owns its own rows, so the invariant holds. Cost: it duplicates the title text — a short string per nameable node.Staleness repair
backfill_title_fts_if_stalemirrors the existing repair, with the two differences the partial standalone shape forces:count(*) FROM node WHERE title IS NOT NULL, notcount(*) FROM node. The plain node count would call a correct index stale on every open of any database holding a single child node.'rebuild'is unavailable for a standalone table and could not express the NULL skip anyway.count(*) FROM node_title_ftsis a real row count here, unlike the external-content case that forcesnode_ftsto read itsnode_fts_docsizeshadow table.Tests
Six, each verified to fail without the code it pins (guard removed, test run, guard restored):
skips_null_titlesremoves_a_node_whose_title_becomes_nullindexes_a_node_that_gains_a_titledrops_a_deleted_nodebackfill_treats_null_titles_as_healthybackfill_repairs_a_desynced_indexOne subtlety worth the reviewer's attention:
skips_null_titlesasserts index membership, not matchability. FTS5 stores a NULL title as a row with no terms, which noMATCHcan return — so an id-based query alone still passes when the guard is dropped. Only a row count catches it. That was caught by the fail-without-fix check rather than by reasoning.Not in this PR
Phase B (the offline sizing measurement) is deliberately deferred. The corpus it needs would be eval fixture prompts, whose entity names are absent from the graph by design — so the pass would mostly measure misses, an inverted signal rather than a noisy one. That number is the sole input to the general-mechanism-vs-special-case decision, so it should come from real messages or not at all.
Verification
cargo test --lib --bins --tests -p nodespace-core— all green, including the embedding/BM25 integration tests covering the untouched content indexbun run quality:fixclean; full pre-push gate passedPart of #2841 — deliberately does NOT close it. Phase B (sizing) and the routing tiers remain open on that issue.
🤖 Generated with Claude Code