Repository navigation
Description
Surfaced in review of #1825. The aggregate complement rewrites derive "average over entities without key K" as (universeSum − withSum) / (universeCount − withCount). The identity only holds when the anti-joined edge (?product ex:feature ?feature) matches each (product, feature) pair at most once. An RDF list with a repeated element breaks that: the same (s, p, o) is stored once per list position (o_i), so the positive WITH join counts that product's offers once per position, while FILTER NOT EXISTS excludes the product only once. The rewritten query returns a wrong number, without any error.
The original complement fold (cedd922, already on main) has the bug. #1825 adds a second consumer of the same identity but admits a subset of the same shapes, so it does not increase exposure.
Reproduction
Use the seed(120, 12) fixture from fluree-db-api/tests/it_query_bi_q4.rs and add:
{"@id":"ex:pdup","@type":"ex:Type","ex:feature":{"@list":[{"@id":"ex:f0"},{"@id":"ex:f0"},{"@id":"ex:f1"}]}},
{"@id":"ex:odup1","ex:product":{"@id":"ex:pdup"},"ex:price":500},
{"@id":"ex:odup2","ex:product":{"@id":"ex:pdup"},"ex:price":700}Root-policy view, feature f0. Results are identical from novelty and after reindex:
| Query | Shared plan (#1825) | Complement fold only (+ 0 on the cast bypasses sharing) |
No fold (GROUP BY instead of DISTINCT in the universe) |
|---|---|---|---|
Q4 priceRatio |
1.9420725776281333 | 1.9420725776281333 | 1.7793667007150153 |
WITHOUT-only withoutFeaturePrice |
40.77181208053691 | 40.77181208053691 | 44.5 |
The standalone WITH join reports COUNT(?price) = 67 for f0, including four rows from pdup (two offers × two list positions). The no-fold answer is the one consistent with how the engine evaluates the unrewritten query.
Code locations:
- The identity: shared.rs:370 and aggregate_complement_fold.rs:316.
- Where the rewrite runs: operator_tree.rs:2312.
Why this isn't a one-line gate
The rewrite happens on the IR at plan time. At that point the planner has only a StatsView, and stats carry no list-ness. List-ness is stored in two places:
- Indexed data: the
HAS_O_Ileaflet flag.predicate_unsafe_for_cross_predicate_o_key_joinalready reads it for Three fast-path shapes return wrong results (fast ≠ generic under the kill switch) #1652, by opening every leaf for the predicate. - Novelty: list rows need a row-level check.
Precedent for handling the same premise failure:
- Runtime detection:
MembershipJoinOperator(Semantics: is a var-object join over RDF list elements a bag join over positions or a set join over values? #1687) found that stats can't detect this at plan time. Its build drain doubles as the detector: a key inserted twice means a ground triple matched more than one flake. It then falls back to exact per-row joins (membership_join.rs). - Stats-backed licence:
StatsView::property_ref_onlyis a soundness flag derived fromobserved_datatypes. It is monotone under novelty retraction and conservative until a reindex removes the evidence. A "may carry list rows" flag could follow the same pattern.
Candidate approaches (not yet investigated; choose after measuring)
- Stats flag. Record per-predicate list presence at index build, merge novelty assertions into it, and decline both rewrites when the edge predicate may carry list rows.
- Plan-time metadata probe. Walk the edge predicate's leaf directory for
HAS_O_Iand check novelty rows. - Runtime detection with fallback. Keep the rewrite, have the grouped WITH scan detect a repeated
(product, feature)pair, and fall back to the original plan built alongside it. Fast paths already do this with afallbackoperator. - De-duplicate the edge. Aggregate over distinct
(product, feature)pairs. PSOT sorts(p, s, o_type, o_key, o_i), so repeated list positions of one pair are adjacent. A streaming adjacent de-dupe might be O(1) memory, but whether it composes with the join order the planner picks is unknown.
Adding list presence to stats (1) looks like the cleanest long-term signal, and other lanes (#1687, #1652) would benefit too. Whether it's the best path is unknown without more investigation.
Performance risks — check each before merging
BI Q4 improved roughly 2–25× from these rewrites (#1825 numbers). A correctness fix must not quietly take that away, or slow unrelated queries.
- Over-declining. A coarse "this predicate has any list rows" flag also disables the rewrite for lists with no repeated elements, where the identity is still exact. BSBM loads from N-Triples, which cannot produce
o_ilist rows, so the benchmark would not catch this regression. Prefer a signal about duplicates if one is affordable, and add a perf guard test with list-valued but duplicate-free edges that must keep the rewrite, as Semantics: is a var-object join over RDF list elements a bag join over positions or a set join over values? #1687's test does for ordinary multi-valued rows. - Unknown on existing ledgers. A new stats field is missing from index roots written before the change. If "missing" means "may have lists", every existing ledger loses the rewrite until reindex. The flag needs an explicit unknown state and a documented choice between declining and probing in that state.
- Retraction and staleness. Like
property_ref_only, the flag can only be conservative within the novelty window: a retracted list keeps the rewrite off until the next reindex. Confirm that is acceptable, and that novelty assertions of list rows turn it on immediately. - Plan-time I/O. Approach 2 opens leaves on the planning path. Locally,
open_leaf_handlereads the whole leaf blob, and on remote storage it's a fetch. That is fine for Three fast-path shapes return wrong results (fast ≠ generic under the kill switch) #1652's fast paths but is new cost for every query that reaches the complement candidate check. Measure on a large edge predicate and on remote storage. - Runtime fallback cost. Approach 3 has to build (not open) the original plan too, and detecting a repeated pair means tracking pairs per group. Measure memory at 1,000+ features, and make sure the no-duplicate path doesn't pay for detection it doesn't need.
- Keep the fix local. Stats-view and scan-layer changes reach every query. Any new field or merge step belongs in the cached stats build, not per query. Run the registered benches (
regression-budget.json) and BSBM BI before and after, not only Q4.
Related gates to check while in here
These are not verified:
- The original complement fold runs whenever the shape matches (aggregate_complement_fold.rs:101). Only the perf(query): reuse aggregates for matched BI Q4 subqueries #1825 sharing step is gated to current-state, single-graph, root policy.
- A multi-graph default union (the same triple in two graphs) or history mode (one match per version) could create the same "edge matches more than once" condition. Check whether either can reach the original fold, and gate it the same way if so.
Validation expected
- Add the fixture above to
it_query_bi_q4.rs. It must fail before the fix and pass after, and it must cover both the ratio and WITHOUT-only shapes, in novelty and indexed state. - Add a duplicate-free list fixture that keeps the rewrite, checked by plan or fuel, so the fix can't pass by always declining.
- Per repo practice, revert the fix and show the new test fails. If a SPARQL test is added, add a JSON-LD twin.
Activity
bplatz commentedon Sep 14, 2026
Regression test for this gap, ready to add to
fluree-db-api/tests/it_query_bi_q4.rs. It uses that file's existingseed,queryandassert_rowshelpers. It compares the shared plan and the complement-fold-only plan against an unrewritten control, which usesGROUP BYin the universe so that neither rewrite matches. The comparison covers the ratio and WITHOUT-only shapes, from novelty and after reindex.Verified at c954b62 with
cargo test -p fluree-db-api --test grp_query_sparql bi_q4_complement_matches_unrewritten -- --ignored:http://example.org/f0: 1.9420725776281333 != 1.7793667007150153FLUREE_DISABLE_AGG_COMPLEMENT_SHARING=1FLUREE_DISABLE_AGG_COMPLEMENT_FOLD=1A fix should remove the
#[ignore]and make the default run pass. Pair it with the duplicate-free list guard described above, so a blanket decline can't satisfy the test.