Skip to content

Adaptive codec selection for structural substreams - #117348

Merged
rienath merged 15 commits into
masterfrom
adaptive-compression-substreams
Sep 5, 2026
Merged

rienath merged 15 commits into
masterfrom
adaptive-compression-substreams

Conversation

@rienath

@rienath rienath commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Adaptive codec selection now covers every substream of a column that uses the default codec, not only the main data stream. A substream with a type gets a codec from the regular pool. For example, UInt64 Array/String size streams and UInt8 null maps are priced against T64. A substream without a type is priced against NONE and the default codec, so incompressible bytes are stored raw.

Changelog category (leave one):

  • Experimental Feature

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

Adaptive codec selection (enable_adaptive_codec_selection) now applies to every substream of a column, such as Array and String sizes and null maps, instead of the main data stream only.


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

Version info

  • Merged into: 26.9.1.772 (included in 26.9 and later)

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3cbd827]

Summary: ✅


AI Review

Summary

This PR extends enable_adaptive_codec_selection from leaf streams to structural substreams and centralizes codec resolution in MergeTreeDataPartWriterOnDisk::getSubstreamCodec. The refactor is directionally sound, but I would not merge it as-is: one new carrier (SparseOffsets) is still classified by a logical UInt64 type that does not match its on-disk bytes, and the previously reported shared-Nested offset stream issue is still present in the current code.

Missing context / blind spots
  • ⚠️ Praktika exposed only Build profile diff for this PR; I did not have functional or performance CI results to validate the new benchmark coverage or catch runtime regressions automatically.
Findings

⚠️ Majors

  • [src/Storages/MergeTree/MergeTreeDataPartWriterWide.cpp:194-226, src/Storages/MergeTree/MergeTreeDataPartWriterCompact.cpp:79-115] [dismissed by author -- https://github.com/Adaptive codec selection for structural substreams #117348#discussion_r3905450817] Shared Nested offsets still let the first sibling decide whether the physical n.size0 stream is adaptive. With share_nested_offsets = 1, a schema like n.a Array(UInt64), n.b Array(UInt64) CODEC(ZSTD) creates n.size0 on the first sibling and the second sibling just reuses it, so an explicit-coded sibling can silently inherit mixed T64/NONE/default blocks or suppress adaptivity purely by declaration order. Master already had first-sibling reuse for generic codecs, but this PR newly makes that reused stream adaptive. Suggested fix: compute the shared-offset codec policy across all siblings that own n.size0, or keep shared Nested offsets non-adaptive until ownership is modeled explicitly.
  • [src/Storages/MergeTree/MergeTreeDataPartWriterOnDisk.cpp:742-751] The new typed-substream rule treats substream_path.back().data.type as evidence that the stream can use the regular adaptive pool, but SerializationSparse::enumerateStreams still marks SparseOffsets as UInt64 while serializeOffsets writes VarUInt group sizes plus an end-of-granule flag. That means sparse parts can now benchmark or choose T64 for a byte layout that is not a fixed-width UInt64 stream, so compression behavior depends on misleading metadata rather than the actual serialized bytes. Suggested fix: exclude SparseOffsets from adaptive selection until the serialization stops advertising a numeric type, or land the SerializationSparse change in the same PR.
Tests
  • ⚠️ Add a focused stateless test for shared Nested offsets with one default-coded sibling and one explicit-coded sibling. The current 05047_adaptive_codec_size_substreams case only covers the all-default layout and would not catch the declaration-order-dependent reuse of n.size0.
  • ⚠️ Add either a sparse-column stateless test or a small benchmark for SparseOffsets. Nothing in the current test set exercises the path where adaptive selection sees substream_type = UInt64 but the on-disk bytes are VarUInt groups.
Final Verdict

❌ Changes requested.

LLVM Coverage Report

Measured on commit 3cbd827.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 71/73 (97.26%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Aug 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3cbd827b1 with master 35a0d6f0c (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 323d42647; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

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

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

83 translation units recompiled, 802 s compile time in total, 83 of them have a recent master baseline.

Job report

@Michicosun Michicosun self-assigned this Sep 1, 2026

const auto & substream_type = substream_path.back().data.type;
/// Adaptive could pick an unencrypted codec for some blocks and drop the encryption. Thus skip adaptivity for an encrypting default.
if (settings.apply_adaptive_codec && column_uses_default_codec && substream_type && !resolved_codec->isEncryption())

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.

Shared Nested offsets make column_uses_default_codec too local here. With share_nested_offsets = 1, n.size0 is one physical stream, but addStreams in both writers creates it on the first sibling and later siblings just return on column_streams.contains / compressed_streams.contains. That means a table like (`n.a` Array(UInt64), `n.b` Array(UInt64) CODEC(ZSTD)) lets the first default-coded sibling wrap n.size0 in CompressionCodecAdaptive, and the explicit-coded sibling silently reuses that adaptive stream. The resulting codec depends on declaration order and violates the contract that only default-coded columns go adaptive. Please either keep shared Nested offsets non-adaptive or compute eligibility across all siblings that own the shared n.size0 stream, and add a focused regression test for that case.

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.

True, but the same complaint belongs to master. My change didn't create that, and fixing it properly is a separate, pre-existing question.

/// A structural substream goes adaptive if its serialized bytes = declared type and a candidate wins on size without losing read speed.
/// Excluded: null maps (adaptive wins size but reads slower), `SparseOffsets` (`UInt64` in memory, varint on disk).
const auto kind = substream_path.back().type;
const bool is_size_substream = kind == ISerialization::Substream::ArraySizes || kind == ISerialization::Substream::StringSizes;

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 looks hacky, can't we take into account deserialization time when choosing codecs?

@rienath rienath Sep 2, 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.

CI is green, but I agree. I will make rules structural and instead of an allowlist before merging

Michicosun
Michicosun previously approved these changes Sep 2, 2026
Previously we gated null maps. T64 alone does not compress them well. But we plan to add {codec + default} as a candidate, and T64 + LZ4 and T64 + ZSTD are better than LZ4 and ZSTD alone. The other one was SparseOffsets, which stored varint pretending to be UInt64. We will guard these off by a non-hacky rule instead (see next commits)
@Michicosun
Michicosun dismissed their stale review September 2, 2026 16:36

will be changed

@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 pushing me to improve the design. Now adaptivity applies to all substreams. Substreams without a type would get {default, None}. Substreams with a type would get the codecs based on the type.

There were two problematic cases previously:

  1. Null map almost always compressed worse with T64 as values of a map are binary. I benchmarked it with chain T64 + Default and saw a good improvement. Since adding chains is a follow-up, we can keep null maps adaptive.
  2. Sparse serialization offsets were VarUInt on disk, but we wrote UInt64 as the type in SerializationSparse.cpp. Thus it never compressed well. Instead of a hack to avoid it, I will make a follow-up PR that removes the type info from serialization. Then it will faithfully never receive T64 again

@clickhouse-gh clickhouse-gh Bot added the comp-codecs Compression/encoding codecs (LZ4/ZSTD/etc.), archive formats (tar/zip/7z), codec selection and IO... label Sep 4, 2026

/// Adaptive could pick an unencrypted codec for some blocks and drop the encryption. Thus skip adaptivity for an encrypting codec.
if (settings.apply_adaptive_codec && column_uses_default_codec && !codec->isEncryption())
return std::make_shared<CompressionCodecAdaptive>(substream_type, 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.

substream_type is not a reliable proxy for "the bytes in this stream match a regular typed column". SerializationSparse::enumerateStreams still tags SparseOffsets as UInt64, but serializeOffsets writes VarUInt group sizes with an end-of-granule flag. After this change, that stream now goes through the regular adaptive pool and can benchmark or pick T64 even though the on-disk payload is not a fixed-width UInt64 stream.

Please keep SparseOffsets out of adaptive selection until the serialization stops advertising it as UInt64, or land that SerializationSparse change in this PR. Otherwise sparse-column compression and read trade-offs depend on misleading metadata rather than the actual byte layout.

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.

It is, what you describe is a bug I've fixed in #118048

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-codecs Compression/encoding codecs (LZ4/ZSTD/etc.), archive formats (tar/zip/7z), codec selection and IO... 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.

3 participants