Repository navigation
Compress hash join right-side blocks in memory before OOM / spilling - #107667
alexey-milovidov wants to merge 140 commits into
Conversation
Re-implementation of the idea from PR #63696 ("Added possibility of compressing in HashJoin") against the current `HashJoin`/`ScatteredBlock` architecture, with the direction adjusted so compression is an adaptive step taken *before* an out-of-memory condition or spilling to disk, and so it covers `hash`, `parallel_hash` and `grace_hash` (which all build on the same `HashJoin`). New settings: - `enable_join_in_memory_compression` (Bool, default false): when a hash-based join hits memory pressure (the same trigger as block shrinking: more than half of `max_bytes_in_join`, or half the query memory limit), compress the stored right-side blocks instead of only shrinking them. Wired through both the legacy `Settings` path and the analyzer `JoinSettings` / `QueryPlanSerializationSettings` path. - `join_decompressed_columns_cache_bytes` (UInt64, default 128 MiB): bounds the per-join cache of decompressed right-side blocks used during the probe phase. Build side: `shrinkStoredBlocksToFit` and the shrink-on-insert path in `addBlockToJoin` compress stored columns (`IColumn::compress`) when the setting is on, setting `have_compressed`. Reranging is skipped for compressed data. Probe side: stored `ColumnsInfo` are decompressed on demand through a thread-safe `CacheBase` keyed by the stored block pointer (so a block is decompressed once and reused). The lazy `buildOutputFromBlocks` path, the limit/offset path, `joinGet`, the non-lazy ANY path, and the RIGHT/FULL non-joined-rows streams all translate stored pointers through the cache; `buildOutputFromRowRefLists` (which reads raw `RowRefList` pointers) is bypassed when compression is active. Performance (measured, 2M-row 1:1 `INNER JOIN`, full payload through the join): compressible payload shrinks the build side ~2.4x (402 -> 168 MiB) at ~1.85x probe time; incompressible payload saves no memory but still costs ~1.5x. Hence the feature is opt-in and only triggers under memory pressure: it lets a memory-bound compressible join complete in memory instead of failing or spilling. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Refine `enable_join_in_memory_compression` so a stored right-side column is kept in compressed form only when compression reduces its data by at least 10% (`IColumn::compress(force_compression=true)` followed by a size check against `byteSize`); otherwise the column is just shrunk to fit (`cloneResized`). This means barely- or in-compressible columns stay directly readable and incur no probe-time decompression cost, and `have_compressed` (which routes the probe through the decompression-aware path) is set only when something actually compressed. `shrinkStoredBlocksToFit` now returns early when blocks are already compressed, so the `force_optimize` path (`StorageJoin::optimize`) does not attempt to `cloneResized` a `ColumnCompressed` (which would throw). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [466751d] Summary: ❌
AI ReviewSummaryAdds opt-in compression of stored right-side blocks for hash-based joins, with a configurable byte threshold, decompression during probing, and streaming handoff during spilling. No actionable findings remain on Representation consumers traced: ordinary/ The Fast test report reports all 13 compression regression tests passing, including pending-stream and concurrent-activation cases. Missing context / blind spots
Final VerdictStatus: ✅ Approve |
…lgorithm `HashJoin::releaseJoinedBlocks` returned stored columns as ordinary `Block` columns, but with `enable_join_in_memory_compression` those columns can be `ColumnCompressed`. The spill / algorithm-switch consumers (`SpillingHashJoin` switching to `GraceHashJoin`, `GraceHashJoin` bucket rehashing, `JoinSwitcher`, `ConcurrentHashJoin` slot release) then read them as ordinary columns and hit `ColumnCompressed must be decompressed before use`. Decompress the stored columns in both the scattered (non-restructure) and restructure paths; `decompress` is a cheap no-op for columns that were only shrunk. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`buildAdditionalFilter` materialized right-side values straight from the stored `ColumnsInfo` via `getBlockColumnAndRow`. With `enable_join_in_memory_compression` an extra `JOIN ON` predicate that reads a compressed right column (e.g. `... ON l.k = r.k AND r.pad = 'x'`) passed a `ColumnCompressed` to `insertFrom` and raised `ColumnCompressed must be decompressed before use` instead of evaluating the filter. Route those reads through the same `DecompressResolver` / decompressed-blocks cache that the output paths already use: move `DecompressResolver` to `AddedColumns.h`, expose `getColumnAndRow`, and drop the now-unused `getBlockColumnAndRow`. The resolver is a transparent pass-through when nothing was compressed. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`04357_join_in_memory_compression_edge_cases` covers the two surfaces that read stored right-side blocks directly and must be decompression-aware: - an extra `JOIN ON` predicate over a compressed right column, evaluated by `buildAdditionalFilter`; - `releaseJoinedBlocks` when a `hash` join compresses under `max_bytes_in_join` pressure and then spills to `GraceHashJoin` (the build-side blocks, and the grace buckets while rehashing, are released as `ColumnCompressed`). Also rename the feature test from `04341` to `04356` to resolve a test-number collision with `04341_distributed_plan_join_function_key_type_mismatch` that was added on master. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…alFilter The first case of `04357_join_in_memory_compression_edge_cases` used an INNER JOIN with the residual `length(r.pad) > l.lv % 2000`. For an INNER JOIN the analyzer turns such a residual into a post-join `Filter` over the already-materialized (decompressed) output, so it never reaches `buildAdditionalFilter` and reads no stored `ColumnCompressed`. Verified by A/B: against the pre-fix build that case returned the correct result instead of throwing, i.e. it did not cover the bug. Switch it to a LEFT JOIN with the cross-side residual `r.pad != toString(l.lv)`. In a LEFT JOIN the residual decides matching, so it stays a residual join filter (`EXPLAIN` shows `Residual filter: notEquals(pad, toString(lv))`) evaluated by `buildAdditionalFilter`; referencing both sides keeps it from being pushed to the right-table scan. Against the pre-fix build this now fails with `ColumnCompressed must be decompressed before use` (the additional-filter blocker), and equals the uncompressed result after the fix. `enable_analyzer = 1` is pinned at the top level because residual `JOIN ON` conditions are only supported by the analyzer (and a per-subquery override is rejected under the old-analyzer run). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`ConcurrentHashJoin::onBuildPhaseFinish` splices each non-zero slot's stored columns into slot 0 (the two-level-map merge), after which probing reads everything through slot 0. But `have_compressed` is a per-`HashJoin` flag, so if a non-zero slot compressed its blocks (`enable_join_in_memory_compression`) while slot 0 did not, slot 0 ends up holding `ColumnCompressed` with `have_compressed` still false and the probe reads them as ordinary columns, raising `ColumnCompressed must be decompressed before use`. Synchronize the flag into slot 0 during the merge (mirroring the existing `all_values_unique` sync) via a new `HashJoin::setHaveCompressed`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`TableJoin`'s `JoinSettings` constructor (the analyzer / `JoinStepLogical` path) initialized `max_memory_usage` from `settings.max_bytes_in_join`, so the documented secondary compression/shrinking trigger (half of the query memory limit) was dead on that path: with `enable_join_in_memory_compression = 1`, `max_memory_usage = ...`, `max_bytes_in_join = 0` the join never compressed. Add `max_memory_usage` to `JoinSettings` (populated from `Setting::max_memory_usage` and carried through query-plan serialization) and use it in the constructor, matching the old-analyzer `TableJoin(Settings)` path. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Standalone `grace_hash` inserts into its in-memory bucket with `check_limits = false`, which returns from `HashJoin::addBlockToJoin` before `shrinkStoredBlocksToFit`, so the bucket never compressed under `enable_join_in_memory_compression` (contrary to the documented contract) — it only rehashed/spilled. When a bucket overflows, try compressing it (`shrinkStoredBlocksToFit` with `force_optimize`) before rehashing; if compression brings it back under the limit the bucket stays in memory, like `hash`. Only the standalone path is affected (`SpillingHashJoin`-driven grace already compresses in its inner `HashJoin` before handing blocks over). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Count the right-side join columns kept compressed in memory by `enable_join_in_memory_compression` (incremented in `compressColumnIfWorthwhile` when a column actually shrinks and is stored compressed). This gives observability into when in-memory join compression triggers and lets regression tests assert that compression really happened rather than only that results are unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ace_hash `04358_join_in_memory_compression_contract` forces `enable_join_in_memory_compression` under memory pressure for `parallel_hash` (slots compress and are merged into slot 0 via two-level maps) and standalone `grace_hash` (the active in-memory bucket), checking both that the compressed result equals the uncompressed one and, via the `JoinInMemoryCompressedColumns` profile event, that compression really happened. The `grace_hash` case fails without the bucket-compression fix (the event stays zero). The analyzer `max_memory_usage` trigger is fixed too but is not asserted here: its firing depends on total query-memory growth, which in a small test is dominated by the uncompressible hash table rather than the compressible stored blocks, leaving no robust threshold to assert. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… join-in-memory-compression
…ression # Conflicts: # src/Interpreters/HashJoin/HashJoin.h
`04358_join_in_memory_compression_contract` failed the style check because it used the global `SYSTEM FLUSH LOGS` form, which is forbidden in stateless tests; replace it with the per-log `SYSTEM FLUSH LOGS query_log` form. The `parallel_hash` scenario asserts that compression keeps the join under `max_bytes_in_join`, but `clickhouse-test`'s randomized block-size / memory settings shift the per-slot footprint and make that threshold flaky (observed `SET_SIZE_LIMIT_EXCEEDED` under some seeds). Add a `-- Tags: no-random-settings` line so the test runs against the documented thresholds. The plain-`hash` tests (04356, 04357) use a single hash table and are not affected. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Merging `master` brought in tests that already use the 04356/04357/04358 prefixes (the `geojson` family, `nullable_tuple_beta`, etc.), so renumber the three feature tests to the next free numbers to avoid colliding prefixes: 04356_join_in_memory_compression -> 04402 04357_join_in_memory_compression_edge_cases -> 04403 04358_join_in_memory_compression_contract -> 04404 `log_comment` values inside the contract test are updated to match the new number. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Shepherd pass on this PR. Pushed Pushed (CI-unblocking + housekeeping only — no algorithm changes)
All three renumbered tests pass locally; the three core join TUs syntax-check clean against current Not pushed — left for you (the two open
|
`04404_join_in_memory_compression_contract` failed only on the `Stateless tests (amd_llvm_coverage, old analyzer, ...)` job with `SET_SIZE_LIMIT_EXCEEDED` on the `parallel_hash` case, while passing on every other config (all sanitizers, and the other coverage jobs, which use the analyzer). The scenarios use `query_plan_join_swap_table = 'false'` to force the right (compressible) table as the build side, but that is an analyzer / query-plan-only setting: under the old analyzer it is a no-op, so the build-side choice (and therefore the per-slot footprint) is undefined and the tight `max_bytes_in_join` limit can be exceeded before compression catches up. Pin `enable_analyzer = 1` on both outer queries, matching the sibling test 04403 which uses the same approach and passes on the old-analyzer job. The old-analyzer compression path itself stays covered by 04402, which is not analyzer-pinned. CI report: #107667 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ed `HashJoin` `master` removed `ConcurrentHashJoin`: `parallel_hash` is now a `HashJoin` with several build streams that share one `RightTableData`. The PR's changes to `ConcurrentHashJoin` are dropped and the in-memory compression is reworked for the build streams: - `join_in_memory_compression_min_bytes` applies to the whole join (the shared atomic `allocated_size`), no longer divided between slots, so `setInMemoryCompressionMinBytes` is gone. - The decision to compress is a CAS on `compress_stored_blocks`, like `shrink_blocks`. Each build stream compresses only its own list (`BuildStreamData::compression_done`), the one that passed the threshold right away and the others before they store their next block. - `have_compressed` and the compression statistics are atomics, set by any build stream; there is one `HashJoin`, so no synchronization between slots at the end of the build is needed. - `shrinkStoredBlocksToFit` skips a build stream whose blocks are compressed. - `releaseBuildStreamBlocks` returns `ReleasedJoinedBlocks` too, so `SpillingHashJoin` streams the blocks of each build stream out one at a time, decompressing them as it goes. - The duplicate `materializeStoredBlock` is dropped in favour of the one on `master`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged
The CHANGES_REQUESTED review from @rschu1ze, asking for the direction to be discussed with the join team first, is still open. That decision has to come from a human. |
… idle build streams With several build streams (`parallel_hash`, or `hash` reading the right side in several streams), a build stream decided to compress only after storing its block. A concurrent build stream that had already stored its own block uncompressed was counted at its full size by the first one's `max_bytes_in_join` check, so the join threw `SET_SIZE_LIMIT_EXCEEDED` even though compression would have fit it (failures of `04492_join_in_memory_compression`, `04493_...`, `05443_...` in the flaky check and targeted runs). - The decision now counts the block about to be stored, so it is made before the block is stored; with `join_in_memory_compression_min_bytes = 0` every block is compressed on insertion. - A build stream that stored a block while another one decided to compress compresses it right after the insert instead of waiting for its next insert, which may never come. - `onBuildPhaseFinish` compresses the build streams that finished before compression started (review: #107667 (comment)). CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107667&sha=latest&name_0=PR&name_1=Stateless%20tests%20(arm_asan_ubsan%2C%20targeted) PR: #107667 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…mpty_right_side` The randomized `enable_join_in_memory_compression = 1` compresses the highly compressible right side of the all-filtered `FULL ALL` query below `max_bytes_before_external_join`, so it legitimately stays in memory and the check for the switch to `GraceHashJoin` fails. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107667&sha=latest&name_0=PR&name_1=Stateless%20tests%20(amd_asan_ubsan%2C%20db%20disk%2C%20distributed%20plan%2C%20targeted) PR: #107667 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged
All the PR's tests (plus |
|
🕵 All CI checks on The CHANGES_REQUESTED review from @rschu1ze, which asks for the direction to be discussed with the join team first, is still open. That decision has to come from a human. |
# Conflicts: # src/Interpreters/HashJoin/HashJoin.cpp
The row-store string support from master added a `block` local in the bytes-limit accounting that shadows the `block` resolved for in-memory compression. Rename it to `row_store_block`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tore_strings` The test checks that a row store is built, but in-memory compression of the right-side blocks disables the row store, so the test failed when the setting was randomized to `1`. Pin it to `0`, as done for the other row store tests. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107667&sha=ec00d6754b3f2ce4eeb5cf4b9c6198a01c7eb593&name_0=PR PR: #107667 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged |
Address review: with a nonzero `join_in_memory_compression_min_bytes`, a build stream could store its last block uncompressed before another stream latched compression. That block was caught up only in `onBuildPhaseFinish`, so the `max_bytes_in_join` check of the other stream (and the spill decisions of `SpillingHashJoin`, `GraceHashJoin`, `JoinSwitcher`) counted it uncompressed, failing with `SET_SIZE_LIMIT_EXCEEDED` although the compressed right side fits. Each build stream now has a mutex, held by its own thread while it stores a block. `compressPendingBuildStreams` takes these locks one at a time and compresses every build stream that has not caught up; it runs before a size limit reports an excess and before a wrapper decides to spill or switch. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Status of The CHANGES_REQUESTED review from @rschu1ze is still open. It asks to discuss the direction with the join team first, so that is a human decision. |
…ression Resolved the conflicts in `HashJoin.cpp` after `master` gave each `ON` disjunct its own `HashJoinTable` (#120515): - includes: drop `<any>` as on `master`, keep `<algorithm>` from this PR; - `addBlockToJoin`: keep this PR's conditional `shrinkToFit` (skipped when compressing on insertion), using `build_layout.num_slots` instead of the removed `data->slots`; - `releaseJoinedBlocks`: keep this PR's streaming `ReleasedJoinedBlocks`; it drops `data` without touching the maps, so `master`'s `HashJoinTable::releaseMaps` loop there is not needed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged The join objects and the On the previous head, the only red check was |
The `arm_tidy` builds failed with `modernize-use-nodiscard` on these two accessors in `HashJoin.h`: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107667&sha=504ff60e8c38786726912e24c553f69907882905&name_0=PR&name_1=Build%20(arm_tidy%2C%204%2F4) #107667 Co-Authored-By: Claude Fable 5.2 <[email protected]>
… overflow Several build streams can each store a block below `join_in_memory_compression_min_bytes` and cross it together. Each of them notices it only after it has inserted the keys of its block, so another build stream could reach the `max_bytes_in_join` check while `compress_stored_blocks` was still unset. The check then skipped `compressPendingBuildStreams` and threw `SET_SIZE_LIMIT_EXCEEDED`, although the whole right side, compressed, fits. `compressPendingBuildStreams` now makes the decision itself when the stored size has reached the threshold, and the over-limit path in `addBlockToJoin` no longer depends on the latch. The callers that decide to spill or switch (`SpillingHashJoin`, `JoinSwitcher`, `GraceHashJoin`) get the same guarantee through the shared helper. #107667 (comment) Co-Authored-By: Claude Fable 5.2 <[email protected]>
…_tuples` The test (added on `master`) checks that a row store is built, and in-memory compression disables the row store. The setting is randomized by `clickhouse-test` in this PR, so pin it to `0`, as in the other row store tests. #107667 Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Merged
The CHANGES_REQUESTED review from @rschu1ze is still open. It asks to discuss the direction with the join team first, which is a decision for a human. |
The `settings_changes_history` style check failed after the version on `master` moved to 26.12: `enable_join_in_memory_compression` and `join_in_memory_compression_min_bytes` were recorded under 26.11. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=107667&sha=f8f65ff1f1c01870755fb9866d4605e70ddb1330&name_0=PR&name_1=Style%20check #107667 Co-Authored-By: Claude Fable 5.2 <[email protected]>
…pression settings Query-plan serialization version 21 was released in 26.11 without `enable_join_in_memory_compression` and `join_in_memory_compression_min_bytes`, so the comments and the protocol spec no longer hold: the names are added in 26.12 at the same version. No new version is needed, because a reader at version 21 skips a plan setting name it does not know, and such a peer runs the join without in-memory compression, which changes only its memory usage. The bytes on the wire do not change. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Merged
Verification: the 50 join-related objects ( The review thread about concurrent activation of compression has the reply from 2026-11-21 (e4e3385) and no newer comment. The CHANGES_REQUESTED review from @rschu1ze is still open. It asks to discuss the direction with the join team first, which is a decision for a human. |
Re-implementation of the idea from #63696 ("Added possibility of compressing in
HashJoin", by @p1rattttt) against the currentHashJoin/ScatteredBlockarchitecture, and it covershash,parallel_hashandgrace_hash(which all build on the sameHashJoin).Motivation
When a hash-based join's right (build) side is large, ClickHouse either reaches the memory limit (and throws / spills to disk via grace hash) or shrinks over-allocated blocks. Compressing the stored right-side blocks in memory is a cheaper-than-spilling intermediate step: a memory-bound join whose right side is compressible can complete entirely in memory instead of failing or going to disk.
What it does
New settings:
enable_join_in_memory_compression(defaultfalse): compress the right-side blocks stored by hash-based joins.join_in_memory_compression_min_bytes(default 128 MiB): the stored size after which compression starts. When it is reached, the blocks stored so far are compressed in one pass, and every later block is compressed on insertion. Forparallel_hashit applies to the whole join, and each build stream compresses its own blocks; forgrace_hashit applies to each in-memory bucket.Since the stored size shrinks,
max_bytes_in_join, the automatic switch to an external join (max_bytes_before_external_join) and the switch ofautotopartial_mergesee the compressed size, so a compressible right side stays in memory longer.The settings are carried in the serialized join step at query plan serialization version 21, without a new version: a peer at version 21 that does not know the names (release 26.11) skips them and runs the join without compression (only its memory usage differs). The setting is randomized in
clickhouse-test.Mechanism:
addBlockToJoincompresses the stored columns once the threshold is reached, and the new blocks on insertion. A column is kept compressed only when compression shrinks its data by at least 10%; otherwise it is just shrunk (cloneResized), so barely- or in-compressible columns stay directly readable and incur no probe-time cost. Reranging is skipped for compressed data.buildOutputFromBlockspath, the limit/offset path, the additional-filter (buildAdditionalFilter) path for extraJOIN ONpredicates that read a right column,joinGet, the non-lazy ANY path, and the RIGHT/FULL non-joined-rows streams all translate stored pointers through the resolver.SpillingHashJoinswitching toGraceHashJoin,GraceHashJoinbucket rehashing,JoinSwitcher, per-build-stream release inSpillingHashJoin),releaseJoinedBlocksandreleaseBuildStreamBlocksstream the stored blocks out one at a time: each block is decompressed as it is pulled and its stored source is freed right after, so the receiving algorithm reads ordinary columns while the handoff never materializes the whole uncompressed right-hand side at once (the consumers run exactly when memory is short).Performance
Measured on a 2M-row 1:1
INNER JOINwith the full payload forced through the join (join_algorithm = 'hash'):So the feature trades probe-time CPU for lower peak memory only when the right side is actually compressible; that is why it is opt-in and only starts above a byte threshold.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added setting
enable_join_in_memory_compression(off by default). When it is on, hash-based joins (hash,parallel_hash,grace_hash) compress their right-side blocks in memory once they grow pastjoin_in_memory_compression_min_bytes(128 MiB by default), so a larger right side fits undermax_bytes_in_joinand before spilling to disk. This trades probe-time CPU for lower memory; decompressed data is held only per output block during the probe.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/107667]