Skip to content

fix(query): match unbound keys in materialized subquery joins - #1827

Merged
bplatz merged 3 commits into
mainfrom
fix/subquery-unbound-join-keys
Sep 14, 2026
Merged

bplatz merged 3 commits into
mainfrom
fix/subquery-unbound-join-keys

Conversation

@bplatz

@bplatz bplatz commented Sep 12, 2026

Copy link
Copy Markdown
Contributor

Materialized subqueries treated an unbound outer join key as an exact hash key, silently losing compatible rows. For a grouped subquery over products A and B, VALUES ?p { UNDEF ex:a } returned only the explicit A match instead of A, A, B. A DISTINCT subquery with LIMIT/OFFSET similarly lost the match from the UNDEF row.

Match actual unbound key positions as wildcards. Fully bound parents retain exact hash lookups; wholly unbound keys broadcast the materialized rows; partially bound keys scan compatible existing buckets. Preserve duplicate inner and outer solutions, reconciliation of non-key variables, and the independent subquery's slice. Track raw Unbound bindings before normalization so Poisoned bindings, which also normalize to Absent, keep their existing blocking behavior.

Stacked on #1826, targeting perf/ti3-bound-literal-seeks so the diff contains this correctness fix while retaining the earlier performance improvements for combined testing.

Regression coverage includes indexed and novelty data, composite keys, duplicate rows, empty results, aggregate-output reconciliation, UNION missing columns, existing poisoned OPTIONAL behavior, DISTINCT/LIMIT/OFFSET, and reuse across parent batches. An operator-level test pins the materialized path independently of planner ordering. The grouped-UNDEF and sliced-subquery API regressions were observed failing on the parent implementation.

Validation: 2,912 passing query-engine and API tests across SPARQL, JSON-LD, history, reasoning, policy, and Cypher. Query library/test Clippy and the SPARQL API test target pass with -D warnings; formatting and whitespace checks pass. Includes a one-line numeric-literal formatting cleanup in the inherited TI3 fixture exposed by the broader test-target Clippy check.

@bplatz bplatz added bug Something isn't working as expected area:query Query execution, planning, fast paths, overlay, result formatting labels Sep 12, 2026
@bplatz
bplatz requested review from aaj3f and zonotope September 12, 2026 15:24

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

This is a good catch and a good fix. The problem makes sense and the fix is great. I would have approved outright, but Claude's sweep did uncover a possibly significant improvement for how this path could, potentially, reduce an O(n) Vec loop on the query hot-path into an O(1) op. Claude flagged it as optional below (since this PR wins on "correctness" for a condition that was previously wrong-result), but it feels worth folding-in if possible within this PR rather than as a follow-up. Full review below:


This is a really satisfying fix — the bug is a genuine silent-wrong-results one (an unbound outer key was probed as if Absent were a value, so every compatible row got dropped), and the three-way split reads like the obvious right answer once you see it: exact hash for fully bound, broadcast for wholly unbound, compatible-bucket scan for the middle. I especially like that the fast path is untouched, so BSBM never sees the new code.

I checked the tests rather than trusting them: swapping subquery.rs back to the base and rerunning, all four new API tests fail, so they pin the real defect and not a nearby one. I also chased the mirror case — an inner row unbound at a join-key column — and it's genuinely unreachable, since self_produced_vars only admits always-bound variables and pinned_requires_per_row pushes the one Cypher exception to per-row mode.

The one thing I'd like resolved before merge is the merge order: the it_query_ti3.rs clippy fix is repairing #1826 from inside #1827, which leaves #1826 red on its own branch, so that hunk really wants to move down one PR.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ extends the existing join_keys / GroupKeyOwned probe rather than adding a parallel path; reuses binding_to_group_key_normalized and the existing reconcile_vars merge unchanged.
  • Performance (speed first, memory second): ✔ fully-bound rows keep the exact hash probe and allocate no mask; the new O(buckets) scan and the whole-materialization clone run only on rows that previously returned wrong results. No bench covers this path, and none is warranted.
  • Testing: ✔ four API tests (wired at grp_query_sparql.rs:38-39, each run on novelty and indexed) all fail on the pre-fix engine, plus an operator-level test that survives planner reordering. ⚠️ the partial-scan branch has no query-level coverage — see the inline note.
  • Conventions: ✔ multi-line conventional commit, no AI attribution, cargo fmt --all -- --check and cargo clippy -p fluree-db-query --all-targets -- -D warnings both clean.

Verified locally at branch HEAD 5529b53ea: 5 API subquery-unbound tests and 2 fluree-db-query subquery unit tests pass; the same API tests go 4/4 red against base 6bf720eb9; a mutation at subquery.rs:469 is caught only by the operator-level test; git merge-tree --write-tree origin/main 5529b53ea is conflict-free, and subquery.rs is byte-identical on main, so the production change could stand alone.

Approving so you can merge when ready — just be sure the it_query_ti3.rs literal lands in #1826 first, so that branch is green on its own rather than depending on this one to fix it.

graph.push(
// Keep p3's average fanout above p2's, matching TI3's join order.
json!({"@id":format!("ex:u{i}"), "ex:p3":decimal(if i < 2 {230+i} else {100000+i % (probe / 20).max(1)})}),
json!({"@id":format!("ex:u{i}"), "ex:p3":decimal(if i < 2 {230+i} else {100_000+i % (probe / 20).max(1)})}),

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.

fluree-db-api/tests/it_query_ti3.rs:30 — blocking (merge order). This one-line 100000 → 100_000 cleanup is fixing #1826's clippy failure from inside #1827, and that leaves #1826 broken on its own. it_query_ti3.rs doesn't exist on main — it arrives with #1826 — and unreadable_literal is denied workspace-wide with fluree-db-api opting in at fluree-db-api/Cargo.toml:615, while grp_query_sparql.rs:42-43 wires this file into a real test target. So at #1826's head, cargo clippy --all --all-features --all-targets -- -D warnings fails right here, and #1826 will go red the moment it's retargeted to main and pushed — this PR's copy of the fix can't save it. Could you move the hunk down into #1826? If you'd rather not rewrite that branch, the alternative is to say explicitly in #1826 that it must not merge before #1827, but I think moving it is cleaner since #1826 should be green on its own.

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.

No longer applies: #1826 merged with the same literal fix (b2cdbc5), and after merging main this PR no longer touches it_query_ti3.rs.

// duplicate keys, and let the existing merge bind the parent.
mat.rows.clone()
} else {
let mut matches = Vec::new();

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.

fluree-db-query/src/subquery.rs:479 — optional, but I'd like it in this PR. Claude caught this: I instrumented all three arms of the probe and ran the whole new API suite plus the earlier review probe, and the partial-scan branch never executed once — every materialized probe was exact with 0 or 1 key columns or broadcast with 1, including inside grouped_subquery_restricts_partially_bound_composite_keys. Confirming from the other direction: mutating line 469 so a partially-bound key takes the exact-hash path (the pre-fix behavior for that shape) leaves all five API tests green and is caught only by the operator-level test at subquery.rs:851. I don't think that's a defect — it reads more like the planner never handing this operator a multi-column join key in these shapes — but it does mean this branch's only guard is a hand-constructed unit test, and someone will eventually "simplify" that test away. Could you either add an API-level case that provably lands here (a Cypher CALL (a, b) import, or whatever shape actually produces a two-column key), or leave a comment on the branch naming the query shape that reaches it? Minor and non-blocking — but if you agree it's right, I'd rather see it in this PR 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 288da4f

The existing composite VALUES (?p ?price) case never reaches this operator's probe: the planner runs the grouped subquery first and joins the VALUES afterwards. The new case uses a small sliced UNION parent ((?row ?p) on one side, (?row ?price) on the other), which is evaluated first and probes the two-column key with one column unbound per row. Routing partial keys through the exact hash lookup makes it fail.

Comment thread fluree-db-query/src/subquery.rs Outdated
.iter()
.zip(key)
.enumerate()
.all(|(col, (p, s))| p == s || unbound_columns.contains(&col))

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.

fluree-db-query/src/subquery.rs:488 — optional. unbound_columns.contains(&col) is a linear scan of a Vec in the innermost comparison of a per-parent-row, per-bucket loop, and the whole branch is O(buckets) per row where the old code was O(1). That cost only lands on rows that used to return wrong answers, so it isn't a regression — but this is the query engine's hot path, and a u64 bitmask would make the test a single &, while a secondary index keyed by the bound-column subset (built lazily per distinct mask) would get the branch back to O(1) amortized. I don't think this is reachable enough today to matter, given the instrumentation above — so I'd take the bitmask now and leave the secondary index alone. We may want to revisit if a real workload starts landing here.

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 288da4f

Rather than a bitmask, the bound columns are collected once per parent row and only those are compared, so there's no lookup in the bucket loop and no 64-column limit. Left the secondary index alone.

// duplicate keys, and let the existing merge bind the parent.
mat.rows.clone()
} else {
let mut matches = Vec::new();

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.

fluree-db-query/src/subquery.rs:479-490 — optional. The partial branch iterates a std::collections::HashMap, whose iteration order is randomized per process, while the other two branches emit rows in materialization order. Same query, same data, different row order run to run. SPARQL doesn't promise ordering without ORDER BY, and the new tests sort before comparing, so nothing is wrong — but it's an odd asymmetry to leave in. Worth noting that #1828 swaps the index to an IndexMap and makes this deterministic for free, which is one more reason to land the two together.

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.

Leaving this to #1828, which switches the index to an IndexMap.

// Track actual Unbound bindings before key normalization:
// Poisoned also normalizes to Absent, but must not become a
// wildcard. Fully bound rows allocate no extra mask storage.
let mut unbound_columns = Vec::new();

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.

fluree-db-query/src/subquery.rs:451-460 — praise. Capturing the unbound mask from the raw binding before binding_to_group_key_normalized runs is the detail the whole fix turns on, and it would have been very easy to get wrong: Poisoned also normalizes to Absent, and treating it as a wildcard would have resurrected failed-OPTIONAL rows and broken W3C join-scope-1. The comment says exactly that, and grouped_subquery_distinguishes_union_unbound_from_optional_poisoned pins it. Please keep both.

use crate::var_registry::VarId;

#[tokio::test]
async fn materialized_join_matches_partial_keys_without_reviving_poisoned_rows() {

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.

fluree-db-query/src/subquery.rs:851 — praise. Setting join_mode, join_keys and materialized by hand so planner reordering can't hide the case turned out to be more load-bearing than it looks — per the instrumentation above it is currently the only coverage the partial branch has. Worth a comment on the test saying so, so it survives the next cleanup pass.

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.

With the API case from 288da4f, this test is no longer the only coverage of the partial branch, so I didn't add that comment. It stays as the planner-independent pin.

Base automatically changed from perf/ti3-bound-literal-seeks to main September 14, 2026 20:15
The existing composite-key API case never reaches the materialized
probe: the planner evaluates the grouped subquery first and joins the
VALUES afterwards. A small sliced UNION parent is evaluated first and
probes the two-column key with one column unbound per row, so add that
case. Routing partial keys through the exact hash lookup now fails it.

The partial scan compared every column and skipped unbound ones with a
Vec lookup per bucket. Collect the bound columns once per parent row
and compare only those.
@bplatz
bplatz merged commit e99e07d into main Sep 14, 2026
16 checks passed
@bplatz
bplatz deleted the fix/subquery-unbound-join-keys branch September 14, 2026 20:32
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