Skip to content

Squash source blocks before projection calculate to reduce temp parts - #100047

Merged
CurtizJ merged 5 commits into
ClickHouse:masterfrom
amosbird:pre-calculate-squash
Jun 3, 2026
Merged

CurtizJ merged 5 commits into
ClickHouse:masterfrom
amosbird:pre-calculate-squash

Conversation

@amosbird

@amosbird amosbird commented Mar 19, 2026 •

Copy link
Copy Markdown
Collaborator

During projection MATERIALIZE (in both mutation and merge paths), every 8192-row block independently calls projection.calculate(), each producing a separate temporary MergeTree part. For a 50M-row single part, this creates ~6100 temp parts, requiring multiple levels of tree merge with hundreds of merge rounds.

This adds a pre-calculate squashing step using the existing Squashing class to accumulate source blocks up to min_insert_block_size_rows (~1M rows) before calling projection.calculate(). This reduces temp parts from ~6100 to ~50, cutting the tree merge from 4 levels / ~610 rounds to 1 level / ~5 rounds.

Local benchmark on 50M rows with an aggregating projection (ALTER TABLE ... CLEAR PROJECTION ..., MATERIALIZE PROJECTION ...):

  • Before: ~5.5s
  • After: ~1.6s (~3.4x speedup)

Changelog category (leave one):

  • Performance Improvement

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

Squash source blocks before projection.calculate() during MATERIALIZE PROJECTION to reduce the number of temporary projection parts and merge overhead. ~3.4x speedup on a 50M-row table.

Documentation entry for user-facing changes

  • Documentation is not required for this change.

Version info

  • Merged into: 26.6.1.340

@clickhouse-gh

clickhouse-gh Bot commented Mar 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [25be18c]

Summary: ✅


AI Review

Summary

This PR batches source blocks before projection.calculate in merge and mutation projection materialization paths, then keeps the existing post-calculate temp-part batching. The current code also addresses the earlier metric accounting, cancellation, and wide-block memory concerns. I did not find any remaining correctness, safety, or performance issue that warrants an inline review comment.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Mar 19, 2026
@amosbird
amosbird force-pushed the pre-calculate-squash branch from 1803f6f to 38bd70d Compare March 19, 2026 14:03
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Apr 2, 2026
During projection MATERIALIZE operations, every small block (~8192 rows)
independently calls projection.calculate(), producing a separate temporary
MergeTree part. This adds a pre-calculate squashing step to accumulate
source blocks up to min_insert_block_size_rows before calling calculate().
Reduces temp parts from ~6100 to ~50 for a 50M-row table, ~3.4x speedup.

Ref: ClickHouse#100047
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Apr 2, 2026
During projection MATERIALIZE operations, every small block (~8192 rows)
independently calls projection.calculate(), producing a separate temporary
MergeTree part. This adds a pre-calculate squashing step to accumulate
source blocks up to min_insert_block_size_rows before calling calculate().
Reduces temp parts from ~6100 to ~50 for a 50M-row table, ~3.4x speedup.

Ref: ClickHouse#100047
@amosbird
amosbird force-pushed the pre-calculate-squash branch 2 times, most recently from bb1b628 to f20c9d2 Compare April 28, 2026 06:12
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Apr 28, 2026
During projection MATERIALIZE operations, every small block (~8192 rows)
independently calls projection.calculate(), producing a separate temporary
MergeTree part. This adds a pre-calculate squashing step to accumulate
source blocks up to min_insert_block_size_rows before calling calculate().
Reduces temp parts from ~6100 to ~50 for a 50M-row table, ~3.4x speedup.

Ref: ClickHouse#100047
amosbird added a commit to amosbird/ClickHouse that referenced this pull request Apr 29, 2026
During projection MATERIALIZE operations, every small block (~8192 rows)
independently calls projection.calculate(), producing a separate temporary
MergeTree part. This adds a pre-calculate squashing step to accumulate
source blocks up to min_insert_block_size_rows before calling calculate().
Reduces temp parts from ~6100 to ~50 for a 50M-row table, ~3.4x speedup.

Ref: ClickHouse#100047
amosbird added a commit to amosbird/ClickHouse that referenced this pull request May 5, 2026
During projection MATERIALIZE operations, every small block (~8192 rows)
independently calls projection.calculate(), producing a separate temporary
MergeTree part. This adds a pre-calculate squashing step to accumulate
source blocks up to min_insert_block_size_rows before calling calculate().
Reduces temp parts from ~6100 to ~50 for a 50M-row table, ~3.4x speedup.

Ref: ClickHouse#100047
amosbird added a commit to amosbird/ClickHouse that referenced this pull request May 9, 2026
During projection MATERIALIZE operations, every small block (~8192 rows)
independently calls projection.calculate(), producing a separate temporary
MergeTree part. This adds a pre-calculate squashing step to accumulate
source blocks up to min_insert_block_size_rows before calling calculate().
Reduces temp parts from ~6100 to ~50 for a 50M-row table, ~3.4x speedup.

Ref: ClickHouse#100047
amosbird added a commit to amosbird/ClickHouse that referenced this pull request May 10, 2026
During projection MATERIALIZE operations, every small block (~8192 rows)
independently calls projection.calculate(), producing a separate temporary
MergeTree part. This adds a pre-calculate squashing step to accumulate
source blocks up to min_insert_block_size_rows before calling calculate().
Reduces temp parts from ~6100 to ~50 for a 50M-row table, ~3.4x speedup.

Ref: ClickHouse#100047
amosbird added a commit to amosbird/ClickHouse that referenced this pull request May 13, 2026
During projection MATERIALIZE operations, every small block (~8192 rows)
independently calls projection.calculate(), producing a separate temporary
MergeTree part. This adds a pre-calculate squashing step to accumulate
source blocks up to min_insert_block_size_rows before calling calculate().
Reduces temp parts from ~6100 to ~50 for a 50M-row table, ~3.4x speedup.

Ref: ClickHouse#100047
amosbird added a commit to amosbird/ClickHouse that referenced this pull request May 14, 2026
During projection MATERIALIZE operations, every small block (~8192 rows)
independently calls projection.calculate(), producing a separate temporary
MergeTree part. This adds a pre-calculate squashing step to accumulate
source blocks up to min_insert_block_size_rows before calling calculate().
Reduces temp parts from ~6100 to ~50 for a 50M-row table, ~3.4x speedup.

Ref: ClickHouse#100047
amosbird added a commit to amosbird/ClickHouse that referenced this pull request May 17, 2026
During projection MATERIALIZE operations, every small block (~8192 rows)
independently calls projection.calculate(), producing a separate temporary
MergeTree part. This adds a pre-calculate squashing step to accumulate
source blocks up to min_insert_block_size_rows before calling calculate().
Reduces temp parts from ~6100 to ~50 for a 50M-row table, ~3.4x speedup.

Ref: ClickHouse#100047
amosbird added a commit to amosbird/ClickHouse that referenced this pull request May 20, 2026
During projection MATERIALIZE operations, every small block (~8192 rows)
independently calls projection.calculate(), producing a separate temporary
MergeTree part. This adds a pre-calculate squashing step to accumulate
source blocks up to min_insert_block_size_rows before calling calculate().
Reduces temp parts from ~6100 to ~50 for a 50M-row table, ~3.4x speedup.

Ref: ClickHouse#100047
@amosbird
amosbird force-pushed the pre-calculate-squash branch from 9294dad to cfa25f0 Compare May 21, 2026 15:54
@CurtizJ CurtizJ self-assigned this May 21, 2026
During projection MATERIALIZE (mutation/merge), every small block from the
pipeline independently calls projection.calculate(), each creating a separate
temp MergeTree part. For a 28M-row part with index_granularity=8192, this
produces ~3500 temp parts requiring 4 levels of tree merge with ~390 rounds.

Add a pre-calculate squashing step that accumulates source blocks up to
min_insert_block_size_rows before calling calculate(). This reduces temp parts
from ~3500 to ~30, cutting merge overhead from 4 levels / 390 rounds to
1 level / 3 rounds. The optimization applies to both MergeTask and MutateTask.
@amosbird
amosbird force-pushed the pre-calculate-squash branch from 9833cd2 to 125f50f Compare May 28, 2026 03:12
Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
All projections consume the same source blocks, so there is no reason
to maintain independent Squashing accumulators for each one. Replace
the per-projection std::vector<Squashing> with a single shared
std::optional<Squashing>. This also changes calculateProjectionForBlock
to take const Block & instead of Block by value, avoiding unnecessary
copies when the same big block is passed to multiple projections.
@amosbird
amosbird force-pushed the pre-calculate-squash branch from 125f50f to bd50f45 Compare May 28, 2026 06:47
…tion only

Move `writeTempProjectionPart` out of the `MutateTaskProjectionsCalculationMicroseconds`
scope so the metric does not include temp part write/finalize/storage commit
work, matching the pre-refactor behavior.

@CurtizJ CurtizJ 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.

LGTM

Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
Two bot review findings on PRs/100047 b31b4f0..13df0ac:

1. Memory: `pre_squash` previously retained full source `Block` until
   `min_insert_block_size_*` was reached. For a wide source with a projection
   that only reads a few columns (e.g. the key), every merge/mutation task
   accumulated whole batches of unrelated columns. Push only the union of
   `projection.required_columns` (plus `_row_exists` when present) into the
   squash buffer.

2. Cancellation: `MergeTask::ExecuteAndFinalizeHorizontalPart::finalizeProjections`
   is also called from the cancellation branch in `executeImpl`. The deferred
   pre-calculate flush could start a fresh `projection.calculate` and temp
   projection part write for a large accumulated batch that
   `checkOperationIsNotCanceled` later throws away. Skip the flush when
   `merge_list_element_ptr->is_cancelled` is latched.

In the mutation path, `finalizeTempProjectionsAndIndexes` is reached only via
the normal end-of-stream branch (`checkOperationIsNotCanceled` throws on
cancel), so no skip is needed there.
@clickhouse-gh

clickhouse-gh Bot commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 92.40% 92.30% -0.10%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 124/130 (95.38%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 2 line(s) · Uncovered code

Full report · Diff report

@CurtizJ
CurtizJ added this pull request to the merge queue Jun 3, 2026
Merged via the queue into ClickHouse:master with commit 88939cf Jun 3, 2026
166 of 167 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 3, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @amosbird @CurtizJ — while reviewing this PR I found the following:

Could you review the test PR and add the can be tested label if it looks good?
Happy to discuss — close anything that's wrong or already addressed.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 19, 2026
DatabaseCatalog::addUUIDMapping(uuid, db, table) threw a LOGICAL_ERROR when
the UUID was already mapped to a live table. During ATTACH DATABASE (and
server startup) tables are loaded via attachTable, which calls addUUIDMapping
directly with a real (database, table) pair and bypasses the empty "lock"
reservation. If two table metadata files in the loaded database declare the
same explicit UUID, the second table reaches that throw and the LOGICAL_ERROR
aborts the whole server in debug/sanitizer builds.

Two table .sql files sharing one UUID is user-controlled, external on-disk
state: it can be produced by manual edits, or by a leftover _tmp_replace_*
table from CREATE OR REPLACE TABLE ... UUID '...' that carries the same
explicit UUID as the live target table. That is a user error, not an internal
invariant violation, and the sibling branch already reports the same condition
as a non-fatal TABLE_ALREADY_EXISTS ("UUID collision, most likely because some
not random UUIDs were manually specified"). The runtime ATTACH TABLE path even
hits that friendly error today; only the load path aborts.

Report the collision as TABLE_ALREADY_EXISTS instead of LOGICAL_ERROR. The
conflicting table fails to load with a clear message, the rest of the database
attaches, and the server stays up. This covers both the ATTACH DATABASE async
load path and the server startup path.

Found by BuzzHouse (amd_tsan) on PR ClickHouse#105020 (STID 3178-4166); the family also
hit PRs ClickHouse#100047, ClickHouse#106268, ClickHouse#100703 (STID 3178-4504). New test
04340_attach_database_duplicate_uuid_no_crash reproduces the crash
deterministically and verifies the server survives.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
shankar-iyer pushed a commit to shankar-iyer/ClickHouse that referenced this pull request Jul 11, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

4 participants