Skip to content

Bound the total number of nested -Resample combinator states - #121083

Merged
alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
qoega:json-fuzz-group9-resample-combinators-bound
Nov 8, 2026
Merged

alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
qoega:json-fuzz-group9-resample-combinators-bound

Conversation

@qoega

@qoega qoega commented Sep 19, 2026 •

Copy link
Copy Markdown
Member

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 to CHANGELOG.md):

Bound the total number of nested -Resample combinator states by the product of each level's element count, so nested -Resample chains with an empty innermost range no longer loop over 2^60 nested states and pin a CPU thread indefinitely.

Documentation entry for user-facing changes

No documentation change needed.

Detailed description / Documentation

AggregateFunctionResample bounded each level individually to max_elements = 1048576 and, through sizeOfData, the total state size to 2^40 bytes. Nested -Resample levels multiply both the number of nested states and the loop work in create, destroy, add, merge, serialize, insertResultInto. With an empty innermost range (0, 0, 1) the nested state size is zero, so the size threshold never fires; each of three outer levels still iterates 1048576 times: 2^60 nested calls. The query below runs for 60+ s on a release build with default settings and cannot be interrupted by max_execution_time because the loop is inside the aggregate function's create/destroy path:

SELECT countResampleIfResampleIfResampleIfResample(0, 0, 1, 0, 1048576, 1, 0, 1048576, 1, 0, 1048576, 1)
    (number, 1, number, 1, number, 1, number)
FROM numbers(1);

Fix: the constructor walks the nested-function chain, multiplies the element counts of all -Resample levels (each counted as at least one), and throws ARGUMENT_OUT_OF_BOUND when the product exceeds max_elements, so the total number of nested states and the loop work are bounded regardless of the nested state size.

Adjusts 03175_aggregate_state_bulk_deserialization_overflow.sql: the pre-existing 2^37-state example is now rejected up front by the new check; the test is updated to expect the new outcome. The bulk-deserialization overflow guard stays in place as defense in depth for hand-built serialized states.

Test 05247_nested_resample_combinators_bound (renumbered from the branch's 05244 to avoid collision with the JSON-AST hardening PR).

Closes: #121082

cc @groeneai — fuzz-lab find (JSON AST fuzzer)

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1642-master (included in 26.11 and later)

qoega and others added 2 commits September 19, 2026 21:26
Every level of a nested `-Resample` combinator was bounded to 2^20 elements on its
own and the total state size to 2^40 bytes, but the loops in `create`, `destroy`,
`merge`, ... iterate over the product of the element counts, and an empty innermost
range makes the state size zero while the loops still run:
`countResampleIfResampleIfResampleIfResample(0, 0, 1, 0, 1048576, 1, 0, 1048576, 1,
0, 1048576, 1)` never finished (2^60 nested calls, not interruptible by
`max_execution_time`). The constructor now bounds the product of the element counts
of all nested `-Resample` levels by the same 2^20.

Test `05055` used products of 2^37 and 2^31 states to reach an allocation-size
overflow; such states can no longer be constructed and the queries are rejected up
front, the overflow check stays as defense in depth.

Found by `json_ast_sql_execution_fuzzer`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The JSON-AST hardening PR renumbers its foreign-key-declaration test
from 05228 to 05244; move this one to 05247 so both PRs can land in
either order.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@qoega qoega added the fuzz Problem found by one of the fuzzers label Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [30a51e1]

Summary: ✅


AI Review

Summary

The PR bounds nested -Resample work involving zero-sized states and exposes tuple children to the traversal. The total-work limit still misses work accumulated across tuple siblings, leaving the CPU exhaustion bug reachable. Request changes.

Findings

⚠️ Majors

  • AggregateFunctionResample.h:142–145: Tuple siblings bypass the total-work budget. Each child receives the full nested_elements allowance independently, while AggregateFunctionTuple::create executes every child. A nothingResampleTupleResampleState aggregate with two 1,024-bucket levels and 4,096 tuple elements passes every per-path check but performs 2^32 zero-byte nested calls. On the PR-head Fast test binary, it required an external kill after five seconds despite max_execution_time = 1; the same query's EXPLAIN and a same-width small-range control each finished in approximately 0.27 seconds. State avoids materializing result arrays, isolating the initialization work. Sum sibling contributions with checked/saturating arithmetic and multiply at -Resample levels, then enforce the zero-sized-work budget over the subtree. Existing review thread.

    Reproducer generator (execute the printed SQL):

    elements = ','.join(['number'] * 4096)
    print(f'SELECT nothingResampleTupleResampleState(0, 1024, 1, 0, 1024, 1)(tuple({elements}), number) FROM numbers(1) SETTINGS max_execution_time = 1, max_threads = 1 FORMAT Null')
Tests
  • ⚠️ Add a regression where tuple paths individually fit max_elements but their combined zero-sized work exceeds it. The existing single-element tuple test cannot detect this gap.
Final Verdict

Status: ⚠️ Request changes. Account for combined sibling work and add the focused regression before merging.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). labels Sep 19, 2026
qoega and others added 3 commits September 22, 2026 19:07
Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ample itself

Master added an empty-range check to `countResample`/`sumResample` after
this test was written (they now throw `ARGUMENT_OUT_OF_BOUND` on
`(start, start, step)`). The last query is our fix's zero-nested-total
case; add the serverError specifier and drop the now-unreachable
giant-empty-array reference line. The overall coverage stays: the fix
still catches the product-of-nested-element-counts overflow shown in
queries 1 and 2.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…t query throws)

The previous commit added the serverError specifier to the last query
but only trimmed the reference to 4 lines; it should be 3, because
queries 1, 2, and 6 all throw and queries 3-5 produce three lines of
output.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
The previous commit added a hard cap of 2^20 on the product of the nested
element counts of all nested -Resample combinators, but that rejects legitimate
nested chains whose state fits comfortably in the existing `sizeOfData` /
`max_state_size` limits. In particular `countResampleIfResample(0, 2048, 1,
0, 2048, 1)` now threw even though its state is ~32 MiB of 8-byte count
buckets. The same regression would have hit existing queries and persisted
`AggregateFunction(countResampleIfResample(...))` columns after upgrade.

The pathological case that motivated the cap is a zero-byte nested state:
`sizeOfData` is zero no matter how many buckets, so the state-size cap passes
vacuously, but every `create` / `destroy` / `merge` call still loops over
`total` no-op nested calls and nested -Resample combinators multiply those
loops. Only enforce the nested-element cap in that case; nonzero nested
states remain bounded by `sizeOfData` / `max_state_size` alone.

Test `05247` now expects the 2048*2048 count chain to succeed and adds
`nothingResampleIfResample(0, 2048, 1, 0, 2048, 1)` for the zero-state case.
Test `05055` reverts to the pre-PR behaviour (`MEMORY_LIMIT_EXCEEDED`): with
nonzero `count` state the Resample constructor no longer throws up front, and
the bulk-deserialization check / arena allocation hit the memory limit as
before.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@qoega

qoega commented Nov 1, 2026

Copy link
Copy Markdown
Member Author

Review follow-up landed as 4c8327e534c. Addresses the 2026-09-25 BLOCKER on the backward-incompatible nested -Resample cap.

Narrowed the guard (Option A). The new nested_elements > max_elements loop in src/AggregateFunctions/Combinators/AggregateFunctionResample.h now runs only when sizeOfData(nested) == 0. Nonzero-state nested chains remain bounded by the existing sizeOfData / max_state_size (2^40 B) check, so countResampleIfResample(0, 2048, 1, 0, 2048, 1) (~32 MiB of count state) is accepted again — matching pre-PR behaviour, which was the compatibility concern for existing queries and persisted AggregateFunction(countResampleIfResample(...)) column types after upgrade. Zero-byte nested states (the pathological fuzz case: nothing-based chains, or any chain whose innermost -Resample was empty before the per-level empty-range gate rejected it up front) still can't spin through 2^40+ no-op loops.

Test updates.

  • tests/queries/0_stateless/05247_nested_resample_combinators_bound.sql: countResampleIfResample(0, 2048, 1, 0, 2048, 1)(number, 1, number) moved from { serverError ARGUMENT_OUT_OF_BOUND } to a length(...) = 2048 success case (reference gains a leading 2048). Added nothingResampleIfResample(0, 2048, 1, 0, 2048, 1) as the zero-state throw case so the narrowed guard still has coverage.
  • tests/queries/0_stateless/05055_aggregate_state_bulk_deserialization_overflow.sql: three countResampleIfResample(...) deserialization cases reverted to MEMORY_LIMIT_EXCEEDED (file hash matches pre-PR). They had been retargeted to ARGUMENT_OUT_OF_BOUND by the overbroad cap; with Option A the Resample constructor no longer throws for those nonzero-state chains, so the memory limit catches it as before.

Fits the "narrow the fix to the zero-sized / otherwise unsafe cases" option you offered.

{
size_t nested_total = 0;
if (const auto * resample = dynamic_cast<const AggregateFunctionResample<UInt64> *>(nested.get()))
nested_total = resample->total;

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.

This still leaves the CPU-pin reachable through any wrapper that contributes its own state bytes but forwards create / destroy to a zero-sized inner -Resample. For example, nothingResampleDistinctResample(0, 1048576, 1, 0, 1048576, 1)(number, number) is legal: Distinct makes the outer size_of_data nonzero via prefix_size + nested_func->sizeOfData, so this branch is skipped, but Distinct::create still calls the inner Resample::create once per outer bucket. That reconstructs the same 2^40 nested calls with only O(total) state.

Can we key the guard off the presence of any zero-sized inner -Resample in the nested chain, not only size_of_data == 0 on the immediate nested function? A focused stateless case around nothingResampleDistinctResample would lock the hole down.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🫧 Fixed in 201a05c. The guard now walks the full nested aggregate-function chain, records any zero-sized inner -Resample even through stateful wrappers such as -Distinct, and applies the nested-element bound to the full product. I added the focused nothingResampleDistinctResample stateless case.

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.

The -Distinct example is fixed, but the wrapper bypass remains at src/AggregateFunctions/Combinators/AggregateFunctionResample.h:122: AggregateFunctionTuple stores multiple nested functions and inherits the default null getNestedFunction, so this walk stops before its inner -Resample.

SELECT nothingResampleTupleResample(
    0, 1048576, 1, 0, 1048576, 1
)(tuple(number), number)
FROM numbers(1)
SETTINGS max_execution_time = 1, max_threads = 1;

Here nested_elements stays at the outer 1048576, so the check at line 136 passes, while create still performs 2^40 zero-byte nested calls. I reproduced this with the Fast test binary for 787cfecb2ffd83b00d12f35d2b9c08d46306aa73: it required an external kill after five seconds despite the one-second execution limit; the small-range equivalent succeeds. Please carry the work bound through the aggregate-function subtree, including multiple-child combinators, and add this stateless regression case.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🫧 Fixed in d7b214e. The bound now traverses the complete aggregate-function subtree through a general forEachNestedFunction hook, with AggregateFunctionTuple exposing every child. The element product is tracked independently per path, so sibling tuple elements are not incorrectly multiplied together. I also added the exact nothingResampleTupleResample query as a stateless regression.

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.

The single-child tuple reproducer is fixed, but the total-work bound is still bypassable at src/AggregateFunctions/Combinators/AggregateFunctionResample.h:142–145: every sibling gets the same full allowance, without summing the work of the children that AggregateFunctionTuple::create executes sequentially.

For example, generate a tuple with 4,096 elements:

elements = ','.join(['number'] * 4096)
print(f'SELECT nothingResampleTupleResampleState(0, 1024, 1, 0, 1024, 1)(tuple({elements}), number) FROM numbers(1) SETTINGS max_execution_time = 1, max_threads = 1 FORMAT Null')

Each path has 1024 * 1024 == max_elements, so all checks pass, but create makes 4096 * 1024 * 1024 = 2^32 zero-byte nested calls. I reproduced this with the Fast test binary for 30a51e18fa3534743e68311fb456773acefb760d: the query required an external kill after five seconds despite the one-second limit. EXPLAIN for the same query and a same-width control with ranges (0, 3, 1, 0, 2, 1) both finish in about 0.27 seconds. Returning State avoids materializing the large result arrays, so the timeout is already in state initialization.

Please sum sibling work with checked/saturating arithmetic, multiply at -Resample levels, and enforce the zero-sized-work budget over the subtree. Sibling element counts should not be multiplied together, but checking each sibling independently still leaves the CPU exhaustion mechanism reachable. Add a focused case whose individual paths fit the limit but whose combined work exceeds it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I propose to move it to a follow up and merge the main change

@clickhouse-gh

clickhouse-gh Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 30a51e18f with master f37c6e757 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 8fa6602f7; 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.

Object file sizes

149 object files changed (+1.27 MiB total), 0 added.

Object file Master PR Δ
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniq.cpp.o 13.55 MiB 13.63 MiB +83.11 KiB (+0.60%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionCovar.cpp.o 6.88 MiB 6.94 MiB +64.79 KiB (+0.92%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionCorr.cpp.o 7.07 MiB 7.13 MiB +64.50 KiB (+0.89%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupArrayMov… 5.89 MiB 5.95 MiB +55.98 KiB (+0.93%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionGroupNumericI… 5.79 MiB 5.83 MiB +42.03 KiB (+0.71%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionSum.cpp.o 3.81 MiB 3.85 MiB +38.57 KiB (+0.99%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.12 MiB 3.15 MiB +32.59 KiB (+1.02%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined2… 3.11 MiB 3.14 MiB +32.57 KiB (+1.02%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.11 MiB 3.14 MiB +32.57 KiB (+1.02%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.11 MiB 3.15 MiB +32.57 KiB (+1.02%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.11 MiB 3.15 MiB +32.57 KiB (+1.02%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.11 MiB 3.14 MiB +32.57 KiB (+1.02%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.11 MiB 3.15 MiB +32.57 KiB (+1.02%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.11 MiB 3.14 MiB +32.57 KiB (+1.02%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionUniqCombined1… 3.11 MiB 3.15 MiB +32.57 KiB (+1.02%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileExact… 2.98 MiB 3.01 MiB +27.05 KiB (+0.89%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionAvgWeighted.c… 13.64 MiB 13.66 MiB +22.30 KiB (+0.16%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileExact… 2.43 MiB 2.45 MiB +21.97 KiB (+0.88%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionQuantileExact… 2.41 MiB 2.43 MiB +21.79 KiB (+0.88%)
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionsArgMinArgMax… 16.05 MiB 16.07 MiB +18.68 KiB (+0.11%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov alexey-milovidov self-assigned this Nov 7, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 7, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Thanks, approved!

However, the fix is not generic enough. The culprit is that it creates or iterates over a lot of aggregate states. This begs the question - are other aggregate function combinators affected? We can fix it by introducing a counter for iterations inside factory methods and throwing if it is too large.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, after this is merged, send a PR with a re-implementation with a generic fix.

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. Once this is merged, I'll send a PR that replaces the -Resample-specific bound with a generic counter of nested states created or iterated in the aggregate function factory, and check the other combinators for the same problem.

Merged via the queue into ClickHouse:master with commit 7b5f2bf Nov 8, 2026
186 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 8, 2026
@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator

Sent as #130120: IAggregateFunction::createNestedStates counts the states that occupy no memory created within one create (through any wrapper, across -Tuple elements) and throws above 1048576; the -Resample tree walk is removed, so every type parses again. Other combinators: -ForEach was affected the same way (over a zero-sized -Resample, and through the element count of a serialized state), and -Tuple adds up its elements; one-state wrappers only forward. -Map keys and array elements still get the limit each, like GROUP BY keys (nothingResampleMapArray(0, 1048576, 1) over 2^20 one-key maps is still slow): counting them per row cost 5-12% on ordinary -Map / -ForEach rows.

groeneai pushed a commit to groeneai/ClickHouse that referenced this pull request Nov 12, 2026
ThinLTO inlining and identical-code folding can attribute equal live allocations to different container or column specializations. Anchor cross-build stacks at the stable ClickHouse caller so the differential flamegraph does not show balanced allocation plumbing as regressions and improvements.

Observed in https://s3.amazonaws.com/clickhouse-test-reports/PRs/121083/30a51e18fa3534743e68311fb456773acefb760d/pr/storage_memory_check/storage_memory_report.html

Related: ClickHouse#121083
Related: ClickHouse#121545
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.). fuzz Problem found by one of the fuzzers 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.

Nested -Resample combinators with an empty inner range loop over 2^60 nested states; the query never finishes and is uncancellable

4 participants