Repository navigation
fix(query): share EXISTS strategy with OPTIONAL+!bound rewrite - #1238
Merged
Merged
Conversation
The `OPTIONAL { ...binds ?v... } FILTER(!bound(?v))` shape was
recognized at planning time but unconditionally dispatched through
`ExistsOperator` (per-row inner-plan rebuild), citing a "outer is
selective, inner may be large" heuristic. For large outer streams
(e.g. 34k-row file scans) this is O(N × inner-plan-cost) and times out.
Extract the EXISTS strategy decision into a pure
`choose_exists_strategy(outer_schema, inner_patterns) -> ExistsStrategy`
helper with explicit `Semijoin { key_vars }` / `Exists { reason }`
variants. `build_exists_strategy` is a thin wrapper that calls it,
logs the choice at debug, and constructs the operator. Both the
pattern-level `Pattern::Exists` / `Pattern::NotExists` dispatch and the
`OPTIONAL { ... } FILTER(!bound(?v))` rewrite now route through the
same chooser, so the rewrite picks `SemijoinOperator` (build-once +
hash probe) when the inner shares produced key vars with the outer
schema. Per-row `Exists` is still selected for the genuine
uncorrelated and outer-only-consumed cases.
Also:
- Append an actionable hint to the "Unknown function" parse error.
Tokens that imply unbound-testing (`!bound`, `nil?`, `not-bound`,
`notbound`, `unbound`, `missing?`) point at `(not (bound ?v))` or
`["not-exists", ...]`. Bare `!` and any other `!`-prefixed token get
the generic "logical negation is spelled `not`" hint, since `(!
(= ?age 18))` is the common attempt and steering toward `bound`
there would be wrong. Existing tests matching exact
"Unknown function: foo" text keep working — unrelated names get no
hint suffix.
- Unit tests pin the strategy decision directly (a future revert to
per-row would fail CI even if integration tests still produce the
right rows): root-level absence shape → Semijoin; uncorrelated →
Exists/Uncorrelated; outer-only consumed → Exists/OuterOnlyConsumed;
empty outer schema → Exists/Uncorrelated; key var order tracks
outer schema (load-bearing for SemijoinOperator's column lookup).
- Integration tests assert `OPTIONAL { ... } FILTER (not (bound ?v))`
returns the same rows as the equivalent `["not-exists", ...]`, in
both the s-expression and the `["not", ["bound", "?v"]]` data filter
forms.
- `docs/query/jsonld-query.md` gets a new "Negation Patterns" section
covering `not-exists` as canonical, the `OPTIONAL + (not (bound ?v))`
form, a supported-vs-unsupported filter idiom table, and a
SPARQL → JSON-LD translation table. The perf note states the precise
strategy condition (inner-produced shared vars + no outer-only
consumed vars), not the broader "shares a variable" wording.
- `docs/transactions/conditional-updates.md` reconciled: best-practice
guidance now describes both supported absence idioms and when to
pick each (OPTIONAL/BOUND when the variable feeds downstream
templates; `not-exists` for pure guards).
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
OPTIONAL { ...binds ?v... } FILTER(!bound(?v))planner, which unconditionally chose per-rowExistsOperatorand timed out on large outer streams. Both the pattern-levelPattern::Exists/Pattern::NotExistsdispatch and this rewrite now share one strategy chooser, so the rewrite picksSemijoinOperator(build-once + hash probe) when the inner shares produced key vars with the outer schema.!bound,nil?,not-bound, …) without misleading users who try bare!for plain logical negation.not-exists,(not (bound ?v)), and the SPARQL → JSON-LD translation indocs/query/jsonld-query.md; reconcile the conditional-updates doc.Why
The rewrite at
fluree-db-query/src/execute/where_plan.rsrecognised the shape but unconditionally dispatched it throughExistsOperator, citing a "outer is selective, inner may be large" heuristic that doesn't hold when the outer is a full class scan.ExistsOperator::has_matchrebuilds and re-executes the inner operator tree per outer row, so a n-row outer drives n subquery plan-and-executes.The pattern-level
Pattern::NotExistsdispatch already had the right logic — pickSemijoinOperatorwhen the inner is correlated only via produced vars. Two callers, one decision, one helper.What changed
Code
fluree-db-query/src/execute/where_plan.rs— introduceExistsStrategy { Semijoin { key_vars } | Exists { reason } }andchoose_exists_strategy(outer_schema, inner_patterns) -> ExistsStrategy. The chooser is pure (no operator construction, no stats, no I/O), unit-testable in isolation.build_exists_strategyis the thin wrapper that calls it, emitstracing::debug!(strategy, …, "exists dispatch"), and constructs the operator. The pattern-levelPattern::Exists/Pattern::NotExistsdispatch and the OPTIONAL+!bound rewrite both call it.fluree-db-query/src/parse/lower.rs—unknown_function_hint(name)appended to the "Unknown function" parse error. Bound-test hint for!bound,nil?,not-bound,notbound,unbound,missing?. Generic "spellednot" hint for bare!and any other!-prefixed token (so(! (= ?age 18))doesn't get pushed toward bound-testing).Tests
where_plan.rspinning the strategy decision:choose_exists_strategy_semijoin_for_root_level_absence_shape— regression guard for the OPTIONAL+!bound rewritechoose_exists_strategy_exists_when_uncorrelatedchoose_exists_strategy_exists_when_outer_only_consumedchoose_exists_strategy_exists_when_outer_schema_emptychoose_exists_strategy_semijoin_key_vars_follow_outer_schema_orderit_query_negation.rsassertingOPTIONAL + (not (bound ?v))returns the same rows as the equivalent["not-exists", ...], in both s-expression and["not", ["bound", "?v"]]data filter forms.lower.rs.Docs
docs/query/jsonld-query.md— new "Negation Patterns" section:not-exists(canonical),OPTIONAL + (not (bound ?v)),minus, supported-vs-unsupported filter idiom table, SPARQL → JSON-LD translation table. The perf note states the precise strategy condition (inner-produced shared vars + no outer-only consumed vars) rather than the broader "shares a variable" wording.docs/transactions/conditional-updates.md— reconciled with the new query docs. Best-practice guidance now describes both supported absence idioms and when to pick each.Behaviour
ExistsOperatorandSemijoinOperatorproduce the same solutions for every input the chooser distinguishes. The fix is purely about which one runs.OPTIONAL + (not (bound ?v))shape now plans the same as["not-exists", { ... }]whenever the inner shares an inner-produced var with the outer and references no outer-only var.ExistsOperator— confirmed bychoose_exists_strategy_exists_when_outer_only_consumed.