Skip to content

fix(query): share EXISTS strategy with OPTIONAL+!bound rewrite - #1238

Merged
bplatz merged 1 commit into
mainfrom
fix/optional-not-bound-rewrite-perf
May 12, 2026
Merged

bplatz merged 1 commit into
mainfrom
fix/optional-not-bound-rewrite-perf

Conversation

@bplatz

@bplatz bplatz commented May 11, 2026

Copy link
Copy Markdown
Contributor
  • Fix the OPTIONAL { ...binds ?v... } FILTER(!bound(?v)) planner, which unconditionally chose per-row ExistsOperator and timed out on large outer streams. Both the pattern-level Pattern::Exists / Pattern::NotExists dispatch and this rewrite now share one strategy chooser, so the rewrite picks SemijoinOperator (build-once + hash probe) when the inner shares produced key vars with the outer schema.
  • Append an actionable hint to the "Unknown function" parse error covering common query attempts (!bound, nil?, not-bound, …) without misleading users who try bare ! for plain logical negation.
  • Document not-exists, (not (bound ?v)), and the SPARQL → JSON-LD translation in docs/query/jsonld-query.md; reconcile the conditional-updates doc.

Why

The rewrite at fluree-db-query/src/execute/where_plan.rs recognised the shape but unconditionally dispatched it through ExistsOperator, citing a "outer is selective, inner may be large" heuristic that doesn't hold when the outer is a full class scan. ExistsOperator::has_match rebuilds 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::NotExists dispatch already had the right logic — pick SemijoinOperator when 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 — introduce ExistsStrategy { Semijoin { key_vars } | Exists { reason } } and choose_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_strategy is the thin wrapper that calls it, emits tracing::debug!(strategy, …, "exists dispatch"), and constructs the operator. The pattern-level Pattern::Exists / Pattern::NotExists dispatch 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 "spelled not" hint for bare ! and any other !-prefixed token (so (! (= ?age 18)) doesn't get pushed toward bound-testing).

Tests

  • Five new unit tests in where_plan.rs pinning the strategy decision:
    • choose_exists_strategy_semijoin_for_root_level_absence_shape — regression guard for the OPTIONAL+!bound rewrite
    • choose_exists_strategy_exists_when_uncorrelated
    • choose_exists_strategy_exists_when_outer_only_consumed
    • choose_exists_strategy_exists_when_outer_schema_empty
    • choose_exists_strategy_semijoin_key_vars_follow_outer_schema_order
  • Two new integration tests in it_query_negation.rs asserting OPTIONAL + (not (bound ?v)) returns the same rows as the equivalent ["not-exists", ...], in both s-expression and ["not", ["bound", "?v"]] data filter forms.
  • Four hint unit tests in 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

  • Correctness is unchanged for any query: ExistsOperator and SemijoinOperator produce the same solutions for every input the chooser distinguishes. The fix is purely about which one runs.
  • The 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.
  • Failure cases that legitimately need per-row evaluation (uncorrelated inner, or inner referencing outer-only consumed vars via a filter) still get ExistsOperator — confirmed by choose_exists_strategy_exists_when_outer_only_consumed.

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).
@bplatz
bplatz requested review from aaj3f and zonotope May 11, 2026 15:31

@zonotope zonotope left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🪭

@bplatz
bplatz merged commit 462c5a5 into main May 12, 2026
12 of 13 checks passed
@bplatz
bplatz deleted the fix/optional-not-bound-rewrite-perf branch May 12, 2026 23:07
@bplatz bplatz mentioned this pull request May 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants