Repository navigation
Release the reader cursor before a nested store read (closes #2410) - #2416
Conversation
Ten read-path methods in `SqliteStore` called another store method while their own result cursor was still live. `ReadRows` owns its reader connection until it drops, so the nested `self.read()` checked out a second connection and neither returned to the pool until the whole function ended — two connections pinned per call where one would do, halving effective concurrency against `MAX_IDLE_READERS` and inflating the pool's peak. Each site now drains its cursor into an owned value inside a scope, so the connection is back in the pool before the nested read runs: - nodes.rs: get_all_schemas, get_schema_node, get_subtree_with_relationships, assert_may_gain_parent - embeddings.rs: search_embeddings, search_embeddings_by_node_type, bm25_search_roots - relationships.rs: get_incoming_mention_containers, get_collection_by_name, get_collections_by_names The rule was documented but nothing caught a violation, so `Connections` now carries a `ReaderGauge` tracking live checkouts and their high-water mark. It is a gauge rather than an assertion deliberately: the store is legitimately read concurrently, so no fixed bound holds globally — the bound is a property of a single sequential call path, which is what the new regression test drives. Each assertion is paired with a check that the fixture actually reaches the nested call, so none of them can pass vacuously; each was confirmed to fail when its fix is reverted. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01HmwT4WEExtJZEoMddTrCS8
Pragmatic Code Review — PR #2416Review Type: Initial Review Requirements CheckAcceptance criteria from #2410:
Correctness of the ten rewrites — each checked individually, all semantically identical:
Gauge soundness — checked the paths you'd expect to leak:
I also empirically probed the one place the loop-scoping is non-obvious — Code Review Findings🟡 Important1. The gauge is unconditional in release builds, but only ever read under 📁
// connections.rs
fn checkout(&self) { … } // no cfg(test)
fn release(&self) { … } // no cfg(test)
#[cfg(test)]
pub(crate) fn peak(&self) -> usize { … } // only reader
#[cfg(test)]
pub(crate) fn reset_peak(&self) { … } // only readerTo be clear about magnitude: this is cheap. Relative to opening or checking out a SQLite connection and running a query, three uncontended relaxed atomics are noise, and I would not block on the cost. The issue is justification, not cycles — the code carries permanent machinery whose sole consumer is compiled out. A reader a year from now cannot tell whether the gauge is load-bearing in production or not, and the field's own doc comment points only at a test helper. Two defensible resolutions:
The first is smaller and matches YAGNI. The second is a real feature. What I would not leave is the current middle position. Principle: YAGNI / cost-transparency — production code should either serve production or be compiled out of it; machinery that does neither is unexplained weight. 2. Only 6 of the 10 fixed sites are covered by the regression test. 📁 The PR body says "each assertion is paired with a guard proving the nested call is actually reached, and each was confirmed to fail when its fix is reverted." The first half is true and well done — every assertion is genuinely non-vacuous, with an explicit fixture guard ( But the test has 7
This matters because the test is the entire enforcement mechanism the PR chose in place of an assertion. Criterion 4 was answered with "a test can assert the bound" — an untested site is one where that answer does not actually apply, and a future refactor could reintroduce the nested read in
gauge.reset_peak();
assert!(
store.get_schema_node("task").await?.is_some(),
"fixture must find the seeded schema, or get_schema_declarations is never reached"
);
assert_eq!(gauge.peak(), 1, "get_schema_node held a cursor across get_schema_declarations");
At minimum I'd add Principle: A regression test's value is exactly its coverage. Where a test is the sole substitute for a compile-time guarantee, gaps in it are gaps in the guarantee. 🟢 Suggestions3. Broken intra-doc link — 📁 /// one would do — and [`SqliteStore::peak_readers_in_flight`] lets a test
/// assert the bound directly instead of trusting review to catch it.
The actual accessor is Suggest: Principle: Comments that name a symbol are checked by readers, not by the compiler; a wrong name costs more than no name. 4. Nit: comment on 📁 The Genuinely optional. The comments are otherwise accurate — I checked each against the code it annotates and found no false claims. 5. Nit: the module doc's framing is slightly stronger than the mechanism delivers. 📁
"Rather than leaving the rule to review" overstates it while Finding 2 stands: for the four uncovered sites, the rule is still left to review. The sentence becomes true once coverage is complete — which is another reason to close that gap rather than reword this. What's good hereWorth saying explicitly, because it's the majority of the change:
RecommendationAPPROVE This is a clear net improvement: a correctly diagnosed real defect, fixed minimally at all ten sites with no semantic drift, plus an enforcement mechanism that is more than the issue asked for. The suite is green and clippy is clean. Findings 1 and 2 are worth addressing — I'd particularly like the two cheap test cases ( |
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.
Finding 1 (🟡): the gauge was maintained unconditionally but only readable under `#[cfg(test)]` — permanent machinery whose sole consumer is compiled out. Gated the whole thing (struct, field, `checkout`, `release`, the `ReadConn.gauge` field and the atomics import), so release builds carry none of it. Chose this over exposing the peak on daemon diagnostics: that would be a real feature, but it is scope creep for a bug-fix PR. Finding 2 (🟡): only 6 of the 10 fixed sites had a gauge assertion. Since the test is the entire enforcement mechanism chosen in place of an assertion, an uncovered site is one where that answer doesn't apply. Added the four missing — `get_schema_node`, `assert_may_gain_parent`, `search_embeddings`, `search_embeddings_by_node_type` — rather than only the two cheap ones. The embedding cases reuse the existing `unit_embedding` / `unit_query` helpers, so the fixture cost was low. Each new assertion was confirmed to fail (`left: 2, right: 1`) with its own fix reverted, so none passes vacuously. Finding 3 (🟢): fixed the broken intra-doc link — the referenced `SqliteStore::peak_readers_in_flight` never existed. Finding 5 (🟢): resolves itself now that coverage is complete; the module doc's claim is true as written. Finding 4 (🟢) skipped: the reviewer calls it genuinely optional and confirms the existing comments contain no false claims. Rewording nine accurate comments to mirror a tenth's phrasing is churn. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01HmwT4WEExtJZEoMddTrCS8
Review addressed —
|
Problem
Ten read-path methods in
SqliteStorecalled another store method while their own result cursor was still live.ReadRowsowns its reader connection until it drops, so the nestedself.read()checked out a second connection and neither returned to the pool until the whole function ended — two connections pinned per call where one would do. WithMAX_IDLE_READERSat 8, that halves effective concurrency and inflates the pool's peak, on paths that are called concurrently.Fix
Each site drains its cursor into an owned value inside a scope, so the connection is back in the pool before the nested read runs.
nodes.rsget_all_schemasget_all_schema_declarationsnodes.rsget_schema_nodeget_schema_declarationsnodes.rsget_subtree_with_relationshipsget_nodenodes.rsassert_may_gain_parentget_node_membershipsembeddings.rssearch_embeddingsget_nodeembeddings.rssearch_embeddings_by_node_typeget_nodeembeddings.rsbm25_search_rootsget_nodes_by_idsrelationships.rsget_incoming_mention_containersget_node_typerelationships.rsget_collection_by_nameget_noderelationships.rsget_collections_by_namesget_nodeOne correction to the issue's analysis: it lists the three
embeddings.rssites andget_subtree_with_relationshipsas calling the nested method inside the row loop. They don't — the loop completes first. The cursor simply stays in scope for the rest of the function, so the nested reads still run with it pinned. Same defect, same fix; onlyget_collections_by_namesgenuinely nests inside its loop.Making the rule checkable
The "do not nest a read under a live cursor" contract was documented but nothing caught a violation.
Connectionsnow carries aReaderGaugetracking live checkouts and their high-water mark.It's a gauge rather than a
debug_assertdeliberately: the store is legitimately read concurrently by many tasks, so no fixed bound holds globally. The bound is a property of a single sequential call path — which is exactly what the new test drives. The gauge's inspection accessors are#[cfg(test)], so nothing is added to release builds.Testing
New regression test
a_read_path_does_not_pin_a_second_connection_for_a_nested_readasserts a peak of 1 connection across seven representative call paths.Each assertion is paired with a check that the fixture actually reaches the nested call. This mattered: the first version of the test passed against the unfixed code, because the collection fixture had no
titleandget_collection_by_namematched no row — so the nestedget_nodenever ran and the assertion was vacuous. The same flaw hid two more cases (nohas_childedge, nomentionsedge). Each assertion was then confirmed to fail (left: 2, right: 1) when its corresponding fix is reverted.bun run test:all— green, no new failures vs. baseline (frontend 231 files / 4857 tests;nodespace-core1225 tests)bun run quality:fix— cleanNote on the pre-push gate
Pushed with
--no-verify. The gate'stest:e2ephase fails onmainfor a pre-existing, unrelated reason tracked in #2402, which documents that it forces exactly this workaround.Because this PR touches
get_all_schemas— the method those failing tests call — I verified the attribution rather than assuming it: runningschema-seeding.e2e.tsagainst a daemon built from this branch reproduces #2402's documented signature exactly (Tests 2 failed | 3 passed (5), the same two tests, same 30s timeouts). #2402 independently confirms the same failure against758f9f4dwith this branch's code reverted.Closes #2410
🤖 Generated with Claude Code
https://claude.ai/code/session_01HmwT4WEExtJZEoMddTrCS8