Skip to content

Aggregate complement rewrites miscount when the anti-joined edge has repeated list elements #1837

Open

Description

@bplatz

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:

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:

Precedent for handling the same premise failure:

Candidate approaches (not yet investigated; choose after measuring)

  1. 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.
  2. Plan-time metadata probe. Walk the edge predicate's leaf directory for HAS_O_I and check novelty rows.
  3. 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 a fallback operator.
  4. 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.

  1. 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_i list 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.
  2. 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.
  3. 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.
  4. Plan-time I/O. Approach 2 opens leaves on the planning path. Locally, open_leaf_handle reads 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.
  5. 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.
  6. 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

  1. added
    bug
    P2
    area:query
    on Sep 14, 2026
  2. bplatz commented on Sep 14, 2026

    @bplatz
    ContributorAuthor

    Regression test for this gap, ready to add to fluree-db-api/tests/it_query_bi_q4.rs. It uses that file's existing seed, query and assert_rows helpers. It compares the shared plan and the complement-fold-only plan against an unrewritten control, which uses GROUP BY in 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:

    Environment Result
    default fails: http://example.org/f0: 1.9420725776281333 != 1.7793667007150153
    FLUREE_DISABLE_AGG_COMPLEMENT_SHARING=1 fails with the same values (complement fold alone)
    FLUREE_DISABLE_AGG_COMPLEMENT_FOLD=1 passes (control and rewrites agree)

    A 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.

    /// Known gap (#1837): a list-valued feature edge with a repeated element
    /// matches the same `(product, feature)` once per list position. The positive
    /// WITH join counts that product's offers per position, while NOT EXISTS
    /// excludes the product once, so `universe − with` over-subtracts.
    #[tokio::test]
    #[ignore = "#1837: complement rewrites miscount repeated list elements"]
    async fn bi_q4_complement_matches_unrewritten_on_repeated_list_elements() {
        fn rows(result: &Value, value_var: &str) -> Vec<(String, f64)> {
            result["results"]["bindings"]
                .as_array()
                .unwrap()
                .iter()
                .map(|row| {
                    (
                        row["feature"]["value"].as_str().unwrap().to_owned(),
                        row[value_var]["value"].as_str().unwrap().parse().unwrap(),
                    )
                })
                .collect()
        }
        assert_index_defaults();
        let fluree = FlureeBuilder::memory().build_memory();
        seed(&fluree, 120, 12).await;
        let ledger = fluree.ledger("q4:main").await.unwrap();
        fluree
            .insert(
                ledger,
                &json!({"@context":{"ex":"http://example.org/"},"@graph":[
                    {"@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}
                ]}),
            )
            .await
            .unwrap();
        for indexed in [false, true] {
            if indexed {
                rebuild_and_publish_index(&fluree, "q4:main").await;
            }
            let ledger = fluree.ledger("q4:main").await.unwrap();
            let db = crate::support::graphdb_from_ledger(&ledger);
            for without_only in [false, true] {
                let value_var = if without_only {
                    "withoutFeaturePrice"
                } else {
                    "priceRatio"
                };
                let q = query(without_only).replace(" FROM <q4:main>", "");
                // GROUP BY in the universe matches neither rewrite.
                let control = q.replace(
                    "SELECT DISTINCT ?feature WHERE { ?p a ex:Type ; ex:feature ?feature . }",
                    "SELECT ?feature WHERE { ?p a ex:Type ; ex:feature ?feature . } GROUP BY ?feature",
                );
                // Adding zero bypasses sharing but keeps the complement fold.
                let fold_only = q.replace(
                    "xsd:float(xsd:string(?price))",
                    "(xsd:float(xsd:string(?price)) + 0)",
                );
                let mut results = Vec::new();
                for sparql in [&control, &q, &fold_only] {
                    let result = db
                        .query(&fluree)
                        .sparql(sparql)
                        .execute_tracked()
                        .await
                        .unwrap();
                    assert_eq!(result.status, 200);
                    results.push(result.result);
                }
                let expected = rows(&results[0], value_var);
                for (label, result) in ["shared", "fold_only"].into_iter().zip(&results[1..]) {
                    eprintln!("indexed={indexed} without_only={without_only} {label}");
                    assert_rows(result, &expected, value_var);
                }
            }
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2area:querybug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions