Skip to content

Correct estimated compression ratio in a couple of cases - #120190

Merged
nickitat merged 26 commits into
masterfrom
autopr-compressed-state-size-estimate
Oct 12, 2026
Merged

nickitat merged 26 commits into
masterfrom
autopr-compressed-state-size-estimate

Conversation

@nickitat

@nickitat nickitat commented Sep 15, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Version info

  • Merged into: 26.10.1.2204-master (included in 26.10 and later)

nickitat and others added 3 commits September 11, 2026 21:02
`RuntimeDataflowStatisticsCacheUpdater` estimates how many bytes the replicas
would send to the initiator, and the automatic parallel replicas cost model
divides that estimate by the number of replicas to price the transfer. Two
things made it several times too large.

`Aggregator::estimateSizeOfCompressedState` builds a `CompressedWriteBuffer`
over a `NullWriteBuffer` and then serializes every sampled state past it,
straight into the null buffer, so the `wb.count()` it scales up is the
serialized size and not the compressed one the comment above it describes.

The group keys were sampled in the wrong row order. The statistics come from the
single-node plan, whose `MergingAggregatedBucketTransform` is given an empty
`required_sort_description` and emits in hash-table order, while the replicas run
that same transform over a `WithMergeableState` - which does produce results in
bucket order, so memory-bound merging applies there and sorts by the group by
keys. Compressing one and the same sample both ways, a monotonic `UInt64` key
column reaches 3.0-3.9x in hash order and 7.8x sorted, and 7.8x is what the wire
achieves. So the sample is put into key order first, by a permutation built only
for a block that is actually sampled and only where the two plans differ this
way.

Measured against what the replicas actually put on the wire - with compression
forced on every replica of the test cluster, since a replica whose address looks
local is not compressed by default and its share alone moves the total severalfold:

  aggregation in order, `UInt64` keys   4.3-9.0x too large -> 1.9-3.2x
  aggregation in order, `UInt32` keys   up to 1.9x         -> up to 1.2x
  plain hash aggregation               up to 1.9x          -> up to 1.3x

What remains is the aggregate states, which `estimateSizeOfCompressedState`
samples from the hash table and so cannot put in key order without the keys. It
reads high on states that repeat their group key and low on states that do not,
so ordering that sample would trade one for the other.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01WCjBRRshJunXWy6z6FwvUd
Both comments explaining `setReplicasSendOutputInKeyOrder` named the two plans
only as "there" and "here", and never said what the sample is for or why its row
order matters. Say which plan each order belongs to, and that hash table order
compresses several times worse than the key order the replicas send in.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b9693db]

Summary: ✅


AI Review

Summary

This PR fixes the obvious CompressedWriteBuffer bug in Aggregator::estimateSizeOfCompressedState and improves the key-order accounting for materialized aggregation output, but I do not think it is fully review-clean yet. One of the newly added branches still has no regression coverage, and the remaining aggregate-state path is still knowingly biased enough to reject some beneficial parallel-replicas plans.

Findings

⚠️ Majors

  • [dismissed by author -- https://github.com/Correct estimated compression ratio in a couple of cases #120190#discussion_r4018147567] tests/queries/0_stateless/05184_autopr_output_bytes_key_order.sql:10, src/Processors/QueryPlan/Optimizations/considerEnablingParallelReplicas.cpp:1015 — the new regression still never enables parallel_replicas_plan_based = 1 with distributed_aggregation_memory_efficient = 0, even though the new branch in considerEnablingParallelReplicas exists specifically because the plan-based implementation disagrees with the query-based one there. Today the fix is exercised only on the query-based path, so the exact divergence this PR added logic for can regress silently. Suggested fix: add a variant that pins parallel_replicas_plan_based = 1, distributed_aggregation_memory_efficient = 0, and enable_memory_bound_merging_of_aggregation_results = 1.
  • [dismissed by author -- https://github.com/Correct estimated compression ratio in a couple of cases #120190#discussion_r4020798813] src/Processors/QueryPlan/Optimizations/RuntimeDataflowStatistics.cpp:288, src/Interpreters/Aggregator.cpp:5946, src/Processors/Transforms/MergingAggregatedMemoryEfficientTransform.cpp:455, tests/queries/0_stateless/04100_autopr_input_bytes_estimation_aggregation_in_order.sql:82 — the key-order fix still stops at the materialized-column path. In the multi-stream bucket merge, aggregate states are still priced by recordAggregationStateSizes before the later sortBlock(required_sort_description), and the test now explicitly accepts a persistent 1.8x–2.1x overestimate for that reason. That is still a real AutoPR false-negative: queries whose states compress much better in key order can be priced high enough to keep parallel replicas disabled even when the actual wire cost is low. Suggested fix: either defer aggregation-state accounting until after the final sort and reuse recordAggregationStateColumnSizes, or teach recordAggregationStateSizes the same key-order permutation.
Final Verdict

⚠️ The core direction looks right, but I would not sign this off yet: the plan-based branch the PR just introduced still is not pinned by a regression, and the remaining aggregate-state overestimate is still large enough to affect automatic_parallel_replicas_mode decisions.

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Sep 15, 2026
`keyOrderPermutation` declares a `SortDescription`, but the definition
reached this translation unit only through `Interpreters/JIT/compileFunction.h`,
which includes it under `#if USE_EMBEDDED_COMPILER`. The fast test builds
without the embedded compiler, so there only the forward declaration from
`Interpreters/sortBlock.h` was visible:

    RuntimeDataflowStatistics.cpp:150:21: error: variable has incomplete type 'SortDescription'

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120190&sha=b312dbdd5f010fd08ffc0d3e0526ca442e1cf19b&name_0=PR&name_1=Fast%20test
#120190

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The replica sorts with its own `group_by_sort_description`, whose prefix takes
its direction from the read order, so the permutation built here need not be
the same one. It does not have to be: the compression ratio responds to equal
and neighbouring keys ending up adjacent, and sorting the same 1M rows
descending instead of ascending moves every column by less than 0.02% - keys,
`String`, the `Nullable` null map and aggregate states alike.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Whether a replica sorts its partial aggregation output by the group by keys was
reconstructed inside `AggregatingStep::transformPipeline` by assuming the
replica produces results in bucket order. That holds for the query-based
parallel replicas, where `Planner` turns bucket order on for a
`WithMergeableState` plan under either `distributed_aggregation_memory_efficient`
or `enable_memory_bound_merging_of_aggregation_results`, but not for the
plan-based one, where `applyParallelReplicas` turns it on under
`distributed_aggregation_memory_efficient` alone. With that setting off and
memory-bound merging enabled, the replicas send hash-table order while the
sample was being sorted, which prices the transfer low.

Read the decision off the replicas plan instead: it is available where the
updater is created, and the step that will run there answers for whichever
implementation built it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
nickitat and others added 2 commits September 15, 2026 22:03
`estimateSizeOfCompressedState` serializes about a hundred sampled states
through a `CompressedWriteBuffer` and scales what reaches the null buffer by the
sampling period. That byte count also carries the frame's checksum and header,
and the scaling multiplies them: with a two-level table that is 25 bytes times
the period times 256 buckets, which for cheap states - a `count` state is a
varint - outweighs the states themselves. Pricing the states compressed then
made the estimate grow where it should have shrunk.

Measured on `test.hits` with three replicas, `GROUP BY SearchPhrase` went
5534872 before the compressed pricing to 6307261 after it, and `GROUP BY UserID`
1500135 to 2303049. Charging only the compressed payload brings them to 2796408
and 1711704. A replica writes its states into full blocks, where the frame
overhead is amortized to nothing, so the payload is what it puts on the wire.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The recorded values were network bytes received from the replicas, measured on
the test cluster, where every replica address looks local and is therefore
shipped uncompressed (`Cluster.cpp` defaults `compression` to `!is_local`). That
is several times more than any real cluster transfers, and the estimate of the
day matched it only because it overshot by the same factor.

Re-measured on 2e6 rows with compression forced on every replica, the five
queries transfer 4158835, 4150820, 2115022, 5043367 and 646299 bytes. The
estimate is now 1.8x, 1.9x, 1.9x, 2.9x and 2.1x of that, against 4.9x to 9.0x
before this branch. The new expectations are the estimate itself, with those
measurements recorded in the comment as the anchor.

Ten consecutive runs pass; repeated runs agree exactly on three of the five
queries and within 15% on the other two, well inside the 2x window.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120190&sha=c6df0a4df7ae4c55f46575a0121bb84172356225&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29
#120190

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
nickitat and others added 2 commits September 16, 2026 11:31
The expectations were the estimate itself, which made the check circular. They
are now `NetworkReceiveBytes` on the initiator, measured with the local plan
disabled and compression forced on every replica - without forcing it every
replica address of the test cluster looks local and ships uncompressed, which is
what made the previous values several times too large.

`agg_in_order_multi_agg` is dropped. Its `min(s)` states are sampled from the
hash table, so they are priced in hash-table order while the replicas send them
in key order, and the estimate lands 2.9x off the transferred bytes - the check
would have measured that defect rather than the estimate. The remaining shapes
run 1.8x to 2.1x high for the same reason on a smaller scale (their `sum(value)`
is a monotone function of the key), so the tolerance is 2.5x. Over ten runs the
estimates span 1.78x to 2.09x and the transferred bytes vary by 0.1%.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
SELECT format('{}: output estimation off by {}x (expected~{}, estimated={})', log_comment, round(ratio, 2), expected, statistics_output_bytes)
-- Check the output bytes estimate against what the replicas actually send (ratio within 2.5x).
-- The expected values are `NetworkReceiveBytes` on the initiator, measured on 2e6 rows with the local
-- plan disabled and compression forced on every replica of the cluster.

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.

and compression forced on every replica of the cluster

This is what I haven't done when calculated these reference values, so the bug wasn't detectable because both estimations and references were uncompressed.

@nickitat nickitat changed the title Correct estimated compression ratio in two cases Correct estimated compression ratio in a couple of cases Sep 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit b9693dbd15c75ca88651a9baced78f7e05c6e658 was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ { "name": "file", "type": "LowCardinality(String)" …).

See the job log for details.

alexey-milovidov added a commit that referenced this pull request Sep 17, 2026
…` to the transferred bytes

The expected output sizes were the uncompressed serialized sizes of the
states - what the estimator reported before it serialized its sample through
the compression buffer - so the corrected estimate could only fail against
them: 8.9 MB against an expected 25.5 MB for `agg_in_order_single`.

The new expected values are `NetworkReceiveBytes` on the initiator, measured
with the local plan disabled, `network_compression_method = 'zstd'` and
compression enabled on every replica (the test cluster's replicas are local
addresses, for which `Cluster` disables compression by default, so a plain run
transfers the uncompressed 32 MB). They agree with the values measured
independently in #120190 to
within 0.1%. The estimate runs 2.1x-3.2x high on these shapes, because the
merged hash tables' states are sampled and compressed in hash-table order
while the replicas send whole blocks in key order; the tolerance is 3.5x for
now and can be tightened once the key-order pricing lands.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111985&sha=790c9d74856a16dca62d2b06f29c76c703145aee&name_0=PR&name_1=Stateless%20tests%20(amd_debug%2C%20parallel)
PR: #111985

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@nickitat
nickitat marked this pull request as ready for review September 17, 2026 08:56
@nickitat
nickitat requested a review from rienath October 6, 2026 10:59
nickitat and others added 5 commits October 6, 2026 17:02
One conflict, in the Top-K overload of `recordAggregationKeySizes`: master gave
it a bounded sample of the untruncated keys to take the compression ratio from,
while this branch gave it the row order the replicas send in. The resolution
takes the key order from whichever columns are priced - the sample when the
conversion kept one, the chunk otherwise.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The expectations dated from different estimator generations and had drifted:
`query_12` read 2640000 where both master and this branch now produce ~6.5M, so
the ratio sat on the 2.5x threshold and tipped over on run-to-run randomization -
master commit ed7e72d reported 6625852 in the same
`amd_asan_ubsan, distributed plan` check on 2026-10-03, and this branch reports
6626070 and 6667827. `query_43` was 1.5x stale the same way and failed on master
in `amd_release` on 2026-09-26.

They are now `NetworkReceiveBytes` on the initiator, measured per query with
`parallel_replicas_local_plan = 0`, `prefer_localhost_replica = 0` and compression
forced on every replica - without forcing it every replica address of the test
cluster looks local and ships uncompressed, which is not what a real cluster
transfers. `serialize_query_plan` moves the estimate by less than 0.4%, so the one
set of values covers both parallel-replicas implementations.

Queries transferring less than 100 KB are no longer checked: at that size the
bytes on the wire are mostly protocol framing and per-replica fixed cost, which
the estimate does not model. The six that remain land between 1.05x and 1.80x.

Fifteen runs pass with the binary CI built for this branch: ten with the plain
settings and five with `serialize_query_plan = 1`, the setting of the job that
reported the failure.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120190&sha=42c801eb0704bf82fe25ae22125e038241939bbf&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20distributed%20plan%2C%20targeted%29
#120190

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Skipping the pairs whose transfer stays under 100 KB also meant an estimate that
blew up on them could never fail the test. Each pair is compared again, and the
100 KB is an absolute slack instead: a pair has to differ both by more than 2.5x
and by more than 100 KB. Below that the difference is protocol framing and
per-replica fixed cost - a single-row `COUNT(*)` result costs about 17 KB on the
wire against a 12-byte estimate - while an estimate that runs away on those
queries moves the difference past the slack and is caught.

Measured while re-recording the expectations: `parallel_replicas_local_plan` has
to stay 0 for the measurement. With the local plan on, the local replica wins the
range race on a warm single-machine cluster and almost nothing crosses the wire:
`query_12` transfers 5358127 bytes with it off and 4675 with it on, and
`query_15` swings between 3421 and 260928 between runs. Suppressing the progress
and profile-event packets takes only 1-6 KB off the small transfers and nothing
off the large ones, so it does not make those queries comparable either.

Fourteen runs pass with the binary CI built for this branch, ten plain and four
with `serialize_query_plan = 1`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The slack comes down from 100 KB to 64 KB: over 35 runs the widest difference it
has to absorb is 51922 bytes on `query_22`, then 49676 on `query_23`, so 64 KB
keeps about a quarter of headroom and nothing more.

The same 35 runs show the ratio cannot stay at 2.5x, though. `query_10` reaches
2.48x - its estimate swings between 145883 and 204903 because `uniqExact` states
are sampled from the hash table - and its difference from the transferred bytes is
216319, so no slack covers it. At 2.5x that query alone would have flaked the way
`query_12` just did, so the ratio goes to 3x. Every other pair stays well inside:
`query_28` 1.08x, `query_43` 1.18x, `query_34` 1.69x, `query_15` 1.82x and
`query_12` 1.84x.

Replaying all 35 recorded runs through the new predicate flags none of the eleven
queries, and eight more runs with the binary CI built for this branch pass, five
plain and three with `serialize_query_plan = 1`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The transfer and the estimate agree only because two defaults coincide:
`network_compression_method` is `ZSTD` at level 3 and `getDefaultCodec`, which the
estimate prices with, is `ZSTD(3)`. Measured against a cluster that sets `LZ4` the
same queries transfer 1.04x to 1.66x more - `query_43` 54328834 instead of
32658851 - so a re-measurement there would record values that do not belong with
this estimate. Say so where the values are recorded.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
nickitat and others added 10 commits October 8, 2026 17:25
The ratio the output estimate scales by was measured one output block at a time,
and a codec measures only as good a ratio as the window it is given: over the
same `String` key column `ZSTD(3)` reaches 1.46x on 2.8 KB and 3.30x on 553 KB.
What arrived in that window was whatever the output happened to be split into. A
single-stream aggregation emits a few large blocks and measured 3.30x; a
multi-stream one emits many small blocks - the bucket Top-K conversion hands over
a bounded sample of each bucket, a few dozen rows - and measured 1.46x. The same
`GROUP BY SearchPhrase` was therefore estimated at 2793157 bytes with one thread
and 6400586 with two, and the thread count is whatever the machine gives.

So gather the sampled rows instead of compressing them block by block, and
compress a block's worth of them once, at the end. `query_12` of 03634 now
estimates 2661778 with one thread and ~3356000 with two or more - 1.26x apart
instead of 2.30x - and repeats within 0.2% at a fixed thread count instead of 3%.
`query_10`, whose estimate swung 145883..204903 over 35 runs and was the next
query about to flake, now repeats exactly.

Against the bytes the replicas actually transfer the estimate also lands closer:
`query_34` 1.63x off becomes 1.17x, `query_28` 1.05x becomes 1.01x, `query_43`
1.18x becomes 1.12x; `query_15` goes the other way, 1.16x to 1.52x. One
compression of a 148 KB window costs 983 microseconds where five of a few KB each
cost more, and the sample is capped at a block of rows or 4 MiB, whichever comes
first.

Ordering the sample by the group by keys still earns its place and is kept: on
the same queries it takes the estimate from 9721403..10713407 down to a repeatable
7694587 (04100's multi-stream shape) and from 4398570 to 3431547 (05184). Its
margin over hash order is smaller than it was, though - over a block's worth of
rows the codec finds the structure of a monotonic `UInt64` key in either order -
so 05184 asks for 1.3x rather than 2x.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
3x was there for `query_10`, whose estimate swung between 145883 and 204903 and
reached 2.48x of the transferred bytes. With the ratio now measured over a block's
worth of rows that query reports 198565..198636 - 1.82x, repeating within 0.04% -
and the widest ratio outside the slack is 2.02x on `query_12`, which still varies
with the thread count. 2.5x keeps about a quarter of headroom over it.

The slack stays at 64 KB: the widest difference it has to absorb is 49676 bytes
on `query_23`, so there is little to take off it.

Ten runs pass, six plain and four with `serialize_query_plan = 1`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The gathered sample was compressed in the updater's destructor, which puts a
block's worth of rows - up to 17 milliseconds of serializing and `ZSTD(3)` - on
whichever thread tears the query down, after the query has produced its result,
and on one thread however many were aggregating.

`appendToSample` now says when its call is the one that filled the sample, and
that caller compresses it: the work lands on a pipeline thread while the query is
still running, alongside the other threads' work. The destructor still compresses
a sample that never filled, which is as small as the sampling got.

The estimate is unchanged - `GROUP BY SearchPhrase` still reports 2661778 with one
thread and ~3356000 with four or sixteen, off a 4429891 and 148754 byte sample
respectively.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The destructor call stays, because something has to compress a sample that never
reached the budget, and an output smaller than a block's worth of rows is most of
them: only the sample that fills is handed to the thread that filled it. What it
compresses is capped at 8192 rows now, so the query's teardown path carries a
couple of milliseconds at the very most rather than a whole budget's worth.

The cap changes nothing measured: the samples that reach the destructor are far
smaller than it. `GROUP BY SearchPhrase` on four threads gathers 148754 bytes -
the bucket Top-K conversion bounds what each call offers - and takes 1047
microseconds; the few-group queries gather about 4 KB and take 70. The 4429891
byte sample of the same query on one thread is the one that fills, and its 16
milliseconds are spent mid-query.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Reverts "Measure the compression ratio over a block's worth of rows", "Compress
the sample on the thread that fills it", "Cap what the destructor may compress of
an unfilled sample", and the ratio tightening that depended on them.

Two reasons. It does not belong in this pull request, which prices the estimate -
the compressed size of the states and the row order the replicas send in - and has
no business reshaping how the sample is gathered.

And its premise was wrong. It gathered rows across blocks to compress them as one
window, on the grounds that a wider window is what the wire achieves. The wire does
no such thing: `TCPHandler::sendData` writes a block and then calls
`maybe_compressed_out->next()`, so every block is compressed as its own frame, in
the shape the pipeline produced it. Block borders are exactly what the estimate
should keep.

What the measurements do show is still worth following up on, separately: the
blocks the probe plan hands the recorder are not shaped like the blocks a replica
would send. With one thread it offers a few large ones and the ratio comes out
3.30x; with more, the bucket Top-K conversion offers a few dozen rows at a time and
the same column measures 1.46x, while a replica sending `WithMergeableState` would
frame a whole bucket. Matching the sampled block to the one a replica sends is the
fix, not concatenating blocks the wire keeps apart.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The ratio is measured per output block, the way the wire compresses it, so how
the output is split into blocks is what the codec gets to work with: a
single-stream aggregation hands over a few large blocks and the same `String` key
column measures 3.30x, while many streams hand over the bucket Top-K conversion's
bounded samples - a few dozen rows - and measure 1.46x. With `max_threads = 0` the
estimate followed whatever thread count the machine gave: across 35 runs
`query_12` ranged over 2924508..6655105 and `query_10` over 145883..204903, and
that is what put this test on its threshold.

Pinning it to 16 pins the block shape. Over three runs each query repeats within
3% - `query_10` within 0.2%, `query_12` within 2.1% - and the widest ratio outside
the slack falls to 1.80x on `query_10`, so the ratio goes back to 2.5x with about
40% of headroom. The slack stays at 64 KB, which `query_23` needs 49676 of.

Thirteen runs pass, ten plain and three with `serialize_query_plan = 1`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Master moved the statistics state out of `RuntimeDataflowStatisticsCacheUpdater`
into a shared `RuntimeDataflowStatisticsBlock`, so the updater now holds that
block and a `duplicated` flag instead of the arrays. The key order the replicas
send in stays on the updater, which is where it is decided and read:
`replicas_send_output_in_key_order` and `keyOrderProviderFor` sit next to the two
new members, and the updater built in `considerEnablingParallelReplicas` is told
about the order after the block is created. The second updater master creates
there for the duplicated reads is left alone - it accounts reads, not output.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The flaky check hands every worker the same changed test, so a test there contends
with `--jobs N` copies of itself rather than with unrelated tests, and
`clickhouse-test` exempts a `long` test from its 180 second verdict for exactly
that reason. Over 4192 runs of the flaky check 05184 has a median of 20.5s and one
run reached 355.5s, which is the red on this pull request; 05183 has a median of
10.3s and reaches 119.1s, close enough to the verdict to be worth the same tag.
Both sit far below it everywhere else - the targeted and parallel jobs measure 8.2s
and 13.9s medians - and the other estimation tests, 03634 and 04100, already carry
the tag.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120190&sha=latest&name_0=PR
#120190

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@nickitat
nickitat enabled auto-merge October 12, 2026 14:19
@nickitat
nickitat added this pull request to the merge queue Oct 12, 2026
Merged via the queue into master with commit 610f78b Oct 12, 2026
340 of 343 checks passed
@nickitat
nickitat deleted the autopr-compressed-state-size-estimate branch October 12, 2026 15:13
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 12, 2026
alexey-milovidov added a commit that referenced this pull request Oct 13, 2026
…-compressed-size-estimate

Conflicts with #120190, which priced the
sampled aggregate states compressed as well:
- `Aggregator::estimateSizeOfCompressedState`: keep this branch's version (sample measured
  with the wire codec, `CompressedStateSizeEstimate` with the compression clamp), which
  already writes the sample through the compressing buffer - the bug master fixed.
- `RuntimeDataflowStatistics`: keep both the wire codec of this branch and master's
  `KeyOrderProvider`. `recordColumns` takes both; the compression of a sampled block,
  including the serialized state leaves, is measured on the columns permuted into the
  replicas' key order, while the uncompressed sizes come from the original columns.
- `03634_autopr_output_bytes_estimation` and `04100_...`: take master's values, which are
  now measured against the transferred bytes rather than the estimate itself.
- `gtest_aggregator_state_size_estimate`: pass the new `use_aggregation_memory_tracker_`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Oct 19, 2026
… that read periodic data

`04034_autopr_min_rows_per_replica_reuses_index_analysis`,
`04034_autopr_dataflow_cache_reuse_between_different_queries`,
`05024_autopr_plan_based_parallel_replicas` and
`05059_autopr_settings_in_select_settings_clause` create the same table, insert the same
periodic data (`number % 1000 / 500 / 200`) and assert that the query reusing the collected
statistics chooses parallel replicas. With the tests' pinned `max_threads = 4` and
`max_parallel_replicas = 3` the gate in `considerEnablingParallelReplicas` reduces to
`input_bytes > 2 * output_bytes`, where `input_bytes` is the compressed size of the read.

A `Wide` part (`min_bytes_for_wide_part = 0`) with a ZSTD server codec compresses the 7 MB
read to ~131 KB, so the gate depends on the output estimate, which two-level aggregation makes
noisy: on the settings of the failing job of ClickHouse#125475 input was 131499 in every run, output took
values from 7735 to 76000, and every run with output above 65749 declined parallel replicas
(13 of 40 locally, 36 of 67 in CI). ClickHouse#120190 raised the aggregation state estimate of this query
from 12000 to 30000 bytes, which moved the high end of the output estimate up by 18000 (54636
before, 76000 after; 0 of 80 failures on a master build from before it). That is why the four
tests started failing on master and on unrelated PRs on 2026-10-12.

`CODEC(NONE)` on `WatchID` keeps the read large whatever the part format, server codec, row
order, compress block sizes or sparse serialization of a run: input is 2.4 MB or more in every
measured configuration (2942464 on the failing job's settings), at least a ~16x margin. Queries,
settings and references are unchanged, and no setting is pinned. Same approach as
`05045_autopr_skip_plan_build_for_small_reads` (e8588c7).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Nov 12, 2026
The original defect of this PR (`estimateSizeOfCompressedState` serializing past the
`CompressedWriteBuffer`) is already fixed on master by
#120190. Drop everything else this PR
had accumulated (wire codec selection, wire state versions, in-order arena sizing,
`groupBitmap` legacy-state fixes, and the unit tests), as requested in
#111985 (comment)

What remains: in the single-level case the sampling period was capped at 100 and the
iteration stopped after `100 * period` states, so for tables above 10000 states only
a prefix was sampled. Fixed hash maps (`UInt8` and `UInt16` keys) are iterated in key
order, so the prefix is biased whenever the state size correlates with the key. Do not
cap the period, so that about a hundred samples span the whole table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-not-for-changelog This PR should not be mentioned in the changelog 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.

2 participants