Skip to content

Compress hash join right-side blocks in memory before OOM / spilling - #107667

Open
alexey-milovidov wants to merge 140 commits into
masterfrom
join-in-memory-compression
Open

alexey-milovidov wants to merge 140 commits into
masterfrom
join-in-memory-compression

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 16, 2026 •

Copy link
Copy Markdown
Member

Re-implementation of the idea from #63696 ("Added possibility of compressing in HashJoin", by @p1rattttt) against the current HashJoin/ScatteredBlock architecture, and it covers hash, parallel_hash and grace_hash (which all build on the same HashJoin).

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 (default false): 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. For parallel_hash it applies to the whole join, and each build stream compresses its own blocks; for grace_hash it 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 of auto to partial_merge see 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:

  • Build side — addBlockToJoin compresses 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.
  • Probe side — stored blocks are decompressed on demand, per output batch: each batch decompresses the distinct stored blocks it references (each at most once per batch, via a per-batch resolver), holds them only while the batch is materialized, and releases them right after, so no decompressed data stays resident. The lazy buildOutputFromBlocks path, the limit/offset path, the additional-filter (buildAdditionalFilter) path for extra JOIN ON predicates 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.
  • Release / spill side — when a join that already compressed in memory is still released to another algorithm (SpillingHashJoin switching to GraceHashJoin, GraceHashJoin bucket rehashing, JoinSwitcher, per-build-stream release in SpillingHashJoin), releaseJoinedBlocks and releaseBuildStreamBlocks stream 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 JOIN with the full payload forced through the join (join_algorithm = 'hash'):

Right-side payload Build memory Probe time
Compressible 402.8 → 153.7 MiB (≈ 2.6×) ≈ 1.85×
Incompressible shrunk only, not kept compressed ≈ 1.0× (no probe overhead)

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):

  • New Feature

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 past join_in_memory_compression_min_bytes (128 MiB by default), so a larger right side fits under max_bytes_in_join and 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

  • Documentation is written (mandatory for new features)

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

alexey-milovidov and others added 2 commits June 16, 2026 19:48
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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [466751d]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, parallel) FAIL
05058_max_joined_block_size_rows_zero_with_bytes FAIL cidb
Stateless tests (amd_tsan, s3 storage, targeted) FAIL
05626_join_packed_string_keys_hash_grace_big FAIL cidb

AI Review

Summary

Adds 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 466751d0e01d2daffaf197d7827a038549e48875. The previously reported concurrent-activation issue is addressed: compressPendingBuildStreams now evaluates the threshold itself and synchronizes pending streams before limit and spill decisions. The corresponding bot thread is resolved.

Representation consumers traced: ordinary/ANY/ASOF output uses the decompression resolver; limit/offset output resolves columns before byte accounting; buildAdditionalFilter and buildJoinGetOutput resolve stored inputs; NotJoinedHash uses grouped decompression; spill/switch/repartition consumers receive ordinary columns one block at a time. Compression disables the row store and prevents reranging compressed blocks. The persistent StorageJoin build does not enable compression.

The Fast test report reports all 13 compression regression tests passing, including pending-stream and concurrent-activation cases.

Missing context / blind spots
  • ⚠️ Full sanitizer and stateless CI for this head is still in progress. Runtime validation beyond Fast test depends on those jobs; no local tests were run because this review job has no ClickHouse binary.
  • ⚠️ The existing human request to discuss the feature's direction with the join team remains a maintainer decision; this technical review does not settle it.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jun 16, 2026
Comment thread src/Interpreters/HashJoin/HashJoin.cpp Resolved
alexey-milovidov and others added 4 commits June 18, 2026 03:07
…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]>
Comment thread src/Interpreters/HashJoin/HashJoin.h Resolved
Comment thread src/Interpreters/TableJoin.cpp Resolved
…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]>
Comment thread src/Core/Settings.cpp Resolved
alexey-milovidov and others added 6 commits June 18, 2026 21:40
`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]>
Comment thread src/Interpreters/GraceHashJoin.cpp Resolved
Comment thread src/Interpreters/GraceHashJoin.cpp Resolved
alexey-milovidov and others added 4 commits June 19, 2026 20:31
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Shepherd pass on this PR. Pushed d83b63cc..bb1d99e2e32 (clean fast-forward).

Pushed (CI-unblocking + housekeeping only — no algorithm changes)

  1. Style-check fix (the only red). The contract test used the global SYSTEM FLUSH LOGS, which is forbidden in stateless tests and was failing Style check first, so every build/stateless job was DROPPED. Replaced with SYSTEM FLUSH LOGS query_log.
  2. Stabilized the contract test under randomization. The parallel_hash case asserts that compression keeps the join under max_bytes_in_join; clickhouse-test's randomized block-size / memory settings shift the per-slot footprint and made it throw SET_SIZE_LIMIT_EXCEEDED (~1 in 5 local runs). Added -- Tags: no-random-settings (verified 6/6 stable afterwards). The plain-hash tests use a single hash table and were not affected, so they keep full randomization.
  3. Merged master (it was CONFLICTING). Clean merge; the SettingsChangesHistory entries landed in the 26.6 block.
  4. Renumbered the three feature tests — master now uses the 04356/04357/04358 prefixes (the geojson family, nullable_tuple_beta, …):
    • 04356_join_in_memory_compression → 04402
    • 04357_join_in_memory_compression_edge_cases → 04403
    • 04358_join_in_memory_compression_contract → 04404

All three renumbered tests pass locally; the three core join TUs syntax-check clean against current master (no API drift from the merge).

Not pushed — left for you (the two open GraceHashJoin.cpp:809 threads)

There was uncommitted WIP in my worktree addressing both grace_hash majors (set shrink_blocks in the force_optimize path of HashJoin::shrinkStoredBlocksToFit so the bucket keeps compressing on insert after the first compaction; run shrinkStoredBlocksToFit after each grace insert to wire the max_memory_usage trigger for standalone grace_hash). The code appears correct by inspection, syntax-checks clean, and the contract test passes — but I kept it uncommitted because the regression test meant to validate it does not hold up, and these are your design calls:

  • "Must not spill" is not achievable for grace_hash. The draft test asserts ExternalJoinWritePart = 0, but grace_hash is a disk-partitioning algorithm. I swept max_bytes_in_join from 8 MB to 60 MB (≫ the ~50 MB raw / highly compressible right side) and it spills at every limit (2–4 parts). Compress-on-insert does compress more under repeated pressure (JoinInMemoryCompressedColumns rises), but it does not eliminate grace_hash's rehash/spill, so the no-spill assertion can't pass.
  • The max_memory_usage trigger isn't robustly assertable on small data — exactly the caveat the contract test header already documents. With max_bytes_in_join = 0, max_memory_usage = 200M, the join-build memory delta stays below the 100 MB (half) threshold (measured peak 169 MB), so the trigger correctly never fires and the assertion reads 0.

The WIP diff and the draft 04401 regression are preserved in the worktree. If you want the compress-on-insert improvement landed, I'd suggest asserting "more compression / fewer spilled parts" rather than "no spill", and not asserting the max_memory_usage trigger (per your own caveat). I did not resolve the two threads or self-approve; CI should now run the full matrix.

alexey-milovidov and others added 2 commits June 23, 2026 02:14
`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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (7f11488) in e0d84fe. The merge had conflicts and needed a rework: master removed ConcurrentHashJoin, and parallel_hash is now one HashJoin with several build streams sharing one RightTableData. Changes to the PR's design that follow from this:

  • join_in_memory_compression_min_bytes now applies to the whole parallel_hash join, through the shared allocated_size, instead of being split between slots. setInMemoryCompressionMinBytes is gone, and the setting docs and PR description are updated.
  • The decision to compress is a CAS on compress_stored_blocks, the same as shrink_blocks. Each build stream compresses only its own list (BuildStreamData::compression_done). The stream that crosses the threshold compresses right away. The others catch up before they store their next block, and from then on compress each new block on insertion.
  • have_compressed and the compression statistics are now atomics. Since there is only one HashJoin, the end-of-build sync of have_compressed across slots and the zero-copy special case are no longer needed.
  • shrinkStoredBlocksToFit skips a build stream whose blocks are already compressed.
  • releaseBuildStreamBlocks now returns ReleasedJoinedBlocks too, so SpillingHashJoin::tryConvertBuildStreams still releases blocks one at a time, decompressing each as it goes.

clickhouse builds. All the PR's tests, plus the row store tests it touches, pass locally with and without randomized settings (3 runs). 231 stateless tests that use parallel_hash, grace_hash or the external join settings also pass, apart from 3 that fail only because of my local setup (remote replicas, server config, file permissions). Before the push, the only red check was CH Inc sync, which was blocked by the same conflict.

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.

Comment thread src/Interpreters/HashJoin/HashJoin.cpp Resolved
alexey-milovidov and others added 3 commits November 8, 2026 11:07
… 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (7b5f2bf, no conflicts) and fixed the CI failures of the previous run (e0d84fe8332a):

  • 04492_join_in_memory_compression, 04493_join_in_memory_compression_edge_cases, 05443_join_in_memory_compression_nullable (flaky check and targeted runs) threw SET_SIZE_LIMIT_EXCEEDED. With several build streams (here hash reading a Memory table in two streams, e.g. max_block_size = 37640, query_plan_optimize_join_order_limit = 0), one stream decided to compress after storing its small block. Its max_bytes_in_join check then counted the 37 MB block the other stream had just stored but not compressed yet. Fixed in 4f4eabd: the decision is made before a block is stored (counting that block), a block stored while another stream latched compression is compressed right after the insert, and onBuildPhaseFinish compresses the streams that finished before compression started (the open review thread). New test 05569_join_in_memory_compression_uneven_build_streams. All 22 failing setting combinations from CI now pass locally.
  • 05245_spilling_join_empty_right_side (from master): the randomized enable_join_in_memory_compression = 1 compresses the right side below max_bytes_before_external_join, so the expected switch to GraceHashJoin legitimately does not happen. The setting is pinned to 0 there (aeae507), as in 05136 and 05237.

All the PR's tests (plus 05245) pass against a server, with compression both on and off. The CHANGES_REQUESTED review by @rschu1ze (discuss the direction with the join team first) still needs a human decision.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 All CI checks on aeae5076ece4 pass except CH Inc sync. The private sync PR conflicted with private master in docs/resources/develop-contribute/native-protocol/protocol.mdx, because private master words the QUERY_PLAN_SERIALIZATION row differently. I resolved it there by keeping the private text and appending this PR's sentence about version 21. Only that one file conflicted, and the sync PR is now MERGEABLE. No change is needed in this PR.

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.

alexey-milovidov and others added 4 commits November 10, 2026 21:15
# 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and pinned enable_join_in_memory_compression = 0 in the new test 05345_hash_join_row_store_strings (it checks that a row store is built, which in-memory compression disables), like the other row store tests. The Build profile diff failure is an infrastructure error (LogClusterNotReady: the endpoint never became ready) and is unrelated. The open change request about the general direction still needs discussion with the join team.

alexey-milovidov and others added 2 commits November 14, 2026 01:01
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status of 2df50389802f: every CI check passes except CH Inc sync, which failed because the private sync PR conflicted with private master. The conflict was only in docs/resources/develop-contribute/native-protocol/protocol.mdx, the same QUERY_PLAN_SERIALIZATION row as last time. I put this PR's 50 files on top of private master (71c8caf19ffd), kept the private text and added this PR's sentence about version 21, and pushed the merge to the sync branch (4be36a63ea74). The private diff against private master matches this PR's diff line for line. No private-only code uses the changed HashJoin build-stream API. The sync PR is now MERGEABLE, and its CI is running. This PR needs no code change.

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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (cf7ef0b) in 504ff60 to resolve the conflict. The only conflict was in HashJoin.cpp. master (#120515) now gives each ON disjunct its own HashJoinTable, so the conditional shrinkToFit in addBlockToJoin now uses build_layout.num_slots instead of the removed data->slots. releaseJoinedBlocks keeps this PR's streaming ReleasedJoinedBlocks. It drops data without touching the maps, so it does not need master's releaseMaps loop. I checked that every line this PR adds in src/Interpreters/HashJoin/ is still there after the merge.

The join objects and the clickhouse binary build. Locally, all 18 tests this PR adds or changes pass. I also ran 82 hash_join / parallel_hash / grace_hash / join_algorithm tests with randomized settings, which include enable_join_in_memory_compression. All of them pass except ones that need a cluster or dataset the local server doesn't have (parallel_replicas, test_cluster_one_shard_three_replicas_localhost, test.hits).

On the previous head, the only red check was CH Inc sync. 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.

alexey-milovidov and others added 4 commits November 21, 2026 15:14
… 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (3232ee3, no conflicts) and pushed three fixes:

  • 3754939: the arm_tidy builds failed with modernize-use-nodiscard on ReleasedJoinedBlocks::empty and size in HashJoin.h; both are now [[nodiscard]]. This was the only CI failure on 504ff60e8c38.
  • e4e3385: addresses the open review thread about concurrent activation of compression (Compress hash join right-side blocks in memory before OOM / spilling #107667 (comment)). compressPendingBuildStreams now makes the decision to compress itself when the stored size has reached join_in_memory_compression_min_bytes, so the max_bytes_in_join check and the pre-spill callers no longer depend on a build stream having latched it. New test 05839_join_in_memory_compression_limit_concurrent_activation.
  • f8f65ff: 05346_hash_join_row_store_tuples (from master) checks that a row store is built, which in-memory compression disables; enable_join_in_memory_compression is pinned to 0 there, as in the other row store tests.

clickhouse builds. Locally, the 15 tests this PR adds or changes pass against a server. Three runs of the hash_join / grace_hash / join_algorithm tests with randomized settings gave 229 passes and 23 failures: 22 came from the local server lacking the parallel_replicas clusters and system.query_thread_log, and one was the 05346 case fixed above. 05346 was not rerun after the pin.

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.

alexey-milovidov and others added 3 commits November 24, 2026 13:53
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (f38054d, no conflicts) and pushed two commits:

  • c22d3fa: the only CI failure on f8f65ff1f1c0 was settings_changes_history in Style check. master moved to 26.12, so enable_join_in_memory_compression and join_in_memory_compression_min_bytes are now recorded under 26.12 instead of 26.11.
  • 466751d: query-plan serialization version 21 was released in 26.11 without these two settings, so the comments in ProtocolDefines.h and JoinOperator.cpp, the sentence in the native protocol spec, and the PR description said something that no longer holds. They now say that the names are added in 26.12 at version 21. The version is not bumped: the 26.11 reader skips a plan setting name it does not know, and such a peer runs the join without in-memory compression. Only comments and documentation changed in this commit.

Verification: the 50 join-related objects (HashJoin, GraceHashJoin, JoinSwitcher, SpillingHashJoin, JoinOperator, JoinStepLogical, Settings, QueryPlanSerializationSettings) compile on the merged tree. I did not finish a full clickhouse build in this pass, so no tests were run locally after the merge.

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.

This branch was successfully deployed

1 active deployment
staging - docs — 466751d0 Deployed Nov 24, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants