Repository navigation
Compact, index-based row references for the hash join - #107189
harikrishnan94 merged 34 commits into
Conversation
…on flag
Port the best parts of RadixHashJoin's LeafHT design into the hash join
(`ConcurrentHashJoin` + `HashJoin`) without changing external behavior:
- Replace the pointer-based in-cell `RowRef` (16 B) / `RowRefList` (24 B)
mapped values with an 8-byte `BuildRef` `{block_no, row_no}` for every
map variant (`key8`/`key16`/`key32`/`key64`, `keys128`/`keys256`,
`key_string`, `key_fixed_string`, `hashed`, two-level and range
variants). `block_no` resolves through a per-join `StoredColumnsIndex`
built from `RightTableData::columns` and shared between all slots of a
`ConcurrentHashJoin`, so block numbers stay globally unique and remain
valid after `onBuildPhaseFinish` splices slot block lists. Cell sizes
shrink 1.5-2x, e.g. `key64` ALL cells 32 -> 16 bytes, string ALL cells
48 -> 32 bytes.
- For `MapsAll`, make the mapped value a tagged 8-byte union with the
RadixHashJoin `SINGLETON_FLAG` in the MSB of `block_no`: a unique key
stores the encoded ref inline (zero extra memory and zero extra loads
on probe), and the first duplicate switches the cell to a pointer to an
arena-allocated `BuildRefList::Blob` holding the row count plus the
refs, with `Batch`-chained overflow exactly like the old `RowRefList`
(the iteration order is preserved, so ALL join output order does not
change). The rerange ("sorted") optimization stores consecutive-rows
ranges in the blob via `is_range`.
- `JoinUsedFlags::per_row_flags` is rekeyed from `&columns_info->columns`
to `block_no`; `KnownRowsHolder` dedups by the encoded 64-bit ref word.
`LazyOutput` entries share the cell encoding and are resolved to
`(columns_info, row_num)` at emit time through the index (ASOF join
keeps pointer-based `RowRef` and is not affected).
The `RowRef::SizeT == UInt32` assumptions stay explicit: blocks are
limited to 4G rows (existing check) and the join to 2^31 stored blocks
(`StoredColumnsIndex::add` throws, the MSB is the singleton flag).
Co-authored-by: Cursor <[email protected]>
…e duplicate count into the cell word
The previous commit made ALL-join cells 8 bytes, but duplicate keys paid two
dependent loads per probe hit: cell -> `Blob` (for `rows`) -> `Batch` (for the
refs). On duplicate-heavy joins (100M build x 300M probe, 2 rows/key) this
regressed p50 by up to 14% vs the pointer-based `RowRefList`.
Now a duplicate key owns a single 64-byte arena node, and the probe loop does
not dereference it at all:
- node layout: bit-field header `{is_range:1, size:7, total_rows:56}`, `head`
(the first-inserted ref word), and 6 ref slots; up to 7 rows live in one
pointer-free node;
- the next pointer materializes in `slots[5]` only when the node overflows:
the resident ref is evicted into the new overflow node, and `slots[5]`
always points at the newest overflow node (O(1) insert); overflow nodes
repurpose `head` as the next-older link;
- the cell word packs `min(total_rows, 0x7FFF)` into bits 62..48, so `rows`
is read straight from the cell; the sentinel `0x7FFF` means "load
`total_rows` from the node"; pointers are decoded via `asBatch` masking
with `PTR_MASK`, and node allocation fails loudly (`LOGICAL_ERROR`) if a
pointer ever exceeds 48 bits;
- emission order matches the old `RowRefList` for keys with up to 8 rows and
deviates deterministically above that; the head row (`firstWord`, used by
RightAny semantics and `headRowFlag`) is always the first-inserted row.
Benchmark (same session, 100M x 300M, 16 threads, reps=7, p50 vs the
pointer-based `RowRefList` baseline): all 8 sweep cells improved by 7-21%;
the former worst cell (sel=1.0, 2 rows/key, 1 payload column) went from +14%
to -20.6% (1071 -> 850 ms); build memory: unique keys 8.1 -> 4.1 GiB,
duplicate keys 10.1 -> 6.1 GiB (was 8.1 GiB with the Blob design).
Differential check vs the previous representation (order-independent
fingerprints): identical results for `hash` and `parallel_hash` across Int,
String, FixedString, Nullable, Array, Tuple and Variant keys, INNER/LEFT/
RIGHT/FULL, ANY/SEMI/ANTI, multi-disjunct ON clauses, the rerange path,
StorageJoin, `joinGet` and ASOF.
Co-authored-by: Cursor <[email protected]>
…rehashing When there is no statistics hint to preallocate from, the build phase used to fill the two-level hash maps incrementally, rehashing as the buckets grew. This adds an exact-size build for that case: each slot buffers its scattered right blocks during the build instead of inserting them, and at `onBuildPhaseFinish` the slot's owned buckets are reserved to the exact (now known) row count and the blocks are replayed, so the maps are filled without a single rehash. It is skipped, falling back to the streaming build, when statistics already provide a good size hint (the existing `reserveSpaceInHashMaps` path), when join size limits require incremental enforcement, for `any_take_last_row`, and for single-level maps (`FixedHashMap` is already exact-size). The whole change lives in `ConcurrentHashJoin`; `HashJoin` is untouched. It coexists with a wrapping `SpillingHashJoin`: `getTotalRowCount` and `getTotalByteCount` add the per-slot buffered rows/bytes (a slot's data is in exactly one place at a time - buffered, in the map, or released - so the sum never double-counts), so the spill threshold check still sees the real memory footprint. If the wrapper decides to spill, `releaseSlotBlocks` hands the buffered blocks (materialized to their selected rows only, so rows are not duplicated across slots) straight to `GraceHashJoin` without ever building the in-memory map. Validation: on a server, a cold `parallel_hash` build with statistics disabled fires the deferred reserve (it is the only remaining source of `HashJoinPreallocatedElementsInHashTables`); `hash` and `parallel_hash` produce identical results for INNER/LEFT/RIGHT/FULL on UInt64 and String keys; and a forced spill (`max_bytes_before_external_join=1000000`) switches to `GraceHashJoin` while still producing identical results, exercising the buffered-to-Grace path. Join and `BuildRefList` unit tests pass. Co-authored-by: Cursor <[email protected]>
|
Workflow [PR], commit [bad5fde] Summary: ✅
AI ReviewSummaryThis PR replaces pointer-based hash-join row refs with 8-byte block/row indices and adds a shared column-resolution cache for the lazy Findings
Final VerdictNot ready to merge: the compact row-ref changes themselves look sound, but |
|
CC: @rschu1ze |
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
Ergus
left a comment
There was a problem hiding this comment.
5-level paging is uncommon in production (most cloud VMs and bare-metal servers use 4-level) that's why this won't fail in typical CI or deployments. But it is a real operability issue for anyone who happens to run on an Ice Lake+ server with a 5-level kernel.
Could we also add a functional stateless tests covering at least: parallel_hash duplicate-heavy ALL join, cold-stats build, and a forced-spill case?
Reduces
|
| Query | peak master | peak PR | Δ peak | min master (ms) | min PR (ms) | Δ time |
|---|---|---|---|---|---|---|
| Q02 | 2.08 GiB | 1.25 GiB | −40% | 611 | 617 | +1.0% |
| Q03 | 1.72 GiB | 1.10 GiB | −36% | 1889 | 1744 | −7.7% |
| Q04 | 0.92 GiB | 0.67 GiB | −27% | 1319 | 1264 | −4.2% |
| Q05 | 0.98 GiB | 0.59 GiB | −40% | 2275 | 2202 | −3.2% |
| Q07 | 2.27 GiB | 1.57 GiB | −31% | 1857 | 1795 | −3.3% |
| Q09 | 5.74 GiB | 4.15 GiB | −28% | 4836 | 4529 | −6.3% |
| Q10 | 6.92 GiB | 6.13 GiB | −11% | 2161 | 2099 | −2.9% |
| Q11 | 0.22 GiB | 0.21 GiB | −3.5% | 452 | 465 | +2.9% |
| Q12 | 0.51 GiB | 0.37 GiB | −27% | 1794 | 1739 | −3.1% |
| Q13 | 6.37 GiB | 5.86 GiB | −8.0% | 2868 | 2770 | −3.4% |
| Q14 | 1.01 GiB | 0.63 GiB | −37% | 813 | 784 | −3.6% |
| Q15 | 0.91 GiB | 0.88 GiB | −3.4% | 1496 | 1488 | −0.5% |
| Q16 | 0.77 GiB | 0.64 GiB | −17% | 559 | 548 | −2.0% |
| Q17 | 0.06 GiB | 0.03 GiB | −49% | 1826 | 1819 | −0.4% |
| Q18 | 12.37 GiB | 12.42 GiB | +0.4% | 3518 | 3426 | −2.6% |
| Q19 | 0.06 GiB | 0.06 GiB | ~0% | 1672 | 1627 | −2.7% |
| Q20 | 0.34 GiB | 0.32 GiB | −4.6% | 3988 | 4014 | +0.7% |
| Q21 | 5.73 GiB | 4.10 GiB | −28% | 5308 | 4922 | −7.3% |
| Q22 | 0.32 GiB | 0.26 GiB | −20% | 864 | 565 | −34.6% |
Total min over these 19 join queries: 40.1 s → 38.4 s (~1.04×). Peak memory is lower on 18 of the 19; the largest-footprint query (Q18, 12.4 GiB) is essentially unchanged (+0.4%). The only runtime change above run-to-run noise in the slower direction is Q11 (+2.9%).
…alizing per probe row `KnownRowsHolder::Type` became a plain `UInt64`, so clang-tidy now flags the deliberately uninitialized `array_holder` (`cppcoreguidelines-pro-type-member-init`, `hicpp-member-init`), failing `Build (arm_tidy)` and dropping the rest of CI. The holder is constructed per probe row on the multi-disjunct path and only the first `items` entries are ever read, so keep the no-init semantics and suppress the check instead of value-initializing 128 bytes per row. Failed CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107189&sha=bb1fb365303e08ce902da93d0b237751eebe5fc7&name_0=PR&name_1=Build%20%28arm_tidy%29 PR: ClickHouse#107189
With a deferred (exact-size) build the maps are empty for the whole build phase, so `getTotalByteCount` saw only the buffered block bytes, and both spill checks of `SpillingHashJoin` (the pre-insert `*2` check and the build-finish safety net) were blind to the hash-table memory the replay would allocate: after the in-memory promotion the replay could overshoot `max_bytes_before_external_join` by a multiple of the cap with no spill opportunity left. Add `ConcurrentHashJoin::getProjectedTotalByteCount`: the current footprint plus the projected hash-table buffers for the buffered rows (mirroring `reserveBucketsBySize` and `HashTableGrower::set`) and, for string-key maps, the arena copies of the key bytes tracked at buffering time. Both spill checks use it now; on the non-deferred path nothing is buffered and the value equals `getTotalByteCount` exactly, so the behavior is unchanged.
…Transform` The deferred exact-size build of `parallel_hash` fills the whole hash table inside `onBuildPhaseFinish`, and `prepare` must stay lightweight (it blocks the executor's scheduling, and cancellation cannot be observed inside it), so request one more `Ready` round-trip and call it from `work` instead - for warm and cold runs and for all join types alike, mirroring the existing `hasPostBuildPhase`/`runPostBuildPhase` flow. `isLast` increments a shared counter, so the branch is entered exactly once and the next `prepare` call short-circuits on `build_phase_finished`.
The deferred replay inserts with `check_limits=false`, which early-returns before `keys_to_join` is maintained and before `shrinkStoredBlocksToFit`: `avgPerKeyRows` then saw zero keys and silently flipped the `output_by_row_list` emit heuristic to the per-row path, and the memory-pressure shrink never engaged for deferred builds. Compensate per slot after the replay (as `GraceHashJoin` does with `getAndSetRightTableKeys` after its own `check_limits=false` inserts), before the bucket merge sums the per-slot key counts into slot 0. Also capture the memory baseline of `shrinkStoredBlocksToFit` when the first block is buffered instead of at replay time, so the shrink heuristic sees the buffered bytes in its query-memory delta, as the streaming build does.
…t pointer packing Review follow-ups: `StoredColumnsIndex::at` now asserts that the entry was not cleared by `clearEntry`, so a stale ref trips a `chassert` in debug builds (and dereferences nullptr deterministically in release builds) instead of reading freed memory; the comments now say so precisely instead of the vague "fails loudly". The `BuildRefList` pointer-packing comment now documents why 48 bits are safe today (even with 5-level paging / `CONFIG_X86_5LEVEL` or arm64 52-bit LVA, Linux returns mappings above the 47-bit boundary only for explicit mmap address hints, which our allocators never pass) and the contingency if that ever changes: shrink the count field from 15 to 7 bits (saturation at 127 instead of 32767), which keeps pointers 56-bit-safe and does not limit rows per key - it only lowers the load-free `rows()` fast-path threshold from 32766 to 126 rows per key.
`04327_parallel_hash_deferred_build` compares `hash` and `parallel_hash` result fingerprints on duplicate-heavy (including more than 8 duplicates per key) and unique keys, `UInt64` and `String`, for `ALL INNER/LEFT/RIGHT/FULL` and `ANY` joins with statistics collection disabled, which forces the deferred exact-size build - including the non-joined output paths that exercise the block-number-keyed used flags. `04328_parallel_hash_deferred_build_spill` runs the same shapes with a small `max_bytes_before_external_join`, so the spill threshold is crossed while the right blocks are still buffered, validating the handoff of the buffered blocks to `GraceHashJoin` (`releaseSlotBlocks`) without loss or duplication. Both tests assert via `system.query_log` that the intended path actually executed (the exact-size reserve and the switch to grace join respectively).
…g commits The declaration and the call sites went into "Project the deferred build size in `SpillingHashJoin` spill checks", but the hunk with the method body was left out of the staged set. No functional change relative to the intended state of that commit.
`max_rows_in_join` / `max_bytes_in_join` no longer disable the deferred exact-size `parallel_hash` build: the deferred branch of `ConcurrentHashJoin::addBlockToJoin` now ends with the same global `SizeLimits::check` as the streaming build, with `getTotalRowCount` exact during buffering and `getProjectedTotalByteCount` standing in for the bytes of the not-yet-built maps, so `join_overflow_mode = 'throw'` fires before the replay allocates them and `'break'` stops the build at the same point as the streaming path. The replay keeps inserting with `check_limits = false`: the limits were already enforced at buffering time. This matters because common configurations set benign limits: the CI stateless profile (`tests/config/users.d/limits.yaml`) sets both settings to 10G, which silently kept every CI query on the streaming build and would have done the same on production setups with any join limit configured. The new test `04335_parallel_hash_deferred_build_size_limits` asserts that the deferred build engages under benign limits (the CI profile shape) with results identical to `hash`, that `throw` raises `SET_SIZE_LIMIT_EXCEEDED` for row and byte limits the build side cannot satisfy, and that `break` succeeds. Co-Authored-By: Claude Fable 5 <[email protected]>
A second identical insert into the `ANY`-join build side produces whole blocks in which every key already exists, so nothing is inserted, the stored block is dropped and its `StoredColumnsIndex` entry is cleared; no ref may ever resolve to it. The case runs under both `hash` and `parallel_hash` (including the deferred replay), with the ASan CI runs covering the no-stale-access guarantee. Co-Authored-By: Claude Fable 5 <[email protected]>
With size limits no longer disabling the deferral, every cold `parallel_hash` build preallocates, and the cold-run assertions of `02151_hash_table_sizes_stats_joins` / `..._reordered` (`HashJoinPreallocatedElementsInHashTables = 0` before statistics are cached) started failing. Report the deferred exact-size reserve under the new `HashJoinDeferredPreallocatedElementsInHashTables` event instead: `HashJoinPreallocatedElementsInHashTables` keeps its pre-PR meaning (statistics-driven preallocation only), so the statistics-cache behaviour stays observable in isolation and the 02151 tests and `03319_concurrent_hash_join_double_preallocation_bug` keep working unchanged. The positive controls of `04327_parallel_hash_deferred_build` and `04335_parallel_hash_deferred_build_size_limits` now read the new event; their reference output is unchanged. Co-Authored-By: Claude Fable 5 <[email protected]>
Address the review comments from ClickHouse#107189 (review): - Replace the "singleton" term with "inline" everywhere: `SINGLETON_FLAG` -> `INLINE_FLAG`, `SINGLETON_WORD_FLAG` -> `ENCODED_INLINE_FLAG`, `isSingleton` -> `isInline`, and the corresponding comment mentions. - Rename `RowRef::word` to `encode` and document its purpose: it packs the ref into the single `UInt64` stored in hash map cells and `LazyOutput` entries, with explicit shifts so the bit layout is byte-order-independent. - Rewrite the `RowRef` doc comment without the "word layout" and "count-tagged" jargon; state that `row_no` and `block_no` take 4 bytes each and define an inline ref (always for `ANY` joins; for `ALL`-join keys without duplicates), deferring the `RowRefList` bit layout to that struct's own doc. - Fix the contradictory "bit 63 clear, non-zero" wording in the `RowRefList` doc and reword "count-tagged" as pointer+count packing where it appeared. - Turn the `chassert`s in the `RowRef` constructor into a real all-builds range check that throws `LOGICAL_ERROR` via the new out-of-line `throwRowRefOutOfRange` (the reviewer's snippet had the condition inverted). - Explain why the non-const `RowRefList::asBatch` overload cannot be const (would collide with the const overload and leak mutable access). - Remove the fwd-declaration comment for `StoredBlock` and drop "compact" from the `Inserter` comment in HashJoinMethods.h and the `StoredBlock` doc. - Make test 04402 self-documenting: a high-level black-box header comment (no C++ class names, explains why the `Join` engine is required), `SELECT`-header lines so the reference file associates results with queries, and per-query comments stating the expected results in plain language. Co-Authored-By: Claude Fable 5 <[email protected]>
Expression-level cleanups only; no behavior change: - `RowRefList::setRange` subsumes the single-row case (stores the inline ref, no node), collapsing the branch and temporary at its rerange call site. Covered by a new assertion block in the `RangeRepresentation` gtest. - Add `RowRefList::fromWord` and a sentinel `end`, drop the pure-forwarding `RowRefsRange` wrapper (`refsOf` now returns `RowRefList` by value), and replace the copy-pasted two-step "default-construct then assign `word`" reconstructions and manual `ForwardIterator` loops with `fromWord` / range-for over `refsOf` (`IColumn.cpp`, `AddedColumns.cpp`, `JoinUsedFlags.h`, `KnownRowsHolder.h`). - Delete `Batch::assertIsRange` (its production caller was replaced by an inline chassert during the rewrite; the gtest asserts the fields directly) and the vestigial `RowRef::SizeT` alias (the one remaining consumer now spells `decltype(RowRef::row_no)`). - Fold the single-caller `appendFromBlockImpl` back into `AddedColumns<false>::appendFromBlock`. - Delete the dead `constexpr` pair of `setUsed` calls in the ASOF branch of `processMatch` (both were compile-time no-ops kept alive by a fabricated `block_no` argument). - Drop the transitional `ScatteredColumns` alias: `NullMapHolder` uses `StoredBlock`, `ScatteredColumnsList` becomes `StoredBlocksList`. - Move `StoredBlock::allocatedBytes` next to the struct's other definitions in `RowRefs.cpp`; hoist the duplicated `blocksData` fetch above the `constexpr` split in `NotJoinedHash::fillColumns`; deduplicate the replicated/range emit logic in `fillColumnFromRowRefs` into one `emit_range` lambda. Co-Authored-By: Claude Fable 5 <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 666/762 (87.40%) · Uncovered code |
|
Hi @harikrishnan94 @Ergus @rschu1ze — while reviewing this PR I found the following:
Could you review the test PR and add the |
Reconcile the in-memory hash-join compression feature with master, which since this branch diverged has (1) merged #107189 ("compact hash join row refs"), replacing the `ColumnsInfo`/`ScatteredColumns` substrate with the inlined `StoredBlock` + `StoredColumnsIndex` emit-table model, and (2) bumped `DBMS_QUERY_PLAN_SERIALIZATION_VERSION` to 2 for the bucketed `ReadFromMergeTree` plan encoding, colliding with this branch's own version-2 bump. Conflict resolutions: * Plan-serialization version: master owns version 2 (bucketed read), so the join-compression settings move to version 3. `DBMS_QUERY_PLAN_SERIALIZATION_VERSION` is now 3; `QueryPlanSerializationSettings::writeChangedBinary` omits the three compression setting names for any receiver below version 3 (previously below 2); `SerializationFlags` keeps master's `version` field plus this branch's `serializeForReceiver`; the gtests and `docs/.../NativeProtocol.md` are updated to the version-3 boundary (and the spec now documents version 2 as the bucketed read). * HashJoin decompression path ported onto the `StoredBlock` substrate: the decompressed-columns cache, `getDecompressedColumns`, and the `DecompressResolver` / `NonJoinedDecompressResolver` are re-keyed from `const ColumnsInfo *` to `const StoredBlock *` (the decompressed view is a fresh `StoredBlock` over the decompressed columns, with `replicated_columns` rebuilt). Compressed joins are routed exclusively through the cold `buildOutputFromBlocks*` / `getBlockColumnAndRow` paths (which decompress each block on demand via the resolver); the new `fillFromRowRefs` emit-table fast path is skipped when `have_compressed` is set, and `resolveEmitColumns` is not built in that case, since pre-resolved raw pointers into `ColumnCompressed` columns would be unreadable. This preserves the feature's original behaviour (it always used the cold decompression path; the emit table is new from #107189) while keeping the fast path intact for non-compressed joins.
The `463f7814646` merge/port left the decompression-cache declarations in `HashJoin.h` on the pre-#107189 `ColumnsInfo` type while the definitions in `HashJoin.cpp` and the callers in `AddedColumns` were already re-keyed to `StoredBlock`. That made `HashJoin` ill-formed (`unknown type name 'ColumnsInfo'`), which cascaded into every `make_shared<HashJoin>()` -> `shared_ptr<IJoin>` conversion (`PlannerJoins.cpp`, `ConcurrentHashJoin.h`) and broke the fast_test / arm_tidy builds. Re-key `DecompressedColumnsWeightFunction::operator()`, `DecompressedColumnsCache`, `DecompressedColumnsPtr`, and `getDecompressedColumns` from `ColumnsInfo` to `StoredBlock` so the header matches the already-ported `.cpp`. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107667&sha=463f781464651f7bf1c4c6a903f638c22cc6feb9&name_0=PR&name_1=Fast%20test Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…alizing per probe row `KnownRowsHolder::Type` became a plain `UInt64`, so clang-tidy now flags the deliberately uninitialized `array_holder` (`cppcoreguidelines-pro-type-member-init`, `hicpp-member-init`), failing `Build (arm_tidy)` and dropping the rest of CI. The holder is constructed per probe row on the multi-disjunct path and only the first `items` entries are ever read, so keep the no-init semantics and suppress the check instead of value-initializing 128 bytes per row. Failed CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107189&sha=bb1fb365303e08ce902da93d0b237751eebe5fc7&name_0=PR&name_1=Build%20%28arm_tidy%29 PR: ClickHouse#107189
Splits the exact-size `parallel_hash` build out of PR ClickHouse#107189 into its own pull request. After this commit the branch contains only the compact index-based row references (changes 1 and 2); its tree is identical to the standalone cell-representation branch `hash-join-compact-row-refs`. The exact-size deferred build now lives on `parallel-hash-exact-size-deferred-build`. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address the review comments from ClickHouse#107189 (review): - Replace the "singleton" term with "inline" everywhere: `SINGLETON_FLAG` -> `INLINE_FLAG`, `SINGLETON_WORD_FLAG` -> `ENCODED_INLINE_FLAG`, `isSingleton` -> `isInline`, and the corresponding comment mentions. - Rename `RowRef::word` to `encode` and document its purpose: it packs the ref into the single `UInt64` stored in hash map cells and `LazyOutput` entries, with explicit shifts so the bit layout is byte-order-independent. - Rewrite the `RowRef` doc comment without the "word layout" and "count-tagged" jargon; state that `row_no` and `block_no` take 4 bytes each and define an inline ref (always for `ANY` joins; for `ALL`-join keys without duplicates), deferring the `RowRefList` bit layout to that struct's own doc. - Fix the contradictory "bit 63 clear, non-zero" wording in the `RowRefList` doc and reword "count-tagged" as pointer+count packing where it appeared. - Turn the `chassert`s in the `RowRef` constructor into a real all-builds range check that throws `LOGICAL_ERROR` via the new out-of-line `throwRowRefOutOfRange` (the reviewer's snippet had the condition inverted). - Explain why the non-const `RowRefList::asBatch` overload cannot be const (would collide with the const overload and leak mutable access). - Remove the fwd-declaration comment for `StoredBlock` and drop "compact" from the `Inserter` comment in HashJoinMethods.h and the `StoredBlock` doc. - Make test 04402 self-documenting: a high-level black-box header comment (no C++ class names, explains why the `Join` engine is required), `SELECT`-header lines so the reference file associates results with queries, and per-query comments stating the expected results in plain language. Co-Authored-By: Claude Fable 5 <[email protected]>
…-join-row-refs Compact, index-based row references for the hash join
Since ClickHouse#107189 the hash join emits consecutive same-block rows of a key with one `insertRangeFrom` instead of one `insertFrom` per row. `RowRefList` keeps a key's rows in nodes of up to 6 refs, so these runs are 2-6 rows long. When the source block's dictionary differs from the output column's, `ColumnLowCardinality::insertRangeFrom` builds about five temporary columns per call whatever the length (`cut`, `mapUniqueIndex`, `index` of the used keys, `uniqueInsertRangeFrom`, `index` of the positions), so such a run costs ~25x per row what `insertFrom` costs. ClickHouse#115961 avoids it only when the right side has a single shared dictionary; several parts, `FINAL` or a `LowCardinality` value computed per block still hit it on every run. Ranges of at most 32 rows from a different dictionary are now translated row by row with the per-key rules of `uniqueInsertRangeImpl`: the source NULL maps to the destination NULL, a key that compares equal to the default (so `-0.0` too) maps to the default slot, anything else goes through `uniqueInsertFrom`, which canonicalizes NaN. Positions are computed before the indexes change and the range is bounds-checked first, so a throw leaves the rows untouched, as on the range path. The threshold is the largest power of two at which the per-row path is not slower than the range path in a microbenchmark of ns per call (RelWithDebInfo, one core, median of 7): range/per-row at 32 rows is 1.99x for 7 short keys, 2.52x for 10000 random keys, 1.48x for two 200-byte keys and 3.61x for 1000 UInt64 keys; at 64 the 200-byte case drops to 0.87x. A/B, RelWithDebInfo, n = 10 interleaved, medians (26.6.8.7 / parent / this): issue repro 4 with `compatibility = '23.8'` 2.31 / 8.93 / 2.30 s; repro 1 with the table in 4 parts 1.33 / 5.12 / 0.79 s, at default settings 1.00 / 4.40 / 0.50 s; a table-free `hash` join 0.18 / 0.75 / 0.15 s. Shared-dictionary and `String` controls unchanged. Repro 4 at default settings does not reach this path (the join sides are swapped and the time is in the row-store emit). The gtest compares a short range against a 600-row range of the same rows for every length 1-256; it fails when the default fold, the bounds check or the NULL branch is removed. Closes: ClickHouse#123874 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolves: #107188
Compact the right-hand-side (build-side) representation of the hash join to reduce memory and speed joins up.
This pull request covers the cell representation only. The exact-size
parallel_hashbuild (the "no rehash on cold builds" change) that was previously bundled here has been split into its sibling pull request #108129; the two are independent and can be merged in either order.Motivation
Each hash-map cell for the right (build) side stored a pointer-based
RowRef={const ColumnsInfo * (8 bytes), UInt32 row_num}, and forALLjoins additionally embedded aRowRefListhead (arowscount plus aBatch * next). Consequences:ALL-join cells were large — e.g. 32 bytes forkey64, 48 bytes for string keys — so fewer keys fit per cache line and every probe touches more memory than necessary.The change covers every
HashJoin::MapsTemplatevariant (key8/16/32/64,keys128/256,key_string/key_fixed_string, and the hashed/serialized fallback for Array/Tuple/Map/Variant keys) and every join kind/strictness.What changed
Compact 8-byte index-based row refs (replaces the pointer-based
RowRef) for all map variants. A cell holds{UInt32 block_no, UInt32 row_no}(8 bytes);block_nois resolved to the stored block's columns through a per-join index (StoredColumnsIndex) built during the build phase. A per-key singleton flag (the MSB ofblock_no) stores a unique key's ref inline — zero extra memory and zero extra loads on probe — and only the first duplicate switches the cell to an out-of-line list. This makesALL-join cells as small asANY-join cells for every key type (the largest win is for the string and serialized maps, whose cells were the fattest). Key storage is untouched (string keys stay arena-copied with saved hash; serialized keys stay 128-bit hashes).Single 64-byte list node with a count-tagged cell word. A duplicate key's rows live in one 64-byte arena node (an eviction-based design that avoids a second indirection), and the cell word packs the duplicate count into its high bits so the probe loop reads the per-key row count straight from the cell — no dereference — in the common case.
The former
ScatteredColumns(aColumnsInfo+ selector) becomesStoredBlock(columns + replicated handles + selector +block_no); the sharedStoredColumnsIndexresolvesRowRef::block_noto columns at emit time and is shared across allConcurrentHashJoinslots so block numbers stay globally unique. This change also fixes aForwardIteratorpointer-arithmetic undefined-behaviour on the row-ref iteration path.Limits and user-facing behaviour
Query results are unchanged; these are the only observable differences:
ALLjoins). For anALLjoin on a key with more than 8 matching build rows, the order of those rows inside one left row's output can differ from before. Join output order is not guaranteed withoutORDER BY; counts and values are identical.LOGICAL_ERRORif exceeded, both far beyond practical sizes): the right side of a single join may hold at most 2^31 − 1 stored blocks (the index uses 31 bits; the pre-existing limit of 2^32 − 1 rows per block is unchanged), and arena node pointers must fit in 48 bits (true on Linux x86-64 / aarch64).Benchmark
The numbers below were measured on the combined PR #107189 (
r6a.8xlarge,RelWithDebInfo, both binaries26.6.1.1,parallel_hash). The peak-memory / cell-size reductions and the warm-build probe-path time wins shown here are produced by this compact-cell change — they reproduce whenever a hash-table size hint is available (every run after the first, the default), so the exact-size build (the sibling PR) is not engaged. The cold-build "no rehash" first-run speedups and the cold duplicate-heavy over-reservation finding are attributed to the sibling PR and are not claimed here.Synthetic grid (216 queries crossing key type {
uint64,str12,str32}, strictness {INNER ALL,ANY INNER,ANY LEFT}, build multiplicity {1:1, 1:4, 2:8}, selectivity and output width). Median per class (time% / peak%), with statistics on (the warm/default case this change covers):String
ALLjoins (the targeted win): median time −14.4%, median peak −20.7%.ANYjoins (must-not-regress): 0 regressions. No query became slower across the grid.TPC-H SF=100 cross-check (
parallel_hash,max_threads = 16). The headline metric is the minimum over 7 reps — a warm run, where the per-query-shape hash-table size statistics are already cached (collect_hash_table_stats_during_joins, on by default), so the exact-size build is not engaged and these deltas isolate the compact-cell effect: across the 19 join queries peak memory drops on 18 (e.g. Q17 −49%, Q05/Q02 −40%, Q14 −37%, Q07 −31%, Q03 −36%, Q21 −28%, Q09 −28%), and the probe-bound queries keep clear time wins (drift-controlled interleaved A/B, user-CPU tracking wall time): Q22 −37% time / −41% user-CPU, Q03 −8.5%, Q21 −8.1%, Q09 −4.8%. Reproduced on ARM (Graviton3,r7g.8xlarge): median peak −25%, 0 real time regressions, memory deltas matching x86 almost exactly.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Reduced memory usage and improved the performance of
JOINs. The right-hand side of a hash join now uses a compact 8-byte index-based row reference, so the hash-table entries ofALLjoins are as small as those ofANYjoins for every key type. Benchmarked on largeparallel_hashjoin queries —INNERandANYjoins of 100–300 million row tables onUInt64andStringkeys, with both unique and duplicated keys: the median query became about 12% faster and used about 15% less peak memory, with no query becoming slower.INNERjoins onUInt64keys gained the most (median about 21% faster with 38% less memory).Documentation entry for user-facing changes
Version info
26.7.1.480(included in26.7and later)