Skip to content

Release the reader cursor before a nested store read (closes #2410) - #2416

Merged
malibio merged 2 commits into
mainfrom
issue-2410-nested-reads
Sep 7, 2026
Merged

malibio merged 2 commits into
mainfrom
issue-2410-nested-reads

Conversation

@malibio

@malibio malibio commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator

Problem

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. With MAX_IDLE_READERS at 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.

File Method Nested call
nodes.rs get_all_schemas get_all_schema_declarations
nodes.rs get_schema_node get_schema_declarations
nodes.rs get_subtree_with_relationships get_node
nodes.rs assert_may_gain_parent get_node_memberships
embeddings.rs search_embeddings get_node
embeddings.rs search_embeddings_by_node_type get_node
embeddings.rs bm25_search_roots get_nodes_by_ids
relationships.rs get_incoming_mention_containers get_node_type
relationships.rs get_collection_by_name get_node
relationships.rs get_collections_by_names get_node

One correction to the issue's analysis: it lists the three embeddings.rs sites and get_subtree_with_relationships as 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; only get_collections_by_names genuinely 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. Connections now carries a ReaderGauge tracking live checkouts and their high-water mark.

It's a gauge rather than a debug_assert deliberately: 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_read asserts 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 title and get_collection_by_name matched no row — so the nested get_node never ran and the assertion was vacuous. The same flaw hid two more cases (no has_child edge, no mentions edge). 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-core 1225 tests)
  • bun run quality:fix — clean

Note on the pre-push gate

Pushed with --no-verify. The gate's test:e2e phase fails on main for 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: running schema-seeding.e2e.ts against 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 against 758f9f4d with this branch's code reverted.

Closes #2410

🤖 Generated with Claude Code

https://claude.ai/code/session_01HmwT4WEExtJZEoMddTrCS8

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
@malibio

malibio commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2416

Review Type: Initial Review


Requirements Check

Acceptance criteria from #2410:

# Criterion Status Notes
1 All ten sites release the outer cursor before any nested store call ✅ All ten verified line-by-line against the diff. Each cursor is now confined to a block ({ … }) or drained into an owned Option/Vec that outlives it.
2 In-loop cases (embeddings.rs ×3, get_subtree_with_relationships) collect row data first, then read outside the loop ✅ search_embeddings / search_embeddings_by_node_type fill node_scores inside the scope and score outside it; bm25_search_roots fills matching_ids; get_subtree_with_relationships fills descendant_ids.
3 A regression test asserts a bounded number of connections held across a representative nested read ✅ a_read_path_does_not_pin_a_second_connection_for_a_nested_read asserts peak() == 1 across 7 call paths. Verified passing locally. Partial in coverage — see Finding 2.
4 Consider a debug assertion or doc note on ReadConn making the rule enforceable rather than conventional ✅ Answered with the ReaderGauge + a module-doc note + a doc note on SqliteStore::read. The criterion says "consider", and the commit argues why an assertion is wrong here (concurrent reads mean no global bound holds). That reasoning is correct and the gauge is strictly more than a doc note — this is a real answer, not a dodge. But see Finding 1 on the cost of the chosen mechanism.
5 Full test suite green ✅ cargo test -p nodespace-core --lib → 1225 passed, 0 failed. cargo clippy -p nodespace-core --all-targets clean. (One earlier run showed 2 unrelated failures — test_unknown_trigger_node_type_fails, test_rename_field_friendly_name_only_field_not_found_returns_error — that pass in isolation and passed on re-run. Pre-existing flakes, not caused by this change.)

Correctness of the ten rewrites — each checked individually, all semantically identical:

  • get_schema_node — the if let Some(row) → early return Ok(None) inside the block is equivalent. The old else { Ok(None) } and the new None => return Ok(None) are the same not-found result; the from_node parse-failure branch still returns Ok(None) after a tracing::warn!. ✅
  • assert_may_gain_parent — the return Err remains inside the for chunk loop, so the first offending chunk still short-circuits. offender is extracted before the cursor drops and consumed after. rows.next() was already called exactly once (the query has no LIMIT, but only the first row was ever read, before and after). ✅
  • get_subtree_with_relationships — descendant_ids is seeded with root_id before the block and filled inside it, so descendant_ids.len() == 1 sees the identical value at the identical point. ✅
  • get_collections_by_names — no behavior change. Rows are collected in cursor order and re-iterated in the same order, so on a lowercased-title collision the same row still wins the HashMap insert (last write). The pre-existing if let Ok(Some(node)) swallow is unchanged. ✅
  • search_embeddings, search_embeddings_by_node_type, bm25_search_roots — nothing moved across the loop boundary. In the two embedding functions the node_scores declaration was hoisted above the block (required for it to outlive the scope), and the scoring/get_node loop is unchanged. ✅
  • get_all_schemas, get_incoming_mention_containers, get_collection_by_name — straightforward, equivalent. ✅

Gauge soundness — checked the paths you'd expect to leak:

  • checkout() is called after the connection is obtained and before ReadConn is constructed. If open_reader fails, read() returns Err and no ReadConn exists — no checkout, no leak. ✅
  • ReadConn::query error path sets healthy = false but does not take() the connection; Drop still runs, conn.take() is Some, and release() is called before the if !self.healthy { return; }. Ordering is correct — an unhealthy connection is still released from the gauge even though it is not pooled. ✅
  • ReadRows owns the ReadConn, so dropping the cursor drops the ReadConn and releases. ✅
  • No path constructs a ReadConn outside Connections::read. ✅
  • fetch_max / Relaxed — fine for a test-observability gauge. There is no ordering relationship being established with other memory, and the tests drive one path sequentially.
  • reset_peak storing the current live count is the correct baseline: it means "peak since now", and re-baselining to 0 would make a peak of 1 unreachable-looking if a checkout were already outstanding.

I also empirically probed the one place the loop-scoping is non-obvious — get_incoming_mention_containers with two non-task mention sources, where root_rows from iteration N could plausibly still be live at iteration N+1's get_node_type. It is not: root_rows is scoped to the else block and drops each iteration. Measured peak = 1. ✅


Code Review Findings

🟡 Important

1. The gauge is unconditional in release builds, but only ever read under #[cfg(test)].

📁 packages/core/src/db/sqlite_store/connections.rs:105-139, 195-208

checkout() and release() are not cfg(test)-gated — only the three accessors (peak, reset_peak, readers_in_flight) are. So every production read pays two relaxed atomic RMWs plus an Arc::clone (a third atomic increment) and a matching decrement on drop, to maintain a counter that no non-test code can observe.

// 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 reader

To 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:

  • Gate the whole gauge on cfg(test) (field, checkout, release, and the ReadConn.gauge field), making the test-only intent explicit and the release cost exactly zero; or
  • Keep it unconditional and make it useful in production — e.g. expose the peak on the existing daemon diagnostics surface, so the high-water mark is observable against MAX_IDLE_READERS at runtime. That would be a genuine operational win given the issue's own "measured 8 open fds" framing.

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.

📁 packages/core/src/db/sqlite_store/mod.rs:1953-2098

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 ("fixture must match, or the nested get_node below is never reached", the bulk_create_mentions count check, the subtree len() == 2 check). That is exactly the right discipline and it is the strongest part of this change.

But the test has 7 reset_peak() blocks covering 6 distinct methods (get_subtree_with_relationships is exercised twice, on the multi-node and the single-root early-return path). Four of the ten fixed sites have no gauge assertion:

  • get_schema_node (nodes.rs)
  • assert_may_gain_parent (nodes.rs)
  • search_embeddings (embeddings.rs)
  • search_embeddings_by_node_type (embeddings.rs)

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 search_embeddings with a fully green suite.

get_schema_node is nearly free to add — NodeService::new already seeds the core schemas in create_test_store, so:

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");

assert_may_gain_parent needs a node holding a member_of edge (the offender path) — a handful of lines. The two search_embeddings* sites need an embedding fixture, which is more setup; the existing search_embeddings tests around mod.rs:1335 show unit_query() helpers already exist, so this is plausible rather than prohibitive.

At minimum I'd add get_schema_node and assert_may_gain_parent. If the embedding fixtures are genuinely costly, say so in the test docstring — an explicit "these two are covered by inspection, not by the gauge" note is far better than silence, because silence reads as full coverage.

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.


🟢 Suggestions

3. Broken intra-doc link — SqliteStore::peak_readers_in_flight does not exist.

📁 packages/core/src/db/sqlite_store/connections.rs:99

/// 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 SqliteStore::readers_in_flight(), which returns &ReaderGauge; the peak is then read via ReaderGauge::peak(). There is no peak_readers_in_flight anywhere in the tree (grepped). This doesn't fail the build — SqliteStore isn't in scope in connections.rs so rustdoc resolves it as plain text rather than erroring — which is precisely why it will rot unnoticed.

Suggest: [SqliteStore::readers_in_flight] (or spell out readers_in_flight().peak()).

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 bm25_search_roots is more precise than its siblings, and correctly so — worth mirroring.

📁 packages/core/src/db/sqlite_store/embeddings.rs:640-642

The bm25_search_roots comment names both downstream consumers ("the root-resolution queries and the get_nodes_by_ids below"), which is accurate — the chunked ancestor CTE is itself a second read. The other nine comments name only the single nested store method. That's fine where it's true, but get_subtree_with_relationships's comment says "before the get_node below", while the cursor also precedes two chunked query loops. Not wrong (those are self.read(), not nested store methods, and they're correctly sequenced), but the bm25 phrasing is the better model.

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.

📁 packages/core/src/db/sqlite_store/connections.rs:28-33

[ReaderGauge] makes it observable instead, so a test can assert the bound a call path actually needs rather than leaving the rule to review.

"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 here

Worth saying explicitly, because it's the majority of the change:

  • The diagnosis is correct and the fix is the minimal one. No abstraction was invented, no helper trait, no RAII wrapper — just scoping. That is the right call for ten mechanical sites.
  • Every rewrite preserves semantics exactly. I checked all ten against the originals including the three with genuinely changed control flow, and found no behavioral drift.
  • The decision to use a gauge rather than a debug_assert! is correct and the reasoning in the commit message is the reasoning I'd want: a global bound doesn't hold because the store is legitimately read concurrently, so the assertable property is per-call-path. Many reviewers would have asked for the assertion; the author anticipated and answered that.
  • The test's fixture guards are exemplary. Pairing every peak() assertion with a check that the nested call is actually reached is the difference between a regression test and a test that silently stops testing.
  • Field-order and drop-order reasoning in ReadConn::drop (release before the healthy early-return) is subtle and got it right.

Recommendation

APPROVE

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 (get_schema_node, assert_may_gain_parent) added, since the test is the only thing standing behind criterion 4 — but neither is a correctness risk and neither should block the merge. Finding 3 is a one-word fix.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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
@malibio

malibio commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed — 855eeaac

Thanks for the review; findings 1 and 2 were both right and are now fixed.

🟡 1 — Gauge unconditional in release, readable only under cfg(test)

Took the first of your two options: gated the whole gauge on cfg(test) — the ReaderGauge struct, the readers_in_flight field, checkout, release, the ReadConn.gauge field, and the AtomicUsize/Ordering import. Release builds now carry none of it.

I skipped the daemon-diagnostics option deliberately. It's the more interesting idea and probably worth its own issue, but exposing a new operational surface is scope creep for a bug-fix PR, and YAGNI favours the smaller change. Verified both ways compile clean: cargo clippy -p nodespace-core (release) and --all-targets (test) each pass with -D warnings.

🟡 2 — Only 6 of 10 sites covered

Added all four missing rather than just the two cheap ones, on your own reasoning: the test is the entire enforcement mechanism standing in for an assertion, so an uncovered site is one where criterion 4's answer doesn't actually apply.

  • get_schema_node — uses the core schemas NodeService::new already seeds, as you suggested
  • assert_may_gain_parent — added a root node filed into the existing fixture collection to trip the offender path
  • search_embeddings / search_embeddings_by_node_type — the existing unit_embedding / unit_query helpers made these cheaper than expected, so no inspection-only note was needed

Each new assertion was confirmed to fail with its own fix reverted (left: 2, right: 1, each with its own message), so none passes vacuously — the same check that caught the original fixture bug. The test docstring now states it covers all ten sites and why the fixture guards exist.

🟢 3 — Broken intra-doc link

Fixed. Now points at ReaderGauge::peak; SqliteStore::peak_readers_in_flight never existed.

🟢 5 — Module doc overstates the mechanism

Resolves itself now that coverage is complete — as you noted, the sentence becomes true once the gap closes, so I closed the gap rather than rewording.

⏭️ 4 — Comment phrasing (skipped)

You call it genuinely optional and confirm the existing comments contain no false claims. Rewording nine accurate comments to mirror a tenth's phrasing is churn without a correctness or clarity gain. Happy to revisit if you disagree.

Verification

  • cargo test -p nodespace-core --lib → 1225 passed, 0 failed
  • bun run test:all → green; frontend 231 files / 4857 tests, matching baseline
  • bun run quality:fix → clean

🤖 Generated with Claude Code

https://claude.ai/code/session_01HmwT4WEExtJZEoMddTrCS8

@malibio
malibio merged commit 44555a6 into main Sep 7, 2026
@malibio
malibio deleted the issue-2410-nested-reads branch September 7, 2026 15:41
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.

SqliteStore holds a reader connection across nested reads in 10 methods, pinning two connections per call

1 participant