Skip to content

Price small single-level aggregation tables in full for the automatic parallel replicas estimate - #131697

Open
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/autopr-price-small-single-level-tables
Open

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/autopr-price-small-single-level-tables

Conversation

@groeneai

@groeneai groeneai commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #131357
Related: #131358
Related: #129565
Related: #111985

Changelog category (leave one):

  • Improvement

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

Automatic parallel replicas now estimates the size of the aggregation states of a small GROUP BY (at most 1000 groups whose states fit into 1 MiB) from all of its states instead of a sample of 100, so a few large states, or the state of the NULL key, are no longer missed.

Description

Aggregator::estimateSizeOfCompressedState prices a single-level table from at most 100 sampled states. On a skewed table the sample misses the few states that hold most of the bytes: 03634_autopr_output_bytes_estimation query_10 (215 keys, three uniqExact states hold 70% of the data) is priced at about 0.72x of the exact size, which occasionally falls below the test's 2.5x bound (CI report). Since #129565 the default merge packs partitions per worker, and there the same sampler scatters between 0.45x and 1.2x (#131357, closed after #131358 pinned the test to the serial merge). The state of the NULL key, kept outside the hash table, was never serialized.

A single-level table of at most 1000 states whose sampled size fits one compressed block (1 MiB per call, shared by the aggregate functions) is priced from all its states, the NULL key included. The states are serialized into a MemoryWriteBuffer of the remaining budget, so CurrentBufferExhausted stops writing a large state the sample missed, and the sample stands. Larger tables and two-level buckets are sampled as before.

Validation (debug build): the new test 05768 fails on master and under each of fourteen mutations. query_10 on CI's test.hits: 197.8K..204.6K in 60/60 runs across the serial merge, max_threads = 32 and the default merge (master: 148.8K..149.6K and 155K..247K). Cost: tables of more than 1000 states or 1 MiB never take the full pass (duration unchanged); 150 states, 1 MB in total, add about 5.5 ms of estimator time, a pass aborted on a 2 MB String state 0.17 ms.

The #131358 pin in 03634 is no longer needed for this estimate; I left it in place.


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

groeneai and others added 2 commits November 14, 2026 22:19
…tput estimate

`Aggregator::estimateSizeOfCompressedState` prices a single-level table from at
most 100 sampled states (`period = max(N / 100, 1)`) and scales by N / samples.
On a skewed table a few states hold most of the bytes and the sample misses
them. `03634_autopr_output_bytes_estimation` query_10 (215 `MobilePhoneModel`
keys, the three largest `uniqExact` states hold 70% of the 25380 pairs) was
priced at 145.9K / 149.3K, about 0.72x of the exact ~200K, and dipped to 142K,
below the test's 2.5x bound of 144880 (PR ClickHouse#131529, arm_asan_ubsan azure,
2026-11-14). Since ClickHouse#129565 the default merge packs a worker's hash partitions
into one table per call (ClickHouse#131357), and the same sampler prices query_10 at
91K..136K there.

After the existing sample, a single-level table of at most 1000 states (more
than 100, or with a `NULL` key) whose sampled serialized size fits the remaining
budget is priced from all its states. The budget is one compressed block
(`DBMS_DEFAULT_BUFFER_SIZE`, 1 MiB) per call, shared by the aggregate
functions. The full pass serializes into a `MemoryWriteBuffer` of that size, so
`WriteBuffer::CurrentBufferExhausted` stops a large missed state midway; the
sample then stands. The full pass also prices the state of the `NULL` key,
which `AggregationDataWithNullKey` keeps outside the hash table: `size()`
counts it, `forEachMapped` never visits it, so an all-NULL group was priced as
0. Sampled passes are unchanged (the NULL state at position 0 of a sample
would be weighted by the period).

A first version priced every table of at most 1000 states in full. A count
bound does not bound bytes: on `k = number % 1000, uniqExact(v)` over 10M rows
the serial merge went from 642 to 1037 ms (estimator 48 -> 467 ms) for an
unchanged estimate.

Measured on a debug build:
- new test 05768: base 0 0 1 1 0 0 0 0 0 0, fix 1 1 1 1 1 1 1 1 1 1 (raw
  101424 / 101437 / 384 / 1770 / 100370 / 601483 / 101601 / 600066 /
  100683 / 1740..1993); trigger disabled 0 0 1 1 0 0 0 0 0 0; budget 50000
  0 0 1 1 0 0 0 0 0 0; NULL-key visit removed 1 0 1 1 0 1 1 0 1 1; catch
  removed: the third query fails with CurrentBufferExhausted.
- byte bound removed (`MemoryWriteBuffer(0)`) 1 1 0 1 1 0 1 0 1 1 (2001478,
  1202535, 1500118); count bound removed 1 1 1 0 1 1 1 1 1 1 (101607).
- `|| has_null_key` removed from the trigger 1 1 1 1 0 1 1 0 1 1 (124, 37);
  budget per aggregate function 1 1 1 1 1 0 1 0 1 1 (1202535, 1500118).
- exclusive count bound (`< 1000`) 1 1 1 1 1 1 0 1 1 1 (1769).
- budget not zeroed after an aborted pass, or the `> 0` guard removed,
  1 1 1 1 1 1 1 0 1 1 (900089); lower bound `> 101` 1 1 1 1 1 1 1 1 0 1 (188).
- state priced uncompressed (`size = all->second`) 1 1 1 1 1 1 1 1 1 0
  (1001412); budget 700 KiB 1 1 1 1 1 1 1 1 1 0 (384).
- query_10 on CI's test.hits, 20 runs each: fix 197802..197884 (pinned serial
  merge), 197802..197872 (max_threads 32), 198877..204593 (default merge);
  base 148809..149620, 149466..149620, 155062..247124.
- cost, interleaved two-server A/B with cross-over, medians of 30 runs: the
  1000/1001/50000-key cases never take the full pass (instrumented probe, 0 of
  76 calls) and keep their duration; 150 states of 1.02 MB serialized add
  5.3..5.9 ms of estimator time; a pass aborted at 1 MiB adds 0.17 ms.

Related: ClickHouse#131357
Related: ClickHouse#131358

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Return the frame-overhead comment to its place in master above the scaling it explains; shorten the NULL-key and small-table pricing comments to one line each.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (7 review rounds)

Bounce cap reached - published as-is: the last fix round (test case 10 only, no source change) was not re-run through the gate. Every finding below was fixed or answered; nothing is left open.

  • ❌ Test does not pin the bounds of the full pass (round 1, own review + gate, test-liveness) - AGREE, fixed: the aborted-pass case asserts that the sample stands, and a 1001-state case pins the count bound; both are red under a mutation that removes the bound.
  • ❌ Test does not pin the NULL-only trigger or the shared budget (round 2, gate, test-liveness) - AGREE, fixed: a 50-group Nullable case and a two-function case; each is red under a mutation that removes its clause.
  • ❌ The inclusive 1000-state bound has no case (round 3, gate, test-liveness) - AGREE, fixed: a 1000-state case next to the 1001-state one; red under < instead of <=.
  • ❌ The budget after an aborted pass has no case (round 4, gate, test-liveness) - AGREE, fixed: a three-function case on a table that holds only the NULL key, where the second state stops the pass and the third would fit; red when the budget is not zeroed or its > 0 check is dropped.
  • ❌ The lower edge of the full pass (more than 100 states) has no case (round 4, own review, test-liveness) - AGREE, fixed: a 101-state case whose heavy state is the one the first-100 sample misses; red under > 101.
  • ❌ The full pass is not shown to price compressed bytes, and the 1 MiB budget is not pinned from below (round 5, gate, test-liveness) - AGREE, fixed: a 215-state case with a compressible state of almost 1 MiB that the sample misses (about 1.8 KB compressed); red when the pass charges the serialized size, or when the budget is smaller than 1 MiB.
  • ⚠️ The 1 MiB cap does not bound a serializer that builds its output first (groupBitmap) (round 2, gate) - DISAGREE as a blocker: the pass stops at the first state that does not fit and the budget drops to 0, so it adds at most one state's serialization per call, which is what the existing sampler already pays for every state it samples; streaming serializers (uniqExact, String) stop at the cap.
  • ⚠️ bucket == -1 also reaches a two-level table (overflow row, WITH TOTALS) (round 3, gate) - DISAGREE: that whole-table record and the later per-bucket records are unchanged from master, which samples the same states there; this change only prices them exactly. The double record itself is separate and not raised (no measured consequence).
  • 💡 The bucket == -1 guard has no test - not added: a full pass only makes an estimate more exact, so such a test would have to assert a two-level under-estimate or depend on hash-cell order.
  • 💡 The NULL key's state is still extrapolated in sampled passes (tables above 1000 states, two-level buckets) - not raised: outside this change, no measured consequence.
  • 💡 Cost cells marginally above the pre-registered thresholds in some 10-run variants - not a regression: the full pass never runs there (0 of 76 estimator calls), and a control binary with the trigger compiled out shows the same deltas.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05768 on master prints 0 0 1 1 0 0 0 0 0 0 in 5/5 runs (raw estimates 384 / 392 / 384 / 1770 / 124 / 431 / 1769 / 37 / 188 / 384; cases 1, 2, 5, 7 and 9 hold a 100000-byte state, case 6 two of 600000 bytes, case 8 states of 600000, 600000 and 300000 bytes, case 10 a 1000000-byte state that repeats one 1000-byte block); query_10 of 03634 on CI's test.hits is priced at 148.8K..149.6K, 2.7% above the 144880 bound, and the CI failures (142K) are the tail of that mode.
b Root cause explained? The single-level sampler prices a table from at most 100 states and scales; on a skewed table of 101..1000 states it misses the few heavy ones (query_10: 0.72x of exact), and it never visits the state of the NULL key, which lives outside the hash table.
c Fix matches root cause? Yes. Such a table is priced from all its states when they fit one compressed block (1 MiB per call); a MemoryWriteBuffer of the remaining budget stops writing a large missed state. No test bound is changed.
d Test intent preserved / new tests added? New 05768 with ten cases: a completed full pass, a Nullable key whose NULL group holds the bytes, a pass aborted at the byte budget, a 1001-state table above the count bound, a 50-group Nullable key priced in full only for its NULL state, two aggregate functions sharing one budget, a table of exactly 1000 states at the inclusive count bound, a NULL-only key whose later aggregate functions stay sampled after an aborted pass, a 101-state table at the lower bound, and a compressible 1000000-byte state priced at its compressed size. 03634 is unchanged and passes 20/20.
e Both directions demonstrated? Master 0 0 1 1 0 0 0 0 0 0, fix 1 1 1 1 1 1 1 1 1 1 (101424 / 101437 / 384 / 1770 / 100370 / 601483 / 101601 / 600066 / 100683 / 1740..1993). Fourteen mutations: trigger disabled 0 0 1 1 0 0 0 0 0 0, budget 50000 0 0 1 1 0 0 0 0 0 0, NULL visit removed 1 0 1 1 0 1 1 0 1 1, catch removed: the third query fails, byte bound removed 1 1 0 1 1 0 1 0 1 1, count bound removed 1 1 1 0 1 1 1 1 1 1, || has_null_key removed from the trigger 1 1 1 1 0 1 1 0 1 1, budget per aggregate function 1 1 1 1 1 0 1 0 1 1, exclusive count bound (< 1000) 1 1 1 1 1 1 0 1 1 1, budget not zeroed after an aborted pass 1 1 1 1 1 1 1 0 1 1, > 0 budget guard removed 1 1 1 1 1 1 1 0 1 1, lower bound > 101 1 1 1 1 1 1 1 1 0 1, state priced uncompressed (size = all->second) 1 1 1 1 1 1 1 1 1 0, budget 700 KiB 1 1 1 1 1 1 1 1 1 0. 50/50 randomized runs pass.
f Fix is general across code paths? One function with one caller; every single-level variant shares the lambda. Two-level buckets, without_key and the in-order path are unchanged by design.
g Fix generalizes across inputs (params/datatypes/wrappers)? Covered: UInt16 fixed map, Nullable(UInt16) with 215 and 50 groups, a state larger than the budget, 101, 1000 and 1001 states, a NULL-only key, two aggregate functions sharing the budget, a compressible 1000000-byte String state, String keys with uniqExact (query_10), UInt64 keys with uniqExact and inline count() states (cost cases).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or on-disk change; only the in-memory statistics estimate.
i Invariants and contracts preserved? serialize takes a const state, so a stopped pass leaves every state intact; the aborted buffer is cancelled (no unfinalized-buffer report in any log); only CurrentBufferExhausted is caught; the budget cannot underflow.

Session id: cron:clickhouse-impl-slot-40:20261114-221000

@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [af5e7ae]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, azure, targeted) FAIL
03634_autopr_input_bytes_estimation FAIL cidb
03634_autopr_input_bytes_estimation FAIL cidb
03634_autopr_input_bytes_estimation FAIL cidb
03634_autopr_input_bytes_estimation FAIL cidb
03634_autopr_input_bytes_estimation FAIL cidb
Too many test failures FAIL cidb
AST fuzzer (amd_debug, targeted) ERROR
OOM in dmesg ERROR cidb
AST fuzzer (amd_debug, targeted, old_compatibility) ERROR
OOM in dmesg ERROR cidb

AI Review

Summary

This PR improves the automatic parallel replicas output estimate by fully serializing small aggregation tables, including the NULL group, within a shared 1 MiB budget. No actionable correctness, safety, or compatibility findings. The ten-case regression test 05768_autopr_state_size_estimate_small_table passes in the Fast test report; the PR provides before/after estimate and overhead measurements. Broader CI is still running; no local tests were run.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements can be tested Allows running workflows for external contributors comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). labels Nov 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

⚠️ Significant changes: object file sizes.

Binary sizes

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

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

Object file sizes ⚠️

4 object files changed (+278.18 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 29.32 MiB 29.59 MiB +278.18 KiB (+0.93%)

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

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - af5e7ae

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / OOM in dmesg not from this PR: the kernel memcg OOM-killed the server (anon-rss 42.9 GiB). 0.4 s earlier the global memory tracker was corrected from -755.41 GiB to 11.11 GiB, so four 64 GiB charges of a fuzzed no-key anyOrDefault(toFixedString(..., 1048576)) (one per thread, at the start of aggregation, from another test's query) were admitted past the 40.31 GiB limit #131625 (mine, open)
AST fuzzer (amd_debug, targeted, old_compatibility) / OOM in dmesg not from this PR: the kernel memcg OOM-killed the server (anon-rss 43.0 GiB) while 3 shards of a fuzzed no-key count(toFixedString(..., 1048576)) from another test charged 8 GiB per thread at the start of aggregation, past the 39.84 GiB limit. #131185 avoids that copy only for functions that ignore repeated values, and count is not one of them a fix task is created (investigating at full effort, fixing-PR link to follow here)
Stateless tests (arm_asan_ubsan, azure, targeted) / 03634_autopr_input_bytes_estimation flaky, not from this PR: query_23 (no aggregation) read 2.02x its estimate (12563041 6218818, the bound is 2x). This job repeats the test with fixed settings, so the query condition cache prunes the read of query_23 run after run until the ratio crosses the bound. The same row failed on 4 other PRs since this job was added on 2026-11-14 #131690 (mine, open)
Stateless tests (arm_asan_ubsan, azure, targeted) / Too many test failures the runner stopped after the repeated runs of the row above #131690 (mine, open)
PR praktika rollup of the rows above #131625, #131690 (mine, open) and the fix task above

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261115-020012

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 15, 2026
The previous commits avoided the copy of a constant argument to the size of
the block only for functions that ignore repeated values. Every other
function still received the full copy, although all its rows are equal. The
AST fuzzer runs on PR ClickHouse#131697 hit exactly that case:
`anyOrDefault(toFixedString(<const>, 1048576))` and
`count(toFixedString(<const>, 1048576))` without keys asked for 64 GiB and
8 GiB per `AggregatingTransform` thread, and the server was OOM-killed. A
constant of 1 MiB is not folded by the analyzer, so `count` keeps its
argument and the copy happens.

Now, without keys, when all arguments of a function are constants, they are
copied to at most `max(1, 1 MiB / bytes of one row)` rows (one row for a
function that ignores repeated values), and that copy is added repeatedly
through `Aggregator::addBatchSinglePlace` until the rows of the block are
covered. The function sees the same values in the same order through the
same batch API, so every function and combinator is covered (`count`, `any`,
`-OrDefault`, `-If`, `-Array`, `-State`, Null adapters). A constant of up to
16 bytes still gets one batch of the whole block at the default block size.

The existing conversion pipeline (`convertToFullColumnIfConst`, replicated,
sparse and `LowCardinality` handling) is reused on a shorter constant
(`ColumnConst::cloneResized`), which replaces the separate one-row branch.

Not covered: aggregation with keys (keyed consumers, the JIT loop and the
adaptive producer's argument staging read arguments at block positions), and
a function with both constant and non-constant arguments.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=131697&sha=af5e7aee158e8379e77dc757c0a1c04b91ea14d2&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=131697&sha=af5e7aee158e8379e77dc757c0a1c04b91ea14d2&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

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

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the AST fuzzer OOM in dmesg rows in the ledger above: #131185 (updated) copies all-constant arguments to at most 1 MiB in aggregation without keys for every function, which removes the anyOrDefault copies of the targeted run and the count copies of the () grouping set in the old_compatibility run. It does not cover the keyed (a) set of that GROUPING SETS query, which still copies the constant to the block size; the targeted run's admission past the memory limit is #131625.

This branch has not been deployed

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

Labels

can be tested Allows running workflows for external contributors comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant