Skip to content

Check memory limit after reading or copying aggregate function states - #129553

Draft
azat wants to merge 1 commit into
ClickHouse:masterfrom
azat:aggregate-state-memory-limit
Draft

azat wants to merge 1 commit into
ClickHouse:masterfrom
azat:aggregate-state-memory-limit

Conversation

@azat

@azat azat commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

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

Check memory limit after reading or copying aggregate function states

Closes: #127561
Closes: #127334


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

@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [58f099c]

Summary: ❌

job_name test_name status info comment
Performance Comparison (amd_release, master_head, 2/6) FAIL Performance dashboard
uniq_stored #2 FAIL dashboard
Performance Comparison (arm_release, master_head, 1/6) FAIL Performance dashboard
uniq_states_read_merge #1 FAIL dashboard
aggregating_merge_tree #0 slower query history
uniq_states_read_merge #0 slower query history
Performance Comparison (arm_release, master_head, 2/6) FAIL Performance dashboard
uniq_stored #2 FAIL dashboard

AI Review

Summary

The PR adds explicit memory-limit checks after reading and copying aggregate states whose allocations can bypass enforcement. The checks reject the reproduced large-state copies near the limit, but their per-state cost substantially slows small-state reads and copies. The ownership-copy regression also accepts the unchecked implementation because a later allocation raises the expected exception.

PR Metadata

Performance Improvement does not match this memory-limit bug fix. A changelog entry is required and present, but should explain the affected limits and user impact; exact replacements are below.

Findings

❌ Blockers

  • src/AggregateFunctions/IAggregateFunction.h:802: Full tracker walks dominate small-state processing. Each non-trivially destructible state invokes CurrentMemoryTracker::check, including small inline states. For one million rows, median Native read time rose from 32.0 to 121.5 ms (3.80×); shared-state copies rose from 61.0 to 153.5 ms for a small String (2.52×), and from 181.0 to 279.0 ms for FixedString(32) (1.54×). These alternating single-thread measurements use the same PR Fast-test binary, comparing the original helper against an immediate-return replacement; all caller overhead remains. Amortize the full tracker walk across the new call sites while retaining prompt enforcement for large allocations.

⚠️ Majors

  • tests/queries/0_stateless/05493_aggregate_state_memory_limit.sql:13: The ownership-copy assertion does not prove bounded memory use. With the new helper disabled and the query reduced to 400 rows, it still raises MEMORY_LIMIT_EXCEEDED: the later finalized-result allocation reports 829.73 MiB of prospective usage, versus 98.21 MiB with the checks enabled, under the same 95.37 MiB limit. Assert refusal usage near the limit through system.query_log, rather than accepting any eventual memory exception.

💡 Nits

  • Replace the changelog category with Bug Fix (user-visible misbehavior in an official stable release).
  • Suggested changelog entry: “Enforce max_memory_usage and max_server_memory_usage while reading or copying AggregateFunction states that allocate memory outside the arena, preventing excessive memory growth before the query is stopped.”
Missing context / blind spots
  • ⚠️ Timing evidence isolates the new check in the published aarch64 Fast-test binary; a separately compiled master/head comparison on release builds would quantify the complete production impact. Local runtime checks did not cover Protobuf.
Tests
  • ⚠️ Add a focused small-state read/copy performance regression covering inline states with non-trivial destructors.
  • ⚠️ Strengthen the memory regression with a refusal-usage bound so removing or deferring the checks fails it. Fast test currently passes the new test; local checks also verified near-limit refusal for shared-state copies, aggregate-state addition, and neighbor.
Final Verdict

Status: ❌ Block. Amortize the checks, demonstrate acceptable small-state read/copy performance, and make the regression reject delayed memory-limit enforcement.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Nov 5, 2026
Comment on lines +801 to +802
if (check_memory_limit)
checkMemoryLimitForAggregateFunctionState();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ [P1] Amortize the full memory-tracker check for small states

This runs CurrentMemoryTracker::check once per non-trivially destructible state, even when the state fits inline and performs no heap allocation. The full tracker walk then dominates ordinary reads and copies. Using this PR's aarch64 Fast-test binary, with 1,000,000 rows, max_threads = 1, alternating trials and six measured samples per variant:

Operation Helper returns immediately Current code
Native read of anyLastState('x') 32.0 ms 121.5 ms
Shared-state copy of anyLastState('x') 61.0 ms 153.5 ms
Shared-state copy over FixedString(32) 181.0 ms 279.0 ms

The control is the same binary, with only the new helper's body replaced by an immediate return; caller overhead remains in both variants. This isolates the check's cost rather than claiming a separately compiled master comparison. The copy query is:

SELECT finalizeAggregation(materialize(initializeAggregation('anyLastState', 'x')))
FROM numbers(1000000)
SETTINGS max_threads = 1, max_memory_usage = '1G' FORMAT Null;

Please amortize the expensive tracker walk while preserving prompt enforcement for large states, and add a small-state read/copy benchmark. The same per-state cost also occurs in ColumnAggregateFunction::ensureOwnership and the other new call sites; checking only once per block would reintroduce the memory-limit problem.

Comment on lines +12 to +13
SELECT finalizeAggregation(materialize(initializeAggregation('anyLastState', toFixedString('\0', 1048577)))) FROM numbers(4000)
SETTINGS max_memory_usage = '100M', max_block_size = 65536 FORMAT Null; -- { serverError MEMORY_LIMIT_EXCEEDED }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ [P2] Assert that the ownership copy stops near the memory limit

Checking only for MEMORY_LIMIT_EXCEEDED does not distinguish the fix from the original unchecked copy. ColumnAggregateFunction::convertToValues calls ensureOwnership and then reserves the finalized FixedString result, whose allocation can raise the same exception after all states have already been copied.

I disabled only the new check helper in the PR's Fast-test binary and ran this query with 400 rows instead of 4000 to bound the experiment: it still returned the expected exception, reporting 829.73 MiB of prospective usage, including a refused 400 MiB allocation. The unchanged PR binary rejected it at 98.21 MiB, under the same 95.37 MiB limit. Thus the exception assertion accepts the unchecked implementation too, and would also accept a check deferred until after the copy loop.

Record these queries with a distinct log_comment and assert from system.query_log that the reported refusal usage remains close to the configured limit (for example below 150 MB). This makes the test protect the bounded-memory behavior rather than an eventual allocation failure.

@clickhouse-gh clickhouse-gh Bot added the comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). label Nov 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 58f099c3d with master de6daf9f5 (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

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

Median compile-time ratio to the baselines is ×0.95 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -155.1 s (-6%) in total before that adjustment.

Job report

eoger-ant pushed a commit to eoger-ant/ClickHouse that referenced this pull request Nov 16, 2026
…rter of the states

No existing query number or text changes: 2 queries are disabled and 2
copies appended as 5 and 6. The copies are queries 0 and 2 with
`WHERE k < 1250000`: the first quarter of the one part of
uniq_tiny_states (153 of 611 granules), the same mix of 2- and
9-element states; each of the 1000 GROUP BY sets ends two size degrees
smaller at the same fill.

Locally (official amd builds, perf.py, two repetitions on different NUMA
nodes, L3 capped to 1 way and to 3 ways): per-row time of the copies
0.94-1.06 of the originals', per-row user time too; the GROUP BY copy
keeps 0.86-0.995 of the effect of ClickHouse#111493 (9b9c059 -> d1a7da6,
CI x1.14 amd / x1.20 arm on query 2), the finalizeAggregation copy keeps
0.94 of the effect of the ClickHouse#129553 CI build (CI x1.31 / x1.39 on query 0).
The pair passes ran 15 runs per query and server. The copy's 80 MB of
sets sits between arm's 36 MB and amd's 105 MB shared L3, so the regime
and the effect were gated at both cache widths.

Saving: about 27 s of query time per master perf job on amd, 25 s on arm.

Related: ClickHouse#129258

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

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

comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant