Skip to content

Support JOIN with arbitrary ON condition (block nested loop) - #114184

Merged
vdimir merged 75 commits into
masterfrom
vdimir/generic-block-nested-loop-join
Oct 2, 2026
Merged

vdimir merged 75 commits into
masterfrom
vdimir/generic-block-nested-loop-join

Conversation

@vdimir

@vdimir vdimir commented Aug 10, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

  • 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 Support OUTER JOIN with an inequality key #106352

Workflow [PR]
Sync PR [sync-upstream/pr/114184]

Version info

  • Merged into: 26.10.1.1293-master (included in 26.10 and later)

vdimir and others added 25 commits August 7, 2026 17:05
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.
@mintlify

mintlify Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Sep 30, 2026, 12:36 PM

@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a4ca80b]

Summary: ✅


AI Review

Summary

This PR teaches the planner to execute keyless JOIN ON conditions with a new block nested loop join path, adds the execution machinery for it, and documents / exposes it in EXPLAIN ANALYZE. The feature is close, but there are still correctness and contract violations on the fallback-planning path, on build-side limit enforcement, and on the new observability surface. I also found the new serialized join setting still unsafe for mixed-version distributed-plan deserialization, and the checked-in docs remain out of sync with the new contract.

Findings
  • ❌ Blockers

    • [src/Processors/QueryPlan/JoinStepLogical.cpp:1854] The new fallback still turns analyzer/name-resolution failures into executable no-key joins instead of rejecting them. The checked-in regression case at tests/queries/0_stateless/04259_cte_subquery_dot_column_leak.sql:94 now returns the padded row recorded at tests/queries/0_stateless/04259_cte_subquery_dot_column_leak.reference:17 when the default resolution collapses a.id = b.id onto one side. That is a silent wrong-answer change for malformed / ambiguously resolved ON clauses.
    • Suggested fix: keep same-side or ambiguous cross-table predicates on the INVALID_JOIN_ON_EXPRESSION / analyzer-error path until the analyzer can prove a real two-table condition.
    • [src/Interpreters/JoinOperator.cpp:451] [dismissed by author -- https://github.com/Support JOIN with arbitrary ON condition (block nested loop) #114184#discussion_r3813148168] allow_block_nested_loop_join is serialized unconditionally into every JoinSettings, but QueryPlanSerializationSettings is a strict named schema and the query-plan serialization version was not bumped for this new setting. A newer initiator can therefore send an otherwise ordinary distributed join plan to an older worker and fail during deserialization with UNKNOWN_SETTING, even when the query never needs the new operator.
    • Suggested fix: either bump the query-plan serialization version for the new setting, or gate writing / reading it the way other named plan settings are version-guarded and fail closed only when a plan actually depends on the new behavior.
    • [src/Processors/Transforms/BlockNestedLoopJoinData.cpp:269] join_overflow_mode = 'break' is only reported back to the build transform that hit the limit. Because that stop is not latched in shared BlockNestedLoopJoinData state, sibling build streams can each append another full block after the first overflow, so max_rows_in_join / max_bytes_in_join stop being hard caps under parallel build.
    • Suggested fix: latch BREAK in shared build-side state and make later addBlock calls short-circuit before accounting or storing another block.
    • [src/Processors/Transforms/BlockNestedLoopJoinData.cpp:256] Once a large incoming block is sliced, the loop appends every slice and only then runs size_limits.check. If the first slice already crosses the cap, BREAK still stores the rest of the original chunk and THROW needlessly materializes or spills it before aborting, which again violates the advertised join-size contract.
    • Suggested fix: check the limits after each appendBlock and stop the slicing loop immediately on the first failure or exception.
  • ⚠️ Majors

    • [src/Processors/Transforms/BlockNestedLoopJoinData.h:255] mayMaterializeBlocks ignores the spill-on-memory-pressure path (tmp_data != nullptr, max_bytes_in_memory == 0). In that configuration the store can still spill, but oversized build chunks skip slicing and are later rematerialized whole by every probe stream, reintroducing the per-stream memory blow-up the slicing guard is supposed to prevent.
    • Suggested fix: treat any store with tmp_data != nullptr as potentially materializing blocks, not only the threshold-driven spill case.
    • [src/Processors/Transforms/BlockNestedLoopJoinData.cpp:245] slice_rows is derived from the average allocatedBytes() / num_rows, which is not a safe upper bound for skewed variable-width rows. A block with a few large String / Array rows and many tiny rows can still produce multi-MiB slices here even though MAX_STORED_BUILD_BLOCK_BYTES is meant to cap rematerialized blocks around 1 MiB.
    • Suggested fix: cut by a conservative cumulative row-size estimate, isolating oversized rows when needed, instead of using an average-per-row heuristic.
    • [src/Processors/Transforms/BlockNestedLoopJoinTransform.cpp:649] / [src/Processors/Transforms/BlockNestedLoopJoinTransform.cpp:671] max_joined_block_size_bytes is checked and then cut using walk.build_row_bytes, i.e. the current build block’s average row width, even when the pending output already spans earlier build_runs from wider blocks. Once the walk moves from a wide build block into a narrow one, both sites can underestimate the bytes already queued and emit chunks far above the configured byte cap.
    • Suggested fix: track pending bytes per run (or maintain an accumulated pending-byte counter) instead of reusing the last block’s row width for every pending pair.
    • [src/Processors/QueryPlan/Profiling/Analysis/JoinStatsAnalyzer.cpp:282] The new BlockNestedLoopJoinStep fast path diverges from the join-step EXPLAIN ANALYZE contract in two ways: it skips the generic Cost / Selectivity / Output rows / Input (left/right) groups, and for ANTI joins it routes fanout through matchedOutputRows, which returns the matched-row count and therefore reports fanout 1.00 where the docs say ANTI joins should report fanout 0.00.
    • Suggested fix: either run block nested loop joins through the same join-step enrichment as other logical joins, or explicitly carve them out in the documented contract and fix the ANTI special-case before reusing enrichJoinSides here.
  • 💡 Nits

    • [src/Core/Settings.cpp:4278] / [src/Parsers/ParserTablesInSelectQuery.cpp:593] / [src/Parsers/ParserTablesInSelectQuery.cpp:1016] / [src/Parsers/ParserTablesInSelectQuery.cpp:1028] The docs source-of-truth and generated English docs are still out of sync. docs/reference/settings/session-settings/allow.mdx has no allow_block_nested_loop_join entry, docs/reference/statements/select/join.mdx still describes the pre-PR restrictions, and the source text in ParserTablesInSelectQuery.cpp still contains mutually contradictory statements about whether arbitrary ON expressions are supported.
    • Suggested fix: regenerate the affected English docs and remove the stale source paragraphs that still describe the old contract.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • restore rejection for analyzer-misresolved same-side ON clauses instead of normalizing them into executable no-key joins;
    • make the new serialized join setting safe for mixed-version plan deserialization;
    • enforce build-side limits at the moment the store first crosses them, including under parallel build and under sliced input;
    • fix the remaining per-stream memory / chunk-size contract violations in the block nested loop storage and probe paths;
    • bring the new EXPLAIN ANALYZE / docs surface into line with the actual behavior.

LLVM Coverage Report

Measured on commit a4ca80b.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 1201/1254 (95.77%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Aug 10, 2026
if (for_totals)
data->setBuildSideTotals(std::move(block));
else
stop_reading = !data->addBlock(std::move(block), num_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.

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.

@vdimir

vdimir commented Sep 23, 2026

Copy link
Copy Markdown
Member Author

Stress test (arm_tsan) FAIL
Segmentation fault (STID: 1635-49b2) FAIL cidb

@groeneai is it known failure, do we have repro?

@vdimir
vdimir added this pull request to the merge queue Sep 23, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Sep 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

Known, and not caused by this PR.

STID 1635-49b2 is a null query_info.query_tree dereference at StorageDistributed.cpp:636 (getOptimizedQueryProcessingStageAnalyzer), reached from the old interpreter. The stack on 410c2e76 is:

ExecuteScalarSubqueriesVisitor.cpp:124  getQueryInterpreter
  -> InterpreterSelectWithUnionQuery -> InterpreterSelectQuery::getSampleBlockImpl (:1354)
  -> StorageDistributed::getQueryProcessingStage (:555)
  -> StorageDistributed.cpp:636  typeid_cast<QueryNode const &>   // query_tree is 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 (pull_request_number = 0 AND head_ref = 'master'), across 10 check flavours, all of it since 2026-09-21 11:23Z and nothing at all in the preceding 90 days. Your own flavour on master: Stress test (arm_tsan), e96f004b.

The onset is #120311, which left that deref without the non-analyzer branch in front of it: its squash commit 3c54270f07bd is an ancestor of the head you tested, and the first occurrence anywhere is about 12 hours after it landed.

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 CREATE segfaults on a master build (3/3 here; under gdb si_addr=0x0, with both query_info.planner_context and query_info.query_tree null). This shape lands on the sibling deref at StorageDistributed.cpp:773, reported as STID 3422-39ed: same producer, same null pointer, one call further along.

Two fixes are open for it:

Nothing to do on this PR.

vdimir and others added 2 commits September 25, 2026 11:59
…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]>
vdimir added 2 commits October 1, 2026 13:18
# 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))

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.

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)

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.

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.

@vdimir
vdimir added this pull request to the merge queue Oct 2, 2026
Merged via the queue into master with commit 6276244 Oct 2, 2026
150 checks passed
@vdimir
vdimir deleted the vdimir/generic-block-nested-loop-join branch October 2, 2026 15:16
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 2, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Oct 3, 2026
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)).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support OUTER JOIN with an inequality key

6 participants