Repository navigation
Bound the total number of nested -Resample combinator states - #121083
alexey-milovidov merged 11 commits into
Conversation
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]>
|
Workflow [PR], commit [30a51e1] Summary: ✅
AI ReviewSummaryThe PR bounds nested Findings
Tests
Final VerdictStatus: |
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]>
|
Review follow-up landed as Narrowed the guard (Option A). The new Test updates.
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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🫧 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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🫧 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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
I propose to move it to a follow up and merge the main change
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes149 object files changed (+1.27 MiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units333 translation units recompiled, 2620 s compile time in total, 333 of them have a recent master baseline. |
|
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. |
|
@groeneai, after this is merged, send a PR with a re-implementation with a generic fix. |
|
Acknowledged. Once this is merged, I'll send a PR that replaces the |
|
Sent as #130120: |
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
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Bound the total number of nested
-Resamplecombinator states by the product of each level's element count, so nested-Resamplechains with an empty innermost range no longer loop over2^60nested states and pin a CPU thread indefinitely.Documentation entry for user-facing changes
No documentation change needed.
Detailed description / Documentation
AggregateFunctionResamplebounded each level individually tomax_elements = 1048576and, throughsizeOfData, the total state size to2^40bytes. Nested-Resamplelevels multiply both the number of nested states and the loop work increate,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 iterates1048576times:2^60nested calls. The query below runs for 60+ s on a release build with default settings and cannot be interrupted bymax_execution_timebecause the loop is inside the aggregate function'screate/destroypath:Fix: the constructor walks the nested-function chain, multiplies the element counts of all
-Resamplelevels (each counted as at least one), and throwsARGUMENT_OUT_OF_BOUNDwhen the product exceedsmax_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-existing2^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's05244to 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
26.11.1.1642-master(included in26.11and later)