Skip to content

Use actual codec to estimate compressed column sizes for dataflow statistics - #114535

Merged
nickitat merged 6 commits into
masterfrom
autopr-input-bytes-compact-part-codec
Sep 5, 2026
Merged

nickitat merged 6 commits into
masterfrom
autopr-input-bytes-compact-part-codec

Conversation

@nickitat

@nickitat nickitat commented Aug 12, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

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

Take a column's CODEC into account when estimating how many bytes a query reads from compact parts. The estimate compressed a sample with the default codec (LZ4) no matter how the data is really stored, so a column stored with a stronger codec was overestimated, which inflates effective_max_reading_threads and can make automatic parallel replicas distribute a query that is cheaper to run on a single node.


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

Version info

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

`RuntimeDataflowStatistics` estimates how many compressed bytes a read step
will read, and `considerEnablingParallelReplicas` turns that into
`effective_max_reading_threads` when deciding whether parallel replicas are
worth it. Wide parts store per-column sizes, so the estimate reads them off the
part. Compact parts store none, and the estimate fell back to compressing a
sample of each column with `CompressedWriteBuffer`, which uses the built-in
default codec - `LZ4`.

That models the wrong thing whenever the data is stored with another codec, and
it is wrong in one direction only: `LZ4` compresses worse than `ZSTD`, so the
estimate comes out too large. Measured on a compact part of TPC-H `lineitem`
columns stored with `ZSTD(1)`, the estimate was 54.0 MB against 35.8 MB really
read, and on the sequential integers of the new test 4.52 MB against 1.29 MB -
a 3.5x overestimate. The error does not stay proportional either: it inflates
`effective_max_reading_threads`, which is what flips the decision to spread a
query across replicas that cannot pay for the coordination.

A compact part does have measured compressed and uncompressed totals for all
its columns together, so use that ratio instead of modelling one. It is
codec-correct by construction - including per-column `CODEC` overrides, which
are not recorded in the part's columns metadata at all and so cannot be
recovered from it - and it costs nothing, where sampling costs a compression
pass per block. The assumption it makes in exchange is that columns inside a
part compress alike, which matters only when a query reads a subset of them;
it is exact for the whole part.

Sampling stays for parts with no measured totals, such as those whose checksums
are not loaded.
The previous commit derived the compression ratio of a compact part from the
part's measured totals. That is codec-correct, but it assumes every column in a
part compresses alike, and they do not: on `hits` the ratio ranges from barely
compressible to more than an order of magnitude, so a query reading a subset of
the columns gets an estimate smeared towards the part average. Measured on two
`lineitem` columns stored with `ZSTD(1)`, the part ratio was off by -29.5% and
+26.5% respectively.

Go back to sampling, but hand `CompressedWriteBuffer` the codec the column is
actually stored with instead of letting it use its built-in default. The codec
cannot be recovered from the part - `default_codec` is only the part-wide
default, and a part's `ColumnsDescription` is built from a `NamesAndTypesList`,
which carries no codec at all - so it is resolved from the table metadata that
the readers already hold, the same way `IMergeTreeDataPartWriter` resolved it
when writing. Only columns that override the part default need an entry, and
they are resolved once per read task rather than per block.

This keeps per-column resolution and is accurate either way: on the same two
columns the estimate is now within 0.2%, and the whole-part reads that the part
ratio got exactly right stay within 0.1%.
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [aae8153]

Summary: ✅


AI Review

Summary

The PR changes compact-part sampling in RuntimeDataflowStatistics to stop using the built-in default codec and instead resolve codecs from table metadata, and it adds regression coverage for the exception-on-composite cases. That improves several schemas, but the implementation still reconstructs the write codec from lossy metadata, so automatic_parallel_replicas_mode can still make decisions from non-actual compact-part byte estimates on realistic tables.

Findings
  • ⚠️ Major [src/Storages/MergeTree/MergeTreeReadTask.cpp:143] Default-coded compact-part columns written with allow_experimental_adaptive_codec_selection are still sampled with the base part default, not the actual per-block codec. IMergeTreeDataPartWriter::maybeAdaptiveDefaultCodec can choose NONE or a specialized codec per block for those streams, while default_compression_codec.txt intentionally stores only the base default, so this path can still misprice RuntimeDataflowStatisticsInputBytes and skew automatic_parallel_replicas_mode. Suggested fix: if adaptive default-coded blocks are meant to be supported, derive the sample codec from the on-disk stream headers; otherwise mark this compact-part case unsupported instead of silently sampling it as plain default_codec.
  • ⚠️ Major [src/Storages/MergeTree/MergeTreeReadTask.cpp:58] [dismissed by author -- https://github.com/Use actual codec to estimate compressed column sizes for dataflow statistics #114535#discussion_r3808100262] Multi-stream columns with type-specific codecs still do not use the actual on-disk codec. resolveCodecForWholeColumn drops every non-generic codec as soon as a column has more than one stream, so Nullable(...) CODEC(GCD, LZ4), Array(...) CODEC(Delta, ZSTD(1)), or Tuple(...) CODEC(T64) are sampled as only the generic codec or even NONE, while the part writer applies GCD/Delta/T64 to the data substreams. That leaves compact-part byte estimates materially biased on supported schemas. Suggested fix: either sample per substream codec and combine the result, or treat multi-stream columns with type-specific codecs as unsupported instead of collapsing them to generic-only codecs.
  • ⚠️ Major [src/Storages/MergeTree/MergeTreeReadTask.cpp:144] [dismissed by author -- https://github.com/Use actual codec to estimate compressed column sizes for dataflow statistics #114535#discussion_r3769897373] The estimator still resolves per-column codecs from live table metadata rather than from the codec this compact part was written with. During ALTER TABLE ... MODIFY COLUMN ... CODEC(...) and the ensuing mutation, old compact parts can coexist with new metadata for a long time, so historical parts are sampled with a codec that was never used for them. Suggested fix: if per-column codec history is unavailable in the part, fail closed for these mixed-codec compact parts instead of sampling with current metadata.
Tests
  • ⚠️ 04839_autopr_input_bytes_estimation_codec_types only proves that the read no longer throws. There is still no focused check that ProfileEvents['RuntimeDataflowStatisticsInputBytes'] stays close to ProfileEvents['ReadCompressedBytes'] for a multi-stream column with type-specific codecs, or for a compact part written with adaptive codec selection if that surface is supposed to work.
Final Verdict

⚠️ Needs changes before merge: the current implementation still cannot honestly claim to use the "actual codec" for several compact-part cases, so the cost model remains wrong on realistic schemas.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 50/56 (89.29%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing aae815306 with master 12e8fa319 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 704.42 MiB 701.39 MiB -3.03 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

69 object files changed (+43.99 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeReadTask.cpp.o 232.94 KiB 262.70 KiB +29.76 KiB (+12.78%)
src/CMakeFiles/dbms.dir/Storages/NATS/StorageNATS.cpp.o 568.35 KiB 597.33 KiB +28.98 KiB (+5.10%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@nickitat nickitat changed the title Estimate compact-part input bytes from the part's measured ratio Use actual codec to estimate compressed column sizes for Dataflow statistics Aug 13, 2026
@nickitat nickitat changed the title Use actual codec to estimate compressed column sizes for Dataflow statistics Use actual codec to estimate compressed column sizes for dataflow statistics Aug 13, 2026
The estimate resolved a column's `CODEC` against the whole column type, but a
codec is never applied to a column as a whole: the writer resolves it per
substream against the substream's type, and for structural substreams (`Array`
offsets, null map, ...) it drops the type-specific codecs and keeps only the
generic ones. Asking the factory for a type-specific codec with a composite type
throws, so a legal table such as `Tuple(UInt32, Array(UInt64)) CODEC(T64)` or
`Nullable(Int64) CODEC(GCD)` failed to read as soon as the statistics updater was
attached, with the exception escaping into `MergeTreeSelect`:

  Code: 431. T64 codec is not supported for specified type Tuple(UInt32, Array(UInt64))
  Code: 36. Codec GCD cannot be applied to column Nullable(Int64)

Follow the same rule as the writer: use the type-specific codec chain only when
the column is a single stream carrying the column type itself, i.e. a plain
numeric or date column, where `Delta`/`T64` do drive the ratio; otherwise keep
only the generic codecs, which dominate the ratio anyway and can be built for any
type. Also substitute the server default when a part carries no codec of its own,
so a borrowed part cannot pass a null codec to `CompressedWriteBuffer`.

Reproduced by tests `01504_compression_multiple_streams` and `02872_gcd_codec`
under randomized parallel-replicas settings:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114535&sha=e760449095e7e7062620682d2112d9e35b727bf9&name_0=PR
#114535

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mo4KqdD9kXtX2Rz8DGDJtF
nickitat and others added 2 commits August 20, 2026 15:28
`test_cluster_one_shard_three_replicas_secret` was swept into `dd2a92f39ecbb`
from a different investigation. No test on this branch, or anywhere else in the
repository, references it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01USSfxYr3RqkPzJ4GVphmtS
`ColumnCodecByName` is built once per read task and lives as long as the task,
so it is one allocation per task per column with a `CODEC`, on the query's
memory. Use `UnorderedMapWithMemoryTracking`, which accounts through the
throwing methods of the `MemoryTracker` instead of the non-throwing ones that
plain `std::unordered_map` goes through. Both the map and everything that
touches it use the same alias, so nothing is copied by the change.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01USSfxYr3RqkPzJ4GVphmtS
@nickitat
nickitat marked this pull request as ready for review August 21, 2026 12:16
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

Release-transition baseline: compared against the last 26.8 master because no 26.9 master baseline exists at or before the trusted base-commit anchor.

This PR changes the runtime dataflow-statistics input-bytes estimation to compress column samples with each column's actual codec instead of the built-in default, which alters the per-read serialization work done during MergeTree reads. ClickBench Q34 shows a +5.1% shift that is consistent across both tests but lands inside master's normal variance band, so the math suppressed it to not_sure; because Q34 is a read that directly exercises the changed sample-compression path, we surface it rather than hide it as pure noise. Estimating with a heavier real codec is a plausible cause of the small added cost, but the delta is borderline and not a confirmed regression. No other queries were flagged.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 34 not_sure 1228 1291 +5.1% 0.0001 cpu: The changed sample-compression estimation now uses each column's real codec instead of the default, adding read-path serialization work Q34 exercises; +5.1% is borderline and within master's normal range.

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: 5be62148-ec55-4152-87da-54fe30918a4f
  • MIRAI run: 3e254704-02e3-46b0-89f2-2ca354f11530
  • PR check IDs:
    • clickbench_312703_1787659431
    • clickbench_312714_1787659432
    • clickbench_312727_1787659431
    • tpch_adapted_1_official_312733_1787659431
    • tpch_adapted_1_official_313113_1787659465
    • tpch_adapted_1_official_313226_1787659509

@nickitat
nickitat requested a review from devcrafter August 25, 2026 17:11
@devcrafter devcrafter self-assigned this Aug 25, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
@nickitat
nickitat added this pull request to the merge queue Sep 4, 2026
Merged via the queue into master with commit d2fd9fe Sep 5, 2026
346 of 348 checks passed
@nickitat
nickitat deleted the autopr-input-bytes-compact-part-codec branch September 5, 2026 01:02
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 5, 2026
Comment on lines 103 to +104
NullWriteBuffer null_buf;
CompressedWriteBuffer compressed_buf(null_buf);
CompressedWriteBuffer compressed_buf(null_buf, codec);

@rienath rienath Sep 6, 2026 •

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.

Suggested change
NullWriteBuffer null_buf;
CompressedWriteBuffer compressed_buf(null_buf);
CompressedWriteBuffer compressed_buf(null_buf, codec);
CompressedSizeCalculator calc(codec);

We can use CompressedSizeCalculator here. Not critical, just to raise awareness it exists :)

pull Bot pushed a commit to sjoerd2025/ClickHouse that referenced this pull request Sep 6, 2026
…es not match

The input-bytes estimate for a compact part serializes a sample of every column it
reads and compresses it with the column's `CODEC`, resolved once per read task from
the table metadata. The metadata does not describe that sample on its own, and the
estimate used the type-specific codec regardless:

- the serialization is chosen per block from the column at hand, so a column stored
  `Sparse` (or `Replicated`) arrives as several substreams funnelled into one buffer;
- a column read from a part keeps its pre-`ALTER` type until the mutation that
  rewrites it has run, while the codec was resolved for the new type.

A type-specific codec then measures a stream it was never resolved for. Most only
mismeasure it, but `ALP` validates its input and fails the query outright:

    Cannot compress with ALP(RD) codec, data size 19209 is not aligned to 4.
    (CANNOT_COMPRESS)

Resolve both the type-specific and the generic-only codec up front and pick between
them from the serialization and the type the sample actually has, keeping only the
generic codecs for every other shape - exactly what the writer does for structural
substreams.

Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=3324e948a5143641935d0389afbe55193545c4f2&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%29
Caused by: ClickHouse#114535
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-improvement Pull request with some product improvements 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