Repository navigation
Gather hash join output columns directly from the stored blocks - #117460
harikrishnan94 merged 22 commits into
Conversation
When a hash join makes its output, it copies the values of the right-side columns one row at a time, and each copy is a call on the stored block's column object. When the right table has many columns, this costs more than the hash lookup itself. Now each output column is prepared once per probe block: we walk its type and write down, for every level of the type, where the raw data of each stored block begins. After that we copy straight from the raw data. To read one value we need two loads, and the second one depends on the first, so the CPU waits. Each copy loop therefore also prefetches the data for the row 32 places ahead of the one it is copying. The waiting of one row then overlaps the work of another. There is one copy loop per kind of type: - fixed-size types: copy the bytes directly, with a special case for the common sizes; - `String`: copy a whole run of rows with one `memcpy`, then fix up the offsets; - `Nullable`, `Array`, `Tuple`, `Variant` and `Map`: go down into the inner column and copy ranges of rows there, instead of one row at a time; - `LowCardinality`, `JSON`, `Dynamic`, `AggregateFunction`, `QBit`, `Nothing` and the empty `Tuple()`: group neighbouring rows into runs, and let the column class copy each run with its own `insertRangeFrom`. Only that class knows how to merge what differs between two stored blocks - a dictionary, a path set, a variant list, an arena. Every loop can copy single rows or whole ranges. Ranges help most for nested types: an `Array(Variant(...))` is copied level by level, a whole range at a time. A row with no match gets a default value, built once per column with `insertDefaultInto` and then written with `memset`. Every column type is handled, and there is no fallback. `resolveGatherNode` handles every column class a stored block can hold, and if it ever meets one it cannot read, it throws `LOGICAL_ERROR`. It never goes back to the per-row path. That is what makes it safe to prepare the plan once and then trust it, and it is what lets the second copy path go away: `direct_gather_ok`, `ColumnsWithRowNumbers`, `fillFromBlocksAndRowNumbers` and `IColumn::fillFromRowRefs` are all removed. `HashJoinDirectGatheredValues` counts the values copied this way. The functional test checks exact numbers against it. Co-Authored-By: Claude Opus 5 <[email protected]>
`05054_hash_join_direct_gather` has one case per type and per output builder. Every case also checks that it really used the new path: it asserts the exact `HashJoinDirectGatheredValues` count for its query. If a case stops reaching the gather, it fails instead of passing quietly. The values are checked against a source that does not share the code under test: a `full_sorting_merge` copy of the same query where that is possible, and a hand-computed count otherwise. The cases that the row store could take over, or that the planner could steer elsewhere, pin `enable_hash_join_row_store` and `enable_analyzer`, because otherwise an estimate outside the test's control decides what the case measures. Types and shapes covered: fixed-size types, including `Enum` and `Interval` defaults; `Nullable`; `String`; `Array`; `Tuple`; `Variant`, including two stored blocks with different local discriminator orders and a `Variant` inside an `Array`; `Map`; `LowCardinality` with three dictionary sizes; `JSON`; `Dynamic`; `AggregateFunction` over several arenas; `QBit`; `Nothing`; the empty `Tuple()`; sparse and const columns; an empty right table; lazily replicated columns; `ASOF`; the non-joined scans of `RIGHT` and `FULL`; `joinGet`; storage `Join`; and each of the four output builders. `tests/performance/hash_join_direct_gather.xml` carries the same shapes for the performance run. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Workflow [PR], commit [ab8b575] Summary: ✅
AI ReviewSummaryThis PR replaces the per-row RHS materialization in Findings❌ Blockers
Final Verdict
LLVM Coverage ReportMeasured on commit ab8b575.
Changed lines: Changed C/C++ lines covered: 869/944 (92.06%) · Uncovered code |
This comment was marked as low quality.
This comment was marked as low quality.
`direct` no longer tells the reader anything. There is one way to copy an output column, so the word contrasts with nothing. It is also misleading twice over: a `Kind::Rows` node does not copy directly, it calls the column class's own `insertRangeFrom`; and in a join context `direct` already means the direct key-value join. So `DirectGatherNode`, `DirectGatherColumn` and `DirectGatherRowRemap` become `GatherNode`, `GatherColumn` and `GatherRowRemap`, and `gatherColumnDirect` becomes `gatherColumn`. The other names in the same header were unprefixed already - `GatherRange`, `GatherRanges`, `resolveGatherNode` - so this makes the file read the same way throughout. The `HashJoinDirectGatheredValues` profile event goes away with the word. Nothing in the server reads it, and there is one copy path per type, so it has nothing left to tell apart. `gatherRawRanges` now picks its copy by width, the way `gatherFixedStride` already does. Its range copy is one call for a whole run, but an unmatched row is written one row at a time, and with the width known only at run time each of those rows was a `memcpy` call - a run of ten thousand unmatched rows cost ten thousand calls to move eight bytes each. With the width known at compile time each row is a single load and store. A run-time width stays a `memcpy` call. `memcpySmallAllowReadWriteOverflow15` is the obvious alternative and it is slower here: measured on `FixedString(40)`, its 16-bytes-at-a-time loop costs 4% to 8% more emit CPU than the call it saves.
The tests move with the code: `05054_hash_join_direct_gather` becomes `05054_hash_join_gather`, and `hash_join_direct_gather.xml` becomes `hash_join_gather.xml`. The block that read `HashJoinDirectGatheredValues` out of `system.query_log` is gone with the event. Every arm still checks its values against a source that shares no code with the kernel under test, and every arm still keeps the row store out of its own outcome, either by pinning the setting or by carrying a `FixedString(40)` payload above the row store's limit. With the block gone the `log_comment` and `ast_fuzzer_runs` settings had nothing left to feed, so they go too, and the test no longer reads `system.query_log` at all. Two comments were wrong. One explained an assertion in terms of `directGatherAdmits`, which exists nowhere. The other called the `Enum8` query in the performance test a control on the grounds that `Enum8` is not gathered - it is, as a fixed-width leaf - so that query is the stride-1 arm and now says so.
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| Object file | Master | PR | Δ |
|---|---|---|---|
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/HashJoin.cpp.o |
4.28 MiB | 4.02 MiB | -260.42 KiB (-5.94%) |
src/CMakeFiles/dbms.dir/Columns/IColumn.cpp.o |
2.16 MiB | 1.97 MiB | -194.19 KiB (-8.77%) |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/gatherJoinOutputColumns.cpp.o |
new | 100.05 KiB | +100.05 KiB |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinAny.cpp.o |
3.48 MiB | 3.39 MiB | -85.78 KiB (-2.41%) |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAny.cpp.o |
3.02 MiB | 3.10 MiB | +76.75 KiB (+2.48%) |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAnyMapsAll.cpp.o |
3.14 MiB | 3.20 MiB | +62.95 KiB (+1.96%) |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAny.cpp.o |
2.65 MiB | 2.71 MiB | +55.29 KiB (+2.04%) |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAsof.cpp.o |
2.84 MiB | 2.81 MiB | -31.10 KiB (-1.07%) |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAsof.cpp.o |
2.84 MiB | 2.81 MiB | -31.10 KiB (-1.07%) |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinAsof.cpp.o |
2.70 MiB | 2.67 MiB | -29.25 KiB (-1.06%) |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinAsof.cpp.o |
2.70 MiB | 2.67 MiB | -29.23 KiB (-1.06%) |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAll.cpp.o |
3.67 MiB | 3.64 MiB | -28.45 KiB (-0.76%) |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAntiMapsSet.cpp.o |
2.47 MiB | 2.44 MiB | -26.95 KiB (-1.07%) |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinSemiMapsSet.cpp.o |
2.35 MiB | 2.32 MiB | -26.64 KiB (-1.11%) |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinRightAny.cpp.o |
3.42 MiB | 3.39 MiB | -25.15 KiB (-0.72%) |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinAll.cpp.o |
3.57 MiB | 3.55 MiB | -24.89 KiB (-0.68%) |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinRightAnyMapsAll.cpp.o |
3.22 MiB | 3.20 MiB | -24.84 KiB (-0.75%) |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinRightAnyMapsAll.cpp.o |
3.12 MiB | 3.10 MiB | -24.16 KiB (-0.76%) |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinAll.cpp.o |
3.38 MiB | 3.35 MiB | -24.15 KiB (-0.70%) |
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinSemiMapsAll.cpp.o |
3.12 MiB | 3.10 MiB | -24.15 KiB (-0.76%) |
717 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.
Compile time of recompiled translation units
2509 translation units recompiled, 13946 s compile time in total, 2507 of them have a recent master baseline.
Four things the review asked for. `RowRefList::ForwardIterator` kept a range's remaining count in a `UInt32` while `rows` reads the same count as 56 bits from `Batch::total_rows`. A run long enough to tell the two apart cannot be built today: iterating a range advances only the ref word's 32-bit row field, so a range that outgrew the field would corrupt `block_no` before the counter wrapped, and a block is already capped below that many rows. The counter is now as wide as `rows`, and `setRange` says the range's own limit out loud instead of borrowing it from the block. Two tests cover it: one walks a range whose count was set past 2^32 and checks the iterator has not run out, the other checks the boundary where the run stops fitting. `StoredColumnsIndex` cached an emit-table entry by column position alone, so a second request for the same position reused whatever type the first one asked for. `resolveGatherNode` catches a differing shape, but two types of the same shape can still want different defaults - `Enum8` and `Int8` - and would have shared one `default_pattern`. I could not reach it: `StorageJoin` refuses a query whose `join_use_nulls` differs from its own, `joinGet` refuses a storage that is not `Left Any`, and asking for a `Tuple` and then one of its subcolumns is correct in either order. The entry now records its type and a second type throws, because rebuilding the entry would invalidate the plane pointers an earlier caller still holds. The shape of the recorded words is a contract between the probe and the emit, and it was held together by a comment. Two `static_assert`s in `processMatch` now tie each whole-key branch to `emits_whole_key_per_word`, and a third pins that flag to `need_replication`, which is the same condition for a reason. Checking the shape per word instead would cost about one instruction per row on a loop that is already limited by how many instructions it can issue. Two comments still pointed at `addRowsForKey`, which is now `processMatch`.
|
All three done.
|
|
📊 Cloud Performance Report ✅ AI verdict: Release-transition baseline: compared against the most recent available 26.9 masters at or before the trusted base-commit anchor because no 26.10 master baseline exists there. no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
`gatherStringRows` copied one row at a time, where the removed `IColumn::fillFromRowRefs` merged a run of consecutive rows of one block into a single `insertRangeFrom`. `ALL` still produces that shape whenever a key's duplicate rows were stored next to each other, so the emit lost a bulk copy there. Pass 1 already reads every word, so it now also answers whether the characters pass has any run to coalesce, for one compare per row. Pass 2 dispatches on that answer. `gatherStringChars<false>` is the original per-row loop, so a scattered selection pays nothing beyond the compare, and `gatherStringChars<true>` defers each copy until its run ends. Measured on aarch64 over eight `String` payload columns against a build side of ten adjacent rows per key: 0.86x wall and 0.83x emit CPU at one thread, 0.95x and 0.98x at 96 threads. A scattered build side stays within 1.02x on both. Two earlier shapes of the same fix charged that scattered case 5% to 8% and were dropped. This also drops the comments in this file that recorded how a decision was measured rather than what it means, and corrects `gatherRowsByRuns`, whose comment claimed runs coalesce across keys. The build side is scattered by hash bucket, so only one key's rows can form a run. Co-Authored-By: Claude Opus 5 <[email protected]>
The comments here had grown into paragraphs that narrate the code beside them, and a few recorded how a decision was measured rather than what it means. Cut them back to what a reader cannot get from the code: the hazards, the invariants, and the reason a non-obvious choice exists. No code changes. Co-Authored-By: Claude Opus 5 <[email protected]>
`setRange` rejects a run that leaves its block with a `LOGICAL_ERROR`, and `Exception::handleErrorCode` turns any `LOGICAL_ERROR` into `abortOnFailedAssertion` whenever `DEBUG_OR_SANITIZER_BUILD` is set. So `EXPECT_THROW` could never catch it in those builds. The unit test binary aborted after 2548 of its 20557 tests in `Unit tests (asan_ubsan)`, `(tsan)` and `(msan)`, and the rest of the suite never ran. The case that a run fitting inside one block is accepted stays an ordinary test. The rejection becomes a death test guarded by `DEBUG_OR_SANITIZER_BUILD`, following `ColumnArrayDeathTest`. A `GTEST_SKIP` would also fix the abort, but CI runs no release unit test job, so it would leave the invariant unchecked everywhere. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117460&sha=9b9fad5a202befd6a914a4af65fbb163b2967db6&name_0=PR Co-Authored-By: Claude Opus 5 <[email protected]>
The flaky check runs one copy of the changed test per core. On the 16 vCPU runners that self-contention puts this test at a median of 172 seconds under ASan, against a 180 second cap, so `Stateless tests (amd_debug, flaky check)`, `(amd_asan_ubsan, flaky check)` and `(amd_binary, flaky check)` reported `Test runs too long`. None of the 250 runs across the six job configurations produced a result diff, and the 32 vCPU runners finish it in 41 to 92 seconds. `clickhouse-test` skips the cap for a test tagged `long`. Only `Fast test` and non-per-test LLVM coverage pass `--no-long`, so every other job still runs it. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117460&sha=9b9fad5a202befd6a914a4af65fbb163b2967db6&name_0=PR Co-Authored-By: Claude Opus 5 <[email protected]>
`emit_gather` is empty for a join that puts no right column in the output, not only for `joinGet` as the assertion in `emitColumnarOutputs` assumed. A `SELECT count()` join still records row refs when `EXPLAIN ANALYZE matches = 1` asks for an exact match count, so it reaches the emit with nothing to append and aborts the server on `!emit_gather.empty()`. `buildOutputFromRowRefLists` was the only one of the three emit builders without the `columns.empty()` guard its two siblings already have. Release builds were unaffected, because `chassert` compiles away there and the loops that follow are bounded by the empty `output_access_indexes`. `Stateless tests (amd_debug, parallel)` caught it through the master test 04759_explain_analyze_join_matched_rows_merge_algorithms, which reaches the row-list builder only when the runner randomizes `join_output_by_rowlist_perkey_rows_threshold` down to zero or one and leaves `joined_block_split_single_row` off. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117460&sha=02a30186ec3ee5dfdd1651dfdcbffb4b32720d0a&name_0=PR Co-Authored-By: Claude Opus 5 <[email protected]>
The three emit builders are selected by settings the test runner randomizes, so a join with an empty output reached the row-list builder only on an unlucky roll. This pins the settings and walks all three. Co-Authored-By: Claude Opus 5 <[email protected]>
…typed-gather Master's key-only join maps and this branch both changed `NotJoinedHash::fillColumns`. Keep master's guard: a key-only map stores no right row, and only RIGHT and FULL joins have non-joined rows, so asking a set map for them is a logical error. Call `fillColumnsFromMap` with the single template argument this branch leaves it with - the `with_columns` dimension is gone from that class, because the ref words already say which outputs come from stored columns.
watch-pr generalizes the three ad-hoc PR watchers that were running on dev into one skill any of the four agents can load. SKILL.md carries the workflow: assignment, the 🕵️ prefix on agent-written GitHub posts, per-PR handoff state, observation, failure attribution, repair, publish, and completion gates. references/clickhouse.md holds the ClickHouse CI specifics. scripts/observe_pr.py is a read-only observer that snapshots GitHub state and records change events so a restarted watcher can replay them. The skill was drafted and independently reviewed in a Codex session on dev (thread "Generalize PR monitoring handoff", 2026-09-07) and smoke tested live against ClickHouse/ClickHouse#117460. One change on top of that draft: the observer's consistency guard now retries a mid-collection PR change up to three times before failing. A busy PR tripped it on the first live read, and in --watch mode that exit would have ended the watcher. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…typed-gather Master added a failpoint and geometric index growth to `StoredColumnsIndex::add`, and this branch rewrote the include block of the same file. Only the includes conflicted. Keep this branch's sorted layout and add master's `#include <Common/FailPoint.h>` to its `Common/` group. Master's `add` comes across unchanged, so its test `05048_hash_join_stored_block_registration_fault` still passes.
…typed-gather Master moved 180 commits and none of them touch this branch's files, so the merge is clean. It also regenerates the private sync branch, whose `arm_tidy` job still builds a test-merge from before master dropped a duplicate include in `MergeTreeIndexConditionText.cpp`.
m-selmi
left a comment
There was a problem hiding this comment.
Nice optimization. Not completely done with the review yet, but I posted some comments for the main parts of the change.
…able - `LazyOutput::buildOutput` emits the columnar columns once from the recorded words in whatever shape they have (flat, lists, ranges), then fills the row store either from pointers resolved once or per column above the rowlist threshold. `buildOutputFromBlocks` and `buildOutputFromRowRefLists` are gone; the threshold now steers only the row store, which is all it ever changed. - `NotJoinedHash` collects ref words only when a columnar column reads them and counts rows separately. - `GatherNode`'s per-block vectors and the replicated remap table use `VectorWithMemoryTracking`, like `StoredColumnsIndex::blocks`, so a huge build fails the query at the memory limit instead of the process. - The replicated remap table is sized on the first `ColumnReplicated` block only. - `gatherStringChars` always coalesces runs of consecutive source rows. The per-row specialization and the pass that chose it were measured at within 1% of each other on scattered input, and runs pay 5-10% on contiguous input, so the split was dead weight. - Comment fix in `fillRowStoreOutputColumns.h`. Review: ClickHouse#117460 Co-Authored-By: Claude Fable 5.1 <[email protected]>
`Nullable` over a fixed-width column went through the flat word expansion and then two passes over the words, one for the null map and one for the values, each with its own lead prefetch. Now one pass reads each word once and writes the null byte and the value together, dispatched on the value width like the fixed kernel. Measured on a 2M-row build with N rows per key and ~100M output rows, emit CPU against the branch before this change: keys stored contiguously 1.06x (N=4), 1.08x (10), 1.09x (30), 1.18x (100), 1.12x (1000); keys stored scattered and fan-out 1 within noise. Against master at 100 contiguous rows per key this goes from 0.83x to 0.98x, at 1000 from 0.78x to 0.85x. Two other attempts at the same gap were measured and dropped: handing the range kernels ranges built from list words, and master's run coalescing inside the fixed kernel's list walk. A `RowRefList` yields a key's refs one `Batch` node at a time, newest first, so a run never exceeds 7 rows, and a `memcpy` per run loses to the per-row copy on every cell. Review: ClickHouse#117460 Co-Authored-By: Claude Fable 5.1 <[email protected]>
…a `String` perf arm - `05054_hash_join_gather.sql`: the only `parallel_hash` arm read `dg_build`, whose 30 payload columns are all fixed width. Two more arms run the same join under `parallel_hash` on the structural fixtures: `dg_ext` (`String`, `Nullable`, `Array`, `Tuple`) and `dg_variant`, each against the existing `hash` arm and `full_sorting_merge` control. - `tests/performance/hash_join_gather.xml`: a tenth query joins eight `String` payload columns, the one variable-width kernel; the other nine cover the fixed strides only. Review: ClickHouse#117460
`IColumn::getPlanes` returns a column's row planes: the shape, the `data` and `aux` bases, the stride and the children. `ColumnNullable`, `ColumnString`, `ColumnArray`, `ColumnTuple`, `ColumnVariant` and `ColumnMap` override it; a fixed-width column gets the default, and so does every column without planes, whose rows only `insertRangeFrom` can copy. `resolveGatherNode` no longer casts the stored column to each concrete class. It switches on the reported shape, checks that the declared type creates the stored column's class, and recurses over the children. The per-class `RowsBinding` list and its includes are gone with it. On the way: one `withStride` dispatcher instead of three stride switch macros, one `planJoinEmit` for the probe and the not-joined scan instead of two copies of the emit-table resolution, and a few comments shortened. Review: ClickHouse#117460
| for (size_t dst_idx = 0; dst_idx < positions.size(); ++dst_idx) | ||
| { | ||
| for (size_t dst_idx = 0; dst_idx < lazy_output.output_access_indexes.size(); ++dst_idx) | ||
| const ColumnAccessIndex access_index = row_store_initialized |
There was a problem hiding this comment.
joinGet can still receive a RowStore access index here. planJoinEmit always copies data.column_access_indexes first, and with_gather = false only skips building emit_gather; it does not force joinGet back onto columnar positions. For a StorageJoin whose saved RHS projection is, say, two UInt64 attributes, initRowStore stores both in the row store and leaves StoredBlock::columns empty. A later joinGet(..., 'a', ...) then reaches buildJoinGetOutput, where the debug assertion at AddedColumns.cpp:220 fires; in release builds the code falls through to getBlockColumnAndRow(block, row_num, access_index.index) and indexes the compacted StoredBlock::columns array with a row-store-local index, so it can return the wrong attribute or read out of bounds.
Please either make joinGet reject RowStore access indexes up front, or teach buildJoinGetOutput to read row-store fields through block_row_stores / field_offset / field_size.
| .begin = row_refs_begin, .end = row_refs_end, .rows = countRefWordRows({row_refs_begin, row_refs_end}, shape), .shape = shape}; | ||
| chassert(selection.rows <= size_to_reserve); | ||
|
|
||
| emitColumnarOutputs(columns, selection); |
There was a problem hiding this comment.
This call is still reached when the RHS output is entirely row-store-backed. initRowStore allows that whenever the saved RHS projection has at least two fixed-width <= 32-byte columns, so a normal hash join on two UInt64 payload columns ends up with has_row_store = true, has_columns = false, a non-empty columns array, and an intentionally empty emit_gather. buildOutput still calls emitColumnarOutputs unconditionally, and the chassert(!emit_gather.empty()) at AddedColumns.cpp:200 then aborts debug/sanitizer builds before the row-store fill runs.
This path needs a !has_columns guard before calling emitColumnarOutputs (or an early return inside emitColumnarOutputs itself).
m-selmi
left a comment
There was a problem hiding this comment.
overall LGTM, just some minor suggestions.
|
For my understanding: Does this PR affect when the row layout should be chosen? |
Good question, it improves the baseline join output emit the row layout is compared to, so the switch point likely changed (the row store weight the effort it takes to restructure the build against the improvement in join output emit). This PR has optimizations the row layout should use too (prefetching, insertRawUninitialized + memcpy, ...). I can adopt them and re-tune when the row layout is enabled in a follow-up. |
`isLazy` named the old choice between recording a match and copying it during the probe. Every strictness records now. The flag only chooses whether the sink takes one word for the whole key, so the name is `appendsWholeKey`. `05054_hash_join_gather` is tagged `long`, so Fast test skips it. The new test joins `UInt64`, `String`, `Nullable(UInt64)` and `Array(UInt64)` and checks the result against `full_sorting_merge`. Co-authored-by: Cursor <[email protected]>
`PartitionedHashJoinProbeImpl.h` still asked `AddedColumnsType` for `isLazy`, a member that no longer exists. Master renamed it to `appendsWholeKey` in `3d313b5e5f6`, which is an ancestor of the #117460 merge `3dc51e394227` - the same merge that supplied the missing gather and fill files this stack needed. So taking that master content fixed one defect and introduced this one, and because the member and its callers live in different files no rebase reported a conflict. The substitution is behaviour-preserving: the old member was `static constexpr bool isLazy() { return true; }` and the new one is `static constexpr bool appendsWholeKey() { return true; }` on the same class, so every one of the three uses evaluates exactly as before. A literal `true` would NOT be equivalent - `HashJoinMethodsImpl.h` defines an unrelated `PreSelectedRows` adapter whose `appendsWholeKey` returns `false` - so the member call is kept. The third use, in an `if constexpr` further down, never appeared in the build output: `-ferror-limit` stopped each translation unit after 19 errors from the first two. Fixing only the reported two would have surfaced it on the next run. The gate for this change is `ninja -C build clickhouse unit_tests_dbms` reaching exit 0 on this tree, where it previously failed with 64 instances of `no member named 'isLazy' in 'DB::AddedColumns'` across the four `PartitionedHashJoinProbe*` objects. That build has not run yet at the time of this commit; the result is recorded in the run report rather than asserted here.
When a hash join makes its output, it copies the values of the right-side columns one row at a time. Each copy is a call on the stored block's column object. When the right table has many columns, this copying costs more than the hash lookup itself.
This pull request changes how the copy is done. Each output column is prepared once per probe block: we walk its type and write down, for every level of the type, where the raw data of each stored block begins. After that we copy straight from the raw data.
To read one value we need two loads, and the second load depends on the first, so the CPU waits. Each copy loop therefore also prefetches the data for the row 32 places ahead of the one it is copying. The waiting time of one row then overlaps the work of another.
There is one copy loop per kind of type:
String: copy a whole run of rows with onememcpy, then fix up the offsets;Nullable,Array,Tuple,VariantandMap: go down into the inner column and copy ranges of rows there, instead of one row at a time;LowCardinality,JSON,Dynamic,AggregateFunction,QBit,Nothingand the emptyTuple(): group neighbouring rows into runs, and let the column class copy each run with its owninsertRangeFrom. Only that class knows how to merge what differs between two stored blocks - a dictionary, a path set, a variant list, an arena.Every loop can copy single rows or whole ranges. Ranges help most for nested types: an
Array(Variant(...))is copied level by level, a whole range at a time.A row with no match gets a default value. We build that default once per column with
insertDefaultInto, then write it withmemset.This replaces #117207
I did not like the shape of that pull request, so this one replaces it instead of continuing it. Two things are different, and both are about substance, not wording.
Every column type is gathered, not only the ones the issue listed. #116833 gave a list -
FixedString,Time,Time64,Interval,IPv4,IPv6,Nullable,String,Variant,Tuple,Array,ColumnReplicated- and leftJSON,Dynamic,Enum8/Enum16,LowCardinality,MapandQBitout, as "not a pointer-table gather". All of them are handled here, and so areAggregateFunction,Nothingand the emptyTuple(). The types with no plain array of values are not read through a pointer table. They get the run-and-insertRangeFromloop above, because only the column class can merge a dictionary, a path set, a variant list or an arena between two blocks.There is no fallback. #116833 asked for a per-column fallback to the old per-row path, and the replaced pull request had one. It is gone. Every column class is read: the ones with a plain layout through their planes, the rest through their own
insertRangeFrom. If the declared type and the stored column disagree,resolveGatherNodethrowsLOGICAL_ERROR. It never goes back to the per-row path.This is what makes it safe to prepare the plan once and then trust it. It is also what a fallback hides: while the fallback existed, the per-row path ran far more often than intended, and nothing reported it. And it is what lets the second copy path go away -
direct_gather_ok,ColumnsWithRowNumbers,fillFromBlocksAndRowNumbersandIColumn::fillFromRowRefsare all removed.The eager path is gone too. Master had two copy paths chosen at compile time:
AddedColumns<true>recorded the matches and copied later, andAddedColumns<false>copied each matched row inside the probe loop, oneinsertFromper row per column.ANYjoins andjoinGetused the eager one. This pull request records for every strictness. One 8-byte word per left row is written, then each column is copied by its kernel with the prefetch lead above. That removes thelazytemplate dimension from every probe instantiation and leaves one copy path.joinGetkeeps its per-rowinsertFrom(it needs thejoinGetOrNullnullable dispatch), so it pays the word array without gaining a kernel; the table below has its cost.One output builder.
LazyOutput::buildOutputemits the columnar columns once from the recorded words and then fills the row store, either from row pointers resolved once or per column abovejoin_output_by_rowlist_perkey_rows_threshold. The threshold now steers only the row store. The columnar kernels read list words directly either way, which they already did before this change.Each column describes its own planes.
IColumn::getPlanesreturns where a column's rows live: the shape, the raw bases, the stride and the child columns.Nullable,String,Array,Tuple,VariantandMapoverride it. The join no longer casts a stored column to each concrete class. It switches on the reported shape, checks that the declared type creates the same column class, and recurses into the children.uBench
One case per column type, on a 96-core Neoverse-V2. The right table has 2,000,000 rows, unique keys, and one payload column. The probe side is a table of 100,000,000 keys made with
rand64(), so the lookups are random.parallel_hash; both external-join limits set to 0; the row store turned off on both sides, so every case measures the column copy path.emit CPU is the CPU time of
SELECT * ... FORMAT Nullminus the CPU time of aSELECT count()over the same join.count()drops the payload column, so the difference leaves out the probe, the hash lookup and the aggregate. Each number is the median of 5 runs.The baseline is
masterat 9f35a2b, built from the same tree.UInt64Decimal64(4)DateTime64(3)Enum8UUIDIPv6FixedString(32)Nullable(UInt64)StringArray(UInt64)Tuple(UInt64, String)Variant(String, UInt64)Array(Variant(String, UInt64))Map(String, UInt64)Tuple()LowCardinality(String), 10 keysLowCardinality(String), 10k keysLowCardinality(String), 1M keysJSONDynamicAggregateFunction(uniqExact, UInt64)QBit(BFloat16, 16)UInt64(wide right table)ColumnReplicated(lazy replication)Nothing gets slower. Two cases show wall time 2% and 1% slower, which is inside the noise. In those the copy is only a small part of the query, so the wall time follows the probe. Their CPU is still 38% and 40% faster.
The two groups of types differ, and that is expected. A type with a plain array of values is 2.2x to 4.0x faster, because a value is now
base + row * strideread from prefetched memory, instead of a call on the column object. The other types still call their owninsertRangeFrom, which cannot be skipped, so they are 9% to 44% faster and no more. They are still worth adding, because that is what leaves one copy path and no fallback.This setup is also the scattered case for those kernels. Unique build keys and a random probe put consecutive output rows on random build rows, so
gatherRowsByRunssees runs of one and pays its one compare per ref.Thread sweep on the same wide case (32 x
UInt64), 3 runs, median. The gain is there with one thread and grows with more threads. The baseline spends 45.9 s of emit CPU at 1 thread and 113.7 s at 96 threads for the same 100M values; the new loops go from 29.0 s to 43.6 s.ANYjoins andjoinGetSame setup as the per-type table: probe 100M random keys, build 2M unique keys, 96 threads, median of 5. For the joins, emit CPU is
SELECT *minuscount()on the same binary.joinGethas no control without the copy, because lookup and copy are one call. Its control is a scan of the probe keys, so read the ratio, not the absolute.ANY LEFT,UInt64ANY LEFT,StringANY LEFT, 32 xUInt64ANY INNER,UInt64ANY INNER,StringjoinGet,UInt64joinGet,StringjoinGetOrNull,StringANY INNERclaims each right key once here, so it emits 2M rows and its emit is below the noise floor.Many rows per key
The case the
join_output_by_rowlist_perkey_rows_thresholdregime is about: build 2M rows with 10, 100 and 1000 rows per key, probe drawn at random and sized so every cell emits ~100M rows. The output is 50x the build and 10x to 1000x the probe. The build is stored two ways: a key's rows next to each other (contig) and shuffled (scatter). Master walks each key's row list once per output column and callsinsertFromper row, coalescing consecutive rows intoinsertRangeFrom. This pull request expands the lists once into 8 bytes per output row (flatWords) and runs the kernels over that.Nullableover a fixed width copies the null byte and the value in one pass.StringStringNullable(UInt64)Nullable(UInt64)UInt64UInt64StringStringNullable(UInt64)Nullable(UInt64)UInt64UInt64StringStringNullable(UInt64)Nullable(UInt64)UInt64UInt64Master keeps one cell:
Nullable(UInt64)at 1000 contiguous rows per key, where this pull request is 17% slower, withString3% slower. ARowRefListyields a key's refs oneBatchnode at a time, newest first, so no run is longer than 7 rows. There, master's one virtual copy per run, serving both planes, is cheaper than per-row copies of both planes. Everywhere else the per-row copies win. Coalescing those runs here was measured and is slower on every cell.The prefetch
This pull request against a build of it that never issues the prefetch. The prefetch distance is set past any row count, so the loops keep their shape and only the prefetch is gone.
One row per key (the per-type setup):
UInt64FixedString(32)Nullable(UInt64)StringArray(UInt64)Variant(String, UInt64)Array(Variant(String, UInt64))UInt64Many rows per key, emit CPU with prefetch vs without:
StringcontiguousStringscatteredNullablecontiguousNullablescatteredUInt64contiguousUInt64scatteredWith the prefetch the copy is 11% to 44% faster wherever the source rows are random. It is up to 12% slower at 1000 contiguous rows per key, where the next row is already in the line being read.
The string run split
gatherStringCharsused to pick one of two loops per batch: run coalescing when a first pass saw two adjacent source rows, per row otherwise. Forced on and forced off against that version, emit CPU:String, unique keys (no runs)FixedString(32)(kernel unaffected, noise floor)Forcing runs on shuffled input is within 2% either way. Turning them off is 5% to 10% slower on contiguous input. So the loop now always coalesces.
Testing
05054_hash_join_gatherhas one case per type and per emit path: the recorded words read as they are, the limit and offset walk, and the not-joined scans. Every case pins the settings that select the path, because the test runner randomizes them. Every case also keeps the row store out of its own outcome. It either pins the setting, or it reads a fixture whose payload is above the row store's 32-byte limit. So the only copy path that can produce its rows is the one under test.The values are checked against a source that does not share the code under test: a
full_sorting_mergecopy of the same query where that is possible, and a hand-computed count otherwise.Types and shapes covered: fixed-size types, including
EnumandIntervaldefaults;Nullable;String;Array;Tuple;Variant, including two stored blocks with different local discriminator orders and aVariantinside anArray;Map;LowCardinalitywith three dictionary sizes;JSON;Dynamic;AggregateFunctionover several arenas;QBit;Nothing; the emptyTuple(); sparse and const columns; an empty right table; lazily replicated columns;ASOF; the non-joined scans ofRIGHTandFULL;joinGet; storageJoin; and each emit path.Closes: #116833
Closes: #117587
Related: #117207
Related: #115254
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
hashandparallel_hashjoins now copy the right-side output columns straight from the raw data of the stored blocks, with a copy loop picked for the column type and with prefetching ahead of the copy, instead of calling the stored column object once per row. This works for every column type, includingString,Array,Tuple,Nullable,Variant,Map,LowCardinality,JSON,Dynamic,AggregateFunctionandQBit.Workflow [PR]
Sync PR [sync-upstream/pr/117460]
Version info
26.10.1.409-master(included in26.10and later)