Repository navigation
fix(query): a constant-IRI BIND seeds the scans that read it - #2401
Conversation
reorder_patterns places a variable-free BIND first and costs every later
pattern with its variable bound, but collect_inner_join_block held the
BIND in the block and applied it only after the first scan, which then
ran with the variable free. BIND(<q> AS ?o) ?s <p> ?o read every <p>
triple and checked ?o afterwards; on Wikidata that is a 60 s timeout
where the same query written with VALUES takes 0.74 s.
A leading BIND(IRI("...") AS ?v) whose ?v a triple of the block reads now
runs on its own ahead of the block, so each scan reading ?v probes the
constant, as the VALUES spelling already does. Literal and computed
BINDs keep the held-back check: a literal probe matches numerics by
value across subtypes, where the BIND compares terms.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is a nice fix at the right altitude: the reorder already decided the BIND goes first, and this just makes execution agree. Claude found the rows unchanged from the merge-base across 96 probe cases (every scope a BIND can sit in, time travel, history, policy, indexed data with novelty, a two-ledger union), and on a 200k-subject ledger every targeted shape got faster (a selective object lookup went from 99.576 ms to 1.150 ms) with the no-BIND controls flat.
The one thing I'd fold in: the i == start gate misses the same BIND when another leading BIND comes first (a BIND("en" AS ?lang), say), so that query still scans. It's a one-line change; details below.
Full review below:
✅ Approve. This is a careful, narrow fix: it reuses the collector's existing zero-pattern fallback rather than adding a lane, the rows don't move anywhere Claude looked, and the tests check the plan as well as the rows, so they go red without the fix.
Notes:
- Optional, inline: the
i == startgate atwhere_plan.rs:2217misses a constant-IRI BIND that follows another leading BIND; gating on "no triple collected yet" closes it (Claude ran that change on a box, details on the line). - This is the fourth fix of one shape: a variable fixed to one constant by a pattern the planner costs as bound, while the plan builder applies that pattern after the scan that reads it. #1659 folded a one-row VALUES into its object, #1626 and #1824 settled which VALUES seeds a star, and this does the constant-IRI BIND;
FILTER(?o = <const>), from your "Not covered", is the next one. The class fix would be one constant-propagation pass ahead ofreorder_patternsthat treats a one-row VALUES, a constant-IRI BIND and an IRI-equality FILTER alike (fold into object positions, seed subject and predicate ones), growinginline_singleton_values_objects. It would also hand the constant to the count fast paths, which a seed can't reach: a COUNT over the seeded probe takes 3.334 ms here against 0.070 ms with the IRI inline. Not this PR: the point fix is right here. - Performance: by the code, the only new work is a pattern match per BIND at a block head and one walk of the block per constant-IRI BIND, at plan time, so nothing without a constant-IRI BIND pays anything per row. Claude ran a merge-base/head A/B on a quiet c7i.4xlarge (release builds, three interleaved rounds, a fresh 200,000-subject indexed ledger per round, row counts identical at both trees); every row is in the table below. Every targeted shape got faster (-36.2% to -99.8%). The seeded chain gives up the star's
PropertyJoinOperatorthat the VALUES spelling keeps, which is where the body's "the plan theVALUESspelling already gets" isn't literal for an object, and it still wins: 24.642 ms against 49.857 ms for the VALUES twin on an unselective anchored star. The controls moved -3.4% to +4.2%, noise for code they don't reach (the +4.2% is 0.024 vs 0.025 ms). - No bench covers a BIND today. A BIND twin next to the singleton VALUES control in
fluree-db-api/benches/query_hot_values_star.rswould pin this gain. Minor and non-blocking, but if you agree, I'd rather see it in this PR than lost in the backlog. - Merge order with my #2214 and #2201: both merge cleanly with this (
git merge-tree), and #2201 only touchesrunner.rs. Claude merged this onto #2214, whose union-graph scans the seeded probe now flows through, and ran the probes andit_query_explain: rows match this head everywhere except["iri", "ex:T1"], which #2214 now expands through the@context(#2214 alone gives the same rows, so that's its change, and by the code the expanded argument is theIRI("…")constant this seeds on). No order constraint either way.
A/B table (medians, ms)
Round 1:
| case | base r1 / r2 / r3 (ms) | head r1 / r2 / r3 (ms) | base median | head median | change |
|---|---|---|---|---|---|
Q1-obj-selective-bind |
99.576 / 102.135 / 99.443 | 1.160 / 1.150 / 1.148 | 99.576 | 1.150 | -98.8% |
Q1-obj-selective-values |
4.751 / 4.726 / 4.792 | 4.745 / 4.755 / 4.723 | 4.751 | 4.745 | -0.1% |
Q1-obj-selective-const |
4.714 / 4.726 / 4.749 | 4.708 / 4.715 / 4.734 | 4.726 | 4.715 | -0.2% |
Q2-obj-unselective-star-bind |
170.985 / 172.986 / 173.551 | 68.979 / 69.857 / 70.880 | 172.986 | 69.857 | -59.6% |
Q2-obj-unselective-star-values |
80.033 / 80.056 / 79.415 | 79.119 / 78.349 / 78.721 | 80.033 | 78.721 | -1.6% |
Q2-obj-unselective-star-const |
68.450 / 68.317 / 67.520 | 67.789 / 66.962 / 67.368 | 68.317 | 67.368 | -1.4% |
Q3-subj-bind |
90.510 / 92.366 / 91.093 | 0.197 / 0.195 / 0.196 | 91.093 | 0.196 | -99.8% |
Q3-subj-const |
0.030 / 0.029 / 0.029 | 0.028 / 0.027 / 0.028 | 0.029 | 0.028 | -3.4% |
Q4-pred-bind |
0.069 / 0.070 / 0.069 | 0.043 / 0.045 / 0.044 | 0.069 | 0.044 | -36.2% |
Q4-pred-const |
0.024 / 0.024 / 0.025 | 0.027 / 0.024 / 0.025 | 0.024 | 0.025 | +4.2% |
Q5-count-bind |
92.550 / 94.185 / 92.887 | 3.334 / 3.385 / 3.320 | 92.887 | 3.334 | -96.4% |
Q5-count-const |
0.070 / 0.074 / 0.070 | 0.070 / 0.069 / 0.083 | 0.070 | 0.070 | +0.0% |
Q6-limit-bind |
12.510 / 12.687 / 12.654 | 0.594 / 0.578 / 0.592 | 12.654 | 0.592 | -95.3% |
Q6-limit-const |
1.034 / 1.050 / 1.046 | 1.052 / 1.045 / 1.048 | 1.046 | 1.048 | +0.2% |
C1-ctrl-const-pair |
4.735 / 4.760 / 4.734 | 4.799 / 4.746 / 4.735 | 4.735 | 4.746 | +0.2% |
C2-ctrl-star |
1.346 / 1.328 / 1.302 | 1.256 / 1.333 / 1.287 | 1.328 | 1.287 | -3.1% |
C3-ctrl-literal-bind |
91.626 / 90.700 / 91.263 | 89.638 / 89.241 / 89.874 | 91.263 | 89.638 | -1.8% |
C4-ctrl-unread-iri-bind |
0.234 / 0.233 / 0.233 | 0.237 / 0.233 / 0.236 | 0.233 | 0.236 | +1.3% |
C5-ctrl-range |
5.140 / 5.142 / 5.129 | 5.135 / 5.139 / 5.149 | 5.140 | 5.139 | -0.0% |
C6-ctrl-scan-join |
0.020 / 0.020 / 0.020 | 0.020 / 0.020 / 0.020 | 0.020 | 0.020 | +0.0% |
Round 2 (a second pair of binaries):
| case | base r1 / r2 / r3 (ms) | head r1 / r2 / r3 (ms) | base median | head median | change |
|---|---|---|---|---|---|
Q7-literal-bind-first |
168.352 / 168.729 / 167.628 | 167.075 / 169.912 / 169.266 | 168.352 | 169.266 | +0.5% |
Q7-literal-bind-first-values |
108.363 / 107.336 / 108.221 | 108.448 / 106.384 / 107.138 | 108.221 | 107.138 | -1.0% |
Q7-iri-bind-first |
151.044 / 150.753 / 150.246 | 1.208 / 1.223 / 1.208 | 150.753 | 1.208 | -99.2% |
Q8-unselective-anchored-star-bind |
45.545 / 45.391 / 45.229 | 24.562 / 24.642 / 24.831 | 45.391 | 24.642 | -45.7% |
Q8-unselective-anchored-star-values |
48.596 / 48.766 / 48.556 | 49.293 / 50.451 / 49.857 | 48.596 | 49.857 | +2.6% |
Q8-unselective-anchored-star-const |
46.921 / 46.940 / 47.053 | 47.814 / 47.325 / 48.355 | 46.940 | 47.814 | +1.9% |
Q9-selective-anchored-star-bind |
42.141 / 42.016 / 41.978 | 1.373 / 1.401 / 1.382 | 42.016 | 1.382 | -96.7% |
Q9-selective-anchored-star-const |
4.763 / 4.879 / 4.838 | 4.824 / 4.816 / 4.856 | 4.838 | 4.824 | -0.3% |
C1-ctrl-const-pair |
4.648 / 4.704 / 4.695 | 4.714 / 4.681 / 4.710 | 4.695 | 4.710 | +0.3% |
C2-ctrl-star |
1.257 / 1.280 / 1.273 | 1.272 / 1.278 / 1.331 | 1.273 | 1.278 | +0.4% |
Adherence: Patterns ✔ · Performance ✔ · Deployment targets ✔ · Testing ✔ · Conventions ✔ · verification
- Patterns/abstractions: ✔ reuses
build_single_pattern's fallback and the existingBindOperator, with no new operator or lane. SPARQL<iri>/ex:xand JSON-LD["iri", "…"]both lower toIRI("…"), so both front ends take the path; Claude's JSON-LD array, s-expression and multi-pairbindcases match the SPARQL ones. - Performance (speed first, memory second): ✔ plan-time cost only, one pass per constant-IRI BIND; measured -36.2% to -99.8% on the targeted shapes, controls within noise.
- Deployment targets: ✔ n/a: a plan-shape change in shared engine code with no thread, filesystem, clock or process-lifetime state;
wasm32andwasm-smokegreen on this head. - Testing: ✔
it_query_explainis its own[[test]]target and CI'stestjob ran all three new tests on this head; both plan tests go red with the fix reverted. A literal-first case would come with the optional gate change. - Conventions: ✔ multi-line conventional commit; no docs change needed, since rows don't change and
explain.mdalready describes the planner's side.
Verified at 873262d6a: CI test green with the three new tests run by name (16180 passed); the plan tests red at the merge-base's where_plan.rs and green here; 96 probe cases with identical rows at the merge-base and here (SPARQL and JSON-LD; OPTIONAL, UNION, MINUS, EXISTS, NOT EXISTS, subquery, nested group, GRAPH; unknown IRIs in every position; several BINDs; time travel, history, a policy that hides a property; indexed data with novelty; a two-ledger union default graph with differing namespace codes); a release A/B in two rounds; the one-line gate change run against the probes, it_query_explain, grp_query and the fluree-db-query lib tests; git merge-tree against #2214 and #2201, and the probes on this merged onto #2214.
Approving so you can merge when ready, but maybe worth folding in the gate change first, since it's the same query with one more BIND in front.
| i += 1; | ||
| } | ||
| Pattern::Bind { var, expr } => { | ||
| if i == start && bind_seeds_block(*var, expr, &patterns[i + 1..]) { |
There was a problem hiding this comment.
Optional: the same BIND still runs after the scan when another leading BIND comes first.
bind_seeds_block is only asked when i == start. The reorder drains every ready variable-free BIND in written order (planner.rs:2994-3000), so BIND("en" AS ?lang) BIND(ex:T1 AS ?o) ?s ex:about ?o . ?s ex:lang ?lang reaches the collector as [BIND ?lang, BIND ?o, …]. The literal BIND isn't an IRI, so it joins the block, and the IRI one is at start + 1, never asked, and held back exactly as before. A leading IRI BIND that no triple reads does the same.
Claude checked the plans at this head: with a literal or an unread IRI BIND in front, the plan is back to an unbound DatasetOperator scan, while the same two BINDs written the other way round seed. On the box's 200,000-subject ledger, BIND("en" AS ?lang) BIND(ex:T1 AS ?o) ?s ex:about ?o . ?s ex:lang ?lang takes 169.266 ms at this head (168.352 ms at the merge-base), and the same two BINDs written IRI-first take 1.208 ms.
It seems asking "has this block collected a triple yet?" rather than "is this the block's first pattern?" closes it. Anything collected before the break is a BIND or FILTER the reorder placed there because its inputs were bound, and a block with no triples already builds on an EmptyOperator seed (where_plan.rs:3015-3018). Claude made that one-line change on the box: both shapes then seed (BindOperator > BindOperator under the scans), all 96 of Claude's probe cases return the same rows as this head, and it_query_explain (19), grp_query (566) and fluree-db-query's lib tests (1803) pass.
| if i == start && bind_seeds_block(*var, expr, &patterns[i + 1..]) { | |
| if triples.is_empty() && bind_seeds_block(*var, expr, &patterns[i + 1..]) { |
A literal-first case in sparql_constant_iri_bind_seeds_the_triples_that_read_it would pin it. I recognize this is minor and non-blocking, but it's the same query with one more BIND in front, so if you agree it's right, I'd rather see it folded in now than lost in the backlog.
There was a problem hiding this comment.
Addressed in eb388a7
The one-line gate on its own changes rows: whatever the collector takes before the break runs ahead of the triples, so a literal BIND in front becomes a probe. BIND(1 AS ?n) BIND(ex:T1 AS ?o) ?s ex:about ?o . ?s ex:n ?n then matched xsd:int, xsd:long, xsd:decimal and xsd:double 1 as well as the xsd:integer one. So the gate admits only FILTERs, VALUES and constant-IRI BINDs ahead of the seed, and reorder_patterns drains constant-IRI BINDs first within a ready batch, so the literal-first query reaches the collector IRI-first. Both of your shapes seed now; literal_bind_ahead_of_a_constant_iri_bind_still_compares_terms pins the rows.
| /// The planner costs every triple after a variable-free BIND with its variable | ||
| /// bound, so the BIND has to run first: held back, it only checked `?o` after a | ||
| /// scan that read every `ex:about` triple. | ||
| fn assert_bind_seeds_every_scan(physical: &serde_json::Value, shape: &str) { |
There was a problem hiding this comment.
Nice: these assert the plan as well as the rows, which is what makes them bite. Claude reverted the where_plan.rs hunk under these tests on a box and both plan tests go red there, with the merge-base plan showing the BIND fused into an unbound about scan; constant_iri_bind_seed_keeps_bind_results passes at both, as it should, since the rows never changed.
The seed only fired for a BIND at the head of its block. Another leading
BIND in front of it put it back to the held-back check after a full scan:
`BIND("en" AS ?l) BIND(ex:T1 AS ?o) ?s ex:about ?o . ?s ex:lang ?l`
and the same with an IRI BIND no triple reads.
Letting any BIND ahead of the block's first triple seed it is not enough
on its own: whatever precedes it then runs ahead of the triples too, and
a literal BIND run there becomes a probe, which matches numbers by value
across datatypes where the held-back BIND compares terms.
`BIND(1 AS ?n) BIND(ex:T1 AS ?o) ?s ex:about ?o . ?s ex:n ?n` would then
match `xsd:int`, `xsd:long`, `xsd:decimal` and `xsd:double` 1 as well as
the `xsd:integer` the held-back BIND matches.
So the collector ends the block at a seeding constant-IRI BIND only when
nothing but FILTERs, VALUES and other constant-IRI BINDs precede it, and
`reorder_patterns` drains constant-IRI BINDs ahead of the rest of a ready
batch, which none of the batch reads. A literal BIND written first now
lands after the IRI BIND and stays a term check inside the block.
`singleton_anchor_bind` spells the `singleton_anchor` VALUES as `BIND(ex:A AS ?a)`. Before the BIND seeded the star it was applied after a scan of every `ex:entity1` edge, so this pins the gap between the two spellings closing.
Addressed in d453841 |
Filed as #2420. |
A seed gives the block an upstream operator, and a PropertyJoinOperator needs none, so seeding a star the planner would otherwise run as a property join replaced it with a nested-loop chain. The join starts from the star's bound object; the chain starts at the triple reading the BIND's variable, which count/ndv prices as rare whatever the IRI. With the IRI on half the subjects that took `BIND(ex:Common AS ?c) ?s ex:lang "fr" ; ex:p1 ?a ; ex:p2 ?b ; ex:about ?c` from a few milliseconds to a probe of `ex:lang` for every subject naming `ex:Common`. The collector now holds such a BIND back when the block, with it held, plans as a property join, which is the plan the block got before the seed existed. Outside a property join a seed only narrows the scan the held-back plan reads first, so it stays there, and so does a seed into the star's subject, which pins the star to one subject.
A block fed by an upstream operator cannot plan as a property join, so the check for one a seed would displace can only answer no there. It ran anyway, collecting the block a second time and extracting its filter bounds, and an OPTIONAL body is planned once per outer row: a body with a constant-IRI BIND over 50,000 outer rows paid it 50,000 times. The previous commit also said a seed only narrows the scan the held-back plan reads first wherever the block is not a property join. That is not so: the seed also decides how the next triple joins, and a common IRI the planner prices as rare takes `BIND(ex:Common AS ?c) ?s ex:lang "fr" ; ex:about ?c` from a full scan with a membership join to a probe of `ex:lang` per row. The comment no longer claims it.
|
A release A/B after the approval found two shapes this made 100–230x slower than Fixed in 6002dec (the BIND stays held back when the block would plan as a property join, unless it binds the star's subject) and dd0a5a5 (that check is skipped under an upstream operator, since an OPTIONAL body is planned once per outer row). With both, every spelling of those shapes is back to Two trade-offs remain, both in the body: a rarer IRI inside such a star keeps |
Problem
BIND(<constant> AS ?x)followed by triple patterns that use?xis executed as if?xwere unbound: the first scan reads the whole predicate (or the whole dataset) and?xis checked afterwards. Results are correct; only the plan is wrong. On the full Wikidata ledger (21.1B flakes):BIND(<Q18350948> AS ?o) ?s schema:about ?o . ?s schema:inLanguage "fr"VALUES ?o { <Q18350948> }BIND(wdt:P509 AS ?var4) . ?var5 ?var6 ?var4 . …wdt:P509inlinedBIND(wd:Q… AS ?item)is a standard WDQS idiom. Every position is affected:BIND(<a1> AS ?s) ?s <p> ?oalso scans all of<p>.Root cause
The planner and the plan builder disagree about the BIND:
reorder_patternsdrains a variable-free BIND first and adds its variable to the bound set, so later triples are costed and ordered as bound lookups (explain'slogicalestimate for?s schema:about ?oisrow-count: 2).collect_inner_join_blockcollects the same BIND as a pending bind and applies it after the first scan, as an equality check. That first scan therefore runs with the variable free, and it is the triple the planner put first because it thought the variable was bound.Fix
collect_inner_join_blockends the block at a BIND ahead of its first triple when its expression is a constant IRI, a triple in the same block reads its variable, and only FILTERs, VALUES and other constant-IRI BINDs precede it. The constant IRI isIRI("…"), which both SPARQL<iri>/ex:xand JSON-LD["iri", "…"]lower to. The existing fallback then builds it as a standaloneBindOperatorthat seeds the block, so every triple reading the variable is a bound probe: the plan theVALUESspelling already gets. Explain's execution hints use the same collector, so they agree with execution.reorder_patternsdrains constant-IRI BINDs ahead of the rest of a ready batch (nothing in one batch reads another), soBIND("en" AS ?l) BIND(ex:T1 AS ?o) …reaches the collector IRI-first and seeds like the IRI-first spelling.The one exception is a star that, with the BIND held back, plans as a
PropertyJoinOperator. A seed gives the block an upstream operator and the property join needs none, so seeding it would swap the join, which starts from the star's other bound object, for a chain that starts at the triple reading the BIND's variable. The planner prices that triple atcount / ndvwhatever the IRI, so a common one drives the chain: on a 200,000-subject ledger withex:Commonon half the subjects, seeding tookBIND(ex:Common AS ?c) ?s ex:lang "fr" ; ex:p1 ?a ; ex:p2 ?b ; ex:about ?cfrom 3.5 ms to 400 ms. The collector holds such a BIND back, which is the plan the star got before this change, unless its variable is the star's subject: that seed pins the star to one subject.The scope is deliberately narrow:
BIND(ex:T1 AS ?o) ?s ex:lang "en" ; ex:p1 ?a ; ex:p2 ?b ; ex:about ?o: 451 ms before, 435 ms now, where seeding it would take 2.8 ms).BIND(ex:Common AS ?c) ?s ex:lang "fr" ; ex:about ?c, withex:Commonon half of 200,000 subjects, goes from 189 ms to 399 ms: the seed replaces a full scan with a membership join by a probe ofex:langper row. Its mirror,BIND(ex:T1 AS ?o) ?s ex:about ?o . ?s ex:lang "fr"withex:T1on two subjects, goes from 131 ms to 0.92 ms. The two differ only in the data, so telling them apart, like the bullet above, needs per-value counts the planner doesn't have. The loss is bounded: a seeded row costs about 4x a scanned one here, so the seed loses only when the IRI is on more than about a quarter of its predicate's rows, and by at most about 4x, while the gain grows with the predicate's size. In the WDQS organic log (872,555 queries), 15,595 bind a constant IRI; the two-triple shape appears 450 times, nearly all as theschema:about/schema:inLanguagequery above with a specific entity, where the seed wins, and a property-join star with a rarer IRI than its other bound object (the bullet above) at most about 360 times.same_term), so seeding a literal could change rows. That is also why a literal BIND ahead of the IRI one has to stay in the block: run ahead of the triples,BIND(1 AS ?n)would matchxsd:int,xsd:long,xsd:decimalandxsd:double1 too.count_plan,fast_whole_graph_agg,aggregate_complement_fold, …) and the R2RML SQL lane read the IR beforewhere_planand are unaffected.Tests
In
it_query_explain.rs:sparql_constant_iri_bind_seeds_the_triples_that_read_itandjsonld_constant_iri_bind_seeds_the_triples_that_read_it: in subject, predicate and object position, and after a literal BIND or an unread IRI BIND, the physical plan has the BIND as its own operator and no triple scanned with the variable free, and the rows equal theVALUEStwin's. Both fail with the fix reverted.literal_bind_ahead_of_a_constant_iri_bind_still_compares_terms:BIND(1 AS ?n)ahead of the IRI BIND seeds the plan and still matches only thexsd:integer1, as the held-back BIND does, amongxsd:int,xsd:long,xsd:decimalandxsd:doubleones.constant_iri_bind_leaves_a_star_its_property_join: an object-position BIND in a star with another bound object, SPARQL (alone and after a literal BIND, and intordf:type) and JSON-LD, keeps thePropertyJoinOperator, and a subject-position one still seeds; rows equal theVALUEStwin's. It fails with either half of the rule removed.constant_iri_bind_seed_keeps_bind_results: unknown IRIs (an unregistered namespace, and an unseen name in a known one) match nothing; a BIND inside OPTIONAL still runs per outer row; a JSON-LD BIND into a variable a triple binds still checks it.The existing cross-ledger SERVICE/GRAPH BIND cases (
it_service_cross_ledger_iri) cover the seeded probe across ledgers.query_hot_values_stargainssingleton_anchor_bind, theBINDspelling of its singleton anchor.Not covered
BIND("fr" AS ?l),BIND(NOW() AS ?t)) keep the planner/plan mismatch. Seeding them needs the numeric-equality difference above resolved first.FILTER(?o = <const>)is still applied after the join rather than as a bound object (4.65 s against 0.73 s inlined on the same Wikidata query). Follow-up: One constant-IRI fold for VALUES, BIND and FILTER equality #2420, one fold for this, the one-row VALUES and the constant-IRI BIND.Not verified