Skip to content

fix(query): filter and negation placement, and point-in-time visibility after reindex - #1965

Merged
bplatz merged 4 commits into
mainfrom
fix/minus-unbound-and-history
Sep 29, 2026
Merged

bplatz merged 4 commits into
mainfrom
fix/minus-unbound-and-history

Conversation

@bplatz

@bplatz bplatz commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up: #1986

Negation could run before a preceding triple filled an unbound value, producing incorrect results for VALUES with UNDEF. Point-in-time reads could also expose newer assertions after reindexing when a stored history segment contained no events; this affects plain type and property scans at an earlier t, not only negation. Separately, FILTER, EXISTS and NOT EXISTS could run before a later pattern in their group filled in a variable they read. This fixes all three pre-existing bugs; the first two were discovered while validating #1959, and the third while checking the first fix.

  • Require MINUS, EXISTS, and NOT EXISTS to wait for preceding binding-producing patterns. A variable appearing in the schema does not prove that every row has a value for it. In the 12-person regression fixture, the VALUES/UNDEF query now returns the correct 10 rows instead of 14, including all three surviving copies of the duplicated subject.
  • Replay historical leaflets even when their encoded history segment is empty. Newer assertions in the base rows still need to be undone. In the regression fixture, the historical MINUS query returns 8 rows instead of 9, while the current result remains 9. Plain type and property scans also exclude the newly inserted person at the earlier time.
  • Apply FILTER, EXISTS and NOT EXISTS to their whole group, wherever they are written (SPARQL 1.1 §18.2.2.6). A filter used to become ready once each variable it reads was in the schema. It now waits, per variable, until a pattern that binds that variable on every row is placed, or until every pattern that can bind it is. This fixes EXISTS and NOT EXISTS written before the pattern that binds a variable they read: VALUES ?p { … UNDEF } FILTER NOT EXISTS { ?p ex:worksFor ?org } ?p a ex:Person returned 2 rows instead of 10. It also fixes a plain FILTER on a variable that an OPTIONAL binds on some rows and a later required triple fills on the rest: the filter ran between the two, so FILTER(BOUND(?org)) returned 0 rows instead of 1. EXISTS and NOT EXISTS no longer hold a later OPTIONAL behind them, since they now wait for it; plain FILTERs already worked that way. In the usual case a required triple binds the variable first, so plans do not change. The query docs now say what "anywhere" placement means.
  • Add planner and integration regressions checking exact rows, counts, duplicate multiplicity, MINUS/EXISTS/NOT EXISTS, novelty-only and indexed execution, updates, and historical reads before and after reindexing. The VALUES/UNDEF case has a JSON-LD twin (a null VALUES cell followed by minus, not-exists or exists), since the planner fix is shared by both surfaces. The group-scope fix has SPARQL and JSON-LD tests for each shape, and planner tests pin that a filter on a variable a required triple binds still runs before an OPTIONAL.

Validation: 3,100 tests passed, with nine existing tests ignored. Clippy, formatting, and diff whitespace checks passed. The JSON-LD twin passes with the fix and fails with the planner change reverted (14 rows instead of 10), as the SPARQL test does.

For the group-scope fix, run on EC2:

  • fluree-db-query --lib passed 1,638.
  • grp_query_sparql, grp_query and grp_query_history passed 421, 472 and 65.
  • The full W3C suite passed 36 of 36, with no register entries to remove.
  • Clippy with --all-targets was clean.

Each part of the fix was reverted separately, and the tests aimed at it failed each time:

  • the readiness check;
  • the OPTIONAL-barrier exemption;
  • the every-row shortcut.

Relaxing #1965's negation rule to this new check was measured and rejected; see #1986.

cargo test -p fluree-db-query -p fluree-db-binary-index --lib --offline
cargo test -p fluree-db-api --test grp_query_sparql --test grp_query_history --test grp_query --test grp_policy --offline -- --test-threads=1
cargo clippy -p fluree-db-binary-index -p fluree-db-query -p fluree-db-api --lib --test grp_query_sparql --offline -- -D warnings
cargo clippy -p fluree-db-query --all-features --all-targets --locked --offline -- -D warnings
cargo fmt --all --check

@bplatz bplatz added bug Something isn't working as expected area:query Query execution, planning, fast paths, overlay, result formatting labels Sep 26, 2026
@bplatz
bplatz requested review from aaj3f and zonotope September 26, 2026 16:11

@aaj3f aaj3f 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 👍 this is great. My only personal review point to spotlight is the JSON-LD coverage of what this PR achieves (details below):


Two genuine silent-wrong-results bugs, two minimal fixes, and a regression for each that I confirmed goes red under mutation of its own fix and stays green under the other's — that's about as clean as a correctness PR gets, @bplatz. I especially like that the negation fix is one-directional by construction: after_indices is ANDed with the unchanged required_vars, so it can only delay a negation and never hoist one, which makes the safety argument something a reader can actually hold. And I chased the history fix back to the encoder rather than trusting the comment — HistSidecarBuilder::build() really does write an empty segment as a bare 0u32 with len: 4, so "empty segment" genuinely is distinguishable from "no sidecar," and since the sidecar is emitted whenever any leaflet in the leaf has entries, every sibling leaflet was getting one. That's a common trigger, not an exotic one.

Two things I'd like before this merges, neither of them about the mechanism. First, there is no CI on this head at all — gh api repos/fluree/db/commits/771be85bd/check-runs shows only the cargo-dist release workflow (plan success, everything else skipped); no test, no clippy, no fmt, no testsuite-sparql. The pull_request: branches: [main] filter in ci.yml is presumably why, and I know retargeting to main after #1959 lands will fix it — I just want it said out loud that right now the only machine verification these two fixes have is what I ran locally, on a PR whose whole subject is wrong answers. Worth confirming a real green run on the retargeted head before merge rather than after. Second, both new integration regressions are SPARQL-only, and the fix is in shared IR — JSON-LD can express the exact VALUES/UNDEF + MINUS query (parse/values.rs:30,144 maps null to Unbound), negation isn't on the parity-exempt list, and the file already carries the twin convention at :883. That's a copy of one test and I'd rather see it here.

Smaller: the title undersells the second fix — when I revert it, the first thing that breaks is a plain ?p a ex:Person count at a historical t, so this is general point-in-time correctness after reindex, not a negation bug, and titles feed the release notes. And both commits are subject-only; the schema-vs-per-row-boundness insight in your PR body is exactly what a git blame reader will want and currently won't get.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ Extends the existing DeferredPattern.after_indices mechanism rather than adding a second ordering channel; the history fix converges onto the already-correct replay_leaflet_at_t behavior instead of forking a third variant.
  • Performance (speed first, memory second): ✔ Near-neutral. The binary_cursor.rs change costs nothing — with an empty segment history_max_t == 0, so the newly-reached replay_leaflet call only happens when batch_has_rows_above_t already found real work, and load_sidecar_segment was paid before the fix either way. The planner change is strictly more constrained and can only delay a negation; the only cost is the redundant-producer shape above, which no bench covers.
  • Testing: ⚠️ it_query_negation.rs is properly declared at grp_query_sparql.rs:30-31 and genuinely runs, the assertions pin exact rows and duplicate multiplicity, and both mutation checks went red — but the coverage is SPARQL-only against a shared-IR fix, and nothing in CI has executed any of it.
  • Conventions: ⚠️ Clippy- and fmt-clean locally across all three crates with --all-targets; subject-only commit bodies on a two-bug fix, and a title that undersells half of it.

Verified locally at branch HEAD 771be85bd: fluree-db-query --lib 1633 passed · fluree-db-binary-index --all-targets 414 · grp_query_sparql 406 · grp_query 471 · grp_query_history 65 · grp_index 93 · grp_policy 116 — zero failures, and your reported "3,100 passed / 9 ignored" reproduces byte-exactly. cargo clippy -p fluree-db-query -p fluree-db-binary-index -p fluree-db-api --all-targets -- -D warnings and cargo fmt --all --check both clean. Mutation A (after_indices → Vec::new()) → minus_after_values_undef_binds_shared_variable fails left: 14, right: 10; Mutation B (restore the !history.is_empty() guard) → minus_at_historical_time_after_reindex fails left: 13, right: 12.

Approving so you can merge when ready, but I'd want a real CI run on the retargeted-to-main head before this actually lands, and the JSON-LD twin folded in while you're in there.

@@ -40,6 +40,135 @@ async fn assert_minus_count(
);

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.

fluree-db-api/tests/it_query_negation.rs:40 — optional, and the one I'd most like folded in. Both new integration regressions are SPARQL-only — assert_minus_count at :19 and assert_negation_subjects at :45 both take QueryInput::Sparql. The fix lives in shared IR (planner.rs::reorder_patterns), so JSON-LD gets the same behavior change, and JSON-LD can express the exact failing query: parse/values.rs:30,144 maps null to UnresolvedValue::Unbound, and parse/where_clause.rs:248,253 handles positional ["values", …] and ["minus", …].

Negation isn't on the parity-exempt list in docs/contributing/sparql-compliance.md (that's property paths, RDF-star, ASK and SPARQL Update), so by our own rule this wants a JSON-LD twin. The nice thing is the file already sets the precedent — jsonld_not_exists_treats_optional_unbound_var_as_free at :883 sits right next to its sparql_ sibling, and support::query_jsonld is right there.

It's a copy of one test, so I'd rather see it in this PR than tracked separately.

@@ -1915,7 +1917,9 @@ pub fn reorder_patterns(
required_vars: required,

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.

fluree-db-query/src/planner.rs:1917 — more of a question than a suggestion. (0..i).filter(|&j| !patterns[j].produced_vars().is_empty()) waits on every preceding producer, including ones whose variables the negation body never references. It only diverges from the old plan when a preceding pattern is a redundant producer — all its vars already bound by something placed earlier, e.g. ?s :p1 ?o . ?s :p2 ?o . MINUS {…} — and then the cost is (rows the anti-join would have cut) × one reducer probe.

I'm not at all sure it matters, and I like that the current form is obviously sound — after_indices is ANDed with the unchanged required_vars at :2775-2776, so it can only ever delay a negation, never hoist one, which made it easy to convince myself there's no correctness hole. A tighter rule (wait only on preceding producers whose produced_vars intersect the negation's referenced_vars(), and aren't already certainly bound) would be sound too and cheaper.

I mention it mostly because there's no bench covering negation placement at all — grep -rln "MINUS\|NOT EXISTS\|Pattern::Minus\|NotExists" over both bench dirs is zero hits — so if it ever does cost something, nothing will tell us. Happy to leave it as-is if you've already weighed it; I'd just want the reasoning in the commit body rather than nowhere.

  • PR title (no diff line — belongs in the body) — optional. "preserve negation ordering and historical visibility" undersells the second half. When I revert the binary_cursor.rs change, the first assertion that fails in minus_at_historical_time_after_reindex is SELECT (COUNT(*) AS ?n) WHERE { ?p a ex:Person } at a historical t — a plain type scan, no negation anywhere in it. Any point-in-time read against a reindexed ledger could see newer data. Since PR titles feed .github/release.yml's auto-generated notes, something like "fix(query): preserve negation ordering and point-in-time visibility after reindex" would land better with whoever is deciding whether they need the patch.

  • Both commits (no diff line — belongs in the body) — nit. The commit is subject-only for a two-bug fix, and the PR body has all the good material — the schema-vs-per-row-boundness insight and the empty-segment encoding detail are exactly the things a git blame reader six months from now will need and won't have. Your own fix: close Cypher benchgraph gaps and add benchmark-critical fast paths #1448 commit body is the model here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I measured this rather than guess. I implemented the tighter rule and A/B'd it against this PR's rule. Under the tighter rule, a negation waits on each variable its body reads only until a pattern that binds it on every row is placed, or until every pattern that could bind it is.

The comparison used query_hot_negation_count (now on main via #1959) plus five scratch scenarios that have a redundant producer. Setup: small scale (10k people), same EC2 host, both sides built the same way (thin LTO). Two runs of the same build differed by up to 30%, so the table compares the two warmed-up runs.

Scenario This PR Tighter rule
minus_count 1.34 ms 1.35 ms
not_exists_after_optional 25.7 ms 25.8 ms
?p ex:livesIn ?c . ?p a ex:Person + NOT EXISTS 7.9 ms 4.1 ms
same + MINUS 5.7 ms 2.4 ms
?p ex:name ?n . ?p a ex:Person + NOT EXISTS, rows 7.6 ms 7.7 ms
?p ex:knows ?f . ?f ex:knows ?p + NOT EXISTS 14.2 ms 40.7 ms
same + MINUS 13.1 ms 38.0 ms

It cuts both ways. Running the negation ahead of the redundant producer drops rows early, which pays off when that producer is a per-row type check. In the cycle, though, it splits the two knows triples, and those join far better together.

The tighter rule also failed this PR's seeded planner test. A variable that comes in from the seed can still be unbound on some rows. The current rule is what holds the negation behind the pattern that fills it; the tighter rule treats a seeded variable as bound everywhere.

So I'm keeping the current rule. It is sound, and it gives the same plans as main on both benches. The cost of redundant producers is real but not one-sided. Choosing the better placement per query needs a cost estimate, not a tighter readiness rule.

{
batch = replayed;
}
// An encoded sidecar segment can contain no

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.

fluree-db-binary-index/src/read/binary_cursor.rs:481 — removing the guard is right, and the reason I'm confident isn't the comment, it's that the parallel implementation never had it: replay_leaflet_at_t (read/replay.rs:126-156), used by the batched join probe (fluree-db-query/src/join.rs:168) and the indexer (run_index/build/incremental_leaf.rs:902), has always replayed unconditionally, and its doc even claims "It mirrors what BinaryCursor does internally" — which it didn't. This converges two hand-maintained copies onto the one that was already correct. (Which is also the argument for a shared gate eventually — the drift is the bug. Genuinely separable; the obstacle is that the cursor holds a decoded Vec<HistEntryV2> while the helper takes raw bytes plus a LeafletDirEntryV3.)

@@ -40,6 +40,135 @@ async fn assert_minus_count(
);

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.

fluree-db-api/tests/it_query_negation.rs:40 — minus_after_values_undef_binds_shared_variable asserting duplicate multiplicity (all three surviving copies of the duplicated subject), not just the row count, is what makes this a real regression net rather than a count check. That's the assertion that would catch a future dedup-shaped regression, and it's the one I'd have been tempted to leave out.

Base automatically changed from perf/chain-limit-startup to main September 29, 2026 11:04
@bplatz bplatz changed the title fix(query): preserve negation ordering and historical visibility fix(query): preserve negation ordering and point-in-time visibility after reindex Sep 29, 2026
The ordering fix lives in the planner both surfaces share. JSON-LD reaches
it with a null VALUES cell followed by minus, not-exists or exists, and
must keep the same rows and duplicate multiplicity as SPARQL.
A filter became ready once each variable it reads was in the schema. A
variable can be in the schema while unbound on some rows (VALUES with
UNDEF, an OPTIONAL, one UNION branch), and a later pattern in the group may
still fill it in. That went wrong two ways:

- EXISTS and NOT EXISTS waited only for patterns written before them. Written
  ahead of the pattern that binds a variable they read, they ran with it
  unbound, although SPARQL applies a FILTER to its whole group (18.2.2.6).
- A plain FILTER on a variable an OPTIONAL binds ran right after the
  OPTIONAL, before a later required triple filled in the rows the OPTIONAL
  left unbound, wherever the FILTER was written.

Each deferred FILTER, EXISTS and NOT EXISTS now records, per variable it
reads, the patterns in the group that bind it, and waits until one that
binds it on every row is placed, or all of them are. Usually a required
triple binds the variable first, so plans do not change. EXISTS and NOT
EXISTS no longer hold a later OPTIONAL behind them, since they now wait for
it; plain FILTERs already worked that way. Both surfaces share the fix.
@bplatz bplatz changed the title fix(query): preserve negation ordering and point-in-time visibility after reindex fix(query): filter and negation placement, and point-in-time visibility after reindex Sep 29, 2026
@bplatz
bplatz merged commit 079c16a into main Sep 29, 2026
16 checks passed
@bplatz
bplatz deleted the fix/minus-unbound-and-history branch September 29, 2026 12:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:query Query execution, planning, fast paths, overlay, result formatting bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants