Repository navigation
Sample aggregate states from the whole single-level hash table in estimateSizeOfCompressedState - #111985
Conversation
…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]>
|
Workflow [PR], commit [61d4ceb] Summary: ✅
AI ReviewSummaryPR #111985 removes the single-level sampling-period cap and adds a stateless regression for 65,536 Findings
Tests
Final Verdict
|
…-compressed-size-estimate
`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.
|
Pushed 30adc98: master merged, plus the two fixes described in the updated description (the tiny-sample compression ratio, with the new test Status of the reds on the previous run, for the record:
|
|
Checked both reports on Upgrade check (amd_release): confirmed, nothing new. Part Stress test (amd_debug): this one is not #111053. The victim is not a fabricated part: All 7 aborts in Two things I did not expect:
#111922 and #112000 cannot cover this: both only touch the five One lead I have not finished checking: Nothing is needed from you here. The log has exactly one |
|
Both commitments from my previous comment are done. 1. The refresh path is now covered by the regression testPushed to #111626: 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 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.
|
| 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.
…-compressed-size-estimate
`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.
|
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 Both reds on
The 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 |
…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.
…-compressed-size-estimate
…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.
|
Pushed The Major, accepted — and it was wider than the estimator.
I preferred this over sourcing the version from the serialization object: the estimator only ever sees an New unit test The three reds on
@groeneai, investigate the failure: Integration tests (amd_tsan, 1/6) - 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 |
|
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:
Attribution comes from the wedged server's own build hash, 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 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 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]>
|
Pushed 6d554ce: the AI review's remaining Major, accepted. The Major. The uncompressed side of the in-order The test the review asked for. Verified locally: the changed translation units build clean and |
…-compressed-size-estimate
…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]>
|
🕵 Pushed 608a5b3: master merged (clean), the AI review's remaining Major, and the The Major, accepted and fixed (02f90c7). The estimator serialized the sampled states with the default version, while
The single red on 6d554ce is unrelated. |
|
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 |
`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]>
|
🕵 Merged master again. It includes #128088, which fixes the |
|
🕵 Merged master again (no conflicts; the PR translation units and its unit tests compile). The only red check on the previous head, |
# Conflicts: # src/Interpreters/Aggregator.cpp
|
🕵 Merged master (c916695, no conflicts; the PR's translation units and its unit tests compile). The only red check on the previous head, |
|
The diff is too large, I don't like it. |
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
|
🕵 Merged master (de4ca6d) and resolved the only conflict: the |
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]>
estimateSizeOfCompressedStateestimateSizeOfCompressedState
| 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. |
There was a problem hiding this comment.
[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.
Related: #120190
Aggregator::estimateSizeOfCompressedStateestimates 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 after100 * periodstates, 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 (UInt8andUInt16keys) 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):
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
UInt8andUInt16group keys.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/111985]
Version info
26.11.1.2137-master(included in26.11and later)