Skip to content

Keep a key sample in the bucket Top-K conversion for the output-bytes estimate - #123807

Merged
nickitat merged 4 commits into
ClickHouse:masterfrom
groeneai:fix/03634-autopr-output-bytes
Nov 6, 2026
Merged

nickitat merged 4 commits into
ClickHouse:masterfrom
groeneai:fix/03634-autopr-output-bytes

Conversation

@groeneai

@groeneai groeneai commented Oct 4, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #104510
Related: #123781

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

The output-bytes estimate of automatic parallel replicas no longer depends on whether the final aggregation keeps only each bucket's top rows (query_plan_aggregation_bucket_top_k).

Description

03634_autopr_output_bytes_estimation failed on master with query_12 at 2.51x of its golden (tolerance 2.5x):
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=ed7e72d6797b8e678518f5a2a26faff7f2bd695e&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%29

The bucket Top-K conversion emits only the best rows of each two-level bucket. For the dataflow statistics it already
reports the untruncated key bytes, but it kept no key sample, so the statistics took the keys' compression ratio from
the 10-row chunk. Ten keys compress much worse than the whole bucket (ratio ~1.5 instead of ~2.7 on test.hits
SearchPhrase), so the estimate came out ~1.8x higher than the same aggregation without Top-K. query_12 takes Top-K
only when its tables go two-level, which depends on the read split, so CI landed on both sides of the tolerance.

The conversion now keeps the meter's bounded sample (at most 1024 keys / 1 MiB per bucket) and passes it to the
statistics, as the HAVING pre-filter conversion already does. The open #123531 rewrites this function and adds a
second Top-K conversion that also passes keep_sample = false.

Validation, debug build, server with 32 streams like the CI job, query_12 estimate:

arm before after
single-level, no Top-K 2.90M 2.96M
two-level, Top-K 6.18M 3.44M
two-level, Top-K disabled 3.43M 3.44M
  • New test 05321 compares the estimate with and without Top-K: fails 5/5 before (2.37x), passes 50/50 randomized
    after. Removing either of its two pins makes it fail in a configuration CI can produce.
  • 03634 is unchanged and passes 45/45 in three modes, including enable_adaptive_aggregator = 0 (the pin of Disable the adaptive aggregator in 03634_autopr_output_bytes_estimation #123781),
    which does not avoid Top-K at 32 streams (2.27-2.42x before). query_34 now estimates 0.66x of a golden recorded
    before bucket Top-K existed, inside the tolerance, so I did not re-measure it.

🤖 Generated with Claude Code


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

Version info

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

groeneai and others added 2 commits October 4, 2026 01:01
… estimate

The bucket Top-K conversion (`query_plan_aggregation_bucket_top_k`) emits only the
best rows of each two-level bucket. For the runtime dataflow statistics of automatic
parallel replicas it already reports the untruncated key bytes, but it kept no key
sample, so the statistics took the keys' compression ratio from the emitted chunk.
Ten rows compress far worse than the bucket's keys (ratio ~1.5 instead of ~2.7 on
`test.hits` `SearchPhrase`), so the estimate came out about twice as high as the same
aggregation without Top-K. `03634_autopr_output_bytes_estimation` query_12 takes Top-K
only when its tables go two-level, which depends on the read split, and its estimate
then straddled the 2.5x tolerance (2.51x on master ed7e72d).

Keep the meter's bounded sample (at most 1024 keys / 1 MiB of the bucket) and hand it
to the statistics, as the HAVING pre-filter conversion already does. With the change
the Top-K estimate equals the non-Top-K one within 1% on the same data.

New test 05321 compares the estimate with and without the Top-K conversion on a
deterministic two-level fixture.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Name what the bucket Top-K meter samples: the bucket's keys, not the kept rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 4, 2026
@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 findings) plus my own review of the same head.

# Sev Finding Verdict Evidence / action
1 ⚠️ The kept key sample can exceed its 1 MiB bound, because the bound is checked after a key is copied (Aggregator.cpp, MaterializedKeyBytesMeter::takeRow) DISAGREE The overshoot is at most one key, which the meter's scratch row and the aggregation arena already hold; both HAVING pre-filter conversions use the same meter with a sample.
2 💡 Related: links #104510, which is unrelated DISAGREE #104510 is where this fix was requested.
3 💡 keep_sample is now true at every MaterializedKeyBytesMeter site, so the parameter is constant noted Kept, so the change stays at the one call site.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261004-021600

@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f7b09ca]

Summary: ✅


AI Review

Summary

The PR retains a sample of untruncated grouping keys during bucket Top-K conversion so automatic parallel replicas estimate key compression from representative data. The regression test compares estimates with Top-K enabled and disabled and checks that both execution paths ran. No unresolved findings at f7b09cabf2e7. The previous serialize_query_plan fixture issue is fixed, and its review thread is resolved.

Missing context / blind spots
  • ⚠️ Current-head builds and their dependent stateless tests are still pending. No local ClickHouse binary was available for an independent rerun; regression evidence includes the focused test and the PR's reported repeated before/after runs with the distributed-plan profile.
Final Verdict

✅ Approve — no further changes requested by this review.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Oct 4, 2026
@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. New test 05321 with --no-random-settings fails 5/5 before the change (Top-K estimate 528822 vs 223503 without Top-K, 2.37x). On a 32-stream server query_12 of 03634 estimates 6.18M with Top-K vs 3.43M without on the same data, on every run.
b Root cause explained? convertOneBucketToChunkTopK reported the untruncated key bytes but kept no key sample, so the dataflow statistics took the compression ratio from the 10-row Top-K chunk (ratio ~1.5 instead of ~2.7). The estimate doubled whenever the final merge was two-level, which for query_12 depends on the read split.
c Fix matches root cause? Yes. The conversion keeps the meter's bounded sample (<= 1024 keys / 1 MiB) and hands it to the statistics, the same mechanism the HAVING pre-filter conversion already uses. No tolerance, golden or setting in 03634 changed.
d Test intent preserved / new tests added? 03634 untouched. New 05321 asserts the estimate does not depend on the Top-K conversion, with liveness lines that the Top-K query took Top-K and the other did not. Each of its two pins was shown necessary by a deletion run.
e Both directions demonstrated? Before: 5/5 (no randomization), 36/36 (max_threads 1/3/8/32 x 1/2/8 parts), 20/20 randomized, 10/10 with serialize_query_plan=1 all fail. After: all pass, plus 50/50 randomized. Build IDs verified on the running server.
f Fix is general across code paths? The map overload is the only truncating conversion without a sample: the set overload throws, both HAVING pre-filter conversions already keep one, non-truncating conversions emit the whole bucket, and skip-merging/external aggregation mark the statistics unsupported.
g Fix generalizes across inputs (params/datatypes/wrappers)? Top-K refuses Nullable and LowCardinality keys; String, numeric, FixedString and serialized multi-key go through the meter code the HAVING path already runs (05234). Covered parts 1/2/8, max_threads 1/3/8/32 and full runner randomization.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default, format or protocol change; only an internal estimate of an experimental feature changes.
i Invariants and contracts preserved? The emitted chunk is unchanged (same rows and header). The sample is bounded and moved out once per bucket, the same ownership pattern as the HAVING path; no new shared state or lock. 03634 45/45, related tests and *autopr* 162/162 randomized, unit_tests_dbms *Aggregat* 67/67.

Session id: cron:clickhouse-impl-slot-6:20261004-020003

@groeneai
groeneai requested review from nickitat and nihalzp October 4, 2026 02:47
@clickhouse-gh clickhouse-gh Bot added the comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). label Oct 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

No arm_release build profile data for commit f7b09ca - the build was skipped, reused from cache, or predates profile upload.

The distributed-plan stateless jobs load tests/config/users.d/distributed_plan.xml,
which sets serialize_query_plan = 1. Since master 9ba7a19 / 76c606e,
tryPushBucketTopKIntoAggregation does not enable the bucket Top-K selection for a
serialized or distributed plan, so in that suite both measured queries took the
ordinary conversion and the liveness line read `bucket_top_k_on 0 1`. Pin the
setting as 04911 and 05183 do.

Measured with the distributed-plan profile: the unpinned test fails 3/3 on the
liveness line; the pinned test passes 3/3 + 20/20 randomized with the fix, and
fails 3/3 + 10/10 randomized at the estimate line without it (ratio 1.85).

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f7b09ca

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
Build profile diff / LogClusterNotReady: the endpoint never became ready CI infra, not from this PR (it changes only Aggregator.cpp and test 05321): the read-only CI logs cluster answers every query, SELECT 1 included, with Code: 241 ((total) memory limit exceeded, maximum 212.40 GiB), so the readiness probe never passes. Every Build profile diff run since 2026-10-26 22:00Z is red the same way (about 60 runs) #126200 (mine, open)
Stateless tests (arm_binary, sequential) / 05218_text_index_substreams_opened_lazily flaky, not from this PR: in_range_above_threshold 1 -> 0; the runner's random-settings diagnosis isolates use_columns_cache = 1 (24/24 fail with the draw, 26/26 pass without). The fix merged at 01:19Z and is absent from the merge commit this job built #127781 (mine, merged)
Mergeable Check, PR praktika rollups of the rows above #126200 and #127781 (the owners of the rows above)

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

Session id: cron:our-pr-ci-monitor:20261027-030010

@nickitat
nickitat added this pull request to the merge queue Nov 5, 2026
Merged via the queue into ClickHouse:master with commit c8c7411 Nov 6, 2026
526 of 529 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 6, 2026
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-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

4 participants