Skip to content

Fix wrong results of the trivial GROUP BY LIMIT optimization with DISTINCT, QUALIFY, window functions or arrayJoin - #114695

Merged
alexey-milovidov merged 4 commits into
masterfrom
trivial-group-by-limit-projection-guards
Aug 15, 2026
Merged

alexey-milovidov merged 4 commits into
masterfrom
trivial-group-by-limit-projection-guards

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 13, 2026 •

Copy link
Copy Markdown
Member

Closes: #114693
Related: #114690

The trivial GROUP BY ... LIMIT optimization (optimize_trivial_group_by_limit_query, default true since 26.5) caps the aggregation at LIMIT + OFFSET distinct keys, which is only sound when the LIMIT directly cuts the produced groups. The shape check missed four constructs that consume or filter the groups between the aggregation and the LIMIT, and each of them returned wrong results with default settings (verified on master; reproducers in the issue and in the added test):

  • DISTINCT collapses the projected groups: SELECT DISTINCT intDiv(k, 25000) FROM t GROUP BY k LIMIT 3 returned 1 row instead of 3.
  • A window function in the projection is evaluated over all groups (hasWindow only catches the named WINDOW clause, not an inline OVER ()): SELECT count() OVER () FROM t GROUP BY k LIMIT 5 returned ~100 instead of 100000.
  • arrayJoin in the projection can drop rows (empty arrays), so the kept groups may produce fewer rows than the LIMIT while more groups exist: 1 row instead of 10.
  • QUALIFY filters the groups after the aggregation: 0 rows instead of 10 (a QUALIFY on plain group keys alone is pushed down below the aggregation and was not affected; a window function in the projection keeps it in place).

The pass now skips these shapes. #114690 contains the same guards as part of a shared shape-check helper; whichever merges second needs a trivial conflict resolution, and this separate pull request keeps the wrong-results fix minimal and backportable on its own.

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

Fixed wrong results of the trivial GROUP BY ... LIMIT optimization (setting optimize_trivial_group_by_limit_query) for queries with DISTINCT, QUALIFY, window functions, or arrayJoin in the projection: these consume or filter the groups after the aggregation, so capping the aggregation at LIMIT + OFFSET keys could return too few rows or wrong values. The optimization no longer applies to such queries.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.8.1.1479 (included in 26.8 and later)
  • Backported to: 26.7.4.55, 26.6.3.60, 26.5.7.60

The trivial `GROUP BY ... LIMIT` optimization
(`optimize_trivial_group_by_limit_query`, default `true`) caps the
aggregation at `LIMIT + OFFSET` distinct keys, which is only sound when
the LIMIT directly cuts the produced groups. The shape check missed four
constructs that consume or filter the groups between the aggregation and
the LIMIT, and each of them returned wrong results with default
settings:

- `DISTINCT` collapses the projected groups: `SELECT DISTINCT
  intDiv(k, 25000) FROM t GROUP BY k LIMIT 3` returned 1 row instead
  of 3.
- A window function in the projection is evaluated over all groups
  (`hasWindow` only catches the named `WINDOW` clause, not inline
  `OVER ()`): `SELECT count() OVER () FROM t GROUP BY k LIMIT 5`
  returned ~100 instead of 100000.
- `arrayJoin` in the projection can drop rows, so the kept groups may
  produce fewer rows than the LIMIT while more groups exist: 1 row
  instead of 10.
- `QUALIFY` filters the groups after the aggregation: 0 rows instead
  of 10 (a `QUALIFY` on plain group keys alone is pushed down below
  the aggregation and was not affected; a window function keeps it in
  place).

The pass now skips these shapes, keeping the optimization to queries
where the first `LIMIT + OFFSET` groups are a valid unspecified subset
of the result.

Closes: #114693

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@mintlify

mintlify Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Aug 13, 2026, 8:50 PM

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [29a48e9]

Summary: ✅


AI Review

Summary

This PR tightens OptimizeTrivialGroupByLimitPass so it no longer applies when post-aggregation operations (DISTINCT, QUALIFY, inline window functions, or projection arrayJoin) can change the row set before LIMIT. The current PR head matches that contract, the earlier autogenerated-docs issue is resolved by keeping the source-of-truth update in src/Core/Settings.cpp, and the added stateless test covers each wrong-result reproducer. I did not find remaining blockers or major issues in the current diff.

Final Verdict

✅ No remaining review findings on the current PR head.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 13/13 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 29a48e919 with master 6d0a17390 (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
Binary Master PR Δ
programs/clickhouse-stripped 693.26 MiB 690.24 MiB -3.02 MiB (-0.44%)

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 units

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

Job report

@alexey-milovidov alexey-milovidov left a comment

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.

Yes, this is good.

@alexey-milovidov alexey-milovidov self-assigned this Aug 15, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 15, 2026
Merged via the queue into master with commit 2926be2 Aug 15, 2026
181 checks passed
@alexey-milovidov
alexey-milovidov deleted the trivial-group-by-limit-projection-guards branch August 15, 2026 21:56
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 15, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 18, 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 Aug 18, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 18, 2026
Backport #114695 to 26.7: Fix wrong results of the trivial GROUP BY LIMIT optimization with DISTINCT, QUALIFY, window functions or arrayJoin
PedroTadim added a commit that referenced this pull request Aug 18, 2026
Backport #114695 to 26.6: Fix wrong results of the trivial GROUP BY LIMIT optimization with DISTINCT, QUALIFY, window functions or arrayJoin
PedroTadim added a commit that referenced this pull request Aug 18, 2026
Backport #114695 to 26.5: Fix wrong results of the trivial GROUP BY LIMIT optimization with DISTINCT, QUALIFY, window functions or arrayJoin
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
…GROUP BY LIMIT optimization with DISTINCT, QUALIFY, window functions or arrayJoin
alexey-milovidov added a commit that referenced this pull request Aug 24, 2026
…uard

The guard checked the stored `FunctionNode` name literally, so with
`normalize_function_names = 0` the case-insensitive alias `unnest` reached the
query tree unchanged and bypassed it, reproducing the wrong results the guard
exists to prevent. Compare canonical names via `getFunctionCanonicalNameIfAny`
instead, as requested by the automated review.

Also remove the duplicated window/`arrayJoin` check from
`OptimizeTrivialGroupByLimitPass` (the shared `getTrivialGroupByLimit` performs
it), and trim test 04837 to the planner-side subquery forms plus the new
`unnest` case: the top-level `INSERT ... SELECT` forms are covered by 04840,
which came in with the backportable guards of #114695 that have merged into
master since.
VighneshPath pushed a commit to VighneshPath/ClickHouse that referenced this pull request Sep 16, 2026
…GROUP BY LIMIT optimization with DISTINCT, QUALIFY, window functions or arrayJoin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.5-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

The trivial GROUP BY LIMIT optimization returns wrong results with DISTINCT, QUALIFY, window functions or arrayJoin in the projection

5 participants