Skip to content

Replace Block to Chunk in Aggregator - #99228

Merged
KochetovNicolai merged 10 commits into
masterfrom
use-positions-in-aggregator
Mar 17, 2026
Merged

KochetovNicolai merged 10 commits into
masterfrom
use-positions-in-aggregator

Conversation

@KochetovNicolai

@KochetovNicolai KochetovNicolai commented Mar 10, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.3.1.750

@CLAassistant

CLAassistant commented Mar 10, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

KochetovNicolai and others added 4 commits March 10, 2026 20:24
Replace name-based column resolution in `Aggregator` with precomputed
positional data, removing the stored `Block header` member:

- Remove `Aggregator::executeOnBlock(const Block &, ...)` overload
- Remove `Aggregator::getHeader` — callers now use `Params::getHeader` directly
- Precompute `keys_positions`, `aggregates_positions`, `key_types`, and
  `aggregate_state_types` in the constructor from the input header
- Update `prepareOutputBlockColumns` and `finalizeBlock` to accept types
  directly instead of a `Block` header
- Remove unused `rows` parameter from `finalizeBlock`
- Move `header` storage to `AggregatingTransformParams` where it is still
  needed for output schema construction

Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Change `mergeOnBlock` to accept `Columns`, `size_t rows`, `bool is_overflows`
  instead of `Block`, eliminating Block construction at call sites
- Change `mergeStreamsImpl` and `mergeBlockWithoutKeyStreamsImpl` similarly
- Move `makeRawKeyColumns` and `makeAggregateColumnsData` from `Params`
  methods to static functions in Aggregator.cpp, using positional column
  access instead of name-based lookups

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Introduce `Aggregator::AggregatedChunk` struct holding a `Chunk` with
`bucket_num` and `is_overflows` metadata, avoiding `Block` and `BlockInfo`
in the aggregation output path.

- Add `AggregatedChunk` and `AggregatedChunks` types to Aggregator
- Replace `convertToBlocks` with `convertToChunks` returning `AggregatedChunks`
- Update callers in `TTLAggregationAlgorithm` and `MergingAggregatedTransform`
  to work with chunks, reconstructing `Block` only when needed for expression
  execution

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Replace `finalizeBlock` with `finalizeChunk` returning `Chunk` instead of
`Block`. Eliminate `ConvertToBlockResVariant` by using `Chunks` (vector)
as the uniform return type for `convertToBlockImpl`, `convertToBlockImplFinal`,
and `convertToBlockImplNotFinal`. Replace `BlocksList` with `AggregatedChunks`
in merge interfaces. Rename `prepareBlockAndFill*` methods to
`prepareChunkAndFill*`. Update `recordAggregationKeySizes` to accept `Chunk`
with positional key access. Replace `group_by_block` with `group_by_chunk`
in `AggregatingInOrderTransform`.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@KochetovNicolai
KochetovNicolai force-pushed the use-positions-in-aggregator branch from 29c0cc1 to 7899dab Compare March 10, 2026 20:24
@clickhouse-gh

clickhouse-gh Bot commented Mar 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1b2e8bb]

Summary: ✅


AI Review

Summary

This PR refactors aggregation internals to pass Chunk/column vectors instead of Block through multiple aggregation and merge paths, including Aggregator, AggregatingTransform, MergingAggregatedTransform, and memory-efficient merging transforms. After reviewing the full diff and current PR head, I did not find additional high-confidence blockers/majors beyond already-discussed threads.

Missing context

  • ⚠️ CI result_pr.json currently reports no executed test entries, so this review could not corroborate behavior via failing/passing test artifacts.

ClickHouse Rules

Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsHistory.cpp ➖
Safe rollout ✅
Compilation time ✅

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 Mar 10, 2026
…tion order

Two bugs introduced during Block-to-Chunk refactoring:

1. In the merge path (`only_merge`), `calculateKeysPositions` and
   `calculateAggregatesPositions` looked up argument names that don't
   exist in the merge header (which uses `column_name` instead).
   Fixed by returning empty when `only_merge` is set, and using
   `column_name` in `calculateAggregateStateTypes` for the merge path.

2. `Chunk::detachColumns` zeroes `num_rows` as a side effect, so
   `Chunk(cur_chunk.detachColumns(), cur_chunk.getNumRows())` passes
   0 rows when `detachColumns` is evaluated first. Fixed by saving
   `num_rows` before detaching.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Comment thread src/Interpreters/Aggregator.cpp Outdated
{
/// Only used in the execute path; in the merge path keys are accessed positionally.
if (params.only_merge)
return {};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

calculateKeysPositions returning an empty vector in only_merge mode breaks runtime statistics collection: recordAggregationKeySizes now relies on aggregator.getKeysPositions() to index key columns, so merge-path chunks report zero key bytes. This regresses RuntimeDataflowStatistics quality for merge pipelines. Please keep key positions available (e.g. 0..keys_size-1 in only_merge) or derive positional indices at the call site when recording key sizes.

KochetovNicolai and others added 2 commits March 12, 2026 11:35
…columns

The merge path in `AggregatingTransform` was missing sparse column
conversion after the Block-to-Chunk refactoring. On master,
`materializeBlock` handled this; now `materializeChunk` is the
Chunk analog — it converts const columns to full and removes
sparse/replicated representations.

Fixes exception "Column Sparse(UInt8) is not a contiguous block of
memory" in `mergeStreamsImpl`.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Instead of returning an empty vector in `only_merge` mode, return
sequential positions 0..keys_size-1. This keeps `getKeysPositions`
usable for `recordAggregationKeySizes` in merge pipelines, preserving
RuntimeDataflowStatistics quality.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Comment thread src/Interpreters/AggregationUtils.cpp Resolved
…hunk

After the Block-to-Chunk refactoring, `mergeBlocks` can return an
empty `AggregatedChunk` (no columns). On master, `sortBlock` on an
empty `Block` was a no-op, but the new code calls
`header.cloneWithColumns(detachColumns())` which fails when the
chunk has 0 columns but the header expects 3.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@KochetovNicolai
KochetovNicolai marked this pull request as ready for review March 13, 2026 16:17
@nickitat nickitat self-assigned this Mar 13, 2026
for (auto & chunk : chunks)
blocks.emplace_back(header.cloneWithColumns(chunk.detachColumns()));
agg_chunks.emplace_back(Aggregator::AggregatedChunk{std::move(chunk)});

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.

Suggested change
agg_chunks.emplace_back(Aggregator::AggregatedChunk{std::move(chunk)});
agg_chunks.emplace_back(std::move(chunk));

it shouldn't be required, right?

auto info = std::make_shared<AggregatedChunkInfo>();
info->bucket_num = block.info.bucket_num;
info->is_overflows = block.info.is_overflows;
info->out_of_order_buckets = block.info.out_of_order_buckets;

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.

Did we lose out_of_order_buckets?

Block block = header.cloneWithColumns(cur_chunk.detachColumns());
block.info.is_overflows = agg_info->is_overflows;
block.info.bucket_num = agg_info->bucket_num;
block.info.out_of_order_buckets = agg_info->out_of_order_buckets;

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.

out_of_order_buckets disappeared again

KochetovNicolai and others added 2 commits March 16, 2026 17:18
C++20 parenthesized aggregate initialization allows `emplace_back`
to construct `AggregatedChunk` directly from forwarded arguments,
making the explicit type wrapper unnecessary.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…sume`

Replace `addBlock(Block)` with `addChunk(Columns, size_t, Int32, bool)` to
avoid constructing a `Block` from the incoming `Chunk` only to extract columns
back later. The `Block` is now constructed inside `addChunk` only when needed
for `ExpressionActions::execute` (grouping sets path).

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.80% 83.80% +0.00%
Functions 23.90% 23.90% +0.00%
Branches 76.30% 76.30% +0.00%

PR changed lines: PR changed-lines coverage: 95.16% (786/826, 4 noise lines excluded)
Diff coverage report
Uncovered code

@KochetovNicolai
KochetovNicolai added this pull request to the merge queue Mar 17, 2026
Merged via the queue into master with commit f64466c Mar 17, 2026
159 checks passed
@KochetovNicolai
KochetovNicolai deleted the use-positions-in-aggregator branch March 17, 2026 12:18
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 17, 2026
zlareb1 added a commit to zlareb1/ClickHouse that referenced this pull request Mar 17, 2026
…ation (PR ClickHouse#99228)

PR ClickHouse#99228 replaces `Block` with `Chunk` throughout the aggregation pipeline
(17 files). Two correctness paths had no test coverage:

1. `04046`: ROLLUP and CUBE with external aggregation (`max_bytes_before_external_group_by = 1`)
   – exercises `writeToTemporaryFileImpl` and `GroupByModifierTransform::merge()`.
   Verifies results match for ROLLUP/CUBE with and without `group_by_use_nulls`.

2. `04047`: GROUPING SETS with external aggregation + `group_by_two_level_threshold = 1`
   – exercises `MergingAggregatedTransform::addChunk`, `mergeBlocks(BucketToChunks)`,
   and `convertBlockToTwoLevel`. Includes a single-set path to cover the reordering branch.

Both tests pass, confirming the refactoring preserves correctness on these paths.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
github-merge-queue Bot pushed a commit that referenced this pull request Mar 19, 2026
…-grouping-sets

Add coverage tests for ROLLUP/CUBE/GROUPING SETS with external aggregation (PR #99228)
yurifedoseev added a commit to yurifedoseev/ClickHouse that referenced this pull request Apr 10, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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