Repository navigation
perf(query): reuse aggregates for matched BI Q4 subqueries - #1825
Conversation
Share the existing WITH aggregate with complement statistics for narrowly matched, current-state root-policy queries. Preserve existing aggregate plans for unsupported shapes and execution contexts. Fix scalar pipeline consumers to wait for all inputs with producers, while avoiding waits on permanently unbound variables. Add semantic, plan-admission, work-count, and scaling coverage. Validation: 2,747 query-engine and API tests passed; Clippy and formatting checks passed. Local A/B measurements improved all 12 tested configurations.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this seems straightforward and good for the exact conditions it improves. No particular standout notes from me. Full review below
This is a tight piece of work — the sharing is expressed as a pure IR mutation on top of the existing fold, the original AVG is preserved rather than re-derived, and the dependency fix in the planner is the kind of small correctness repair that would have been easy to bury inside the perf change but is separately tested here. I reproduced the direction and roughly the magnitude of the win locally (4× at 100 features, 18× at 1,000, dev-fast, same binary with FLUREE_DISABLE_AGG_COMPLEMENT_SHARING as the control), and three of the admission gates fail a test when removed. The one substantive note is not something this PR introduced: the universe − with identity that both the old fold and this sharing rely on is wrong when the feature edge can match twice (a list-valued predicate with a repeated element), and the PR's own GROUP-BY control exposes it — numbers and a fixture are in the inline comment. Since the fix needs a plan-time list signal we don't have yet, I'd file that as a follow-up with the fixture attached rather than hold this; I'd also fold in the one-line EXPLAIN alignment so the API stops reporting a plan the executor doesn't run.
Adherence to repo commitments:
- Patterns/abstractions: ✔ extends
aggregate_complement_foldin place (newsharedsubmodule), reusesPattern/AggregateSpec/Expression; no parallel rewrite.⚠️ Admission is benchmark-shaped by design — consistent with the sibling fold, worth a docs line. - Performance (speed first, memory second): ✔ query-engine hot path, improves 4×–18× on the admitted shape; declined shapes pay one pattern walk after the pre-existing candidate check. No performance-degradation risk.
- Testing: ✔ unit (5 new, incl. 27-case rejection) + integration (oracle, two controls, novelty and indexed, fuel bound) all wired via
grp_query_sparql.rsand seen by name; mutations of three gates go red.⚠️ the list-duplicate case is unpinned (pre-existing gap). - Conventions: ✔
perf(query):subject with a full body;cargo fmt --checkclean; clippy-D warningsonfluree-db-query/fluree-db-api--all-targetsclean (see verification). No CI ran on this PR (stacked base) — retarget tomainbefore merge so the workflow actually runs.
Verified locally at branch HEAD f975b9c1e: grp_query_sparql it_query_bi_q4 2 passed; fluree-db-query --lib 1567 passed; three gate mutations each caught; dev-fast A/B 93.6 ms vs 378.8 ms (f100) and 102.7 ms vs 1.87 s (f1000); merge-tree onto origin/main clean, no #1821 dependency.
Approving so you can merge when ready — just retarget to main once #1821 lands (or now; it applies cleanly), and maybe worth folding in the EXPLAIN one-liner first.
| Pattern::Bind { | ||
| var: without, | ||
| expr: Expression::div( | ||
| Expression::sub(Expression::Var(u_sum), Expression::Var(w_sum)), |
There was a problem hiding this comment.
fluree-db-query/src/aggregate_complement_fold/shared.rs:370 — 🟠 pre-existing, not introduced here. The universe − with derivation is wrong whenever the anti-joined edge matches a product more than once, and both the old fold and this sharing return that wrong answer. Your code didn't introduce this, but this PR adds a second consumer of the same identity, so I'd rather we look at it now than after.
Mechanism: (u_sum − w_sum)/(u_cnt − w_cnt) assumes each (product, feature) pair contributes its offers exactly once to w_*. The only way an RDF triple pattern matches the same (s, p, o) twice is a list row (o_i), and ?product ex:feature ?feature over a product whose feature list repeats an element does exactly that — the WITH aggregate counts that product's offers twice, while the original FILTER NOT EXISTS is boolean and excludes the product once.
Claude caught this with the PR's own GROUP-BY control. Fixture: the PR's seed(120, 12) plus ex:pdup a ex:Type ; ex:feature {"@list": [ex:f0, ex:f0, ex:f1]} and two offers (500, 700). On the root-policy view path, both storage paths: shared plan f0 → 1.9420725776281333 (fuel 4.5), old fold via FLUREE_DISABLE_AGG_COMPLEMENT_SHARING=1 → 1.9420725776281333 (fuel 7.9), no fold at all via FLUREE_DISABLE_AGG_COMPLEMENT_FOLD=1 → 1.7793667007150153 (fuel 16.4), the PR's GROUP-BY control → 1.7793667007150153. Standalone, the WITH shape reports COUNT(?av)=66 for f0 (four rows from pdup, two from multi, sixty from the pool), i.e. the double count is real in the engine's semantics, and the derived WITHOUT for the without_only shape comes out 40.77 where the direct answer is 44.5.
Fix: decline both folds when the edge predicate carries list rows. The signal exists on the store (HAS_O_I leaflet flag — fast_path_common.rs:394–404 already does a metadata-first version of this check for #1652) but not on the StatsView that build_operator_tree_folds has, so this needs a decision about how to expose list-ness at plan time. That makes it one of the two cases where I'd genuinely rather see a follow-up issue than a fold-in — but I'd like the list-valued fixture recorded in it_query_bi_q4.rs (even as an #[ignore = "…"]d known gap with the numbers above) so the next person doesn't re-derive it.
There was a problem hiding this comment.
Filed as #1837 with your fixture, reproduced from novelty and indexed state (1.9420725776281333 vs 1.7793667007150153 for f0). The ignored regression test is attached to the issue (#1837 (comment)) rather than committed here: it fails with both rewrites and passes with FLUREE_DISABLE_AGG_COMPLEMENT_FOLD=1.
| query: &mut Query, | ||
| planning: &crate::temporal_mode::PlanningContext, | ||
| ) { | ||
| if planning.allow_semantic_elision |
There was a problem hiding this comment.
fluree-db-query/src/aggregate_complement_fold.rs:105 — optional. The body already says EXPLAIN can show the old plan; I traced why. fluree-db-api/src/explain.rs:598 builds the physical tree with PlanningContext::current(), never with_semantic_elision(..), so no elision-gated rewrite is ever visible to EXPLAIN — and fluree/solo's POST /v1/fluree/explain/{ledgerId} (fluree-lambda-query/src/handler.rs:1242 → explain_connection_sparql) is that plan verbatim, while its execution path (query_from with no policy inputs → root) does take the shared plan. Pre-existing class, but this PR is the first rewrite where the two plans differ in operator count. It seems the explain path has the view and its enforcer in hand (explain_policy_notice), so PlanningContext::current().with_semantic_elision(db.policy_enforcer().is_none_or(|p| p.is_root())) at explain.rs:598 would make EXPLAIN tell the truth. (The real location isn't in the diff; anchoring to the gate that causes the divergence.) Minor and non-blocking — but if you agree it's right, I'd rather see it in this PR than lost in the backlog.
There was a problem hiding this comment.
Addressed in 0d912c6
The flag is passed through the view explain methods rather than set at explain.rs:598, since the free explain_* functions only receive a snapshot. The view, connection and HTTP explain paths now use the root-policy check; the public snapshot-only functions are unchanged.
| // Keep admission to the measured three-triple universe: a typed product | ||
| // and a separate offer with a product link and numeric price. Larger join | ||
| // graphs get no new plan merely because they also contain two averages. | ||
| if universe.len() != 3 || price == product { |
There was a problem hiding this comment.
fluree-db-query/src/aggregate_complement_fold/shared.rs:283 — question, not a suggestion. Admission is BSBM Q4 to the letter — three-triple universe, offer star, one float cast, a lone ?a/?b BIND — and case 25 shows an identical extra join on both sides gets nothing. That's consistent with how the old fold was scoped and the module doc is upfront about it, so I'm not asking for generality here; I'm asking whether we want docs/design/performance.md to say that this family of complement rewrites is benchmark-shaped (neither fold is documented there today), so a user reading EXPLAIN on a near-miss query knows why they didn't get it.
| /// Mutate only after the complete pair and variable budget have been proved. | ||
| /// Caller gates this to current-state, single-domain, root-policy execution. | ||
| pub(super) fn fold(query: &mut Query) -> bool { | ||
| if std::env::var_os("FLUREE_DISABLE_AGG_COMPLEMENT_SHARING").is_some() |
There was a problem hiding this comment.
fluree-db-query/src/aggregate_complement_fold/shared.rs:165 — ⚪ nit. FLUREE_DISABLE_AGG_COMPLEMENT_SHARING is read on every fold call. That's fine here (only reached after has_aggregate_complement_candidate, and it mirrors FLUREE_DISABLE_AGG_COMPLEMENT_FOLD at :56), just noting neither switch is documented anywhere under docs/; the FLUREE_DISABLE_* family is growing (three in this stack) and a one-table reference would help whoever A/Bs a customer report.
| } | ||
|
|
||
| #[test] | ||
| fn neighboring_query_shapes_are_left_unchanged() { |
There was a problem hiding this comment.
fluree-db-query/src/aggregate_complement_fold/shared.rs:525 — praise. The 27-case rejection loop asserting format!("{q:?}") is byte-identical after a declined fold is exactly the shape of test this kind of rewrite needs; I mutated three separate gates (independence, universe size, ratio-only BIND) and each was caught by a different case.
| // for the pipeline subset evaluates the expression too early. | ||
| if matches!( | ||
| pattern, | ||
| Pattern::Filter(_) | Pattern::Bind { .. } | Pattern::Unwind { .. } |
There was a problem hiding this comment.
fluree-db-query/src/planner.rs:1769 — praise. Restricting the extended wait set to scope_produced_vars (and the COALESCE half of the unit test) is the part I expected to be missing; it's there, and it's why a filter over a never-bound var doesn't get pushed behind every scan.
EXPLAIN built its physical plan with a planning context that never allows semantic elision, so a root-policy view reported the unshared BI Q4 complement plan while execution ran the shared one. The view, connection and HTTP explain paths now pass the same root-policy check execution uses; the snapshot-only explain functions keep their existing behavior.
Record that both complement rewrites admit only the BI Q4 shape, what each requires, and the three FLUREE_DISABLE_* switches used to A/B planner changes.
BI Q4 repeatedly aggregates offers for each feature even though its WITH subquery already computes the matching groups. Reuse that grouped scan for SUM/COUNT alongside the original AVG, then derive the WITHOUT average from universe totals. Also fix scalar pipeline consumers that could evaluate the projected price ratio before a sibling aggregate supplied its input.
Sharing requires a tightly matched pair of independent subqueries and current-state, single-domain, root-policy execution. Extra joins/filters, DISTINCT averages, correlation, reasoning, and dataset/history/restricted-policy paths retain their existing aggregate plans. General join-selection and UNION heuristics are unchanged. The dependency correction waits only on inputs with producers, preserving early placement when a referenced variable is permanently unbound.
Validation
These are optimized, in-process measurements after one warmup, with five measured queries per process and results validated. They do not clear the archived 200M-triple, 32-client timeout; matched concurrency and peak-memory measurements remain outstanding. API EXPLAIN currently uses an untrusted planning context and can still display the previous OPTIONAL plan for an execution that qualifies for sharing.
FLUREE_DISABLE_AGG_COMPLEMENT_SHARING=1restores the previous complement plan while retaining the ratio dependency correction. The ignored scaling probe acceptsQ4_VIEW=1,Q4_PRODUCTS,Q4_FEATURES, andQ4_OFFERSfor repeatable comparisons.Follow-up: #1837 (complement rewrites miscount when the anti-joined edge has repeated list elements; pre-existing in the original fold)