Skip to content

Use detachColumns instead of getColumns in Aggregator merge path - #102330

Merged
alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
yurifedoseev:fix/detach_columns
Jun 11, 2026
Merged

alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
yurifedoseev:fix/detach_columns

Conversation

@yurifedoseev

@yurifedoseev yurifedoseev commented Apr 10, 2026 •

Copy link
Copy Markdown
Contributor

The issue was found during bisecting for another issue with an agent and needs to be confirmed.

PR #99228 replaced Block with Chunk in the aggregation merge path but used getColumns (shared copy) instead of detachColumns (move). This keeps aggregate states alive across all buckets during parallel merge instead of freeing them incrementally, increasing memory pressure and concurrent arena operations.

Restore immediate ownership transfer to match the old std::move(block) semantics.

Measured effect: about 18–30% lower peak memory on the gathered (non-memory-efficient) two-level merge path through Aggregator::mergeBlocks, depending on the size of the per-bucket aggregate states. See the discussion below for the workloads and system.query_log measurements.

Changelog category (leave one):

  • Performance Improvement

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

Reduced peak memory usage when merging partial two-level aggregation results with large aggregate states (e.g. groupArray), by freeing each bucket's source states incrementally during the merge instead of keeping them all alive until the merge completes.


Note

Medium Risk
Touches the aggregation merge hot path and changes column ownership semantics (getColumns -> detachColumns), which could impact memory lifetime expectations or expose hidden reuse assumptions under concurrency.

Overview
Restores move-style ownership transfer of Chunk columns during aggregation merges by replacing Chunk::getColumns() with Chunk::detachColumns() in Aggregator::mergeBlocks (two-level buckets, single-level/unknown bucket, and the chunks-based merge).

This allows aggregate state columns to be released incrementally during parallel bucket merges instead of remaining shared/alive across buckets, reducing memory pressure and concurrent arena contention.

Reviewed by Cursor Bugbot for commit a75f1db. Bugbot is set up for automated code reviews on this repo. Configure here.

Version info

  • Merged into: 26.6.1.618 (included in 26.6 and later)
  • Backported to: 26.4.5.100

PR ClickHouse#99228 replaced `Block` with `Chunk` in the aggregation merge path
but used `getColumns` (shared copy) instead of `detachColumns` (move).
This keeps aggregate states alive across all buckets during parallel
merge instead of freeing them incrementally, increasing memory pressure
and concurrent arena operations.

Restore immediate ownership transfer to match the old `std::move(block)`
semantics.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Apr 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8f7f834]

Summary: ✅


AI Review

Summary

This PR replaces Chunk::getColumns with Chunk::detachColumns in the three Aggregator::mergeBlocks merge loops, restoring move-style ownership for source aggregate-state columns so each input chunk can release its states after it is merged. I traced the changed loops, their callers, Chunk::detachColumns, and the merge helpers; the source chunks are not reused after detaching, and the updated Performance Improvement changelog entry now matches the measured peak-memory claim from the PR discussion.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Apr 10, 2026
@CLAassistant

CLAassistant commented Apr 10, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@yurifedoseev
yurifedoseev marked this pull request as ready for review April 10, 2026 04:52

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a great finding! But could you please provide some examples of the effect of this change?

@alexey-milovidov alexey-milovidov self-assigned this Apr 10, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

To clarify my own question above — the effect is on peak memory and arena pressure during the parallel two-level merge.

Mechanism

Chunk::getColumns returns shared copies of the column IColumn::Ptrs — the Chunk keeps owning them. After the body of for (auto & agg_chunk : bucket_to_chunks[bucket]) runs mergeStreamsImpl(chunk_columns, ...), the chunk_columns local goes out of scope, but each ColumnAggregateFunction still has refcount ≥ 1 from agg_chunk.chunk. The aggregate states held by those columns are only freed when the whole bucket's chunk vector is destructed.

Chunk::detachColumns moves the columns out and leaves the chunk empty, so when chunk_columns goes out of scope at the end of the loop body, refcount drops to 0 and the states are freed immediately. Peak live state goes from O(chunks_per_bucket) down to O(1).

This restores the std::move(block) semantics that existed before #99228 replaced Block with Chunk in the aggregator merge path.

Reproducer

-- forces two-level (5M keys) with ~1 KiB state per key
SELECT k, length(groupArray(s)) AS n
FROM
(
    SELECT (number % 5000000) AS k, repeat('x', 100) AS s
    FROM numbers(50000000)
)
GROUP BY k
FORMAT Null
SETTINGS max_threads = 8, group_by_two_level_threshold = 1;

The peak memory_usage from system.query_log for this query with and without the patch shows the difference. The effect scales with groupArray width, number of chunks per bucket, and max_threads.

@yurifedoseev

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov thank you for the explanation!
I'll reproduce and compare the two versions in query_log

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit fa41fae. Configure here.

Comment thread .github/workflows/auto_releases.yml Resolved
Comment thread .github/workflows/create_release.yml Resolved
Workflow files in this branch were stale or had been deleted as a
workaround for GitHub's workflow-scope check. Restoring them to match
`master` so the PR diff no longer contains those unrelated changes.
@alexey-milovidov

Copy link
Copy Markdown
Member

Here is a concrete example of the effect. I built two binaries from current master, identical except for this 3-line change, and measured peak memory on the non-memory-efficient gathered merge — the MergingAggregatedTransform path that calls Aggregator::mergeBlocks, fed with large groupArray states from 8 partial two-level aggregations:

SELECT k, groupArray(v) AS a, groupArray(s) AS b
FROM remote('127.0.0.{1,2,3,4,5,6,7,8}:PORT', view(
    SELECT (cityHash64(number) % 400000) AS k, number AS v, toString(number) AS s
    FROM numbers_mt(8000000)
))
GROUP BY k
FORMAT Null
SETTINGS distributed_aggregation_memory_efficient = 0,
         max_threads = 8,
         group_by_two_level_threshold = 1,
         group_by_two_level_threshold_bytes = 1;

Peak memory_usage of the initiator query from system.query_log (median of 3 runs):

Build Peak memory
master (getColumns) 7.99 GiB
master + this PR (detachColumns) 5.63 GiB

That is about 30% lower peak memory (~2.4 GiB saved) for this query.

The reason: with getColumns() every bucket's source aggregate-state columns stay alive in bucket_to_chunks until the whole mergeBlocks call returns; with detachColumns() each bucket's source states are released as soon as mergeStreamsImpl has consumed them, so they are freed incrementally during the merge. The effect grows with the size of the per-bucket aggregate states.

@alexey-milovidov

Copy link
Copy Markdown
Member

I measured the effect of this change. I built two binaries from the current master, differing only in these three lines (getColumns() → detachColumns()), and ran an identical workload on each.

Workload — a two-level distributed aggregation whose final merge goes through MergingAggregatedTransform (Aggregator::mergeBlocks over BucketToChunks), with heavy groupArray(String) states so the partial-aggregate columns dominate memory:

SELECT k, groupArray(s) AS ga
FROM remote('127.0.0.{1,2,3,4}', view(
    SELECT number % 200000 AS k, repeat(toString(number), 3) AS s
    FROM numbers_mt(8000000)))
GROUP BY k
FORMAT Null
SETTINGS group_by_two_level_threshold = 1, group_by_two_level_threshold_bytes = 1,
         distributed_aggregation_memory_efficient = 0, max_threads = 8;

memory_usage of the initial query from system.query_log, 4 runs each:

variant peak memory_usage avg
getColumns (before) 4.33 GiB (4 646 386 745) 4.33 GiB
detachColumns (after) 3.56 GiB (3 820 692 013) 3.48 GiB

That is about 18% lower peak memory (~787 MiB) on the merging side, and the getColumns runs were perfectly stable at 4.33 GiB.

Why: with getColumns() the Chunk keeps its own references to the source columns, so every bucket's ColumnAggregateFunction (and the arena holding its states) stays alive until the whole bucket_to_chunks is destroyed at the end of the merge. With detachColumns() the columns are moved out, so each bucket's source states are released as soon as that bucket is merged — restoring the incremental freeing that the old std::move(block) path had before #99228.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 5, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged current master into the branch (it was ~942 commits behind, no conflicts — the change still touches only the three getColumns() → detachColumns() lines in Aggregator::mergeBlocks) and enabled CI by adding the can be tested label.

I re-checked the three call sites after the merge:

  • The two-level merge loop (merge_bucket) and the single-level unknown-bucket loop — the chunk is not used again after detachColumns() in the loop body, so moving the columns out is safe.
  • The third overload — the later references to agg_chunk.chunk (lines ~3824/3837) are to a new local AggregatedChunk agg_chunk declared after the loop that shadows the loop variable, i.e. the merge result, not the detached source chunks. Safe as well.

Pushed as f7b7192b55b.

@clickhouse-gh

clickhouse-gh Bot commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 3 query(s) improved out of 39 analysed

This PR replaces column copies with detaches in the aggregate block-merge code, avoiding copy-on-write copies during the merge step. The three flagged ClickBench improvements (Q4 -17.5%, Q15 -16.8%, Q28 -5.8%) are all aggregation queries that run exactly that path, so the gains are directly attributable to the change rather than noise. Q4 and Q15 are large, clean deltas confirmed by both tests; Q28 is smaller but consistent. No regressions were observed.

clickbench

🟢 3 improved

Flagged queries (3 of 43)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
🟢 4 improvement 268 221 -17.5% <0.0001 aggregation: Q4 (AVG) runs the block-merge path the diff touches; detachColumns avoids copy-on-write copies. -17.5% is plausible.
🟢 15 improvement 250 208 -16.8% <0.0001 aggregation: GROUP BY merge path now detaches columns instead of copying; -16.8% lines up with the change, both tests agree.
🟢 28 improvement 7068 6658 -5.8% <0.0001 aggregation: Heavy aggregation query; -5.8% is smaller but consistent and clean (low variance), matching the merge-path speedup.

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: 007743a5-37a8-4230-927f-4873d8613ba4
  • MIRAI run: 46a4d922-08d5-4c52-b445-4eda908310ad
  • PR check IDs:
    • clickbench_667078_1780868735
    • clickbench_667092_1780868735
    • clickbench_667098_1780868735
    • tpch_adapted_1_official_667104_1780868735
    • tpch_adapted_1_official_667106_1780868735
    • tpch_adapted_1_official_667114_1780868735

…rg::alter

PR ClickHouse#106102 (merged 2026-06-05 17:43 UTC) refactored Iceberg::alter to
declare last_version and compression_method outside an if/else that
assigns them in both branches. Clang-tidy cppcoreguidelines-init-variables
flags the bare declarations and Build (arm_tidy) is built with
-warnings-as-errors, so the build fails for every PR whose CI ran on
master after this commit.

CIDB shows 30+ unrelated PRs hitting this in the last 2 days
(e.g. ClickHouse#89360, ClickHouse#103540, ClickHouse#106120, ClickHouse#106386, ClickHouse#106404, ClickHouse#106522, ClickHouse#105102,
ClickHouse#106590).

Initialize both variables to safe defaults at declaration. They are
unconditionally overwritten in both if and else branches before use,
so behavior is unchanged. The new defaults are only relevant if a
future code path skips both assignments, in which case last_version=0
and compression_method=CompressionMethod::None are sane no-op values
(the same defaults the old structured-binding form would produce
through default-construction of the destructured aggregate).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
(cherry picked from commit d72cac5)
Comment thread src/Interpreters/Aggregator.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged current `master` (branch was 309 commits behind). The Iceberg `Mutations.cpp` init-vars fix is now identical to `master`, so the net diff is back to exactly the three `getColumns()` → `detachColumns()` lines in `Aggregator::mergeBlocks`. CI was green.

Addressed the remaining review thread: changed the changelog category from Not for changelog to Performance Improvement and added a changelog entry, since this is the measured peak-memory improvement documented above.

Pushed as `8f7f834c7d3`.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Jun 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.50% 84.50% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.20% 77.20% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 14/16 (87.50%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 11, 2026
Merged via the queue into ClickHouse:master with commit b6f2946 Jun 11, 2026
166 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 Jun 11, 2026
@KochetovNicolai KochetovNicolai added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Jul 3, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 3, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 3, 2026
fm4v added a commit that referenced this pull request Jul 3, 2026
Backport #102330 to 26.4: Use detachColumns instead of getColumns in Aggregator merge path
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 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 pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

8 participants