Skip to content

Fix wrong aggregates from limit pushdown when ORDER BY is a strict prefix of GROUP BY - #117573

Merged
fm4v merged 10 commits into
masterfrom
fix-agg-in-order-limit-prefix
Sep 20, 2026
Merged

fm4v merged 10 commits into
masterfrom
fix-agg-in-order-limit-prefix

Conversation

@thevar1able

@thevar1able thevar1able commented Sep 1, 2026 •

Copy link
Copy Markdown
Member

Since 26.7, optimize_aggregation_in_order_limit pushes the query LIMIT into in-order aggregation when the ORDER BY is a prefix of the GROUP BY sort description. Each AggregatingInOrderTransform stream stopped as soon as it had emitted LIMIT groups, at a boundary of the full group key. When the ORDER BY is a strict prefix, a group that ties with the emitted ones on that prefix could be cut off in one stream while another stream still emitted its partial state, and the final sort could legally pick the partial group, returning a wrong aggregate value.

A stream now stops only at a boundary of the ORDER BY prefix: once LIMIT groups are emitted, it keeps consuming until the prefix columns change. Every stream then contains all rows whose prefix is at most its cutoff, all groups up to the smallest cutoff are complete, and there are at least LIMIT of them, so the dropped groups always sort strictly after enough complete groups. The optimization keeps working for a strict prefix. A stream may now emit more than LIMIT groups before it stops (everything up to the prefix boundary); the extra groups are discarded by the final LIMIT. When the prefix has few distinct values the stream reads to the end, which is the only correct option there. When the ORDER BY covers the whole GROUP BY key the behavior is unchanged.

Closes: #116849
Caused by: #104859

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):

Fix wrong aggregate values with optimize_aggregation_in_order_limit when the ORDER BY is a strict prefix of the GROUP BY key and a group's rows span multiple parts. In-order aggregation streams now stop early only at a boundary of the ORDER BY prefix. Closes #116849.


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

Version info

  • Merged into: 26.10.1.279-master (included in 26.10 and later)
  • Backported to: 26.9.1.1620, 26.8.10.5

…efix of GROUP BY

`optimize_aggregation_in_order_limit` installed the limit hint whenever the
query sort description was a prefix of the full group-by sort description.
Each in-order stream terminates early at a boundary in full group-key order,
so a group whose rows span multiple parts could be cut off in one stream while
another stream still emitted its partial state; since groups tied on the
strict prefix are interchangeable to the final sort, it could select a group
with an incomplete aggregate value. Require the sort description to match the
full group-by sort description instead.

Closes: #116849

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1a68387]

Summary: ✅


AI Review

Summary

This PR fixes the wrong-aggregate bug in optimize_aggregation_in_order_limit for queries whose ORDER BY is a strict prefix of the GROUP BY key by delaying each in-order stream's stop condition to an ORDER BY-prefix boundary. The transform-side fix looks sound, but the new stateless regression coverage is still nondeterministic under regular random-settings CI, so I would not merge it as-is.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/05055_aggregation_in_order_limit_order_by_prefix.sql:20-43,70-109,146-184] The new regression file still leaves optimize_read_in_order to clickhouse-test randomization. Existing in-order limit tests opt out of random settings for exactly this reason; if the runner flips optimize_read_in_order = 0, these queries fall off the in-order path, so the bug can pass undetected and the read_rows checks can fail spuriously. Suggested fix: add -- Tags: no-random-settings at the top of the file, or pin optimize_read_in_order = 1 everywhere the test is supposed to exercise the optimization.
Final Verdict

Changes requested: the implementation looks correct, but the regression test still does not prove the fix deterministically in CI.

LLVM Coverage Report

⚠️ No coverage measurement for commit 1a68387: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_7.profdata.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 1, 2026
@thevar1able
thevar1able marked this pull request as ready for review September 1, 2026 20:08
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1a68387db with master 6a2bc0c2f (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

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

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 4, 2026
@evillique evillique self-assigned this Sep 4, 2026
thevar1able and others added 4 commits September 4, 2026 15:15
…avior

The optimization now requires ORDER BY to match the full GROUP BY sort
description, not just a prefix. Update the setting description in
src/Core/Settings.cpp (the source of truth for the generated docs) and
the settings-history entry accordingly.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117573&sha=cbb50fbdc19fe16409b6ac9c122ce0a4b6adf263&name_0=PR
#117573

Co-Authored-By: Claude Fable 5 <[email protected]>
Bugfix validation reported that `05055_aggregation_in_order_limit_order_by_prefix`
passes on the master binary. The check was wrapped into `SELECT count() FROM (...)`,
and the outer query changes the plan: master runs the inner aggregation through the
`Top-K` aggregation path with a `Default` read instead of aggregation in order, so the
limit push-down never fires and the bug is hidden. Assert the aggregate value in the
projection of the query itself, which keeps the `Limit -> Sorting -> Aggregating`
in-order plan. Tiny `max_block_size` and `aggregation_in_order_max_block_bytes`, which
the test harness randomizes, also hide the bug, so pin them.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117573&sha=ee9ff177aee08cb1c09614b962c3e4f4843b4f1f&name_0=PR&name_1=Bugfix%20validation%20%28functional%20tests%2C%20amd64%29
PR: #117573
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
`SettingsChangesHistory` is versioned history: the 26.7 row must keep describing
the prefix semantics that 26.7 and 26.8 actually shipped. Record the tightening
as a `{true, true}` row under 26.9, so that `compatibility` with 26.7 or 26.8
does not restore the incorrect strict-prefix push-down. This follows the
precedent of `apply_row_policy_after_final` (25.10) and
`statistics_max_set_size_for_exact_selectivity_estimation` (26.6-26.9).

PR: #117573
@thevar1able
thevar1able marked this pull request as draft September 9, 2026 20:06
…BY` prefix boundary

Instead of rejecting the `LIMIT` push-down when the `ORDER BY` is a strict
prefix of the `GROUP BY` sort description, make the early termination correct
for that case. `AggregatingInOrderTransform` used to stop as soon as it had
emitted `limit_hint` groups, at a boundary of the full group key. A group that
ties with the emitted groups on the `ORDER BY` prefix could then be cut off in
one stream while another stream emitted its partial state, and the final sort
could legally pick that partial group (issue #116849).

Now a stream stops only when the next key differs from the current one in the
first `limit_prefix_columns` group-by columns, i.e. the columns the query is
ordered by. Every stream then contains all rows whose prefix is at most its
cutoff; all groups whose prefix is at most the smallest cutoff are complete,
and there are at least `limit` of them, so the groups a stream drops always sort
strictly after enough complete groups. The optimization pass passes the length
of the `ORDER BY` prefix along with the limit hint.

The settings documentation, the settings history and `04489` are restored to
the original prefix semantics. The regression test asserts the aggregate values
in the projection, since wrapping the query into a subquery changes the plan and
hides the bug, and also checks that the push-down still short-circuits reads
when the prefix has enough distinct values.

Closes: #116849
PR: #117573
… `group_by_key` path

When the input is sorted only by a prefix of the `GROUP BY` key, `AggregatingInOrderTransform`
keeps the groups of one run of the sorted columns in a hash table, and `cur_block_size` counts
those runs rather than groups. The early-stop check therefore compared the number of runs with
`limit_hint` and kept reading until `limit_hint` runs had passed, although a single run may
already hold more than `limit_hint` complete groups. Use the size of the hash table as the
number of groups accumulated for the current block on that path.

Add a test with a table sorted by `a` only and `GROUP BY a, b ORDER BY a LIMIT 5`: the stream now
stops after the first run of `a` and reads 32 rows instead of 128 of the 2000-row table.
`clickhouse-test` randomizes `max_threads` and `read_in_order_two_level_merge_threshold`.
With `max_threads = 1` and a threshold that does not exceed the number of parts, reading in
order merges the parts into a single stream before the aggregation, so there is only one
in-order stream and the bug from issue #116849 cannot occur. Found by running the test against
a build without the fix under randomized settings: 1 of 15 runs passed, and delta-debugging the
session settings of that run left exactly these two. Pin `max_threads = 2` in the correctness
queries and `read_in_order_two_level_merge_threshold` in the `read_rows` queries, whose expected
counts assume one stream per part.
@thevar1able
thevar1able marked this pull request as ready for review September 17, 2026 18:11
@clickhouse-gh clickhouse-gh Bot added comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). and removed comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Sep 17, 2026
@fm4v
fm4v added this pull request to the merge queue Sep 20, 2026
Merged via the queue into master with commit 583e079 Sep 20, 2026
178 checks passed
@fm4v
fm4v deleted the fix-agg-in-order-limit-prefix branch September 20, 2026 07:56
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 20, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 20, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 20, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 20, 2026
…en ORDER BY is a strict prefix of GROUP BY
clickhouse-gh Bot added a commit that referenced this pull request Sep 20, 2026
Backport #117573 to 26.9: Fix wrong aggregates from limit pushdown when ORDER BY is a strict prefix of GROUP BY
fm4v added a commit that referenced this pull request Sep 20, 2026
Backport #117573 to 26.8: Fix wrong aggregates from limit pushdown when ORDER BY is a strict prefix of GROUP BY
strtgbb pushed a commit to Altinity/ClickHouse that referenced this pull request Sep 21, 2026
…ushdown when ORDER BY is a strict prefix of GROUP BY
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.7-must-backport v26.8-must-backport

Projects

None yet

6 participants