Skip to content

Do not aggregate in order when a query needs the aggregation overflow row - #121522

Open
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:aggregation-in-order-overflow-row
Open

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:aggregation-in-order-overflow-row

Conversation

@groeneai

@groeneai groeneai commented Sep 22, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

Aggregation in order is no longer used when a query needs an aggregation overflow row, that is WITH TOTALS together with max_rows_to_group_by and group_by_overflow_mode = 'any'. That path never produces the overflow row, so with force_aggregation_in_order set such a query could fail with Chunk should have AggregatedChunkInfo in TotalsHavingTransform.

Description

Failing job: https://github.com/ClickHouse/ClickHouse/actions/runs/35659017389/job/106583430653 (AST fuzzer (amd_msan)), result Logical error: Chunk should have AggregatedChunkInfo in TotalsHavingTransform. (STID: 3546-3720). It surfaced on PR #113856, which is only the carrier: that PR changes text index files under src/Storages/MergeTree only.

WITH TOTALS with max_rows_to_group_by and group_by_overflow_mode = 'any' sets overflow_row, so TotalsHavingTransform requires an AggregatedChunkInfo on every chunk. Aggregation in order cannot serve that: AggregatingInOrderTransform aggregates through Aggregator::executeOnBlockSmall, which passes overflow_row = nullptr, so the is_overflows chunk is never produced. optimizeAggregationInOrder has refused the combination since c5f93eb, but the force_aggregation_in_order branch of the planner consulted only the setting, so the in-order step was built anyway; with two or more parts the all-empty merge product then loses its chunk info to the header conformance back-fill in ISimpleTransform::work, and the precondition is violated.

The planner now also tests overflow_row, which is the shape #109862 used for the neighbouring condition in the same expression. AggregatingStep::deserialize rejects a serialized plan that carries both with INCORRECT_DATA, so an older initiator cannot ship the combination to a server that accepts query plan packets.

The new test reproduces it deterministically on a Debug build: four single-row parts, a filter that reads every part and matches no row, and GROUP BY ... WITH TOTALS with those settings. It also covers WITH ROLLUP and a mutation's scalar subquery, and pins that no AggregatingInOrderTransform is built for such a query while one still is without the overflow settings.

Keeping chunk_infos across that back-fill would silence the error too, but the query would still run on a path that never produces the overflow row, so the refusal belongs in the planner.


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

groeneai and others added 2 commits September 22, 2026 08:36
… row

WITH TOTALS together with max_rows_to_group_by and group_by_overflow_mode = 'any'
sets Aggregator::Params::overflow_row, which makes TotalsHavingTransform::transform
require an AggregatedChunkInfo on every chunk it sees, and it tests that before its
own early return for an empty chunk.

Aggregation in order cannot serve such a query. Its only aggregation entry point is
Aggregator::executeOnBlockSmall, which calls the five-argument executeImpl with
overflow_row = nullptr, so the is_overflows chunk is never produced.
optimizeAggregationInOrder has refused the combination since c5f93eb ("It just
does not work"), but the force_aggregation_in_order branch of both
Planner::addAggregationStep and InterpreterSelectQuery::executeAggregation consulted
only the setting and the grouping-sets state, so the in-order step was built anyway,
and optimizeAggregationInOrder cannot undo it because its early return is skipped
once explicitSortingRequired() is set from the same bool.

Two or more parts are then needed to observe it.
FinishAggregatingInOrderAlgorithm::consume skips row-less inputs, so with every stream
empty prepareToMerge emits an empty ChunksToMerge;
MergingAggregatedBucketTransform::transform attaches its AggregatedChunkInfo to a chunk
that mergeBlocks left with zero columns, and the header conformance back-fill in
ISimpleTransform::work then replaces that chunk wholesale and discards chunk_infos.
With a single part the tail is FinalizeAggregatedTransform, which back-fills the
missing info, which is why one part passes.

Gating the local bool on overflow_row is sufficient at both sites, because the same
bool also supplies AggregatingStep's
explicit_sorting_required_for_aggregation_in_order argument: the sort descriptions stay
empty, inOrder() and explicitSortingRequired() are both false,
memoryBoundMergingWillBeUsed() is false, and transformPipeline takes the hash branch
that does call checkLimits and does emit the is_overflows chunk. This is the shape
ClickHouse#109862 used for the neighbouring grouping-sets condition in the same expression.

The old analysis is still reached for a mutation scalar subquery, which reproduced the
identical assertion, so it is guarded too and the new test covers that route. The
projection construction site cannot reach it: a projection SELECT does not parse with
WITH TOTALS.

Found by the AST fuzzer (amd_msan) on an unrelated carrier pull request:
https://github.com/ClickHouse/ClickHouse/actions/runs/35659017389/job/106583430653

Co-Authored-By: Claude Opus 5 <[email protected]>
Drop the optimizeAggregationInOrder cross-reference from the Planner comment; it is in the commit message.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model over three rounds (engine: codex; 3 findings), plus my
own cold review of the resulting tree in each round (3 findings), adjudicated together. The final
round of both reviews, over the tree published here, found nothing.

# Sev Finding Verdict Evidence / action
1 ⚠️ The regression test's behavioural cases stop discriminating when the functional-test randomizer picks max_threads = 1, which also removes the only coverage of the legacy-planner guard (tests/queries/0_stateless/05237_aggregation_in_order_with_totals_overflow_row.sql) AGREE, fixed Raised independently by both reviews. AggregatingStep.cpp:572-585 builds the info-losing tail only for more than one stream; the single-stream tail is FinalizeAggregatedTransform, which re-attaches the missing info, and tests/clickhouse-test:1762 randomizes max_threads to randint(1, 3). The test now pins max_threads. Verified on a binary with only the legacy guard reverted: unpinned the revert went undetected ([ OK ]), pinned the assertion fires.
2 ⚠️ Pinning max_threads is not sufficient: max_threads_min_free_memory_per_thread can lower the effective thread count to one under memory pressure, which restores the same silent pass AGREE, fixed The setting defaults to 1 GiB (Settings.cpp:386-396), and getMaxThreadsForAvailableMemoryImpl (Common/MemoryTrackerUtils.cpp:83-104) lowers the count to (hard_limit - tracked) / 1 GiB, floor one. That clamped value is the stream count on both paths the test covers (PlannerJoinTree.cpp:1712-1714 and InterpreterSelectQuery.cpp:797-798), and it never writes back to the setting, so a system.query_log reading of max_threads cannot detect it. The test now also pins the limiter off, which is what 02493_max_streams_for_merge_tree_reading.sql, 01556_explain_select_with_union_query.sql and 02343_aggregation_pipeline.sql do for the same reason.
3 ❌ The guards still allow in-order aggregation to ignore a nonzero max_rows_to_group_by when no overflow row is requested (for example group_by_overflow_mode = 'throw'), so every nonzero limit should be rejected in both forced paths and in optimizeAggregationInOrder DISAGREE Two steps of that scenario do not hold. The limit is consulted on the merge stage of the forced in-order path: MergingAggregatedBucketTransform::transform calls Aggregator::mergeBlocks (MergingAggregatedMemoryEfficientTransform.cpp:453), which calls checkLimits at Aggregator.cpp:5293 and throws TOO_MANY_ROWS at Aggregator.cpp:3013 in throw mode; the cited evidence covers only the partial stage, and no run is shown for the claimed result. And the change cannot affect that behaviour either way: it only ever removes an in-order plan, never adds one, so a query with a nonzero limit and no overflow row is planned exactly as before. The in-tree guard this change mirrors, optimizeReadInOrder.cpp:1818-1822, is keyed on overflow_row alone by design (c5f93eb1081de); widening it would disable optimize_aggregation_in_order for every query that merely sets a group-by limit, which is a behaviour change with no reported defect and outside this change's scope.
4 💡 Three further AggregatingStep construction sites were not enumerated AGREE, no change needed PlannerCorrelatedSubqueries.cpp:928, LazyReadReplacingFinalSource.cpp:298 and the Cascades rule at AggregationPushdown.cpp:627 all pass empty sort descriptions, and inOrder() is !sort_description_for_merging.empty() (AggregatingStep.h:87), so none of them can build an in-order step. All inert.
5 💡 makeDistributed's in-order refusal (makeDistributed.cpp:325-333) no longer fires for these queries AGREE, no change needed Nothing new becomes distributable: the Cascades aggregation rules independently require max_rows_to_group_by == 0 (AggregationPushdown.cpp:255, AggregationImplementations.cpp:69 and :287), which no overflow-row query satisfies. make_distributed_plan is also off by default.

Also noticed while reviewing, and deliberately not raised further: the header conformance back-fill in
ISimpleTransform::work discards chunk_infos, which is what turns the empty merge product into an
info-less chunk here. No consumer is reachable with an info-less chunk once this change is in (the only
producer of an empty() chunk carrying an AggregatedChunkInfo is the in-order
FinishAggregatingInOrderAlgorithm::prepareToMerge, and every other consumer returns early on zero
rows), so there is no user-reachable consequence left to fix.

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

Session id: cron:clickhouse-review-slot-10:20260922-084100

@clickhouse-gh clickhouse-gh Bot closed this Sep 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on a Debug build, no fuzzer and no randomization: four single-row parts, WHERE sipHash64(v) = 0, GROUP BY t WITH TOTALS with totals_mode='after_having_auto', max_rows_to_group_by=1000, group_by_overflow_mode='any', force_aggregation_in_order=1. Load-bearing by leave-one-out: the forced setting, >= 2 parts, and a filter that reads every part and matches no row.
b Root cause explained? Those settings set overflow_row, so TotalsHavingTransform demands an AggregatedChunkInfo on every chunk (and tests it before its own if (!chunk) return;). Aggregation in order never emits the is_overflows chunk (its partial stage calls Aggregator::executeOnBlockSmall, which passes overflow_row = nullptr), yet the force_aggregation_in_order branch of each planner ignored overflow_row; with >= 2 parts the all-empty in-order merge product then loses its chunk info to the header conformance back-fill in ISimpleTransform::work and line 160 throws.
c Fix matches root cause? Yes, at the layer that owns overflow_row: the plan that cannot serve the query is no longer built, so the query runs on the hash path that does emit the overflow row. Silencing the assertion instead would leave the query on a path that cannot produce the overflow row it asked for, trading a loud LOGICAL_ERROR for a silently missing one.
d Test intent preserved / new tests added? New test only, nothing weakened: 05237_aggregation_in_order_with_totals_overflow_row, six arms, each measured non-vacuous in isolation, with max_threads and max_threads_min_free_memory_per_thread pinned so that neither CI randomizing the thread count down to 1 nor the free-memory clamp lowering it under memory pressure can make the behavioural arms vacuous (verified by re-running them unpinned, once at one thread and once with the clamp forced, where they silently match the reference).
e Both directions demonstrated? Yes, with both Build-IDs asserted: without the fix the repro aborts with the exact CI signature and the pipeline pin reports 0; with it the query returns an empty result plus the TOTALS row and the pin reports 1.
f Fix is general across code paths? Yes. The force_aggregation_in_order branch of BOTH planners is guarded (the analyzer route the fuzzer took, and the old analysis reached through a mutation scalar subquery, which reproduced the identical assertion). Measured not exposed: the optimizer route (guarded since c5f93eb), the old-analyzer optimize_aggregation_in_order branch, the projection construction site (a projection SELECT cannot carry WITH TOTALS), AggregatingStep::deserialize, and ReadFromRemote::enforceAggregationInOrder, which needs inOrder(). WITH ROLLUP is covered by the same predicate and has its own arm.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A by construction: a boolean plan-shape predicate with no column, type, Nullable/LowCardinality/Array/Map/Const or Replicated dimension. The settings axis is covered: one arm pins the overflow_row = false direction, another the WITH ROLLUP modifier.
h Backward compatible? Yes. No new setting and no changed default, so no SettingsChangesHistory.cpp entry is owed. The only affected queries are those that today raise this LOGICAL_ERROR.
i Invariants and contracts preserved? The invariant is "an AggregatingStep whose params.overflow_row is true is never built in order". The guard only narrows one local bool whose whole effect is to install the two sort descriptions and the step's explicit-sorting flag, so no error or early-return path changes, and TotalsHavingTransform's precondition is satisfied rather than relaxed.

Also run: 58 tests across the TOTALS / overflow-row / aggregation-in-order families (45 OK; the 13 failures fail identically on the unpatched binary, all Connection refused to addresses this local config does not bind), 02515_projections_with_totals OK, unit_tests_dbms --gtest_filter='*Aggregating*:*Aggregat*' 67/67, and 50/50 runs of the new test both with and without settings randomization.

Session id: cron:clickhouse-impl-slot-5:20260922-081502

@clickhouse-gh clickhouse-gh Bot reopened this Sep 22, 2026
@groeneai
groeneai requested review from nihalzp and novikd September 22, 2026 09:13
@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1e41ef1]

Summary: ✅


AI Review

Summary

The planner now disables forced aggregation in order when an aggregation overflow row is required, and AggregatingStep::deserialize rejects the same invalid combination from serialized plans. The prior inline finding is addressed; no new actionable findings remain. The added stateless regression passes in the Fast test report for the reviewed head. Review covered the current diff and surrounding code; no local build or tests were run.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Sep 22, 2026
Comment thread src/Planner/Planner.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1e41ef109 with master 58f152aee (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, 40 s compile time in total, 8 of them have a recent master baseline.

Job report

AggregatingStep::deserialize rebuilds overflow_row (flag bit 2) and the in-order
sort descriptions (bit 32) independently, and neither the AggregatingStep
constructor nor deserialize cross-checks them, so the combination the planner now
refuses was still accepted when the plan came off the wire instead of being built
locally. A deserialized plan is not planned on the receiving node, so nothing else
downstream declines it.

Measured on two servers, the initiator one commit behind this branch and the
receiving server carrying it with process_query_plan_packet enabled: a
serialize_query_plan = 1 query whose shipped fragment holds both the in-order
Aggregating and the TotalsHaving (EXPLAIN distributed = 1 shows the pair) reached
'Chunk should have AggregatedChunkInfo in TotalsHavingTransform.' at
TotalsHavingTransform.cpp:160 on the receiving server, which in these debug builds
terminated it. With this commit the same query returns INCORRECT_DATA and the
server stays up.

The check reads the flags rather than the reconstructed step so that it sits with
the two version gates already in deserialize, which reject invalid flag
combinations the same way. Enforcing the invariant in the AggregatingStep
constructor instead would not cover the optimizer: optimizeAggregationInOrder
turns a step in-order through applyOrder after construction, so a constructor
check cannot see that path.

There is no serialize-side twin, unlike the two version gates: a node running this
code cannot build the pair, so a check there would only guard already-corrupt
state.

Only a gtest can present the offending stream, because a server that refuses to
build the pair also never serializes it, so the coverage extends the existing
AggregatingStep serialization gtest rather than the stateless test.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). label Sep 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e24a610

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
AST fuzzer (amd_debug, targeted, old_compatibility) / Segmentation fault (STID: 1635-49b2) null query-tree deref in StorageDistributed::getOptimizedQueryProcessingStageAnalyzer (StorageDistributed.cpp:636), reached from the old interpreter: ExecuteScalarSubqueriesVisitor -> InterpreterSelectWithUnionQuery -> InterpreterSelectQuery::getSampleBlockImpl -> getQueryProcessingStage #121418 (mine, open)
Stress test (arm_asan_ubsan) / UndefinedBehaviorSanitizer: undefined behavior (STID: 6440-63f0) the UBSan flavour of the same defect, member call on null pointer of type 'DB::TypePromotion<DB::IQueryTreeNode>' at StorageDistributed.cpp:636:54 #121418 (mine, open)
Mergeable Check, PR praktika rollups of the two rows above, no independent leaf #121418, as above

Neither row belongs to this diff. The crash path runs through getSampleBlockImpl at InterpreterSelectQuery.cpp:1354; this PR's only change to that file is at executeAggregation (line ~3150), adding && !overflow_row to a force_aggregation_in_order condition that is off by default, and it cannot reach a StorageDistributed stage decision. Measured over 30 days, both signatures are master-side and begin on 2026-09-21 with zero rows before it: STID 1635-49b2 on 14 distinct PRs plus 3 true-master runs, STID 6440-63f0 on 3 distinct PRs.

Attribution note, since a SIGSEGV is never written off as noise here: the stack on this head is the ExecuteScalarSubqueriesVisitor producer that #121418 is scoped to, checked frame by frame rather than matched on the STID alone. A second producer of the same crash site reaches it through interpretSubquery, which #121418 deliberately does not cover; that route is owned by #121639 (external, open) and is not the route taken here.

Session id: cron:our-pr-ci-monitor:20260923-010313

groeneai and others added 2 commits October 7, 2026 12:25
…r-overflow-row

# Conflicts:
#	src/Interpreters/InterpreterSelectQuery.cpp
Master now builds a scalar subquery with `InterpreterSelectQueryAnalyzer`
(`ExecuteScalarSubqueriesVisitor`), so a mutation's scalar subquery is
planned by `Planner` and the `Planner` guard covers it. What still reaches
`InterpreterSelectQuery::executeAggregation` is the projection machinery
and the AST arms of `EXPLAIN`, and a projection query cannot carry
`WITH TOTALS`, so `overflow_row` is never set there. The mutation arm of
the test stays: it still raises the logical error on master without the
`Planner` guard.

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

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4a7600b

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.

Every job that ran on this head passed (0 failed tests in CIDB). The red comes only from 3 jobs that never ran.

Check / test Reason Owner / fixing PR
Parser memory check, Storage memory check, Build profile diff (Mergeable Check: Failed: 0, Dropped: 3) infra: GitHub Actions outage on 2026-10-07 (githubstatus critical incidents at 15:14Z and 16:52Z). GitHub never assigned a runner, so praktika marked the jobs DROPPED (Job did not finish, GitHub reported [abandoned]) a fix task is created (it re-runs the lost jobs on a fresh head)

Session id: cron:our-pr-ci-monitor:20261007-180301

…r-overflow-row

`src/Planner/Planner.cpp` was split on master (f6de30c moved `addAggregationStep`
into `src/Planner/PlannerSteps.cpp`). Resolved by taking master's Planner.cpp
and porting the `!aggregator_params.overflow_row` conjunct to PlannerSteps.cpp.

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

can be tested Allows running workflows for external contributors comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant