Repository navigation
Do not create unused aggregate states in aggregation in order with a partial GROUP BY key - #114010
Conversation
…partial GROUP BY key AggregatingInOrderTransform has two output modes. When the sorting prefix covers the whole GROUP BY key, every state created by createStatesAndFillKeyColumnsWithSingleKey (stored in variants.without_key) is handed to a ColumnAggregateFunction by addSingleKeyToAggregateColumns, which also clears the pointer, so nothing is orphaned. In the partial key mode (group_by_key == true, i.e. table ORDER BY parent_key with GROUP BY parent_key, child_key) the aggregated result is produced from the hash table by prepareChunkAndFillSingleLevel, which never reads without_key, and every addSingleKeyToAggregateColumns call site is guarded by if (!group_by_key). The state stored in without_key is therefore write-only: the next call overwrites the pointer and orphans the previous state, and the following variants.invalidate() sets the type to EMPTY, which makes destroyAllAggregateStates return early. The arena bytes are freed but the state's own allocations are not, so any aggregate function whose state owns heap memory leaks once per group. For quantileDD, whose state owns three unique_ptr members, LeakSanitizer reported 11840 bytes in 222 allocations for 74 orphaned states. The producer was left unconditional when the mode and all of its !group_by_key guards were introduced in 3931dbd, so the guard pair has been asymmetric since then. It went unnoticed because an arena-only state leaks nothing observable, which is why the existing test of this plan shape stays green while aggregating count(). Complete the guard pair by splitting the key-column fill into fillKeyColumnsWithSingleKey and calling it from the two partial-key sites, so no aggregate state is created where none will be consumed. The !group_by_key path is unchanged. Widening invalidate() or destroyAllAggregateStates instead would double free the states that path has already handed to ColumnAggregateFunction. overflow_row cannot be set in this mode: optimizeReadInOrder skips aggregation in order entirely when it is set, so the key-only path needs no overflow row state. Closes: ClickHouse#114000
AggregatingInOrderTransform::getName() returns the same string in both of its output modes, so an EXPLAIN PIPELINE guard matching that name cannot tell the partial GROUP BY key mode (the only one that leaked) from the full key mode. The test could therefore keep passing while no longer covering the bug: with force_aggregation_in_order the planner sets the merging sort description to the full key list, the transform is still built, and the old guard stays green. Assert the sorting prefix instead, which is what selects the mode: EXPLAIN actions = 1 prints it as an Order: line, and partial key mode is exactly the case where that list is shorter than the GROUP BY key. A table whose ORDER BY covers the whole GROUP BY key makes the new guard print two columns instead of one, so it is able to fail, which the name based guard was not. Also fix the verb in the new doc comment: addSingleKeyToAggregateColumns transfers ownership of the state to a ColumnAggregateFunction, which is what later destroys it.
Internal second-model review (2 rounds, all findings adjudicated)An independent model reviewed this change cold against the frozen description, in two Round 1 (both AGREED and fixed)
The negative control matters here, and the first one I prescribed did not work: with 💡 Ownership comment was wrong in one word. The new doc comment said Round 2 (one blocker, DISAGREED with evidence)❌ Claim: the full-key path can still leak its first state if setup throws after the
Recorded as noted-not-blocking rather than fixed here. My own review, one nit, also disagreed💡 Two plan steps can emit an Verified independently while reviewingThat leaving Gate spend across both rounds: $41.34. |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-40:20260809-002400 |
|
cc @nickitat @davenger, could you review this? In partial-GROUP-BY-key mode the in-order aggregation transform created a |
|
Workflow [PR], commit [4de7aa9] Summary: ✅
AI ReviewSummaryThis PR fixes the reported partial- Findings❌ Blockers
Final VerdictStatus: Minimum required action: make the first full-key state setup exception-safe so the touched helper cannot still leak aggregate states before ownership is established. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 16/16 (100.00%) · Uncovered code |
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. Compile time of recompiled translation units70 translation units recompiled, 594 s compile time in total, 70 of them have a recent master baseline. |
The test asserts the aggregation sorting prefix via `EXPLAIN actions = 1` to distinguish partial-GROUP-BY-key mode (short prefix) from full-key mode. Two plan steps print an `Order:` line: `AggregatingStep` and, under parallel replicas, the coordinator's `MergingAggregatedStep`, which prints the full GROUP BY key. `applyParallelReplicas` runs before `optimizeAggregationInOrder` (optimizeTree.cpp:379 vs :413), so with parallel replicas enabled the assertion returned two lines instead of one and the test failed 3/3 reruns in `Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel)`. The value rows were unaffected; only the plan-shape guard was. Pin the one setting the assertion depends on rather than tagging the test: the two in-tree tests asserting this same `Order:` line for this same shape (02481_aggregation_in_order_plan and 03273_group_by_in_order_still_used_when_ group_by_key_doesnt_match_order_by_key) are both listed in parallel_replicas_blacklist.txt, so the exclusion is precedented; a query-level pin keeps the test running in that job instead of being skipped there. Verified with a positive control: without the pin the test reproduces the CI diff (3 runs, 2 FAIL, `+Order: parent_key ASC, child_key ASC`); with it, 50/50 pass under full randomization with the same forced settings. The negative control still works: on a table with ORDER BY (parent_key, child_key) the guard prints two columns, so it can still redden. The LeakSanitizer A/B is unchanged (base 1600 B / 30 allocations with the exact CI frames, fixed clean, outputs byte-identical).
|
Pushed
Value rows were byte-identical, so only the guard broke. Two steps print Pinned the one setting the assertion depends on rather than tagging the test. Verification: without the pin the failure reproduces (2 of 3 runs FAIL, same diff; needs
The other three reds are not from this diff: |
The test asserted only the plan shape and the query results, and the leak is invisible to both. Per-arch Bugfix Validation therefore reported "Bug does not reproduce on this arch" on amd64 and aarch64, and the `new_tests_check.py` post-hook failed the workflow: a regression test that cannot fail on master HEAD does not validate the fix. LeakSanitizer's at-exit check aborts `clickhouse local` with exit code 134 on any ASan build when an aggregate state is leaked. Run the queries through `clickhouse local` and fail the test on that, which turns the leak into an ordinary functional signal instead of one only a stress job can see. The plan-shape and result assertions are unchanged, so the reference file is untouched; on a non-ASan build only those are checked. Converted from .sql to .sh because it needs the exit code of a separate process. Verified with clickhouse-test: FAIL on pristine master (1600 bytes leaked in 30 allocations), OK on this branch, 20/20 under randomization.
In partial-key mode the new key is only recorded in res_key_columns; only full-key mode also creates its state. Comment only.
|
Fixed the Bugfix Validation failure. The per-arch jobs reported The test now runs its queries through Verified with
|
CI finish ledger - 4de7aa9Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CI is fully finished on this head with zero failing checks. For contrast, the previous heads on this branch were not clean: Session id: cron:our-pr-ci-monitor:20260810-063000 |
02d5fdc
ReproducerCREATE TABLE t (p Int64, c Int8, v Float64) ENGINE = MergeTree ORDER BY p;
INSERT INTO t SELECT number, number % 3, number FROM numbers(200000);
SELECT value FROM system.metrics WHERE metric = 'MemoryTracking';
SELECT p, c, quantileDD(0.01, 0.5)(v) FROM t GROUP BY p, c FORMAT Null
SETTINGS optimize_aggregation_in_order = 1, max_threads = 1;
SELECT value FROM system.metrics WHERE metric = 'MemoryTracking';
-- 26.7.3.19: MemoryTracking is ~35 MB higher after the query and stays there
-- (one orphaned aggregate state per sorting-prefix key change: 200000 keys).
-- Each further run of the same query adds another ~35 MB.
-- master with #114010: +80 KB.Results:
Backport the fix to CC component owner: @alexey-milovidov @nickitat Analysis metadata
Introducing change: not identified
|
|
Confirmed the backport claim independently, and there is one wrinkle in the test worth flagging before the backport PRs are created. Reproduction. I ran your reproducer against the stock per-branch builds from builds.clickhouse.com. Steady-state retention per run of the query:
Two negative controls on master, 26.7 and 25.8 stay flat (at most 0.1 MB against 33 MB), so the accumulation is specific to the path #114010 fixes rather than generic retention: Label. #114010 is merged but carries only The source cherry-picks cleanly on all five branches, each landing the same five files with a source delta identical to master's, so no prerequisite is missing. The test will be red on 26.6 and older, though. It runs |
Do not create unused aggregate states in aggregation in order with a partial GROUP BY key
Closes: #114000
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes a memory leak with
optimize_aggregation_in_order = 1when the table sorting key is a strict prefix of theGROUP BYkey and an aggregate function whose state owns heap memory is used, such asquantileDD. Server memory grows with every such query until restart.Description
AggregatingInOrderTransformhas two output modes. When the sorting prefix covers the wholeGROUP BYkey, each state created bycreateStatesAndFillKeyColumnsWithSingleKey(stored invariants.without_key) is handed to aColumnAggregateFunctionbyaddSingleKeyToAggregateColumns, which also clears the pointer.In the partial key mode (
group_by_key == true, e.g. tableORDER BY parent_keywithGROUP BY parent_key, child_key) the result comes from the hash table viaprepareChunkAndFillSingleLevel, which never readswithout_key, and bothaddSingleKeyToAggregateColumnscall sites are guarded byif (!group_by_key). So that state is write-only: the next call overwrites the pointer and orphans the previous state, and the followingvariants.invalidate()sets the type toEMPTY, makingdestroyAllAggregateStatesreturn early. Arena bytes are freed; the state's owned allocations are not.The producer was left unconditional when the mode and all its
!group_by_keyguards were added in3931dbd848786e8(2022-03-06), so the guard pair has been asymmetric since then. It is invisible for arena-only states, which is why the in-tree test of this plan shape is green withcount().This completes the guard pair: the key-column fill is split into
fillKeyColumnsWithSingleKey, used by the two partial-key call sites, so no state is created where none is consumed. The!group_by_keypath is unchanged.overflow_rowcannot be set in this mode, so the key-only path needs no overflow-row state.The test runs its queries through
clickhouse local, whose at-exit LeakSanitizer check aborts on a leaked state, so the leak is an ordinary test failure on any ASan build instead of something only a stress job sees. It also pins the plan shape and the results; on a non-ASan build only those are checked. Verified withclickhouse-test: FAIL on pristine master (1600 bytes leaked in 30 allocations), OK here, 20/20 randomized.Version info
26.8.1.1276(included in26.8and later)