Repository navigation
Support IEJoin for joins ON two inequality comparisons - #109920
Conversation
|
Workflow [PR], commit [5e2383d] Summary: ✅
AI ReviewSummaryThis PR adds an Findings
💡 Nits
Final VerdictChanges requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 851/933 (91.21%) · Uncovered code |
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]>
- 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]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
|
Your PR was poisoned by the test |
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]>
|
@groeneai do you have a repro for this stress test failure? https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109920&sha=5e2383dda199922d58d0d82e93f761234c53f0b9&name_0=PR |
|
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, Why it is not your diff. The identical signature, frame for frame (all 13 of The trigger, if you want to chase it. Your own run's artifacts were overwritten by the re-run — all three of SELECT count() FROM t_04493_plain FINAL
WHERE flag AND (value != 7)
SETTINGS move_all_conditions_to_prewhere = 0;from 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 |
|
@groeneai how we can address this issue then? |
|
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. For the bug: it is mine to fix, and I owe you a correction on the pointer I gave you. I suggested starting from What I now think the actual shape is. The in-source TODO at One more thing worth recording: that TODO says to remove the 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 You do not need to wait for any of that. I will follow up on the fix task, not in your thread. |
|
Hi @vdimir — while reviewing this PR I found the following:
Could you review the test PR and add the |
Resolves #109127
Adds the sort-based IEJoin algorithm for joins whose
ONsection has two inequality comparisons (<,<=,>,>=) between expressions of the joined tables.Before this change, an
INNER JOINwith only inequality conditions was executed as aCROSS JOINwith 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_jointo thejoin_algorithmsetting:Supported kinds are
ALL INNER/LEFT/RIGHT/FULL JOINandSEMI/ANTILEFT/RIGHT JOIN. The position ofie_joinin the list sets its priority: listed after other algorithms, it is used only when they do not apply (theONsection has no equality conditions); listed first, it takes any join with two inequality conditions, and forALL INNER JOINthe remaining conditions of theONsection (including equalities) are applied as a filter over the join result. The join appears as anIEJoinstep inEXPLAIN.Interactive demo demonstrating how algorithm works (as of 1d8501c): iejoin_demo.html
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added the sort-based IEJoin algorithm for joins whose
ONsection has twoinequality comparisons (
<,<=,>,>=) between the joined tables,enabled by adding
ie_jointo thejoin_algorithmsetting. Supported kindsare
ALL INNER/LEFT/RIGHT/FULL JOINandSEMI/ANTILEFT/RIGHT JOIN.Previously such queries were executed as a
CROSS JOINwith a filter(
INNERonly), which is much slower on large tables.Version info
26.8.1.909(included in26.8and later)