Skip to content

Sample aggregate states from the whole single-level hash table in estimateSizeOfCompressedState - #111985

Merged
alexey-milovidov merged 142 commits into
masterfrom
fix-aggregate-state-compressed-size-estimate
Nov 12, 2026
Merged

alexey-milovidov merged 142 commits into
masterfrom
fix-aggregate-state-compressed-size-estimate

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 26, 2026 •

Copy link
Copy Markdown
Member

Related: #120190

Aggregator::estimateSizeOfCompressedState estimates the size of the aggregate states that a replica sends to the initiator, for automatic parallel replicas. In the single-level case the sampling period was capped at 100 and the iteration stopped after 100 * period states, so for a table of more than 10000 states only its first 10000 states were sampled and the result was extrapolated to the whole table. Fixed hash maps (UInt8 and UInt16 keys) are iterated in key order, so that prefix is biased whenever the state size correlates with the key. In the new test, the states of the first 10000 keys are empty and the others are 256 bytes each. There the estimate was 133697 bytes against 14217216 bytes of states. This change does not cap the period, so the hundred samples span the whole table.

The original defect this PR was opened for, serializing the states past the CompressedWriteBuffer, has been fixed on master by #120190. Everything else this PR had accumulated has been dropped.

Changelog category (leave one):

  • Improvement

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

Automatic parallel replicas now sample aggregate states from the whole hash table when estimating their size, instead of only a prefix of it, which was biased for UInt8 and UInt16 group keys.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.2137-master (included in 26.11 and later)

…pressedState`

`Aggregator::estimateSizeOfCompressedState` estimates how many bytes the
aggregate states would take when a replica sends them to the initiator, which is
how automatic parallel replicas decides whether distributing a query pays off.
It built a `CompressedWriteBuffer` over a `NullWriteBuffer`, but serialized the
sampled states into the `NullWriteBuffer` directly and then read its counter, so
the `CompressedWriteBuffer` never received a byte and nothing was ever
compressed. Despite its name, and despite its own `We only interested in the
size of compressed state` comment, the function returned the plain serialized
size.

`recordAggregationStateSizes` then stored that one number as all three of
`bytes`, `sample_bytes` and `compressed_bytes`, pinning the compression ratio of
the aggregation-state statistics to 1. Notably `recordAggregationStateColumnSizes`,
which is documented to mirror this logic for in-order aggregation, feeds the very
same `AggregationState` counters through `estimateCompressedColumnSize` and does
measure the compressed size, so the two producers of one statistic disagreed.

Serialize the sample through the compressing buffer and return the sample's
uncompressed and compressed sizes next to the extrapolated total, so the existing
compression-ratio machinery in `RuntimeDataflowStatisticsCacheUpdater` applies the
states' real compression ratio. Taking the ratio from the sample rather than
compressing the extrapolated size also keeps the per-block framing overhead out
of the extrapolation, where multiplying it by `table.size() / num_samples` would
have inflated it.

The estimate drops for queries whose output is dominated by compressible
aggregate states. The recorded values in `03634_autopr_output_bytes_estimation`
are re-measured separately, since they are empirical.

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

clickhouse-gh Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [61d4ceb]

Summary: ✅


AI Review

Summary

PR #111985 removes the single-level sampling-period cap and adds a stateless regression for 65,536 UInt16 groups. At 61d4ceb679d13c8e4d17ef337d0526a416f6ab16, two gaps remain in the promised whole-table coverage; both can underestimate transfer costs and incorrectly enable automatic parallel replicas.

Findings

⚠️ Majors

  • Small fixed maps still sample only a prefix. src/Interpreters/Aggregator.cpp:325: integer division combined with return it < 100 * period still visits only 200 of 256 groups and samples keys 0, 2, …, 198. If keys 200–255 hold the large states, none is measured. With 199 groups, 99 groups are excluded entirely. Use a ceiling-based period or distribute the bounded sample over the complete table. This is the issue in the existing bot thread, reopened silently because its earlier fix is absent from the current code.

  • Nullable maps omit the NULL state entirely. (Inline finding) src/Interpreters/Aggregator.cpp:325: AggregationDataWithNullKey::size counts its separate NULL group, while the inherited forEachMapped never visits it. For a Nullable(UInt16) grouping column containing only NULL, the base iterator is empty and it == 0, so a large groupArray state is charged zero bytes even though conversion emits it. This is a pre-existing carrier gap in the touched estimator. Account for that state separately, or reject statistics collection for the unsupported shape rather than caching an underestimate.

Tests
  • ⚠️ Add focused stateless coverage for 256 UInt8 keys with large states only on keys 200–255, and for a nullable grouping column whose NULL group carries a large state. The added 65,536-key non-nullable test exercises neither gap.
  • ⚠️ Findings were verified through current-head source and iterator/arithmetic traces. No local ClickHouse binary or build directory was available for end-to-end reproduction.
Final Verdict

⚠️ Request changes. Complete the small-map sampling fix and account for the separately stored NULL state, with focused regression coverage; alternatively, link an issue tracking the pre-existing nullable-state gap.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 26, 2026
`estimateSizeOfCompressedState` now serializes its sample of the aggregate
states through a `CompressedWriteBuffer`, and the caller turns the sample's
uncompressed and compressed sizes into the compression ratio it applies to the
extrapolated total. The compressed format writes a 16-byte checksum and a block
header in front of every block, so a sample of a few bytes comes out of that
buffer larger than it went in, and the derived ratio drops below one and
*inflates* the estimate instead of reducing it.

That is not a corner case: with an early conversion to a two-level hash table
(`group_by_two_level_threshold=1`, which the test randomization sets) every one
of the 256 buckets holds a handful of states, so every per-bucket sample is
dominated by the framing. It made
`04034_autopr_dataflow_cache_reuse_between_different_queries` fail in CI - the
output-bytes estimate grew enough for automatic parallel replicas to reject the
two cache-reusing queries:

    04034_..._query_1	0	1  ->  04034_..._query_1	0	0
    04034_..._query_2	0	1  ->  04034_..._query_2	0	0

When the states are really sent, that framing is amortized over
`min_compress_block_size` of data, so a sample too small to outweigh it says
nothing about how well the states compress. Report such a sample as
incompressible rather than as expanding, which keeps the ratio at 1 - exactly
what the caller assumed before the ratio was measured at all.

Test `04653_autopr_state_size_estimate_small_buckets` pins
`group_by_two_level_threshold` to 1 and checks that parallel replicas are still
enabled from the cached statistics. It fails without this commit and passes with
it.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111985&sha=4cef64191a0d4269d696f5b55cfe06ca8cbf870c&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29
…d states

`recordAggregationStateColumnSizes`, the in-order-aggregation producer of the
`AggregationState` statistic, routed the state columns through `recordColumns`,
which totals `IColumn::byteSize`. For `ColumnAggregateFunction` that counts the
state pointers plus the arena *the column owns*, and `AggregatingInOrderTransform`
hands over columns whose states live in a foreign arena (`addArenasToAggregateColumns`),
so the total degenerated to one pointer per row. Arena-backed states - `min(String)`,
`groupArray`, `uniqExact` - were therefore under-counted, and automatic parallel
replicas could pick the distributed plan for a query whose states are expensive to
ship, the mirror image of the overestimate fixed by this pull request for the
hash-table producer.

Size a `ColumnAggregateFunction` from its serialized states instead. Serializing
every state is what `ColumnAggregateFunction::serializedSizeEstimate` does for the
part writer, but the statistics collector sees every chunk of the aggregation and
cannot afford a cost proportional to the number of groups, so the new
`sampledSerializedSizeEstimate` serializes at most as many states as
`Aggregator::estimateSizeOfCompressedState` samples per bucket and extrapolates
from them. Fixed-layout states keep the existing `sizeOfData` shortcut and are not
serialized at all. `serializedSizeEstimate` is now that function with no sampling
limit, so the part writer keeps its exact figure.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed 30adc98: master merged, plus the two fixes described in the updated description (the tiny-sample compression ratio, with the new test 04653_autopr_state_size_estimate_small_buckets, and the in-order producer's byteSize under-count raised in review).

Status of the reds on the previous run, for the record:

03634_autopr_output_bytes_estimation passed on the previous run in Stateless tests (amd_asan_ubsan, distributed plan, parallel) with query_28 left at its original 23722663, which is the confirmation this pull request's premise needed: the recorded values do expect the compressed size. That also means #111981 is unnecessary if this one lands first.

@groeneai

Copy link
Copy Markdown
Collaborator

Checked both reports on 4cef6419. The tested build is 55f31ab7 (read from the job log's own git hash: line, so it is the synthetic merge ref, not the branch tip).

Upgrade check (amd_release): confirmed, nothing new. Part all_1_5_4_1 on test_3.t_plt_evict_reinsert, Code 27 with the storing_version token, cascading to Code 246 on ATTACH. That table is fabricated by 04417_part_loading_tree_rollback_evict_reinsert_contains.sh, so it is #111053 as you said.

Stress test (amd_debug): this one is not #111053. The victim is not a fabricated part:

02:05:29 <Warning> test_jtns1w2h.reader__fuzz_4: Table can't create parts with adaptive granularity,
         but settings min_rows_for_wide_part = 0, min_bytes_for_wide_part = 10485760 ...
02:05:30 <Fatal> Logical error: 'Cannot create part with type Compact and storage type Full ...'

All 7 aborts in clickhouse-server.err.log name that single table, and no t_plt_* table appears in any of the 7 stacks. The table comes from 04545_read_only_disk_refresh_parts.sh under fuzzing: a reader on a plain_rewritable path, where the fuzzer made granularity non-adaptive. That is #111626 instead: a real MergeTree table loading a pre-existing Compact part while its own settings disable polymorphic parts. #111626 is still open, and I verified the guard is present in the tested build.

Two things I did not expect:

  1. The first abort is on the refresh_parts_interval path, not startup: MergeTreeData::refreshDataPartsOnce (MergeTreeData.cpp:3191) -> loadDataPartWithRetries -> MergeTreeDataPartBuilder::build(). The Fix LOGICAL_ERROR when loading an existing Compact part under a non-adaptive table policy #111626 fix covers it, since both paths go through MergeTreeIndexGranularityInfo and build(), but its regression test only drives SYSTEM RESTART DISK, so that path is untested. I will add the refresh shape to it. This frame is invisible in CIDB, including on this run's own row, because the ingested context carries only the reported headline stack (the last abort, which is the startup one) - so I could only see it in the raw log.
  2. The 6 later aborts are the startup path, and they are what escalated the job: each clickhouse start re-attaches the fuzzed table, aborts again while loading its parts, and the runner gave up after 10 attempts. So Cannot start clickhouse-server, the Logical error row and Check failed are one event, not three.

#111922 and #112000 cannot cover this: both only touch the five 04241_* / t_plt_* test files.

One lead I have not finished checking: 04545_read_only_disk_refresh_parts.sh landed on 2026-07-23, and 15 of the 18 sightings of this signature in the last 45 days (18 rows, 18 distinct pull requests, 0 master) are on or after 2026-07-24. I will check whether that test is the common carrier in the others, or whether the timing is a coincidence.

Nothing is needed from you here. The log has exactly one <Fatal> signature, one signal kind and no sanitizer reports, so there is no third thing hiding in it.

@groeneai

groeneai commented Jul 27, 2026 •

Copy link
Copy Markdown
Collaborator

Both commitments from my previous comment are done.

1. The refresh path is now covered by the regression test

Pushed to #111626: 77456c9. 04371_load_compact_part_non_adaptive_reader.sh now also drives the load path through the background refresh task, in addition to SYSTEM RESTART DISK.

Verified both directions on a debug build, Build ID checked against the ELF on each run. Against current master the refresh shape alone aborts the server, with no SYSTEM RESTART DISK anywhere in the probe:

MergeTreeDataPartBuilder.cpp:79:15: DB::MergeTreeDataPartBuilder::build
MergeTreeData.cpp:2487:14:          DB::MergeTreeData::loadDataPart
MergeTreeData.cpp:2594:20:          DB::MergeTreeData::loadDataPartWithRetries
MergeTreeData.cpp:3191:20:          DB::MergeTreeData::refreshDataPartsOnce
MergeTreeData.cpp:3112:5:           DB::MergeTreeData::refreshDataParts

With the fix the part loads and the server stays up. 50 consecutive runs pass, with 5 parallel copies of the test against one server.

2. 04545 is not the common carrier - the timing was a coincidence

I was wrong to suspect it. I pulled clickhouse-server.err.log.zst for every sighting of this signature in the last 45 days (16 of 19 fetched; 3 artifacts have expired) and attributed each abort to its victim table via the Table can't create parts with adaptive granularity warning that immediately precedes it.

The aborting victim is a table named reader__fuzz_* in 15 of 16 runs. But three different tests produce that shape, and the two 2026-07-22 sightings predate 04545 being able to run at all:

carrier test added example sightings
04318_system_restart_disk_plain_rewritable.sh 2026-06-06 #109360, #96630 (both 07-22, 04545 absent from the log)
03362_merge_tree_with_background_refresh.sh 2025-04-11 #109000 (07-27, 04545 absent)
04545_read_only_disk_refresh_parts.sh 2026-07-14 #109351, #110766

03362 has been in the tree since April 2025, so the shape long predates all of these. 04545 merely appears in most recent logs because it runs in every stress job since it landed - being present in a run is not the same as being the carrier, which is what my earlier note conflated.

The one non-reader victim is the oldest sighting, #101434 (06-23): victim test_2.tab, carrier 02354_vector_search_adaptive_index_granularity.sql, and that run has zero refreshDataPartsOnce frames - it is the startup path.

So the common factor is not any one test but the shape they share: a plain_rewritable path with a writer and a read-only reader on it, where the fuzzer sets the reader's index_granularity_bytes = 0. Both entry points into that shape are now in the regression test.

On the clustering that made me suspicious: 15 of 19 sightings are on or after 2026-07-24, and it is not 04545. All three carriers are old enough that a change in exposure rather than a new carrier is the better explanation, so I have not attributed it further.

`sampledSerializedSizeEstimate` reported the figure `MergeTreeIndexGranularity`
wants - the state pointer array plus, for fixed-layout states, `sizeOfData` -
which is not what goes on the wire and not what
`Aggregator::estimateSizeOfCompressedState` measures. The two producers of the
`AggregationState` statistic therefore still disagreed: `count`, for one, has
`sizeOfData` of 8 but serializes as a varint, so a sorted `GROUP BY ... count()`
overstated its output bytes by an order of magnitude and automatic parallel
replicas could still be rejected for it.

`ColumnAggregateFunction::sampledSerializedStateBytes` now returns only the bytes
`IAggregateFunction::serialize` writes - the same thing
`SerializationAggregateFunction` puts on the wire - with no pointer array and no
`sizeOfData` shortcut, and `RuntimeDataflowStatistics` uses that.
`serializedSizeEstimate` keeps its previous body verbatim for the write path, so
`index_granularity_bytes` accounting is unchanged.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed 0203ce5: master merged again, plus the AI review's remaining Major.

The Major, accepted. The uncompressed side of the in-order producer now comes from the same serialization the compressed sample uses. Details in the thread; the short version is that sampledSerializedSizeEstimate was the write-path figure (pointer array + sizeOfData for fixed-layout states), which overstated count by an order of magnitude, so it is replaced by sampledSerializedStateBytes - only the bytes IAggregateFunction::serialize writes, no pointer array, no sizeOfData shortcut. serializedSizeEstimate keeps its previous body verbatim, so index_granularity_bytes accounting is unchanged.

Both reds on 30adc985f1e are fixed on master and cleared by the merge:

The 04241_part_loading_tree_rollback_* reds reported earlier are gone from this run, and 04034_autopr_dataflow_cache_reuse_between_different_queries passes.

One caveat on local verification: the shared build machine is out of memory and the compiler processes are being OOM-killed with no diagnostics, so I could only confirm the three affected translation units compile clean under -Weverything -Werror rather than link and run the binary. CI is the real check on this commit.

Comment thread src/Columns/ColumnAggregateFunction.cpp Resolved
…ateFunction` views and copies

`createView` rebuilt the column with the two-argument constructor, which never
took a version, and the copy constructor left both `version` and `type_string`
default-initialized. Every column produced by `filter`, `permute`, `index`,
`replicate`, `cut` or `cloneResized` therefore serialized versioned aggregate
states with the *default* format rather than the one named by its type, while
`NativeWriter` used the version from the header. `type_string` was even empty
in copies, so `insert` of a `Field` into a copied column always threw.

Both constructors now carry the version through, so a permuted column measured
by `sampledSerializedStateBytes` - the `group_by_key` branch of
`AggregatingInOrderTransform` sorts the block before
`recordAggregationStateColumnSizes` - produces the same bytes that would go on
the wire.
…unction` views and copies

`sumMap` is versioned, so its non-zero version appears in the state's type name;
`permute` (which goes through `createView`) and the copy constructor must both
carry it over.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed 82dd11cace1: master merged again (clean), plus the AI review's remaining Major.

The Major, accepted — and it was wider than the estimator. sampledSerializedStateBytes serializes through the column-local version, and the reviewer is right that views and copies dropped it. Two separate places:

  • createView rebuilt the column with ColumnAggregateFunction(func, arenas), an overload that never took a version at all, so it always fell back to getTypeString(func) with version == nullopt.
  • The copy constructor initialized neither version nor type_string, leaving the latter empty.

createView is the return path of filter, permute, index, replicate, cut and cloneResized, so this is not confined to the estimator: operator[], updateHashWithValue, computeHashInto, serializeValueIntoArena and getExtremes on any such column serialized versioned states with the default format rather than the one named by the column's own type. And because type_string was empty in copies, insert of an AggregateFunctionStateData Field into a copied column always threw Cannot insert element into different column. Both constructors now carry the version (and therefore the type string) through, so the group_by_key branch of AggregatingInOrderTransform - which sortBlocks the ColumnAggregateFunction before recordAggregationStateColumnSizes - measures the same bytes that would go on the wire.

I preferred this over sourcing the version from the serialization object: the estimator only ever sees an IColumn, and the same column-local version is what the five other call sites above already use, so fixing the propagation repairs all of them at once instead of only the estimate.

New unit test ColumnAggregateFunction.ViewsAndCopiesPreserveVersion: sumMap is versioned, its non-zero version is printed in the state's type name, and the test asserts that permute (i.e. createView) and the copy constructor both keep it. Without the fix the permute case reports AggregateFunction(sumMap, ...) and the copy case reports the empty string.

The three reds on 0203ce5ca4c:

@groeneai, investigate the failure: Integration tests (amd_tsan, 1/6) - test_postgresql_replica_database_engine timing out on the TSan shard - and provide a fix in a separate PR, with a tracking issue since there is none. It is reproducible on master, so it is not specific to this branch. If a fix is already in progress, link it here.

Local verification caveat, same as last time. The shared build machine is still saturated (164 of 185 GB used by other workers, load ~115), and earlyoom SIGTERMs the compiler once free memory drops below its threshold, so I could not link a binary or run the new unit test here. What I did verify is that every affected translation unit - ColumnAggregateFunction.cpp, Aggregator.cpp's dependents, RuntimeDataflowStatistics.cpp, MergeTreeIndexGranularity.cpp, FunctionsBitmap.cpp and the gtest itself - compiles clean under -Weverything -Werror via -fsyntax-only. CI is the real check on this commit.

@groeneai

Copy link
Copy Markdown
Collaborator

I investigated this and it is not a standing defect: every failure in the window you measured is attributable to #109339, which was already reverted by #112381.

The shard does not run out of time on its own. One call wedges and eats the whole budget. On the gw0 instance the server log stops mid-statement and never logs another line:

00:13:13.015087 executeQuery: DROP DATABASE IF EXISTS `test_database` SYNC
00:13:13.015406 PostgreSQLReplicationHandler: Deactivating startup task
00:13:13.015432 PostgreSQLReplicationHandler: Deactivating consumer task
00:13:13.015462 PostgreSQLReplicationHandler: Deactivating cleanup task
00:13:13.015486 PostgreSQLReplicationHandler: Resetting consumer

test_virtual_columns then hits pytest-timeout at 900 s inside setup_teardown, waiting on exactly that DROP. Every later failure is Code: 209 SOCKET_TIMEOUT at Connection::receiveHello, so the socket is accepted and the handshake is never answered: the server is wedged, not gone. That is what distinguishes this from the Connection refused shape reported on the same suite. There is no TSan report, no Received signal and no <Fatal> line in any of the four instance logs on that shard, so the shutdown is stuck rather than faulting.

Attribution comes from the wedged server's own build hash, 05c4087fab1cc921f42aa457741f9143dbcc2ae5, which contains #109339 (merged 2026-07-28 14:02 UTC) and does not contain the revert (2026-07-29 01:39 UTC). Your three master data points are the same: e94e3689, 5854921c and efb26ecf all contain #109339 and none contains the revert. efb26ecf is the one whose CI started at 01:43, four minutes after the revert merged, so it was already testing the pre-revert commit.

Post-revert master is clean. Since 2026-07-29 01:39 UTC the suite ran 18345 OK across 68 master commits with 9 failures, and all 9 are that one pre-revert efb26ecf run. The only other post-revert cluster is a single open PR whose own branch calls getTablesIterator during shutdown, which is branch-local.

So I am not opening a tracking issue or a separate fix PR, because the cause is already off master and a new issue would duplicate #109339. What this does mean is that the re-land in #112382 needs to carry the fix, and its diff looks like it does: the two mutexes are documented as a fixed order and the map is taken out under tables_mutex before the wrappers are destroyed. The path that actually hung is DROP DATABASE ... SYNC, not the read path the PR is titled for, so that is the one worth confirming before it merges. If you would still prefer a tracking issue for the hang independently of the re-land, say so and I will open it.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111985&sha=0203ce5ca4cb3ed0f6794dec6aeb4ce3cc414bfd&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%201%2F6%29

None of this is related to #111985.

… and extrapolate the rest

The uncompressed side of the in-order `AggregationState` statistic serialized a sample of the
states of every emitted block, so when `aggregation_in_order_max_block_bytes` splits large
arena-backed states into many small blocks, statistics collection re-serialized every state of
every block. Now only the blocks the compressed side already samples serialize their states, and
the remaining blocks are extrapolated from the per-row figure those samples give. Blocks racing
with the first sampled one serialize too and count as extra samples, so no block is ever sized
from a figure that does not exist yet.

The new test `04661_autopr_in_order_state_size_extrapolation` drives `AggregatingInOrderTransform`
with arena-backed `min(String)` states through a small `aggregation_in_order_max_block_bytes` and
checks the extrapolated output-bytes estimate against the same query fed by large blocks.

#111985

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed 6d554ce: the AI review's remaining Major, accepted.

The Major. The uncompressed side of the in-order AggregationState statistic serialized a sample of the states of every emitted block, so with aggregation_in_order_max_block_bytes splitting large arena-backed states into many small blocks, statistics collection re-serialized every state of every block — the O(number of groups * state size) shape this PR is trying to keep off the collection path. Now only the blocks the compressed side already samples (shouldSampleBlock, 5 per stream) serialize their states, and the rest are extrapolated from the per-row figure those samples give, the same way the compression ratio is. Blocks racing with the first sampled one serialize too and count as extra samples, so no block is sized from a figure that does not exist yet.

The test the review asked for. 04661_autopr_in_order_state_size_extrapolation drives AggregatingInOrderTransform with arena-backed min(String) states through aggregation_in_order_max_block_bytes=8192 — about 45 emitted blocks, of which 5 are sampled (verified from the collector's log: the sample covers ~11% of the stream, collector cost 1.4 ms for 2e5 states) — and checks the extrapolated output-bytes estimate against the same query fed by large blocks; the two estimates must agree within 2x. The two queries run against identical twin tables so both get distinct plan hashes and both collect statistics.

Verified locally: the changed translation units build clean and 04661, 04653_autopr_state_size_estimate_small_buckets, 04100_autopr_input_bytes_estimation_aggregation_in_order, and 04034_autopr_dataflow_cache_reuse_between_different_queries all pass against this branch's binary.

Comment thread src/Interpreters/Aggregator.cpp Resolved
alexey-milovidov and others added 3 commits August 1, 2026 13:43
…output state type

`Aggregator::estimateSizeOfCompressedState` serialized the sampled states with the default
version, while `NativeWriter` serializes them through the `SerializationAggregateFunction`
of the output header's `DataTypeAggregateFunction`, which resolves the type's version. On
the merge path `aggregate_state_types` preserves the input header's type, so a column with
an explicit older state version, such as `AggregateFunction(0, sumMap, ...)`, was measured
in the default format instead of the one actually sent. Resolve the versions from
`aggregate_state_types` and pass them to `IAggregateFunction::serialize`, in the
`without_key` branch too. The new unit test merges an explicitly versioned `sumMap` state
column with `Decimal32` values, whose version-0 payload is smaller than the version-1 one,
and pins the estimate to the version-0 wire size for both the keyed and the `without_key`
paths.

Co-Authored-By: Claude Fable 5 <[email protected]>
…e compressed estimate

#111981 re-measured `query_28` to 58136394, the uncompressed serialized size the estimator
reported while it serialized the sampled states into the `NullWriteBuffer`; that change and
this fix touch the same value and were explicitly mutually exclusive. With the estimator
measuring the compressed size, the estimate returns to the compressed figure the test had
been calibrated against before: both CI runs of this pull request
(4cef641 and 6d554ce, before #111981 merged) passed this test with 23722663.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111985&sha=6d554cecfe7ebd6ab6819102f316beb2ebf0436e&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%29

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 608a5b3: master merged (clean), the AI review's remaining Major, and the query_28 re-record.

The Major, accepted and fixed (02f90c7). The estimator serialized the sampled states with the default version, while NativeWriter uses the version of the output header's DataTypeAggregateFunction — which aggregate_state_types preserves from the input header on the merge path, keeping explicit older versions such as AggregateFunction(0, sumMap, ...). The versions are now resolved from aggregate_state_types and passed to both serialize calls, the without_key branch included. The regression test gtest_aggregator_state_size_estimate.cpp merges an explicitly versioned sumMap state column with Decimal32 values through a merge-path Aggregator and pins the estimate to the version-0 wire size for both the keyed and the without_key paths; verified locally (4/4 pass, and the test asserts the version-0 and default payloads differ, so the pre-fix estimator cannot satisfy it). Details in the thread.

query_28 re-recorded (608a5b3). #111981 merged first, as anticipated in the description, and set the golden to 58136394 — the uncompressed figure this PR removes. Set back to 23722663, the compressed figure both CI runs of this PR (4cef641, 6d554ce) passed with.

The single red on 6d554ce is unrelated. 04490_any_join_constant_condition_reorder in Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) — a duplicated row from t1 INNER JOIN t2 ON t1.c = t2.c ANY INNER JOIN t3 ON 1. That is the known parallel-replicas bug where allowParallelReplicasForJoinTree only examines the leftmost join and ships a non-leftmost ANY join to every replica; it reproduced 3/3 in the flaky-check with --no-random-settings, has 6 hits across unrelated PRs since 2026-07-21 and 0 on master (intermittent race), and the fix is already in progress: #112317 by @groeneai. Nothing in this PR touches join planning; the plan of that query is rejected by considerEnablingParallelReplicas as unsupported (JOIN steps), so the changed estimator is unreachable there.

@groeneai

Copy link
Copy Markdown
Collaborator

Fixed by #127912, merged yesterday at 15:13 UTC. This run built f7f2b02 merged into master 079b5ce, which predates the fix; the run for f8d3085 builds on 047484d, which contains it, so nothing is needed in this PR.

Cause: when a web terminal session closes while the embedded client asks whether to print a binary format, the catch in ClientBase::initOutputFormat destroyed the output buffers but kept output_format, and resetOutput then finalized it into freed memory. #126142 is a different defect on the same resetOutput path (finalizing into a canceled buffer) and does not cover this one. No run whose build contains the fix has shown this stack so far.

alexey-milovidov and others added 2 commits October 30, 2026 08:32
`SerializationVariant` writes the discriminators and the alternatives and
rebuilds the offsets on read, so the offsets never cross the network. The
state-bearing carrier accounting nevertheless counted them in the plain
bytes and sampled their compression as a separate `UInt64` payload, which
dominated small compressible states (e.g. `Variant(AggregateFunction(count), String)`)
by orders of magnitude. `Dynamic` reached the same path.

Exclude the offsets from both the carrier bytes and the compression sample,
and add a regression test comparing the `Variant` estimate with the bare
state column and the `NativeWriter` wire size with explicit `LZ4`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master again. It includes #128088, which fixes the Fast test (arm_darwin) failure of 05397_clickhouse_local_locked_path_untouched, unrelated to this PR. Also addressed the review thread about Variant offsets. Thanks @groeneai for confirming that the Stress test segfault is covered by #127912.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master again (no conflicts; the PR translation units and its unit tests compile). The only red check on the previous head, Stress test (amd_tsan) ThreadSanitizer: data race (STID: 3766-2b51) (https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111985&sha=94a7d4ad84f776dc4569af078a480a7312471f6b&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29), is unrelated: it is a race on ClientEmbeddedRunner::exit_code between the embedded client thread and SSHHandler (src/Server/ClientEmbedded/ClientEmbeddedRunner.cpp:80), fixed by the open #127990.

# Conflicts:
#	src/Interpreters/Aggregator.cpp
@CLAassistant

CLAassistant commented Nov 5, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (2fb10fe, no conflicts; the PR's translation units compile). The previous run on 975e978 had no failed tests: CI was red only because Integration tests (amd_asan_ubsan, db disk, targeted) and Finish Workflow were cancelled. The new commit gets a fresh CI run.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (c916695, no conflicts; the PR's translation units and its unit tests compile). The only red check on the previous head, Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) failing 05515_global_subquery_projection_where with UNKNOWN_IDENTIFIER for a GLOBAL IN external table, is unrelated to this PR and is fixed on master by 1cfc5bb (Do not rewrite GLOBAL IN in projection queries with parallel replicas), which this merge pulls in.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The diff is too large, I don't like it.

alexey-milovidov and others added 2 commits November 10, 2026 19:39
Resolve the conflict in `RuntimeDataflowStatistics.cpp`: keep the PR's
`sampleRowLimit` and pass `nullptr` instead of `std::nullopt` as the format
settings of `NativeWriter::writeData`, which now takes `const FormatSettings *`
after 9975f79. Adapt the other `writeData` calls added by this PR (in
`RuntimeDataflowStatistics.cpp` and two gtests) the same way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Interpreters/Aggregator.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (de4ca6d) and resolved the only conflict: the #include block in src/Interpreters/Aggregator.cpp (kept <algorithm> from this PR and <numeric> from master; master already moved Common/ListWithMemoryTracking.h down). A syntax-only compile of Aggregator.cpp, RuntimeDataflowStatistics.cpp and gtest_aggregator_state_size_estimate.cpp passes. The previous head had no failed tests; the only red check was CH Inc sync, which matches the base-branch conflict. I made no code changes for the note about the diff being too large. Reducing the scope is a design decision for a human.

alexey-milovidov and others added 2 commits November 12, 2026 16:59
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]>
The compressed size of `repeat(hex(...), 4)` states is a small fraction of the
serialized one, so the bounds did not describe what the wire carries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov alexey-milovidov changed the title Measure the compressed size of aggregate states in estimateSizeOfCompressedState Sample aggregate states from the whole single-level hash table in estimateSizeOfCompressedState Nov 12, 2026
const auto period = bucket == -1 ? std::min<size_t>(std::max<size_t>(table.size() / 100, 1), 100) : 100;
/// The single-level period is not capped, so that the samples span the whole table: fixed hash maps
/// (`UInt8` and `UInt16` keys) are iterated in key order, and a prefix of them is biased
/// whenever the size of the state correlates with the key.

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.

[P2] Include the separately stored NULL group in the state estimate

The whole-table sampling invariant also needs to cover nullable aggregation maps. AggregationDataWithNullKey::size includes the NULL group, but its inherited FixedHashMap::forEachMapped iterates only the base table; the state held in getNullKeyData never reaches this sampler.

For a concrete source trace, use a MergeTree table with k Nullable(UInt16) containing only NULL keys and a large groupArray payload, then collect statistics for SELECT k, groupArray(v) FROM t GROUP BY k. The variant is nullable_key16, table.size() is 1, the base iterator is empty, it stays zero, and the estimator returns zero state bytes. convertToBlockImpl nevertheless emits the stored NULL state, and the caller subsequently records only the group-key bytes. Automatic parallel replicas can therefore accept a large transfer priced as an almost empty result. This is an existing carrier gap in the touched estimator, verified from the current code rather than a server run.

Please account for the separately stored state, or mark this shape unsupported if measuring it would violate the serialization budget, and add a focused nullable-key regression. The new non-nullable UInt16 test cannot exercise it.

@nickitat nickitat left a comment

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.

lgtm

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 12, 2026
Merged via the queue into master with commit e2491a6 Nov 12, 2026
203 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-aggregate-state-compressed-size-estimate branch November 12, 2026 21:58
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). 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.

5 participants