Repository navigation
Adaptive codec selection on merges and mutations - #111834
Conversation
|
Workflow [PR], commit [432d1a5] Summary: ✅
AI ReviewSummaryThis PR adds experimental per-block adaptive codec selection for default-coded Findings
Tests
Final VerdictChanges requested. |
| save_primary_index_in_memory, | ||
| blocks_are_granules_size); | ||
|
|
||
| writer_settings.apply_adaptive_codec = (write_origin == WriteOrigin::MergeOrMutation) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Rolling upgrades are safe. I backported the PR that allows reading columns compressed with different codecs to all versions that are relevant #108592
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
| static_cast<WrittenOffsetSubstreams *>(nullptr)); | ||
| static_cast<WrittenOffsetSubstreams *>(nullptr), | ||
| write_origin, | ||
| /*is_explicit_recompression=*/ false); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
| WriteOrigin write_origin, | ||
| bool is_explicit_recompression) |
There was a problem hiding this comment.
This breaks abstractions. Why not just push the try_adaptive_codec flag here and use it with a settings combination?
| /// Which operation is producing the part. Determines if CODEC(Default) should be resolved adaptively. | ||
| enum class WriteOrigin : uint8_t | ||
| { | ||
| Insert, | ||
| MergeOrMutation, | ||
| }; | ||
|
|
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
| /// 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; | ||
|
|
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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
| writer_settings.apply_adaptive_codec = (write_origin == WriteOrigin::MergeOrMutation) | ||
| && (*storage_settings)[MergeTreeSetting::allow_experimental_adaptive_codec_selection] && !is_explicit_recompression; |
There was a problem hiding this comment.
Let's move to the constructor of the merge tree writer settings.
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
| /// 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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
We could get rid of this ad-hoc assignment too in a similar way, but it's outside of the scope of this PR
| /// 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; | ||
|
|
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 220/226 (97.35%) · Uncovered code |
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (2 of 43)
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
|
|
Hi @rienath @Michicosun — while reviewing this PR I found the following:
Could you review the test PR and add the |
…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.
Adds an experimental
MergeTreesettingallow_experimental_adaptive_codec_selection. When enabled, merges and mutations compress each block of a column that uses the default codec (CODEC(Default)or noCODECclause) 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 explicitRECOMPRESScodec is honoured.This is the write side of the adaptive compression RFC (#105404). Inspect the choices with the
mergeTreeCodecBlockCountstable function.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added an experimental
MergeTreesettingallow_experimental_adaptive_codec_selection. When enabled, merges and mutations pick the smallest-output codec per block for columns that use the default codec.