Skip to content

Remove the prefetch batch from the single-level partition merge - #131315

Open
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:single-level-partition-merge-no-prefetch
Open

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:single-level-partition-merge-no-prefetch

Conversation

@groeneai

@groeneai groeneai commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #129565

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Removed the destination prefetch batch from the parallel merge of single-level GROUP BY states, which did not pay off in any measured case.

Description

28d8e94e660e7 (in #110395) made the non-indexed path of Aggregator::mergeSingleLevelPartitionsImpl collect up to 16 cells of the partition and prefetch their destination slots before merging them. That path runs in the parallel merge of single-level GROUP BY states when the adaptive aggregator does not index the tables, for example with a single Nullable numeric key, a LowCardinality key, or enable_adaptive_aggregator = 0. This PR goes back to the plain per-cell loop, the one the indexed and the string-table branches of the same function already use.

@ diegomestre2 asked whether the prefetch pays (#129565 (comment)). I measured it on x86 (#129565 (comment)): it paid off in none of 31 cases (7 key types, 4-64 threads, destinations of 0.03-256 MiB). With a warm allocator the plain loop takes 0.78-0.93 of master's merge time in 15 cases and is slower in none. With jemalloc purged before each run, as the performance tests do, the two loops measure equal: query time 0.99-1.03 of master in the UInt64 and Nullable(UInt64) cases with 3 million keys at 16 and 32 threads, on two servers with the binaries swapped between them (ratio = PR / master). So this PR claims no speed-up the performance tests could show and adds no performance test; the performance CI runs the existing tests that reach this loop. aarch64 was not measured locally.

Results do not change: merge_cell sees the same cells in the same order, the checksums of all 864 measured runs are equal, and the partition-merge stateless tests pass on debug and release builds.

#129180 edits the merge_cell call inside the removed batch; whichever PR lands second resolves one line.

🤖 Generated with Claude Code


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

The non-indexed path of `mergeSingleLevelPartitionsImpl` collected up to 16 cells of the
partition and prefetched their destination slots before merging them. Measured on x86 over
31 cases (7 key types, 4-64 threads, destinations of 0.03-256 MiB), the prefetch paid off in
none. With a warm allocator the plain per-cell loop is 7-22% faster in merge time in 15 cases
and slower in none; with jemalloc purged before each run, as the performance tests do, the
two loops measure equal.
Results: ClickHouse#129565 (comment)

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

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 review of the diff (5 nits, all on the PR text; fixed in the description before publication, none in the code).

# Sev Finding Verdict Evidence / action
1 💡 Description wording on what is and is not claimed about performance AGREE, fixed the description now says no speed-up is claimed that the performance tests could show
2 💡 "a single Nullable key" also covers Nullable(String), which uses the string-table branch without the batch AGREE, fixed now "a single Nullable numeric key"
3 💡 The purged A/B cases were labeled by a superlative that does not hold for every metric AGREE, fixed the cases are named (UInt64 / Nullable(UInt64), 3 million keys, 16 and 32 threads)
4 💡 Measurements are x86 only AGREE, noted stated in the description; the performance CI covers aarch64
5 💡 Changelog entry said the prefetch "never" paid off, which overstates a 31-case measurement AGREE, fixed now "which did not pay off in any measured case"

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

Session id: cron:clickhouse-review-slot-9:20261113-132700

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? N/A for a failure (behaviour-preserving deletion). The measurement is a fixed procedure: 31 reach-gated cases, four servers in a Latin square, median of 5 runs, 4-8 rounds; plus an A/B with jemalloc purged before each run and the binaries swapped across two servers.
b Root cause explained? The prefetch did not pay in any measured case: destinations of 0.03-0.5 MiB at default thresholds, 4 MiB, and 32-256 MiB with two-level disabled. The 16-cell buffer and second pass cost on their own (gating the prefetch on L2 size recovered only part). Why the warm-allocator gain disappears under the purge was not measured and is not claimed.
c Fix matches root cause? Yes: removes the code that does not pay and restores the plain per-cell loop that the indexed and string-table branches of the same function already use.
d Test intent preserved / new tests added? No test changes. No performance test, because the performance CI purges jemalloc before each run and with the purge the two loops measure equal. Existing coverage of the path: 04506, 04507, 04695, 05059, 05257, 05497, 05498, 05565 (single Nullable numeric key, LowCardinality key, enable_adaptive_aggregator = 0).
e Both directions demonstrated? Master vs this change on every measured case: warm allocator, merge time 0.78-0.93 of master in 15 of 31 cases, slower in none; purged, query time 0.99-1.03 of master. The 8 partition-merge tests x3 with random settings pass on both debug and release builds of this change (48/48).
f Fix is general across code paths? The other aggregator prefetches (build phase, serial merge, bucket merge) are already gated on the destination exceeding L2 via minBytesForPrefetch and are untouched; this was the only ungated one. params.enable_prefetch stays in use.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured over 7 key types (UInt64, Nullable(UInt64), UInt32, two UInt64 keys, a short String, (String, UInt64), LowCardinality(String)), 4-64 threads, count() and sum().
h Backward compatible? (maintainer-approved exception only) Yes: no setting, default, format or serialized state changes.
i Invariants and contracts preserved? merge_cell receives the same cells in the same order (the batch kept source order), so destination contents and deferred merges are identical: checksums equal in 864/864 runs. On an exception, a cell not yet visited keeps its state in the source table, as a collected-but-unmerged cell did. The per-source cancellation check and the try/catch are unchanged.

Session id: cron:clickhouse-impl-slot-6:20261113-131600

@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [79a2b1d]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR replaces the destination-prefetch batch in the non-indexed single-level GROUP BY merge with a per-cell loop. The earlier source-state leak is fixed in the current head by the merged #131595. One separate, pre-existing destination-state ownership gap remains in result conversion and needs cleanup or an explicit tracking issue.

Findings

❌ Blockers

  • src/Interpreters/Aggregator.cpp:4686, reached from the changed merge at line 4020: convertToBlockImplFinal queues aggregate pointers and nulls their table slots before all keys have been materialized. If inserting a later key throws, execution bypasses insertResultsIntoColumns, and neither the pointer array nor the table destroys the detached states. This leaks heap buffers owned by aggregates such as quantileExact and uniqExact after a failed query. Preserve ownership until the batch call, add cleanup for this exception window, or link a tracking issue. This is separate from the source-state cleanup fixed in Destroy the queued aggregate states when the merge of GROUP BY tables throws #131595.
Tests
  • ⚠️ The conversion finding is established by tracing ownership in the current code, not by a runtime reproduction. Local probes using the PR-head CI binary either failed during aggregation or completed successfully; they did not reach the suspected exception window. The smallest focused validation is an allocation failure during key materialization after one heap-owning state has been queued, checked with LeakSanitizer. The four existing partition-merge tests passed in the PR-head fast test report, but do not inject this failure.
Final Verdict

❌ Block. Close the destination-state ownership gap or link an issue explicitly tracking this pre-existing defect.

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog can be tested Allows running workflows for external contributors comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). labels Nov 13, 2026
Comment thread src/Interpreters/Aggregator.cpp Resolved
@nihalzp nihalzp self-assigned this Nov 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 79a2b1d67 with master d011c6b84 (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.

Object file sizes

4 object files changed (-18.33 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 29.36 MiB 29.35 MiB -18.31 KiB (-0.06%)

711 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

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

Job report

nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Nov 16, 2026
… throws

The map `mergeDataImpl` (serial single-level merge, two-level bucket merge,
parallel fixed hash map merge) and the non-indexed loop of
`mergeSingleLevelPartitionsImpl` take the state of a key found in both tables
out of the source table (`src = nullptr`) and queue it in a local
`PaddedPODArray` for `mergeAndDestroyDetachedBatch`. Until that call nothing
owns the queued states: a throw in between, e.g. `MEMORY_LIMIT_EXCEEDED` from
the destination `HashTable::resize`, leaked their heap buffers, since the
catches destroyed only the deferred pairs. ClickHouse#117153 made the window after the
batch starts exception-safe; this closes the collection window before it.

Extract the cleanup loop of `mergeAndDestroyDetachedBatch` into
`destroyDetachedSources` and call it from a catch around the collection of
`mergeDataImpl` (the JIT merge and the batch call stay outside the try, the
batch owns the states from there) and from the existing catch of the
partition merge. `flush_merges` clears its arrays in a `SCOPE_EXIT`, because
the batch takes the states also when it throws, so a state is never destroyed
twice. Deferred pairs come only from batches that started and the queued
states only from batches that did not, so the two cleanups are disjoint.

The new ONCE failpoint `aggregator_merge_collect_states_throw` throws at the
end of a collection while states are queued. The test runs it on six paths in
`clickhouse local`, whose LeakSanitizer check at exit aborts on a leak.

`IAggregateFunctionHelper::mergeAndDestroyBatch` and the `-Tuple` combinator
also destroy the rest of their batch when a merge throws, as
`mergeAndDestroyBatchOrDefer` does; the second ONCE failpoint
`aggregator_merge_batch_throw` tests a throw inside the batch in both merges.

Related: ClickHouse#131315 (comment)

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

nihalzp commented Nov 16, 2026

Copy link
Copy Markdown
Member

@groeneai Merge master.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master in 79a2b1d; CI is re-running.

Comment thread src/Interpreters/Aggregator.cpp Resolved

This branch has not been deployed

No deployments
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-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants