Skip to content

Hash join: split probe and build, column scatter kernels and AMAC ring - #130344

Draft
harikrishnan94 wants to merge 10 commits into
ClickHouse:masterfrom
harikrishnan94:half-radix-join-stack
Draft

harikrishnan94 wants to merge 10 commits into
ClickHouse:masterfrom
harikrishnan94:half-radix-join-stack

Conversation

@harikrishnan94

@harikrishnan94 harikrishnan94 commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Related: #120513

This PR holds three changes to the hash join, one on top of the other.

1  probe and build  two steps each instead of one loop per key type: key search and match step, emplace and store
2  column scatter   pieces of exact size, typed kernels, and one count of the rows of each piece per block
3  AMAC ring        a second key search that keeps 32 lookups in flight, for a table larger than the L2 cache

1. Split probe and build. A hash join ran one loop per key type and join kind, and that loop handled the match of a row as soon as it found the key. Now two steps run on each batch of left rows:

findKeys      looks up the key of every row in one disjunct and writes one match word per row, 0 if there is no key
              depends on the key type and the map; sets no used flag and picks no ASOF row
add matches   does what the join kind does with the words: the filter, the replication offsets, the row refs,
              the used flags, the claims of the ANY joins and the ASOF row
              depends on the join kind
fused loop    both steps in one loop, for INNER ANY, the ANTI joins, the joins on a set map, the RIGHT and FULL
              joins other than ALL, and every probe that records no row refs, such as count(); two steps are slower there

JoinProbe::JoinRightColumns runs the steps on one block through function pointers that selectFunctions picks for each block. With one disjunct and no additional filter, it runs them on search batches of at most 4096 rows. The match words of a search batch then stay in the L2 cache until the match step reads them.

The build insert also ran one loop per key type and map, and every join kind compiled it again. Now HashJoinTable::insertTyped runs once per block: it builds the key getter, routes the rows over the slots and picks the functions of the key type. The insert of a slot then runs two steps:

emplace       emplaces the key of every row (`PrefetchingEmplace`, with the prefetch of the old loop)
              depends on the key type and the map
store         stores the row in its cell right after the emplace of its key, before the next emplace, because a later
              insert into the bucket can move cells
              depends only on the kind of map

The routing and the slots share one key getter, so parallel_hash packs the keys of a HashMethodKeysFixed getter once, not twice.

Speed is on par with master, and slightly better. Over 222 join queries on ARM and on x86, the median query takes 0.95 of its time without this change. The queries have one, several or mixed ON disjuncts, 1 or 16 threads, 1e5 or 1e7 right rows, and UInt64 or String keys. A few shapes are slower, by up to 7%: ASOF INNER with unique keys on x86 and ARM, OR LEFT with unique keys on x86, and two ON disjuncts that match no row on a large table with dense keys (2 to 4%).

2. Column scatter. IColumn::scatter created each piece with cloneEmpty and inserted the rows one by one with insertFrom. A caller that split a block counted the rows of each piece again for every column. Now scatter counts once and passes the counts on, and scatterColumns and scatterBlock replace the loops of ten callers. ColumnsScatter sizes every array of every piece to exactly what its rows need, then copies the rows with one typed loop per kind of column. A SmallSelector holds 16-bit piece ids, for at most 65536 pieces.

Speed is slightly better. ColumnsScatter can also stage fixed-width rows in cache lines before it stores them. This write combining is optional: a caller asks for it, and only x86 takes it. IColumn::scatter does not ask.

3. AMAC ring. The key search of point 1 looks up the keys of a block one row after another and, for most key types, prefetches the home cell of a later row. When a lookup walks past its home cell, it still waits for every cell it reads. AmacLookup is a second key search, after AMAC (asynchronous memory access chaining). It keeps 32 lookups in flight and visits them in turn. A visit reads one cell of a lookup and prefetches the cell that the lookup reads at its next visit, so the cache misses of the 32 lookups overlap. A lookup walks the cells of one bucket of a TwoLevelHashTable, with or without the Robin Hood mode.

when          the buckets of the table are all in the Robin Hood mode or none is, the cells take at least as many bytes
              as the L2 cache, the batch has at least 256 rows, and enable_software_prefetch_in_join is on
prepare step  builds the keys of a batch before the ring searches it, for keys32 to keys256, key_packed_string and
              hashed, so the ring loads a key and builds none
flag prefetch in a block that the ring takes, a join with a used flag per key prefetches the flag of the key 16 rows
              ahead when it adds the matches

The ring finds the keys out of order, but it writes the match word of each row in that row's place, so the match step does not change. A fused join runs in two steps for a block that the ring takes. The key search of point 1 stays for key8 and key16, for a table after the fixed-map conversion, for LowCardinality keys and for Join engine tables. It also stays for a key search that stops at the row limit, because the limit counts the rows in order.

Speed is better on the tables that the ring takes. Over 76 join queries, each at 1, 16, 32, 64 and 96 threads, a query takes 0.83 of its time without this change on ARM and 0.80 on x86 (geometric mean). The queries are INNER, LEFT, RIGHT, FULL, ANY INNER, ANY LEFT, ANY RIGHT, LEFT SEMI and LEFT ANTI joins with UInt64 keys, two UInt64 keys, String keys, or a String with a UInt64. The right tables have 1e6 or 1.2e7 keys. Two UInt64 keys gain the most: 0.81 on ARM and 0.75 on x86. No query is slower on ARM. On x86, ANY INNER and ANY RIGHT with 1.2e7 right keys are slower at 64 and 96 threads, by up to 6%, with UInt64 keys and with a String and a UInt64.

For a user:

  1. Query results do not change.
  2. There is no new setting or profile event.
  3. No array of a scattered piece is larger than before, and a piece with one row no longer holds a 4 KiB block.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

@harikrishnan94 harikrishnan94 added the can be tested Allows running workflows for external contributors label Nov 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6e3037a]

Summary: ⏳

job_name test_name status info comment
Stateless tests (arm_binary, parallel) FAIL
05334_row_store_bulk_fixed_columns FAIL cidb

AI Review

Summary

Reviewed PR head 6e3037ade8d996d71a9c792c52eef1024264992f. The PR separates hash join lookup and match processing, adds typed column scatter kernels and AMAC lookups, and replaces ordinary hash join insertion with a deferred, partitioned build. Two existing findings remain: the new build strategy has no experimental rollout gate, and its grouped execution lacks focused regression coverage. No new inline findings were identified.

PR Metadata

The reported query speedups warrant Performance Improvement instead of Not for changelog. The current category requires no entry; the replacement requires one. Suggested replacement:

### Changelog category (leave one):
- Performance Improvement

### Changelog entry:
Accelerate hash joins with batched key lookups, overlapping hash table memory accesses, and more efficient column scattering.
Findings

❌ Blockers

  • src/Interpreters/HashJoin/HashJoin.cpp:518: Ordinary hash joins unconditionally use the new deferred build. The parallel path changes partition sizing, ownership rounds, and memory admission through the new Grouped policy. Neither hash_join_layout = 'serial' nor disabling software prefetch restores the established build strategy. Introduce an experimental setting, disabled by default, with the established path available for rollout and rollback; alternatively, separate the build strategy from this refactor. The existing thread remains unresolved.

⚠️ Majors

  • src/Interpreters/HashJoin/HashJoinBuild.cpp:789: No focused test proves that a Grouped fit executes multiple owner rounds while preserving previously inserted keys and retained payload blocks. The probe tests disable spilling, and existing spilling tests can pass through GraceHashJoin without reaching this branch. Add the focused coverage described below. The existing thread remains unresolved.

💡 Nits

  • PR description: use the performance changelog category and specific entry proposed above.
Tests
  • ⚠️ Add a small stateless test that forces a Grouped fit, verifies HashJoinBuildRounds > 1 and no switch to an external join, and compares counts and right-side payload checksums with a serial baseline. Include duplicate keys followed by new keys, plus an early build followed by additional input.
  • ⚠️ The current CI report is green, but it does not establish that branch coverage. No local tests were run because this review job has no ClickHouse binary and prohibits nested CI runs.
Final Verdict

Status: ❌ Block

Gate or separate the new build strategy and add focused coverage for grouped and subsequent owner rounds.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Nov 9, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Nov 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6e3037ade with master 515c1baee (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 812.64 MiB 805.46 MiB -7.17 MiB (-0.88%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

680 object files changed (-1.29 MiB total), 24 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageJoin.cpp.o 1.93 MiB 3.17 MiB +1.24 MiB (+64.15%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FindKeysMapsAll.cpp.o new 1.15 MiB +1.15 MiB
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAny.cpp.o 2.64 MiB 1.65 MiB -1019.45 KiB (-37.68%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InnerHashJoinAll.cpp.o 2.85 MiB 1.89 MiB -981.42 KiB (-33.61%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAll.cpp.o 2.87 MiB 1.98 MiB -913.31 KiB (-31.06%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FindKeysAmacMapsAll.cpp.o new 873.12 KiB +873.12 KiB
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FindKeysAmacMapsOne.cpp.o new 862.86 KiB +862.86 KiB
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/HashJoinPartitionedBuildMapsAsof.cpp.o new 842.38 KiB +842.38 KiB
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinRightAnyMapsAll.cpp.o 2.68 MiB 1.87 MiB -831.12 KiB (-30.29%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAnyMapsAll.cpp.o 2.68 MiB 1.87 MiB -829.75 KiB (-30.26%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FindKeysAmacMapsSet.cpp.o new 821.95 KiB +821.95 KiB
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinAll.cpp.o 2.91 MiB 2.11 MiB -817.12 KiB (-27.40%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/HashJoinPartitionedBuildMapsOne.cpp.o new 783.88 KiB +783.88 KiB
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/HashJoinPartitionedBuildMapsAll.cpp.o new 781.92 KiB +781.92 KiB
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/FullHashJoinAll.cpp.o 2.94 MiB 2.20 MiB -758.98 KiB (-25.19%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinAny.cpp.o 2.87 MiB 2.15 MiB -741.10 KiB (-25.20%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/RightHashJoinSemi.cpp.o 2.87 MiB 2.15 MiB -741.10 KiB (-25.20%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAntiMapsAll.cpp.o 2.41 MiB 1.71 MiB -717.31 KiB (-29.05%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/InsertKeysMapsAsof.cpp.o new 697.03 KiB +697.03 KiB
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/HashJoinPartitionedBuildMapsSet.cpp.o new 692.11 KiB +692.11 KiB

716 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

2938 translation units recompiled, 12803 s compile time in total, 2914 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×0.93 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -1278.9 s (-9%) in total before that adjustment.

Translation unit Master PR Δ vs median
src/Interpreters/HashJoin/FullHashJoinAny.cpp 16.8 s 10.2 s -5.4 s (-35%)

Translation units without a recent master baseline:

  • src/Interpreters/HashJoin/FindKeysAmacMapsOne.cpp: 8.5 s
  • src/Interpreters/HashJoin/FindKeysAmacMapsAll.cpp: 8.5 s
  • src/Interpreters/HashJoin/FindKeysAmacMapsSet.cpp: 8.3 s
  • src/Interpreters/HashJoin/HashJoinPartitionedBuildMapsAsof.cpp: 7.8 s
  • src/Interpreters/HashJoin/FindKeysMapsAll.cpp: 7.8 s
  • src/Interpreters/HashJoin/HashJoinPartitionedBuildMapsAll.cpp: 7.6 s
  • src/Interpreters/HashJoin/HashJoinPartitionedBuildMapsOne.cpp: 7.5 s
  • src/Interpreters/HashJoin/HashJoinPartitionedBuildMapsSet.cpp: 7.2 s
  • src/Interpreters/HashJoin/InsertKeysMapsAsof.cpp: 6.7 s
  • src/Interpreters/HashJoin/InsertKeysMapsOne.cpp: 6.6 s
  • src/Interpreters/HashJoin/FindKeysMapsOne.cpp: 6.5 s
  • src/Interpreters/HashJoin/InsertKeysMapsAll.cpp: 6.5 s
  • src/Interpreters/HashJoin/HashJoinPartitionedBuild.cpp: 6.5 s
  • src/Interpreters/HashJoin/FindKeysMapsSet.cpp: 6.4 s
  • src/Interpreters/HashJoin/InsertKeysMapsSet.cpp: 6.3 s
  • src/Interpreters/HashJoin/HashJoinBuild.cpp: 6.0 s
  • src/Interpreters/HashJoin/PrepareKeysMapsOne.cpp: 5.4 s
  • src/Interpreters/HashJoin/PrepareKeysMapsSet.cpp: 5.3 s
  • src/Interpreters/HashJoin/PrepareKeysMapsAll.cpp: 5.3 s
Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)2, (DB::JoinStrictness)1, DB::HashJoin::MapsTemplat… 229.45 KiB removed -229.45 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)0, (DB::JoinStrictness)2, DB::HashJoin::MapsTemplat… 229.18 KiB removed -229.18 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)1, (DB::JoinStrictness)6, DB::HashJoin::MapsTemplat… 224.48 KiB removed -224.48 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)0, (DB::JoinStrictness)1, DB::HashJoin::MapsTemplat… 218.02 KiB removed -218.02 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)1, (DB::JoinStrictness)5, DB::HashJoin::MapsTemplat… 217.85 KiB removed -217.85 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)2, (DB::JoinStrictness)6, DB::HashJoin::MapsTemplat… 205.53 KiB removed -205.53 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)0, (DB::JoinStrictness)2, DB::HashJoin::MapsTemplat… 167.22 KiB removed -167.22 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)1, (DB::JoinStrictness)6, DB::HashJoin::MapsTemplat… 165.89 KiB removed -165.89 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)1, (DB::JoinStrictness)6, DB::HashJoin::MapsTemplat… 165.19 KiB removed -165.19 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)2, (DB::JoinStrictness)4, DB::HashJoin::MapsTemplat… 164.15 KiB removed -164.15 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)0, (DB::JoinStrictness)4, DB::HashJoin::MapsTemplat… 164.15 KiB removed -164.15 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)0, (DB::JoinStrictness)1, DB::HashJoin::MapsTemplat… 162.47 KiB removed -162.47 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)0, (DB::JoinStrictness)5, DB::HashJoin::MapsTemplat… 162.47 KiB removed -162.47 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)1, (DB::JoinStrictness)5, DB::HashJoin::MapsTemplat… 162.47 KiB removed -162.47 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)1, (DB::JoinStrictness)5, DB::HashJoin::MapsTemplat… 158.67 KiB removed -158.67 KiB (-100.00%)
programs/clickhouse unsigned long DB::HashJoinMethods<(DB::JoinKind)0, (DB::JoinStrictness)6, DB::HashJoin::MapsTemplat… 142.53 KiB removed -142.53 KiB (-100.00%)
programs/clickhouse COW<DB::IColumn>::immutable_ptr<DB::IColumn> DB::buildAdditionalFilter<DB::AddedColumns, DB::detail… 71.88 KiB removed -71.88 KiB (-100.00%)

Job report

@harikrishnan94
harikrishnan94 force-pushed the half-radix-join-stack branch 8 times, most recently from b3d2126 to d057dbb Compare November 13, 2026 09:20
@harikrishnan94
harikrishnan94 force-pushed the half-radix-join-stack branch 6 times, most recently from e80110b to 148c24d Compare November 18, 2026 05:00
@harikrishnan94 harikrishnan94 added ignore-unresolved-threads Do not limit CI and block merge on unresolved review threads ci-force-all Do not skip any jobs when running labels Nov 18, 2026
@harikrishnan94
harikrishnan94 force-pushed the half-radix-join-stack branch 2 times, most recently from d9c1c31 to 88a9afb Compare November 18, 2026 11:58
@harikrishnan94 harikrishnan94 changed the title Hash join: one table per ON disjunct, split probe and column scatter kernels Hash join: split probe and build, column scatter kernels and AMAC ring Nov 18, 2026
harikrishnan94 and others added 2 commits November 24, 2026 16:03
… kinds

The probe of a hash join ran one loop per key type and join kind. The loop looked up a row and handled its match at
once, for one ON disjunct, for several, and for a mixed ON expression. So each join kind had a copy for each of the 34
key types, and a change to the lookup had to touch every join kind.

A lookup method now finds the keys. It visits the rows of a search and calls a functor for each row with what it found.
It knows no join kind, so another lookup method can replace it without touching the join kinds. `LookupMethod.h` has the
`LookupMethod` concept, the arguments of a key search, and `keyGetterOf`, which gives the key getter of a search.
`FindKeys.h` has the only lookup method, `PrefetchingLookup`. It is the probe loop of `HashJoinTable::probe` in the
parent commit.

With one disjunct and no additional filter, `findKeysAndAddMatches` is one pass. The lookup method finds the key of a
row, and `MatchAdder` adds the output of the row at once: the filter, the replication offsets, the row refs, the used
flags, the claims of the ANY joins, and the ASOF row. The pass is compiled per key type and match handling, not per join
kind. `MatchHandling` holds what the pass reads: the map, the used flag action, what a match adds, whether a row without
a match adds a default row or is kept, whether left rows are replicated, and whether the join always has a filter.
`MatchRules` derives it from `JoinFeatures`. Join kinds with the same handling share one pass per key type: INNER
RightAny and LEFT SEMI, RIGHT ANY and RIGHT SEMI, LEFT ANY and LEFT RightAny. A join that does not always have a filter
reads the filter flag of the block at run time.

The pass searches a block in search batches of at most `max_search_batch_rows` (4096) rows, of about equal size: 65409
rows are 15 search batches of 4089 rows and one of 4074. One `MatchAdder` adds the matches of the whole block, so the
filter, the replication offsets and the row refs come out as with one search of the block. Search batches bound the rows
that a lookup method and a key getter prepare in one call.

With several disjuncts or a mixed ON expression, the probe runs two steps per batch of left rows. `JoinProbe::findKeys`
looks up the key of every row in one disjunct and writes one match word per row: the cell word of the key, or 0 if there
is none. It depends only on the key type and the map, and sets no used flag. The match step then does what the join kind
does with the words, and it has no key type. With several disjuncts, `addMatchesOfDisjuncts` replaces `processMatch`. It
reaches the used flags of the right rows through the match words. A join that stops at its first matching disjunct looks
up a later disjunct only for the rows that no earlier one matched. With a mixed ON expression,
`addMatchesWithAdditionalFilter` collects the pairs that match on the keys and runs the filter on them, as before.

On these two paths the row limit `max_joined_block_size_rows` applies. The first batch has at most as many rows as the
limit, and each later batch doubles, up to `max_disjunct_batch_rows` (8192) rows, or up to the whole block for a mixed
ON expression. With a mixed ON expression, and for a join that replicates left rows, the key search of the first
disjunct stops once the right rows it found reach the limit. So a block that the limit splits into several calls looks
up few rows it does not use. The probe always finishes at least one row of a non-empty block, so the check of
`joinBlockImpl` for a result of 0 is removed.

Some key getters hold state for the rows of a block: `HashMethodKeysFixed` can pack the keys of all the rows into a
buffer, a getter that builds the keys of many rows at once (`PreparedJoinKeys`) fills its buffers, and the
`LowCardinality` getter fills its lookup cache per dictionary index. The probe searches a block once for each disjunct
of each batch or search batch, and the row limit can cut it into several calls of `joinBlockImpl`. So each left block
has a state, `JoinProbe::LeftBlockState`, which `HashJoin::ContinuationResult` keeps for all the calls of the block. It
holds what the probe of the block keeps or works in, apart from the block and the output. For each disjunct that is the
key columns, the kept key getter (`keptKeyGetter`) and the skip bytes (`skipBytesOf`). For the block it is the work
buffers of a batch: the match words, the key offsets, the unmatched rows, the pairs of an additional filter and the
right rows that a disjunct added. The contents of a work buffer do not outlive a batch; only its capacity lasts across
the calls, and each call poisons the buffers for MemorySanitizer. So a call that resumes a block does not pack the keys
of the whole block, convert its constant and `LowCardinality` key columns, merge its null maps, convert its ON mask or
allocate its work buffers again. The call that finishes the block frees the state before the output of the block is
built. `AddedColumns` no longer copies the key columns; it gets only the ASOF key column. The walk of `addFoundRowAll`
for a join with a used flag per row is in `addFoundRowAllWithFlagPerRow`, out of line as `addFoundRowAll` was.

A `PreparedJoinKeys` getter builds the keys of a search in chunks of 256 rows. A search that is likely to stop at the
row limit starts with chunks of 8 rows that double, so that it builds few keys it does not read. `prepareRange` picked
the small chunks for every range that starts after the first row of a block. In the parent commit, such a range was
always the rest of a block that the limit cut. Here, most search batches and batches also start after the first row. So
the lookup method now asks for the small chunks only for a search that can stop at the limit and starts after the first
row of the block. The key search of a later disjunct prepares a list of rows once per batch, so `skipUnlisted` sets the
skip bytes only from the first listed row: a fill from row 0 each time is quadratic in the block size.

`JoinProbe::JoinRightColumns` runs the probe of one block through function pointers, which `selectFunctions` picks for
each block. The pass, the match steps and `selectFunctions` are in `JoinRightColumnsImpl.h`. Only
`HashJoinMethodsImpl.h` includes it, so only the files of the join kinds compile it. `HashJoinTable::probe`,
`HashJoinTable::probeAll`, `detail::probeAllRows`, `processMatch`, `MultiMapLookupSampler`, the `setUsed` and
`setUsedOnce` overloads that take a find result, `JoinUsedFlags::headRowFlag` and `getUsed`, the per-key branches of
`JoinUsedFlags::setUsed` and `setUsedOnce` (the flag of a key is set with `setUsedAt` and `setUsedOnceAt`),
`JoinOnKeyColumns::isRowFiltered` and `JoinFeatures::emits_whole_key_per_word` lost their last callers and are removed.
Against the parent commit, the `.text` of the server binary is 11.3 MiB (3.4%) smaller on ARM and 14.0 MiB (3.6%)
smaller on x86.

The benchmark compares with the parent commit on ARM (Neoverse-V2) and x86 (Xeon 8488C), 96 cores each, at 1, 16 and 64
threads. It runs 158 joins on Memory tables with 1 thousand to 100 million right keys, unique and duplicate, at 1 %, 50
% and 100 % of left rows matched. They cover INNER, LEFT, RIGHT, ANY, SEMI, ANTI and ASOF joins, joins with two
disjuncts and joins with a mixed ON expression. The median time against the parent commit is 0.94 on x86 and 0.92 on ARM
for one disjunct, and 0.92 and 0.90 for the other two paths.

The stateless test `05622_hash_join_probe_search_batches` runs 21 joins on left blocks of 1000, 4095, 4096, 4097, 12288
and 20001 rows, and on blocks of 4097 rows with a row limit of 61. It expects one result per join. The joins cover ALL,
ANY, SEMI and ASOF joins, ALL joins on unique keys that run as `RightAny`, several key types, conditions in ON, and two
disjuncts, also with two key columns each.

The stateless test `05837_hash_join_probe_resume_state` runs 18 joins without a row limit and on left blocks that the
limit cuts into many calls, and expects one result per join. They cover packed fixed-width, `hashed`, packed `String`,
`String`, `LowCardinality` and constant keys, `Nullable` keys and conditions, RIGHT and FULL joins, two disjuncts, and a
grace hash join. It also drops a result in the middle of a block, and throws in a call that resumes a block. The
performance test `hash_join_split_output` runs LEFT joins with a condition in ON, at the default row limit and at a
limit of 8192, and INNER joins with two disjuncts, for seven key types, on left blocks that the limit cuts into several
calls.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
…p per map

The build insert of a hash join ran one loop per key type and map. The loop emplaced the key of a row and stored the row in
the cell at once, through `Inserter`. The loop and the insert around it were in `HashJoinTable.h`, and every join kind
compiled them again through `HashJoinMethods::insertFromBlockImpl`.

Now `JoinBuild::insertKeys<Maps, row_list, Emplace>` inserts a run of rows into a map. An emplace method emplaces the key
of every row, and a lambda stores each row. The lambda depends only on the kind of map: `MapsOne`, `MapsAll`,
`MapsAsof` or a set map. The emplace method calls the store right after each emplace, before the next one.
Saving the cells of a batch of keys and storing their rows later would be wrong: a later insert into the bucket can move
cells, by a shift in the Robin Hood mode of the two-level maps or by a growth. Another emplace method only needs to follow
the `EmplaceMethod` concept in `EmplaceMethod.h`. `insertKeys` takes the map and the key getter as typed arguments, so it
can insert into any map with the cells of the join maps.

`PrefetchingEmplace` is the loop that was `insertSlotRows`, with the same software prefetch. The store does what
`Inserter` did. It writes `BuildResult` only for a key that is already in the map. With `MapsOne`, `is_inserted` comes
from the count of new keys after the loop. The loop keeps every field it reads in a local, so the stores do not make it
reload them.

`HashJoinTable::insertTyped` routes the rows over the slots and inserts each slot under its lock, as before. Its
definition moved to `InsertKeys.h`, and `insert<Maps>` is compiled once per map, in `InsertKeysMaps*.cpp`, instead of in
the file of every join kind. `HashJoin::addBlockToJoin` calls it directly, and `insertFromBlockImpl` is removed.
`PreparedJoinKeys::prepareRows` lost its last caller and is removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
harikrishnan94 and others added 4 commits November 24, 2026 20:22
…ucket

`TwoLevelHashTable::computeBucketPrefix` now also fills `bucket_cells`. An entry has, for one bucket, the first cell, one
past the last cell, the mask that gives the home cell of a hash, and the bucket's entry of `bucket_cells_prefix`. It is 32
bytes and aligned to 32, so it lies in one cache line. A lookup that walks the cells itself reads this entry. Otherwise it
would read the buffer pointer and the grower of the bucket, which are in two cache lines.

`computeBucketPrefix` also sets `robin_hood_buckets`: whether no bucket, every bucket, or only some of the buckets are in
the Robin Hood mode. A bucket switches to that mode once it has held more than 32768 keys, and a lookup in such a bucket
may stop before it reaches an empty cell. So a lookup that walks the cells itself has to know the mode.

Both are valid until the next insert, like `bucket_cells_prefix`. No other member moves, and no existing function reads
the new ones. A table that never calls `computeBucketPrefix`, such as one of an aggregation, keeps an empty vector. The
table object keeps its size, because the new members fit in the padding at its end: the maps of the join and of the
aggregation stay at 32896 bytes with 256 buckets, and at 256 bytes with one bucket.

Co-authored-by: Cursor <[email protected]>
…larger than the L2 and the L3 cache

The probe looks up the keys of a block one row after another, and prefetches the home cell of a later row. A lookup that
has to walk past the home cell still waits for each cell that it reads. A join with a used flag per key also waits for
the flag of each found key, which is a cache miss of its own in a table larger than the cache.

AMAC (asynchronous memory access chaining) keeps 32 lookups in flight. A visit does one step of one lookup that depends
on memory, and prefetches the address that the next visit of that lookup reads, so the misses of the lookups overlap.
`AmacRing.h` is the driver, `amacRun`, taken from the partitioned hash join branch (`pbnp-join`, commit 6c9909e).
`AmacLookup.h` is a second lookup method of the probe (`LookupMethod.h`). Its policy, `AmacFindPolicy`, is based on
`SharedAmacFindPolicy` of that branch (commit a32920e), and walks the cells of one bucket of a `TwoLevelHashTable`,
whose bounds it reads from `bucket_cells`. It has three forms, chosen at compile time: a map of one bucket, whose bounds
it keeps in its frame; a map of 256 buckets, with the bucket of each lookup in one byte of the ring; and a map of 256
buckets that are all in the Robin Hood mode, where a lookup also keeps the distance it has walked and stops by the rule
of `HashTable::findCellRobinHood`.

The ring takes three kinds of key search:

- The searches of a join with several disjuncts, and of the later disjuncts of a join with a mixed ON expression. Each
  row writes its own match word, so the lookups may finish out of order.
- The pass of a join with one disjunct and no additional filter, which adds the output of a row as soon as its key is
  found, in row order. A finished lookup waits in a reorder window of 128 rows until every earlier row has retired, and
  `amacRun` starts no row while the window is full.
- The same pass for a join with a used flag per key (INNER ANY, the RIGHT and FULL joins, RIGHT ANTI). The window also
  keeps the key offset of each row. A lookup that finds its key prefetches the key's flag, and the row retires only
  after 16 more lookups have finished, so that the flag has time to arrive.

A search that stops at the row limit keeps `PrefetchingLookup`. For a key type whose key is built from the key columns
(`keys32` to `keys256`, `key_packed_string` and `hashed`), a prepare step (`PrepareKeys.h`) builds the keys of the rows
as an array before the ring searches them. A prepared getter hashes 8 strings at a time there, and the ring loads a key
and calls nothing.

`HashJoinTable::freezeForProbing` decides whether the ring may take a table: the buckets are all in the Robin Hood mode
or none is, and the cells take at least as many bytes as the L2 and the L3 cache together. `JoinRightColumns` then gives
a search to the ring if it has at least 256 rows and `enable_software_prefetch_in_join` is on. There is no new setting.
A table that fits in the L2 and the L3 leaves the ring few misses to overlap. On Graviton4 (2 MiB of L2, 36 MiB of L3,
16 threads), with the L2 alone as the gate, the ring was up to 14% slower than `PrefetchingLookup` for a table of one
bucket with 2 to 32 MiB of cells (up to 18% at one thread), and up to 4% slower for a table of 256 buckets below 16 MiB.
The performance test `lazy_materialization_join` showed it in CI on two right tables of 50 thousand keys: 11.7% slower
on x86. With the gate at the L2 and the L3, that query is 6% faster than `master` on Graviton4, as without the ring,
and the ring still makes a table of 256 buckets with 1.6 to 3.2 million keys 7-9% faster.

The L3 size comes from the new `getCPUDataCacheSize`, which returns the size of the data cache at one level, or 0 when
it cannot read it. It reads the size from CPUID on x86_64, otherwise from sysfs on Linux and from `sysctl` on Darwin.
`getL2CacheSize` now calls it and returns the same value as before on every platform.

The ring does not take these tables, which keep `PrefetchingLookup`: `key8`, `key16` and a table converted to a
direct-addressed map, which have no collision chain; the LowCardinality key types, whose getter caches lookups per
dictionary index; a table of 256 buckets of which only some are in the Robin Hood mode, which happens only at about 8.2
to 8.6 million distinct keys; and the table of a `Join` engine table, which is never frozen. The build does not use the
ring. An insert could move the cells of a bucket, so a `chassert` in `HashJoinTable::insert` checks that no insert comes
after `freezeForProbing` for a table that the ring may take.

Measured on the probe split at `1c96b1c483d4` against `master` `4564d472d8b`, on AArch64 (Neoverse-V2, 96 cores), with
`parallel_hash` and spilling off, the whole query at 16 and 64 threads (below 1: faster). These tables are above the
gate:

    INNER ANY, 100 million keys, all rows matched    0.70  0.82
    INNER ANY, 30 million keys, all rows matched     0.68  0.81
    INNER ANY, 30 million keys, 1% of rows matched   1.01  0.99
    RIGHT ALL, 30 million keys, all rows matched     0.79  0.88
    INNER ALL, 30 million keys, all rows matched     0.88  0.90
    LEFT ANTI, 100 million keys, all rows matched    0.98  0.99

The probe split alone gives 0.88 to 1.02 on the same joins.

Tests: `AmacRing.EveryRowCompletesOnce` and `AmacRing.InOrderRetiresEveryRowInOrder` run `amacRun` with policies that
have no memory to wait for; the second one fills the reorder window with a few long walks and checks that every row
retires once, in row order. The gtest of `AmacLookup` compares the ring with `PrefetchingLookup` on one frozen table, for
every key type and map that the ring supports, in the searches of a range and of a row list, out of order and in row
order, with and without flags: the words, the order of the rows, and the key offsets of the found keys. It covers the
Robin Hood mode with integer, string and packed string keys, walks that wrap at the end of a bucket, runs of NULL keys
longer than the ring, blocks of only zero keys, and the key types that the prepare step builds. The stateless tests
`05617_hash_join_amac_lookup` and `05621_hash_join_amac_lookup_built_keys` run the join kinds with
`enable_software_prefetch_in_join` on and off, in both layouts, and expect one result per join. Their joins on 10
million keys reach the ring. Two of those in `05617_hash_join_amac_lookup`, INNER ANY and RIGHT SEMI, have a used flag.

Co-authored-by: Cursor <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
`IColumn::scatter` splits a column into pieces by a selector, which holds one piece id per row. Columns that build their
pieces themselves counted the rows of each piece first, to reserve or size the pieces. To split a block, a caller called
`scatter` once per column, so a block of K columns counted the same selector K times. Other columns split each of their
nested columns with `scatter`, so they counted once per nested column: the elements of a `Tuple`, the indexes of a
`LowCardinality`, the nested `Array` of a `Map`, the paths and shared data of an `Object`, the captures of a `Function`,
the `Variant` inside a `Dynamic`, and the discriminators of a `Variant`.

`scatter` is no longer virtual. It counts once and passes the counts to the new protected virtual `doScatter`. The new
`scatterWithCounts` takes counts that the caller already has and returns one piece per count. In every build it throws
`LOGICAL_ERROR` when the counts do not sum to the selector size. Debug and sanitizer builds also count the selector
again and compare.

The columns listed above pass the counts on to each nested column that the same selector splits. The variants of a
`Variant` have their own selectors and still count them. Overrides that compare the selector size with the column size
keep that check and its error code.

Ten callers split a block or several columns by one selector, each with its own copy of the same loop: `Aggregator`,
`JoinCommon::scatterBlockByHash` (used by `GraceHashJoin`), `DistributedSink::splitBlock`,
`MergeTreeDataWriter::splitBlockIntoParts`, `MergingAggregatedTransform`, `ScatterByPartitionTransform`,
`HashedDictionaryParallelLoader`, `PartitionedSink`, the Delta Lake sink and Iceberg's `ChunkPartitioner`. The new
`scatterColumns` and `scatterBlock` in `ColumnsCommon.h` replace these loops. They count once and split every column
with the counts. `scatterColumns` also returns the number of rows in each piece.

Three callers do not fit these helpers. The Variant and Dynamic adaptors split every argument except the `Variant` or
`Dynamic` one, and `arrayFold` keeps the pieces of each column together. These three count once themselves and call
`scatterWithCounts`.

The new `IColumn::SmallSelector` holds 16-bit piece ids. It takes 2 bytes per row instead of 8 and allows at most 65536
pieces. `scatter`, `scatterWithCounts`, `scatterColumns`, `scatterBlock` and `countColumnsSizeInSelector` accept it, and
every column type implements `doScatter` for both selector types. With a `SmallSelector`, `countColumnsSizeInSelector`
throws `LOGICAL_ERROR` for more than 65536 pieces, and so do `scatter`, `scatterColumns` and `scatterBlock`, which call
it. `scatterWithCounts` checks the piece count only in debug and sanitizer builds, when it counts again.

A caller uses a `SmallSelector` when it has a bound of at most 65536 on the number of pieces, and keeps 64-bit ids
otherwise. `GraceHashJoin` uses it when `grace_hash_join_max_buckets` is at most 65536, and decides once, in the
constructor. `DistributedSink::splitBlock` uses it when the cluster has at most 65536 shards.
`ScatterByPartitionTransform` uses it for at most 65536 outputs, with 16-bit output from `mapToRange`.
`MergingAggregatedTransform` uses it for at most 65536 grouping sets.

`MergeTreeDataWriter::splitBlockIntoParts` uses it when `throw_on_max_partitions_per_insert_block` is on and
`max_partitions_per_insert_block` is between 1 and 65536. `buildScatterSelector` then throws `TOO_MANY_PARTS` before it
writes an id of `max_partitions_per_insert_block` or more. The `out_selector` of `splitBlockIntoParts` is a
`std::variant` of both selector types, and `MergeTreeSink` and `ReplicatedMergeTreeSink` pass it on to
`DeduplicationInfo::filterToPartition`.

Four callers have a fixed bound and always use it: `Aggregator` (256 buckets), `HashedDictionaryParallelLoader` (at most
128 shards), the Variant adaptor (at most 256 pieces) and the accumulator split of `arrayFold` (2 pieces).
`PartitionedSink`, the Delta Lake sink, the Dynamic adaptor and the array split of `arrayFold` have no bound and keep
64-bit ids.

`mapToRange`, `createBlockSelector`, `StorageDistributed::createSelector` and the `Block` overload of
`JoinCommon::scatterBlockByHash` take the id type as a template parameter. `buildScatterSelector` and
`DeduplicationInfo::filterToPartition` accept either selector type. With 16-bit ids and more than 65536 partitions,
`buildScatterSelector` leaves the selector empty but still lists every partition. Iceberg's `ChunkPartitioner` uses
16-bit ids when `iceberg_insert_max_partitions` is at most 65536, and checks its limit after it builds the selector. So
its "Too many partitions per insert operation" error reports the same partition count as before.

Every piece has the same rows and the same reserved size as before, and every existing error keeps its code.

The random mode of `ScatterByPartitionTransform` (`createRandom`) fills the 64-bit alternative of its selector.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`IColumn::scatter` and `scatterWithCounts` default to `IColumnHelper::doScatter`. It created each piece with
`cloneEmpty`, reserved it when it got more than one row, and inserted the rows one by one with `insertFrom`. For a row
of a `Nullable` or an `Array`, `insertFrom` called the nested column through the virtual `IColumn` interface. `reserve`
sizes fixed-width values and offsets exactly, but the chars of a `String`, the null map of a `Nullable` and the elements
of an `Array` grow by powers of two. A piece with one row was not reserved, so each array that `insertFrom` filled with
`push_back` started with a 4 KiB block.

`ColumnsScatter` scatters a column in two steps, with the rows per piece that the caller has counted. First it sizes
every array of every piece to exactly what its rows need. For a `String` or an `Array`, it walks the selector once more
to add up the bytes and the elements of each piece.

Then one loop per kind of column copies each row to its piece, through a write cursor per piece. Fixed-width values have
loops for widths of 1, 2, 4, 8, 16 and 32 bytes. Other widths copy with overlapping moves that write nothing past the
row. A `Nullable` scatters its null map and its nested column the same way. A `Tuple` inside an `Array` or a `Nullable`
scatters each of its elements the same way.

A `String` row copies its chars and appends its offset, rebased on the piece. An `Array` row copies its whole element
range. These copies of chars and element ranges may read and write up to 15 bytes past their end. The extra bytes fall
into the padding, or into bytes that the next row of the piece overwrites.

`ColumnsScatter::hasKernel` accepts the columns for which the kernels give the same pieces as the `insertFrom` loop. It
accepts `ColumnVector`, `ColumnDecimal`, `FixedString` and `String`. It accepts `Nullable(X)` and `Array(X)` when it
accepts X, and a `Tuple` inside them when it accepts every element of the `Tuple`. It rejects `Const`, `Sparse` and
`Replicated` at any depth, and every other column. `IColumnHelper::doScatter` now calls the kernels when `hasKernel`
holds, and keeps the `insertFrom` loop otherwise, for both `UInt16` and `UInt64` piece ids. `Tuple`, `Map`,
`LowCardinality`, `Variant`, `Dynamic`, `Object` and `Function` scatter their nested columns, such as the elements of a
`Tuple` or the indexes of a `LowCardinality`. These nested columns reach the kernels the same way.

Every piece has the same rows, the same type and the same representation as before. Only allocated sizes change: no
array of a piece is larger than before, and a piece with one row no longer holds 4 KiB blocks. A piece with no rows
holds what `cloneEmpty` gives it, as before.

A second overload of `ColumnsScatter::scatter` takes several sources of one type, such as one column of several blocks.
It scatters them into one set of pieces, with counts from `countRowsPerPiece`, and each piece holds its rows in source
order. With one source, it returns what `scatterWithCounts` returns. When all sources are `Const` with the same value,
compared byte for byte, the pieces are `Const`.

Otherwise it removes the wrappers with `convertToFullIfWrapped`, splits a `Tuple` into its elements, and splits a `Map`
into its nested `Array`. For a column that `hasKernel` accepts, one call of the kernels writes the rows of all sources.
It scatters any other column source by source and joins the parts with `insertRangeFrom`. The caller passes sources of
one type. It throws `LOGICAL_ERROR` when their type ids differ, when the ids and the counts do not match the sources,
and for more than 65536 pieces with `UInt16` ids.

A separate API scatters one fixed-width column into pieces that the caller allocated. It takes `UInt16` piece ids and
works chunk by chunk. Its parts are `allocateUninitializedFixed`, `ScatterScratch`, `scatterPidChunk`, and
`histogramPidChunk` with its histogram lanes and `reduceHistogramLanes`. `scatterBatchRowsTarget` gives the rows of a
chunk for a number of pieces, and `computePassBits` splits the bits of a piece id into the fewest passes that a fanout
cap allows. The tests call this API and the second overload of `scatter`, and the benchmark times the second overload.
Nothing calls `scatterBatchRowsTarget` yet. The partitioned join of a later commit will use all of them.

The new `getL1CacheSize` returns the L1 data cache size from `getCPUDataCacheSize`, or 32 KiB when it cannot read it.
Nothing calls it yet: the partitioned join will use it to cap its number of partitions.

`benchmark_columns_scatter` times `IColumn::scatter` of one column with both id types. It covers a matrix of column
types, piece counts, selectors and row counts, and sweeps the thread count for four types. It also times `scatterBlock`
on a block of eight columns, and the second overload over eight sources. Each cell reports the peak memory of a call and
the allocated bytes of its pieces. A cell keeps its name at every `SCATTER_BENCH_LEVEL`, so the baseline is the same
file built at level 0 on the parent commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@harikrishnan94
harikrishnan94 force-pushed the half-radix-join-stack branch 4 times, most recently from 49cbad0 to 05a636d Compare November 24, 2026 19:10
Comment thread src/Interpreters/HashJoin/HashJoin.cpp Resolved
initial_table_bytes.push_back(table->bufferBytes());

/// Every join but a `Join` engine table waits: it keeps its blocks and builds its tables when the wait ends.
if (!build_layout.insert_on_arrival)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Blocker] Gate the new build strategy before enabling it for ordinary joins

This creates a deferred build for every non-Join-engine hash join. The parallel path now uses live cardinality estimates, scatter/owner rounds, and the new Grouped memory-fit policy, so this changes the execution and memory-admission strategy rather than only splitting the existing insert loop. It is enabled for existing queries immediately; hash_join_layout = 'serial' still takes deferred replay, and disabling software prefetch changes only the probe path.

Please put the new build strategy behind an experimental setting, disabled by default, retaining the established build path for rollout and rollback. Alternatively, separate this strategy from the probe/scatter refactor until that gated path is ready. The existing settings currently provide no way to restore the previous build behavior if the new sizing or spill handoff fails in production.

while (begin < records.size())
{
size_t end = records.size();
if (budget)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Major] Prove the grouped build and subsequent owner rounds in a focused test

This branch reuses tables and retained row references across several scatter/owner rounds, but no focused test demonstrates that a Grouped fit actually reaches it. The new parallel probe tests disable spilling; the existing spilling/limit tests can pass by switching directly to GraceHashJoin, without exercising this branch. A final join checksum alone therefore does not establish that the new in-memory build policy works.

Please add a small stateless regression test that forces a Grouped fit, verifies more than one build round through HashJoinBuildRounds (and that the join stayed in memory), and checks counts plus right-side payload checksums against a serial baseline. Include duplicate keys followed by new keys so later rounds must preserve both earlier table entries and their stored blocks. Also exercise an early build followed by additional input, since that enters the same owner code with an existing table and no new partition plan.

harikrishnan94 and others added 4 commits November 25, 2026 08:21
`ColumnsScatter` writes each fixed-width row straight to the write cursor of its piece. With many pieces, every write
cursor sits in a different cache line. These lines do not fit in cache together, so each store first reads its line from
memory.

`StoreMode::Combined` stages the rows of each piece in a 64-byte line and stores the line when it is full. A full line
goes to the piece with one non-temporal store, so the destination line is not read first. That store needs a
line-aligned destination. The first line of a piece starts at the piece's cursor, which can be anywhere in a line, so a
misaligned first line goes out with a regular copy.

`ScatterScratch` holds the staging lines and one fill counter per piece, in the same allocation as the cursors, so a
scratch that stays direct takes no more memory than before. `ScatterScratch::drain` stores the rows that are still
staged, orders the non-temporal stores before later reads, and sets every cursor to null, so the next column seeds its
own. In the `Combined` mode, `ScatterScratch::seed` asserts that the cursor of the piece is null: seeding a piece
again before `drain` would drop the rows staged for it.

`chooseStoreMode` picks the mode for a fixed-width column. A caller that knows the pieces are about equally big and the
output is large, as in a hash partitioning, passes the hint `allow_combining`. Without the hint, `chooseStoreMode`
returns `Direct`, which keeps the loop of the previous commit. With the hint, it returns `Combined` only for rows of 1,
2, 4, 8 or 16 bytes. The column also needs 256 to 65536 pieces and at least 2 lines of rows per piece on average.
Otherwise it returns `Direct`. On AArch64 it always returns `Direct`: Neoverse cores combine consecutive stores to a
line in hardware, so staging only adds a copy, and the non-temporal pair store is slower than a regular one there.

Each limit has a reason. Below 256 pieces, the cursors stay in cache. Above 65536 pieces, the staging lines would pass 4
MiB per column. With fewer lines of rows per piece, the last, partial line of each piece holds a larger share of the
rows, and that line goes out with a regular copy.

`IColumn::scatter` passes no hint, so it stays direct. The batched `ColumnsScatter::scatter` takes the hint as a
parameter, false by default, and asks `chooseStoreMode` for each fixed-width column that it writes row by row: numbers,
`FixedString`, the null map of a `Nullable`, the elements of a `Tuple` and the indexes of a `LowCardinality`. The
elements of an `Array` are copied by ranges, so they stay direct. While a call runs, a combined column holds 68 bytes
per piece of staging memory: 64 for the line and 4 for the fill counter.

The chunk API takes the mode. `ScatterScratch::init` gets the mode and allocates the staging lines for `Combined`.
`setStoreMode` changes the mode between two columns, after `drain`, and throws `LOGICAL_ERROR` for `Combined` when
`init` made no staging lines. A caller of the chunk API asks `chooseStoreMode` once for the whole column, not for each
chunk.

`scatterPidChunk` takes the mode as an argument and throws `LOGICAL_ERROR` when it differs from the mode of the scratch.
For `Combined`, it also throws when the width is not 1, 2, 4, 8 or 16, and when a cursor of the scratch is not a
multiple of the width. A staging line fills to exactly 64 bytes only when every cursor is a multiple of the width.

Every piece has the same rows and the same sizes as before.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…hile it is written

The partitioned hash join of the next commit needs the number of distinct right-side keys before any hash table
exists: to choose the number of partitions, to check the spill budget and the size limits while the build waits, and
to see when new keys stop arriving. Each build stream feeds its own counter, and any thread may read all of them while
they are written.

A defaulted trailing template parameter selects the new mode. In it:
- the 4096 registers are one byte each, read and written with relaxed `std::atomic_ref`;
- the denominator is computed in `size` instead of on every insert;
- `mergeLive` takes the register-wise maximum while the other counter is being written, and `consumeChange` reports
  whether a register rose since the last call;
- `insert` takes the low 32 bits of a hash and mixes them with `fmix32`, added next to `intHash32`.

The live mode cannot be serialized. The default instantiations keep their code, `sizeof` and serialized state, so
`uniqCombined`, `uniqCombined64`, `uniqHLL12`, the disk set filters and adaptive aggregation do not change.

A new gtest checks that the live mode's `size` equals the packed counter's for the same input, that `mergeLive` gives
the serial result while other threads insert, and that the default mode's state bytes and `sizeof` are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`HashJoin` had two build layouts. The serial one filled one hash table from one stream. The parallel one filled a
`TwoLevelHashTable` of 256 buckets from many streams, through `BuildSlots` with one lock per slot, and every bucket
grew on its own. Now both layouts are one build: the right side waits, and when the wait ends the join builds
partition tables of the right size, each one filled by one thread without a lock. The class stays `HashJoin`; there is
no new `join_algorithm`, and `hash_join_layout` and `parallel_hash_join_threshold` keep their meaning: serial is one
partition, parallel is several.

The wait. A right-side block is stored as before, with a small record of what its insert needs: the prepared key
columns, the NULL map and the `ON` mask. With several build streams the record also holds a 2-byte route per row (bits
16 to 31 of the key's hash) and feeds a distinct-key sketch, the live mode of `HyperLogLogCounter`. The wait ends at
build finish, or earlier when a size limit could be crossed, when keys only repeat (fewer than one new key in 16 rows,
for joins that drop blocks), on the verdict the statistics cache remembers from the last run, or at a quarter of the
spill budget (the backstop, again only for joins that drop blocks).

One build stream (the serial layout, every `UInt8` key, grace buckets, `JoinSwitcher`) replays the waiting blocks in
arrival order with the old insert, so the table, the row `ANY` keeps, `ASOF` ties, block drops and limit checks are
those of the old code. After an early end, blocks go straight in.

Several build streams. The number of partitions comes from the key estimate: the smallest power of two for which the
buffer that the partition's grower allocates for 1.2 times its share fits in 0.8 of the L2 cache, at least the number
of streams, and at most what keeps the 16-byte descriptors in a quarter of the L1 cache. An early build takes
max(256, next_pow2(2 x max_threads)). A scatter copies the keys and 4- or 8-byte row locators into one contiguous piece
per partition, using the typed scatter kernels of layer 3. Then one owner per partition creates its table, reserves it
once, inserts its piece and frees it. Repeated keys are `RowRefList` batches in the build streams' arenas. After an
early end the join waits again, and each batch ends by the same rules; a round takes a `SharedMutex` exclusively.

The probe is not partitioned. A partition view holds one table by value, or P tables with a flat array of 16-byte
descriptors (cells and mask) and a separate prefix array for the used flags, so a probe row reads one descriptor and
never a table object. The AMAC ring takes a 2-byte partition index and a run-time shift.

Memory. `getTotalByteCount` stays the allocated bytes. A new projection adds the tables and arenas that do not exist
yet, and the spill check, grace's overflow check and the byte bound of the wait read it. At build finish
`SpillingHashJoin` chooses between building at once, building in rounds over ranges of blocks, and spilling, from the
peak of the build (the larger of the whole copy with one table, and all tables with one piece). The memory scheduler's
last turn to spill is right before the build.

The finish step is `finishBuild`, run once by every driver; `runPostBuildPhase` runs it and then the rerange, the
fixed-table conversion and the shared runtime filter. Grace builds its current bucket in `onBuildPhaseFinish` and no
longer finishes a join on its header probe. A `Join` engine table inserts every block on arrival and is never frozen,
as before.

Removed: `BuildSlots`, the 12 `two_level_*` key types, `NUM_HASH_TABLE_BUCKETS`, and the join's use of
`TwoLevelHashTable`. New ProfileEvents: `HashJoinBuildPartitions`, `HashJoinBuildRounds`,
`HashJoinPartitionTableResizes`, `HashJoinBuildScatterMicroseconds`, `HashJoinBuildInsertMicroseconds`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
After the previous commit the join no longer uses `TwoLevelHashTable`: each partition is an ordinary hash table, and
the partition view keeps its own descriptors and cell offsets. These parts have no user left:
- `BucketCells`, `bucket_cells`, `RobinHoodBuckets` and `robin_hood_buckets`, from the bucket-listing commit;
- `computeBucketPrefix`, `bucket_cells_prefix`, `iteratorAt`, `setRobinHoodAllowed` and the prefix form of
  `offsetInternal`, whose callers were in the join;
- `BucketPartitionedTable.h` (`getBucketOfKey` and its two concepts), and `PartitionedFixedHashTable::computeBucketPrefix`.

`offsetInternal` goes back to the form `master` had before the prefix cache. The gtests of the removed parts go; the
`PartitionedFixedHashMap` and `PartitionedFixedHashSet` tests stay.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors ci-force-all Do not skip any jobs when running ci-relocation-headroom-ok Accept an expected decrease of the relocation headroom in the build check comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... ignore-unresolved-threads Do not limit CI and block merge on unresolved review threads pr-not-for-changelog This PR should not be mentioned in the changelog pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant