Repository navigation
Support JOIN with arbitrary ON condition (block nested loop) - #114184
Conversation
Add `BlockNestedLoopJoinStep`, a `TableJoin`-free physical join step that will
evaluate an arbitrary `JOIN ON` condition on candidate row pairs, and select it
in `buildPhysicalJoinImpl` for the conditions that no other algorithm can claim:
where the planner used to throw `INVALID_JOIN_ON_EXPRESSION` ("cannot determine
join keys"), it now builds the new step. `INNER`/`CROSS` with `ALL` strictness
keep the cross-join-with-a-filter plan and disjunctions of equi-clauses keep
their hash clauses, so no working query changes its plan.
The operator itself is not implemented yet: `updatePipeline` throws
`NOT_IMPLEMENTED`, and the tests that pinned the old planner error now pin that.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Adds `BlockNestedLoopJoinData`, the shared build side of the block nested loop join: build streams append `StoredBlock`s to it concurrently, the size limits are checked on every insert, and `finish` closes it for writing and assigns the global row numbering the probe phase indexes through. Adds `BlockNestedLoopBuildTransform`, which feeds the build pipeline into the store and finishes its empty-header output port once the last stream is counted out by the `FinishCounter`. The store also answers what the operator must produce when the build side turns out empty, which is "nothing" for every kind except `LEFT`/`FULL` with a strictness other than `SEMI`, where every probe row is emitted padded. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`BlockNestedLoopJoinStep::updatePipeline` now builds the build-then-probe graph instead of throwing: the right input fans out to `max_streams` `BlockNestedLoopBuild` transforms sharing one `FinishCounter`, and `addPipelineBefore` holds every probe stream back until the store is closed. `WITH TOTALS` follows `JoinCommon::joinTotals`: the totals rows take no part in matching, and the joined totals row is the probe totals row extended with the build totals row or with defaults. A build side with totals uses a single build stream, the one that owns the totals port. Matching itself lands in the next change; `BlockNestedLoopProbe` still refuses a non-empty chunk with `NOT_IMPLEMENTED`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Make `BlockNestedLoopProbeTransform` actually match: for every probe chunk it walks the stored build blocks in tiles of candidate pairs, evaluates the whole `JOIN ON` condition on each tile, and emits the surviving pairs. `INNER` and `LEFT` with `ALL` strictness are complete; the remaining kinds and strictnesses still refuse to run and are the subject of the next steps. A tile is `probe_rows x build_rows` (`ColumnReplicated` over each side's source column plus an index column, where lazy replication pays off), sized in pairs independently of the output limit, so peak memory is one tile plus the build side rather than the cartesian product. `FilterDescription` turns the condition column into the match mask, which is where "a NULL condition value is not a match" comes from. Matched pairs are accumulated as row indexes and materialized once per output chunk, cut to `max_joined_block_size_rows` / `max_joined_block_size_bytes`; the walk resumes across `work` calls, so one probe chunk can span many output chunks. `LEFT` emits a probe row that matched nothing once, with the build side's columns set to their defaults. Tests that pinned the operator's `NOT_IMPLEMENTED` for a keyless `LEFT`/`INNER` join now assert its result. Those queries pin `query_plan_join_swap_table` off, because the swap turns a `LEFT` join into a `RIGHT` one, which is not implemented yet. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Give `BlockNestedLoopJoinData` a per-build-row match flag, set it from the probe core for the kinds whose result still depends on a build row after the probe phase, and add the stage that emits the build rows no probe row matched. `RIGHT` and `FULL` with `ALL` strictness now execute an arbitrary `JOIN ON` condition; `ANY`, `SEMI` and `ANTI` still refuse to run and are the subject of the next step. The flags are one `atomic_bool` per row - only matched rows are written, so a relaxed store beats an atomic `fetch_or` on a word shared by 64 rows. Both the writes and the reads are relaxed: a flag is only ever set, and the happens-before edge that makes every write visible to the scan comes from the pipeline, where a probe stream finishes its output port after its last write and `DelayedPortsProcessor` observes that finish before it opens the delayed ports. The scan itself is one `BlockNestedLoopUnmatchedBuildRowsTransform` per stream, wired as those delayed ports, with the stored blocks dealt out round-robin so the streams cover the build side exactly once without a shared cursor. An empty probe side needs no special case: the probe streams still finish and every flag is still unset. Tests that pinned the operator's `NOT_IMPLEMENTED` for a keyless `RIGHT`/`FULL` join now assert its result, and the `query_plan_join_swap_table` pins added for the unimplemented swapped kind are gone. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Complete the strictness matrix of the block nested loop join. The probe now states in one place - `PairSelection` - how many of the pairs that satisfy the condition reach the result: every one for `ALL`, one per probe row for a left-driven `ANY`/`SEMI`, one per build row for a right-driven one, one per row of both sides for `ANY INNER`, and none for `ANTI`, whose result is made of the rows that matched nothing. A probe row leaves the walk over the build side as soon as it has its pair, unless the kind pads the build rows nothing matched - those need every match flagged. A build row is given to one probe row by an atomic exchange on its match flag, so the right-driven selections need neither a lock nor a second pass. `ANY INNER` takes each row of either side at most once, rather than one row per probe row: the planner swaps a join's inputs for `ANY` and flips the kind with `reverseJoinKind`, which leaves `INNER` unchanged, so a left-driven reading would answer differently depending on `query_plan_join_swap_table`. `join_any_take_last_row` is ignored on this path, as the setting itself documents: with no join key there is no group of rows to take the last of.
The materialized build side is now kept the way a cross join keeps one: a stored block is compressed once the build side passes `cross_join_min_rows_to_compress` / `cross_join_min_bytes_to_compress`, and the whole of it is streamed to a temporary file once it holds more than `max_bytes_before_external_join` or when the query memory tracker asks for it through `spillOnSize`. `max_rows_in_join` / `max_bytes_in_join` stay a hard limit on the build side as a whole, spilled blocks included, so `join_overflow_mode` means the same whether the build side fits in memory or not. The spill file is written in block-index order and read forward only; every consumer of the store already walks the blocks by increasing index, and `BuildSideBlockReader` turns that into one forward pass. A block's row count is kept whether or not its columns are, so the global row numbering the build-side match flags are indexed by does not change when a block moves to disk.
… join Every pass that keys on a physical `JoinStep` and its `TableJoin` was read to confirm that it skips `BlockNestedLoopJoinStep` rather than concluding that the plan holds no join. None needed a change. The passes that would be wrong to skip all run before the logical join is physicalized: filter push-down reaches the input the `WHERE` names down to its `PREWHERE`, and an outer keyless join is still narrowed by a `WHERE` on its padded side - `FULL` to `LEFT`, keeping the operator, `LEFT` to `INNER`, going back to the cross join with a filter. `removeRedundantSorting` needed no companion case next to `IEJoinStep`: that entry exists because an IEJoin merges pre-sorted inputs the planner inserts for it, while the block nested loop operator requires no sorted input, so a sorting below it that an `ORDER BY` above it makes redundant is genuinely redundant. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`describeActions` reports the kind, the strictness and the `ON` condition. The condition is named by its column in the legacy format - `less(__table1.x, __table2.y)` - and rendered as the expression that computes it in the pretty one, `x < y`. `formatColumnPretty` cannot do the latter: the condition is computed inside the operator, so its name is not in the plan's pretty-name map and the sub-DAG has to be formatted directly. `actions = 1` also dumps the predicate's `ExpressionActions` next to the condition column, as `FilterStep` does for the column it filters on; the JSON overload adds the same dump as an `Expression` tree. The `JOIN` documentation gains a section on an arbitrary `ON` condition: which kinds it covers, that no `join_algorithm` selects it, and what a nested loop costs. Two of its existing claims were stale - an inequality between columns of different tables works with `join_use_nulls` (the restriction lives in `PlannerJoins::buildJoinClausesAndActions`, which nothing calls any more), and "only `hash` and `grace_hash`" is true only of a condition that also has an equality. `04821_block_nested_loop_join_spill` was flaky, 4 failures in 20 runs, always `RIGHT SEMI`: it compared the emitted pairs between a spilled and an unspilled run, but `RIGHT SEMI` and `LEFT ANY` take one pair per row of the side that drives them and which pair that is stays open. Those two now compare only their driving side's rows. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Ran the final validation pass over the operator and recorded the results in the plan. - 408 keyless `JOIN ON` queries across every supported kind/strictness and a wide set of condition shapes: none is rejected with "Cannot determine join keys". `ANY FULL` is the one admitted combination no query can reach, because `QueryTreeBuilder` rejects it for equi joins too. - No takeover of a working path: `INNER`/`CROSS` non-equi still plans as `CROSS` + filter, an all-keyed disjunction as hash clauses, two inequalities as `IEJoin`, and every modified pre-existing test line is a query that used to throw. - Peak memory is flat at ~4.3 MiB across a 20x growth in probe rows and up to 1.95 billion evaluated pairs, against identical results from the `CROSS JOIN` + `WHERE` rewrite; a hostile always-true predicate stays bounded under a memory cap. - The join stateless suite (1010 tests) has 987 passing, the 23 failures being the known environment-limited set; all 12 block nested loop tests and all 54 gtests pass; the style check reports nothing in any file this branch touches; the build is warning-free under `-Werror`.
Reconcile the plan's "Technical Details" with the operator as it was built: the store keeps `BuildBlockEntry` and hands blocks out by index through a `BuildSideBlockReader`, the match flags also cover `ANY INNER`, the happens-before edge for the unmatched scan is `DelayedPortsProcessor` rather than the `FinishCounter`, the tile is bounded in pairs by `DEFAULT_BLOCK_SIZE` rather than by the output limit, the match mask comes from `FilterDescription`, and the early exit is off for the kinds that pad unmatched build rows. The repository has no file for issue-tracker notes, so each follow-up from "Deliberately out of scope" is recorded as a `TODO` at the code site where it would land: tile pruning by interval arithmetic at `matchNextTile`, grace partitioning at `spillInMemoryBlocks`, and both the smaller-side swap and the takeover of the cross-plus-filter and disjunctive paths at the routing site in `buildPhysicalJoinImpl`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
- reject `arrayJoin` in an `ON` section with no join key: the condition is evaluated on a batch of candidate pairs and filtered with the result, so a row-count-changing condition produced `SIZES_OF_COLUMNS_DOESNT_MATCH` or a silently wrong answer; a guard in the probe turns any remaining mismatch into an error instead of a wrong result - tag `01478_not_equi-join_on` `no-old-analyzer` and pin `enable_analyzer = 1` on the three rewritten `01881_join_on_conditions_merge*` queries: routing to the operator lives in `buildPhysicalJoinImpl`, so the old analyzer still throws `INVALID_JOIN_ON_EXPRESSION` and the old-analyzer CI jobs would fail - flush the blocks already in memory when a threshold-triggered spill starts, so the temporary file really is in block-index order as its readers assume; without it the probe restarted the file once per chunk - count the largest in-memory block uncompressed and reset it on spill, so the spill reserve the memory tracker reads is neither an underestimate nor a stale peak - cut an output chunk by `max_joined_block_size_bytes` as well: the byte budget only stopped further accumulation, so a chunk could overshoot it by a whole tile - roll back `used_expressions` with the clauses in `tryAddDisjunctiveConditions`, so an abandoned disjunctive attempt no longer leaves a `_CAST` column that the operator materializes, compresses and spills for nothing - drop `EmptyBuildSideAction`, `emptyBuildSideActionFor` and `isBuildSideEmpty`: no production caller, and the kind/strictness matrix they encode duplicates `keepsUnmatchedProbeRows` - correct the documentation: only left-driven `ANY`/`SEMI` exit early, `ANY FULL` is not implemented, the operator makes a previously rejected `ON` section run, and the settings that bound, compress, spill and limit its build side say so Tests: block size limits (`04825`), the `arrayJoin` rejection, build-side totals with a non-empty probe side, the interleaved spill order, compression shrinking what is held in memory, and row counts next to the "pairs match" assertions so an empty result is no longer indistinguishable from a satisfied one.
- a right side that a physical join would look up in place - a `Join` engine table, a dictionary, another key-value storage - is an ordinary stream to the block nested loop operator, which performs no lookup and pads unmatched rows with the column type's default. The three places in `buildPhysicalJoinImpl` that leave the `join_use_nulls` conversion to the storage are now gated on `!use_block_nested_loop`, so on that path the `toNullable` aliases stay in the right pre-join actions as for any other input. Without the gate the operator emitted the raw non-nullable column into a header declaring it `Nullable` (`3 0 ''` where `3 \N \N` was correct) and any expression over it raised `Unexpected return type from plus`; for a key-value storage the predicate's own input resolved to the `Nullable` alias and the condition failed outright. `IEJoinStep` needs no such gate - `tryExtractIEJoinDescription` declines a prepared storage. - bound what the pairs waiting to be emitted keep alive. Each of them holds the build block it came from, and a compressed or spilled block is materialized anew on every read, so a condition selective enough to match a few rows in every block accumulated one materialized block per stored block and brought the whole build side back into memory. Measured on a 100 MB build side with `max_bytes_before_external_join`: 191 MiB peak before, 20 MiB after, against 29 MiB for the same query with a non-selective condition. A run over a block the reader had to materialize now counts its bytes towards `MAX_RETAINED_BUILD_BYTES`, and reaching it cuts the output chunk; a block the store hands out as it is costs nothing and is not counted. - apply `max_joined_block_size_bytes` to the two padded output stages as well. Both cut a block by row count alone, so the unmatched probe rows of a `LEFT` join and the unmatched build rows of a `RIGHT` join overshot the byte budget by orders of magnitude on a wide row: 500-row blocks of kilobyte rows against a 10 KB budget, now 9 rows. - drop `ANY FULL` from `BlockNestedLoopJoinStep::isSupportedJoinType`. Nothing in ClickHouse implements it, and `pairSelectionFor` fell through to left-driven semantics for it, so the capability predicate promised a combination the probe would have answered wrongly. - document the strictness the operator gives `ANY` and `SEMI` when there is no join key, including that `ANY INNER` limits both sides at once and which pairs make up the result is arbitrary. Tests: `04826` covers a `Join` engine and a dictionary right side under a keyless `ON` with `join_use_nulls` both ways and pins that an equality still reaches the storage as a filled join, `04827` the byte limit on the padded stages, `04828` the retained-block bound as a memory cap an unbounded walk would exceed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
- Squash the build side to `min_joined_block_size_rows` / `min_joined_block_size_bytes` before storing it. A tile of candidate pairs never spans two stored blocks, so a right input written in small blocks cost one evaluation of the condition per block per probe chunk, and the unmatched-build-rows stage emitted one chunk per block. On a 20000-row build side written one row per block, a 50-row probe went from 176 ms to 81 ms, which is what the `CROSS JOIN` plus filter path costs on the same input. - Build the gather indexes of an output chunk once per run rather than once per build column; they were rebuilt and refilled identically for every column of the build side. - `chassert` the identity-selector invariant the match flags and the unmatched scan are both indexed by, where a stored block is first read. - Say in the documentation that the operator needs the analyzer.
The block nested loop join incremented `JoinBuildTableRowCount` but never `JoinProbeTableRowCount`, so `system.query_log` reported a build row count with no probe row count for these joins - reading as an empty probe side rather than as a missing metric. Count the probe rows in `startProbeChunk`, as `JoiningTransform` does for every other join. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Do not leave `BuildSideBlockReader` naming a block it does not hold. `current_index` was assigned before the read, so a decompression or spill-file read that throws left the cached index naming the new block while `current` still held the previous one, and the fast path in `read` would then hand out the wrong block. Set up a probe chunk in `work` instead of in `prepare`. `startProbeChunk` is work over every row of the chunk (materializing const/sparse columns, sizing the match filter, filling the active-row list), and `ExecutingGraph::updateNode` calls `prepare` under the node's status mutex and does not count its time as the processor's own, so the setup both stalled the executor's traversal and was invisible in `processors_profile_log`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
- Resolve the join condition's input column positions against the headers the pipeline is actually built on instead of trusting the positions resolved against the plan's input headers at step construction time. - Release the probe stream's accumulated pairs, the build blocks they pinned and the per-chunk state when the probe finishes, instead of keeping them charged to the query for as long as the processor sits in the finished pipeline. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
- Drain accumulated join pairs with a head offset instead of erasing the front of the arrays on every output chunk: one tile accumulates up to `DEFAULT_BLOCK_SIZE` pairs, so cutting it into chunks much smaller than that moved the pending pairs once per chunk. A 20000 x 20000 keyless `LEFT JOIN` at `max_block_size = 64` went from 37.9 s to 9.1 s, and at 1024 from 3.7 s to 1.9 s, matching the default block size. - Release the build-side reader of the unmatched-build-rows stage from `prepare` rather than only where the scan runs out of blocks, so that a `LIMIT` above a `RIGHT`/`FULL` join does not leave a materialized block and the temporary-file handle charged to the query until the pipeline is torn down, as `releaseProbeState` already avoids for the probe stage. - Check the type of every condition input against the type the condition declares for it when resolving it against the pipeline's headers, as `IEJoinTransform` does; a mismatch was passed through to the condition. - Correct the claim in the join documentation that every keyless condition reaches the operator: an `ON` section that is a bare column, and a disjunction with such an operand under a `join_algorithm` without `hash`/`auto` or with `allow_general_join_planning = 0`, are still rejected during logical planning.
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
|
Workflow [PR], commit [a4ca80b] Summary: ✅
AI ReviewSummaryThis PR teaches the planner to execute keyless Findings
Final Verdict
LLVM Coverage ReportMeasured on commit a4ca80b.
Changed lines: Changed C/C++ lines covered: 1201/1254 (95.77%) · Uncovered code |
| if (for_totals) | ||
| data->setBuildSideTotals(std::move(block)); | ||
| else | ||
| stop_reading = !data->addBlock(std::move(block), num_rows); |
There was a problem hiding this comment.
join_overflow_mode = 'break' only stops the current BlockNestedLoopBuildTransform. The other build streams keep pulling until they each append one more block and see addBlock == false, so with max_threads > 1 the materialized right side can overshoot max_rows_in_join / max_bytes_in_join by one full block per stream. The new overflow test forces max_threads = 1, so this stays hidden. We need a shared stop flag in BlockNestedLoopJoinData (or equivalent) that makes later addBlock calls short-circuit before storing another block once any stream has hit BREAK.
@groeneai is it known failure, do we have repro? |
|
Known, and not caused by this PR. STID 1635-49b2 is a null No JOIN frame anywhere in it. CIDB breadth for that STID: 28 rows over 18 unrelated carrier PRs, plus 7 rows on plain master ( The onset is #120311, which left that deref without the non-analyzer branch in front of it: its squash commit Yes, I have a repro, deterministic, no sanitizer and no randomization needed: CREATE TABLE t_src (id UInt64) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t_src VALUES (1);
-- the scalar subquery of a CHECK constraint is executed while the table is created
CREATE TABLE t_user (x UInt64, CONSTRAINT c CHECK x < (SELECT max(id) + 1000 FROM remote('127.0.0.1', currentDatabase(), 't_src'))) ENGINE = MergeTree ORDER BY tuple();The Two fixes are open for it:
Nothing to do on this PR. |
…k-nested-loop-join Resolve the conflict with the move of the settings changes history into the setting declarations (ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as trailing arguments of the `DECLARE` of each setting. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
# Conflicts: # src/Processors/QueryPlan/Profiling/Analysis/JoinStatsAnalyzer.cpp # src/Processors/QueryPlan/Profiling/Analysis/StepStatsAnalyzer.cpp
| /// The block nested loop join is a plan step of its own rather than an `IJoin`. It never swaps its | ||
| /// inputs and reports no per-stage metrics, so the derived per-side numbers and the spill group | ||
| /// are all there is to shape. | ||
| if (const auto * block_nested_loop_step = typeid_cast<const BlockNestedLoopJoinStep *>(context.step)) |
There was a problem hiding this comment.
Routing BlockNestedLoopJoinStep through enrichJoinSides also routes LEFT/RIGHT ANTI through matchedOutputRows. That helper currently special-cases JoinStrictness::Anti by returning the matched-row count, so the new EXPLAIN ANALYZE surface reports fanout 1.00 for anti joins (matched_output_rows == matched_rows) even though anti joins emit no matched output rows and the docs say their fanout should be 0.00.
The new 04926_block_nested_loop_join_explain_analyze test only covers FULL and INNER, so this incorrect contract stays untested. Can we either drop the anti special-case here or make it return 0 before wiring BlockNestedLoopJoinStep into the generic join-side enrichment path?
| size_t slice_rows = num_rows; | ||
| if (mayMaterializeBlocks()) | ||
| { | ||
| if (const size_t bytes_per_row = build_block.allocatedBytes() / num_rows; bytes_per_row != 0) |
There was a problem hiding this comment.
slice_rows is computed from the average allocatedBytes() / num_rows, so it does not actually enforce the MAX_STORED_BUILD_BLOCK_BYTES bound for skewed variable-width data. A block with a handful of ~900 KiB String rows and many tiny rows still gets cut into ~10-row slices here, and the slice containing those large rows is still several MiB.
That matters because compressed/spilled blocks are materialized whole per probe stream. In this shape we can still end up with multi-MiB rematerialized blocks per stream even though the store is trying to cap them at 1 MiB, which defeats the memory bound this slicing is supposed to provide. Please make the slicing conservative with respect to actual row sizes instead of using an average-per-row heuristic.
Edited by the nightly changelog CI job following .claude/skills/edit-changelog/SKILL.md. Changelog-revert: 123033 122902 Revert "Revert "Fix ALTER TABLE ... COMMENT COLUMN being silently discarded on a materialized view with an inner table"" Changelog-revert: 123588 123062 Revert "Cancel vector similarity index builds when a merge or mutation is cancelled" Changelog-revert: 123641 114184 Revert "Support JOIN with arbitrary ON condition (block nested loop)" Changelog-deleted-entry: 114184 [New Feature] [raw] * Implemented generic block nested loop join algorithm. `JOIN` now supports an arbitrary `ON` condition with no equality between the two tables, executing it as a block nested loop join — as slow as a `CROSS JOIN` with a filter — instead of failing with `INVALID_JOIN_ON_EXPRESSION`; the new setting `allow_block_nested_loop_join` turns it on/off. Close [#106352](#106352). [#114184](#114184) ([Vladimir Cherkasov](https://github.com/vdimir)). Changelog-deleted-entry: 123062 [Improvement] [section] * `DROP TABLE` and other operations that cancel merges and mutations no longer wait for an in-progress `vector_similarity` index build to finish. [#123062](#123062) ([Raúl Marín](https://github.com/Algunenano)).
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
JOINnow supports an arbitraryONcondition with no equality between the two tables, executing it as a block nested loop join — as slow as aCROSS JOINwith a filter — instead of failing withINVALID_JOIN_ON_EXPRESSION; the new settingallow_block_nested_loop_jointurns it on/off.Close Support OUTER JOIN with an inequality key #106352
Workflow [PR]
Sync PR [sync-upstream/pr/114184]
Version info
26.10.1.1293-master(included in26.10and later)