Repository navigation
Fix a server crash when merging -OrNull/-OrDefault states under group_by_overflow_mode = 'any' - #114740
Conversation
Under group_by_overflow_mode = 'any' the aggregator freezes its hash table once max_rows_to_group_by is exceeded, and mergeStreamsImplCase assigns the overflow row to every subsequent row whose key is absent. That pointer is null whenever the overflow row is disabled, which is the case for any query that is not GROUP BY ... WITH TOTALS, so places[i] == nullptr is a normal value on the merge path meaning the key did not fit and the row is dropped. The comment above that assignment states this. AggregateFunctionOrFill::mergeBatch was the only consumer of a places array that did not honour the contract: it unconditionally dereferenced places[i] to OR its trailing "was anything aggregated" flag byte, so a dropped row became a write through a null pointer and the server crashed with "Address: 0x8. Access: write". The base IAggregateFunctionHelper::mergeBatch and AggregateFunctionOrFill::addBatch already carry the same guard for the identical write; this adds the third and last instance of it. Reproduced on master with a debug build via an aggregate projection queried with max_rows_to_group_by = 10 and group_by_overflow_mode = 'any', for both -OrNull and -OrDefault and for both the single-number and the fixed-keys aggregation methods. Found by the targeted AST fuzzer (STID 2575-398a). Co-Authored-By: Claude Fable 5 <[email protected]>
Test-only follow-up to the AggregateFunctionOrFill::mergeBatch null-place guard; the source change is unchanged. The overflow arms passed on unfixed code in roughly half of CI runs. optimize_aggregation_in_order is randomized 0/1 by the test runner, and under 1 the merge goes through Aggregator::mergeOnBlockSmall, which passes no_more_keys = false unconditionally and never calls checkLimits. The frozen hash table that produces the null place is therefore never built, so the guarded line is unreachable. Measured on a pristine-master build: the arm segfaults at optimize_aggregation_in_order = 0 and returns normally at 1. Every overflow arm now pins the setting in its outer SETTINGS, which is the placement that takes precedence over the runner's client-level injection. The oracle was count() > 0, which is satisfied whether or not overflow dropped any group. It is now the exact surviving count, measured stable at 1000 across max_block_size 1 to 87122, both group_by_two_level_threshold extremes, max_threads = 8 and aggregation_in_order_max_block_bytes = 1. A run in the vacuous configuration returns 3000, so the assertion reddens instead of passing quietly. Each arm also sets force_optimize_projection_name so that a plan change which stops using the aggregate projection fails loudly rather than draining the coverage; that setting is gated on optimize_use_projections, so it cannot throw when the runner turns projections off. The two-key arm grouped by k and k + 7. optimize_group_by_function_keys defaults to true and removes keys that are functions of other keys, so the second key was dropped and the arm ran the same key64 method as the single-key arm, covering none of the fixed-keys method that the second CI check faulted on. The second key is now a stored column, and the aggregation method was verified to be keys128. The arm asserts that both keys survive via EXPLAIN; the same assertion returns 0 for the old degenerate form. AggregateFunctionFactory::get resolves the final suffix first, so sumTupleOrNull is OrNull(Tuple(sum)) with the OrFill combinator outermost, duplicating the plain -OrNull arm. The Tuple(OrNull(sum)) composition, which reaches the guard through AggregateFunctionTuple::mergeBatch, is spelled sumOrNullTuple. Both orders now ship as separate arms, confirmed by their return types Nullable(Tuple(UInt64)) and Tuple(Nullable(UInt64)). Renamed 04894 to 04896 to avoid colliding with an open pull request. Verification: all five overflow arms A/B'd individually (server dies on pristine master, correct values with the fix); the full test through clickhouse-test kills a master server with one fault block at AggregateFunctionOrFill.h:258 and is OK with the fix, with optimize_aggregation_in_order randomized to both values in the failing run; 50 of 50 runs green under full randomization. Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model review (click to expand)Two review rounds by an independent model, plus my own cold review of the resulting code Round 1 — fixed ❌ Arms 2-5 could pass on unfixed code in roughly half of CI runs. ❌ The "two keys" arm tested one key. ❌ The
💡 Test number collided with an open PR; renamed, re-verified free against master, all Round 2 — no findings. The independent model returned zero findings against the Disagreed, with reasons
Session id: cron:clickhouse-review-slot-8:20260814-005300 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260814-001300 |
|
Workflow [PR], commit [8ee7580] Summary: ✅
AI ReviewSummaryThis PR fixes the null- Final Verdict✅ No new findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 4/4 (100.00%) · Uncovered code |
|
cc @rschu1ze @nickitat, could you review this? Under group_by_overflow_mode = 'any' the aggregator hands a null place for every key that did not fit the frozen hash table, and AggregateFunctionOrFill::mergeBatch was the one batch consumer dereferencing it unconditionally to OR its trailing flag byte, so the server segfaults; the base helper and OrFill::addBatch already carry the same if (places[i]) guard. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units7 translation units recompiled, 9 s compile time in total, 7 of them have a recent master baseline. |
sum() skips NULL rows, so the previous sum(s != k) oracle stayed 0 whenever a surviving row came back NULL instead of its aggregate. That made the -OrNull arms blind to a partial loss of the OrFill trailing flag: measured with a mutant that propagates the flag on every other row, the -OrNull arms in isolation still reported [ OK ], while a total loss reddened only because sum() over an all-NULL column returns NULL. Comparing s IS NULL OR s != k instead reddens both mutants on every arm. The same change is applied to the -OrDefault, tuple and no-overflow arms, since the type default is equally invisible to the old form. .reference is unchanged. Reported by clickhouse-gh on the pull request.
…separately The test inserts three parts and asserts an exact surviving-row count under group_by_overflow_mode = 'any'. Nothing pinned the part topology, so a merge landing before the SELECT would both change the counts and remove the coverage: measured on the pre-fix binary, three parts segfault in AggregateFunctionOrFill::mergeBatch while one merged part returns 3000 rows cleanly, because a single part is aggregated in one pass and never merges partial aggregate states. A merge is not reachable in a fast run (SimpleMergeSelector needs min_age around 2400s at this part size before lowered_base drops to the range where the three parts qualify), but the test should not depend on that margin. SYSTEM STOP MERGES is used rather than max_bytes_to_merge_at_max_space_in_pool because the latter does not hold: an explicit OPTIMIZE TABLE FINAL still collapsed the parts under it, while with merges stopped the same OPTIMIZE is refused with ABORTED and the topology survives. Verified: the reference is unchanged; the pre-fix binary still segfaults at AggregateFunctionOrFill.h:258 with the pin in place, so detection is preserved; both mergeBatch mutants from the previous round still redden six arms; injecting an external merge reddens the test only when the pin is removed; 50 runs green under full randomization.
CI finish ledger - 8ee7580No failures. The praktika report is Session id: cron:our-pr-ci-monitor:20260814-173000 |
ReproducerCREATE TABLE t_orfill (k UInt64, v UInt64,
PROJECTION p (SELECT k, sumOrNull(v) GROUP BY k))
ENGINE = MergeTree ORDER BY tuple();
SYSTEM STOP MERGES t_orfill;
INSERT INTO t_orfill SELECT number, number FROM numbers(1000);
INSERT INTO t_orfill SELECT number + 1000, number + 1000 FROM numbers(1000);
INSERT INTO t_orfill SELECT number + 2000, number + 2000 FROM numbers(1000);
SELECT k, sumOrNull(v) FROM t_orfill GROUP BY k
SETTINGS optimize_use_projections = 1, max_threads = 1, optimize_aggregation_in_order = 0,
max_rows_to_group_by = 10, group_by_overflow_mode = 'any',
force_optimize_projection_name = 'p';
-- observed: server dies, SIGSEGV write to 0x8 in AggregateFunctionOrFill::mergeBatch
-- (also with sumOrDefault; needs >1 part so the projection merge path runs)Results:
CC component owner: @alexey-milovidov @nihalzp Analysis metadata
Introducing change: not identified
|
…Default states under group_by_overflow_mode = 'any'
Backport #114740 to 26.7: Fix a server crash when merging -OrNull/-OrDefault states under group_by_overflow_mode = 'any'
The test failed deterministically whenever the runner randomized index_granularity_bytes small, throwing Code: 117 ... Projection p is specified in setting force_optimize_projection_name but not used at four observed values (7801, 9281, 49209, 1024). That reddened unrelated PRs' CI and, more importantly, replaced the coverage the arm exists for: the null-place mergeBatch segfault fixed in ClickHouse#114740. The optimizer was right. p stores four aggregate states where the sibling p2 stores one, and granule sizing charges an aggregate-state column at its serialized width, so at small index_granularity_bytes p reads more marks than the base table and than p2 and is dropped -- once by the lost-to-parent check at optimizeUseAggregateProjection.cpp:1036, once by the single-best candidate selection at :1048. At coarse granularity every candidate floors to one granule per part, the mark counts tie, and p wins only because it is declared first, so the test's green rested on that tie for its whole life. Both comparisons are removed at the fixture level instead of clamping the randomizer away from a correct decision. index_granularity = 1 makes the base and every projection read one row per granule, which takes state width out of the mark counts, and the sumOrNull arm (the only arm where p2 is a candidate at all, since matchAggregateFunctions looks aggregates up by name) also names p as preferred, which reduces the candidate list to one entry before any cost comparison. An explicit CREATE TABLE setting is immune to the runner, whose injection skips names already present. force_optimize_projection_name = 'p' is kept, so the oracle is exactly as strong as before; index_granularity_bytes, min_bytes_for_wide_part and use_const_adaptive_granularity stay randomized. This matches 04063 and 04365, the other tests using this pin. Validated at all four culprit values, across 36 combinations of the settings that remain randomized times 5 arms (Compact and Wide), with 50/50 runs both with and without randomization; the pre-fix binary still segfaults at AggregateFunctionOrFill.h:258 with this fixture. The reference file is unchanged. Co-Authored-By: Claude Fable 5 <[email protected]>
…Default states under group_by_overflow_mode = 'any'
Backport #114740 to 26.6: Fix a server crash when merging -OrNull/-OrDefault states under group_by_overflow_mode = 'any'
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes a server crash that happens when aggregate states of the
-OrNullor-OrDefaultcombinators are merged withgroup_by_overflow_mode = 'any'and a non-zeromax_rows_to_group_by, for example when a query reads through an aggregate projection.Description
Under
group_by_overflow_mode = 'any'the aggregator freezes its hash table oncemax_rows_to_group_byis exceeded, and every subsequent row whose key is absent gets the overflow-row pointer. That pointer isnullptrwheneveroverflow_rowis off, which is the case for any query that is notGROUP BY ... WITH TOTALS, soplaces[i] == nullptris a normal value on the merge path meaning "this key did not fit, skip the row".Aggregator::mergeStreamsImplCasestates this in an in-source comment and hands the array tomergeBatchwithout filtering.Every batch consumer honours that contract except
AggregateFunctionOrFill::mergeBatch, which unconditionally dereferencedplaces[i]to OR its trailing "was anything aggregated" flag byte, so a null place became a write through a null pointer.IAggregateFunctionHelper::mergeBatchandAggregateFunctionOrFill::addBatchalready carry the sameif (places[i])guard; this adds the third and last instance of it.Reproduced on master
bf580ecb357f39df87f814ad214698f2c8aeab17with a debug build: aMergeTreetable with an aggregate projection queried withmax_rows_to_group_by = 10, group_by_overflow_mode = 'any'dies withAddress: 0x8. Access: writeatAggregateFunctionOrFill.h:258, for both-OrNulland-OrDefaultand for both the single-number and the fixed-keys aggregation methods. The added test covers those arms plus both-Tuple/-OrNullnesting orders, and fails (the server dies) without the change.Behaviour changes only for rows the aggregator has already decided to drop, so no query that never trips
max_rows_to_group_byunder modeanyis affected.Found by the targeted AST fuzzer (
AST fuzzer (amd_debug, targeted)and..., old_compatibility, STID 2575-398a): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114690&sha=9b5110134d760b3aace6e8c767073cb51c338233&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29. The defect is on master and independent of that PR, which only made the path easier to hit.Version info
26.7.4.50,26.6.5.31