Skip to content

Adaptive codec selection on merges and mutations - #111834

Merged
rienath merged 14 commits into
masterfrom
enable-adaptive-codec
Aug 1, 2026
Merged

rienath merged 14 commits into
masterfrom
enable-adaptive-codec

Conversation

@rienath

@rienath rienath commented Jul 24, 2026 •

Copy link
Copy Markdown
Member

Adds an experimental MergeTree setting allow_experimental_adaptive_codec_selection. When enabled, merges and mutations compress each block of a column that uses the default codec (CODEC(Default) or no CODEC clause) with whichever codec gives the smallest output: the table's default codec, NONE, or a specialised codec suited to the column type. Compression is never worse than the default, an encrypting default codec is never substituted, and an explicit RECOMPRESS codec is honoured.

This is the write side of the adaptive compression RFC (#105404). Inspect the choices with the mergeTreeCodecBlockCounts table function.

Changelog category (leave one):

  • Experimental Feature

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

Added an experimental MergeTree setting allow_experimental_adaptive_codec_selection. When enabled, merges and mutations pick the smallest-output codec per block for columns that use the default codec.

@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [432d1a5]

Summary: ✅


AI Review

Summary

This PR adds experimental per-block adaptive codec selection for default-coded MergeTree columns during merges and mutations, threads the flag through projection materialization, and documents the new behavior. The overall direction looks sound, but two user-visible surfaces still diverge from the contract this PR introduces, so I would not merge it as-is.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/IMergeTreeDataPartWriter.cpp:196-198] Adaptive selection is only activated for AdaptiveCodec::isCandidateType, so non-candidate default-coded columns never see the NONE fallback. The new 04305 test already shows String and Int128 staying on LZ4, but the setting text and docs say default-coded columns choose among the table default codec, NONE, and type-specialized codecs, and that incompressible blocks are stored raw. Either wrap every default-coded type so NONE is always considered, or narrow the docs/tests to the current candidate subset.
  • [src/Storages/MergeTree/MergeTreeDataWriter.cpp:1231] Projection-level MergeTree settings are supposed to override the parent table, but the projection write path still computes compression_codec through MergeTreeData::getCompressionCodecForPart, which reads default_compression_codec from the parent table settings. After this PR, writeTempProjectionPart enables adaptive selection for projection merges/materialization, so WITH SETTINGS default_compression_codec = ... is silently ignored exactly on the new path.
  • [src/Storages/MergeTree/MergeTreeDataWriter.cpp:1231,1329] [dismissed by author -- https://github.com/Adaptive codec selection on merges and mutations #111834#discussion_r3667516797] Rebuilt projections still do not inherit an explicit due RECOMPRESS CODEC(X) from the parent merge/mutation. writeProjectionPartImpl chooses the codec from empty TTL info, and writeTempProjectionPart still hard-codes try_adaptive_codec = true, so this PR can now write the projection with adaptive T64/NONE while the base part is pinned to the explicit recompression codec.
Tests
  • ⚠️ Add a focused projection regression test with PROJECTION ... WITH SETTINGS (default_compression_codec = 'NONE' or 'ZSTD(1)') plus allow_experimental_adaptive_codec_selection = 1; the new projection merge/materialization path should prove it uses the projection’s own override instead of the parent table’s codec.
Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Jul 24, 2026
@Michicosun Michicosun self-assigned this Jul 24, 2026
save_primary_index_in_memory,
blocks_are_granules_size);

writer_settings.apply_adaptive_codec = (write_origin == WriteOrigin::MergeOrMutation)

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.

This enables mixed-codec streams for merge output without any version negotiation on replicated tables. The new backward-compatibility test already demonstrates the failure mode: an older replica can fetch the part successfully and then throw CANNOT_DECOMPRESS on a normal read of the mixed-codec column (tests/integration/test_backward_compatibility/test_adaptive_codec.py, test_old_version_cannot_read_mixed_codec_part). That makes rolling upgrades unsafe, and turning allow_experimental_adaptive_codec_selection back off does not repair parts that were already written or fetched. The same missing guard exists in the column-only mutation path at src/Storages/MergeTree/MergedColumnOnlyOutputStream.cpp:54. We should reject this setting for ReplicatedMergeTree until all replicas advertise support for per-block codec changes, or add an explicit format/version handshake that prevents older replicas from fetching these parts.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Rolling upgrades are safe. I backported the PR that allows reading columns compressed with different codecs to all versions that are relevant #108592

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.

tests/integration/test_backward_compatibility/test_adaptive_codec.py:83-104 still pins the old replica to CLICKHOUSE_CI_MIN_TESTED_VERSION (25.3) and asserts that a fetched mixed-codec part throws CANNOT_DECOMPRESS on read. The merge/mutation writers still enable adaptive output unconditionally at src/Storages/MergeTree/MergedBlockOutputStream.cpp:70-71 and src/Storages/MergeTree/MergedColumnOnlyOutputStream.cpp:54-55, so the original rolling-upgrade hole is still present for the minimum compatible version.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, we do exercise this path in tests to pin behaviour of very old version. But we do not expect rolling updates to be from 25.2 to 26.8. Even 26.3 → 26.8 is quite a stretch, but we support it

@mintlify

mintlify Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 24, 2026, 6:02 PM

static_cast<WrittenOffsetSubstreams *>(nullptr));
static_cast<WrittenOffsetSubstreams *>(nullptr),
write_origin,
/*is_explicit_recompression=*/ false);

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.

writeTempProjectionPart now routes projection rebuilds through WriteOrigin::MergeOrMutation, but this helper still hard-codes is_explicit_recompression = false and never receives the parent part's TTL-derived codec. On a table with a projection plus TTL ... RECOMPRESS CODEC(NONE), the base-part merge/mutation path will correctly disable adaptive selection while the projection rebuild here can still emit adaptive T64 or default-compressed blocks. Since projections inherit the table's compression settings, that looks like a violation of the same explicit-RECOMPRESS contract this PR adds for normal parts. Please either thread the parent merge/mutation codec/flag into projection writes or keep projections on the old non-adaptive path until that is handled.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Projections never receive the recompression codec in the first place. That is pre-existing behaviour, tracked in #108927. When projections honour recompression TTLs, the flag will be threaded together with the codec

Comment on lines +46 to +47
WriteOrigin write_origin,
bool is_explicit_recompression)

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.

This breaks abstractions. Why not just push the try_adaptive_codec flag here and use it with a settings combination?

Comment on lines +11 to +17
/// Which operation is producing the part. Determines if CODEC(Default) should be resolved adaptively.
enum class WriteOrigin : uint8_t
{
Insert,
MergeOrMutation,
};

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.

Not sure that this is the right approach because part can be written by multiple functions, for example, createEmptyPart or something similar.


bool MergeTreeData::isExplicitRecompression(const IMergeTreeDataPart::TTLInfos & ttl_infos, time_t current_time) const
{
auto metadata_snapshot = getInMemoryMetadataPtr(getContext(), false);

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.

That is not correct, we need to use metadata that is being used in merge/mutation tasks - it will be stored in the merge/mutation context somewhere. If we use that metadata, we can move the implementation out of the merge tree data.

The same problem looks like exist in getCompressionCodecForPart.

Comment thread src/Storages/MergeTree/MergeTreeData.h Outdated
Comment on lines +1369 to +1372
/// True if a `RECOMPRESS` TTL applies to a part with these `ttl_infos` at `current_time` and its codec is not `Default`.
/// Such a codec is an explicit per-part directive, so adaptive codec selection must not override it.
bool isExplicitRecompression(const IMergeTreeDataPart::TTLInfos & ttl_infos, time_t current_time) const;

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.

Will it be better to change the API of getCompressionCodecForPart to return the chosen codec and some information about it - for example, was it taken from the TTL rules?

@rienath rienath Jul 31, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks for suggestion! I've done this, but still had to keep isExplicitRecompression call in MutateTask. On mutation, we need to keep part's default codec in default_compression_codec.txt. If we re-resolve here by calling getCompressionCodecForPart instead, we would change it.

Another option is to remove isExplicitRecompression and call getCompressionCodecForPart and then rewrite the codec inside the PartCompressionCodec that we get. This way we'll pass a single struct instead of two values down the line. But we also locked the context mutex and resolved the codec (which might be worth it for the cleaner API, but I am not sure how much cleaner it is in this case).

Let me know what you think

Comment on lines +70 to +71
writer_settings.apply_adaptive_codec = (write_origin == WriteOrigin::MergeOrMutation)
&& (*storage_settings)[MergeTreeSetting::allow_experimental_adaptive_codec_selection] && !is_explicit_recompression;

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.

Let's move to the constructor of the merge tree writer settings.

rienath added 5 commits July 30, 2026 16:37
Fixes pre-existing bug where an ALTER of recompression TTLs mid-operation could give the new part a codec chosen from newer metadata than the merge or mutation was running under
...and do not fetch possibly newer table metadata
to derive the codec and flag from one TTL selection rather than two
…ructor

Now applied centraly instead of duplicating in ouptut streams
@rienath
rienath requested a review from a team as a code owner July 31, 2026 11:35
@rienath
rienath removed the request for review from a team July 31, 2026 11:36
/// 1. Adaptive could pick an unencrypted codec for some blocks and drop the encryption. Thus skip adaptivity for an encrypting default.
/// 2. TODO: `isCandidateType` leaves non-candidate non-adaptive. So they always use the default and never fall back to NONE.
/// If the default expands incompressible data, the block is stored larger than raw. Fix: see `isCandidateType`.
if (settings.apply_adaptive_codec && column_uses_default_codec && substream_type && AdaptiveCodec::isCandidateType(*substream_type)

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.

maybeAdaptiveDefaultCodec only wraps AdaptiveCodec::isCandidateType, so non-candidate default-coded columns never see the NONE fallback at all. The new 04305 test already shows String and Int128 staying on LZ4, but both the setting text and the new docs say default-coded columns choose among the table default, NONE, and type-specific codecs, and that incompressible blocks are stored raw. Either wrap every default-coded type so NONE is always considered, or narrow the docs/tests to the current candidate subset.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Both texts already narrow this. The setting says Only integer-like types are currently adaptive, the docs end with Selection currently covers integer-like columns: .... Non-candidates skipping the NONE is a known TODO deliberately deferred

}

auto compression_codec = data.getCompressionCodecForPart(0, {}, time(nullptr));
auto compression_codec = data.getCompressionCodecForPart(metadata_snapshot, 0, {}, time(nullptr)).codec;

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.

This newly-adaptive projection path still seeds compression_codec from MergeTreeData::getCompressionCodecForPart, which reads default_compression_codec from data.getSettings() instead of the projection's data_settings. A projection declared with WITH SETTINGS default_compression_codec = 'ZSTD(1)', allow_experimental_adaptive_codec_selection = 1 will therefore build its adaptive pool around the parent table's default codec, silently ignoring the projection-level override that docs say should apply only to the projection. Please thread the effective projection settings into getCompressionCodecForPart (or compute the default codec from data_settings here) before enabling this path.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Pre-existing. The pre-image of this line reads the same table-level settings, so projection-level default_compression_codec was already ignored before this PR. Adaptive builds its pool around the resolved default, so it stays consistent with the non-adaptive baseline and would automatically follow a future fix at the resolution site

@rienath rienath left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks for the review @Michicosun! I've addressed all the points you've raised

/// This stream is used only by merge and mutation, never inserts
writer_settings.apply_adaptive_codec
= (*storage_settings)[MergeTreeSetting::allow_experimental_adaptive_codec_selection] && !is_explicit_recompression;
writer_settings.external_packed_skip_indices_writer = external_packed_skip_indices_writer;

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

We could get rid of this ad-hoc assignment too in a similar way, but it's outside of the scope of this PR

Comment thread src/Storages/MergeTree/MergeTreeData.h Outdated
Comment on lines +1369 to +1372
/// True if a `RECOMPRESS` TTL applies to a part with these `ttl_infos` at `current_time` and its codec is not `Default`.
/// Such a codec is an explicit per-part directive, so adaptive codec selection must not override it.
bool isExplicitRecompression(const IMergeTreeDataPart::TTLInfos & ttl_infos, time_t current_time) const;

@rienath rienath Jul 31, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks for suggestion! I've done this, but still had to keep isExplicitRecompression call in MutateTask. On mutation, we need to keep part's default codec in default_compression_codec.txt. If we re-resolve here by calling getCompressionCodecForPart instead, we would change it.

Another option is to remove isExplicitRecompression and call getCompressionCodecForPart and then rewrite the codec inside the PartCompressionCodec that we get. This way we'll pass a single struct instead of two values down the line. But we also locked the context mutex and resolved the codec (which might be worth it for the cleaner API, but I am not sure how much cleaner it is in this case).

Let me know what you think

/// 1. Adaptive could pick an unencrypted codec for some blocks and drop the encryption. Thus skip adaptivity for an encrypting default.
/// 2. TODO: `isCandidateType` leaves non-candidate non-adaptive. So they always use the default and never fall back to NONE.
/// If the default expands incompressible data, the block is stored larger than raw. Fix: see `isCandidateType`.
if (settings.apply_adaptive_codec && column_uses_default_codec && substream_type && AdaptiveCodec::isCandidateType(*substream_type)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Both texts already narrow this. The setting says Only integer-like types are currently adaptive, the docs end with Selection currently covers integer-like columns: .... Non-candidates skipping the NONE is a known TODO deliberately deferred

}

auto compression_codec = data.getCompressionCodecForPart(0, {}, time(nullptr));
auto compression_codec = data.getCompressionCodecForPart(metadata_snapshot, 0, {}, time(nullptr)).codec;

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Pre-existing. The pre-image of this line reads the same table-level settings, so projection-level default_compression_codec was already ignored before this PR. Adaptive builds its pool around the resolved default, so it stays consistent with the non-adaptive baseline and would automatically follow a future fix at the resolution site

@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 220/226 (97.35%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR adds adaptive per-block codec selection on the merge/mutation write path, gated behind the new off-by-default experimental setting allow_experimental_adaptive_codec_selection; the query read path and decompression are untouched. Both flagged ClickBench queries (Q30 +20.3%, Q31 +10.7%) are SELECTs that cannot exercise the changed code with the setting disabled, and both land inside master's current variance band with essentially flat CPU. The deterministic gates already suppressed them as within-envelope, and that reading holds — these are run-to-run variance, not a PR effect. No real regression is attributable to this change.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 30 not_sure 271 326 +20.3% <0.0001 This is a read query, but the PR only changes merge/write-time codec selection behind an off-by-default experimental setting. The +20.3% sits inside master's own variance band with flat CPU, so it reads as noise.
⚠️ 31 not_sure 382 424 +10.7% <0.0001 Same story: adaptive codec selection touches nothing this SELECT executes, and +10.7% falls within master's current variance band with essentially unchanged CPU. Treat as run-to-run variance.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: df4f48a1-0b9d-427e-9543-f51b29c3c283
  • MIRAI run: f558ae0c-2d6b-407e-8d06-0721f735b3a9
  • PR check IDs:
    • clickbench_1184434_1785544263
    • clickbench_1184445_1785544264
    • clickbench_1184452_1785544263
    • tpch_adapted_1_official_1184920_1785544546
    • tpch_adapted_1_official_1185035_1785544563
    • tpch_adapted_1_official_1185164_1785544617

@rienath
rienath added this pull request to the merge queue Aug 1, 2026
Merged via the queue into master with commit db2ec70 Aug 1, 2026
522 of 527 checks passed
@rienath
rienath deleted the enable-adaptive-codec branch August 1, 2026 06:52
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 1, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @rienath @Michicosun — while reviewing this PR I found the following:

Could you review the test PR and add the can be tested label if it looks good?
Happy to discuss — close anything that's wrong or already addressed.

CurtizJ pushed a commit to CurtizJ/ClickHouse that referenced this pull request Aug 3, 2026
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Aug 27, 2026
…ive_codec_selection`

The `allow_experimental_` prefix is the pre-tier way of gating a feature. The `EXPERIMENTAL` tier in the setting declaration already carries that information (it is exposed as `tier` in `system.merge_tree_settings`), so the prefix duplicates it in the one place that is expensive to change later: the name. When the feature graduates, a prefixed name has to be renamed and the old spelling carried as an alias forever, which is why the tree already holds `allow_experimental_analyzer` -> `enable_analyzer`, `allow_experimental_nullable_tuple_type` -> `enable_nullable_tuple_type` and `allow_experimental_database_iceberg` -> `allow_database_iceberg`.

The setting was added in ClickHouse#111834 and has not shipped in any release: its `SettingsChangesHistory` entry is in the unreleased `26.8` block, so this is a plain rename with no alias and no compatibility entry.

`enable_` matches the neighbouring MergeTree booleans (`enable_block_number_column`, `enable_mixed_granularity_parts`) and the graduation path is now a one-word tier change.

The autogenerated settings reference pages still spell the old name; they are regenerated from the binary by the nightly docs job.

This branch was successfully deployed

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

Labels

pr-experimental Experimental Feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants