Skip to content

Fix a memory leak of min/max states built for _minmax_count_projection - #132557

Merged
Algunenano merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-minmax-count-projection-state-leak
Nov 18, 2026
Merged

Algunenano merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-minmax-count-projection-state-leak

Conversation

@groeneai

@groeneai groeneai commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

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):

Fixed a memory leak in queries answered by _minmax_count_projection that compute min or max of a Tuple, Array or FixedString primary key or partition column: every part read leaked one aggregate state.

Description

Related: Stress test (arm_asan_ubsan, s3), Sanitizer (STID: 1830-4545) (LeakSanitizer, SingleValueDataGeneric::set <- MergeTreeData::getMinMaxCountProjectionBlock). No related open issue found.

On 26.3.63.123, 2000 runs of SELECT max(k) over a two-part MergeTree table ordered by k Tuple(UInt64, String) (64 KiB strings) raise MemoryTracking by 280 MB, versus 1.4 MB with optimize_use_implicit_projections = 0. The memory is never freed.

Root cause: getMinMaxCountProjectionBlock built each state in a temporary place (create + add) and passed it to ColumnAggregateFunction::insertFrom(place). That overload creates its own state and merges place into it, and nothing destroyed place. SingleValueDataGeneric keeps a heap-owning Field for Tuple, Array or long string values, so each such state leaked.

Change: create the state in the column (insertDefault, then fill getData().back()), so the column owns it on every path, including the early returns and an exception from add. Results are unchanged. The block builder for aggregation from column statistics (makeBlockFromStatistics in optimizeUseAggregateProjection.cpp) had the same pattern and gets the same change. It does not leak today only because the states it builds (count, numeric min/max, integer or Decimal sum/avg) own no heap memory.

Validation: the new test counts LeakSanitizer reports of a short-lived clickhouse-local, and it fails on the unfixed ASan master build (0 -> 1). The fixed ASan build reports no leak for Tuple, Array, FixedString and Nullable(FixedString) keys or a FixedString partition column, the existing minmax_count projection tests pass on debug and ASan, the aggregation-from-statistics tests pass on debug, and the new test passes 50/50 in repeated runs.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.2767-master (included in 26.11 and later)
  • Backported to: 26.10.7.13, 26.9.33.11, 26.8.41.16, 26.3.67.26

`MergeTreeData::getMinMaxCountProjectionBlock` built each min/max/count
state in a temporary place (arena alloc + `create` + `add`) and then
called `ColumnAggregateFunction::insertFrom(place)`. That overload does
not take ownership: it creates a new column-owned state and merges
`place` into it, so `place` was never destroyed. For a `min`/`max`
state that owns heap memory (`SingleValueDataGeneric` holding a `Tuple`,
`Array` or long `FixedString` field of the first primary key column or
of a min-max partition column) every part read leaked one state, which
LeakSanitizer reported in a stress run (STID 1830-4545).

Build the state inside the column instead (`insertDefault` and fill
`getData().back()`, as `FunctionsConversion.cpp` does), so the column
owns it from creation and destroys it on every path, including the
early returns and an exception from `add`. Results are unchanged:
merging into a default state yields the same state.

The new test runs the query in a short-lived `clickhouse-local` and
counts LeakSanitizer reports in its own log; the count is 0 on builds
without a leak sanitizer, and an EXPLAIN line asserts the projection
was used.

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 cold review (1 nit, no code change).

# Sev Finding Verdict Evidence / action
1 💡 The aggregation-from-statistics block builder (optimizeUseAggregateProjection.cpp) keeps the same create + insertFrom(place) shape DISAGREE Not a leak: it admits only numeric min/max and integer or Decimal sum/avg (non-Nullable, non-LowCardinality), whose states are trivially destructible. Left unchanged, one bug per PR.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261118-011200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One ASan clickhouse-local --tmp run: CREATE TABLE tab (k Tuple(UInt64, String)) ENGINE = MergeTree ORDER BY k, two inserts (two parts), SELECT min(k), max(k), count() FROM tab. The unfixed master ASan build aborts at exit with LeakSanitizer: detected memory leaks (448 bytes in 4 allocations), on every run. The symbolized frames match CI: ColumnTuple::get <- SingleValueDataGeneric::set <- setIfGreater/setIfSmaller <- getMinMaxCountProjectionBlock (max and min call sites).
b Root cause explained? The insert lambda in MergeTreeData::getMinMaxCountProjectionBlock built each state in a temporary arena place (create + add) and called ColumnAggregateFunction::insertFrom(place). That overload does not take ownership: it calls insertDefault() and merges place into the new state. Nothing called destroy(place), so a SingleValueDataGeneric Field holding a Tuple/Array/long string kept its heap block forever, one per part read.
c Fix matches root cause? Yes. The state is created in the column (insertDefault(), then getData().back() is filled), so the column owns it from creation and its destructor destroys it. This is the in-tree idiom of FunctionsConversion.cpp. No guard, no tag, and no change to insertFrom, whose other callers own and destroy their place.
d Test intent preserved / new tests added? New 05828_minmax_count_projection_state_leak.sh. It runs the query in a short-lived clickhouse-local and counts LeakSanitizer reports in its own log (0 on non-LSan builds, so one reference fits every build). An EXPLAIN line asserts the projection is used, so a 0 leak count cannot be vacuous. No existing test is edited.
e Both directions demonstrated? Through clickhouse-test: FAIL 3/3 on the unfixed master ASan binary (the leak line 0 -> 1; the other lines match). OK 10/10 on the fixed ASan build, and 50/50 randomized on the fixed debug build.
f Fix is general across code paths? All four call sites (primary key min/max, partition min/max) and count share the fixed lambda, and so do the early returns and the exception path. The statistics block builder in optimizeUseAggregateProjection.cpp has the same shape, but it only admits numeric min/max and integer sum/avg, whose states own no heap memory, so it is unchanged. The other insertFrom(place) callers (createSingleCountStateColumn, trivial count, runningAccumulate) already destroy place.
g Fix generalizes across inputs (params/datatypes/wrappers)? Matrix on both ASan binaries: Array(UInt64) PK, FixedString(64) PK, FixedString(32) partition column, Nullable(FixedString(32)) PK (allow_nullable_key), multi-column (Tuple, UInt64) PK. Every case leaks on the unfixed build and none on the fixed one, with identical results. LowCardinality(String) (arena-backed SingleValueDataString) leaks on neither.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or serialization change. The resulting state equals merge(default, temp), so query results are unchanged (existing minmax_count projection tests pass unchanged).
i Invariants and contracts preserved? Every aggregate state in the output columns has exactly one owner, the column, on the normal path, on every early return {} and on an exception from createColumnConst/add. A throwing create inside insertDefault is already popped by pushBackAndCreateState. createOrGetArena() is taken before insertDefault() and returns the same arena it uses (it never replaces an existing one).

Session id: cron:clickhouse-impl-slot-4:20261118-002500

@clickhouse-gh

clickhouse-gh Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2af1cae]

Summary: ✅


AI Review

Summary

The change fixes leaked min/max states in _minmax_count_projection by constructing them directly in ColumnAggregateFunction, and applies the same ownership pattern to aggregation from column statistics. Reviewed head 2af1caea3ab72d0408469f33416aeff8bb25bec8, including the follow-up change and all prior discussion. No actionable findings.

Missing context / blind spots
  • ⚠️ Latest-head CI is still running; its completed results remain to be checked. The unchanged regression test passed 50 targeted ASan runs on the preceding commit, and bugfix validation confirmed that the unfixed binary reports the leak. No local build or test execution was performed. Targeted ASan results, bugfix validation.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-projections Projections: precomputed layouts for accelerating queries (projection parts, maintenance). labels Nov 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0bc213c

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
Build profile diff infra, not from this PR (no ci/ file in the diff): all 8 readiness probes to the CI logs cluster hit Read timed out. (read timeout=3), so has_pr_data raised LogClusterNotReady: the endpoint never became ready. The same job failed on 29 PRs in the last 24 hours #129675 (mine, open)
PR praktika rollup of the row above #129675 (the owner above)

Both Bugfix validation (functional tests) jobs passed. Mergeable Check, Review Threads and CH Inc sync are green.

Session id: cron:our-pr-ci-monitor:20261118-053020

@Algunenano Algunenano self-assigned this Nov 18, 2026

@Algunenano Algunenano 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. I checked other places using arena.alignedAlloc and ColumnAggregateFunction::insertFrom(place) and insertMergeFrom(place) and they are safe, but src/Processors/QueryPlan/Optimizations/optimizeUseAggregateProjection.cpp:1224 doesn't leak today but pure luck (the states don't use heap memory).

Could you address it in this PR too please?

`makeBlockFromStatistics` had the same shape as the
`_minmax_count_projection` builder fixed in the previous commit: it
allocated each state in the column's arena, filled it, and passed it to
`ColumnAggregateFunction::insertFrom(place)`, which merges `place` into a
new column-owned state and never destroys `place`. It does not leak
today only because the states it builds have no heap memory: `count`,
`min`/`max` of a type whose value is a number (`canStatisticsTrackMinMax`),
and `sum`/`avg`/`sumCount` of an integer or `Decimal`.

Use `insertDefault` and fill `getData().back()` here too, so the column
owns the state from creation and destroys it on every path, including an
exception from `add`.

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

Copy link
Copy Markdown
Collaborator Author

Thanks. Done in 2af1caea3ab7: makeBlockFromStatistics now builds each state with insertDefault and fills getData().back(), as getMinMaxCountProjectionBlock does, so the column owns the state on every path, including an exception from add.

I did not add a test, because those states hold no heap memory and nothing leaks there today. The existing aggregation-from-statistics tests (04512, 05043, 05045, 05320, 05567) pass 5/5 on a debug build. I updated the PR description.

@Algunenano Algunenano added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Nov 18, 2026
@Algunenano
Algunenano enabled auto-merge November 18, 2026 16:37
@clickhouse-gh

clickhouse-gh Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2af1caea3 with master f14e64768 (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.

Compile time of recompiled translation units

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

Job report

@Algunenano
Algunenano added this pull request to the merge queue Nov 18, 2026
Merged via the queue into ClickHouse:master with commit 82024f1 Nov 18, 2026
195 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 18, 2026
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 18, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 18, 2026
Backport #132557 to 26.10: Fix a memory leak of `min`/`max` states built for `_minmax_count_projection`
clickhouse-gh Bot added a commit that referenced this pull request Nov 18, 2026
Backport #132557 to 26.9: Fix a memory leak of `min`/`max` states built for `_minmax_count_projection`
robot-clickhouse added a commit that referenced this pull request Nov 19, 2026
Cherry pick #132557 to 26.3: Fix a memory leak of `min`/`max` states built for `_minmax_count_projection`
robot-clickhouse added a commit that referenced this pull request Nov 19, 2026
robot-clickhouse added a commit that referenced this pull request Nov 19, 2026
Cherry pick #132557 to 26.8: Fix a memory leak of `min`/`max` states built for `_minmax_count_projection`
robot-clickhouse added a commit that referenced this pull request Nov 19, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 19, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 19, 2026
Backport #132557 to 26.8: Fix a memory leak of `min`/`max` states built for `_minmax_count_projection`
Algunenano added a commit that referenced this pull request Nov 19, 2026
Backport #132557 to 26.3: Fix a memory leak of `min`/`max` states built for `_minmax_count_projection`
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-projections Projections: precomputed layouts for accelerating queries (projection parts, maintenance). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

5 participants