Repository navigation
fix(query): filter and negation placement, and point-in-time visibility after reindex - #1965
Conversation
aaj3f
left a comment
There was a problem hiding this comment.
@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_indicesmechanism rather than adding a second ordering channel; the history fix converges onto the already-correctreplay_leaflet_at_tbehavior instead of forking a third variant. - Performance (speed first, memory second): ✔ Near-neutral. The
binary_cursor.rschange costs nothing — with an empty segmenthistory_max_t == 0, so the newly-reachedreplay_leafletcall only happens whenbatch_has_rows_above_talready found real work, andload_sidecar_segmentwas 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.rsis properly declared atgrp_query_sparql.rs:30-31and 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( | |||
| ); | |||
There was a problem hiding this comment.
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, | |||
There was a problem hiding this comment.
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.rschange, the first assertion that fails inminus_at_historical_time_after_reindexisSELECT (COUNT(*) AS ?n) WHERE { ?p a ex:Person }at a historicalt— 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 blamereader 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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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( | |||
| ); | |||
There was a problem hiding this comment.
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.
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.
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.VALUES ?p { … UNDEF } FILTER NOT EXISTS { ?p ex:worksFor ?org } ?p a ex:Personreturned 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, soFILTER(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.nullVALUES cell followed byminus,not-existsorexists), 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 --libpassed 1,638.grp_query_sparql,grp_queryandgrp_query_historypassed 421, 472 and 65.--all-targetswas clean.Each part of the fix was reverted separately, and the tests aimed at it failed each time:
Relaxing #1965's negation rule to this new check was measured and rejected; see #1986.