Skip to content

Exact-size JOIN Hashtable build to avoid rehashing on cold builds - #108129

Draft
harikrishnan94 wants to merge 7 commits into
ClickHouse:masterfrom
harikrishnan94:parallel-hash-exact-size-deferred-build
Draft

harikrishnan94 wants to merge 7 commits into
ClickHouse:masterfrom
harikrishnan94:parallel-hash-exact-size-deferred-build

Conversation

@harikrishnan94

@harikrishnan94 harikrishnan94 commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

A hash join builds hash tables from the right side and probes them with the left side. Today HashJoin::addBlockToJoin stores each right block and inserts its keys into the map at once. Each map cell holds a key and a reference to its row (block number and row number).

The size of the maps is known in advance in three cases:

  • collect_hash_table_stats_during_joins (on by default) recorded the size of the same join in an earlier run, in the hash table statistics cache.
  • A bucket of grace_hash takes the number of keys of the previous bucket.
  • With this change, the right join key has a uniq or uniq_v2 column statistic (see below).

Otherwise the build is cold: the first run of a join, an evicted statistics entry, or the statistics turned off. A cold build starts each table at 256 cells, and each resize rehashes every key of the table:

  • The two-level layout has 256 tables, one per bucket. The join uses it when the right side has parallel_hash_join_threshold rows or more, or no row estimate. A bucket resizes when more than half of its cells are used, and grows 4 times while it has fewer than 2^15 cells, then 2 times. At 2^16 cells it switches to Robin Hood mode in place, and from then on it fills to 90% before it doubles.
  • Below the threshold, the join fills one table on one thread (the serial layout). It resizes when more than half of its cells are used, and grows 4 times while it has fewer than 2^23 cells, then 2 times.

In cold INNER and RIGHT joins with 10^8 right rows, these resizes make the query up to 1.2 times as slow on the two-level layout (1.12 to 1.14 times at the median). On the serial layout they make it up to 1.8 times as slow, but a right side that large gets the serial layout only with a raised parallel_hash_join_threshold or a row estimate that is far too low.

Design

During addBlockToJoin, a deferred build only stores the right blocks, and counts their distinct keys while they arrive. After the last block, it reserves each map once for that count and inserts the stored blocks. A reserve for n keys gives a table that holds n keys without a resize: at most half full, or 90% full for a two-level bucket of more than 2^16 cells. So the inserts resize a table only when the count was too low.

Counting the distinct keys

HashJoin::addBlockToJoin is split into storeBlock and insertStoredBlock. A deferred build calls only storeBlock, then counts the block in addPendingInsert. Each build stream keeps, per ON clause:

  • a HyperLogLog sketch with 2^13 byte registers (8 KiB, standard error about 1.15%). It takes the low 32 bits of the hash that the map uses, mixed with the MurmurHash3 finalizer, so a CRC hash still gives independent register indexes and ranks;
  • the number of rows per bucket of the map, and the bytes of the string keys per bucket.

Only the rows that the insert takes are counted: a NULL key, or a row that fails the right-side ON condition, is skipped. The estimate is the merged sketch of all streams, capped at the number of counted rows.

HyperLogLogCounter gets the byte registers, written with relaxed atomic stores, mergeLive to read a sketch while its stream writes it, and a flag that tells whether an insert raised a register. Its default parameters keep the current code, and its existing users compile to the same instructions.

Reserving and inserting

In the post-build phase, the build reserves each bucket from the estimate e and its own counted rows r. With one bucket (the serial layout), the reserve is min(e, r). With 256 buckets, let s be e / 256, the even share of a bucket. A bucket reserves its share of e by its rows, but at least s + 4·sqrt(s), at most 4·s, and never more than r. The lower bound covers the spread of evenly hashed keys. The upper bound keeps a bucket full of duplicates of one hot key from reserving for keys it does not have. A bucket that gets more keys than its reserve grows as in a streaming build.

Then the stored blocks are inserted, with min(build streams, stored blocks) threads. Each thread takes the next stored block of any stream and inserts it through the slot locks. With one thread, the blocks are inserted in the order they were stored.

When the build defers

The build defers when enable_hash_join_deferred_build is on (the default) and all of the following hold:

  • The size is not known in advance (see above).
  • The join is not join_overflow_mode = 'break' with a size limit: break stops at the block that crosses the limit, so the limit must be checked as the blocks arrive.
  • The map is not one that has all its cells from the start (key8, key16 and the fixed-range maps).
  • Until the inserts, the deferred build holds no more than the streaming build. The next two conditions make this exact.
  • The stored blocks hold every right key as a plain column. The streaming build stores the keys of an INNER or LEFT join only when the join may spill (max_bytes_before_external_join or max_bytes_ratio_before_external_join), has OR conditions, or has a condition on both tables that the join evaluates itself. RIGHT and FULL joins always store them. A right key that the join outputs can be stored in the row store instead; then the build does not defer either.
  • The map keeps every right row (ALL and ASOF maps). INNER and LEFT ANY joins, LEFT SEMI joins and LEFT ANTI joins keep at most one row per key. Their streaming build drops a block that adds no new key as soon as the block arrives, while a deferred build would hold it until the inserts.

Sizes from column statistics

The planner can now take the size from a uniq or uniq_v2 statistic of the right key. This needs a single join key that is a column of the right table, read with no filter, limit or aggregation in between, and the statistic in every part of the table. The planner marks such distinct counts where it reads the statistics. It keeps the mark through aliases, materialize and toNullable, and clears it at any other function or cast, at a filter, a limit, an aggregation and a join. After it chooses the join order, it passes the marked count of the build side to the join. Such a build streams, and the two-level layout reserves from the count, as with the statistics cache.

Spilling

A deferred build has no maps while the blocks arrive, so SpillingHashJoin compares the spill threshold with a projection of what the build will hold. The projection is the stored blocks plus:

  • the buffers of the reserved buckets;
  • the distinct string keys that the maps copy into the arenas, from the bytes of the counted keys;
  • the row list nodes of the keys with duplicates, from the estimate and the rows;
  • the null maps that the inserts add for RIGHT and FULL joins.

The arena terms follow the chunk growth of Arena, per slot. While the blocks arrive, the projection uses the counts that the streams have published, with the rows spread evenly over the buckets. It is recomputed by one thread at a time, each time the stored rows have grown by 1/16 since the last recompute. At the end of the build it uses the final counts. When the projection reaches the threshold, the join switches to GraceHashJoin before any key is inserted and hands it the stored blocks. The existing switch at twice the stored bytes stays.

For the memory spill scheduler, a deferred build reports the bytes that its inserts will allocate as memory it needs. So the scheduler can also hand the stored blocks to GraceHashJoin before the inserts.

Limits and cancellation

With join_overflow_mode = 'throw', the size limits are checked once, after the inserts, against the keys and bytes that the join holds then. So a deferred build accepts and rejects the same joins as a streaming build. Every inserting thread checks KILL QUERY and max_execution_time before each block.

Events

HashJoinDeferredBuilds counts the deferred builds, HashJoinDeferredPreallocatedElementsInHashTables the keys they reserved, and HashJoinDeferredBuildBucketsGrown the buckets that grew past their reserve. HashJoinPreallocatedElementsInHashTables now also counts the reserves made from a uniq statistic.

Caveats

Memory

The keys are stored anyway whenever the build defers, so a deferred build holds the same stored blocks as the streaming build until its inserts. On top of that it holds, per build stream and ON clause, an 8 KiB sketch and two 64-bit counters per bucket, and the right-side ON condition columns of each block until it is inserted.

Without a spill threshold, the streaming build of an INNER or LEFT join on key equalities drops the key columns, because the maps hold the keys. A deferred build would have to keep a key for every right row until the inserts, also for the duplicates that take no cell of their own. So such joins do not defer.

Behavior

  • Query results do not change. Without ORDER BY, the joined rows can come in another order when several threads insert, as with any parallel build.
  • A join over a throw size limit fails only after the whole right side is read and inserted.
  • The sketch counts distinct 32-bit hashes, so it reads low when keys collide in them: about 6% low for 10^8 distinct structured string keys. Then some buckets grow past their reserve, and HashJoinDeferredBuildBucketsGrown counts them.
  • The counting and the deferred inserts have a fixed cost. In builds of 10^5 to 10^7 rows, mostly at 96 threads, some joins are up to 1.1 times as slow, by at most a few milliseconds.

Closes: #111268
Related: #115605

Changelog category (leave one):

  • Performance Improvement

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

Hash joins no longer rehash their hash tables as they grow on a cold build, when no statistics give the size of the hash tables in advance (the first run of a join, or collect_hash_table_stats_during_joins = 0). The build stores the right side first, counts its distinct keys while it arrives, and reserves each hash table once for that count. Cold INNER and RIGHT joins with large right sides get up to 1.2 times faster with the default layout. The setting enable_hash_join_deferred_build controls it.


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

@harikrishnan94 harikrishnan94 added performance pr-performance Pull request with some performance improvements comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... can be tested Allows running workflows for external contributors labels Jun 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [04b035f]

Summary: ✅


AI Review

Summary

This PR preallocates cold hash joins using deferred distinct-key counting or column statistics. Block: replay can exhaust query memory before spilling, some statistics hints still overallocate, arena projection can force unnecessary spills, and soft timeouts do not stop replay. These five concerns belong to existing discussions; no duplicate inline findings were posted.

Findings

❌ Blockers

  • Replay can exceed the memory limit before the final spill check. DeferredBuild.cpp:210, SpillingHashJoin.cpp:494: the projection budgets reservations rather than subsequent bucket growth, and discounts string bytes by the global distinct-row fraction. For one million distinct UInt64 keys routed to one bucket, a cold parallel-layout build projects approximately 18 MiB, passing a 24 MiB spill threshold, but insertion needs a 32 MiB bucket buffer plus approximately 8 MiB of stored blocks. With a 32 MiB query limit, replay fails before the new post-insertion check; streaming inserts in small blocks can spill first. Distinct long strings mixed with frequent short duplicates create the same unsafe underestimate. Preserve spill decisions between replay blocks or bound replay's allocation peak conservatively. Existing discussions: bucket growth, string-byte skew.

⚠️ Majors

  • Row-dropping array joins retain whole-table distinct counts. optimizeJoin.cpp:1457: both ArrayJoinStep and expression-form arrayJoin preserve trusted statistics for unaffected key columns despite dropping rows with empty arrays or element filters. A million-key table with only 100 nonempty arrays can therefore preallocate for a million build keys, causing excessive memory use or spilling. Clear the provenance across these operations. Existing discussion.

  • Join-key conversion can invalidate an already selected hint. JoinStepLogical.cpp:2625: the hint is selected before physical planning adds accurateCastOrNull for signed/unsigned equality keys. Negative right-side values become NULL and are skipped, but their original distinct count still disables deferred counting and sizes the map. Validate the hint after key normalization or invalidate it for conversions that reject values. Existing discussion.

  • One long key inflates every slot's projected arena. DeferredBuild.cpp:244: the global max_allocation is applied to every nonempty slot. With 16 slots, one 1 MiB string and 999 short distinct keys, projection adds over 16 MiB of arena chunks although only one arena copies the long key. A build fitting an 8 MiB threshold can unnecessarily switch to GraceHashJoin. Track the maximum allocation per slot. Existing discussion.

  • Soft timeouts do not interrupt deferred insertion. HashJoin.cpp:3545: QueryStatus::checkTimeLimit returns false for timeout_overflow_mode = 'break', but replay ignores it and inserts every remaining block. The executor cannot observe the timeout until this entire task returns. Handle the false return and stop replay consistently with executor cancellation. Existing discussion.

Tests
  • ⚠️ Cover bucket and string-byte skew using multiple input blocks under a tight query memory limit, comparing deferred and streaming completion. The new post-insertion spill tests do not constrain replay's peak memory.
  • ⚠️ Cover empty-array/element-filter build inputs and signed/unsigned key conversion; verify that unrepresentative whole-table hints are rejected.
  • ⚠️ Cover a fitting multi-slot build with one long key and many short keys, asserting that it does not spill.
  • ⚠️ Exercise timeout_overflow_mode = 'break' with the timeout reached during replay. The current cancellation test covers throw and KILL QUERY.
Missing context / blind spots
  • ⚠️ The failure traces above were verified against source, without local server tests or benchmarks. Focused memory-capped and replay-timeout runs would establish exact runtime thresholds.
Final Verdict

Status: ❌ Block. Protect replay's allocation peak, invalidate the two unsound statistics hints, project arena maxima per slot, and honor soft timeout results with the focused coverage above.

@harikrishnan94

Copy link
Copy Markdown
Contributor Author

cc @Ergus @nickitat — this is the exact-size parallel_hash build split out of #107189 into its own PR, as requested. It is independent of the compact index-based row references (now scoped to #107189) and can be reviewed and merged separately, in either order.

Comment thread src/Interpreters/ConcurrentHashJoin.cpp Resolved
harikrishnan94 added a commit to harikrishnan94/ClickHouse that referenced this pull request Jun 23, 2026
The new test for the deferred `parallel_hash` build to `GraceHashJoin`
spill handoff exceeded the 180s per-run limit of the stateless flaky
check under the `amd_asan_ubsan`, `amd_tsan` and `amd_debug` builds
("Test runs too long (> 180s). Make it faster."). It also risked a
non-deterministic positive control: with parallel replicas the build
side is range-split across replicas, so a per-replica buffer might not
cross the small spill threshold and the handoff would not be exercised.

Shrink the dataset (build `numbers(50000)` -> `numbers(8000)`, probe
100000 -> 16000 rows) and lower `max_bytes_before_external_join` from
256 KiB to 128 KiB so the spill is still forced (the ~0.5 MiB build side
is several times the threshold) while the whole test runs in well under a
second even under sanitizers. Pin `enable_parallel_replicas = 0` so the
build side stays on one node and the deferred-build handoff is exercised
deterministically. Query results are unchanged in shape; the reference is
regenerated for the smaller data.

Verified locally against a RelWithDebInfo server: 80/80 runs with random
settings pass, each well under a second.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108129&sha=b8148d3fc215bcba150a80dd111e934a6449d47a&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29
PR: ClickHouse#108129

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Comment thread src/Interpreters/ConcurrentHashJoin.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

This PR only changes the parallel hash-join build path in ConcurrentHashJoin (a deferred exact-size build plus NDV-based preallocation of the hash tables). The two flagged queries, ClickBench Q4 and Q15, are single-table aggregation scans that execute no join, so the change cannot plausibly affect them. Their -18.4% and -11.6% medians are run-to-run variance, and the deterministic within-envelope suppression to no_change is correct. No perf change attributable to this PR was observed in the flagged set.

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 079bde79-42c9-45c3-a7a9-d926b6cad88d
  • MIRAI run: 310bd6d1-4f65-48e3-b122-aff37a70d52d
  • PR check IDs:
    • clickbench_242881_1784944030
    • clickbench_242895_1784944030
    • clickbench_242901_1784944030
    • tpch_adapted_1_official_242912_1784944030
    • tpch_adapted_1_official_242935_1784944030
    • tpch_adapted_1_official_242949_1784944031

harikrishnan94 added a commit to harikrishnan94/ClickHouse that referenced this pull request Jun 23, 2026
The deferred exact-size `parallel_hash` build buffers the whole right side
before checking `max_rows_in_join` / `max_bytes_in_join` exactly at
`onBuildPhaseFinish`. The streaming build instead enforces the byte cap
incrementally, so a query with `join_overflow_mode = 'throw'`,
`max_bytes_before_external_join = 0` and a small `max_bytes_in_join` could
buffer and build the full hash table and only throw at the end, overshooting
the join cap or hitting `max_memory_usage` first.

The buffered block bytes (`getTotalByteCount`) are a lower bound on the final
join footprint, so fail early once even that lower bound crosses
`max_bytes_in_join`, restoring the streaming build's incremental-byte-guard
behavior. The check passes `rows = 0` so only the byte dimension can trip: the
buffered source-row count over-counts distinct keys and must wait for the exact
post-replay check, which still enforces both dimensions at `onBuildPhaseFinish`.

The deferral is disabled for `break` mode, so the mode here is always `throw`.
No false rejections are introduced: the lower-bound byte count only grows, and
the existing `04335_parallel_hash_deferred_build_size_limits` test (whose
`max_bytes_in_join = 1024` case now throws during buffering rather than at
replay, with the same `SET_SIZE_LIMIT_EXCEEDED` code) still passes.

Addresses the `clickhouse-gh` review thread on
src/Interpreters/ConcurrentHashJoin.cpp in
ClickHouse#108129

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Interpreters/ConcurrentHashJoin.cpp Resolved
Comment thread src/Interpreters/ConcurrentHashJoin.cpp Outdated
external_join_threshold,
ProfileEvents::HashJoinDeferredPreallocatedElementsInHashTables);

for (auto & scattered_block : hash_join->buffered_blocks)

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.

The deferred replay now runs through every buffered block inside one onBuildPhaseFinish work item, but this loop never polls cancellation. Before this change, the right side was inserted block-by-block through separate processor work calls, so KILL QUERY could interrupt between blocks; now a large cold parallel_hash build that has already buffered its right side will keep reserving and replaying the whole join before cancellation is observed. Please thread a cancellation check into this replay (for example via the query status from CurrentThread::tryGetQueryContext or a callback from FillingRightJoinSideTransform) and check it between buffered blocks/tasks.

@harikrishnan94 harikrishnan94 Jun 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch on the cancellation latency. Let me see what I can do here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done. onBuildPhaseFinish now grabs the query status from CurrentThread::tryGetQueryContext and polls checkTimeLimit between buffered blocks during the replay, so KILL QUERY and max_execution_time interrupt a large cold build instead of waiting for the whole replay to finish.

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.

The timeout fix is still incomplete at src/Interpreters/HashJoin/HashJoin.cpp:3545: QueryStatus::checkTimeLimit returns false for timeout_overflow_mode = 'break', but replay discards the return value and continues inserting every stored block. The executor checks the timeout again only after this entire post-build task returns. Please handle that return value; the existing cancellation test exercises only throw and KILL QUERY.

@Ergus Ergus left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

SpillingHashJoin is created only when params.max_bytes_before_external_join > 0

if (params.max_bytes_before_external_join > 0 && table_join->getTempDataOnDisk() && GraceHashJoin::isSupported(table_join))

IIUC that threshold derives from the absolute setting and the 0.5 ratio, so, when both are 0; there is no wrapper at all and ConcurrentHashJoin runs standalone with external_join_threshold = 0.

A while ago I saw a similar case where that was causing MEMORY_LIMIT_EXCEEDED. I will investigate and come back in a while

Comment thread src/Interpreters/ConcurrentHashJoin.cpp Resolved
@Ergus

Ergus commented Jun 23, 2026

Copy link
Copy Markdown
Member

SpillingHashJoin is created only when params.max_bytes_before_external_join > 0

if (params.max_bytes_before_external_join > 0 && table_join->getTempDataOnDisk() && GraceHashJoin::isSupported(table_join))

IIUC that threshold derives from the absolute setting and the 0.5 ratio, so, when both are 0; there is no wrapper at all and ConcurrentHashJoin runs standalone with external_join_threshold = 0.

A while ago I saw a similar case where that was causing MEMORY_LIMIT_EXCEEDED. I will investigate and come back in a while

OK, Claude agreed with my concern and detailed the potential root cause:

For a duplicate-heavy parallel_hash join, the exact-size deferred build can raise build-phase peak memory enough to throw MEMORY_LIMIT_EXCEEDED on a cold run, while the same query with the same settings completes once a hash-table size hint is cached. So the failure is not a deterministic property of the query — it's "throws when cold, works on retry," which is surprising to operate and to debug.

Why peak memory rises on the deferred path
The deferred build sizes the maps by buffered source-row count, not by distinct-key count.

In onBuildPhaseFinish (ConcurrentHashJoin.cpp):

size_t global_total_rows = 0;
for (const auto & hash_join : hash_joins)
global_total_rows += hash_join->buffered_rows; // SOURCE rows, not distinct keys
...
reserveBucketsBySize(*hash_join->data, i, global_total_rows, slots, external_join_threshold, ...);

buffered_rows is accumulated as dispatched_block.rows() in addBlockToJoin — i.e. every right-side row, including duplicates. But a hash map only allocates cells for distinct keys; duplicate rows are appended to a RowRefList in the arena, not to new cells. So for a build with ~2 rows per key, reserveBucketsBySize reserves ~2× the cells the map actually needs. With the grower's power-of-two rounding (bufSize in [2n, 4n)), the cell buffer can be up to ~4× the distinct-key working set. The PR description confirms this exactly: "a 20M-row build preallocates 20M elements whether it has 20M or 10M distinct keys."

That over-sized cell buffer is allocated up front by reserve() (a single calloc-style allocation of the whole buffer) and is charged to the query MemoryTracker at allocation time — which is precisely what max_memory_usage enforces. So even if the extra cells are never written, the limit check sees the full reserved size. The streaming build never has this transient: it grows the buffer incrementally and only as far as the distinct keys require.

Net peak difference vs. a correctly-sized build ≈ (rows − distinct_keys) × cell_size, rounded up to a power of two — easily hundreds of MB to >1 GB on a large build, which is enough to tip a tight max_memory_usage.

Why it's cold-only (the nondeterminism) deferred_build is gated on there being no size hint (ConcurrentHashJoin.cpp):

deferred_build = !any_take_last_row
&& hash_joins[0]->data->twoLevelMapIsUsed()
&& !getSizeHint(stats_collecting_params).has_value() // only when cold
&& !(size_limits.hasLimits() && overflow_mode == BREAK);

  • Cold run (no hint cached — first run of the query shape, or after a server restart / stats-cache eviction, or with collect_hash_table_stats_during_joins = 0): deferral engages, reserve is by row count → inflated peak. This run also records the stats.
  • Warm run (hint present): deferral is skipped; the streaming path preallocates via reserveSpaceInHashMaps to the cached ht_size, which is the hash-table cell count = distinct keys, not rows. So the map is sized correctly and the peak is back to normal.

That's the asymmetry: the same query throws on the cold run and succeeds on the warm run. And because the hint lives in a process-global, evictable, non-persistent cache, a query that "worked yesterday" can fail again after a restart — with no change in data or settings.

Why this is confined to the spilling-disabled configuration

This only becomes an exception (rather than a transparent spill) when there is no SpillingHashJoin escape valve, i.e. max_bytes_before_external_join = 0 and max_bytes_ratio_before_external_join = 0:

  • Spilling enabled (the default, ratio = 0.5): the wrapper is present. Its spill checks consult getProjectedTotalByteCount, and the projection (projectedTwoLevelMapBytes(total_buffered_rows)) is also computed from the row count — so it already "sees" the over-reservation and switches to GraceHashJoin before the over-sized map is built. The reserve is additionally capped by budget_entries. So in spilling-enabled configs the over-reservation turns into an (earlier) spill, not an OOM. Safe.
  • Spilling fully disabled but max_memory_usage set: no wrapper (external_join_threshold = 0), so the reserve is not capped (reserveBucketsBySize skips the if (external_join_threshold > 0) branch) and there is no spill path. The only guard is the global MemoryTracker, which throws MEMORY_LIMIT_EXCEEDED.

harikrishnan94 added a commit to harikrishnan94/ClickHouse that referenced this pull request Jun 24, 2026
…ild finish

Follow-up to ClickHouse#108129.

`SpillingHashJoin::addBlockToJoin` computed `ConcurrentHashJoin::getProjectedTotalByteCount` for every
buffered block. During a deferred build no hash map exists yet (only buffered blocks), so the
power-of-two doubling race that motivated the projection does not apply there - only the real buffered
bytes can OOM before the replay. For a non-deferred build there are no buffered rows, so
`getProjectedTotalByteCount` already equals `getTotalByteCount`. Switch the per-block `concurrent_join`
branch to `getTotalByteCount` and keep the projection-based spill decision at build finish
(`SpillingHashJoin::onBuildPhaseFinish`), right before the replay would allocate the maps.

This is a strict no-op on results: the terminal gate uses the same
`projection * SPILL_TRIGGER_HEADROOM_FACTOR >= max_bytes_before_external_join` test the old per-block
check used, and the projection is monotonic during buffering, so any spill the old code would trigger
mid-build the new code still triggers at finish. The deferred buffer stays bounded at ~threshold/2, so
it cannot OOM before the terminal check. An independent review confirmed the result no-op on all paths
(non-deferred, single `HashJoin`, standalone, grace, deferred) and the absence of an OOM regression.

Adds a regression test that the spill happens at finish (not per block) and that parallel_hash matches
the plain hash reference.

Co-authored-by: Cursor <[email protected]>
harikrishnan94 added a commit to harikrishnan94/ClickHouse that referenced this pull request Jun 24, 2026
…s, not source rows

Follow-up to ClickHouse#108129. Addresses the review comment that
the deferred reserve used source rows rather than distinct keys
(ClickHouse#108129 (comment)), which over-allocates the
hash maps for duplicate-heavy build sides and can overshoot the `SpillingHashJoin` memory cap.

While the right side is buffered, a HyperLogLog (precision 12, like `uniqHLL12`) estimates the number of
distinct join keys from the already-computed scatter hashes. At build finish the maps are reserved to
that distinct-key count instead of the source-row count, and `getProjectedTotalByteCount` /
`projectedTwoLevelMapBytes` use the same estimate, so the `SpillingHashJoin` spill decision matches the
footprint the replay actually builds. The projection also adds a tight `RowRefList::Batch` arena bound
computed from a down-biased estimate (so it stays an upper bound), while the map term uses an up-biased
estimate (so the reserve does not under-shoot); both keep the projection a conservative upper bound. The
deferred reserve no longer applies the `threshold/2` budget cap, because the terminal spill check has
already approved the full projected footprint, so the replay does not rehash.

The estimator is kept cheap and off the build's hot path. Each `addBlockToJoin` caller feeds its whole
block's raw scatter hashes into one of several sharded HLLs chosen round-robin, taking the shard lock
once per block - rather than feeding a per-slot HLL under the contended per-slot buffering mutex, which
regressed cold unique builds. The raw scatter hash is reused directly (the HLL's own `intHash32` mixes
it; no extra finalizer is needed once the estimate is global), and the shards are merged (HLL union, so
a key seen in several shards is not double-counted) before the reserve.

Measured on a cold synthetic grid (100M build x 300M probe, no statistics, parallel_hash): duplicate-heavy
2:8 builds drop peak memory ~22-39% versus reserve-by-rows with no time regression, and unique builds are
unaffected. An independent review confirmed spill-size == reserve-size, that the projection is a true
upper bound (within the HLL error envelope), and that the raw-hash reuse keeps the estimate accurate
(a 2,000,000-distinct string build reserves ~2,128,544, i.e. within the up-bias margin).

Adds a test that a duplicate-heavy cold build reserves ~NDV (not source rows) and does not spuriously
spill under a memory cap that the old source-row sizing would have overshot.

Co-authored-by: Cursor <[email protected]>
harikrishnan94 added a commit to harikrishnan94/ClickHouse that referenced this pull request Jun 24, 2026
…ustworthy key NDV

Follow-up to ClickHouse#108129. When the planner already knows a
trustworthy distinct-key count for the right join key, the exact-size build does not need to buffer and
estimate - it can size the maps directly. This extracts that count from
`JoinStepLogical::result_column_stats` and, when present (and there is no cross-run statistics size
hint), sets `deferred_build = false` and preallocates the streaming build to the distinct-key count via
`reserveSpaceInHashMaps`/`reserveBucketsBySize` - exactly like the warm `ht_size` path.

Only a real `uniq`-statistic-backed distinct count is trusted, never the `0.1 * rows` mock
(`ConditionSelectivityEstimator::default_cardinality_ratio`) used when no `uniq` statistic exists. A new
`ColumnStats::num_distinct_values_from_uniq` flag carries that provenance: it defaults to false and is
set true only at the leaf (`estimateRelationProfile`) under the same `stats.contains(Uniq)` condition
that makes `estimateCardinality` return the real value, and it is ANDed when distinct counts are
combined (the equi-key min in the join-order DP), so a value that ever touched a mock is never trusted.
Composite keys, expression keys, multi-relation columns, and sources without `uniq` statistics
(subqueries, non-MergeTree) all yield "absent" and fall back to the estimated (HLL) deferred build. The
NDV is threaded into the `ConcurrentHashJoin` constructor (forwarded through `clone` and
`SpillingHashJoin`); the legacy `ExpressionAnalyzer` path passes `nullopt`. The cross-run `ht_size` hint
keeps precedence.

Measured: a build whose key has a materialized `uniq` statistic preallocates ~NDV and does not defer,
while the same build without statistics still uses the deferred (HLL-sized) build. An independent review
confirmed the mock can never drive preallocation, the extraction safely rejects composite/expression/
multi-relation keys and degrades to deferral on a name mismatch, and the streaming preallocation is
capped to the spill threshold.

Adds a test that a `uniq`-backed key preallocates ~NDV without deferring while a no-statistics (mock) key
still defers, including a self-join case.

Co-authored-by: Cursor <[email protected]>
@harikrishnan94

Copy link
Copy Markdown
Contributor Author

The Request changes summary ran on 7e8ea2d (source-row sizing). I've since pushed:

  • d1bd3ba — size the deferred build by estimated distinct keys (merged HLL shards), not source rows.
  • 2a15fef — skip the deferred build entirely when the planner has a trustworthy uniq-backed NDV.
  • 33020fa / 3df3b3 — projection-at-finish + a no-behavior-change cleanup.

The TPC-H Q16 +21.6% was an earlier cloud run and isn't reproduced in the latest reports: Cloud Performance Report shows tpch_adapted_1_official → No significant changes (no_change overall), and the standard Performance Comparison shows no significant changes (the flagged join queries flip sign across shards — noise). A fresh run is now in flight on the distinct-key commits; I'll post the updated Q16 numbers here.

The build-size gate stays a tracked follow-up: it's an algorithm change whose threshold needs benchmark evidence, and the two concrete harms (over-reservation memory, and the stats-backed small-build case) are already handled by d1bd3ba and 2a15fef. If the fresh run still flags Q16, I'll add the gate.

Comment thread src/Interpreters/ConcurrentHashJoin.cpp Resolved
harikrishnan94 added a commit to harikrishnan94/ClickHouse that referenced this pull request Jun 24, 2026
Follow-up to ClickHouse#108129 (comment). A cold
`parallel_hash` build with no size hint defers: it buffers the right-hand blocks and replays them in one
`onBuildPhaseFinish` work item, which polls `QueryStatus::checkTimeLimit` before the reserve and between
every buffered block so a large cold build can be interrupted mid-replay rather than reserving and
replaying to completion first. `checkTimeLimit` throws `TIMEOUT_EXCEEDED` for `max_execution_time` and
`QUERY_WAS_CANCELLED` for a `KILL`, so both triggers exercise the same in-replay poll.

The test forces the cold, two-level, deferred build (no statistics hint, no `SpillingHashJoin` wrapper,
build side pinned) and checks two things:
- `max_execution_time` interrupts the build mid-flight. To stay machine independent it measures the build
  duration `D` on the same machine (the minimum of several warm runs, a stable steady state) and uses a
  limit of `0.7 * D`. With the in-replay poll the query stops at ~`0.7 * D`; without it the replay runs to
  ~`D` first. Because where the limit lands (buffering vs replay) wobbles run to run, it is probabilistic:
  several trials are run and a majority must stop before `0.82 * D`. A trial that trips during the
  already-interruptible buffering phase still stops early, so it never causes a false failure.
- `KILL QUERY` cancels a cold deferred build (`QUERY_WAS_CANCELLED`).

Verified by removing the in-replay `checkTimeLimit` calls and rebuilding: the timeout check then fails
every run, while it passes on every run (including under randomized settings) with the calls in place.

Co-authored-by: Cursor <[email protected]>
harikrishnan94 added a commit to harikrishnan94/ClickHouse that referenced this pull request Jun 24, 2026
…V, not the post-join NDV

The planner NDV shortcut that skips the cold deferred build (`extractTrustworthyRightKeyNdv`)
read the right-key distinct count from `JoinStepLogical::getResultColumnStats`, which holds
the post-join output stats. `DPJoinEntry` clamps both equi-key NDVs to `min(left, right)`, so
a probe (left) side with fewer distinct keys than the build (right) side shrank the right-key
NDV - e.g. a 10-distinct-key probe against a 1M-distinct-key build returned 10. That disabled
the deferred/HLL path and preallocated the streaming `parallel_hash` build to that tiny min,
so the cold build rehashed through the full right key set, losing the exact-size behavior.

Thread the right (build) input relation's column stats - taken before this join's equi-key
min-clamp - onto `JoinStepLogical` via a new `right_input_column_stats`, and read the NDV from
`getRightInputColumnStats` instead. The build side is the post-flip right child, so the swap
in `chooseJoinOrder` is accounted for. `getResultColumnStats` is unchanged and still feeds the
join-order cost model. As a side effect the shortcut now also applies when only the build side
has a `uniq` statistic, since the trust flag no longer needs both sides.

Add a regression `04409_parallel_hash_deferred_build_plan_ndv_asymmetric` where the build NDV
(~30000) is much larger than the probe NDV (10): the build map must preallocate to ~30000
(not the post-join min of 10) and must not defer, while results match the plain `hash` join.

Addresses the review comment: ClickHouse#108129 (comment)
Follow-up to ClickHouse#108129

Co-authored-by: Cursor <[email protected]>
Comment thread src/Interpreters/ConcurrentHashJoin.cpp Resolved
harikrishnan94 added a commit to harikrishnan94/ClickHouse that referenced this pull request Jun 24, 2026
The four `04405`/`04407`/`04408`/`04409` tests for the exact-size
`parallel_hash` deferred build assert exact spill decisions and tight
reserve/preallocation ranges (and, for `04408`, build-duration timing
thresholds). The stateless-test settings randomizer perturbs the spill
decision, the planner NDV path, and the build-duration baseline through
unpinned side channels (`max_threads`, the external-spill ratio, the
join-order algorithm/limit, the statistics toggles), so the trailing
regression guards flapped across CI configs even though the join results
themselves stayed correct.

Add `-- Tags: no-random-settings, no-random-merge-tree-settings` (the
same treatment `04146_spilling_hash_join_low_threshold.sql` already uses
for the same class of spill-threshold regression test). The in-file
`SET` statements still win over the command-line defaults; disabling the
randomizer removes the unpinned variance that the guards are sensitive
to.

Verified locally against an ASan build at this branch head: all four
tests pass deterministically (`04408` run three times for the
probabilistic timing assertion).

CI report:
ClickHouse#108129

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
harikrishnan94 added a commit to harikrishnan94/ClickHouse that referenced this pull request Jun 25, 2026
…serted

Follow-up to ClickHouse#108129, addressing three review threads about the
distinct-key count that drives the exact-size parallel_hash build. All three
were variants of one root cause: a "this distinct-key count is trustworthy"
signal (the planner `num_distinct_values_from_uniq` flag, and at runtime the
HLL estimate) was set at its origin but kept being trusted after the value was
transformed into something that is no longer a real, fully-inserted distinct
count.

Feed the deferred-build HLL only the keys that are actually inserted.
The estimator was fed the scatter hash of every source row, before `HashJoin`
applies the null-key map and the right-side ON condition. `selectDispatchBlock`
now filters the estimator hashes the same way `insertFromBlockImplTypeCase`
filters inserts (skip NULL keys via the same `extractNestedColumnsAndNullMap`,
and rows failing `getColumnAsMask(..., condColumnNames().second)`), so a
selective right-side ON predicate no longer over-sizes the maps / spill
projection. The buffered blocks and the replay are unchanged, so results are
identical. A zero-copy fast path keeps the common build (no NULL keys, no ON
condition) free of extra work, so the cold mostly-unique build is unaffected.
Addresses ClickHouse#108129 (comment)

Do not trust a filtered relation's key NDV. In the filtered relation profile
the key NDV is clamped by an estimated row count (possibly from default factors
of unrelated predicates) and a filter can drop whole keys, so it is only an
upper bound. `ConditionSelectivityEstimator::estimateRelationProfileImpl` now
clears `num_distinct_values_from_uniq`; only the unfiltered overload yields a
uniq-backed NDV.
Addresses ClickHouse#108129 (comment)

Trust a build-input NDV only from a base relation. A join sub-tree's key NDV
is an estimate (equi-key min-clamp and output-cardinality cap). The
output-cardinality cap now clears the provenance flag when it lowers an NDV,
and `right_input_column_stats` is populated only when the build (right) input is
a base relation (a DP leaf), so `extractTrustworthyRightKeyNdv` falls back to
the deferred HLL build for any derived/joined build input.
Addresses ClickHouse#108129 (comment)

Together these keep `extractTrustworthyRightKeyNdv` to the simple, reliable
case: a single plain equi key of an unfiltered base relation with a real `uniq`
statistic. Verified on a cold 30M-key mostly-unique build that the exact-size
deferred path stays ~1.4x faster than the non-deferred (rehashing) build.

Adds regression tests:
- 04410: a selective right-side ON predicate sizes the build by the inserted
  keys, not by all keys.
- 04411: a filtered right side with only a key `uniq` stat still defers (the
  unfiltered control still preallocates).
- 04412: a multi-join whose build input is a sub-join still defers.

Co-authored-by: Cursor <[email protected]>
harikrishnan94 added a commit to harikrishnan94/ClickHouse that referenced this pull request Jul 24, 2026
…-hash-exact-size-deferred-build

Conflict resolved in `src/Interpreters/HashJoin/HashJoin.cpp`: upstream
extracted CROSS/constant joins out of `HashJoin` (removed `Type::EMPTY`,
`Type::CROSS`, `HashJoin::empty`, the `num_rows` `addBlockToJoin` override,
and moved `getCurrentQueryMemoryUsage` into `JoinCommon`). Kept this
branch's `buildPopsZeroInsertBlocks` and `captureMemoryUsageBaseline`
(switched to `JoinCommon::getCurrentQueryMemoryUsage`), dropped the removed
members following upstream.

PR: ClickHouse#108129
@clickhouse-gh

clickhouse-gh Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 86.30% +0.90%
Functions 91.40% 92.00% +0.60%
Branches 77.40% 78.40% +1.00%

Changed lines: Changed C/C++ lines covered: 492/508 (96.85%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

Dear @m-selmi, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@harikrishnan94
harikrishnan94 force-pushed the parallel-hash-exact-size-deferred-build branch from b0ef983 to faa0fe1 Compare October 21, 2026 12:29
@harikrishnan94
harikrishnan94 changed the base branch from master to uhj October 21, 2026 12:29
Copilot AI balanced review requested due to automatic review settings October 21, 2026 12:29

Copilot AI left a comment

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.

🟡 Changes recommended

Unresolved memory-projection and limit-enforcement issues can cause hangs or memory exhaustion instead of timely spilling or failure.

4 open issues
What changed in this PR

Reduces cold-build rehashing in ClickHouse hash joins through deferred, distinct-key-based preallocation, independently of the compact row-reference changes.

Changes:

  • Adds deferred sizing, bucket reservations, and spill-memory projections.
  • Uses trusted column statistics to bypass deferred builds.
  • Adds settings, metrics, and regression coverage for join behavior, spilling, limits, and cancellation.

Missing context / blind spots: Full builds, regression tests, and performance measurements were not independently run.

File Description
tests/​queries/​0_stateless/​05418_hash_join_deferred_build_plan_ndv_negatives.sql Tests invalidation of trusted distinct counts.
tests/​queries/​0_stateless/​05418_hash_join_deferred_build_plan_ndv_negatives.reference Expected statistics-path results.
tests/​queries/​0_stateless/​05417_hash_join_deferred_build_spill_scheduler.sh Tests adaptive scheduler handover.
tests/​queries/​0_stateless/​05417_hash_join_deferred_build_spill_scheduler.reference Expected scheduler behavior.
tests/​queries/​0_stateless/​05416_hash_join_deferred_build_spill_budget.sql Tests spill thresholds and nullable keys.
tests/​queries/​0_stateless/​05416_hash_join_deferred_build_spill_budget.reference Expected spill-budget results.
tests/​queries/​0_stateless/​05415_hash_join_deferred_build_live_refresh.sh Exercises concurrent projection refresh.
tests/​queries/​0_stateless/​05415_hash_join_deferred_build_live_refresh.reference Expected concurrent-build results.
tests/​queries/​0_stateless/​05414_hash_join_deferred_build_spill_points.sh Tests both spill decision points.
tests/​queries/​0_stateless/​05414_hash_join_deferred_build_spill_points.reference Expected spill transitions.
tests/​queries/​0_stateless/​05413_hash_join_deferred_build_projection.sh Checks projections against actual allocations.
tests/​queries/​0_stateless/​05413_hash_join_deferred_build_projection.reference Expected projection bounds.
tests/​queries/​0_stateless/​05412_hash_join_deferred_build_row_limit.sql Tests distinct-key row limits.
tests/​queries/​0_stateless/​05412_hash_join_deferred_build_row_limit.reference Expected row-limit results.
tests/​queries/​0_stateless/​05411_hash_join_deferred_build_runtime_filters.sql Tests runtime-filter compatibility.
tests/​queries/​0_stateless/​05411_hash_join_deferred_build_runtime_filters.reference Expected runtime-filter results.
tests/​queries/​0_stateless/​05410_hash_join_deferred_build_cold_then_warm.sql Tests transition to cached sizing.
tests/​queries/​0_stateless/​05410_hash_join_deferred_build_cold_then_warm.reference Expected cold/warm allocation events.
tests/​queries/​0_stateless/​05409_hash_join_deferred_build_reserve_bounds.sql Tests masked and skewed-key reservations.
tests/​queries/​0_stateless/​05409_hash_join_deferred_build_reserve_bounds.reference Expected reservation bounds.
tests/​queries/​0_stateless/​05408_hash_join_deferred_build_kinds.sql Covers join kinds, keys, and layouts.
tests/​queries/​0_stateless/​05408_hash_join_deferred_build_kinds.reference Expected join results and eligibility.
tests/​queries/​0_stateless/​05407_hash_join_any_duplicate_only_block.sql Tests duplicate-only block handling.
tests/​queries/​0_stateless/​05407_hash_join_any_duplicate_only_block.reference Expected retained rows.
tests/​queries/​0_stateless/​04695_spilling_hash_join_memory_spill_scheduler.sql Keeps existing scheduler test streaming.
tests/​queries/​0_stateless/​04604_parallel_hash_plan_ndv_clamped_to_row_estimate.sql Tests statistics invalidation after limits.
tests/​queries/​0_stateless/​04604_parallel_hash_plan_ndv_clamped_to_row_estimate.reference Expected limited-build behavior.
tests/​queries/​0_stateless/​04416_parallel_hash_deferred_build_skip_right_full_preserved.sql Tests preservation of unmatched right rows.
tests/​queries/​0_stateless/​04416_parallel_hash_deferred_build_skip_right_full_preserved.reference Expected preserved-row results.
tests/​queries/​0_stateless/​04415_parallel_hash_deferred_build_skip_all_non_regression.sql Tests filtered and duplicate-heavy joins.
tests/​queries/​0_stateless/​04415_parallel_hash_deferred_build_skip_all_non_regression.reference Expected non-regression results.
tests/​queries/​0_stateless/​04413_parallel_hash_deferred_build_multi_nullable_keys.sql Tests composite nullable keys.
tests/​queries/​0_stateless/​04413_parallel_hash_deferred_build_multi_nullable_keys.reference Expected nullable-key results.
tests/​queries/​0_stateless/​04412_parallel_hash_deferred_build_multijoin_right_defers.sql Tests sizing of nested join inputs.
tests/​queries/​0_stateless/​04412_parallel_hash_deferred_build_multijoin_right_defers.reference Expected nested-build behavior.
tests/​queries/​0_stateless/​04411_parallel_hash_deferred_build_filtered_right_defers.sql Tests filtered versus whole-table statistics.
tests/​queries/​0_stateless/​04411_parallel_hash_deferred_build_filtered_right_defers.reference Expected filtered-build behavior.
tests/​queries/​0_stateless/​04410_parallel_hash_deferred_build_on_mask_ndv.sql Tests exclusion of masked keys from sizing.
tests/​queries/​0_stateless/​04410_parallel_hash_deferred_build_on_mask_ndv.reference Expected masked-key reservations.
tests/​queries/​0_stateless/​04409_parallel_hash_deferred_build_plan_ndv_asymmetric.sql Tests build-side statistics selection.
tests/​queries/​0_stateless/​04409_parallel_hash_deferred_build_plan_ndv_asymmetric.reference Expected asymmetric-join sizing.
tests/​queries/​0_stateless/​04408_parallel_hash_deferred_build_cancellation.sh Exercises timeout and query cancellation.
tests/​queries/​0_stateless/​04408_parallel_hash_deferred_build_cancellation.reference Expected cancellation outcomes.
tests/​queries/​0_stateless/​04407_parallel_hash_deferred_build_plan_ndv.sql Tests trusted statistics and self-joins.
tests/​queries/​0_stateless/​04407_parallel_hash_deferred_build_plan_ndv.reference Expected statistics-based reservations.
tests/​queries/​0_stateless/​04405_parallel_hash_deferred_build_ndv_reserve.sql Tests duplicate-aware sizing and spill avoidance.
tests/​queries/​0_stateless/​04405_parallel_hash_deferred_build_ndv_reserve.reference Expected distinct-key sizing results.
tests/​queries/​0_stateless/​04404_04450_spilling_hash_join_two_step_spill_decision.sql Tests final projection-triggered spilling.
tests/​queries/​0_stateless/​04404_04450_spilling_hash_join_two_step_spill_decision.reference Expected end-of-build handover.
tests/​queries/​0_stateless/​04403_parallel_hash_deferred_build_spill_lowcardinality.sql Tests low-cardinality key spilling.
tests/​queries/​0_stateless/​04403_parallel_hash_deferred_build_spill_lowcardinality.reference Expected low-cardinality spill results.
tests/​queries/​0_stateless/​04335_parallel_hash_deferred_build_size_limits.sql Tests size limits and overflow modes.
tests/​queries/​0_stateless/​04335_parallel_hash_deferred_build_size_limits.reference Expected limit behavior.
tests/​queries/​0_stateless/​04328_parallel_hash_deferred_build_spill.sql Tests buffered-block handover correctness.
tests/​queries/​0_stateless/​04328_parallel_hash_deferred_build_spill.reference Expected spill results.
tests/​queries/​0_stateless/​04327_parallel_hash_deferred_build.sql Tests deferred builds across layouts.
tests/​queries/​0_stateless/​04327_parallel_hash_deferred_build.reference Expected results and allocation events.
tests/​queries/​0_stateless/​02151_hash_table_sizes_stats_joins.sh Isolates cached hash-table statistics.
tests/​queries/​0_stateless/​02151_hash_table_sizes_stats_joins_reordered.sh Isolates cached statistics after reordering.
tests/​clickhouse-test Randomizes the deferred-build setting.
src/​Storages/​Statistics/​ConditionSelectivityEstimator.h Adds distinct-count provenance.
src/​Storages/​Statistics/​ConditionSelectivityEstimator.cpp Marks complete-table statistics as trusted.
src/​Processors/​QueryPlan/​QueryPlanSerializationSettings.cpp Registers the serialized setting.
src/​Processors/​QueryPlan/​Optimizations/​RelationStatisticsEstimator.cpp Clears trust after filters and limits.
src/​Processors/​QueryPlan/​Optimizations/​RelationStatistics.h Declares provenance invalidation.
src/​Processors/​QueryPlan/​Optimizations/​RelationStatistics.cpp Invalidates transformed distinct counts.
src/​Processors/​QueryPlan/​Optimizations/​optimizeJoin.cpp Passes trusted build-side statistics.
src/​Processors/​QueryPlan/​Optimizations/​joinOrder.cpp Clears trust for join outputs.
src/​Processors/​QueryPlan/​JoinStepLogical.h Stores trusted right-side counts.
src/​Processors/​QueryPlan/​JoinStepLogical.cpp Selects eligible key statistics.
src/​Planner/​PlannerJoins.h Carries trusted distinct-count hints.
src/​Planner/​PlannerJoins.cpp Enables deferred builds and supplies hints.
src/​Interpreters/​TableJoin.h Exposes deferred-build configuration.
src/​Interpreters/​TableJoin.cpp Initializes the new setting.
src/​Interpreters/​SpillingHashJoin.h Tracks deferred finalization.
src/​Interpreters/​SpillingHashJoin.cpp Integrates projections with spill decisions.
src/​Interpreters/​JoinOperator.h Adds the join setting field.
src/​Interpreters/​JoinOperator.cpp Propagates and serializes the setting.
src/​Interpreters/​HashJoin/​HashJoinMethodsImpl.h Separates deferred preallocation events.
src/​Interpreters/​HashJoin/​HashJoin.h Declares buffering and replay state.
src/​Interpreters/​HashJoin/​DeferredBuild.h Defines sketches and projection interfaces.
src/​Interpreters/​HashJoin/​DeferredBuild.cpp Computes reservations and memory projections.
src/​Interpreters/​HashJoin/​BuildSlots.h Adds per-bucket reservations and growth tracking.
src/​Core/​Settings.cpp Registers and documents deferred building.
src/​Common/​tests/​gtest_hyperloglog_counter_bytes.cpp Tests byte sketches and concurrent merging.
src/​Common/​setThreadName.h Names replay worker threads.
src/​Common/​ProfileEvents.cpp Adds deferred-build profile events.
src/​Common/​HyperLogLogCounter.h Adds atomic byte-register sketches.
src/​Common/​FailPoint.cpp Adds forced projection-refresh failpoint.
src/​Common/​CurrentMetrics.cpp Adds replay thread-pool metrics.
src/​Client/​BuzzHouse/​Generator/​SessionSettings.cpp Adds deferred building to fuzzed settings.

Review effort: Balanced

Comment on lines +46 to +49
chunk = (min_chunk + linear_growth_threshold - 1) / linear_growth_threshold * linear_growth_threshold;
chunk = (chunk + page_size - 1) / page_size * page_size;
allocated += chunk;
usable += chunk - min_chunk;
Comment on lines +218 to +221
const double distinct_share = std::min(1.0, static_cast<double>(projection.estimate) / static_cast<double>(projection.rows));
for (size_t slot = 0; slot < num_slots; ++slot)
{
slot_demand[slot] += static_cast<size_t>(std::ceil(static_cast<double>(projection.slot_key_bytes[slot]) * distinct_share));
Comment thread src/Interpreters/HashJoin/HashJoin.cpp Outdated
Comment on lines +1349 to +1352
size_t total_bytes = getTotalByteCount();
updatePeakBuildBytes(total_bytes);
shrinkStoredBlocksToFit(total_bytes, /*force_optimize=*/false, context.getStream());
return true;
Comment thread src/Interpreters/SpillingHashJoin.cpp Outdated
if (hash_join->defersBuild())
{
const auto projected_bytes = static_cast<Int64>(hash_join->getProjectedBuildBytes(/*all_blocks_stored=*/false));
res.need_reserved_memory_bytes = std::max<Int64>(projected_bytes - res.spillable_memory_bytes, 0);

const size_t empty_bucket_bytes = shape.bucket_buffer_bytes(0);
for (const size_t reserve : projection.bucket_reserves)
bytes += shape.bucket_buffer_bytes(reserve) - empty_bucket_bytes;

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.

[P1] Include bucket growth in the spill projection

bucket_reserves does not bound the buffers after insertion: deferredBuildBucketReserves caps each bucket at four even shares of the global distinct count. For 1M distinct UInt64 keys whose CRC hashes all select bucket 0, this reserves about 15K entries (32K cells), but replay needs about 2M cells in that bucket. With one terminal input block, the live check sees an empty build; the final projection includes only the small reservation and can stay below a 24 MiB spill threshold while the built join exceeds 40 MiB. SpillingHashJoin::runPostBuildPhase has already selected IN_MEMORY_JOIN before those inserts, so growth cannot trigger spilling and can instead hit max_memory_usage.

Please conservatively project the buffers after insertion, or keep spill checks available during replay. Cover distinct-key bucket skew in a single final block; duplicate hot-key coverage does not exercise this case.

## Motivation

A hash join builds hash tables from the right side and probes them with the left side. Today `HashJoin::addBlockToJoin` stores each right block and inserts its keys into the map at once. Each map cell holds a key and a reference to its row (block number and row number).

The size of the maps is known in advance in three cases:
- `collect_hash_table_stats_during_joins` (on by default) recorded the size of the same join in an earlier run, in the hash table statistics cache.
- A bucket of `grace_hash` takes the number of keys of the previous bucket.
- With this change, the right join key has a `uniq` or `uniq_v2` column statistic (see below).

Otherwise the build is cold: the first run of a join, an evicted statistics entry, or the statistics turned off. A cold build starts each table at 256 cells, and each resize rehashes every key of the table:
- The two-level layout has 256 tables, one per bucket. The join uses it when the right side has `parallel_hash_join_threshold` rows or more, or no row estimate. A bucket resizes when more than half of its cells are used, and grows 4 times while it has fewer than 2^15 cells, then 2 times. At 2^16 cells it switches to Robin Hood mode in place, and from then on it fills to 90% before it doubles.
- Below the threshold, the join fills one table on one thread (the serial layout). It resizes when more than half of its cells are used, and grows 4 times while it has fewer than 2^23 cells, then 2 times.

In cold `INNER` and `RIGHT` joins with 10^8 right rows, these resizes make the query up to 1.2 times as slow on the two-level layout (1.12 to 1.14 times at the median). On the serial layout they make it up to 1.8 times as slow, but a right side that large gets the serial layout only with a raised `parallel_hash_join_threshold` or a row estimate that is far too low.

## Design

During `addBlockToJoin`, a deferred build only stores the right blocks, and counts their distinct keys while they arrive. After the last block, it reserves each map once for that count and inserts the stored blocks. A reserve for n keys gives a table that holds n keys without a resize: at most half full, or 90% full for a two-level bucket of more than 2^16 cells. So the inserts resize a table only when the count was too low.

### Counting the distinct keys

`HashJoin::addBlockToJoin` is split into `storeBlock` and `insertStoredBlock`. A deferred build calls only `storeBlock`, then counts the block in `addPendingInsert`. Each build stream keeps, per ON clause:
- a HyperLogLog sketch with 2^13 byte registers (8 KiB, standard error about 1.15%). It takes the low 32 bits of the hash that the map uses, mixed with the MurmurHash3 finalizer, so a CRC hash still gives independent register indexes and ranks;
- the number of rows per bucket of the map, and the bytes of the string keys per bucket.

Only the rows that the insert takes are counted: a NULL key, or a row that fails the right-side ON condition, is skipped. The estimate is the merged sketch of all streams, capped at the number of counted rows.

`HyperLogLogCounter` gets the byte registers, written with relaxed atomic stores, `mergeLive` to read a sketch while its stream writes it, and a flag that tells whether an insert raised a register. Its default parameters keep the current code, and its existing users compile to the same instructions.

### Reserving and inserting

In the post-build phase, the build reserves each bucket from the estimate e and its own counted rows r. With one bucket (the serial layout), the reserve is min(e, r). With 256 buckets, let s be e / 256, the even share of a bucket. A bucket reserves its share of e by its rows, but at least s + 4·sqrt(s), at most 4·s, and never more than r. The lower bound covers the spread of evenly hashed keys. The upper bound keeps a bucket full of duplicates of one hot key from reserving for keys it does not have. A bucket that gets more keys than its reserve grows as in a streaming build.

Then the stored blocks are inserted, with min(build streams, stored blocks) threads. Each thread takes the next stored block of any stream and inserts it through the slot locks. With one thread, the blocks are inserted in the order they were stored.

### When the build defers

The build defers when `enable_hash_join_deferred_build` is on (the default) and all of the following hold:
- The size is not known in advance (see above).
- The join is not `join_overflow_mode = 'break'` with a size limit: `break` stops at the block that crosses the limit, so the limit must be checked as the blocks arrive.
- The map is not one that has all its cells from the start (`key8`, `key16` and the fixed-range maps).
- Until the inserts, the deferred build holds no more than the streaming build. The next two conditions make this exact.
- The stored blocks hold every right key as a plain column. The streaming build stores the keys of an `INNER` or `LEFT` join only when the join may spill (`max_bytes_before_external_join` or `max_bytes_ratio_before_external_join`), has `OR` conditions, or has a condition on both tables that the join evaluates itself. `RIGHT` and `FULL` joins always store them. A right key that the join outputs can be stored in the row store instead; then the build does not defer either.
- The map keeps every right row (`ALL` and `ASOF` maps). `INNER` and `LEFT` `ANY` joins, `LEFT SEMI` joins and `LEFT ANTI` joins keep at most one row per key. Their streaming build drops a block that adds no new key as soon as the block arrives, while a deferred build would hold it until the inserts.

### Sizes from column statistics

The planner can now take the size from a `uniq` or `uniq_v2` statistic of the right key. This needs a single join key that is a column of the right table, read with no filter, limit or aggregation in between, and the statistic in every part of the table. The planner marks such distinct counts where it reads the statistics. It keeps the mark through aliases, `materialize` and `toNullable`, and clears it at any other function or cast, at a filter, a limit, an aggregation and a join. After it chooses the join order, it passes the marked count of the build side to the join. Such a build streams, and the two-level layout reserves from the count, as with the statistics cache.

### Spilling

A deferred build has no maps while the blocks arrive, so `SpillingHashJoin` compares the spill threshold with a projection of what the build will hold. The projection is the stored blocks plus:
- the buffers of the reserved buckets;
- the distinct string keys that the maps copy into the arenas, from the bytes of the counted keys;
- the row list nodes of the keys with duplicates, from the estimate and the rows;
- the null maps that the inserts add for `RIGHT` and `FULL` joins.

The arena terms follow the chunk growth of `Arena`, per slot. While the blocks arrive, the projection uses the counts that the streams have published, with the rows spread evenly over the buckets. It is recomputed by one thread at a time, each time the stored rows have grown by 1/16 since the last recompute. At the end of the build it uses the final counts. When the projection reaches the threshold, the join switches to `GraceHashJoin` before any key is inserted and hands it the stored blocks. When the plan needs the order of the left rows, it switches to `MergeJoin` instead, as a streaming build does. The existing switch at twice the stored bytes stays.

For the memory spill scheduler, a deferred build reports the bytes that its inserts will allocate as memory it needs. So the scheduler can also hand the stored blocks to `GraceHashJoin` or `MergeJoin` before the inserts.

### Limits and cancellation

With `join_overflow_mode = 'throw'`, the size limits are checked once, after the inserts, against the keys and bytes that the join holds then. So a deferred build accepts and rejects the same joins as a streaming build. Every inserting thread checks `KILL QUERY` and `max_execution_time` before each block.

### Events

`HashJoinDeferredBuilds` counts the deferred builds, `HashJoinDeferredPreallocatedElementsInHashTables` the keys they reserved, and `HashJoinDeferredBuildBucketsGrown` the buckets that grew past their reserve. `HashJoinPreallocatedElementsInHashTables` now also counts the reserves made from a `uniq` statistic.

## Caveats

### Memory

The keys are stored anyway whenever the build defers, so a deferred build holds the same stored blocks as the streaming build until its inserts. On top of that it holds, per build stream and ON clause, an 8 KiB sketch and two 64-bit counters per bucket, and the right-side ON condition columns of each block until it is inserted.

Without a spill threshold, the streaming build of an `INNER` or `LEFT` join on key equalities drops the key columns, because the maps hold the keys. A deferred build would have to keep a key for every right row until the inserts, also for the duplicates that take no cell of their own. So such joins do not defer.

### Behavior

- Query results do not change. Without `ORDER BY`, the joined rows can come in another order when several threads insert, as with any parallel build.
- A join over a `throw` size limit fails only after the whole right side is read and inserted.
- The sketch counts distinct 32-bit hashes, so it reads low when keys collide in them: about 6% low for 10^8 distinct structured string keys. Then some buckets grow past their reserve, and `HashJoinDeferredBuildBucketsGrown` counts them.
- The counting and the deferred inserts have a fixed cost. In builds of 10^5 to 10^7 rows, mostly at 96 threads, some joins are up to 1.1 times as slow, by at most a few milliseconds.

## Changelog category

- Performance Improvement

## Changelog entry

Hash joins no longer rehash their hash tables as they grow on a cold build, when no statistics give the size of the hash tables in advance (the first run of a join, or `collect_hash_table_stats_during_joins = 0`). The build stores the right side first, counts its distinct keys while it arrives, and reserves each hash table once for that count. Cold `INNER` and `RIGHT` joins with large right sides get up to 1.2 times faster with the default layout. The setting `enable_hash_join_deferred_build` controls it.

Closes: ClickHouse#111268

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@harikrishnan94
harikrishnan94 force-pushed the parallel-hash-exact-size-deferred-build branch from ca7a617 to c4918f8 Compare November 3, 2026 05:01
@harikrishnan94
harikrishnan94 deleted the branch ClickHouse:uhj November 3, 2026 08:17
@harikrishnan94 harikrishnan94 reopened this Nov 3, 2026
@harikrishnan94
harikrishnan94 changed the base branch from uhj to master November 3, 2026 08:23
@harikrishnan94 harikrishnan94 reopened this Nov 3, 2026
harikrishnan94 and others added 3 commits November 3, 2026 14:26
`Fast test` failed both:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108129&sha=c4918f8a5b721ecb252545db1aaaf64750c36f1b&name_0=PR&name_1=Fast%20test

`04412` checks that a join whose right input is another join defers its build. The join order optimization now puts a
table on the right of both joins, so neither of them defers. The nested join is now a subquery on the right of the join
with `t_c`, and swapping is off so it stays there.

`05340` came in from master with the rebase. It needs the memory spill scheduler to switch the join, but a deferred
build reserves the map once and peaks at 49 MB instead of 81 MB, under the 105 MiB limit, so the scheduler never acts.
The test now turns the deferred build off, as `04695` does. `05417` covers the scheduler with a deferred build.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The tests choose the layout with `hash_join_layout` instead of pinning `parallel_hash_join_threshold`, as the tests
from master do. `05412` drops a `max_rows_in_join` case that its other cases cover, and `04405` a `SET` that repeated
an earlier one.

`DeferredBuildState::projectedBytes` keeps one largest allocation for all slots, because every slot got the same
value. `deferredBuildBucketReserves` takes the share of the clamped estimate, which is what every caller passes.
`addPendingInsert` loses a lambda that it called once per clause.

The rest rewords comments and the description of `enable_hash_join_deferred_build`. The distinct keys are estimated,
not counted, and a switch goes to the external join, `GraceHashJoin` or `MergeJoin`. The description now also says
that a condition on both tables makes an `ANY`, `SEMI` or `ANTI` join defer, and that `auto` or `grace_hash` in
`join_algorithm` keeps the keys like a spill threshold does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`arenaBytes` looped forever when one allocation took almost a whole 128 MiB chunk, for example a key of 128 MiB - 63
bytes in a `RIGHT` join. It credited the chunk with less room than the allocation it was added for. A chunk now holds
at least that allocation, as in `Arena::addMemoryChunk`.

At the end of the build, `SpillingHashJoin` kept the join in memory whenever the projected size was below the spill
threshold. The projection is an estimate. When the frequent keys are short and the rare keys long, or a bucket gets
far more keys than it reserved, the maps hold more than projected. Now the join inserts the stored blocks, compares
what the maps hold with the threshold, as the streaming build does after its last block, and switches to the external
join if they reach it. `HashJoin::insertDeferredBlocks` does the inserts, and `defersBuild` is false after them.

`max_bytes_in_join` was checked only after the inserts, so a join over the limit first read and inserted its whole
right side. Each block now checks it against the stored blocks, which the streaming build holds too. The row limit
still waits for the inserts, which count the keys.

The memory spill scheduler was told that a deferred build needs only what its inserts add. A switch converts the
stored blocks instead, so the build now asks for the larger of the two.

The planner kept the `uniq` mark of a key column for reads that drop or change rows inside `ReadFromMergeTree`:
`FINAL`, `SAMPLE`, a row policy, a `UNIQUE KEY`, deleted rows, patch parts, mutations applied on the fly, masking
policies, and a read split between parallel replicas. Such a build reserved for every value that the parts store.
`readsPartsAsStored` now clears the mark for these reads, and their builds defer.

`enable_hash_join_deferred_build` is written into a serialized plan only for a peer at plan version 21 or above, like
`hash_join_layout`.

Tests `05484` to `05490` cover these cases. Each of them fails without its fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
join_step->setInputRelations(relation_infos[left_rels], relation_infos[right_rels]);
std::unordered_map<String, UInt64> right_distinct_values_from_uniq;
for (const auto & [column_name, stats] : (flip_join ? entry->left : entry->right)->column_stats)
if (stats.num_distinct_values_from_uniq)

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.

[P2] Clear trusted distinct counts across row-dropping array joins

This flag can still describe the table before an ARRAY JOIN. In estimateReadRowsCount, the ArrayJoinStep branch keeps the statistics of unaffected columns, and the expression form keeps an input column through remapColumnStats. Both can remove rows with empty arrays. For example, if r(k UInt64 STATISTICS(uniq), a Array(UInt8)) has one million distinct keys but only 100 nonempty arrays, (SELECT k FROM r ARRAY JOIN a) supplies only 100 build keys, while this code forwards approximately one million as trusted. The estimated row count is multiplied by 100, so the later clamp does not correct it.

With hash_join_layout = 'parallel', cached join statistics disabled, and spilling disabled, the new shortcut preallocates for the whole table instead of those 100 keys, potentially exhausting the query memory limit. Please clear this provenance when either representation of an array join can drop input rows, and cover empty arrays and element filters.

if (!lhs.fromLeft() || !rhs.fromRight())
return {};

const auto right_key = rhs.resolveAliases();

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.

[P2] Validate the distinct-count hint after join-key conversion

The input-column check runs before buildPhysicalJoinImpl normalizes the equality keys. For an Int64 right key joined to a UInt64 left key, predicateOperandsToCommonType subsequently inserts accurateCastOrNull to the common subtype. Negative right keys become NULL, and hash-table insertion skips them. A right table with one million distinct negative keys and 100 nonnegative keys therefore supplies a trusted hint of approximately one million although only 100 keys enter the map.

The hint disables deferred counting and, with the parallel layout, preallocates for all those rejected values. With spilling disabled this can exhaust memory for a join whose actual map is tiny. Please invalidate the hint when physical planning introduces a value-dropping key conversion, or determine eligibility after normalization, and add a signed/unsigned-key regression.

}

for (size_t slot = 0; slot < num_slots; ++slot)
bytes += arenaBytes(slot_demand[slot], max_allocation);

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.

[P2] Project each arena with its own maximum allocation

max_allocation is shared across all slots, so one long string key makes this loop budget a chunk large enough for that key in every nonempty slot. For example, force the parallel layout with 16 slots and 1,000 distinct String keys: one 1 MiB key and 999 short keys. The long key is copied into only one arena, and the short keys need only small chunks elsewhere. The build fits an 8 MiB spill threshold, but this loop projects over 16 MiB of arena chunks alone and switches it to GraceHashJoin.

This happens even with unique keys and ordinary bucket distribution, and the overestimate grows with the slot count. Please carry the maximum allocation per slot instead of applying the global maximum everywhere, and add a regression that this otherwise fitting build does not spill.

The flaky checks failed both, for example:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108129&sha=f22aee018a4238d34e30163d6d46a4feef4550a9&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20flaky%20check%29
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108129&sha=f22aee018a4238d34e30163d6d46a4feef4550a9&name_0=PR&name_1=Stateless%20tests%20%28amd_binary%2C%20flaky%20check%29

`05410` checks that the second run of a join takes its size from the statistics of the first run. Random settings can
turn the join order optimization off with `query_plan_optimize_join_order_limit = 0`. Then the join gets no key for
its statistics, and both runs are cold. The test now pins the limit, as `02151_hash_table_sizes_stats_joins_reordered`
and `04357` do.

`05416` ran for more than 180 s. Its spill threshold of 1 MiB made `GraceHashJoin` split the right side into up to 512
parts, and such a query took up to 860 MiB, with a streaming build as with a deferred one. Many copies of the test at
once then wait for memory. The threshold is now 3 MiB, which every deferred build in the test still reaches, and the
queries over it take at most 137 MiB. Only 2400 left strings match now, so the joins on the string key return 274286
rows instead of 9143324.

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

clickhouse-gh Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 04b035f00 with master bf8a006e4 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of a8e6d0bf4; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

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 ⚠️

160 object files changed (+1.26 MiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/HashJoin.cpp.o 4.10 MiB 4.79 MiB +703.70 KiB (+16.76%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/DeferredBuild.cpp.o new 55.66 KiB +55.66 KiB
src/CMakeFiles/dbms.dir/Interpreters/SpillingHashJoin.cpp.o 167.15 KiB 184.45 KiB +17.29 KiB (+10.35%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinAny.cpp.o 1.73 MiB 1.74 MiB +16.11 KiB (+0.91%)
src/CMakeFiles/dbms.dir/Interpreters/HashJoin/LeftHashJoinRightAny.cpp.o 1.73 MiB 1.74 MiB +16.10 KiB (+0.91%)

719 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

752 translation units recompiled, 6220 s compile time in total, 751 of them have a recent master baseline.

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse-keeper ProfileEvents::global_counters_storage 14.25 MiB 14.31 MiB +64.00 KiB (+0.44%)
programs/clickhouse ProfileEvents::global_counters_storage 14.25 MiB 14.31 MiB +64.00 KiB (+0.44%)

Job report

`Build (wasm64)` failed with `-Wlifetime-safety-return-stack-addr` in `HashJoin::storeBlock`:
https://s3.amazonaws.com/clickhouse-test-reports/PRs/108129/356dcbe873f146ea36c763e91a377f5591db21e9/pr/build_wasm64/build_clickhouse/build_clickhouse.log

The function returned an iterator that it took from the local list before `splice` moved the node into the list of
the build stream. The node does not move in memory, but the compiler sees the address of a local. It now returns the
last element of the list of the build stream, which is where `splice` put the node.

`Stateless tests (amd_binary, flaky check)` failed `05414` once in 44 runs:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108129&sha=356dcbe873f146ea36c763e91a377f5591db21e9&name_0=PR&name_1=Stateless%20tests%20%28amd_binary%2C%20flaky%20check%29

The first case reads 16 right blocks with four streams. With `enable_join_runtime_filters = 0`, in about 1 run of 10,
the streams stored 8 blocks, half of the spill threshold, before one of them checked the projected size. The join then
switched on its stored bytes, which is also correct, but the test looks for the message of the projection. The case
now reads with one thread, so every block checks the projection first.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@harikrishnan94
harikrishnan94 marked this pull request as draft November 4, 2026 04:05
@harikrishnan94 harikrishnan94 changed the title Exact-size parallel_hash build to avoid rehashing on cold builds Exact-size JOIN Hashtable build to avoid rehashing on cold builds Nov 4, 2026
…ows them

`Performance Comparison (arm_release, master_head, 2/6)` and its `amd_release` twin failed on
`lazy_materialization_join`:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108129&sha=356dcbe873f146ea36c763e91a377f5591db21e9&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%202%2F6%29

The two queries with parallel builds join a table of 40 million rows with dimensions of 50,000 keys. They were 18% to
22% slower, and the extra time was in the probes, not in the builds. A deferred build reserved each bucket of the
two-level map for its keys, and `HashTable::reserve` makes a table at most half full: 512 cells for the 195 keys of a
bucket. The streaming build quadruples a small table when it is half full, so it ends with 1024 cells, 19% full. A
lookup of a missing key walks to an empty cell in a table of fewer than 2^16 cells, so the denser table took 1.45 times
the CPU time to probe. This shows only for 40,000 to 50,000 keys. For fewer and for more keys, both builds end with the
same size.

A table of up to 2^16 cells now reserves the size that the streaming build grows it to. `deferredReserveKeys` finds
that size with the grower, and the size projection of the spill check uses it too. A larger table keeps the exact size.
The build still does not rehash, and a small table can be twice as large as an exact one.

On one binary with `enable_hash_join_deferred_build` off and on, at 16 threads, the two queries went from 1.156 and
1.165 times as slow to 0.981 and 0.991. For right sides of 5,000 to 1,000,000 keys, the probe time is no higher than
that of the streaming build.

Co-Authored-By: Claude Sonnet 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 comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... performance pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[RFC] Exact-size parallel_hash sizing

5 participants