Repository navigation
Destroy the queued aggregate states when the merge of GROUP BY tables throws - #131595
Conversation
… 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]>
Internal second-model review (2 rounds, head fe5cd48): 3 ❌ and 1
|
| Finding | Verdict | |
|---|---|---|
| ❌ | A throw inside a function's batch merge leaked the rest of that batch (plain mergeAndDestroyBatch, no catch) |
AGREE, fixed |
| ❌ | -Tuple combinator: nested functions after the one that threw were not destroyed |
AGREE, fixed |
| ❌ | No test of a throw inside the merge (double destroy unguarded) | AGREE, failpoint + 2 variants |
Test fixture: max_threads_min_free_memory_per_thread can drop the query to one thread, so no merge |
AGREE, pinned to 0 | |
| 💡 | Category should be Bug Fix |
DISAGREE: a leak after a failed query is not a wrong result, data loss or crash |
| 💡 | The catches inside mergeAndDestroyBatch and -Tuple have no CI test |
Noted: checked with max_memory_usage (master leaks 10 to 40 MiB, the fix is clean in 23 runs); a failpoint would sit in the per-row merge loop |
Not changed here (different code): convertToBlockImplFinal has a similar window for destination states.
Session id: cron:clickhouse-review-slot-8:20261114-111700
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-40:20261114-094300 |
|
Workflow [PR], commit [69cf579] Summary: ✅
AI ReviewSummaryThe PR frees detached aggregate states when collecting or merging per-thread Missing context / blind spots
Final Verdict✅ Approve. No new inline findings. |
|
@groeneai A few things:
|
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. The official master build is compiled with Object file sizes144 object files changed (+1.81 MiB total), 0 added.
711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units395 translation units recompiled, 3089 s compile time in total, 395 of them have a recent master baseline. |
…the batch `destroyDetachedSources` and the catches of `IAggregateFunctionHelper::mergeAndDestroyBatch` and of the `-Tuple` combinator destroy their states with `destroyBatch`. `aggregator_merge_batch_throw` now throws inside `IAggregateFunctionHelper::mergeAndDestroyBatch` before the merge of its second row (`IAggregateFunction::injectMergeBatchFault`, out of the header), so the catches of the function and of `-Tuple` run in the test, which gains a `quantileExactTuple` case. Before, it threw after the batch of a function had returned. The NULL key case has NULL keys and pins the non-adaptive partition merge, because the adaptive aggregator merges by cell index and never queues states. The test routes the sanitizer report of each `clickhouse local` to its own log and counts the leak reports, so one reference fits every build, and runs the cases in two processes. Comments: `mergeAndDestroyDetachedBatch` owns the batch from its call on. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks, all six are in 69cf579:
|
Resolve the five conflicts of the 26.8 cherry-pick of ClickHouse#131595. They are all regions where master has code that 26.8 does not have: the deferral of large merges (ClickHouse#117153: mergeAndDestroyBatchOrDefer, DeferredMerges, mergeAndDestroyDetachedBatch and its catch), isSelfMerge (ClickHouse#130678), the bound of zero-sized nested states (ClickHouse#130120), and the partition-by-partition merge of the adaptive aggregator (ClickHouse#129565). None of them is labelled for 26.8, and the resolution takes none of them. 26.8 has no catch around the per-function loop of the batch merge (master got it in ClickHouse#117153), so a throw in the merge of one function would still leak the queued states of every function after it. The resolution adds a 26.8 mergeAndDestroyDetachedBatch, the master function without the deferral: the per-function loop, and a catch that destroys the states of the following functions. The map mergeDataImpl (also the JIT path) and the flush of mergeSingleLevelPartitionImpl call it. The collection loop of mergeSingleLevelPartitionImpl is wrapped in the try of ClickHouse#131595, so it is re-indented. In IAggregateFunctionHelper::mergeAndDestroyBatch the 26.8 assertion is kept (no isSelfMerge). AggregateFunctionTuple.cpp and the test merge cleanly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve the five conflicts of the 26.9 cherry-pick of #131595. They are all regions where master has code that 26.9 does not have: the deferral of large merges (#117153: mergeAndDestroyBatchOrDefer, DeferredMerges, mergeAndDestroyDetachedBatch and its catch), isSelfMerge (#130678), the bound of zero-sized nested states (#130120), and the partition-by-partition merge of the adaptive aggregator (#129565). None of them is labelled for 26.9, and the resolution takes none of them. 26.9 has no catch around the per-function loop of the batch merge (master got it in #117153), so a throw in the merge of one function would still leak the queued states of every function after it. The resolution adds a 26.9 mergeAndDestroyDetachedBatch, the master function without the deferral: the per-function loop, and a catch that destroys the states of the following functions. The map mergeDataImpl (also the JIT path) and the flush of mergeSingleLevelPartitionImpl call it. The collection loop of mergeSingleLevelPartitionImpl is wrapped in the try of #131595, so it is re-indented. In IAggregateFunctionHelper::mergeAndDestroyBatch the 26.9 assertion is kept (no isSelfMerge). AggregateFunctionTuple.cpp and the test merge cleanly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve the five conflicts of the 26.10 cherry-pick of #131595. They are all regions where master has code that 26.10 does not have: the deferral of large merges (#117153: mergeAndDestroyBatchOrDefer, DeferredMerges, mergeAndDestroyDetachedBatch and its catch), isSelfMerge (#130678), the bound of zero-sized nested states (#130120), and the partition-by-partition merge of the adaptive aggregator (#129565). None of them is labelled for 26.10, and the resolution takes none of them. 26.10 has no catch around the per-function loop of the batch merge (master got it in #117153), so a throw in the merge of one function would still leak the queued states of every function after it. The resolution adds a 26.10 mergeAndDestroyDetachedBatch, the master function without the deferral: the per-function loop, and a catch that destroys the states of the following functions. The map mergeDataImpl (also the JIT path) and the flush of mergeSingleLevelPartitionImpl call it. The collection loop of mergeSingleLevelPartitionImpl is wrapped in the try of #131595, so it is re-indented. In IAggregateFunctionHelper::mergeAndDestroyBatch the 26.10 assertion is kept (no isSelfMerge). AggregateFunctionTuple.cpp and the test merge cleanly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Cherry pick #131595 to 26.8: Destroy the queued aggregate states when the merge of GROUP BY tables throws
…e merge of GROUP BY tables throws
Cherry pick #131595 to 26.9: Destroy the queued aggregate states when the merge of GROUP BY tables throws
…e merge of GROUP BY tables throws
Cherry pick #131595 to 26.10: Destroy the queued aggregate states when the merge of GROUP BY tables throws
…he merge of GROUP BY tables throws
Backport #131595 to 26.9: Destroy the queued aggregate states when the merge of GROUP BY tables throws
Backport #131595 to 26.10: Destroy the queued aggregate states when the merge of GROUP BY tables throws
Backport #131595 to 26.8: Destroy the queued aggregate states when the merge of GROUP BY tables throws
Related: #131315
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a memory leak when the merge of the per-thread hash tables of
GROUP BYfailed with an exception, for example onmax_memory_usage: the states of aggregate functions such asuniqExactorquantileExactthat waited to be merged were never freed.Description
The merges of the per-thread hash tables of
GROUP BY(Aggregator::mergeDataImpl: serial, two-level bucket, fixed hash map;mergeSingleLevelPartitionsImpl: parallel hash partitions) take the state of a key found in two tables out of the source table and queue it for a batch merge (mergeAndDestroyDetachedBatch). Two throws leaked such states:MEMORY_LIMIT_EXCEEDEDfromHashTable::resizeof the destination, nobody owned the queued states;IAggregateFunctionHelper::mergeAndDestroyBatchand the-Tuplecombinator did not destroy the rest of their batch when a merge threw.On 26.8.37.168,
SELECT k, quantileExact(number) FROM (SELECT number, toUInt64(number % 4) * 1000003 AS k FROM numbers_mt(16000000)) GROUP BY kwithmax_memory_usage = 200000000,max_threads = 4and the serial single-level merge throws inmergeAndDestroyBatch; 20 such failures growMemoryTrackingof oneclickhouse localto 399.8 MiB, while 20 failures in the build phase stay at 93.5 MiB.The fix destroys the queued states in a
catcharound the collection (destroyDetachedSources);mergeAndDestroyDetachedBatchowns the batch from its call on, so thatcatchnever sees it.mergeAndDestroyBatchand-Tupledestroy the rest of their batch withdestroyBatch.Validation: the test
05638_aggregator_merge_exception_destroys_queued_statesthrows from twoONCEfailpoints, after a duplicate state is queued (six cases) and insidemergeAndDestroyBatchafter its first row (both merges andquantileExactTuple), and counts the LeakSanitizer reports. On ASan it fails without eithercatchof the batch (leak) or with the batch cleared after its call (double free).Not changed here: the conversion of the merged table (
convertToBlockImplFinal) can leak destination states the same way undermax_memory_usage.Raised in the review of #131315: #131315 (comment)
🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/131595]
Version info
26.11.1.2406-master(included in26.11and later)26.10.5.49,26.9.31.14,26.8.39.13