Repository navigation
fix(query): restore fast paths after cached index adoption - #1967
Conversation
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz I will admit that I got very confused while reading this because I knew you and I had talked about this a while ago and so was surprised that we were suffering from this issue. It turns out we were right back then (#1305 (comment)) and the problem was just that the method you introduced back then as a result (is_effectively_empty()) just didn't have the call-site coverage it deserved and we never noticed it (still produced correct results; just not performant ones). I do think it gives a little more clarity into where we may still be missing out on this perf win, which is to say, anywhere still checking epoch = 0 or epoch != 0 directly rather than using is_effectively_empty() etc. In any event, full review below (and glad to have the wins regardless)
No single PR lost these fast paths: 5985d0f01 ("fluree v4 baseline") introduced the epoch() == 0 gates and in-place cached index adoption in the same commit, so the counter-as-emptiness assumption has been wrong since v4 day one — clear_up_to does self.epoch += 1 (fluree-db-novelty/src/lib.rs:1231), so a drained, indexed, cached handle is epoch-nonzero forever. You already diagnosed exactly this in #1448 and built the right helper; these sites were simply missed. git blame puts every one of them before 40f1095f9, and git tag --contains 5985d0f01 puts the original in v4.0.0 through the current v4.2.1. So this is a ~5-month shipped performance regression, live in every v4 release we've published, on a production steady state (long-running server, cached handle, background index, LIMIT query) rather than an edge case.
That's why I'd ask about merge order rather than just approving into the stack. This PR's diff is textually independent of both parents — no file overlap with #1965 at all, and its only shared file with #1959 is binary_scan.rs, where #1959 changes module docs (lines 1–11) and this changes 1369–1375 and 2852 — so a cherry-pick onto main should apply clean. Given it fixes something users are hitting today while #1959/#1965 are still in review, is there a reason not to retarget this one to main and land it first? Your call; I just don't want it to sit behind a perf PR that's still answering questions.
On the substance, I couldn't break it. Retraction-only overlays are safe (is_effectively_empty bottoms out in flake_count == 0, and a retraction flake is still a flake — your own unit test asserts this); epoch == 0 with flakes present is impossible since every flake-adding path bumps epoch; and the fatal case, a drained overlay paired with a stale store, can't happen because ExecutionContext takes binary_store and overlay from the same GraphDbRef and apply_index replaces snapshot, novelty and the dict novelty together. Mutating binary_scan.rs:1375 back to the epoch gate reproduces your headline exactly — 23.01 fuel, versus 3.01 with the fix.
The notes are all non-blocking. binary_scan.rs:2538 still has the coarse if ctx.overlay.is_some() gate — the last one, in the file you fix twice, and per the comment at :2529 it's a mutex acquisition per probe row inside a nested-loop join. Only 4 of 9 OverlayProvider impls override is_effectively_empty, so reasoning, staged and historical views get nothing here (safe, but the body implies broader). The /info change is a separate concern riding along, and it collapses commit-t into t by construction, which quietly removes the gap it_notify_incremental.rs exists to model. And the thing I'd most like written down somewhere: query_overlay_matrix.rs's three conditions all call .load(), so they're all epoch-0 by construction — the cached-handle steady state is benched nowhere, which is the structural reason this survived five months.
One thing worth flagging for whoever merges: there is no CI on this head at all — only the cargo-dist release workflow ran; no test, clippy, fmt, or testsuite-sparql. The local runs below are the only machine verification this has had, and fast_vector_topk.rs — behind the vector feature, which doesn't build here (usearch → cxx missing <algorithm>) — has had none at all.
Adherence to repo commitments:
- Patterns/abstractions: ✔ Net-deletes abstraction: removes
cyclic_bgp.rs's duplicate helper, consolidates the cursor identity-column projection, and threadsepochout of six functions — all converging on #1448's existingoverlay_has_novelty. - Performance (speed first, memory second): ✔ Strongly positive, and verified to the decimal (23.01 → 3.01 fuel by mutation). No path made slower. Two caveats: one coarse gate remains at
binary_scan.rs:2538, and 5 of 9 overlay impls see no change. - Testing: ✔ All touched test files are wired and run (
grp_index.rs:22-23,grp_http.rs:18, plus an in-cratemod tests); fuel-parity assertions are the right instrument.⚠️ No bench covers the cached-handle condition, andfast_vector_topk.rs's conversion is unverified by any run. - Conventions:
⚠️ Clippy-clean under--all-targetsand fmt-clean; both commit bodies are empty on a change whose whole value is the explanation.
Verified locally at branch HEAD 80cb8bc01: cargo test -p fluree-db-query --lib --offline → 1634 passed / 0 failed / 1 ignored; grp_index::published_index_matches_fresh_query_on_cached_handle → ok (10 shapes, result and fuel parity across two publications and an intervening write); grp_http::http_queries_use_fast_paths_after_background_index_publication → ok; cargo clippy -p fluree-db-query --all-targets -- -D warnings and cargo fmt --all --check → clean. Mutation checks: binary_scan.rs:1375 → RED at 23.01 fuel; fast_path_plus_count_all.rs:90 → RED. No wall-clock timing taken — the box was at load average 37.9, so I measured only deterministic fuel.
Approving so you can merge when ready — but I'd genuinely like an answer on whether this should jump the stack to main, given it's fixing something that's been live in every v4 release since April.
| @@ -2849,10 +2850,7 @@ impl Operator for BinaryScanOperator { | |||
| &self.inline_ops, | |||
There was a problem hiding this comment.
fluree-db-query/src/binary_scan.rs:2850 — optional; the real subject is binary_scan.rs:2538, which isn't in this diff, so I'm parking it on the other hunk in the same file. binary_scan.rs:2538 still reads if ctx.overlay.is_some() { — the coarse gate, in the very file this PR fixes twice.
Because ExecutionContext always carries a provider (the comment at :2529 says as much), that block runs on every scan open even when the overlay is drained: content_version(), a translated_overlay_cache.lock() plus map probe, a global_translation_cache() probe, a trivially-empty translate walk, and a global-cache insert of an empty entry. And :2529 also notes that per-row join probes re-open a scan per left row — so inside a nested-loop join that's a mutex acquisition per probe row, for an overlay we now know is empty.
Guarding it with overlay_has_novelty(ctx) is a one-liner of exactly the class this PR is already making. I'm calling it non-blocking deliberately: there's no correctness impact, the per-execution memo bounds steady state to one lock plus one hash get, and it costs a freshly-loaded ledger the same as a cached one — so it isn't part of the regression you're fixing. But it is the last one, it's in this file, and if you agree it's right I'd rather see it folded in here than left for whoever writes the next "restore fast paths" PR.
There was a problem hiding this comment.
Folded in (c68a92f), but guarded with the overlay's own is_effectively_empty() rather than overlay_has_novelty.
overlay_has_novelty also returns false whenever epoch() == 0. That is safe at the fast-path gates, because a wrong "no novelty" there only declines a fast path and the generic scan still merges the overlay. This block is that generic merge, so a wrong answer here would drop rows. DerivedFactsOverlay takes its epoch from its caller, so an overlay with rows and a zero epoch is not impossible.
is_effectively_empty() defaults to false for overlays that can't vouch for it, so it errs on the side of translating.
published_index_matches_fresh_query_on_cached_handle now checks both directions:
- the drained handle's scan never opens
overlay_translate; - after the next write, the scan does open it.
The second check means the first can't pass on a tracing subscriber that missed the span. With the old is_some() gate restored, the test fails on the drained assertion.
| @@ -767,18 +767,6 @@ fn graph_display_name(g_id: GraphId, store: Option<&BinaryIndexStore>) -> String | |||
|
|
|||
There was a problem hiding this comment.
fluree-db-api/src/ledger_info.rs:767 — more of a question than a suggestion, on scope. The /info change is a separate concern riding along in a perf-restoration PR, and it makes one behavior change I don't think the body flags.
commit_t: Some(ledger.t()) and t: Some(ledger.t()) are now the same expression, so /info's commit-t is definitionally identical to t. In the multi-node "cache falls behind another writer" scenario that it_notify_incremental.rs exists to model, /info can no longer show that gap — the two fields move together by construction. Was that intended?
Separately, the index_t half looks like a no-op: both apply_index and apply_loaded_db already write record.index_t = self.snapshot.t, so ns_record.index_t and ledger.index_t() already agreed after any install. Only the commit_t half is substantive (nothing refreshes record.commit_t on commit), which makes "commit/index timestamps" in the body a slight overstatement.
Blast radius is genuinely small — no golden or snapshot test pins the old values (it_indexing_stats.rs:1577 only asserts commit-t is present), and the CLI's commit_t reads in remote_client.rs, commands/branch.rs, list.rs and sync.rs all go to the nameservice record rather than /info. So I'm not asking for it to be split out; just for a sentence in the body naming the commit-t == t collapse so it isn't discovered later.
There was a problem hiding this comment.
Intended, and I don't think it loses a real signal. The old commit-t came from ns_record, which is set only when the LedgerState is built. notify looks up a fresh record to plan its update, but never stores it on the state.
So on a cached handle the old value was the t at load time:
- after a local commit, it was stale;
- after a commit from another writer, applied through
CommitCatchUp, it was stale too; - it never showed another writer's head ahead of the cache.
You're right that the index_t half was a no-op. The body now says commit-t always equals t and why, and no longer says "commit/index timestamps". If we want /info to show a node falling behind another writer, it would need a live nameservice lookup, which is a separate change.
Merging main broke this test's NsRecord::new call (it now takes a single ledger id); b824742 fixes it.
| @@ -3032,12 +3014,27 @@ pub fn build_overlay_cursor_for_subject_range( | |||
| projection, | |||
There was a problem hiding this comment.
fluree-db-query/src/fast_path_common.rs:3014 — optional, and really a body note. The PR reads as a broad restoration, and it's narrower than that: only 4 of 9 production OverlayProvider impls override is_effectively_empty. NoOverlay, Novelty, SizedOverlayRef and CompositeOverlay do; StagedLedger (fluree-db-ledger/src/staged.rs:327), HistoricalLedgerView (historical.rs:469), DerivedFactsOverlay (fluree-db-reasoner/src/overlay.rs:207), ReasoningOverlay (fluree-db-query/src/reasoning.rs:61) and SchemaBundleOverlay (schema_bundle.rs:387) inherit the conservative false default. For those, overlay_has_novelty still reduces to epoch != 0 and the fast paths stay off.
That's the safe direction and I'm not suggesting you change it here. But it means reasoning, staged-view and historical queries get nothing from this PR, and a reader of the body would reasonably assume otherwise. One sentence would fix it.
There was a problem hiding this comment.
Agreed. The body now says which overlays benefit: plain novelty, sized and composite overlays, and the empty overlay. It also says that staged, historical and reasoning views and schema bundles keep the conservative default, so their fast paths stay off after indexing as before.
| @@ -16,6 +16,152 @@ use fluree_db_api::{ | |||
| use fluree_db_transact::{CommitOpts, TxnOpts}; | |||
There was a problem hiding this comment.
fluree-db-api/tests/it_notify_incremental.rs:16 — optional, and the highest-value follow-on I found. This is the structural reason the bug survived five months: fluree-db-api/benches/query_overlay_matrix.rs has exactly three conditions, and its own comment names the first // --- condition: base (indexed, epoch 0) ---. All three build state with fluree.graph(&alias).load() — a fresh load, which always yields a fresh Novelty at epoch 0. The production steady state this whole PR is about (cached handle, indexed, drained, epoch ≠ 0) is benched nowhere; grep -rE "apply_index|rebuild_and_publish|ledger_cached|clear_up_to" across both bench dirs only hits annotation_hydration.rs and annotation_planner.rs.
A fourth condition on query_overlay_matrix — cached handle after a publish — would have caught this in v4.0.0 and would catch the next one. Your integration test already proves the behavior; the bench is what makes nightly defend it. I know that's the largest ask here and I'd understand pushing it to its own PR — but if so, could it be an issue you file with the measurement in hand, rather than a note in a merged body?
- Both commits (no diff line — belongs in the body) — nit.
fix(query): restore fast paths after cached index adoptionandfix(query): share live novelty checks across remaining pathsboth have empty bodies. All the substance is in the PR body — the epoch-never-returns-to-zero mechanism, the fuel numbers, the scope. Given how hard this bug was to find from the code alone (five months, and the first fix in fix: close Cypher benchgraph gaps and add benchmark-critical fast paths #1448 got the helper right but missed these sites), thegit logreader doing the next round of this archaeology is the exact person who needs it. Your own fix: close Cypher benchgraph gaps and add benchmark-critical fast paths #1448 commit body — premise, measurements, live verification — is the model.
There was a problem hiding this comment.
Added in this PR (c68a92f). query_overlay_matrix has a fourth condition, cached:
- Populate through
ledger_cached+stage(&handle). - Index with
trigger_index, so the publication listener installs the root on that handle in place. - Assert the handle is indexed, drained, and has a nonzero epoch.
reindex couldn't be used, because it disconnects the cached handle and the next load starts fresh at epoch 0.
Measured on EC2 with the same bench file built against main and against this branch (thin LTO on both):
| Scenario | Base condition | cached, main |
cached, this PR |
|---|---|---|---|
| star, small | 1.18 ms | 2.89 ms | 1.22 ms |
| group-by, small | 1.30 ms | 11.03 ms | 1.37 ms |
| star, medium | 8.65 ms | 22.49 ms | 8.87 ms |
| group-by, medium | 13.32 ms | 110.88 ms | 13.09 ms |
So on main the new condition shows the regression at 2.4–8.5×, and this PR brings it back to the base condition's numbers. The three existing conditions stay within run-to-run noise. query_overlay_matrix is already in the nightly compare subset, so the new scenarios show up there as new rather than failing until a baseline includes them.
On the commit bodies: the merge of main is already pushed, so rewriting those two commits would mean force-pushing over it. I've left them. The PR body carries the explanation, and the new commit has a full body.
| @@ -684,7 +684,7 @@ impl CyclicBgpOperator { | |||
| }; | |||
There was a problem hiding this comment.
fluree-db-query/src/cyclic_bgp.rs:684 — this PR deletes a duplicate rather than adding one: the private overlay_may_have_facts was already byte-equivalent to the shared helper, and its four call sites now use fast_path_common::overlay_has_novelty. Same story with overlay_cursor_projection consolidating identity-column logic that had been copy-pasted between the serial and parallel cursor builders, and with the epoch parameter threaded out of six functions. Converging on #1448's existing helper instead of inventing a second predicate is the repo's "extend the shared mechanism" rule done right, and it's the reason the diff is net-simpler than its line count suggests.
| @@ -16,6 +16,152 @@ use fluree_db_api::{ | |||
| use fluree_db_transact::{CommitOpts, TxnOpts}; | |||
There was a problem hiding this comment.
fluree-db-api/tests/it_notify_incremental.rs:16 — assert_cached_queries_match_fresh asserting fuel parity and not just result parity is what makes this a real fast-path regression net rather than a correctness smoke test. Results would have matched throughout the five months this bug was live; only fuel tells you which lane served the query. Keeping the original cached handle across two index publications and an intervening write is the right fixture shape too.
| @@ -2993,20 +2984,11 @@ pub fn build_overlay_cursor_for_subject_range( | |||
| hi: u64, | |||
There was a problem hiding this comment.
fluree-db-query/src/fast_path_common.rs:2984 — I went at the parallel-cursor change hardest, because "a cursor that skips a merge it needed drops rows" is the scary version of this. It can't: the set_overlay_ops condition goes from epoch != 0 && !sliced.is_empty() to !sliced.is_empty(), and ops cannot be non-empty at epoch 0, so the gate is effectively unchanged; the real change is the projection, and overlay_cursor_projection only ever widens internal, never output, so the widening now happens exactly when the merge runs — a tighter invariant than before. All six call sites check out: none calls set_overlay_ops on the returned cursor, and every consumer reads only s_id/o_type/o_key/row_count, all in output.
A scan still translated the overlay on every open after an index install had drained a cached handle's novelty: a lock and cache probes per scan, and per probe row in a nested-loop join. It now asks the overlay whether it is empty. It does not use `overlay_has_novelty`, which also trusts a zero epoch: this is the scan's only overlay merge, so a wrong answer here would drop rows rather than decline a fast path. query_overlay_matrix gains a `cached` condition: populate through a cached handle and index in the background, leaving it indexed and drained with a nonzero mutation counter. The other conditions load the ledger fresh, at epoch 0, which is why no bench caught the fast paths this PR restores.
|
@aaj3f on the review-level points:
The inline threads have the rest: the scan gate, |
…dex states Pins the answers a single-triple OPTIONAL and the equality surfaces must give whichever form a row carries a term in, on a ledger that is - loaded fresh with the index covering every commit (overlay epoch 0), - written through a cached handle that then adopted an index (novelty drained, epoch nonzero: a long-running server after #1967), or - carrying novelty the index does not cover. Each case checks a hand-written expectation in all three states, and that the OPTIONAL's lookup ran with its correlated slot bound (no scan of the triple with that slot left a variable). SPARQL, JSON-LD, the WHERE of a SPARQL UPDATE, and Cypher's OPTIONAL MATCH. Red on main: on the encoded lane the OPTIONAL drops matches whose correlated value is an encoded predicate (`?p rdfs:label ?l` after `ex:s1 ?p ?o`) or an encoded subject used as a predicate, and scans the whole predicate for an encoded object. DISTINCT, GROUP BY, MINUS, EXISTS, NOT EXISTS and a trailing VALUES treat one IRI met as a predicate and as a subject as two terms. With novelty pending, an OPTIONAL after a batched join drops every match.
Cached ledgers kept taking slower query paths after background indexing had installed the binary index and drained novelty. Several operators treated the overlay mutation counter as an emptiness check, but that counter remains nonzero after indexing. Scans therefore decoded whole batches before LIMIT, and other operators declined their indexed fast paths until the ledger was reloaded.
Use the shared live-novelty check for scan materialization, encoded filters, counts, ordering, fulltext deltas, and absent-predicate fallbacks. Parallel cursors use their actual overlay rows to decide whether merging is needed, and share the identity-column projection helper with serial cursors. Preserve the mutation counter for cache invalidation.
Only overlays that can report that they are empty benefit: plain novelty, sized and composite overlays, and the empty overlay. Staged, historical and reasoning views, and schema bundles, keep the conservative default, so their fast paths stay off after indexing as before.
A scan also skips overlay translation when the overlay is empty, instead of taking a lock and probing two caches on every open, which in a nested-loop join means every probe row. It asks the overlay directly rather than using the shared check, which also trusts a zero mutation counter: this is the scan's only overlay merge, so a wrong answer there would drop rows, not just decline a fast path.
/infonow reports the watermarks of the state serving the request, socommit-talways equalst. It used to come from the nameservice record saved when the ledger was loaded. Nothing updates that record afterwards, so after the first commit it was stale, and it never reflected another writer's head.index-talready matched after an index install.The regression reproduces 23.01 versus 3.01 fuel for a 2,000-subject LIMIT query on cached versus freshly loaded state; the fix makes them equal. Coverage keeps the original cached handle through two index publications and an intervening write, comparing results and fuel across ten query shapes. An HTTP regression exercises create, Turtle insert, background indexing, tracked query, and info without reloading the ledger.
A property-path regression covers absent overlays, explicit empty overlays, repeated novelty draining with a nonzero epoch, subsequent writes, and retraction-only overlays. Pending facts still require the generic fallback.
query_overlay_matrixgains acachedcondition: a ledger populated through a cached handle and indexed in the background, so the handle is indexed and drained with a nonzero mutation counter. The other conditions load the ledger fresh, which always starts the counter at 0, which is why no bench caught this. Comparing the bench onmainwith this branch (EC2, both built with thin LTO):cached,maincached, this PRcountwas already on its fast path in both builds. Every scenario in the other three conditions moved by less than 2.5%, the spread seen between two runs of the same build.Validation after merging
main:--all-featuresclippy and nextest jobs, which build thevectorfeature thatfast_vector_topk.rsneeds.fluree-db-query --lib,grp_index,grp_query(three runs),grp_query_sparql, thefluree-db-servergrp_httpgroup, the/infounit tests, and clippy with warnings denied across all targets of the query, API and server crates.Validation before merging
main: