Repository navigation
fix(sparql): aggregate and sub-select edge cases - #1374
Conversation
…ts, parse bare GROUP BY built-ins Three SPARQL query correctness fixes plus review hardening (W3C subquery/sq11 now passes; eval 250 -> 256, no regressions). GROUP BY bare built-in/function call: - parse_group_condition only accepted a bare variable or a parenthesized expression, so `GROUP BY DATATYPE(?v)` was silently dropped and the query degraded to a single implicit group. Parse the bare BuiltInCall/FunctionCall form, restoring the stream position on a partial parse so it cannot desync. Sub-SELECT ORDER BY/LIMIT/OFFSET scoping: - A sliced sub-SELECT was seeded per parent row, so an inner LIMIT applied per row and leaked rows past the slice into the outer join. SPARQL 1.1 18.2 sub-SELECTs are uncorrelated: add SubqueryPattern.uncorrelated, set it at the SPARQL lowering sites, and force materialize-once + hash-join for those subqueries. JSON-LD subqueries keep their existing per-row behavior. - Fix SubqueryOperator::next_batch returning None (operator exhausted) when a parent batch matched no subquery row, which dropped every later batch. Blank-node property lists: - `[ :p ?o ]` was a parser placeholder that discarded its inner triples, dropping the nested variables. Desugar to a fresh blank node plus its nested triples in subject and object position, and fold them into CONSTRUCT / INSERT / DELETE templates as well as WHERE BGPs. The synthetic label uses a character outside PN_CHARS so it cannot collide with a user blank node. Adds parser unit tests and SPARQL integration regression tests, and documents the supported features in docs/reference/compatibility.md.
Over an implicit single group (no GROUP BY) whose pattern matches nothing, SUM and AVG returned an unbound variable instead of their additive identity. COUNT already returned 0, so the empty-group behavior was internally inconsistent. NumericAcc::finalize_sum / finalize_avg now return "0"^^xsd:integer when the accumulated count is 0, matching SPARQL 1.1 18.5.1.3 / 18.5.1.4 and the W3C agg-avg-03 / agg-empty-group-sum tests. MIN/MAX/SAMPLE keep returning unbound (no identity element), and a query with GROUP BY over an empty pattern still returns zero rows (no groups). The streaming and DISTINCT aggregate paths both delegate to these helpers, so all are covered. Updates the empty-aggregate unit tests, the inner-OFFSET subquery regression test (empty SUM is now 0, not unbound), and the compatibility docs.
… identity 0 The scalar-aggregate fast paths bypass the generic aggregate.rs, so they needed the same empty-multiset identity fix: an indexed AVG(?o) over an absent or empty predicate returned unbound instead of "0"^^xsd:integer, diverging from the generic path. fast_predicate_scalar_agg.rs now returns the integer identity 0 for the empty AVG case (both the absent-predicate empty_result and the count==0 finalize); empty SUM already returned 0 there. Refreshes the now-stale "empty SUM is Unbound" documentation in fast_count.rs: since empty SUM is the identity 0 (= the COUNT identity), SUM(?o cmp K) equals the match count for every input, and the empty-input branches deferring to the general pipeline are a conservative choice rather than a correctness requirement. Adds an indexed regression for absent-predicate SUM(?o)/AVG(?o) and updates the existing absent-predicate SUM(compare) test (the shared general result is now 0).
A dynamic value error in a projection / BIND / ORDER BY expression (e.g. arithmetic on incompatible operand types from a heterogeneous predicate) aborted the whole query with HTTP 400 instead of leaving that variable unbound for the solution. Per SPARQL 1.1 §18.5 Extend, an expression error yields an unbound value for that variable and the remaining solutions are still returned. Queries now run with strict bind errors OFF (the spec-compliant default); transactions keep strict mode via execute_where_streaming so a computed WHERE value cannot silently become unbound before it is written. The BIND/Extend demotion is narrowed to dynamic value errors (arithmetic, comparison): structural errors — a built-in called with the wrong arity, an unknown datatype IRI — still surface as a query error, since they describe a malformed query rather than dirty data. Dynamic type mismatches already evaluate to unbound without raising. Covers W3C functions/plus-1-corrected, plus-2-corrected, and project-expression/projexp02. Adds integration tests for projection and WHERE-BIND / ORDER BY expression errors and a unit test for the new classification, and documents the semantics in docs/reference/compatibility.md.
aaj3f
left a comment
There was a problem hiding this comment.
Good SPARQL conformance fixes @bplatz 👍 A few notes below, one of them possibly more significant from a performance regression perspective.
Also, it seems all new regression tests landed only in it_query_sparql.rs / it_query_sparql_indexed.rs. That makes sense, because the focus of the PR was SPARQL, but there were additional consequences on the JSON-LD surface as well, and so perhaps it's worth some valuable additions to it_query.rs / it_query_analytical.rs / it_query_grouping.rs. e.g. a JSON-LD analytical test asserting SUM/AVG over an empty match = 0, and a JSON-LD projection/BIND expression-error test asserting an unbound cell rather than a 400. Those tests might guarantee against regressions for both (i.e. guarantee we don't ever diverge in correctness between SPARQL & JSON-LD).
| // Eligible for evaluate-once + hash-join when there is no inner slice and | ||
| // every NON-key correlation var is an unreferenced pass-through (it | ||
| // appears only in the SELECT, never constraining the body). Omitting such | ||
| // a var from the join key matches SPARQL join semantics. A correlation | ||
| // var that is referenced but not produced is a genuine per-row input. | ||
| let body_referenced = referenced_vars_set(&subquery.patterns); | ||
| let pass_through_ok = correlation_vars | ||
| .iter() | ||
| .all(|v| produced.contains(v) || !body_referenced.contains(v)); | ||
| let eligible = subquery.limit.is_none() && subquery.offset.is_none() && pass_through_ok; | ||
|
|
||
| // Cardinality guard: evaluating once + hash-join removes the per-row | ||
| // operator-rebuild overhead, which pays off when the parent drives many | ||
| // rows; for a small parent, per-row seeding (with its pruning seed) can | ||
| // be cheaper, so fall back to it (the pre-existing behavior — this guard | ||
| // never regresses below it). An uncorrelated subquery has no shared key | ||
| // and MUST be evaluated once regardless (per-row recomputes identically). | ||
| let join_mode = eligible | ||
| && (correlation_vars.is_empty() | ||
| || child | ||
| .estimated_rows() | ||
| .is_none_or(|n| n >= SUBQUERY_MATERIALIZE_MIN_PARENT_ROWS)); | ||
| let join_mode = if subquery.uncorrelated { | ||
| // SPARQL 1.1 §18.2: a sub-SELECT is evaluated INDEPENDENTLY (its | ||
| // complete, ordered, sliced solution sequence) and then joined — it | ||
| // is never seeded per parent row, which would correlate it (and let | ||
| // an inner LIMIT/OFFSET apply per row, leaking rows past the slice; | ||
| // W3C subquery/sq11). Materialize once + hash-join on `join_keys`. | ||
| // A non-produced correlation var is unbound in every inner row, so | ||
| // omitting it from the key is the correct natural join (unbound is | ||
| // compatible with any parent value), and the merge fills it from the | ||
| // parent. So this is correct regardless of `pass_through_ok`. | ||
| true | ||
| } else { |
There was a problem hiding this comment.
It seems the SPARQL lowering sites in the code(lower/select.rs:683, lower/pattern.rs:63, lower/describe.rs:87) set uncorrelated = true on every SPARQL sub-SELECT, which then forces join_mode = true (materialize-once + hash-join) unconditionally. That would then bypass both the limit/offset eligibility check and the SUBQUERY_MATERIALIZE_MIN_PARENT_ROWS cardinality guard for all of them, including plain sub-SELECTs with no ORDER BY/LIMIT/OFFSET and no aggregate
It seems per §18.2, materialize-once is "correctness-mandated" only when the subquery is sliced or aggregated. For the plain, equivalent case this then is, I think, an over-broad de-optimization. There aren't any benchmarks in this PR for this case, but in a case where the shape is a small, selective outer that shares a produced join-key var with a large, selectively-keyable inner, we'll no longer benefit from the legacy cardinality-guarded per-row pruning path that computed only the inner rows matching the outer's few keys
| /// Finalize as SPARQL SUM. Empty group returns `Unbound`. | ||
| /// Finalize as SPARQL SUM. The empty multiset sums to the additive identity | ||
| /// `"0"^^xsd:integer` (SPARQL 1.1 §18.5.1.3; W3C agg-empty-group-sum). | ||
| /// | ||
| /// Result datatype follows the W3C arithmetic promotion lattice: | ||
| /// all integer → xsd:integer (Long if it fits, else BigInt) | ||
| /// any decimal → xsd:decimal | ||
| /// any double → xsd:double | ||
| pub(crate) fn finalize_sum(self) -> Binding { | ||
| if self.count == 0 { | ||
| return Binding::Unbound; | ||
| return Binding::lit(FlakeValue::Long(0), xsd_integer()); |
There was a problem hiding this comment.
More of a question than a suggestion. The general fix here makes sense to me, but it seems this would also now affect scenarios where count == 0 is also reached by a non-empty group where all values are non-numeric/unbound (i.e. reached by both truly-empty groups and some non-empty groups). I don't know what's right for this, though. If this is not the desired behavior, we'd also need a kind of "saw any row" flag
| // SPARQL 1.1 §18.2: a sub-SELECT is evaluated INDEPENDENTLY (its | ||
| // complete, ordered, sliced solution sequence) and then joined — it | ||
| // is never seeded per parent row, which would correlate it (and let | ||
| // an inner LIMIT/OFFSET apply per row, leaking rows past the slice; | ||
| // W3C subquery/sq11). Materialize once + hash-join on `join_keys`. | ||
| // A non-produced correlation var is unbound in every inner row, so | ||
| // omitting it from the key is the correct natural join (unbound is | ||
| // compatible with any parent value), and the merge fills it from the | ||
| // parent. So this is correct regardless of `pass_through_ok`. |
There was a problem hiding this comment.
I'm not entirely positive I'm right about this, but it seems maybe that the claim, "correct regardless of pass_through_ok", may not be true for a correlation var that's bound inside the sub-SELECT by an aggregate/BIND/OPTIONAL rather than a top-level triple. Those would be excluded from join_keys and yet would be bound in the materialized rows. And then the non-clobbering merge in subquery.rs:417-423 would keep the parent's value with no equality check, so a row that should fail the natural join might survive with the parent's binding.
I'm thinking of something like
SELECT ?s
WHERE {
?s :p ?c .
{
SELECT ?s (COUNT(?x) AS ?c)
WHERE { ?s :r ?x }
GROUP BY ?s
}
}I'm not sure in this query we'd see enforcement of :p == count, for example.
With that said, if the above is right, I don't think this PR introduced this (I think it's pre-existing if true), and it's probably beyond the scope of this PR, but perhaps it's worth investigation and a follow-up issue.
… parity tests Address review feedback on #1362 / PR #1374: - Forcing materialize-once for EVERY SPARQL sub-SELECT (via uncorrelated) was over-broad: per §18.2 it is only required when the subquery is sliced, DISTINCT, aggregated, or has a correlation var referenced but not produced (an inner FILTER/BIND). A plain projection sub-SELECT is equivalent under per-row seeding, so it now falls through to the cardinality-guarded path and can prune via per-row seeding for a small, selective parent — restoring the legacy optimization that the blanket materialize-once removed. sq11 (inner LIMIT) still materializes once. - Add JSON-LD parity tests so the SPARQL and JSON-LD surfaces (shared IR) can't diverge: SUM/AVG over an empty match return 0; a SELECT/BIND projection value error leaves the cell unbound rather than failing the query. The aggregate-produced correlation-var join-enforcement gap raised in review is pre-existing (reproduces on main) and tracked separately in #1388.
|
Addressed in 245e67d
|
Addresses some SPARQL aggregate and sub-select edge cases surfaced while exercising analytical queries. These are small cleanups that bring a few corner cases in line with how the rest of the engine already behaves — no large feature work.
What's here
ORDER BY/LIMITscoping — an innerORDER BY … LIMIT non a sub-SELECT is now evaluated to its complete sliced result before it joins the enclosing pattern (instead of the slice effectively applying after the join). Also fixes a related case where a parent batch that matched nothing could end the join early.SUM/AVG— over an empty match these now return0, matching whatCOUNTalready did, rather than an unbound cell. Covers both the generic and the indexed scalar-aggregate fast paths.GROUP BYon a bare built-in —GROUP BY DATATYPE(?v)(a built-in / function call without surrounding parens) now groups correctly; the unparenthesized form was previously dropped, collapsing the query to one implicit group.[ :p ?o ]in subject/object position (and inCONSTRUCT/INSERT/DELETEtemplates) now binds its nested variables.SELECT/BIND/ORDER BYexpression (e.g. arithmetic over a heterogeneous column) leaves that one cell unbound for the row instead of failing the whole query; structural errors (wrong arity, etc.) still surface, and transactions keep strict evaluation.Testing
Closes: #1362