Skip to content

fix(query): a bind whose target is bound at a join step no longer yields a cross product - #2425

Merged
bplatz merged 4 commits into
mainfrom
fix/query-bind-target-live-through-joins
Nov 19, 2026
Merged

bplatz merged 4 commits into
mainfrom
fix/query-bind-target-live-through-joins

Conversation

@bplatz

@bplatz bplatz commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #1867. That PR first proposed rejecting a JSON-LD bind onto a bound variable. Its JSON-LD half was dropped to keep the existing equality-check behavior (pinned in #1453), and checking that behavior turned up this bug on main.

Follow-up: #2458 (one exhaustive set of the variables a pattern reads, for the planner's three reader sets).

Problem

In JSON-LD, a bind onto a variable an earlier pattern bound is an equality check. That has been the behavior since v4, and it is pinned on main as a reviewed divergence from SPARQL, which rejects the shape (jsonld_bind_on_bound_variable_accepted_as_constraint). The check silently disappears when a join sits between the binding and the bind:

"where": [
  { "@id": "?s", "ex:age": "?a" },
  { "@id": "?s", "ex:name": "?n" },
  { "@id": "?t", "ex:val": "?v" },
  ["bind", "?a", "?v"]
]

(count ?s) returns 6 (the cross product) instead of 1.

SPARQL reaches the same trim. A SPARQL BIND can't target an in-scope variable, but later triples can read its target, and the planner may join those triples before the one the BIND's expression needs:

SELECT (COUNT(?s) AS ?n)
WHERE { ?s ex:p ?x . BIND(?x AS ?y) ?y ex:q ?z . ?z ex:r ?w }

Over twelve ex:p subjects of which two continue through ex:q and ex:r, this returns 24 on main (every subject twice) instead of 2. The trim has been in the planner since v4, so this is a wrong SPARQL 1.1 result in every v4 release. The two-triple shape ?s ex:p ?x . BIND(?x AS ?y) ?y ex:q ?z was right either way: a leading scan doesn't trim.

Cause

The bind's expression waits on a later pattern, so the planner holds it back. Each intermediate join step trims its output to the variables still live: later triples, pending filters, and the variables pending binds' expressions read. The bind's own target wasn't among them, so a target already bound at that step (?a, or SPARQL's ?y) was trimmed. The bind then found no value and bound afresh, and the equality check, or the join it stood for, was gone.

Fix

A pending bind's target now counts as live. Ported from next (5f7b284), where the same fix also corrects SPARQL RDF 1.2 reified-edge counts; that lowering is next-only.

What a pending bind reads (its expression's variables and its target) is now one definition, BindPattern::read_vars. The live set and the range-semijoin fold's "read elsewhere" test both call it, so they can't disagree again. The fold already counted the target; the live set had spelled it out by hand without it.

Performance: the change is in planning, not execution. An operator keeps schema ∩ live, so an extra live variable that is not yet bound changes nothing. A plan changes only where a pending bind's target is already bound at a join step: a JSON-LD rebind, or a SPARQL BIND whose target later triples read and the planner joins first. There it keeps the one column the bind needs, and the answer goes from wrong to right. Every other plan is identical.

Docs

docs/query/jsonld-query.md (Bind Patterns) now says that a bind onto a bound variable filters rather than reassigns, and points to filter for comparisons.

Tests

In it_query_expression_semantics (grp_query), each failing without the fix:

  • jsonld_bind_into_a_bound_variable_checks_it_when_only_counted: the JSON-LD rebind, counted and listed (6 rows without the fix, 1 with it).
  • sparql_bind_target_read_by_later_triples_joins_on_it: the SPARQL shape above (24 without the fix, 2 with it).

When merging into next

next has 5f7b28425 and the JSON-LD test. In where_plan.rs, carry BindPattern::read_vars over and call it at next's two sites (the live set and the fold), in place of their hand-written forms. In the test file, keep next's side and add the SPARQL test.

A JSON-LD bind into a variable an earlier pattern bound is an equality
check against it. When the bind's expression waits on a later pattern, the
planner holds it back, and each intermediate join step trims its output to
the variables still live: later triples, pending filters, and the variables
pending binds' expressions read. The bind's own target was not among them,
so a target nothing else read was trimmed. The bind then found no value and
bound afresh, the check disappeared, and a count became a cross product (6
instead of 1). A pending bind now keeps its target live.

Ported from `next` (5f7b284). The JSON-LD docs now say what a bind onto
a bound variable does.
@bplatz bplatz added bug Something isn't working as expected area:query Query execution, planning, fast paths, overlay, result formatting labels Nov 17, 2026
@bplatz
bplatz requested a review from a team November 17, 2026 15:30

@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 nice find, and the port of 5f7b28425 is faithful. The one thing I'd want before this merges: it isn't JSON-LD-only. A SPARQL BIND whose target later triples read hits the same trim when the planner joins those triples first: { ?s ex:p ?x . BIND(?x AS ?y) ?y ex:q ?z . ?z ex:r ?w } returns the 24-row cross product on main and the right 2 rows with this PR (Claude reproduced it on a box). So SPARQL plans do change here, for the better, and I'd like a SPARQL test pinning that, plus the body's "every SPARQL BIND plans identically" corrected.

Full review below:


✅ Approving to unblock: please get the SPARQL regression test in before merging. The fix is the right line in the right place, and its JSON-LD test fails without it (6 rows instead of 1, mutation-checked on a box); the one gap is that it also fixes a SPARQL wrong result that nothing pins.

Before merging:

  1. fluree-db-api/tests/it_query_expression_semantics.rs:2253: add the SPARQL twin of the test, since the planner fix corrects SPARQL's 24-vs-2 cross product too.

Notes:

  • This is another instance of one shape: a hand-built set of "variables a later operator reads" misses one reader, a join trims that column, and the join silently becomes a cartesian product. Earlier instances are 016131db4 (list-view and search patterns' variables as join variables), f3003506e (the quoted-triple variables the chain elision needs) and 1a0bd7509, plus this one. The class fix would be one exhaustive "variables this pattern reads" method that collect_var_stats, the live set and the fold's read_elsewhere all call. That's not for this PR; the point fix is right here (the BindPattern-local half is the optional comment above).
  • The body's performance paragraph and the title, as in the blocking comment. Apart from the SPARQL shape, Claude found no plan change: with the head instrumented to log every step where a pending bind's target was already bound, the line changed a join step's live set only in your test and Claude's probes, across 3,659 tests in 18 fluree-db-api binaries and 1,803 fluree-db-query unit tests.
  • The docs paragraph states the #1453 / #1867 equality-check behavior as intent, which matches how #1867 settled it.
  • Merge order: this merges cleanly onto current main and alongside #2408 and #2414 (Claude merged all three on a box; this test and the parity pin pass there). My #2383 conflicts with main in list_view.rs with or without this PR, so I'll rebase it either way. On the next main→next merge, the only conflicts are this comment and the appended test; keep next's side of both.
Adherence: Patterns ✔ · Performance ✔ · Deployment targets ✔ · Testing ⚠️ · Conventions ⚠️ · verification
  • Patterns/abstractions: ✔ Fixes the live set where it's computed and matches the fold's existing rule for a bind's target. Nothing parallel added.
  • Performance (speed first, memory second): ✔ Planning-only. One more variable per pending bind per step, and the plan changes only where a pending bind's target is bound at a join step, keeping the one column the bind needs. No performance-degradation risk.
  • Deployment targets: ✔ n/a: host-neutral planner code, the same on every host.
  • Testing: ⚠️ The JSON-LD test runs in CI (grp_query) and fails without the fix. The SPARQL wrong result the same line fixes has no test.
  • Conventions: ⚠️ Multi-line commit, clippy and fmt green on the head. The body's "every SPARQL BIND" claim and the JSON-LD-only title understate what it fixes.

Verified at 0424ef4fa: CI green on this SHA (test 16,259 passed incl. the new test, clippy, fmt, testsuite-sparql, wasm32); on a box Claude reverted the hunk (the test fails 6 vs 1, the SPARQL probe returns 24 vs 2), ran the parity pins at head and under the mutation, ran the instrumented live-set pass above, and merged #2408, #2414 and #2425 onto current main (tests pass).

Approving so you can merge when ready, but please get the SPARQL test in first.

// A BIND into a variable an earlier pattern bound is an equality check
// =============================================================================

/// The bind's expression waits on the last pattern (`ex:val`, the largest

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.

Blocking: this fix also corrects a SPARQL wrong result, and nothing pins it.

A SPARQL BIND can't target an in-scope variable, but a later triple can read its target, and the planner is free to join those triples before the triple the bind's expression needs. Then the target is bound at a join step while the bind waits, and the step trims it exactly as in the JSON-LD case: the bind binds afresh and the join it stood for is gone.

Claude reproduced it on a box, with 12 ex:p subjects of which 2 continue through ex:q and ex:r. SELECT (COUNT(?s) AS ?n) WHERE { ?s ex:p ?x . BIND(?x AS ?y) ?y ex:q ?z . ?z ex:r ?w } returns 24 with this PR's where_plan.rs hunk reverted (and SELECT ?s returns every subject twice), and 2 with it. The two-triple shape ?s ex:p ?x . BIND(?x AS ?y) ?y ex:q ?z is fine either way, since a leading scan doesn't trim. The trim has been in the planner since the v4 baseline, so this is plain SPARQL 1.1 returning wrong rows in every v4 release, and this PR is what fixes it.

Since the fix is shared planner code, I think we want the SPARQL twin of your test here (it's Claude's probe, returning 2 at this head and 24 without the fix):

/// SPARQL reaches the same trim: the planner joins the triples that read the
/// BIND's target (`ex:q`, `ex:r`) before the one its expression needs
/// (`ex:p`), so the target is bound at a join step while the BIND waits.
#[tokio::test]
async fn sparql_bind_target_read_by_later_triples_joins_on_it() {
    let fluree = FlureeBuilder::memory().build_memory();
    let ledger0 = genesis_ledger(&fluree, "exprsem/bind-join-step:sparql");
    let mut graph: Vec<JsonValue> = (0..12)
        .map(|i| json!({"@id": format!("ex:s{i}"), "ex:p": {"@id": format!("ex:o{i}")}}))
        .collect();
    graph.extend([
        json!({"@id": "ex:o1", "ex:q": {"@id": "ex:z1"}}),
        json!({"@id": "ex:o2", "ex:q": {"@id": "ex:z2"}}),
        json!({"@id": "ex:z1", "ex:r": {"@id": "ex:w1"}}),
        json!({"@id": "ex:z2", "ex:r": {"@id": "ex:w2"}}),
    ]);
    let ledger = fluree
        .insert(ledger0, &json!({"@context": ctx(), "@graph": graph}))
        .await
        .expect("insert")
        .ledger;
    let q = "PREFIX ex: <http://example.org/ns/> \
             SELECT (COUNT(?s) AS ?n) WHERE { ?s ex:p ?x . BIND(?x AS ?y) ?y ex:q ?z . ?z ex:r ?w }";
    assert_eq!(sparql_rows(&fluree, &ledger, q).await, json!([[2]]));
}

Along with it, the body's performance paragraph ("every SPARQL BIND … the plan is identical") wants to say that SPARQL plans change here too, from a wrong answer to the right one. The PR title feeds the release notes, so dropping "JSON-LD" from it would let SPARQL users find this fix.

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.

Addressed in ba0e45f. The PR body's performance paragraph and the title are corrected too.

live.extend(pending_binds.iter().flat_map(|b| b.expr.referenced_vars()));
// A pending bind reads its target too: once an earlier step binds
// that variable, the bind is an equality check against it.
live.extend(pending_binds.iter().flat_map(|b| {

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 is more of a suggestion than a must. The range-semijoin fold already counts a pending bind's target as a reader (where_plan.rs:4194-4196, b.var == *v || b.expr.referenced_vars().contains(v)), and this line now does the same for the live set, so the two agree, but each says it by hand. A BindPattern::read_vars() (the expression's variables plus var) used at both sites would make "what a pending bind reads" one definition, which is the shape behind this bug and a few before it (more in the review body). It's minor and non-blocking, but if you agree it's right, I'd rather see it folded in now than lost in the backlog.

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.

Addressed in 820d147

The live-set fix this branch makes is shared planner code, and it
corrects a SPARQL wrong result as well. A SPARQL `BIND` cannot target
an in-scope variable, but later triples can read its target, and the
planner may join those triples before the one the BIND's expression
needs. The target is then bound at a join step while the BIND waits,
and the step trimmed it: the BIND bound afresh, and the join it stood
for became a cross product.

The test joins `?y ex:q ?z . ?z ex:r ?w` before `?s ex:p ?x`, which
the BIND waits on, over twelve `ex:p` subjects of which two continue
through `ex:q` and `ex:r`. It counts 2 subjects, and 24 without the
fix.
A pending bind reads its expression's variables and its target: once
an earlier step binds the target, the bind is an equality check
against it. Two planner sites count a pending bind's readers, the live
set a join step keeps and the range-semijoin fold's "read elsewhere"
test, and each spelled that out by hand. The live set had missed the
target, which is the bug this branch fixes.

`BindPattern::read_vars` now says it once, and both sites call it. It
reads the expression's variables, not `required_vars`, which a bind
containing BNODE widens to every bound variable. Planning is
unchanged.
@bplatz bplatz changed the title fix(query): a JSON-LD bind onto a bound variable keeps its equality check past a join fix(query): a bind whose target is bound at a join step no longer yields a cross product Nov 19, 2026
@bplatz

bplatz commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

add the SPARQL twin of the test, since the planner fix corrects SPARQL's 24-vs-2 cross product too

Addressed in ba0e45f; the body's "every SPARQL BIND" claim and the JSON-LD-only title are corrected.

The class fix would be one exhaustive "variables this pattern reads" method that collect_var_stats, the live set and the fold's read_elsewhere all call.

Follow-up: #2458. The BindPattern half is 820d147.

On the next main→next merge, the only conflicts are this comment and the appended test; keep next's side of both.

In the PR body under "When merging into next", with read_vars carried over to next's two sites.

@bplatz
bplatz merged commit b1977e0 into main Nov 19, 2026
21 checks passed
@bplatz
bplatz deleted the fix/query-bind-target-live-through-joins branch November 19, 2026 03:16
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