Skip to content

fix(query): BIND and UNWIND do not wait for the patterns that bind their target - #2013

Merged
bplatz merged 3 commits into
mainfrom
fix/unwind-target-placement
Oct 11, 2026
Merged

bplatz merged 3 commits into
mainfrom
fix/unwind-target-placement

Conversation

@aaj3f

@aaj3f aaj3f commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

Summary

#1995 made BIND (aa685685f) and UNWIND (f6a953e1b) wait, as FILTER already did, for the patterns that bind the variables they read. attach_filter_binders took those variables from Pattern::referenced_vars(), which for Bind and Unwind also contains the target. So an UNWIND waited for the triple that binds its own alias. That triple ran first, unconstrained, and UnwindOperator then 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:

Query before #1995 main this PR
Cypher UNWIND range(1,3) AS i MATCH (n:Item {idx: i}) RETURN n.idx (5 items) 3 15 3
Cypher UNWIND [x IN ["Alice","Bob"] | x] AS nm MATCH (p:Person {name: nm}) RETURN p.name 2 10 2
Cypher MATCH p = shortestPath((a)-[:KNOWS*]->(c)) UNWIND nodes(p) AS pn MATCH (pn:Person) RETURN pn.name 3 15 3
JSON-LD ["unwind", "?n", "(range 3 5)"], then {"@id": "?s", "ex:num": "?n"} (20 subjects) 3 60 3
JSON-LD ["unwind", "?n", "(range 3 4)"], then a union whose branches bind ?n 4 56 4

Writes are affected through JSON-LD: an update whose where is 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 literal range is 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+ ?x ran 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_binders reads with deferred_required_vars, the helper the reorder already uses for these patterns' required_vars, instead of referenced_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_vars had ended up above subquery_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.
  • The deferral of consumers of a WITH subquery's outputs: moving a BIND ahead of a sliced subquery would change its correlation.
  • Liveness and the range-semijoin fold: conservative, they only keep columns.

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 UNDEF tests (it_values_undef_placement, including f6a953e1b'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):

Shape Ledger before #1995 main this PR
Cypher UNWIND range(1,3) … MATCH (n:Item {idx: i}), 20k items novelty 0.052 (0.040–0.144) 127.0 (122.4–128.5), 60k rows 0.039 (0.036–0.144)
same indexed 0.038 (0.033–0.092) 39.9 (39.4–40.2), 60k rows 0.040 (0.033–0.112)
JSON-LD unwind then a triple, 20k subjects novelty 0.028 (0.024–0.100) 34.3 (33.4–35.9), 60k rows 0.024 (0.022–0.151)
same indexed 0.031 (0.026–0.105) 42.3 (41.5–43.1), 60k rows 0.029 (0.026–0.063)
JSON-LD unwind then a union, 20k subjects novelty 0.037 (0.035–0.064) 27.0 (26.0–28.5), 44k rows 0.036 (0.035–0.048)
same indexed 0.039 (0.038–0.042) 36.1 (35.4–36.9), 44k rows 0.040 (0.039–0.066)
SPARQL BIND(ex:s0 AS ?start) ?start ex:next+ ?x, 2k-node chain novelty 3.26 (3.15–3.59) 483.1 (431.2–514.0) 3.23 (3.17–3.57)
same indexed 65.5 (63.6–82.5) 453.5 (439.3–514.1) 58.8 (55.6–63.7)

Shapes 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): the range, list-comprehension and nodes(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 is BindOperator over PropertyPathOperator (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.

  • On an indexed ledger, a BIND whose target a triple of the same join block also binds returns no rows. 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 with Binding ==, which is false for EncodedSid against Sid and EncodedLit against Lit. It is the mixed-representation class 17472650e fixed at nine other equality surfaces; the BIND clobber checks were not among them. Routing the two clobber checks (BindOperator, InlineOperator::Bind) through the encoding-aware bindings_compatible_for_values that ValuesOperator already uses made all eight shapes I tried return the novelty answers.
  • Cypher UNWIND [1, 2, 3] AS i MATCH (n {idx: i}) returns no rows on data inserted through JSON-LD: list-literal integers lower to xsd:long (literal_to_binding), stored integers are xsd:integer.

…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 bplatz 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.

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:long vs stored xsd:integer), please file issues and reference them as Follow-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.

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.

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() {

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.

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() {

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.

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.
@bplatz

bplatz commented Oct 11, 2026

Copy link
Copy Markdown
Contributor

I merged current main into this branch (fac41609c, no conflicts) and pushed the test coverage from my review as 7dd55ef9c:

  • unwind_binds_the_variable_a_later_triple_matches_indexed runs the UNWIND-then-triple query against a rebuilt index.
  • jsonld_bind_anchors_the_property_path_that_starts_from_its_target is the JSON-LD twin of the property-path test. It asserts both the plan and the rows.
  • bind_feeds_the_union_whose_branches_read_its_target pins the BIND-before-UNION plan. The rows are the same either way, so it asserts the plan.

Each of the three fails with the one-line fix reverted.

On the other review items:

Could you update the description before merging?

  • Add Follow-up: #2054, and Follow-up: #2010 (if that's the one) along with an issue for the Cypher case.
  • The line saying the regression is in no versioned release is out of date. fix(query): place BIND and FILTER after the triple that binds their variable #1995 shipped in v4.2.3 and v4.2.4-beta.1/beta.2. On v4.2.3, BSBM's DESCRIBE (Q9) does a full scan, taking 63 s and returning an empty result; on v4.2.2 it takes 0.10 s and returns the right one. Saying so lets the release notes flag this as a fix for a released regression.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants