Repository navigation
tighten indexed fast-path eligibility guards - #1628
Conversation
The (subject_var, pred) cache key answers "does this subject have any
object for this predicate", which is the truth value of the EXISTS only
when the inner object is free. Both eligibility gates tested
Term::is_bound() — that is !is_var(), a plan-time syntactic test that
rejects a constant object but is blind to a variable an outer pattern has
already bound, so NOT EXISTS { ?s2 :member ?x } was answered as
NOT EXISTS { ?s2 :member ?anything } on the indexed lane.
Carry the object var out of collect_simple_exists_keys so the cache build
can skip an entry whose object is correlated (and not pay for its PSOT
scan), and add a per-row backstop for rows where the var is in schema but
unbound. Declined rows fall through to eval_exists_for_row, which already
serves the novelty lane correctly.
Stamp the cache verdict on the fluree::fastpath target — this path has no
FastPathOperator to stamp for it, and without an observable the regression
test cannot tell "declined" from "never on the indexed lane".
{ ?x <p> ?x } carries an implicit equality join. The metadata-backed
detectors answer from per-predicate index metadata and never compare the
subject to the object, so COUNT(*) over a self-loop returned the
predicate's cardinality (5 instead of 2, and 4 instead of 0 for { ?a a ?a
}). count_plan.rs has rejected this shape since the v4 baseline; the
older per-shape detectors never got the same guard.
validate_simple_triple is the shared choke point for the COUNT / COUNT
DISTINCT / AVG / MIN-MAX detectors, so the s != o check goes there, with
the contract stated in its doc comment. detect_count_distinct_position
and detect_count_triples admit a variable predicate and so destructure
the triple themselves; they get their own pairwise check across all three
positions.
Drop the "positional ambiguity ... subjects -> predicates -> objects"
tie-break note: a repeated variable is not a naming ambiguity to be
resolved by dispatch order, it is a join constraint that disqualifies the
fast path.
detect_fused_scan_sum_i64 read only the predicate and object positions, in
both the bare-triple and the BIND arm. It therefore fired on a CONSTANT
subject as well as on a self-loop, and the operator sums the predicate's
whole object column: SELECT (SUM(?v) AS ?n) WHERE { <n1> <score> ?v }
returned the ledger-wide 30 where the answer is 10. A bound-subject SUM is
a mainstream shape — total spend for one customer, line items on one
order — so this silently answered a per-entity question with the whole
ledger. Its AVG / MIN-MAX / COUNT siblings already route through the
shared helper and were always right here.
detect_sum_numeric_compare_as_count has the same hole; the helper also
supplies the tp.dtc rejection both were missing.
detect_count_blank_node_subjects destructures inline (it admits a variable
predicate) and gets the pairwise check directly.
The two rarer detectors are pinned with unit tests rather than fixture
rows: a numeric-compare SUM and a blank-node-subject COUNT need data the
integration fixture does not carry, and a guard with no discriminating
case is indistinguishable from no guard.
{ ?x <rel> ?x . ?x a ?c } failed outright with "Duplicate VarId VarId(0)
in schema" — a hard query error on every lane, with or without an
aggregate, while { ?x <rel> ?x . ?x <rel> ?y } was fine.
NestedLoopJoinOperator built right_output_vars position by position, so a
right pattern naming one variable in two positions contributed two columns
carrying the same VarId and Batch::new rejected the schema. The scan layer
already gets this right: schema_from_pattern_with_emit folds the repeat
into a single slot and within_row_var_equality_ok enforces the implied
equality per row, so the join only had to stop widening it. combine_rows
and the batched paths address right columns by name, not by position, so
the narrower vector needs no other change.
The same-predicate shape plans to a different operator, which is why the
failure looked arbitrary from the outside.
"(o_type, o_key) is fact identity" reads as a global guarantee and is documented as one on the NumBig arena's own insert path, but the arena is per-predicate (its module header opens "Per-predicate equality-only arena") and allocates handles from 0 within each (g_id, p_id). The pair is an identity only once p_id is fixed. The general pipeline already knows this — it carries p_id_for_numbig alongside (o_kind, o_key) in both its join key and its group key — but nothing named the rule, so a whole-graph consumer had nothing to trip over. Also correct the XSD_DECIMAL comment: it still described an inline f64 with overflow spilling to NumBig, while the resolver routes every typed xsd:decimal to NumBig with no inline branch, so no stored row carries that o_type at all.
COUNT(DISTINCT ?o) over { ?s ?p ?o } is answered from OPST leaflet
directory metadata by grouping on the 10-byte lead o_type(2) + o_key(8),
which stops immediately before p_id at bytes [14..18]. For a NumBig row
that lead is a per-predicate arena handle, so the first decimal under one
predicate and the first under another share it and count as one term.
Because handles are sequential per predicate the result was max over
predicates of their distinct big-value counts rather than the size of the
union — a silent undercount that can never over-report, which is why
nothing downstream ever tripped. Every xsd:decimal is affected, as is any
xsd:integer beyond i64.
Gate on the leaflet directory rather than special-casing the NumBig slice:
o_type is the leading big-endian u16 of an OPST key, so an entry's
[first_key, last_key] interval says whether the leaflet can hold a
non-identifying key without opening a column. Counting the slice exactly
would need p_id payload reads, arena loads, and reconciliation against
retractions; it is a perf follow-up, not a correctness prerequisite.
Only the whole-graph object arm is unsound. The distinct-subject arm's
SPOT lead is s_id, a genuinely global id, and the per-predicate object
count's 14-byte POST lead starts with p_id, which scopes the handle
correctly; both keep their fast path on a decimal-bearing ledger.
Eight must-not-fire fixtures — the reported two-triple case, decimals under one predicate, one value under two predicates, 3-and-1, 3-and-3, the 5-and-4-sharing-one production shape, decimals mixed with strings and small integers, and overflow xsd:integer across two predicates — each assert the hand-computed value AND that the "distinct object COUNT" site emits no proceed stamp. Without the fix all eight reproduce the audit's numbers exactly (1/2, 3/4, 3/6, 5/8, 6/8, 1/2). Three must-fire controls (i64 integers, doubles, strings across two predicates) assert a positive proceed stamp, so a gate that declines more than the NumBig case fails. Two more assert the same on a decimal-bearing ledger, where COUNT(DISTINCT ?s) and the bound-predicate COUNT(DISTINCT ?o) must still fire — that is the over-broad-fix trap, since declining the whole operator would pass every value assertion. The neighbourhood pins (GROUP BY, DISTINCT, cross-predicate value join and FILTER equality, whole-graph MIN/MAX, and ORDER BY over decimals inserted in non-numeric order) were correct before the fix and document its boundary: those paths decode through the arena instead of comparing raw keys, and the same value under two predicates must stay one term.
bplatz
left a comment
There was a problem hiding this comment.
All five narrowings check out, and I traced the NumBig gate end to end. Three notes beyond the inline comments.
The test isolation is the right call and worth saying so. Separate [[test]] binaries for the ones that toggle the process-global kill switch or assert routing via tracing capture, and wait_for_index_application as a real barrier rather than sleeps. That's what keeps these from becoming the flaky-under-load tests this pattern usually produces.
One narrowing isn't in the list of five. Routing detect_fused_scan_sum_i64 through validate_simple_triple also inherits the tp.dtc.is_some() decline, which that detector never had — so a datatype-constrained SUM that previously took the fused scan and ignored the constraint now falls back. That's a sixth correctness fix riding along; it deserves a line in the body rather than being discovered later.
The decimal fast-path loss needs a tracked issue, not a sentence. Every xsd:decimal and any xsd:integer past i64 puts a graph on the general pipeline for whole-graph COUNT(DISTINCT ?o), permanently. "A reasonable perf follow-up" in a PR description isn't a plan — and this area has already been through a disable/fix/reinstate cycle once. Please file it and link it here before merge.
One thing I checked so it doesn't get re-derived: the row_count == 0 || lead_group_count == 0 skip sits above the new non_identifying check, so the zero-row leaflets #1624 starts emitting can't trip the gate. The two PRs compose cleanly.
| /// set. Per-predicate consumers are unaffected: their key already carries | ||
| /// the `p_id` that scopes the handle. | ||
| #[inline] | ||
| pub const fn o_key_is_globally_identifying(self) -> bool { |
There was a problem hiding this comment.
This has no call sites — I grepped the branch and main. leaflet_may_hold_non_identifying_o_key open-codes lo <= NUM_BIG_OVERFLOW <= hi instead of calling it, and the only other reference is the doc-link from that function's comment.
Because it's pub, the compiler won't warn, so it lands as silently dead API on a type that's part of the storage format's vocabulary. The repo's dead-code policy wants one of: use it, #[expect(dead_code)] with why/when/how, or delete.
Using it is easy and better than the current shape — the leaflet_may_hold_non_identifying_o_key interval test can express itself in terms of this predicate rather than repeating the NUM_BIG_OVERFLOW constant, which is exactly the coupling the doc comment is trying to establish.
There was a problem hiding this comment.
You're right, and thanks for grepping main as well as the branch — I'd quietly counted the doc-link from leaflet_may_hold_non_identifying_o_key as a use, which of course it isn't, and pub meant nothing was ever going to tell me otherwise.
Fixed by taking your suggestion rather than reaching for #[expect(dead_code)]. Both forms now derive from one list, OType::NOT_GLOBALLY_IDENTIFYING: o_key_is_globally_identifying answers the point question from it, and a new range_holds_non_globally_identifying(lo, hi) answers the interval question, which is the one a leaflet directory entry is actually asking — [first_key[0..2], last_key[0..2]] bounds every o_type in the leaflet. The gate then calls the point predicate for the type-homogeneous case the indexer actually emits and the range form otherwise, and names no o_type constant of its own. So a future non-identifying o_type is one list entry with no edit in fluree-db-query.
I added a small unit test (globally_identifying_point_and_range_agree) that walks the list and asserts the point and range forms agree, plus the adjacent-value cases either side of NUM_BIG_OVERFLOW, mostly so the two can't drift if that list ever grows.
| // The object var is fed by an outer pattern, so this EXISTS asks about | ||
| // one specific object rather than "any object". The subject-set key | ||
| // cannot express that, and the per-row guard in | ||
| // `try_eval_simple_exists_semijoin` would decline every row anyway — |
There was a problem hiding this comment.
This justification isn't right, and the two gates don't actually agree.
The per-row guard declines only when batch.get(row_idx, object_var).is_some_and(Binding::is_matchable). A var that's in the schema but unbound in a given row — an unmatched OPTIONAL, say — is is_matchable == false, so the per-row guard lets that row proceed. This build-time gate skips the entry whenever the var appears in the schema at all, bound or not. It's strictly more conservative, not equivalent.
The direction is safe (correctness-preserving, perf-only), and there's a perfectly good reason for it — at cache-build time you can't know per-row bindings, and speculatively paying a PSOT scan for rows that may all decline is the wrong trade. That's the argument the comment should make.
Worth noting the per-row guard's treatment of the unbound case is subtly correct, not just permissive: an unbound variable inside EXISTS is a fresh free variable per SPARQL, so "any object" is the right answer there. That's non-obvious enough to be worth stating where the guard lives.
There was a problem hiding this comment.
You're right and the comment was straightforwardly wrong — thank you for working the case through rather than just flagging it. Schema presence is strictly more conservative: a var that's in the schema but unbound in a given row (the unmatched OPTIONAL case you name) is is_matchable == false, so the per-row guard lets that row take the semijoin while the build-time gate has already skipped the whole cache entry. "Would decline every row anyway" was me reasoning about the bound case and writing it as though it covered both.
Rewrote it to make the argument you laid out: at cache-build time there are no per-row bindings to consult, so the choice is between skipping the entry and speculatively paying a PSOT scan for rows that may all decline — and the skip is safe to reason about precisely because it costs only performance, with the per-row guard doing the correctness work.
I also took the second half of your note and put it where the per-row guard lives, since you're right that it's non-obvious: EXISTS substitutes only the bindings the row actually carries, so a variable left unbound by an unmatched OPTIONAL is a fresh free variable inside the subpattern, and "does this subject have any object for this predicate" is genuinely the right question for those rows. That reads as an accident in the code otherwise.
bplatz
left a comment
There was a problem hiding this comment.
Left some feedback below to look at before merge
o_key_is_globally_identifying had no callers: the leaflet gate open-coded lo <= NUM_BIG_OVERFLOW <= hi and only the doc-link referenced it. Because it is pub the compiler stayed quiet, so it landed as dead API on a type that is part of the storage format's vocabulary — and it duplicated the constant the predicate exists to hide. Fold both forms onto one exceptions list. The point predicate answers from it, and a new range form answers "can this [lo, hi] o_type interval hold a non-identifying key", which is the question a leaflet directory entry actually asks. The gate now calls the point predicate for the homogeneous case the indexer emits and the range form otherwise, and names no o_type constant of its own; a future non-identifying o_type needs one list entry and no edit in the query crate. A unit test pins that the two forms agree.
The cache-build comment claimed the per-row guard would decline every row the build-time gate skips. It would not: the per-row guard declines only a row where the object var is matchable, and a var that is in the schema but unbound in a given row (an unmatched OPTIONAL) proceeds. Schema presence is strictly more conservative than per-row boundness, not equivalent to it. The real argument is the one worth writing down: cache-build time has no per-row bindings to consult, so the choice is between skipping the entry and speculatively paying a PSOT scan for rows that may all decline, and the skip costs only performance because the per-row guard is what keeps the answer right. Record at the per-row guard why letting an unbound var proceed is correct rather than merely permissive: an unbound variable inside EXISTS is a fresh free variable, so "any object" is the question being asked there.
Routing detect_fused_scan_sum_i64 through validate_simple_triple also inherited that helper's tp.dtc.is_some() decline, which the SUM detector never had of its own — so a datatype-constrained SUM used to take the fused scan and sum the predicate's whole object column across every datatype under it. Nothing in the suite covered it. A datatype constraint alongside a variable object has no SPARQL surface, so the case runs a JSON-LD query against its own small ledger holding two datatypes under one predicate: constrained to xsd:integer the answer is 10, unconstrained it is 30. Before the change the constrained form returned 30 with a SUM(?o) proceed stamp. xsd:positiveInteger is the second datatype because it survives numeric-datatype normalization, which folds xsd:long and friends into xsd:integer and would make the constraint a no-op. The same ledger carries the must-fire control: drop the constraint and SUM(?o) must proceed again, so the decline cannot widen into a disable.
|
@bplatz — the review-body notes: On the sixth narrowing: Good catch, and you're right that it deserved a line rather than being found later. Routing It also had no test, which I liked less than the missing body line — so there's one now. A datatype constraint alongside a variable object has no SPARQL surface (it's the JSON-LD One fixture note in case it looks arbitrary: the second datatype is On the decimal fast-path loss: Filed as #1638 and linked from the body. Fair point that "a reasonable perf follow-up" in a description isn't a plan, and the disable/fix/reinstate history in this area is exactly why. The issue carries the mechanism, the two traps I'd want the next person to not rediscover (arena contents over-approximate live rows once anything has been retracted, so unioning the per-predicate arenas over-counts; and recovering On the composition check and the test-isolation note: Thank you for the And I appreciate you calling out the test isolation as deliberate rather than incidental. The separate |
…ipeline Each of these answered a COUNT with a plausible wrong number under HTTP 200, and each is reproducible as fast != generic under the FLUREE_DISABLE_QUERY_FAST_PATHS kill switch on a small indexed ledger. GroupByObjectStarTopKOperator treated the star's filter triples as an existence semi-join: the merge-join lane deduplicated filter subjects and the multi-predicate lane intersected them into a set, so `GROUP BY ?o (COUNT(?s))` over `?s <p_group> ?o . ?s <p_filter> ?x` counted qualifying subjects instead of joined rows. A subject with three filter rows contributed one. The merge-join lane now consumes a whole filter-subject run into an `(s, count)` group, the multi-predicate lane folds the filter predicates into a subject -> product-of-counts map, and `AggStateStar::observe` takes that multiplicity: COUNT adds it, MIN/MAX/SAMPLE (duplicate-insensitive) ignore it. The operator also stamps its fast-path outcome so routing is assertable. PostObjectGroupCountIter restarted an object group at every leaflet boundary, emitting one o_key twice with partial counts. `execute_chain` seeks PSOT forward-only, so the repeated (non-increasing) key read as absent and every row of the second fragment was dropped — an undercount for plain, OPTIONAL, MINUS and EXISTS chain COUNT(*) alike, sized by how many groups straddle a boundary. It now carries the open group across leaflet and batch refills the way PsotSubjectCountIter already did. Found alongside: a homogeneous non-IRI leaflet ended the stream rather than being skipped, and since POST sorts non-IRI o_types below IRI_REF, that truncated every IRI group behind one on a mixed-object predicate. count_composite_join_pairs merge-joined `?s <p1> ?o . ?s <p2> ?o` on (s_id, o_type, o_key) across two different predicates. A NUM_BIG_OVERFLOW o_key is a handle into a per-predicate arena, not a term identity, so equal decimals or overflow integers under the two predicates never matched — the same trap fluree#1628 gated for the whole-graph COUNT(DISTINCT ?o); this lane never had the gate. List rows are the second hazard: the generic pipeline's list-element join semantics are not expressible in a key that drops o_i. Both now decline through predicate_unsafe_for_cross_predicate_o_key_join, which answers from leaflet directory metadata and decodes an o_type column only for a mixed leaflet whose key range straddles NUM_BIG_OVERFLOW — inline numerics sort below it and langstrings above, so the range test alone would over-decline ordinary predicates. The overlay lane declines row-wise on a live o_i, covering novelty list rows the directories have not seen. All three are eligibility- or arithmetic-level changes rather than disables: ledgers without arena values or lists keep the composite fast path, and the star and chain lanes keep theirs outright. Regression coverage in it_fastpath_1652_regression.rs: fifteen cases over five ledgers (the chain ledger indexed at three-row leaflets to force boundary-straddling groups at test scale), each pinning the fast lane's answer, the generic pipeline's answer, and the fast-path stamps — must-fire for every shape that keeps its lane, must-not-fire for the composite shapes that now decline. The differential harness gains a group_by_object_star_topk case across base, overlay and novelty.
Six related cases where an indexed-lane fast path answered a question its metadata can't actually answer, each returning a plausible wrong number (or a spurious error) with HTTP 200. All of the fixes are eligibility narrowings — the declined query falls through to the general pipeline, which computes the correct answer in every case — so no currently-correct query changes behavior.
The EXISTS semijoin keyed on
(subject_var, pred)and gated on a plan-timeTerm::is_bound(), which is blind to a variable an outer pattern binds at runtime — soNOT EXISTS { ?s2 :member ?x }with?xcorrelated was answered as "does?s2have any member" on the indexed lane (the W3Csubset-02negation query returned 25 rows where 11 is correct). The COUNT/COUNT DISTINCT/AVG/MIN-MAX detectors never compared subject to object, so a repeated-variable triple like{ ?x :rel ?x }counted the predicate's full cardinality instead of the self-loops. The fused SUM detectors never read the subject position at all, so a constant-subjectSUM(?v)returned the ledger-wide sum for a per-entity question. Routing those SUM detectors through the shared triple validator also picked up its datatype-constraint decline, which they never had of their own — so a datatype-constrainedSUMno longer takes the fused scan and sums the predicate's whole object column across every datatype under it. A repeated-variable triple joined to a second same-subject pattern failed outright withDuplicate VarId(the nested-loop join widened the same variable into two schema columns; the scan layer already folds it). And the whole-graphCOUNT(DISTINCT ?o)grouped on the OPST(o_type, o_key)lead, which for NumBig objects is a per-predicate arena handle rather than a global identity — two different decimals under two predicates share a lead, so distinct counts collapsed toward the largest single predicate's count (everyxsd:decimaland anyxsd:integerbeyond i64 is arena-routed). That last gate declines on directory metadata alone; an exact NumBig-aware counter is tracked as #1638 so decimal-heavy graphs eventually get the fast path back.The regression suite asserts both directions via the span-capture harness: must-not-fire (no
proceedstamp, correct value) for every broken shape, and must-fire (positive stamp) for the shapes that should keep their fast path — including on decimal-bearing ledgers, so an over-broad gate fails loudly. One note for reviewers: these tests wait for background index application and probe the lane before asserting, since a lost indexer race otherwise downgrades an "indexed" test to novelty and it passes vacuously.