Skip to content

Support IEJoin for joins ON two inequality comparisons - #109920

Merged
vdimir merged 35 commits into
masterfrom
vdimir/iejoin
Aug 6, 2026
Merged

vdimir merged 35 commits into
masterfrom
vdimir/iejoin

Conversation

@vdimir

@vdimir vdimir commented Jul 9, 2026 •

Copy link
Copy Markdown
Member

Resolves #109127

Adds the sort-based IEJoin algorithm for joins whose ON section has two inequality comparisons (<, <=, >, >=) between expressions of the joined tables.

Before this change, an INNER JOIN with only inequality conditions was executed as a CROSS JOIN with a filter, which compares every pair of rows, and the other join kinds were not supported at all. IEJoin sorts both inputs by the join expressions and finds matching pairs by scanning the sorted data, which is much faster on large tables.

To enable it, add ie_join to the join_algorithm setting:

SET join_algorithm = 'direct,parallel_hash,hash,ie_join';
SELECT t1.*, t2.* FROM t1 JOIN t2 ON t1.a < t2.a AND t1.b > t2.b;

Supported kinds are ALL INNER/LEFT/RIGHT/FULL JOIN and SEMI/ANTI LEFT/RIGHT JOIN. The position of ie_join in the list sets its priority: listed after other algorithms, it is used only when they do not apply (the ON section has no equality conditions); listed first, it takes any join with two inequality conditions, and for ALL INNER JOIN the remaining conditions of the ON section (including equalities) are applied as a filter over the join result. The join appears as an IEJoin step in EXPLAIN.

Interactive demo demonstrating how algorithm works (as of 1d8501c): iejoin_demo.html

Changelog category (leave one):

  • New Feature

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

Added the sort-based IEJoin algorithm for joins whose ON section has two
inequality comparisons (<, <=, >, >=) between the joined tables,
enabled by adding ie_join to the join_algorithm setting. Supported kinds
are ALL INNER/LEFT/RIGHT/FULL JOIN and SEMI/ANTI LEFT/RIGHT JOIN.
Previously such queries were executed as a CROSS JOIN with a filter
(INNER only), which is much slower on large tables.

Version info

  • Merged into: 26.8.1.909 (included in 26.8 and later)

@clickhouse-gh

clickhouse-gh Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5e2383d]

Summary: ✅


AI Review

Summary

This PR adds an IEJoin-based execution path for joins with two cross-table inequality predicates, wires it into the analyzer/query-plan pipeline, and adds a substantial stateless test suite around semantics, limits, residual predicates, and NULL/NaN handling. The core operator/planner issues raised earlier look addressed, but there are still a few user-facing contract gaps around when the feature is actually available and which query shapes/documented combinations it supports.

Findings

⚠️ Majors

  • [src/Core/Settings.cpp:3651-3657] The new join_algorithm = 'ie_join' documentation still reads as if the feature is generally available once the setting is listed, but the implementation is analyzer-only. Every IEJoin stateless test is tagged no-old-analyzer (for example tests/queries/0_stateless/04516_ie_join_duckdb_countzeros.sql), and there are still no IE_JOIN references anywhere in the legacy analyzer / TableJoin path. With enable_analyzer = 0, the setting is accepted but IEJoin queries either silently fall back or fail with Can't execute any of specified join algorithms.... The setting should either reject ie_join when the old analyzer is active, or document the analyzer-only requirement here and in the join docs.
  • [dismissed by author -- https://github.com/Support IEJoin for joins ON two inequality comparisons #109920#discussion_r3588781318] [src/QueryPipeline/QueryPipelineBuilder.cpp:406-409] Eligible IEJoin shapes over a subquery with WITH TOTALS still route into joinPipelinesPaired and throw NOT_IMPLEMENTED, and the test suite now pins that behavior (tests/queries/0_stateless/04544_ie_join_detection_negatives.sql). I still consider this a real issue because the public docs continue to promise that WITH TOTALS subqueries are supported inside JOIN (docs/reference/statements/select/group-by.mdx), and I still cannot find an IEJoin-specific caveat in the current tree. Either IEJoin needs to decline totals-bearing inputs before this pipeline path, or the limitation needs to be documented where users learn about inequality joins.

💡 Nits

Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.80% +0.10%

Changed lines: Changed C/C++ lines covered: 851/933 (91.21%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 9, 2026
vdimir and others added 7 commits July 13, 2026 10:49
Files from the `IEJoinStep` refactor and the DuckDB test-suite port
that were left untracked: the dedicated two-input plan step carrying
`IEJoinConditions`, the golden tests and the port of the DuckDB
`test/sql/join/iejoin/` suite.

Co-Authored-By: Claude Fable 5 <[email protected]>
Insert a per-side `SortingStep` over the first-condition key (always
ascending, NULLS LAST, `is_sorting_for_merge_join`) in
`constructIEJoinStep`, so that the read-in-order optimization can turn
it into `FinishSorting` or elide it for tables ordered by the key.

In the operator, build the L1 order with an O(n) two-way merge of the
pre-sorted sides instead of sorting the whole union: a descending L1
iterates the materialized inputs backwards, and on equal keys a loose
first condition pulls the left entry first, a strict one the right
entry (the tie policy expressed as a merge policy). The index-sort
path stays behind the new `inputs_sorted_by_first_key` flag in
`IEJoinConditions` as a fallback; debug builds check the upstream
order per chunk and validate the merged order against the comparator.

10M x 10M band join (count-only): 6.6 s -> 3.0-3.5 s from unsorted
sources, 2.97-3.29 s from MergeTree tables ordered by the key with
`optimize_read_in_order = 1`. A wide-payload check (5 String columns
of ~100 bytes per side) shows no regression from moving whole rows
through the plan-level sort (median 0.45 s vs 0.85 s for the old
index-sort path on a 32-core machine).

Co-Authored-By: Claude Fable 5 <[email protected]>
When both left key positions are equal and the operator families are
opposite (`x BETWEEN a AND b` desugars to such a pair), the L1 and L2
directions coincide for the left side, so the left entries are already
in L2 order within the L1 order. Build L2 by sorting only the right
entries by the second key and merging the two runs in place, instead
of sorting the whole union. Also prepare and filter a side's
comparison column once when both conditions read the same column.

10M x 10M `BETWEEN` band join (count-only): 3.0 s -> 0.8-1.3 s from
unsorted sources, 0.73-0.92 s from MergeTree tables ordered by the key.

Co-Authored-By: Claude Fable 5 <[email protected]>
Per condition the prepared key columns are encoded once in
`buildJoinState` into `UInt64` values whose unsigned order (with the
L1/L2 sort direction folded in) reproduces the
`compareAt(..., nan_direction_hint = 1)` order exactly, including
equality: unsigned integers widen, signed-integer-ordered types
(signed integers, `Date32`, `DateTime64`, `Decimal32/64`, `Enum`) flip
the sign bit, floats use the total-order bit trick with every NaN
mapped to the greatest encoding and `-0.0` canonicalized to `+0.0`,
and `Nullable` encodes the nested column (NULL-key rows never enter
the union). The L1 merge, the fallback L1 index sort, the L2 sort and
the frontier then compare plain integers; the encoded-vs-generic
choice is hoisted out of the loops. Types without an encoding
(`String`, 128/256-bit, ...) keep the generic `compareAt` comparator,
per condition independently, and all debug order asserts stay on the
generic comparator so a debug run cross-validates the encoding.

The second-condition keys are kept in one array indexed by L1
position (+8 bytes per union row while producing); the frontier reads
it through the `permutation` entry it already loads for bit-marking,
which measured better than denormalizing the keys into L2 order.

10Mx10M Memory-table joins, count-only, medians of 3: a zero-output
join with uncorrelated second keys (a full 20M-entry L2 sort) drops
from 10.9 s to 3.4 s in the operator single-threaded (13.9 s to 6.4 s
end-to-end) and from 10.8 s to 3.0 s at 32 threads (11.8 s to 4.0 s
end-to-end). The `BETWEEN` band join and the y = x anti-correlated
variant are unchanged within noise end-to-end (their second keys
arrive nearly sorted, so the generic L2 sort was already cheap); their
operator time at 32 threads improves 0.82 s -> 0.49 s and
0.56 s -> 0.45 s.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Core/Settings.cpp Resolved
vdimir and others added 2 commits July 13, 2026 13:07
- Exclude rows with NaN keys from the sorted union: the join predicates
  follow IEEE semantics (every comparison involving NaN is false), while
  the operator matches by the `compareAt` total order, so enabling
  `allow_experimental_ie_join` changed results for Float keys with NaN
- Enforce `max_rows_in_join` / `max_bytes_in_join` / `join_overflow_mode`
  on the total of both materialized inputs
- Bound the work of one `producePairsBatch` call by a budget, so that
  cancellation is observed during long stretches of the scan that emit
  nothing (e.g. ANTI join)
- Protect the IEJoin pre-sorts from `removeRedundantSorting`, which could
  delete them when re-run over the physical plan by the parallel-replicas
  second optimization pass, silently producing wrong join results
- Throw `LOGICAL_ERROR` in `joinPipelinesPaired` on multi-stream inputs
  instead of silently resizing away the sorted-input contract
- Probe `tryGetLeastSupertype` / `Dynamic` before committing in
  `tryExtractIEJoinDescription`, so keys without a common supertype fall
  back to the generic path instead of failing with an exception
- Update the setting descriptions to cover all supported join kinds and
  document the feature in `join.md`
- Deduplicate the supported-kind matrix in `toIEJoinKind`, drop the
  unused `limit_hint_` parameter and the redundant `l2_union` array
- Renumber tests 04506-04512/04515 to 04534-04541 (numbers taken on
  master); add tests for NaN/Inf/-0.0 keys, empty-side OUTER/SEMI/ANTI,
  detection negatives incl. `WITH TOTALS` and setting-off locks,
  `LowCardinality` keys, type extremes and 128-bit/UUID/FixedString keys,
  and size limits; add `EXPLAIN` guards to the tie/shortcut tests and
  per-family plan guards to the encoded-keys test; add
  `tests/performance/ie_join.xml`

Co-Authored-By: Claude Fable 5 <[email protected]>
@mintlify

mintlify Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

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

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 14, 2026, 12:35 AM

@vdimir vdimir changed the title Support iejoin Support IEJoin algorithm for joins with inequality conditions Jul 13, 2026
@vdimir vdimir changed the title Support IEJoin algorithm for joins with inequality conditions Support IEJoin for joins ON two inequality comparisons Jul 13, 2026
@alexey-milovidov

alexey-milovidov commented Jul 13, 2026 •

Copy link
Copy Markdown
Member

Your PR was poisoned by the test 02346_text_index_bug108519_qcc_skip_index. It is fixed in master. Please update the branch

vdimir and others added 8 commits July 14, 2026 09:00
Diagnosed the one-off randomized failure of 04513_ie_join_duckdb_overlaps:
the failing run hit a stale server binary that predated the
join_algorithm = 'ie_join' enum value (UNKNOWN_JOIN on the first SET),
not a randomized setting; 12 looped runs with settings randomization are
green on the current binary.

Add 04555_ie_join_residual_semi_anti_nullable_oracle: LEFT/RIGHT
SEMI/ANTI with residual ON conditions over Nullable inequality keys,
verified against a cross-join oracle, including checks that NULL-keyed
rows always land on the ANTI side. Full ie_join suite passes 3 runs with
randomized settings (42 tests each).

Co-Authored-By: Claude Fable 5 <[email protected]>
Behavior-preserving refactor of the IEJoin transform:
- split buildJoinState along algorithm stages (materializeSide,
  encodeKeys, buildL1, buildL2) with explicit inputs and outputs
- turn the residual flush lambdas of producePairsBatch into member
  functions flushPendingPairs and decideSemiAntiRow
- derive per-condition sort direction/strictness once in the
  constructor (KeyOrder) instead of recomputing in hot paths
- use IColumn::Permutation for the L2 permutation array
- align member naming with the codebase (l1_row_ids, l1_entries,
  num_union_entries, current_left_row_id)

All 42 ie_join stateless tests stay byte-identical; the 10M-row
benchmark stays within the pre-refactor baseline.

Co-Authored-By: Claude Fable 5 <[email protected]>
Factor the duplicated inequality-condition classification between
isIEJoinPreferred and tryExtractIEJoinDescription into a shared
tryGetInequalityBetweenTables helper, fill IEJoinPlanDescription in the
commit loop instead of during scanning, inline the single-use
ie_join_enabled flag, and drop the stale empty TableJoin clause when the
no-equality-keys IEJoin path claims the join. No behavior changes; the
ie_join suite is byte-identical.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment pass over IEJoinTransform: add per-field descriptions for the
resumable pair-scan state (l2_cursor, frontier, scan_pos,
current_left_row_id) and num_union_entries. The class-level algorithm
comment, per-stage invariants, and encoded-key invariant were already in
place; verified no development-history comments remain.

Co-Authored-By: Claude Fable 5 <[email protected]>
- Bound findNextSetBit and produceUnmatchedBatch by the produce work
  budget so a single merge() call cannot walk a whole bit array or side
  without returning to the executor (which observes cancellation).
- Move the IEJoin early-return in buildPhysicalJoinImpl above the
  TableJoin configuration that only feeds chooseJoinAlgorithm.
- Fix vacuous test 04550: ie_join was listed last while the ON section
  has an equality, so hash executed every query; now ie_join goes first
  and the plan is pinned with EXPLAIN checks.
- Pin enable_join_runtime_filters=1 in 04548/04552 (randomized in
  tests), add EXPLAIN pins to 04517's unpinned shapes, fix stale
  comments in 04518/04530.
- New tests: 04556 (ANY/ASOF/Dynamic detection negatives), 04557
  (residual over LowCardinality columns), 04558 (sparse-serialized
  inputs and extremes), 04559 (query_plan_remove_redundant_sorting
  keeps the pre-join sorts).
- Docs: join_overflow_mode and ie_join texts in Settings.cpp mention
  IEJoin limit handling, memory accumulation and single-threaded
  operator; join.md cross-links the two inequality-join sections;
  query-complexity.md join limit rows generalized beyond hash table.

Co-Authored-By: Claude Fable 5 <[email protected]>
Decline Tuple and Dynamic key types in tryExtractIEJoinDescription:
their SQL comparison (elementwise with IEEE NaN / NULL propagation for
Tuple, unwrapped values for Dynamic) diverges from the compareAt total
order the IEJoin operator matches by, producing wrong results on
NULL/NaN values (e.g. LEFT ANTI dropped rows it must keep). Such
conditions now fall back to the generic path; as residual conjuncts
they are evaluated as real SQL predicates and stay correct. Test
04560_ie_join_tuple_dynamic_keys.

Split the join-state build into stages run one per merge() call
(materialize each side / encode keys / build L1 / build L2), so the
executor observes cancellation between the whole-input passes instead
of running the entire build in a single uncancellable work() call.

Co-Authored-By: Claude Fable 5 <[email protected]>
Exclude NaN-keyed BFloat16 rows from the IEJoin sorted union, matching the
existing Float64/Float32 handling: the operator matches by the compareAt
total order where NaN is the greatest value, but the SQL inequality
predicates follow IEEE semantics under which every comparison involving
NaN is false. Add 04561_ie_join_bfloat16_nan covering INNER/LEFT/SEMI/ANTI
against the cross-join oracle.

Co-Authored-By: Claude Fable 5 <[email protected]>
@vdimir

vdimir commented Aug 6, 2026

Copy link
Copy Markdown
Member Author

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator

No repro of my own, but I can tell you it is not yours, and I can hand you the trigger.

The failure. Attempt 1 of run 31047673640 had exactly one red job, Stress test (amd_debug), and its failure is Logical error: Invalid binary search result in MergeTreeSetIndex (STID 3252-3a4a) — a key-analysis assertion, nothing to do with IEJoin. Frames: Set.cpp:977 <- KeyCondition.cpp:5860 checkInHyperrectangle <- forAnyHyperrectangle <- genericExclusionSearch <- markRangesFromPKRange. You re-ran the workflow at 09:46:32Z and attempt 2 is green, which is why the report shows 156 success / 0 failure now.

Why it is not your diff. The identical signature, frame for frame (all 13 of Set.cpp:977, KeyCondition.cpp:4592/4881/4884/5860, MergeTreeDataSelectExecutor.cpp:1079/1280/2274/2316/2352, GenericExclusionSearch.cpp:78/194, forAnyHyperrectangle), fired on master itself three hours ago: Stress test (arm_debug), sha ac34a0b269499b72ed08f4603703ebd527cc1561, 2026-08-06 09:14:50, head_ref = master. src/Processors/QueryPlan/IEJoinStep.cpp returns 404 at that sha, so none of your code is in that build. Over the last 30 days the signature has 22 rows across 18 distinct PRs, only one of them on master (predicate: test_status IN ('FAIL','ERROR') AND position(test_name, 'Invalid binary search result in MergeTreeSetIndex') > 0), and every single carrier is a debug check, because the throw is #ifndef NDEBUG (Set.cpp:976-980; release returns {true, true}).

The trigger, if you want to chase it. Your own run's artifacts were overwritten by the re-run — all three of clickhouse-server.err.log.zst, stress_run_logs.tar.zst, stderr.log under .../PRs/109920/5e2383dda199922d58d0d82e93f761234c53f0b9/stress_test_amd_debug/ now carry Last-Modified: 11:02Z and contain zero occurrences of the assertion. But an intact copy of the same failure survives on an unrelated carrier, PR 112378 sha 5a674f892a062729fe2fec5230fd4b0de244390e, and there the query is:

SELECT count() FROM t_04493_plain FINAL
WHERE flag AND (value != 7)
SETTINGS move_all_conditions_to_prewhere = 0;

from 04493_lazy_final_prewhere_derived_filter_column, i.e. the query_plan_optimize_lazy_final set-build path, which builds (flag, id) IN __lazy_final_set over the full primary key and runs index analysis on it. The randomized settings for that run are in the archive; the two I would start from are use_lightweight_primary_key_index_analysis = True (it selects the sparse PK representation at MergeTreeDataSelectExecutor.cpp:1958-1959, and genericExclusionSearch is in the stack) and merge_tree_read_split_ranges_into_intersecting_and_non_intersecting_injection_probability = 0.86.

Owner. A fix task owns this class; it has been open since the same signature was raised on 108096 in July, and it is blocked because every local reproduction attempt so far has been negative. It is not covered by the existing family fixes: the intDiv monotonicity one, and the reverse-sorting-key one merged as 109901, both need a trigger this query does not have, and the in-source TODO at Set.cpp:972-975 names the cause as applyMonotonicFunctionsChainToRange applying nonmonotonic functions so that left > right. Note the issue that TODO waits on, 90461, is already closed, so the precondition for removing the #ifndef is stale. I will follow up on the fix task, not here.

@vdimir
vdimir added this pull request to the merge queue Aug 6, 2026
@vdimir

vdimir commented Aug 6, 2026

Copy link
Copy Markdown
Member Author

@groeneai how we can address this issue then?

Merged via the queue into master with commit d6a9c4c Aug 6, 2026
355 of 356 checks passed
@vdimir
vdimir deleted the vdimir/iejoin branch August 6, 2026 12:36
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator

Two separate answers: what unblocks your PR, and what fixes the bug.

For your PR: re-run and merge, and that is not a workaround. The assertion is compiled only into debug builds. Set.cpp:976-980 is an #ifndef NDEBUG around the throw, with return {true, true} under NDEBUG, so in every release build the same condition returns "this granule may match": it costs a little index pruning and nothing else. It cannot affect the correctness of your feature, it cannot fire for users, and it cannot be caused by your diff. The identical stack fired on master at ac34a0b269499b72ed08f4603703ebd527cc1561, where src/Processors/QueryPlan/IEJoinStep.cpp does not exist. Your attempt 2 is already green. Nothing in IEJoin needs to change.

For the bug: it is mine to fix, and I owe you a correction on the pointer I gave you. I suggested starting from use_lightweight_primary_key_index_analysis = True. That is the wrong direction for your failure, and the frame list I quoted is what shows it. The setting selects which of the two MergeTreeSetIndex::checkInRange overloads runs: true takes MergeTreeDataSelectExecutor.cpp:2228, the sparse overload, which throws at Set.cpp:831; false takes :2274, the dense overload, which throws at Set.cpp:977. Your stack has :2274 and :977, so your run had that setting off. The settings I recovered came from a different occurrence, one that aborts at :831. Same defect, different arm, and I pointed you at the arm you were not in.

What I now think the actual shape is. The in-source TODO at Set.cpp:972-975 explains this as applyMonotonicFunctionsChainToRange applying nonmonotonic functions so that left > right. That explanation cannot cover this trigger. It builds (flag, id) IN __lazy_final_set over the primary key of ORDER BY (flag, id), two plain columns with no wrapping function, so isKeyPossiblyWrappedByMonotonicFunctionsImpl returns at KeyCondition.cpp:2980 with an empty chain, the loop at :5023 runs zero times, and :5079 hands the key range back untouched. With no function applied there is no nonmonotonicity to blame. So either the two partition_point predicates at Set.cpp:937-968 disagree on an input the comment at :925-934 does not cover, or the hyperrectangle arrives already inverted, which KeyCondition::checkInRange only chasserts at :4874, debug-only like the throw itself. Either way the fix is probably not the one the TODO implies.

One more thing worth recording: that TODO says to remove the #ifndef once 90461 is fixed, and 90461 was closed as completed on 2026-02-08, so its stated precondition is already stale while the assertion keeps firing. That is consistent with the cause being something else.

I have not reproduced it yet. Today I ran the dense arm locally at index granularity 1, 3, 8192 and 64882, with the recovered settings, and with the sparse arm both on and off; no abort in any of them. Those are real negatives rather than a probe that missed, because EXPLAIN indexes=1 on the same shape shows Search Algorithm: generic exclusion search under Set: __lazy_final_set. Since the failing arm needs no function chain, my next step is to drive the two partition_point predicates directly through MergeTreeSetIndex in src/Interpreters/tests/gtest_merge_tree_set_index.cpp, which already constructs the index with an empty chain and hand-built ranges, instead of trying to provoke them through a query.

You do not need to wait for any of that. I will follow up on the fix task, not in your thread.

@clickgapai

Copy link
Copy Markdown
Contributor

Hi @vdimir — while reviewing this PR I found the following:

Could you review the test PR and add the can be tested label if it looks good?
Happy to discuss — close anything that's wrong or already addressed.

This branch was successfully deployed

1 active deployment
staging - docs — 5e2383dd Deployed Aug 5, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

Performance: native range/interval join algorithm for OUTER JOIN with inequality keys

6 participants