Skip to content

Top-K threshold merge (Fagin's algorithm) for GROUP BY ... ORDER BY aggregate LIMIT n - #116101

Merged
alexey-milovidov merged 74 commits into
masterfrom
group-by-order-by-agg-fagin
Oct 21, 2026
Merged

alexey-milovidov merged 74 commits into
masterfrom
group-by-order-by-agg-fagin

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 24, 2026 •

Copy link
Copy Markdown
Member

Related: #96630
Related: #75098
Related: #107576

Implements a top-K threshold merge — an adaptation of Fagin's Threshold Algorithm — for queries of the form

SELECT keys..., agg(...) FROM t GROUP BY keys ORDER BY agg(...) DESC LIMIT n

where the ordering aggregate has a monotonic merge bound: the finalized value of a merged state is bounded by the finalized values of the partial states being merged. The new IAggregateFunction::getMergedValueBound declares it: count, the unsigned-integer sum (its merged value is the modular sum of the partials, which never exceeds their saturating sum even with wraparound) and uniqExact are subadditive (each partial ≤ merged ≤ sum of partials; the estimating uniq/uniqHLL12 are deliberately excluded — the linear-counting phase of an HLL estimate is superadditive for disjoint register fills, so their estimates violate the bound), and min/max are exactly the extremum of the partials (floating point is excluded: the NaN-skipping merge order cannot be matched by a single compareAt direction for both min and max). The -If and Null combinators forward the subadditive bound (an untouched nested state contributes 0, consistent with a sum), but not the extremum bounds (an untouched state would contribute a bogus default).

After the parallel aggregation, each thread holds a two-level hash table of partial states, and each bucket of the two-level split holds the same groups in every table. The ordinary merge (mergeBucketImpl + conversion) touches every group; the query needs just the n best per bucket (a group outside its own bucket's best n has at least n groups ahead of it globally — the same argument as the existing bucket_top_k conversion). The threshold merge finds them while merging only the groups that can possibly rank:

  1. The partial values of every cell are peeked in devirtualized batches (a new insertResultIntoBatchWithoutDestroying; insertResultInto guarantees the state stays usable) and each table's cells are arranged into a heap by value — Fagin's "sorted access" without sorting whole lists.
  2. Cells are popped in the order of their partial values across the tables. On a group's first appearance it is looked up in every other table ("random access"), its states are merged, and its exact merged value ranks it in a bounded heap of the n best candidates. Consumed cells are nulled, so later pops of the same group are skipped.
  3. The threshold: an unseen group's partial values are bounded by the current heap tops, so its merged value is bounded by their combination — the sum of the heads for the subadditive bound, the best head for the extremum bounds. As soon as that bound cannot strictly beat the worst kept candidate, no unseen group can enter the result and the merge stops without touching the remaining groups.

The result is exactly the same as without the optimization — the bounds are rigorous, so this is not an approximation.

The existing query_plan_aggregation_bucket_top_k setting controls both conversion-stage selection and threshold merging. The planner and aggregator choose the algorithm automatically according to the aggregate, query shape, and distribution of partial states. Setting it to 0 disables both paths; query_plan_enable_optimizations = 0 also disables both.

Scope, driven by measurements on 40M-row / ~9M-group datasets:

  • The extremum bounds of min/max engage for any number of per-thread tables: they converge right after the top n candidates are found. On a heavy-hitter distribution they merged 2560 groups instead of ~9M and left ~9.6M cells untouched.
  • The summing bound of count/sum/uniqExact engages only when one table holds almost all of a bucket's cells (the shape the adaptive aggregator's drain produces), where the walk is nearly a pure selection. Across genuinely split tables it is not worth committing to: with near-uniform values the sum of the heads never lets the walk stop, and even with perfect convergence the outcome measured at parity at best — the groups the threshold prunes are exactly the ones that lost the ranking, whose states are the cheapest to merge anyway.
  • A pop budget (half of the bucket's cells) backstops non-convergent walks (e.g. ORDER BY min(x) DESC, where per-table partial minima can all sit far above the merged minimum): the first bucket to overrun it finishes with a plain linear sweep, and a verdict shared across the buckets (hash-partitioned, so alike) sends the rest to the ordinary merge from the start.
  • Ordering by count alone keeps the existing bucket_top_k conversion-stage selection (a plain scan of the merged bucket beats the value-peeking walk there); the threshold merge serves count when other aggregates ride along, and yields when the runtime dataflow statistics are being collected (they must describe the untruncated merge).

The optimization is skipped for query shapes where pruning groups could change the result: WITH TOTALS, HAVING, LIMIT WITH TIES, ROLLUP/CUBE/GROUPING SETS, more than one ORDER BY column, a COLLATE, exact_rows_before_limit, nullable or low-cardinality group keys, a nullable, floating-point, String or FixedString ordering value (the last two would pay an up-front copy of the whole ordering payload before anything is pruned), and combinator-wrapped ordering aggregates (except the forwarding above). It is observable through the new profile events AggregationThresholdTopKMerges, AggregationThresholdTopKMergedGroups and AggregationThresholdTopKPrunedCells.

Changelog category (leave one):

  • Performance Improvement

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

Merge GROUP BY keys ORDER BY <aggregate> LIMIT n queries with a threshold algorithm (Fagin): the final merge of parallel aggregation walks the per-thread hash tables in the order of the partial values of the ordering aggregate (count, sum of unsigned integers, uniqExact, min, max) and merges and materializes only the groups that can rank among the top n of each two-level bucket, instead of every group. Exact; controlled by the existing query_plan_aggregation_bucket_top_k setting, which covers both threshold merging and conversion-stage selection.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

Version info

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

alexey-milovidov and others added 5 commits August 24, 2026 08:35
…ORDER BY aggregate LIMIT N

For monotonic-mergeable aggregate functions (count, uniqExact, min, max)
the final merge of parallel aggregation walks the per-thread hash tables
in the order of the partial values and merges only the groups that can
rank among the top N of each two-level bucket, instead of merging and
materializing every group.

Co-Authored-By: Claude Fable 5 <[email protected]>
…string keys for probes

The compiled-functions holder is local to Aggregator.cpp, and the
interpreted merge is valid on states the compiled code accumulated (the
layouts are shared by contract). The packed-string cells hand out
unpacked views, so probing another table rebuilds the packed key with
the method's content hash, through a padded copy for the small encoding.

Co-Authored-By: Claude Fable 5 <[email protected]>
…descending order

A near-uniform count split across every thread defeats the summing
threshold (the per-thread partial values say nothing about the merged
order), so the walk would visit every group and only pay overhead: on a
weakly-skewed distribution the merge was 3x slower. The precheck
estimates from the peeked partial values whether the threshold can stop
the walk early and otherwise takes the ordinary merge. The ascending
order for count/uniqExact suffers the same degeneracy with no cheap
estimator, so the plan no longer requests it; the extremum bounds of
min/max converge right after the candidates are found in either order.

Also fixes the test data (tail counts collided with the unique head
counts at the LIMIT boundary) and the uninitialized-variable style
findings, and moves the Merges profile event after all the bail-outs.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ble count, summing bound for a dominant table

Measured on 40M rows / ~9M groups: even with perfect convergence, the
multi-table summing walk is at best at parity with the ordinary merge -
the groups it prunes are exactly the ones whose states are the cheapest
to merge - while near-uniform data risked a regression. The summing
bound of count/uniqExact now engages only when one table holds almost
all cells (the shape the adaptive drain produces), where it is nearly a
pure selection; a pop budget with a bucket-shared verdict backstops the
remaining non-convergent walks (e.g. ORDER BY min DESC) by finishing
the first bucket with a linear sweep and sending the rest to the
ordinary merge. The values are now peeked in devirtualized batches (a
new insertResultIntoBatchWithoutDestroying), and the lone count() keeps
its conversion-stage bucket selection, which a plain scan serves better.

Co-Authored-By: Claude Fable 5 <[email protected]>
…in the events test

Ordering by count is served by the conversion-stage bucket selection
(which a plain scan serves better), so the events test asserts both
mechanisms side by side, and generates the references.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [24bbe38]

Summary: ✅


AI Review

Summary

The PR adds threshold-based merging for supported GROUP BY ... ORDER BY <aggregate> LIMIT queries, reducing aggregate-state merges while preserving exact results. The current code addresses the earlier review findings; no actionable findings remain.

Final Verdict

✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 24, 2026
@EmeraldShift

Copy link
Copy Markdown
Contributor

When exactly does this optimization take place ? I see some description of "After the parallel aggregation", but does this mean only once at the end of the query? Or during every partial re-merge? I recall that re-merges during the query are possible, but not super frequent unless using the TopkThresholdTracker (for a different scan-skipping TopK optz).

The new setting's changes-history entry belongs in the current-version
(26.9) block, and the packed-string probe rebuild passes the size
alongside the view's data pointer, which the tidy check cannot see.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Core/Settings.cpp Resolved
@nihalzp nihalzp self-assigned this Aug 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 24bbe3889 with master c7531f5ee (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
Binary Master PR Δ
programs/clickhouse-stripped 782.20 MiB 781.87 MiB -333.52 KiB (-0.04%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

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 ⚠️

200 object files changed (+6.26 MiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/AggregatorThresholdTopK.cpp.o new 1.40 MiB +1.40 MiB
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionsArgMinArgMax… 15.60 MiB 16.00 MiB +413.05 KiB (+2.59%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniq.cpp.o 11.91 MiB 12.16 MiB +255.87 KiB (+2.10%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionAvgWeighted.c… 13.34 MiB 13.58 MiB +240.94 KiB (+1.76%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupArrayMov… 5.63 MiB 5.81 MiB +185.04 KiB (+3.21%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionCovar.cpp.o 6.65 MiB 6.79 MiB +145.09 KiB (+2.13%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionCorr.cpp.o 6.83 MiB 6.97 MiB +144.38 KiB (+2.06%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupArray.cp… 4.48 MiB 4.62 MiB +137.48 KiB (+2.99%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupNumericI… 7.30 MiB 7.43 MiB +134.79 KiB (+1.80%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileExact… 6.54 MiB 6.65 MiB +118.40 KiB (+1.77%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionSum.cpp.o 3.65 MiB 3.76 MiB +110.19 KiB (+2.95%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionRegr.cpp.o 5.81 MiB 5.92 MiB +109.00 KiB (+1.83%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionsMinMax.cpp.o 2.53 MiB 2.64 MiB +102.73 KiB (+3.96%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionSparkbar.cpp.o 5.23 MiB 5.33 MiB +102.47 KiB (+1.91%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionDeltaSumTimes… 3.42 MiB 3.51 MiB +94.00 KiB (+2.68%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 2.97 MiB 3.05 MiB +76.32 KiB (+2.51%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 2.97 MiB 3.05 MiB +76.32 KiB (+2.51%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 2.97 MiB 3.05 MiB +76.32 KiB (+2.51%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined2… 2.97 MiB 3.05 MiB +76.32 KiB (+2.51%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 2.97 MiB 3.05 MiB +76.32 KiB (+2.51%)

719 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

1242 translation units recompiled, 9313 s compile time in total, 1155 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Interpreters/AggregatorThresholdTopK.cpp: 11.9 s
  • src/Server/GRPCServer.cpp: 10.0 s
  • src/Backups/RestorerFromBackup.cpp: 7.9 s
  • src/Interpreters/InterpreterKillQueryQuery.cpp: 7.1 s
  • src/Interpreters/DistributedQueryStatusSource.cpp: 6.9 s
  • src/Databases/DatabaseReplicatedWorker.cpp: 6.6 s
  • src/Dictionaries/YTsaurusDictionarySource.cpp: 6.5 s
  • src/Server/MySQLHandler.cpp: 6.4 s
  • src/Dictionaries/PostgreSQLDictionarySource.cpp: 6.3 s
  • src/Interpreters/loadMetadata.cpp: 6.2 s
  • src/Storages/Kafka/KafkaConfigLoader.cpp: 6.0 s
  • src/Interpreters/InterpreterRenameQuery.cpp: 5.9 s
  • src/Interpreters/ReplicatedDatabaseQueryStatusSource.cpp: 5.7 s
  • src/Interpreters/DDLOnClusterQueryStatusSource.cpp: 5.7 s
  • src/Processors/Transforms/AsyncInsertQueueTransform.cpp: 5.7 s
  • src/Databases/DatabaseMemory.cpp: 5.6 s
  • src/TableFunctions/TableFunctionYtsaurus.cpp: 5.4 s
  • src/Parsers/LogsQL/LogsQLPipes.cpp: 5.3 s
  • src/Parsers/ExpressionElementParsers.cpp: 5.2 s
  • src/Databases/DatabaseHDFS.cpp: 5.1 s
Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse DB::Aggregator::tryMergeAndConvertOneBucketToChunkThresholdTopK(std::__1::vector<std::__1::shared_p… new 104.44 KiB +104.44 KiB
programs/clickhouse-keeper DB::Aggregator::tryMergeAndConvertOneBucketToChunkThresholdTopK(std::__1::vector<std::__1::shared_p… new 103.43 KiB +103.43 KiB
programs/clickhouse ProfileEvents::global_counters_storage 13.38 MiB 13.44 MiB +64.00 KiB (+0.47%)
programs/clickhouse-keeper ProfileEvents::global_counters_storage 13.38 MiB 13.44 MiB +64.00 KiB (+0.47%)

Job report

…check

The flaky check inflates the per-run cost enough that the 1.2M-row dataset
exceeded the 180s budget on the sanitizer and debug flavors:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116101&sha=4d2b25067bd3af41519492a34c32e292fa6a98f8&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29
#116101

The dataset was that large only because the adaptive aggregator keeps the
per-thread tables single-level while staging (group_by_two_level_threshold
does not act until the scan outgrows the adaptive watermarks), and the
threshold merge serves only the two-level final merge. Pin
enable_adaptive_aggregator = 0 so the forced two-level conversion is
deterministic, and shrink the tail from 8000 keys x 150 rows to
8000 keys x 8 rows: the same number of keys keeps the per-bucket cell
population (and thus the engagement and pruning shape, verified via the
AggregationThresholdTopK* profile events) identical, while the scanned
rows drop from 1.2M to 94K.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🔴 AI verdict: degradation — 1 query(s) regressed out of 31 analysed

This PR adds a threshold top-K merge for two-level aggregation buckets. It only runs for GROUP BY ... ORDER BY <count/unsigned sum/uniqExact/min/max> LIMIT n when more than one aggregate is present. ClickBench Q32 (GROUP BY WatchID, ClientIP ORDER BY count() DESC LIMIT 10, together with sum and avg) has exactly that shape and comes out +13.7% slower with about 15% more CPU, so the regression stands. One caution: the PR median of 838.5 ms is still inside master's recent 683-922 ms range and both sides were noisy, so confirm with the setting turned off before acting. Q20's -42.3% does not go through any of the changed aggregation paths, so it is downgraded to not sure.

clickbench

🔴 1 regressed · ⚠️ 1 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🔴 32 regression 738 838 +13.7% <0.0001 aggregation: Q32 groups by WatchID, ClientIP and orders by count() DESC LIMIT 10 next to sum and avg, the exact shape routed to the new threshold top-K bucket merge. CPU rose about 15%, but 838.5 ms is inside master's recent range and runs are noisy.
⚠️ 20 not_sure 220 127 -42.3% <0.0001 Q20 has no GROUP BY ... ORDER BY aggregate LIMIT shape, so the new threshold top-K merge and the plan rule that enables it never run here. The -42.3% shift is not attributable to this diff.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 37076de0-aac7-40c4-8718-26901ec9e5fd
  • MIRAI run: 46064ef6-2355-4f9e-88b0-48a0130865b5
  • PR check IDs:
    • clickbench_115187_1791947417
    • clickbench_115207_1791947417
    • clickbench_115214_1791947417
    • tpch_adapted_1_official_115239_1791947417
    • tpch_adapted_1_official_115625_1791947422
    • tpch_adapted_1_official_115863_1791947596

The s3/azure read pools split the read into per-part tasks, so the part with
the heavy keys could land in its own stream. A stream that sees fewer distinct
keys than the adaptive freeze threshold survives the drain as a second table,
whose head keeps the summing threshold open on the tied tail values; the pop
budget then trips and the verdict sends every bucket to the ordinary merge,
so `AggregationThresholdTopKPrunedCells` stayed 0 for `uniqExact`. Reproduced
locally with `merge_tree_min_rows_for_concurrent_read = 110001` (two streams).

`max_streams_to_max_threads_ratio = 0.25` pins one scan stream on every
storage backend (a requested stream count of 1 is exempt from the async io
pool raising), while the merge stage keeps running on `max_threads`.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116101&sha=586c89f641ab76bb0d8dce3ed042794945a9bf6f&name_0=PR&name_1=Stateless%20tests%20(arm_asan_ubsan%2C%20azure%2C%20parallel)
PR: #116101

Co-Authored-By: Claude Fable 5 <[email protected]>
…ts test

The previous commit pinned one scan stream, but single-stream aggregation
honors `group_by_two_level_threshold` only when the external aggregation is
possible (`allow_to_use_two_level_group_by` in `AggregatingStep`: a
single-stream two-level table serves nothing but the spill), and the CI
settings randomization sets both `max_bytes_before_external_group_by` and
`max_bytes_ratio_before_external_group_by` to 0. Every state then stayed
single-level and all the profile events read 0 - the flaky checks and several
plain suites failed with an all-zeros diff; the CI's own culprit finder and a
local bisection over the randomized settings both landed on
`max_bytes_ratio_before_external_group_by = 0`.

Pin a spill threshold that is enabled but can never trigger on this dataset
(10 GiB, ratio 0), and pin `enable_adaptive_aggregator = 0` instead of the
previous adaptive settings - the adaptive aggregator stands down for a
single-stream scan anyway, so they were inert.

Verified locally against all five randomized settings sets of the failing
flaky-check runs, the two-settings killer combination alone, the two-stream
read-split adversary, and defaults.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116101&sha=fadc1b416201bf7e29e5139d4276a00508f48c22&name_0=PR&name_1=Stateless%20tests%20(amd_binary%2C%20flaky%20check)
PR: #116101

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Interpreters/Aggregator.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Worth noting that sum of an unsigned number is also monotonic. Let's make sure it is taken into account!

@alexey-milovidov

Copy link
Copy Markdown
Member Author

When exactly does this optimization take place ?

It should take place under similar conditions to our recently implemented GROUP BY with ORDER BY aggregation keys with LIMIT. After accumulating some threshold of keys.

alexey-milovidov and others added 6 commits August 27, 2026 07:58
…gg-fagin

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.cpp
…ructive merge

The random-access merge destroyed each source aggregate substate in place while the
owning pointer stayed live in the hash table until every aggregate finished; if a later
aggregate's merge threw (e.g. `MEMORY_LIMIT_EXCEEDED`), the unwinding would revisit the
cell and destroy the already-consumed substates a second time. Null the cell first, the
same pattern as `mergeDataImpl`.

Co-Authored-By: Claude Fable 5 <[email protected]>
… threshold merge serves `count` with riders

Master's #116124 put the bucket-local selection under `query_plan_aggregation_bucket_top_k`;
the shared plan pass now runs under the disjunction of that setting and
`enable_aggregation_top_k_threshold_merge`, and each optimization checks its own flag, so
disabling one no longer silently disables the other.

Also, per review: the lone-count selection (`bucket_top_k`) no longer preempts the threshold
merge when other aggregates ride along - there the merge is the better deal, since it also
skips merging the losers' other states. The selection still serves the lone `count` and the
shapes the merge does not (e.g. the ascending order).

Co-Authored-By: Claude Fable 5 <[email protected]>
…om the threshold merge

The merge peeks every cell's partial value into a column up front, and for the
variable-length types that is an extra full copy of the ordering payload before anything
is pruned - a memory regression the fixed-width scalars do not have.

Co-Authored-By: Claude Fable 5 <[email protected]>
Requested in review: `sum` of unsigned integers qualifies for the threshold merge just
like `count` - the merged value is the modular sum of the partial values, which never
exceeds their saturating sum even with wraparound. Signed and floating-point sums do not
qualify (negative addends break the bound), and neither do the decimal and wide-integer
results (the bound's arithmetic works on `UInt64` values).

Also refresh the setting description: name `sum`, the `String`/`FixedString` exclusion,
and the actual combinator exception set (`If`/`Null` forward the subadditive bound).

Co-Authored-By: Claude Fable 5 <[email protected]>
- 05043: the count-with-riders query now proves the threshold merge takes over (its events
  flip from the bucket selection), a lone-count query keeps the selection covered, and new
  event assertions prove `sum`, `countIf` and `uniqExact` of a nullable argument (the
  `If`/`Null` subadditive forwarding, as requested in review) actually take the
  threshold-merge path; a `String` ordering value is asserted not to.
- 05042: exactness coverage for `sum(u)` in both directions; note that the `String`
  ordering values are now excluded (the query stays as a correctness check).

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

Copy link
Copy Markdown
Member Author

🕵 Done: sum of unsigned integers now declares the subadditive bound and takes the threshold merge (the merged value is the modular sum of the partials, which never exceeds their saturating sum even with wraparound, so the bound stays rigorous). Signed and floating-point sums are excluded — negative addends break the bound. Covered by exactness tests in 05042 and event assertions in 05043.

This round also addresses the AI review: the destructive merge detaches the source cell before merging (exception safety), the lone-count selection no longer preempts the threshold merge when other aggregates ride along, String/FixedString ordering values are excluded (they would pay an up-front copy of the whole ordering payload), and the pass is reconciled with #116124's query_plan_aggregation_bucket_top_k (each optimization now has its own gate).

alexey-milovidov and others added 4 commits October 17, 2026 16:55
`AggregateFunctionTuple::mergeAndDestroyBatch` destroys the source substates
one child at a time, so a failure in the second child's merge left a source
state whose first child was already destroyed, and the whole-state cleanup
destroyed it a second time. Merge with `mergeBatch` and destroy the source
state once after all the merges succeeded; on failure it is still whole.

Also value-initialize `Entry::key` for `clang-tidy`
(`cppcoreguidelines-pro-type-member-init`):
https://s3.amazonaws.com/clickhouse-test-reports/PRs/116101/35510047feec64eda0eb02f08830b7695864b52e/pr/build_arm_tidy_1_4/build_clickhouse/build_clickhouse.log

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

Copy link
Copy Markdown
Member Author

🕵 Fixed the remaining arm_tidy failures in AggregatorThresholdTopK.cpp (479a223): cppcoreguidelines-pro-type-member-init on Entry::key and misc-misplaced-const on other_state. Local clang-tidy on the file is clean. Also merged master (824e9ea). No unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=116101&sha=824e9ea9bfa450ab334d4bce14142c0400a8d4bc&name_0=PR&name_1=Unit%20tests%20%28asan_ubsan%2C%20function_prop_fuzzer%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

FunctionsStress.stress reports a worker stuck in __asan_stack_malloc_1 while running range, which this PR does not touch. The same test failed on about 30 other PRs and on master from 2026-10-15 to 2026-10-19. This looks like the issue #126210 is meant to fix. No unresolved review threads remain on this PR.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is my #126210 (open). The stuck worker at 824e9ea9 (87.9 s on range(materialize(CAST(8642654 AS Int64)))) has the same stack it addresses: __asan_stack_malloc_1 <- PODArray::operator[] <- ColumnArray::compareAtImpl <- FunctionsStressTestThread::executeFunction.

Mechanism: #120908 (comment). #126210 changes only the test harness; its CI has finished and it is mergeable, waiting for a review.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks, @groeneai: #126210 covers the FunctionsStress.stress hang. It was the only failure on 824e9ea, but it stopped the run before 77 jobs could start. I merged master (0332c23, no conflicts) to get a full CI run. The merged tree builds, and the PR's tests pass locally (05042, 05212, 05258, 05331, 05401). I could not run 05043 locally, because the local cluster config points to a port my test server did not use. No unresolved review threads.

@nihalzp nihalzp self-assigned this Oct 19, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=116101&sha=0332c23a091aa7b027a9d7ed8849a237d79283fd&name_0=PR&name_1=AST%20fuzzer%20%28amd_release%2C%20oracle%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

OOM in dmesg in AST fuzzer (amd_release, oracle): the server was OOM-killed at 53 GB RSS. The last query was SELECT COUNTTupleOrDefault(tuple(* APPLY ...)) FROM merge('system', '^') FINAL, run with max_memory_usage = '0'. It has no GROUP BY, so it does not touch the top-K threshold merge in this PR. In the last 30 days, OOM in dmesg failed the AST fuzzer jobs on many other PRs as well (e.g. 125848, 125726, 124938, and on master).

I merged master (28dd24c, no conflicts) to rerun CI.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating the OOM in dmesg in AST fuzzer (amd_release, oracle) at 0332c23; I'll follow up here with a PR (or my findings) shortly.

@groeneai

Copy link
Copy Markdown
Collaborator

The driver is the per-tick correction from #118094, the same mechanism as in test_memory_limit, so the fix in progress is your #126176.

In the server log, two variants of this query ran back to back, both with max_memory_usage = 0:

  • a6cdacd9 reached Query current memory usage: 59.02 GiB against max_server_memory_usage = 40.33 GiB. Nothing refused it until resident memory itself hit the limit 7 s later: would use 39.59 GiB (attempt to allocate chunk of 4.29 MiB), current RSS: 39.92 GiB, maximum: 39.92 GiB.
  • 57646268 went from 9.00 to 73.68 GiB in 0.24 s. Without its tracker passing that peak, resident memory then grew from 41.34 to 53.13 GiB in 1.5 s, and the 53.78 GiB container killed the server.

A query at 59 GiB under a 40 GiB global limit means the global counter was below one of its children: the memory worker replaces it with the resident memory every tick, and memory that is allocated but not yet written is not resident. stats.allocated includes it, so #126176 should stop both variants at the limit.

The memory itself is expected without a query limit: tuple(* APPLY toTypeName) is a constant with one string per column of every system table, and Aggregator materializes constant arguments for every block (Aggregator.cpp). Locally any(tuple(...)) also runs into an 8 GiB cap, while a tuple of 1s peaks at 0.7 GiB.

I could not reproduce the kill locally: with this run's binary, 16 CPUs and a 12 GiB server limit, the query stops with Code: 241 with the correction both on and off. So this rests on the CI log, not on a repro.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 21, 2026
Merged via the queue into master with commit 485ffc0 Oct 21, 2026
180 checks passed
@alexey-milovidov
alexey-milovidov deleted the group-by-order-by-agg-fagin branch October 21, 2026 20:01
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 21, 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-performance Pull request with some performance 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.

6 participants