Repository navigation
perf(query): a correlated scan takes the store id its row already has - #2415
Conversation
A join or OPTIONAL probing one row at a time bound the row's store id into the scanned pattern as the IRI it decodes to, and the scan then looked that IRI up in the subject dictionary again: a leaf search per probe that ended at the id it started from. DESCRIBE expansion, variable-predicate probes and OPTIONAL's per-row lookups all paid it. Substitution now also records the id, with the store whose dictionary assigned it, and the scan takes it for the bound subject or object instead of looking the IRI up. The pattern stays bound, so the range, policy and history paths that read the pattern are constrained as before. The id is taken only from a persisted id of the store being scanned; a novelty id, or another store's, takes the lookup. Scans emit store ids only while the ledger has no unindexed commits, so this applies to an indexed ledger between writes. The subject dictionary reader counts reverse lookups that search a leaf, which the tests read.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is a nice, narrow design: the id rides beside the still-bound pattern, scoped to its store and the watermark. On a box it took 5–11% off correlated probes on an indexed ledger; the one must is the test-only lookup counter, which shows up under concurrency.
One correction worth folding in: ids do reach probes while commits wait to be indexed, because the batched subject probe emits refs as EncodedSid. So the persisted-only guard is live today (Claude watched it turn away a novelty id), and it deserves the test the body says isn't needed. Also, #2214 merged this morning, so on main is_persisted_subject_id needs to move onto TermView.
Full review below:
✅ Approving to unblock: please get the leaf-lookup counter off the hot path before merging. Taking the id the row already has, instead of looking up the IRI it decoded to, is a clean saving. On the box it measured −9.4% (join with a variable predicate), −5.5% (OPTIONAL), −10.7% (object position) and −5.2% (DESCRIBE) on an indexed ledger, about half a microsecond per probe, with identical answers and the batched, point-lookup and single-probe controls flat. The one must is the test-only counter, which costs 4–9% per reverse lookup under concurrency.
Before merging:
fluree-db-binary-index/src/dict/reader.rs:329: gateleaf_lookupsbehind a dev-only feature (asresidencyis), or count via a trace event; under 2–32 threads it costs 4–9% per reverse lookup.
Notes:
- Ids reach probes under novelty via the batched subject probe, so the persisted-only guard is live (inline on
join.rs:785): a test for it, and a sentence in "Where it applies", would match the code. - Stack altitude: this needs #2413. Its DESCRIBE path takes ids only because #2413's third commit makes
BIND(?x AS ?y)copy them, and it sharesgrp_query_sparql.rsandjoin.rswith the commits below. Rebased ontomain, it has to absorb #2214'sTermViewsignature (inline onbinary_index_store.rs:3652).git merge-treeagainst my #2419 and #2201 is clean. - The same-store guard is unreachable today (inline on
binary_scan.rs:834), and so is a rebuild between plan and open: the store comes from the query'sExecutionContext. History scans never receive ids (dataset_operator.rs:177-186).
Adherence: Patterns ✔ · Performance ✖ · Deployment ✔ · Testing ⚠️ · Conventions ⚠️ · verification
- Patterns/abstractions: ✔ extends
substitute_bindingandScanDatasetBuilderrather than adding a lane; follows the codebase's existing rule that an id never crosses the dictionary that minted it. - Performance (speed first, memory second): ✖ the per-row path gains −5.2% to −10.7% on indexed correlated probes (single-client release A/B, every row in the summary), but the test-only
leaf_lookupscounter adds a shared RMW per reverse lookup: +4.4% to +8.8% at 2–32 threads (memory storage) and +6.7% to +7.9% at 2–8 threads (file storage) against the same head without it. Fix inline onreader.rs:329. - Deployment targets: ✔ shared query code every host runs; the new state is per scan, and the store id it compares is the existing process-unique counter, so nothing assumes a long-lived process or a filesystem.
- Testing:
⚠️ it_correlated_store_ids(7 tests, wired intogrp_query_sparql) passes and pins the subject, object and OPTIONAL parts; the persisted-only guard is reached under novelty and no test pins it. - Conventions:
⚠️ thorough commit body, but its "applies to an indexed ledger between writes" (and the body's "Where it applies") is narrower than the code.
Verified at ff2bf98a1: CI has not run on this head (release-workflow checks only); gates are gate-stack's. On a c7i.4xlarge, Claude ran the PR's 7 tests (pass), answer-and-stamp probes at #2413 and this head, a mutation of each guard (persisted-only: 1 → 2 stamps under novelty, answers unchanged; same-store: no change), a fourteen-shape BIND probe, and a release A/B (3 interleaved runs per side); git merge-tree against #2419, #2201, #2422 and main.
Approving so you can merge once the counter is off the hot path, and maybe worth folding in the novelty test and the "Where it applies" sentence too.
| None => return Ok(None), | ||
| }; | ||
| let find_leaf = clock.lap(); | ||
| self.leaf_lookups.fetch_add(1, Ordering::Relaxed); |
There was a problem hiding this comment.
Blocking (performance).
leaf_lookups adds a shared read-modify-write to every subject reverse lookup, from every query thread, and only the tests read it. Under concurrency it shows.
It is one AtomicU64 per dictionary tree, so every thread looking up a subject on the store fetch_adds the same cache line, on top of the per-load cache_hits/cache_misses adds load_leaf already makes. Every constant IRI, VALUES row and batched-lane key still takes this path; this PR removes only the correlated probes' lookups.
Claude timed find_subject_id from 1 to 32 threads on one indexed store: 100,000 subjects, release builds, a 32-vCPU box, 3 interleaved runs. It compared this head with this head minus the fetch_add, so the struct layout is identical. Single-threaded it's flat (−0.1% on memory storage, −1.4% on file storage). From 2 to 32 threads the counter costs +4.4% to +8.8% per lookup on memory storage, and +6.7% to +7.9% at 2–8 threads on file storage (flat at 16–32). 23 of 30 paired runs went the same way. Binary-to-binary noise on this bench reaches about 13%, so the size is soft, but the direction isn't. It's the same contention shape #2405 just took out of the leaflet cache.
The repo already has the pattern for keeping this off the production path: residency is a fluree-db-binary-index feature that fluree-db-api enables only through its dev-dependency, so release builds compile without it (resolver 2):
# fluree-db-binary-index/Cargo.toml
[features]
test-counters = []
# fluree-db-api/Cargo.toml, [dev-dependencies]
fluree-db-binary-index = { path = "../fluree-db-binary-index", features = ["residency", "test-counters"] }#[cfg(feature = "test-counters")]
self.leaf_lookups.fetch_add(1, Ordering::Relaxed);Gate the field and subject_reverse_leaf_lookups() the same way. Another option is a tracing::trace! event per leaf lookup that the tests count with span_capture: when no subscriber listens, a disabled callsite costs a read, not a write.
| }, | ||
| } | ||
| if let (Binding::EncodedSid { s_id, .. }, Some(gv)) = (binding, gv) { | ||
| if position != PatternPosition::Predicate && gv.is_persisted_subject_id(*s_id) { |
There was a problem hiding this comment.
Optional (test + body correction).
This guard is reached today: ids do get to a probe while commits are waiting to be indexed, because the batched subject probe emits them.
The body (and the commit message) says scans decode their rows under novelty, so "no id then reaches a probe". That's true of BinaryScanOperator's own output (binary_scan.rs:1530-1537). It isn't true of the batched subject probe: subject_lane_object_binding returns a ref object as Binding::encoded_sid(o_key) unless the caller is eager (join.rs:3590-3606). That includes the novelty-only asserts it injects (:2649-2680), whose o_key can be a novelty id. So a per-row probe downstream of a batched hop gets EncodedSids with novelty present, persisted ones and novelty ones alike.
Claude checked this on a box. Take an indexed ledger, then an unindexed ex:b ex:knows ex:n . ex:n ex:name "n" ; ex:knows ex:c, then ex:a ex:knows ?x . ?x ex:knows ?y . ?y ?p ?o. At this head it stamps correlated store ids: proceed once: the persisted ?y takes its id and the novelty ?y takes the lookup. The OPTIONAL and object-position variants and a DESCRIBE over it do the same. Drop && gv.is_persisted_subject_id(*s_id) and it's two stamps, with answers unchanged (the novelty id is what novelty_subject_id would have put in the filter anyway), and all seven tests in it_correlated_store_ids still pass. So the guard is defense in depth rather than load-bearing in these shapes, but it is live, and nothing would notice it going.
Maybe add that chain to it_correlated_store_ids asserting one proceed stamp, and say in "Where it applies" (and the commit body) that rows from the batched subject probe carry ids under novelty too, with this guard keeping a novelty id out? The comment on probes_answer_from_novelty repeats the "no probe has a store id" claim; its one-hop shape never feeds the batched lane. This is minor and non-blocking, but if you agree it's right, I'd rather see it folded in now than lost in the backlog.
There was a problem hiding this comment.
Addressed in 5343570. "Where it applies" in the PR body is corrected too. The original commit's message is left as it is, since changing it would need a force-push; this commit's body carries the correction.
|
|
||
| /// Whether `s_id` was assigned by the store's own dictionary, not by | ||
| /// novelty: at or below its namespace's persisted watermark. | ||
| pub fn is_persisted_subject_id(&self, s_id: u64) -> bool { |
There was a problem hiding this comment.
Optional (rebase note). #2214 merged into main this morning. On main, substitute_binding and substitute_pattern_with_store take Option<&TermView>, and dict_novelty lives on TermView (BinaryGraphView derefs to it). So when this stack retargets, is_persisted_subject_id needs to move to TermView, and gv.store() comes from there. Applying this commit to current main, git merge-tree shows that conflict in join.rs plus two adjacent-insert ones (binary_scan.rs beside #2214's object_is_constant_literal, and the grp_query_sparql.rs registration). Just flagging so it isn't a surprise.
There was a problem hiding this comment.
Addressed in b16e464, the merge of main: is_persisted_subject_id is on TermView, and gv.store() comes from there.
| /// scan has some, so a test can see whether it took them. | ||
| fn resolved_in(&self, store: &BinaryIndexStore) -> Option<ResolvedIds> { | ||
| let ids = self.resolved?; | ||
| let same_store = ids.store_id == store.store_id(); |
There was a problem hiding this comment.
Praise. Scoping the ids by store_id (process-unique) and the watermark, stamping both outcomes, and keeping the pattern bound so range, policy and history read what they always read, is the narrowest way to do this. I'd have assigned the same design. For the record: the same-store check is unreachable today. Multi-ledger datasets and a cross-ledger SERVICE carry IriMatch or clear binary_store (service.rs:222-230), and a query's store is fixed in its context. Removing the check changed nothing in any test or probe, so I don't think it needs a test of its own.
# Conflicts: # fluree-db-query/src/binary_scan.rs # fluree-db-query/src/join.rs
`DictTreeReader::leaf_lookups` was one shared atomic per dictionary tree, incremented on every reverse lookup that searched a leaf. Every query thread looking up a subject wrote the same cache line, so under concurrency the counter cost each lookup a few percent, and only tests read it. The counter, its accessor and `subject_reverse_leaf_lookups` now sit behind a `test-counters` feature of fluree-db-binary-index, off by default. fluree-db-api turns it on through its dev-dependency only, alongside `residency`, so its tests count as before and a production build compiles none of it.
Under novelty a scan decodes its rows, so a probe it feeds has no store id to take. The batched subject probe does not decode: its ref objects reach the per-row probe downstream as store ids, novelty ids among them, while commits wait to be indexed. The persisted-only guard is what keeps a novelty id out of the scan's filter there, and nothing tested it. The new test feeds a per-row probe from a batched hop over an indexed ledger with unindexed commits, and checks that only the persisted subject's probe takes its id: one `proceed` stamp, two without the guard, the answers alike. The novelty test's comment no longer claims that no probe sees an id under novelty.
Addressed in 03c33ca: the counter is behind a
Addressed in 5343570 (one
Addressed in b16e464, the merge of main. |
Brings #2414 and #2415. #2414 ported next's `16a635b8e` to main, and next also has `ef33f6cac`, which lowers annotations on the expansion. next's side is kept in `parse/jsonld.rs` and `parse/edge_annotations.rs`; main's duplicate `reject_reserved_iris_in_clause` and its `values`-cell checks are dropped (next's `values` already get the query side's check, and on next `refuse_reserved_predicate` covers `rdf:reifies` too). What main adds on top comes across: - Bulk import: next still walked every expansion for reserved predicates. A chunk with no lowering is now checked by the import sink, by each statement's predicate Sid, with no pass of its own; a lowered chunk keeps the walk before its lowering. On next the sink refuses `rdf:reifies` as well as the `f:reifies*` slots (`is_annotation_predicate`), as next's walk did, and the import test gains an `rdf:reifies` case. main's `refuse_reserved_in_chunk` is unused here and dropped. - The expander's value-object refusals carry their location (`InvalidValueObject`), with next's reason text. - main's `@vocab` annotation test passes on next, whose lowering reads the expansion; its genesis is awaited. #2415: the per-row store ids join next's `term_only` scan state, and next's independent-count call of `make_right_scan` passes none. On next the fused chain answers `DESCRIBE ?x WHERE { ex:a ex:knows ?x }`, so that check asserts the fused chain's stamp, not per-row probes.
A join or OPTIONAL that probes one row at a time binds the row's store id into the scanned pattern as the IRI it decodes to. The scan then looked that IRI up in the subject dictionary again: a leaf search per probe that ended at the id it started from. DESCRIBE expansion, variable-predicate probes and OPTIONAL's per-row lookups all paid it. This passes the id through instead.
What changes
substitute_bindingrecords a persisted store id it binds into the subject or object asResolvedIds { store_id, subject, object }, keyed by the store whose dictionary assigned it.BinaryScanOperator::opentakes those ids whenstore_idmatches its own store: the subject asfilter.s_id, an object ref as(IRI_REF, s_id). It stampscorrelated store ids(proceedorgate_declined) whenever it has some.ScanDatasetBuilder::with_resolved_ids. History scans never receive them.DictTreeReader::leaf_lookupsandBinaryIndexStore::subject_reverse_leaf_lookupscount reverse lookups that search a leaf, for the tests. They sit behindfluree-db-binary-index'stest-countersfeature, which onlyfluree-db-api's dev-dependency enables, so a production build compiles no counter.Where it applies
Mostly an indexed ledger with no unindexed commits. While any commit is waiting to be indexed, scans decode their rows, because novelty ids are temporary, so a probe a scan feeds has no id to take. The check covers the whole ledger, not the scanned graph or predicate. The batched subject probe does not decode: rows from it carry store ids under novelty too, novelty ids among them. A probe downstream takes the persisted ones, and the persisted-only guard keeps a novelty id out.
Probes off the batched lanes:
?x ?p ?oafter a join);The batched lanes are untouched.
What it saves: one reverse lookup per probe. Whether that also avoids a storage read depends on the dictionary leaf cache.
Guards
store_id()changes on any rebuild or reload, so ids from another store, or from before a rebuild, are ignored.Tests
it_correlated_store_ids(ingrp_query_sparql) counts subject-dictionary leaf lookups per query on an indexed ledger:proceedstamp; two without the persisted-only guard).Removing the subject, object or OPTIONAL part each fails its test.
Not in this PR