Repository navigation
fix(query): BIND and UNWIND do not wait for the patterns that bind their target - #2013
Conversation
…eir target f6a953e added UNWIND to the patterns attach_filter_binders holds behind the binders of the variables they read, and aa68568 added BIND. Both read those variables with Pattern::referenced_vars, which includes the target. So an UNWIND waited for the triple that binds its own target: the triple ran first, unconstrained, and UnwindOperator then overwrote the value it matched. `UNWIND range(1,3) AS i MATCH (n:Item {idx: i})` over five items returned 15 rows instead of 3. In JSON-LD, ["unwind", "?year", "(range 2020 2021)"] before a triple on ?year returned every order once per year, and an update whose WHERE is written that way inserted into every order. A BIND waited the same way. Behind a property path its start was no longer bound, so the path ran unanchored; behind a UNION each branch ran with the computed key unbound. attach_filter_binders now reads with deferred_required_vars, which the reorder already uses for these patterns' required_vars: a BIND's or UNWIND's expression variables, and everything a FILTER, EXISTS or NOT EXISTS mentions. A target is an output, and a pattern that also binds it joins on the value the BIND or UNWIND produced. The affected shapes get the plans they had before #1995; the VALUES UNDEF cases #1995 fixed keep theirs.
bplatz
left a comment
There was a problem hiding this comment.
Approving: the placement fix is right, and I confirmed the new tests fail with the one line reverted. Please take a look at the inline comments before merging. The first one, about UnwindOperator overwriting a bound target, is the important one.
Two more things that don't anchor to a line:
- The BIND-before-UNION plan changes in this PR and nothing pins it. That's fine given your timing note. Just flagging it in case a plan-shape assertion is cheap to add.
- For the "Found while verifying" items (the BIND comparison returning no rows on indexed ledgers, and Cypher list-literal
xsd:longvs storedxsd:integer), please file issues and reference them asFollow-up: #N, so they're tracked even if the separate PR slips.
| /// What a pattern reads is [`deferred_required_vars`]. A BIND or UNWIND target | ||
| /// is an output: a pattern that also binds it joins on the value the BIND or | ||
| /// UNWIND produces, so it is not a binder to wait for. An UNWIND held behind | ||
| /// one overwrites the value that pattern bound. |
There was a problem hiding this comment.
This fixes where the UNWIND is placed, but the overwrite itself is still in UnwindOperator: when the target is already in the child schema, it pops the bound value and pushes the element (unwind.rs). Any plan that still binds the target first gets every match back once per element. That happens when the list reads a variable that only the target's binder provides. On this branch:
"where": [{"@id": "?s", "ex:num": "?n"},
["unwind", "?n", "(range 1 (strlen (str ?s)))"]]With two subjects (ex:num 2 and 5) this returns 42 rows instead of 2. A UNION whose branches both bind ?n and ?m, followed by ["unwind", "?n", "(range 1 ?m)"], returns 6 rows instead of 1. This predates #1995, since the UNWIND had to wait on ?s before too. The node-object form in your tests only avoids it because it splits into two triples and the UNWIND now lands between them.
Could UnwindOperator treat a bound target the way BindOperator does, keeping an element only when it matches the existing value? bindings_compatible_for_values handles the mixed-representation case you found for BIND. That makes UNWIND correct whatever order the planner picks. If you'd rather keep this PR to placement only, please file it and link it as Follow-up: #N.
| /// overwrote the year the triple matched, and every order came back once per | ||
| /// element of the range. | ||
| #[tokio::test] | ||
| async fn unwind_binds_the_variable_a_later_triple_matches() { |
There was a problem hiding this comment.
Could one of these also run against an indexed ledger? After this change, the values the UNWIND produces feed straight into the triple's bound object. That's the lane where encoded vs. decoded comparisons have failed before (the BIND result in your "Found while verifying" section, and xsd:long vs xsd:integer). You measured the same row counts on an indexed ledger, but nothing pins it.
| /// the BIND let the path walk from every node before keeping the rows that | ||
| /// start at `ex:n0`. | ||
| #[tokio::test] | ||
| async fn bind_anchors_the_property_path_that_starts_from_its_target() { |
There was a problem hiding this comment.
Nit: this is SPARQL-only. Since SPARQL and JSON-LD share the IR, a JSON-LD twin (["bind", "?start", "ex:n0"] followed by the ex:next+ path) would cover the other surface.
…LD, and before a UNION Coverage the review asked for: - unwind_binds_the_variable_a_later_triple_matches_indexed: the UNWIND-then-triple query against a rebuilt index, where the triple matches the unwound values against encoded index terms. - jsonld_bind_anchors_the_property_path_that_starts_from_its_target: the JSON-LD twin of the SPARQL property-path test, asserting both the plan (the BIND feeds the path) and the rows. - bind_feeds_the_union_whose_branches_read_its_target: the BIND-before-UNION plan change, which returns the same rows either way and so needs a plan assertion. Each fails with the placement fix reverted. The explain-plan walk moves into a shared physical_ops helper so the JSON-LD test can use it.
|
I merged current
Each of the three fails with the one-line fix reverted. On the other review items:
Could you update the description before merging?
|
Summary
#1995 made BIND (
aa685685f) and UNWIND (f6a953e1b) wait, as FILTER already did, for the patterns that bind the variables they read.attach_filter_binderstook those variables fromPattern::referenced_vars(), which forBindandUnwindalso contains the target. So an UNWIND waited for the triple that binds its own alias. That triple ran first, unconstrained, andUnwindOperatorthen overwrote the value the triple had matched: every match came back once per list element.Measured at main before #1995 (
60a37e95f), at main (61b836e9a) and on this branch, with a release-build probe over a novelty-only and an indexed ledger. Row counts are the same in both:UNWIND range(1,3) AS i MATCH (n:Item {idx: i}) RETURN n.idx(5 items)UNWIND [x IN ["Alice","Bob"] | x] AS nm MATCH (p:Person {name: nm}) RETURN p.nameMATCH p = shortestPath((a)-[:KNOWS*]->(c)) UNWIND nodes(p) AS pn MATCH (pn:Person) RETURN pn.name["unwind", "?n", "(range 3 5)"], then{"@id": "?s", "ex:num": "?n"}(20 subjects)["unwind", "?n", "(range 3 4)"], then aunionwhose branches bind?nWrites are affected through JSON-LD: an update whose
whereis written that way inserted into every order instead of the two the range selects. Cypher writes cannot reach it: a runtime-list UNWIND before a write clause is rejected (lower_cypher_update.rs), and a literal list or literalrangeis folded into a parameter that desugars to VALUES. Constant lists (UNWIND [1, 2, 3],$param) lower to VALUES and were never affected.BIND had the same target inclusion. Where the BIND and the triple that binds its target are in one join block, the join chain re-places the BIND by its expression's variables, so the physical plan did not change. Where the target's binder is something else, it did: behind a property path,
BIND(ex:s0 AS ?start) ?start ex:next+ ?xran the path unanchored (table below); behind a UNION, the branches ran with the computed key unbound.The regression is in no versioned release, and solo's pinned rev predates #1995.
Fix
attach_filter_bindersreads withdeferred_required_vars, the helper the reorder already uses for these patterns'required_vars, instead ofreferenced_vars. FILTER, EXISTS and NOT EXISTS read the same variables as before; BIND and UNWIND no longer count their target. A target is an output, and a pattern that also binds it joins on the value the BIND or UNWIND produced.The doc comment describing
deferred_required_varshad ended up abovesubquery_correlation_vars; it is back on the helper and now covers UNWIND, ShortestPath and EXISTS.The other planner sites that read
referenced_vars()keep it on purpose:left_join_order_barriers: an OPTIONAL that shares a variable with a BIND or UNWIND target must not commute with it.Plans and performance
Across 19 query shapes on both ledgers (38 plans), this branch's results and physical plans are identical to main before #1995. #1995's VALUES
UNDEFtests (it_values_undef_placement, includingf6a953e1b's UNWIND test) pass unchanged.Release build, milliseconds, median of 7 runs after one discarded cold run (min–max). The machine had 16 cores and was shared with other builds (load average 11–17):
UNWIND range(1,3) … MATCH (n:Item {idx: i}), 20k itemsunwindthen a triple, 20k subjectsunwindthen aunion, 20k subjectsBIND(ex:s0 AS ?start) ?start ex:next+ ?x, 2k-node chainShapes the change does not touch stay within noise across all three trees: UNWIND followed by
WHERE n.idx = i, a constant-list UNWIND, and a BIND feeding a lookup inside one join block. The BIND-before-UNION plan differs on main, but with 3 driving rows and 200 targets the extra branch work did not show in time or fuel.Tests
Each fails without the fix (the one changed line reverted, run, restored):
planner::tests::bind_and_unwind_run_before_a_triple_that_binds_their_target: both the BIND and the UNWIND are placed behind the triple.it_query_unwind::unwind_binds_the_variable_a_later_triple_matches(grp_query_sparql): 8 rows, every order once per year, instead of 2.it_query_unwind::update_where_unwind_matches_only_the_unwound_values(grp_query_sparql): all four orders flagged instead of two.cypher_unwind_runtime_list_binds_the_alias_a_later_match_reads(it_query_cypher): therange, list-comprehension andnodes(p)aliases return 15, 10 and 15 rows instead of 3, 2 and 3.it_values_undef_placement::bind_anchors_the_property_path_that_starts_from_its_target(grp_query_sparql): the plan isBindOperatoroverPropertyPathOperator(the path walks from every node) instead of the path over the BIND. Rows are the same either way, and fuel does not count path work, so this one asserts the plan.Found while verifying, not in this PR
Both predate #1995 and are unchanged here. They are about how values are compared and lowered, not where patterns are placed, so they are being fixed in a separate PR, which will be linked here.
BIND(ex:alice AS ?s) ?s ex:name ?n,BIND(3 AS ?n) ?s ex:num ?n,?s ex:num ?num BIND(IRI(CONCAT(…)) AS ?t) ?t ex:val ?v, and their JSON-LD twins are right on a novelty-only ledger and empty once indexed. The join chain applies a BIND only after a triple step, so the BIND becomes its clobber check, and that check compares withBinding ==, which is false forEncodedSidagainstSidandEncodedLitagainstLit. It is the mixed-representation class17472650efixed at nine other equality surfaces; the BIND clobber checks were not among them. Routing the two clobber checks (BindOperator,InlineOperator::Bind) through the encoding-awarebindings_compatible_for_valuesthatValuesOperatoralready uses made all eight shapes I tried return the novelty answers.UNWIND [1, 2, 3] AS i MATCH (n {idx: i})returns no rows on data inserted through JSON-LD: list-literal integers lower toxsd:long(literal_to_binding), stored integers arexsd:integer.