Skip to content

Merge the lazy FINAL in-order deduplicating aggregation in batches, not one group at a time - #123326

Merged
nickitat merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/lazy-final-aggregation-in-order-batched-merges
Nov 6, 2026
Merged

nickitat merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/lazy-final-aggregation-in-order-batched-merges

Conversation

@groeneai

@groeneai groeneai commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #114579

Changelog category (leave one):

  • Performance Improvement

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

Lazy FINAL (query_plan_optimize_lazy_final) is much faster with optimize_aggregation_in_order: its deduplicating aggregation now merges groups in blocks bounded by aggregation_in_order_max_block_bytes, like an ordinary in-order GROUP BY, instead of one group at a time (25000 merges down to 3 on the reproducer from #114579). Closes #114579.

Description

LazyReadReplacingFinalSource::buildPlanFromReadingStep built the deduplicating AggregatingStep with aggregation_in_order_max_block_bytes = 0. The internal plan is optimized with the query's settings, so with optimize_aggregation_in_order = 1 it aggregates in order, and a budget of 0 makes AggregatingInOrderTransform and FinishAggregatingInOrderTransform flush at every key: one Aggregator::mergeBlocks call (two log lines) per group. Every other AggregatingStep builder passes the query's setting; this one now does too. Results are unchanged.

Debug build, clickhouse local, query time, median of 3, logs off (merges counted at trace):

fixture optimize_aggregation_in_order before after
#114579 repro, max_threads = 4 1 0.803 s, 25000 merges 0.021 s, 3 merges
0 0.018 s 0.019 s
2 x 80000 rows, index_granularity = 256, max_threads = 1 1 11.9 s, 80000 merges 0.078 s, 2 merges
0 0.039 s 0.039 s

The new test counts the Merging partially aggregated blocks lines of the #114579 query: 25000 on master, 3 with the fix (it accepts 1 to 100).

The performance test lazy_final_aggregation_in_order.xml reads 20000 filtered keys from two intersecting parts. Under perf.py with the perf-comparison configs (max_threads = 12, trace log), on the CI amd_release binaries: master 0.45 s per run (70527 merges), the fix 0.02 s (2 merges).


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

Version info

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

The deduplicating aggregation that lazy FINAL builds over the intersecting
parts was constructed with aggregation_in_order_max_block_bytes = 0. The
internal plan is optimized with the query's settings, so with
optimize_aggregation_in_order = 1 it aggregates in order, and a byte budget of
0 makes AggregatingInOrderTransform and FinishAggregatingInOrderTransform flush
at every key. Every group then became its own chunk and was merged separately
by Aggregator::mergeBlocks: 25000 merges (and 50000 log lines) for the 35000-row
reproducer from ClickHouse#114579, versus 3 for an ordinary in-order GROUP BY.

Pass the query's aggregation_in_order_max_block_bytes, as every other
AggregatingStep builder does. Results are unchanged; on a debug build the
reproducer query goes from 0.80 s to 0.02 s and an 80000-row single-thread
case from 11.9 s to 0.08 s.

Closes ClickHouse#114579

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 1, 2026
@groeneai

groeneai commented Oct 1, 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; 0 findings) plus my own cold review (1 nit).

# Sev Finding Verdict Evidence / action
1 💡 Test comment says one merge per group would be ~20000 merges; the unfixed binary does 25000 on this fixture (05316_lazy_final_aggregation_in_order_batched_merges.sh) AGREE, noted, not blocking Comment only, the oracle (1..100 merges) is unaffected

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-10:20261001-191000

@groeneai

groeneai commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The #114579 query in clickhouse local --send_logs_level=trace logs 25000 Merging partially aggregated blocks lines with optimize_aggregation_in_order = 1 and 0 with = 0, on every run of a master debug build.
b Root cause explained? LazyReadReplacingFinalSource::buildPlanFromReadingStep built its deduplicating AggregatingStep with aggregation_in_order_max_block_bytes = 0. The internal plan runs under the query's optimization settings, so in-order aggregation applies, and with a 0 budget AggregatingInOrderTransform / FinishAggregatingInOrderTransform flush at every key, so every group is merged separately.
c Fix matches root cause? Yes. The query's aggregation_in_order_max_block_bytes is passed at the one site that made up the 0. No transform semantics change.
d Test intent preserved / new tests added? New 05316_lazy_final_aggregation_in_order_batched_merges.sh: same result as regular FINAL, Lazy FINAL enabled in the trace, merge count between 1 and 100.
e Both directions demonstrated? Unfixed binary: 10/10 FAIL (batched merges: 25000). Fixed binary: 200/200 OK with randomized settings. Repro: 25000 merges before, 3 after.
f Fix is general across code paths? This was the only AggregatingStep builder that made up the byte budget. Planner and InterpreterSelectQuery pass the setting; correlated subqueries and the Cascades aggregation pushdown copy it from the source step. EXPLAIN builds its plan through the same function.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured with budget 0 / 100000 / 50000000 (25000 / 7 / 3 merges), max_threads 1 and 4, with and without is_deleted, and 200 randomized setting draws. Results were identical in every case. The budget does not depend on key types.
h Backward compatible? (maintainer-approved exception only) Yes. No setting is added or changed, results are unchanged, and memory stays bounded by the existing aggregation_in_order_max_block_bytes.
i Invariants and contracts preserved? Same transforms with larger blocks, so the in-order output order and block structure are unchanged. The lazy FINAL output order was already unspecified. The existing lazy FINAL tests have identical results before and after the change.

Session id: cron:clickhouse-impl-slot-4:20261001-182600

@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2b902f0]

Summary: ✅


AI Review

Summary

Reviewed PR #123326 at 2b902f05ab222e2c6a6a20fc3a99b7f77ffd6828. Passing aggregation_in_order_max_block_bytes into the lazy FINAL aggregation restores batched merging. The focused regression and performance tests, together with the reported before/after measurements, support the change. No actionable findings.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 1, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Oct 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 32 queries analysed

This PR changes one argument in the lazy FINAL plan builder (LazyReadReplacingFinalSource), which now passes aggregation_in_order_max_block_bytes instead of 0. That code runs only for FINAL reads on ReplacingMergeTree with query_plan_optimize_lazy_final enabled, and no ClickBench or TPC-H query does that. The flagged ClickBench regressions, Q16 (+16.4%) and Q33 (+5.3%), are downgraded to not sure, and the suppressed Q17 (+13.1%) stays suppressed. All three are memory-heavy GROUP BY queries, and some source runs shared nodes with other benchmark runs and were noticeably noisier than base, so contention is the likely cause rather than this diff. If you want a real signal for this change, look at the new lazy_final_aggregation_in_order perf test.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 505 588 +16.4% <0.0001 aggregation: Q16 is a plain GROUP BY over a MergeTree table with no FINAL, so it never reaches the lazy FINAL source this PR changes. The +16.4% shift lines up with source runs that shared nodes and were much noisier than base.
⚠️ 17 not_sure 236 267 +13.1% <0.0001 aggregation: The +13.1% delta stayed suppressed because Q17 never runs the lazy FINAL code path this PR edits. Nothing in the diff explains it.
⚠️ 33 not_sure 1010 1062 +5.3% <0.0001 aggregation: Q33 is a high-cardinality GROUP BY on a non-Replacing table with no FINAL, so the changed lazy FINAL plan builder is never used. The +5.3% shift is not attributable to this PR.

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: d78501c0-1a2e-455f-b712-b358b10d0a79
  • MIRAI run: 9a13e50d-0c7b-42cd-93fc-efad32d6ff42
  • PR check IDs:
    • clickbench_476771_1791516841
    • clickbench_476777_1791516841
    • clickbench_476783_1791516841
    • tpch_adapted_1_official_476794_1791516841
    • tpch_adapted_1_official_476806_1791516841
    • tpch_adapted_1_official_476842_1791516841

@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

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.

Compile time of recompiled translation units

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

Job report

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6b5a77c

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
Performance Comparison (amd_release, master_head, 6/6) / window_transform #5 dashboard confirmed_regression, client_time 0.0799 -> 0.0978 s (+22.4%), still +20.7% after the harness restarted both servers, and the shard report also calls it slower. The query is quantilesTDigest(...) OVER (ORDER BY k RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) over numbers(1000000): it reads no table and no FINAL, so LazyReadReplacingFinalSource, the only source file this PR changes, never runs. The same query was also flagged slower on 2 unrelated PRs since 2026-09-28, so this is the per-binary code-placement shift on amd, not a regression of this diff a fix task is created (its fix direction awaits a maintainer decision; fixing-PR link to follow on this PR)
Mergeable Check, PR rollups, red only because of the row above a fix task is created (the same owner as the row above)
CH Inc sync - CH Inc sync (private, not actionable by me)

146 of 146 check runs completed (110 passed, 35 not selected, 1 red: the shard above) and Finish Workflow is green. The "2 too long" in that shard's summary does not gate in master_head mode. CIDB has no FAIL or ERROR test row on this head.

Session id: cron:our-pr-ci-monitor:20261002-003227

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the amd_release 6/6 perf red (window_transform #5): #124676. The red is keyed to the master base: on the same base d9bcb5ab00, #119462 was 23.7% slower on this query too, against 7 moves above 10% in 1871 amd runs of it since 2026-09-15.

@nickitat nickitat self-assigned this Oct 8, 2026
@nickitat

nickitat commented Oct 8, 2026

Copy link
Copy Markdown
Member

@groeneai, add a perf test. none of the existing shows speed ups.

The deduplicating aggregation of lazy FINAL runs in order with
optimize_aggregation_in_order = 1. The test reads 20000 filtered keys from
two intersecting parts. Against the CI amd_release binaries under perf.py
with the perf-comparison configs, master takes 0.45 s (70527 merges of
partially aggregated blocks), the fix 0.02 s (2 merges).

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

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

Added tests/performance/lazy_final_aggregation_in_order.xml in 32d9471. The existing lazy FINAL tests run with optimize_aggregation_in_order = 0, so none of them reached the in-order path.

Locally under perf.py with the perf-comparison configs, on the CI amd_release binaries: master 0.45 s per run (70527 merges of partially aggregated blocks), this PR 0.02 s (2 merges).

With a randomized read_in_order_two_level_merge_threshold below the
fixture's 2 parts, the in-order read can merge both parts into a single
stream. The deduplicating aggregation is then single-stream, finalizes in
place and never calls Aggregator::mergeBlocks, so the test saw 0 merge
lines and failed its lower bound (once in Stateless tests (amd_tsan, s3
storage, targeted)), with and without the fix.

Clamp the setting to at least 2 with a Random settings limits line. With
the clamp: 500/500 randomized runs pass on the fixed build, the unfixed
build still fails 20/20 (10191..25000 merges). With the line disabled,
3/300 runs fail with the same "batched merges: 0" diff.

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

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0081b59

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 (arm_tidy, 2/4) / Build ClickHouse master build break, not from this PR: src/Common/Scheduler/Nodes/tests/gtest_throttler_constraint.cpp:25: error: use of undeclared identifier 'FifoQueue'. That test line came with #113697 (merged 2026-10-08 23:18Z), and #116800 had already removed FifoQueue from master. This PR does not touch src/Common/Scheduler #124798 (external, open)
Mergeable Check, PR rollups, red only because of the row above #124798 (external, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

The build failure dropped the 87 jobs that depend on it, so this head has no functional test results yet. The 8 jobs that ran passed: Fast test, Style check, the other three arm_tidy shards, Code Review, Config Workflow and Finish Workflow. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261009-033007

groeneai and others added 2 commits October 23, 2026 12:04
…-aggregation-in-order-batched-merges

# Conflicts:
#	src/Processors/Sources/LazyReadReplacingFinalSource.cpp
…-aggregation-in-order-batched-merges

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nickitat
nickitat enabled auto-merge November 3, 2026 16:58
@nickitat
nickitat added this pull request to the merge queue Nov 5, 2026
Merged via the queue into ClickHouse:master with commit 7ccfda5 Nov 6, 2026
352 of 353 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
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 6, 2026
…the performance tests

The setup of the test asserts two active parts with
`throwIf(count() != 2) FROM system.parts`. The Iceberg configuration
rewrites its ReplacingMergeTree table to IcebergLocal/IcebergS3, which
has no rows in `system.parts`, so the setup fails with Code 395
("expected 2 active parts") and so does the whole Iceberg perf shard.

The test came with ClickHouse#123326, whose last CI run (2026-10-26) predates
ClickHouse#128261, which started running the Iceberg jobs on the tests a PR adds,
so it never ran in this configuration before it reached master.

The reason is the one of lazy_final_early_exit_limit.xml,
lazy_materialization_final_limit.xml and read_in_reverse_order_final.xml,
which have the same check over `system.parts` plus FINAL.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

Lazy FINAL with optimize_aggregation_in_order merges one group at a time (25000 mergeBlocks calls and 50000 log lines for a 35000-row table)

4 participants