Skip to content

Count a single uniqExact in order and choose the aggregation order after projections - #129508

Merged
Algunenano merged 6 commits into
ClickHouse:masterfrom
Algunenano:uniq-exact-in-order
Nov 12, 2026
Merged

Algunenano merged 6 commits into
ClickHouse:masterfrom
Algunenano:uniq-exact-in-order

Conversation

@Algunenano

@Algunenano Algunenano commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

With optimize_aggregation_in_order = 1, a single uniqExact (or count(DISTINCT)) without GROUP BY over a table sorted by its argument now counts the changes of the sorted values instead of keeping them in a set, so its memory does not grow with the number of distinct values. This gives back the bounded memory that the count_distinct_optimization rewrite to an in-order GROUP BY provided, raised in the review of the removal of that setting.

With several threads, the read is split into layers by the sorting key (ReadFromMergeTree::readByLayers, as for joins by shards), so that no value is in two layers, and the layers are counted in parallel. When the read cannot be split (a float argument, a function of the key, FINAL), several streams would have to be merged into one on a single thread, so the read is not requested in order and the radix partitioned uniqExact is used as before. Floats are compared by bits as in uniqExact: the runs of zeros and NaNs are passed to the uniqExact itself.

20 million distinct UInt64, one part, 16 threads: 17 ms and 1.2 MiB, against 24 ms and 266 MiB for the radix partitioned uniqExact. On one thread: 142 ms and 143 KiB against 203 ms and 158 MiB. With many overlapping parts it is slower than radix (each layer merges all the parts), but memory stays bounded.

The first commit also moves the choice of the aggregation order after the normal projections, for GROUP BY as well: a read in order rules the projections out, so GROUP BY x ... WHERE y = ... over a table with a projection sorted by y read the whole table (7813 granules) instead of one granule of the projection. A projection that reads fewer granules now wins even when it is not sorted by the GROUP BY key, which is documented in the setting. For reads by parallel replicas the order is still decided once from the table, before the projections, so that all replicas read in the same order.

Related: #129307 (comment)
Related: #129307

Changelog category (leave one):

  • Improvement

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

With optimize_aggregation_in_order = 1, uniqExact(x) and count(DISTINCT x) without GROUP BY over a table sorted by x count the values in the order of the table, in parallel over ranges of the key, without keeping them in memory. The order of aggregation is also chosen after the projections, so a projection that reads fewer granules is no longer skipped because of optimize_aggregation_in_order.


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

Version info

  • Merged into: 26.11.1.2110-master (included in 26.11 and later)

Algunenano and others added 2 commits November 5, 2026 15:35
`optimizeAggregationInOrder` requested a read in order before the normal
projections were considered, and a read in order rules them out: with
`optimize_aggregation_in_order = 1`, a `GROUP BY` over a table with a
projection matching a selective filter read the whole table instead of a
few granules of the projection. Decide the order after the projections,
as `optimizeReadInOrder` does for `ORDER BY`.

For a read by parallel replicas, keep deciding it before the projections,
once, from the table: a replica can read the table where another one uses
a projection, and all of them have to read in the same order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `optimize_aggregation_in_order = 1`, a single `uniqExact` (or
`count(DISTINCT)`) without `GROUP BY` over a table sorted by its argument
counts the changes of the sorted values instead of keeping them in a set,
so its memory does not grow with the number of distinct values. This
replaces the bounded memory that the `count_distinct_optimization`
rewrite to an in-order `GROUP BY` gave.

With several threads, the read is split into layers by the sorting key
(`ReadFromMergeTree::readByLayers`), so that no value is in two layers,
and the layers are counted in parallel. When it cannot be split (a float
argument, a function of the key, `FINAL`), several streams would be merged
into one on a single thread, so the read is not requested in order and
the usual aggregation is used. Floats are compared by bits, as in
`uniqExact`: the runs of zeros and NaNs are passed to the `uniqExact`
itself.

20 million distinct values, one part, 16 threads: 17 ms and 1.2 MiB,
against 24 ms and 266 MiB for the radix partitioned `uniqExact`.

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

clickhouse-gh Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [264c40f]

Summary: ✅


AI Review

Summary

Reviewed #129508 at 264c40f1cb54d6e90cae0cd3531863ceef2959bd, including the complete prior discussion and current code. The PR counts a single uniqExact over ordered input, partitions eligible reads into disjoint key ranges, and chooses aggregation order after normal projections while preserving the early decision for parallel replicas. No actionable findings. Using the PR's fast-test binary, both 05507_uniq_exact_in_order and 05508_aggregation_in_order_normal_projection matched their references. Additional differential checks passed for reverse sorting, overlapping partitions, fixed keys, nullable expressions, float runs crossing chunk boundaries, and both forms of ARRAY JOIN.

Missing context / blind spots
  • ⚠️ The parallel-replica regression 05509_parallel_replicas_aggregation_in_order_projection_on_follower was reviewed but not executed locally; its runtime validation requires CI's configured replica cluster and failpoint-enabled binary. The full CI suite was still pending during this review.
Final Verdict

✅ Approve. No new inline comments were posted.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Nov 5, 2026
Write the NaNs and -0.0 of `05507_uniq_exact_in_order` by their bits:
whether `nan` and `0/0` give different bits depends on the build. Tag
`05509_parallel_replicas_aggregation_in_order_projection_on_follower`
`no-fasttest`, as it uses a fail point.

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

clickhouse-gh Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 264c40f1c with master 28cd3f355 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

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.

Object file sizes ⚠️

30 object files changed (+514.44 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/AggregatingStep.cpp.o 624.62 KiB 1.02 MiB +416.66 KiB (+66.71%)
src/CMakeFiles/dbms.dir/Processors/Transforms/UniqExactInOrderTransform.cpp.o new 55.32 KiB +55.32 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp.o 339.59 KiB 378.16 KiB +38.57 KiB (+11.36%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

104 translation units recompiled, 882 s compile time in total, 103 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×0.94 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -57.3 s (-6%) in total before that adjustment.

Job report

Algunenano and others added 3 commits November 6, 2026 13:54
The flaky check timed out on `OPTIMIZE TABLE ... FINAL` of the 1M row tables with a projection. Use 10x less data and limit the random granularity settings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeTree.cpp
Under the flaky check, `OPTIMIZE TABLE t_projection FINAL` took about 60 seconds per run, which made the test exceed 180 seconds. Neither `OPTIMIZE` is needed: the projection is built on insert, and the count in order does not need a single part.

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

@Algunenano Algunenano 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.

I'm happy with this PR. It covers a case that's not used by default, but it should help in case we decided to use optimize_aggregation_in_order by default

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants