Skip to content

Do not create unused aggregate states in aggregation in order with a partial GROUP BY key - #114010

Merged
nickitat merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-aggregation-in-order-partial-key-state-leak
Aug 12, 2026
Merged

nickitat merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-aggregation-in-order-partial-key-state-leak

Conversation

@groeneai

@groeneai groeneai commented Aug 9, 2026 •

Copy link
Copy Markdown
Collaborator

Do not create unused aggregate states in aggregation in order with a partial GROUP BY key

Closes: #114000

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixes a memory leak with optimize_aggregation_in_order = 1 when the table sorting key is a strict prefix of the GROUP BY key and an aggregate function whose state owns heap memory is used, such as quantileDD. Server memory grows with every such query until restart.

Description

AggregatingInOrderTransform has two output modes. When the sorting prefix covers the whole GROUP BY key, each state created by createStatesAndFillKeyColumnsWithSingleKey (stored in variants.without_key) is handed to a ColumnAggregateFunction by addSingleKeyToAggregateColumns, which also clears the pointer.

In the partial key mode (group_by_key == true, e.g. table ORDER BY parent_key with GROUP BY parent_key, child_key) the result comes from the hash table via prepareChunkAndFillSingleLevel, which never reads without_key, and both addSingleKeyToAggregateColumns call sites are guarded by if (!group_by_key). So that state is write-only: the next call overwrites the pointer and orphans the previous state, and the following variants.invalidate() sets the type to EMPTY, making destroyAllAggregateStates return 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_key guards were added in 3931dbd848786e8 (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 with count().

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_key path is unchanged. overflow_row cannot 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 with clickhouse-test: FAIL on pristine master (1600 bytes leaked in 30 allocations), OK here, 20/20 randomized.

Version info

  • Merged into: 26.8.1.1276 (included in 26.8 and later)

…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.
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, all findings adjudicated)

An independent model reviewed this change cold against the frozen description, in two
rounds. Round 1 raised one major test-liveness finding plus one nit, both of which I
agreed with and which were fixed in 018b081. Round 2 raised one blocker, which I
disagree with; my refutation is below, with the counter-example that settles it.

Round 1 (both AGREED and fixed)

⚠️ The plan guard could not tell the two modes apart. The original test asserted
EXPLAIN PIPELINE ... ILIKE '%AggregatingInOrderTransform%', but getName()
(AggregatingInOrderTransform.h:52) returns that literal unconditionally while the
leaking mode is the size comparison at .cpp:63. So the guard would have stayed green if
planning ever stopped selecting the partial-key mode, silently removing the regression
coverage. It now asserts the sorting prefix itself with EXPLAIN actions = 1 filtered on
%Order:%, which prints Order: parent_key ASC (one column) against the two-column
GROUP BY -- exactly the condition that selects the mode. This finding corrected my own
review, which had credited the original guard.

The negative control matters here, and the first one I prescribed did not work: with
force_aggregation_in_order = 1 the Order: line still printed one column, because
AggregatingStep::applyOrder overwrites sort_description_for_merging with the real
prefix. That probe was vacuous, not the fix. The working control is a table whose
ORDER BY covers the whole GROUP BY key: the new guard then prints two columns while
the old guard still returns 1. The guard is shown able to redden rather than asserted to be.

💡 Ownership comment was wrong in one word. The new doc comment said
addSingleKeyToAggregateColumns "destroys" the state; it transfers ownership and nulls
without_key (Aggregator.cpp:2782-2809), with destruction in
ColumnAggregateFunction::~ColumnAggregateFunction. Reworded, since that comment exists
precisely to stop a future reader reintroducing this bug.

Round 2 (one blocker, DISAGREED with evidence)

❌ Claim: the full-key path can still leak its first state if setup throws after the
state is created.
Every code citation in this finding is accurate, and the window it
describes is real. It is not, however, a defect of this change, and its suggested remedy
would introduce undefined behaviour.

  1. The ordering is unchanged where the window exists. Normalizing the helper before
    this change against the helper after it, with the extracted fillKeyColumnsWithSingleKey
    inlined back at its call site, gives byte-identical text. The !group_by_key arm of both
    call sites passes the same arguments as before.
  2. The window is eliminated where this change does apply: in partial-key mode no state
    is created at all. So the change strictly narrows the very window the finding describes.
  3. It is not observed. Over 90 days, CIDB has exactly two rows whose context contains
    createStatesAndFillKeyColumnsWithSingleKey. One is the leak this PR fixes. The other is
    the finding's own scenario actually happening: 00164_quantileBfloat16 on an unrelated PR,
    Code: 241 ... (total) memory limit exceeded ... While executing AggregatingInOrderTransform
    -- a throw on that exact path with a heap-owning quantile state. That run reports no
    LeakSanitizer, no SUMMARY, and no Direct leak. The scenario occurred and leaked nothing.
  4. The literal remedy is unsafe. Marking the variant owned before constructing the state
    would make createAggregateStates's own rollback (which destroys slots 0..j-1,
    Aggregator.cpp:836-856) compose with destroyWithoutKey, which destroys all
    params.aggregates_size slots unconditionally (:4322-4334): a double destroy of
    0..j-1 plus destroy() on never-constructed slots. That is a real regression traded
    for a hypothetical one.

Recorded as noted-not-blocking rather than fixed here.

My own review, one nit, also disagreed

💡 Two plan steps can emit an Order: line (AggregatingStep.cpp:786 and
MergingAggregatedStep.cpp:180), and under a genuine parallel-replicas plan the aggregating
step is replaced by a merging step, so in principle the test's single-row assertion could see
two rows. I did not act on it: the only jobs running that configuration are the two
amd_llvm_coverage, ParallelReplicas param sets, which are unconditionally non-blocking
(ci/jobs/functional_tests.py:1365-1368), and the same job activates
parallel_replicas_blacklist.txt in a mode where a failure becomes SKIPPED and a pass
becomes NOT_FAILED (tests/clickhouse-test:3930-3935). Adding a blanket
no-parallel-replicas tag to pre-empt an unobserved, non-blocking, self-neutralising result
would go against pinning only what demonstrably causes trouble.

Verified independently while reviewing

That leaving without_key as nullptr in partial-key mode is behaviour-neutral, from
source rather than from the author's notes: sizeWithoutOverflowRow() does not count it
(AggregatedDataVariants.cpp:96-111), so row counts are unchanged; mergeOnBlockSmall
creates its own state under its own condition and passes the pointer as
mergeStreamsImpl's overflow_row, dereferenced only under no_more_keys, which is
hardcoded false there; destroyWithoutKey null-checks. And that overflow_row and
partial-key mode are mutually exclusive on both analyzers -- the length asymmetry arises
only through AggregatingStep::applyOrder, whose sole caller returns early on
overflow_row (optimizeReadInOrder.cpp:1730), while every other producer assigns the two
sort descriptions equal values.

Gate spend across both rounds: $41.34.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% (not "~1%"). ASAN build, ASAN_SYMBOLIZER_PATH=/usr/bin/llvm-symbolizer-21 ASAN_OPTIONS=detect_leaks=1:symbolize=1 clickhouse local --queries-file leak.sql -- --max_server_memory_usage=32G, where leak.sql creates MergeTree ORDER BY parent_key and runs SELECT parent_key, child_key, quantileDD(0.01, 0.5)(value) ... GROUP BY parent_key, child_key SETTINGS max_threads = 1, optimize_aggregation_in_order = 1. Reproduces the reported stack frame for frame: DDSketch.h:30 -> createAggregateStates<false> (Aggregator.cpp:842) -> createStatesAndFillKeyColumnsWithSingleKey (:2830) -> AggregatingInOrderTransform::consume (:224).
b Root cause explained? Yes. With group_by_key == true (sorting prefix shorter than the GROUP BY key) the state that createStatesAndFillKeyColumnsWithSingleKey stores in variants.without_key is write-only: output comes from the hash table via prepareChunkAndFillSingleLevel, which never reads without_key, and every addSingleKeyToAggregateColumns call site (the only thing that transfers ownership and nulls the pointer) is guarded by if (!group_by_key). Each next call overwrites the pointer, orphaning the previous state; variants.invalidate() then sets the type to EMPTY, so destroyAllAggregateStates returns at if (result.empty()) return; and even the last state is never destroyed. generate() replaces the arena, freeing raw bytes while the state's unique_ptr members are never deleted. Asymmetric since 3931dbd848786e8 (2022-03-06), which made the consumer conditional but left the producer unconditional.
c Fix matches root cause? Yes. It stops creating a state that has no consumer, at the cause. Not a band-aid: no widened bound, no no-random-* tag, no data-size reduction, and no destructor bolted onto invalidate() to compensate for the orphaning. Arithmetic cross-check on the reported numbers: 26 states via :128 + 48 via :224 = 74 orphaned states x 3 heap members = 222 allocations, x 160 bytes = 11840 bytes, matching the LSan summary exactly, so no second mechanism is hidden behind this one.
d Test intent preserved / new tests added? Yes. No existing test weakened or removed. New 04834_aggregation_in_order_partial_key_state_leak.sql covers the shape, and because a correctness oracle cannot observe a leak it also asserts the plan shape. An earlier draft guarded on the processor name (EXPLAIN PIPELINE ... ILIKE '%AggregatingInOrderTransform%'); review showed that cannot distinguish the two modes, since getName() returns that literal unconditionally (AggregatingInOrderTransform.h:52) while the leaking mode is the size comparison at .cpp:63. The shipped guard asserts the sorting prefix instead, via EXPLAIN actions = 1 filtered on %Order:%, printing Order: parent_key ASC (one column) against the two-column GROUP BY -- exactly the condition that selects the mode. It is shown able to redden rather than asserted to be: against a table whose ORDER BY covers the whole GROUP BY key the new guard prints two columns, where the old guard still returned 1.
e Both directions demonstrated? Yes, same SQL and options, only the binary differs. Pre-fix (Build ID fac5885cbcaf23840f036bf0782c57cce17e133b): rc=134, 1600 byte(s) leaked in 30 allocation(s) with the DDSketch / createStatesAndFillKeyColumnsWithSingleKey frames. Post-fix (Build ID 6ed03184beeeeb3de1147c4ab622b2f4f7621e34): rc=0, no report. Results byte-identical. A harder shape (37x11 keys, WITH TOTALS, max_threads=8, LIMIT, max_block_size=2) leaks 18080 byte(s) / 339 allocations before and is clean after, 1639 rows identical.
f Fix is general across code paths? Yes, enumerated by grep rather than inference. createStatesAndFillKeyColumnsWithSingleKey has exactly two callers repo-wide, both fixed; addSingleKeyToAggregateColumns has exactly two, both already guarded and unchanged. Both AggregatingInOrderTransform construction sites reach the same consume(). AggregatingTransform uses neither helper. The other two invalidate() callers are safe: NegativeLimitByTransform.cpp:100 has no aggregate functions at all, and TTLAggregationAlgorithm.cpp:322 is preceded by convertToChunks(final=true). The only_merge branch (mergeOnBlockSmall) was exercised explicitly.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Matrix with Nullable(Int) and LowCardinality(String) keys, Array(Int) values, state-returning quantileDDState, the -ForEach / -Map / -If combinators, uniqExact, groupUniqArray, the only_merge two-level merge path, and the empty-table and single-row boundaries: leaks 2880 byte(s) / 54 allocations before, clean after, 69 rows identical. The fix is per-plan-shape rather than per-function, so every state with a non-trivial destructor is covered at once; the defect is in state-lifetime bookkeeping and is independent of key type.
h Backward compatible? (maintainer-approved exception only) Yes, nothing to be compatible with: no setting, no default change, no serialization or on-disk format, no protocol, no public API. No SettingsChangesHistory.cpp entry is required.
i Invariants and contracts preserved? Yes. The load-bearing invariant is that res_key_columns must still be filled in group_by_key mode, because less() compares the current key against it to find key boundaries; the fix keeps the key fill and removes only the state creation, which is why results are byte-identical everywhere. without_key now stays nullptr in that mode, so invalidate() keeps its narrow meaning and the !group_by_key hand-off path is untouched (widening destruction instead would have double-freed states already owned by ColumnAggregateFunction). I verified the "unread" half rather than assuming it: a temporary assertion at both group_by_key output sites never fired with the fix, and did fire (abort) with the fix reverted, so the check was live and not vacuous. The :211 limit-hint and :251 finalizeCurrentChunk branches become leak-free for the same reason, and the exception rollback in createAggregateStates is unchanged.

Session id: cron:clickhouse-impl-slot-40:20260809-002400

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @nickitat @davenger, could you review this? In partial-GROUP-BY-key mode the in-order aggregation transform created a without_key aggregate state unconditionally, while the only consumer that takes ownership of it is guarded by if (!group_by_key), so each new key overwrote and orphaned the previous state and states with heap-owning members such as quantileDD leaked. The fix stops creating the state on that path rather than adding a destructor.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4de7aa9]

Summary: ✅


AI Review

Summary

This PR fixes the reported partial-GROUP BY-key leak in AggregatingInOrderTransform by stopping creation of without_key states on the path that aggregates into the hash table and never consumes them. That part looks correct, and the new regression test now observes the leak on ASan builds instead of only pinning plan shape. I still see one unresolved exception-safety leak in the touched full-key helper, so I would keep this at ⚠️ Request changes.

Findings

❌ Blockers

  • [src/Interpreters/Aggregator.cpp:2840-2844] [dismissed by author -- https://github.com/Do not create unused aggregate states in aggregation in order with a partial GROUP BY key #114010#issuecomment-5229985372] createStatesAndFillKeyColumnsWithSingleKey still publishes the first full-key state into data_variants.without_key before executeOnIntervalWithoutKey / mergeOnIntervalWithoutKey initializes ownership (aggregator + Type::without_key). If fillKeyColumnsWithSingleKey itself, or the immediately following first-block setup in AggregatingInOrderTransform::consume (src/Processors/Transforms/AggregatingInOrderTransform.cpp:131-139), throws, unwinding still sees type == EMPTY and skips destroyAllAggregateStates, so a non-trivial aggregate state leaks on the full-key path too.
    Suggested fix: keep a local rollback guard around that first-state setup, or catch after createAggregateStates succeeds and explicitly destroy without_key before rethrowing until data_variants has been fully initialized as Type::without_key.
Final Verdict

Status: ⚠️ Request changes

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

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.90% +0.10%

Changed lines: Changed C/C++ lines covered: 16/16 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4de7aa9a2 with master e493bf79b (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 2b2987cc1; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.67 MiB 687.65 MiB -3.02 MiB (-0.44%)

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 units

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

Job report

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).
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 208f240dcea26e5: pinned enable_parallel_replicas = 0 in the new test's plan assertion.

04834 failed 3/3 reruns in Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) with one extra line ahead of the expected one:

+Order: parent_key ASC, child_key ASC
 Order: parent_key ASC

Value rows were byte-identical, so only the guard broke. Two steps print Order:, AggregatingStep and MergingAggregatedStep, and applyParallelReplicas runs before optimizeAggregationInOrder (optimizeTree.cpp:379 vs :413), so the coordinator's merging step prints the full GROUP BY key next to the one-column sorting prefix the test asserts.

Pinned the one setting the assertion depends on rather than tagging the test. 02481_aggregation_in_order_plan and 03273_group_by_in_order_still_used_when_group_by_key_doesnt_match_order_by_key assert the same line for the same shape and are both in parallel_replicas_blacklist.txt; a query-level pin keeps 04834 running in that job instead of skipped.

Verification: without the pin the failure reproduces (2 of 3 runs FAIL, same diff; needs automatic_parallel_replicas_mode = 0, as at the randomizer's value of 2 parallel replicas only collect statistics). With it, 50/50 under full randomization. The negative control still reddens: with ORDER BY (parent_key, child_key) the guard prints two columns. LeakSanitizer A/B unchanged: 1600 B in 30 allocations before, clean after, outputs identical.

02233_optimize_aggregation_in_order_prefix fails under those forced settings too, but identically on pristine master, and this PR does not touch it.

The other three reds are not from this diff: AST fuzzer (amd_tsan) is the pre-existing Invalid number of columns in chunk pushed to OutputPort family, Integration tests (amd_llvm_coverage, 7/8) is a test_storage_nats flake (65 hits / 56 unrelated PRs / 30 days), and Post Hooks follows from those. Finish ledger goes up when CI on this commit completes.

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

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed the Bugfix Validation failure. The per-arch jobs reported Bug does not reproduce on this arch because the test asserted only the plan shape and the query results, and the leak is invisible to both, so new_tests_check.py correctly failed the workflow.

The test now runs its queries through clickhouse local, whose at-exit LeakSanitizer check aborts the process when a state is leaked, and fails on that. The leak is an ordinary functional signal on any ASan build. Converted to .sh since it needs the exit code of a separate process; the plan-shape and result assertions and the reference file are unchanged, and on a non-ASan build only those are checked.

Verified with clickhouse-test against a pristine-master ASan binary and this branch:

  • pristine master: FAIL 3/3, SUMMARY: AddressSanitizer: 1600 byte(s) leaked in 30 allocation(s)
  • this branch: OK 3/3, and 20/20 under full randomization
  • forcing the non-ASan path on the leaking binary still passes, so that branch only drops the leak check and keeps the result assertions

02233_optimize_aggregation_in_order_prefix fails identically on pristine master in my local setup and is untouched here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4de7aa9

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
- no failed checks on this commit -

CI is fully finished on this head with zero failing checks. Config Workflow, Fast test and
Finish Workflow are all success; 157 of 175 check-runs concluded success and the 18
non-running ones each carry an explicit praktika reason (reused from cache, not affected by the changed files, not labeled with 'pr-performance', and similar); no job was dropped.
CIDB records 328328 test rows across 160 checks on this commit with 0 FAIL/ERROR.

For contrast, the previous heads on this branch were not clean: 208f240dcea2 had 4 red rows
and 018b081c2c31 had 6, so this is a real improvement on this head rather than a run that
simply never executed anything.

Session id: cron:our-pr-ci-monitor:20260810-063000

@nickitat nickitat self-assigned this Aug 10, 2026
@nickitat
nickitat added this pull request to the merge queue Aug 12, 2026
Merged via the queue into ClickHouse:master with commit 02d5fdc Aug 12, 2026
354 of 355 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 12, 2026
@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
CREATE 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.

▶ Run on ClickHouse Fiddle

Results:

  • Reproduces on: 26.7, 26.6, 26.5, 26.3, 25.8
  • Does not reproduce on: master
  • Tested versions: master, 26.7, 26.6, 26.5, 26.3, 25.8
  • Also tested (unsupported, context only): 26.2 reproduces
  • ✓ Fix is on master — this PR's change fixes the bug on master. The releases listed above still have the bug and need the backport.

Backport the fix to 26.7, 26.6, 26.5, 26.3, 25.8.

CC component owner: @alexey-milovidov @nickitat

Analysis metadata

comp-aggregation · Severity P2 · Finding phase_d_pr114010

  • Verified against master build b05b99a641f2 (aarch64)
Introducing change: not identified
  • No clean release baseline found and no lower bound established — source-build bisect is required to pin the introducing PR (not yet performed).
  • Walked 6 release(s) below the supported window: still reproduces down to 25.2.
  • Secondary components: comp-testing

@groeneai

Copy link
Copy Markdown
Collaborator Author

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:

  • 26.7.4.25, 26.6.3.30, 26.5.7.46, 26.3.18.25, 25.8.30.17: ~33 MB every run, deterministic
  • master (26.8.1.1309): ~1 KB

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: optimize_aggregation_in_order = 0, and full-key mode (GROUP BY parent_key on a table ORDER BY parent_key, where the consumer of the state runs).

Label. #114010 is merged but carries only pr-bugfix, so nothing was triggered. A single v25.8-must-backport covers exactly the list you asked for: computed with select_backport_branches from tests/ci/cherry_pick_branches.py against the five active release branches, it expands to 26.7, 26.6, 26.5, 26.3, 25.8. @alexey-milovidov could you apply that label? I do not hand-author release-branch PRs, so the robot is the route.

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 SET explain_query_plan_default = 'legacy', and that setting only exists from 26.7. On 26.6, 26.5, 26.3 and 25.8 that fails with Code: 115 UNKNOWN_SETTING and the output stops matching the reference. Dropping just that SET makes the output byte-identical to the committed reference on all four (measured). On master and 26.7 it is load-bearing and should stay. So the generated backport PRs for 26.6 and older need that one-line edit.

@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default 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.

LeakSanitizer: direct leak of quantileDD (DDSketch) aggregate states in AggregatingInOrderTransform in stress tests

5 participants