Skip to content

Fix wrong optimize_aggregation_in_order results on a reverse sorting key - #112200

Merged
nihalzp merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-aggregation-in-order-reverse-key
Sep 4, 2026
Merged

nihalzp merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-aggregation-in-order-reverse-key

Conversation

@groeneai

@groeneai groeneai commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #111901

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

Fixes silently wrong GROUP BY results with optimize_aggregation_in_order = 1. Groups were merged into one another and aggregate values were wrong when the matched sorting-key prefix contained a reverse (DESC) column, and, independently of reverse keys, when a group-by key was a negative monotonic function of a Float sorting-key column, around the NaN boundary. This affected a single MergeTree table and a Merge table over such tables. For a Merge table whose underlying tables read the matched prefix in opposite physical directions, aggregation in order is now declined because a single stream direction cannot describe both.

Description

buildInputOrderFromUnorderedKeys (src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp)
is the InputOrder builder for GROUP BY / DISTINCT / LIMIT BY. It described the stream wrongly
in two independent ways, and AggregatingInOrderTransform compares keys with a direction-aware and
nulls-aware less inside std::upper_bound, so a wrong description makes it miss the key change and
collapse a whole run into one group with wrong aggregate values.

  1. It never consulted KeyDescription::reverse_flags, hardcoding direction 1, while the read side
    emits direction * -1 for a reversed key column. The ORDER BY sibling builder in the same file
    already multiplies in a reverse_indicator; that asymmetry is the bug. Any reversed column in the
    matched prefix is affected, not only the mixed-direction key from the issue.
  2. nulls_direction was left at its default 1 while the direction carried the monotonicity. A
    sorting-key column is stored ASC NULLS LAST forward and DESC NULLS FIRST reversed, and NULL/NaN are
    fixed points of a monotonic match, so on a negative monotonic match the advertised null placement
    contradicts the stream. This half reproduces on a plain forward key with no reverse flag at all.

A Merge table whose children read the matched prefix in opposite physical directions cannot be
described by any single direction, so aggregation in order is now declined there. The decline is
recorded on the file-local InputOrder struct and consumed only in the AggregatingStep branch;
DISTINCT and LIMIT BY compare for equality only and keep their optimization.

No query loses the optimization otherwise. ORDER BY a DESC NULLS FIRST ... LIMIT n over a reversed
key now additionally matches the LIMIT push-down (64 rows read against 1000).

Recovering aggregation in order for the disagreeing Merge needs per-child direction normalization in
ReadFromMerge and AggregatingStep; happy to follow up separately if wanted.

Measurements and test accounting

Before this PR, optimize_aggregation_in_order off against on:

sorting key GROUP BY off on
(a, b DESC) a, b 40 / 520 8 / 168
(a DESC) a 4 1
(a, b DESC, c) a, b 8 4
(a DESC, b) a, b 40 2
(x DESC, y DESC), GROUP BY negate(y), negate(x) 16 2
ReplacingMergeTree ... FINAL, (a, b DESC) a, b 40 / 520 4 / 98
Float64 + NaN, x DESC, GROUP BY negate(x) 6 1
Float64 + NaN, x, GROUP BY negate(x) 6 5
(a, b) (control) a, b 40 40
(a, b DESC), prefix only (control) a 4 4

Nullable keys composed with a monotonic function are not eligible for aggregation in order at all,
so only the Float/NaN shapes are reachable for defect 2.

Every assertion in 04651_aggregation_in_order_reverse_key compares the query at
optimize_aggregation_in_order = 1 against the same query at 0, so no result constant is hardcoded.
The 40 reference lines are 21 value oracles, one read_rows push-down oracle, and 18 plan assertions
(17 positive eligibility pins plus one inverse pin for the Merge decline). A master-HEAD binary fails
15 of the 40; a binary carrying only the reverse-flag half fails the 4 null-placement lines. The
positive pins hold on a pre-fix binary by design: they assert the query is eligible, not that the fix
is present, which is what makes them useful against future rot. 50 randomized runs pass. The
read-in-order / aggregation-in-order / distinct-in-order / limit-by-in-order sweep gives an identical
failure set on this build and on a reverse-flag-only build (74 pass / 17 fail both, all pre-existing
local sandbox configuration failures such as the missing test.hits dataset).

The reverse-flag half was written and then reverted inside PR #105135 (ff21d560c6a560, reverted by
d0214678ad6d28), which went on to delete the sorted merge from LimitByStep entirely. Reading the
commit sequence, it was dropped as no longer needed by that PR rather than as wrong; the GROUP BY
consumer still performs a direction-aware merge and was never covered by its tests. That is a
reconstruction from the commits, not a quote.

ReadFromObjectStorageStep is fixed by the same change; it already builds its InputOrderInfo
honouring reverse_flags, so the two now agree. That path is reasoned, not measured.


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

groeneai added 3 commits July 27, 2026 17:08
buildInputOrderFromUnorderedKeys, the InputOrder builder used by GROUP BY,
DISTINCT and LIMIT BY, never consulted KeyDescription::reverse_flags. It
hardcoded current_direction = 1 and emitted that into the sort_description it
returns, while the ORDER BY sibling builder in the same file computes a
reverse_indicator from reverse_flags and multiplies it in.

The read side does honour the flags, so the parts arrive with a reversed key
column descending while AggregatingStep is handed a description claiming
ascending. AggregatingInOrderTransform then runs a direction-aware less inside
std::upper_bound, never finds a new group boundary, and collapses a whole run
into a single group with a wrong aggregate value. This affects any reversed
column inside the matched key prefix, not just the mixed-direction key from the
report, and it affects a Merge table over such tables as well.

For a Merge table whose children read the matched prefix in opposite physical
directions the direction is not knowable as a single value:
ReadFromMerge::requestReadingInOrder pushes one InputOrderInfo into every
child, each child applies its own reverse_flags, and AggregatingStep hands the
same description to every transform. Aggregation in order is therefore declined
for that case only. DISTINCT and LIMIT BY keep the optimization there: their
transforms compare compareAt(...) != 0, so they are direction-insensitive and
correct today.

The same change was written and then reverted inside PR ClickHouse#105135 (ff21d56
added it, d021467 reverted it with no rationale). Reading the commit
sequence, it was dropped because that PR removed the sorted merge it protected
an hour later (c50a62a), i.e. as no longer needed rather than as
incorrect; the GROUP BY consumer still performs a direction-aware merge and was
never covered by that PR's tests.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&name_0=MasterCI

Closes ClickHouse#111901
…test

Review round r1: test file only, no production change.

Every carrier assertion in 04651 compared the query at optimize_aggregation_in_order = 1
against the same query at 0. That oracle form needs no hardcoded constants, but it is blind
to the optimization silently not being applied: if a shape ever becomes ineligible for
aggregation in order, both sides take the fallback path, the comparison still returns 1, and
the carrier stops being covered with nothing failing. Only one of the single-table shapes had
an EXPLAIN PIPELINE engagement assertion, and case 9's DISTINCT/LIMIT BY controls had none at
all -- result equality there holds whether or not those consumers are optimized, so the
control could not detect the over-correction it exists to detect.

Add an engagement assertion beside every carrier and beside both siblings: a single reversed
column, a reversed column inside a longer prefix, a reversed leading column, the negative
monotonic match, ReplacingMergeTree FINAL, and case 9's DistinctSortedStreamTransform and
LimitBySortedStreamTransform. These are eligibility pins, not defect pins: they hold on a
pre-fix binary and stay green under both mutants, which is what makes them useful against
future rot rather than a restatement of the fix.

Also pin the LIMIT push-down the direction fix newly enables.
optimizeLimitForAggregationInOrder matches the LimitStep's sort description against the
aggregation's group-by description with SortDescription::hasPrefix, and
SortColumnDescription::operator== compares direction, so with the old sign a reversed key
never matched. The new read_rows oracle measures 64 rows read with the push-down against 1000
without on the fixed build, and no reduction at all on a pre-fix build. The NULLS FIRST in
that query is load-bearing and carries a comment saying so: operator== also compares
nulls_direction, which the group-by description leaves at its default +1 while a bare
ORDER BY k DESC yields -1, so without it the descriptions could not match regardless of the
direction fix. (That nulls_direction asymmetry is pre-existing, applies to ascending keys too,
and is deliberately out of scope.)

Finally, record that case 6d's LimitBySortedStreamTransform assertion is load-bearing for
case 6b: 6b pins the decline with a "= 0" plan assertion, which alone cannot distinguish
"declined by the new guard" from "never eligible at all". 6d proves that same Merge IS
eligible for read-in-order, so a cleanup deleting it as redundant sibling coverage would
silently disarm 6b.

Reference grows 20 -> 28 lines, all 1. No assertion was removed or weakened.
Master-HEAD moves 10 of the 28 lines; the fixed build moves none; 50/50 randomized runs OK.
Each value assertion in this test compares the query at
optimize_aggregation_in_order = 1 against the same query at 0, which is a
good oracle for the result but blind to the optimization silently not being
applied: both sides then take the same fallback path and compare equal. Three
assertions that the test advertises as controls rested on that comparison
alone, so they would have kept passing if the thing they control for had
stopped happening:

- case 6d promises that both DISTINCT and LIMIT BY over the mixed-direction
  Merge stay optimized, but only LIMIT BY was pinned. The two are independent
  optimizer entrypoints (buildInputOrderInfo(DistinctStep &) gated by
  canImproveOrderForDistinct, versus buildInputOrderInfo(LimitByStep &) gated
  by getCollationAwareSortPrefixInColumns), so pinning one says nothing about
  the other.
- case 7 (all-ascending key, "no over-correction") would see the
  over-correction it exists to detect as the optimization silently not
  engaging, which is the one thing an oracle comparison cannot see.
- case 8 (prefix-only GROUP BY a over the reversed key) is a different query
  from the existing non-vacuity guard, which uses GROUP BY a, b, so that pin
  did not cover it.

Adds one EXPLAIN PIPELINE engagement assertion to each, bringing the
reference from 28 to 31 lines. All three were measured before being committed
and read 1 on the fixed build; the transform names asserted are the ones the
pipeline actually prints.

These are eligibility pins, not defect pins, so they must hold on a pre-fix
binary as well. Measured: all fifteen engagement pins read 1 on a master-HEAD
binary and under both mutants (direction fix disarmed, decline disarmed),
while only the value oracles move. No production source is touched by this
commit, so the build is bit-identical.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 review rounds, 2 fix rounds, 22 findings adjudicated)

Before opening this PR I reviewed it with an independent model that does not see the
implementation reasoning, then adjudicated every finding against the code. Two fix rounds were
bounced back and implemented; the third round came back clean. Recording it here so the history
is visible rather than hidden.

Rounds: Gate A (approach) 2 rounds, 1 finding. Review 3 rounds: my own cold review produced
4 + 2 + 3 findings, the independent gate produced 1 + 1 + 0. Totals across all review rounds:
13 adjudicated verdicts, 6 AGREE (fixed), 3 DISAGREE (with evidence), 4 dropped or recorded.
Two of the AGREEs bounced back to implementation as fix plans; the rest were corrections to
PR-facing text.

❌ Fixed after review (bounced back to implementation)

Test liveness, raised twice, fixed twice. Every value assertion in the new test compares the
query at optimize_aggregation_in_order = 1 against the same query at 0. That needs no
hardcoded constants, but it is blind to the optimization silently not being applied: if a shape
ever stops being eligible, both sides take the fallback path, the comparison still returns 1,
and the carrier stops being covered with nothing failing. Round 1 closed five carriers plus the
DISTINCT / LIMIT BY siblings; round 2 closed the three remaining advertised controls
(the mixed-direction Merge DISTINCT case, the all-ascending key, the prefix-only GROUP BY),
after confirming that DISTINCT and LIMIT BY reach the optimizer through genuinely independent
entrypoints so pinning one says nothing about the other. The reference grew 20 -> 28 -> 31 lines;
no assertion was removed or weakened.

A claim in this PR's own description that the measurements contradicted. The description
asserted that every EXPLAIN PIPELINE plan assertion holds on a pre-fix binary. That is true of
14 of the 15, and false for the one inverse assertion: line 13 asserts
AggregatingInOrderTransform = 0 for the disagreeing-Merge decline, which does not exist
pre-fix, so it must move there, and it does. The correct split is 15 value oracles + 1 read_rows
oracle + 15 plan assertions, of which 14 are positive eligibility pins and 1 is a defect pin;
10 of the 31 lines move on a master-HEAD binary (8 value oracles, the push-down oracle, and that
decline pin). Corrected before this PR was opened. Two stale counts in the same paragraph
(12 pins, 28 lines) were corrected with it.

⚠️ Disagreed, with evidence

"Pin the decline against the Merge simply being ineligible." Already covered, and the test
says so in-tree: the case-6d comment records that the LimitBySortedStreamTransform assertion on
the mixed-direction Merge is load-bearing for case 6b, because it proves that Merge is
eligible for read-in-order, so the = 0 really means "declined by the new guard" and not "never
eligible at all". Both that pin and the sibling DistinctSortedStreamTransform pin read 1 on a
master-HEAD binary and under both mutants, i.e. exactly where the decline is absent.

"The system.query_log / read_rows push-down assertion is fragile." It is modelled
byte-for-byte on the in-tree precedent 04234_aggregation_in_order_limit_pushdown, which lives on
master with only no-random-settings, while this test carries the strictly stronger
no-random-settings + no-random-merge-tree-settings + no-parallel-replicas. Removing it would
leave the description's push-down claim unmeasured, which an earlier round had already flagged.

💡 Noted, not blocking

An adjacent pre-existing asymmetry, disclosed in the description rather than fixed here: the
group-by sort description always takes the default nulls_direction = +1, so LIMIT push-down into
aggregation in order can only fire for an ORDER BY whose own nulls_direction is +1. Measured
to apply equally to ordinary ascending keys (ASC NULLS FIRST does not fire either), so it has
nothing to do with reverse keys and is one concern away from this PR.

Carrier enumeration was done independently before comparing against the implementation plan, and
agreed on every row. Two mechanisms were re-verified rather than assumed: the memory-bound-merging
distributed path is strictly improved by the direction fix and can never reach the serialized
query-plan wire format, because AggregatingStep::isSerializable() and serialize() both refuse
whenever sort_description_for_merging is non-empty; and StorageBuffer consumes InputOrderInfo,
which this change leaves byte-identical, since the order_key_prefix_descr emit is deliberately
left unmultiplied.

Session id: cron:clickhouse-review-slot-10:20260727-222900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (a-i)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE md (a UInt32, b UInt32) ENGINE=MergeTree ORDER BY (a, b DESC); SYSTEM STOP MERGES md; + two overlapping INSERT ... FROM numbers(20), then SELECT count(), sum(b) FROM (SELECT a, b FROM md GROUP BY a, b) SETTINGS optimize_aggregation_in_order = 1 returns 8 168 on a master-HEAD debug build against the correct 40 520. 100% reproducible, no fuzzing, no timing. Ten of the thirty-one lines of the new test move on a master-HEAD binary.
b Root cause explained? buildInputOrderFromUnorderedKeys (optimizeReadInOrder.cpp), the order builder for GROUP BY/DISTINCT/LIMIT BY, never consulted KeyDescription::reverse_flags: it hardcoded current_direction = 1 and emitted that into sort_description. The read side does honour the flags, so the streams arrive with a reversed key column descending while AggregatingStep is told ascending; AggregatingInOrderTransform's direction-aware less inside std::upper_bound then never finds a new key and collapses a whole run into one group. The ORDER BY sibling builder in the same file already multiplies a reverse_indicator in -- that asymmetry is the defect.
c Fix matches root cause? Yes. The direction claim is corrected where it is manufactured, in the same shape the ORDER BY sibling uses. No widened bounds, no no-random-* on the production side, no defensive check at the consumer, no test weakened. The one place the optimization is declined is a Merge whose children read the matched prefix in genuinely opposite physical directions, where no single direction value can be correct.
d Test intent preserved / new tests added? New 04651_aggregation_in_order_reverse_key.sql. No existing test was changed or weakened; 04316_limit_by_in_order_reverse_key.reference and the two Order:-asserting references (02481_aggregation_in_order_plan, 03273_group_by_in_order_still_used_*) are untouched and still pass. Each value assertion compares the query at optimize_aggregation_in_order = 1 against the same query at 0, so no result constant is hardcoded; because an oracle comparison alone cannot see the optimization silently not being applied (both sides would then take the fallback and compare equal), every carrier additionally carries an EXPLAIN PIPELINE engagement assertion, and so does every control that claims a query must stay optimized. Of the 31 reference lines: 15 value oracles, 15 plan assertions (11 AggregatingInOrderTransform, 2 LimitBySortedStreamTransform, 2 DistinctSortedStreamTransform) and one read_rows push-down oracle. Of those 15 plan assertions, 14 are positive > 0 eligibility pins and one is the inverse = 0 pin asserting the Merge decline. The 14 positive pins hold on a pre-fix binary and under both mutants; the inverse pin is a defect pin and correctly moves pre-fix.
e Demonstrated in BOTH directions? Yes. Master-HEAD debug binary: the new test FAILS on 10 of its 31 lines -- 8 value oracles, the LIMIT push-down oracle, and the inverse = 0 decline pin, which must move there because the decline does not exist yet -- with the remaining 21 lines, including all 14 positive eligibility pins, still passing. Fixed binary: PASSES, 50/50 randomized runs OK. Two mutants pin the halves separately -- disarming the direction fix reproduces master's output byte-for-byte, disarming only the decline fails exactly the two disagreeing-Merge lines and nothing else. Reverting the mutations rebuilt to a bit-identical Build ID.
f General across CODE paths? Fixed in the shared builder, so all four of its call sites benefit (ReadFromMergeTree, ReadFromObjectStorageStep, and the ReadFromMerge per-table loop). Every consumer of the returned description was enumerated: the aggregation path is the defect; DISTINCT and LIMIT BY compare compareAt(...) != 0 and are direction-insensitive (asserted as controls, measured unchanged); canImproveOrderForDistinct negates uniformly so the relative signs survive; FinishAggregatingInOrderAlgorithm and the sortBlock fallbacks become consistent. The legacy ReadInOrderOptimizer aggregation path is unreachable for a GROUP BY query on master and was deliberately not touched.
g Generalizes across INPUTS? The test covers a mixed-direction key, a single reversed column, a reversed column inside a longer prefix, a reversed leading column, a negative monotonic function match composed with the reverse sign, ReplacingMergeTree ... FINAL, and Merge tables in three configurations (children agreeing, disagreeing, all ascending), plus all-ascending and prefix-only controls (each with its own engagement pin, so a control cannot silently degrade into a tautology), and LIMIT push-down into aggregation in order over a reversed key measured through system.query_log.read_rows. Verified to reproduce with enable_analyzer 0 and 1, and independent of max_threads (1/2/16), optimize_use_projections and use_lightweight_primary_key_index_analysis.
h Backward compatible? Yes. No new or changed setting, no serialization or protocol change, so no SettingsChangesHistory.cpp entry. AggregatingStep::isSerializable() already returns false whenever sort_description_for_merging is non-empty, so this description never reaches the distributed query-plan wire format. order_key_prefix_descr (which feeds InputOrderInfo, and hence the existing Merge agreement check and StorageBuffer) is deliberately left unchanged, so InputOrderInfo::operator== behaves byte-identically.
i Invariants and contracts preserved? The invariant restored is exactly the one the function's own comment asserts: the returned sort_description describes the direction the in-order streams are physically sorted in. Today it claims ascending for a descending stream. The new children_directions_agree flag lives on the file-local InputOrder struct (not the public, serialized InputOrderInfo) and defaults to true, so the single-table and object-storage paths are unaffected. The decline returns before requestReadingInOrder is issued, so there is no partially applied read request to unwind.

Local verification: 50/50 randomized runs OK; a sweep of 335 read-in-order / aggregation-in-order / distinct-in-order / limit-by-in-order tests gives an identical failure set on this build and on a pristine master build from the same merge base.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @davenger @antaljanosbenjamin — could you review this? buildInputOrderFromUnorderedKeys never consulted KeyDescription::reverse_flags, so with a DESC column in the matched key prefix AggregatingStep was handed a sort description claiming ascending while the read side delivers descending, and AggregatingInOrderTransform's direction-aware less then collapsed whole runs into one group (silent wrong GROUP BY results). It also declines aggregation in order for a Merge whose children read that prefix in opposite physical directions, where no single direction is correct.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [45ccdd9]

Summary: ✅


AI Review

Summary

This PR fixes two real order-description bugs in optimize_aggregation_in_order: reverse sorting-key columns were previously advertised with the wrong direction, and negative monotonic matches on Float keys kept the wrong nulls_direction around the NaN boundary. It also correctly declines aggregation-in-order for Merge reads whose children would feed the aggregator streams sorted in opposite physical directions. I did not find an unresolved correctness, test, or metadata issue in the current head.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 45ccdd9.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.00% 81.00% +0.00%

Changed lines: Changed C/C++ lines covered: 36/37 (97.30%) · Uncovered code

Full report · Diff report

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

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.30% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 31/36 (86.11%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3f0afa8

CI has fully finished on this head: 174 check-runs, all completed, 0 queued, 0 in progress,
Finish Workflow success at 11:51:36Z. One failing check (155 success, 18 skipped, 1 failure).

Check / test Reason Owner / fixing PR
Fast test (arm_darwin) / Server died macOS server wedge, not PR-caused #112267 (external, open)
Fast test (arm_darwin) / 02466_distributed_query_profiler timeout victim of the same wedge, same job, one event #112267 (external, open)

Both rows are one event with one owner. The 02466_distributed_query_profiler row is
Reason: Timeout! / TimeoutError / timed out whose traceback ends at tests/clickhouse-test:3751
inside self._cleanup(...) -> :3825 _cleanup_database, i.e. the test was merely whatever sat in
database cleanup when the socket timed out against an already-wedged server. It is not a slow or flaky
test in its own right, and the named test is not a signal about this PR.

Not PR-caused: this PR changes src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp plus one
new stateless test, with no link to macOS server startup, sockets or profiling. Breadth over 7 days for
Fast test (arm_darwin) / Server died: 65 hits across 60 distinct pull requests, 0 on master.

Owner justification: #112267 states that it fixes the hang half of exactly these
Fast test (arm_darwin) Server died failures. Its root cause is Darwin pthread_rwlock losing
wakeups under the sampling profiler's signal storm (Apple FB24027930), wedging libfiu's fail-point cache
lock so every new query, connection and system-log flush blocks. That is the wedge signature above.

Session id: cron:our-pr-ci-monitor:20260728-120000

Requested by PedroTadim on issue ClickHouse#111901. The shape ORDER BY (a DESC, b) with
GROUP BY a fails differently from the cases already in this test: pre-fix it
collapses every row of the table into one group, while case 4 (GROUP BY a, b
on the same table) keeps one row per key tuple and only misplaces them.

Verified on the two binaries built from this branch. On the pre-fix binary both
new oracle lines return 0 and the engagement line returns 1, so the shape is
genuinely eligible for aggregation in order and the collapse is real rather
than the optimization silently declining. On the fix binary all three return 1
and the test passes.

Reproducer from the report, confirmed on both arms:

  CREATE TABLE big (a UInt32, b UInt32) ENGINE = MergeTree ORDER BY (a DESC, b);
  INSERT INTO big SELECT number % 100, number FROM numbers(100000);
  SELECT a, count() FROM big GROUP BY a
  SETTINGS optimize_aggregation_in_order = 1, max_threads = 1;

Pre-fix this returns the single row 99 100000; with the fix it returns the
expected 100 rows of 1000 each.
@fm4v
fm4v enabled auto-merge August 24, 2026 12:41
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 45ccdd934 with master dfde23932 (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

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

Job report

…orderedKeys

The GROUP BY / DISTINCT order-info builder emitted SortColumnDescription with the
default nulls_direction of 1 while signing the direction with the monotonicity and
the reverse flag. A sorting-key column is physically stored ASC NULLS LAST when read
forward and DESC NULLS FIRST when reversed, and NULL/NaN are fixed points of the
monotonic functions involved, so the null rows keep their physical position while the
advertised direction flips. On a negative monotonic match the advertised placement then
disagrees with the stream, AggregatingInOrderTransform mis-detects the key change
around the NULL/NaN run, and groups collapse silently.

Measured on a three-part Float64 table with NaN, GROUP BY negate(x):

  ORDER BY x DESC (reverse key)   6 groups expected, 1 produced
  ORDER BY x       (forward key)  6 groups expected, 5 produced

The forward-key case needs no reverse flag, so it reproduces on master independently
of the reverse-key fix in this branch.

Required nulls_direction is current_direction, the pre-multiplication direction:
advertised direction is current_direction * reverse_indicator, nulls are last exactly
when reverse_indicator is 1, and "nulls last" means nulls_direction equal to the
direction, which gives current_direction * reverse_indicator^2. Both direct-match
cases keep the value they had, which is why they were already correct.

Nullable keys composed with a monotonic function are not eligible for aggregation in
order at all, so only the Float/NaN shapes are covered by the new test cases.
auto-merge was automatically disabled August 24, 2026 15:04

Head branch was pushed to by a user without write access

@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 42 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 484c53bc-d759-4075-9450-a5cba85c155a
  • MIRAI run: 2e2c32d2-d7ed-47a6-8838-edac7dc62c6b
  • PR check IDs:
    • clickbench_1073643_1788465494
    • clickbench_1074436_1788465667
    • clickbench_1074614_1788465680
    • tpch_adapted_1_official_1074728_1788465767
    • tpch_adapted_1_official_1074840_1788465784
    • tpch_adapted_1_official_1074984_1788465914

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4cf329b79bea2c1a0eafd30f17304cfc017f6cba

CI is fully finished on this head: praktika root FAIL over 176 nodes as 148 OK, 18 skipped by
digest, 8 FAIL and 2 ERROR (the five failing leaves, their four checks, and the PR roll-up).
Config Workflow, Style check and Finish Workflow are all success and 0 nodes are DROPPED,
so this is a real run and not a label-gate void. All five failures have an owner and none is caused
by this PR.

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Logical error: Not-ready Set is passed as the second argument for function 'globalIn' (STID 0250-41a5) not PR-caused, trunk defect in the object-storage _path / _file prefilter. The trace runs ReadFromObjectStorageStep::createIterator (ReadFromObjectStorageStep.cpp:179) into StorageObjectStorageSource.cpp:581, VirtualColumnUtils.h:136 and getFilterByPathAndFileIndexes (VirtualColumnUtils.cpp:419), then ExpressionActions executes FunctionIn::executeImpl at src/Functions/in.cpp:128 on a set that analysis never built. Frame-keyed 30-day census of that sub-shape: 120 rows over 97 distinct pull requests, 13 true-master rows, 2026-08-01 08:59Z to 2026-08-30 19:47Z (whole STID bucket: 264 rows / 203 pull requests / 26 true-master, so the bucket pools several call paths and the frames pick this one) #112968 (external, open)
Stress test (arm_asan_ubsan) / Segmentation fault (STID 3773-49b1) not PR-caused, trunk defect: stack exhaustion from the mutual recursion between DB::collectSets (src/Planner/CollectSets.cpp:173) and CollectSetsVisitor::enterImpl (:55), which re-enters collectSets for a constant node's source expression, so a deeply chained expression drives the query-tree visitor to the bottom of the stack. The fix merged at 16:11:04Z, after this head was pushed at 15:19:23Z, so the tree that ran predates it: pending_source_expressions counts 10 at the fix's merge commit, 0 at its parent and 0 at this head. It arrives on the next master merge #116978 (ours, merged)
Upgrade check (amd_release) / Cannot start clickhouse-server not PR-caused, CI-harness defect on master: tests/config/install.sh symlinks silk.xml with no version gate, so the previous-release server rejects enable_silk_runtime with Code: 137 ... UNKNOWN_ELEMENT_IN_CONFIG and never starts. Onset is a cliff at 2026-08-30 13:48:57Z: 83 CIDB rows over 82 distinct pull requests in 7 days, 0 true-master rows, still firing at 20:30:34Z #117172 (ours, open)
Upgrade check (amd_release) / Check failed the same job's second abort row (Check failed with exit code 1), same event as the line above #117172 (ours, open)
Integration tests (amd_llvm_coverage, 4/8) / Container memory budget exceeded (/docker) not PR-caused, harness resource defect: the job log shows CI_DIND_NESTED_BUDGET=43782209536, three workers started over 758 collected items, then two oom-kill:constraint=CONSTRAINT_MEMCG, oom_memcg=/docker/<job>/docker kills and cgroup leaf /docker: peak 40.78 GiB of 40.78 GiB cap. So the nested-container cgroup leaf is the thing that breached, not the host and not the job cgroup above the leaves, and the shard's 758 items lose their signal. Signature is one day old: 5 CIDB rows over 5 distinct heads, all on 2026-08-30 between 06:57Z and 17:51Z, of which 1 is a true-master row. No fixing PR covers this shape: #115785 sizes the --dist=each flaky pool and states that loadfile runs keep their 3 workers a fix task is created (investigating at full effort - fixing-PR link to follow here)

Two of the owners are worth substantiating, so they do not read as same-area coincidences.
#112968 rewrites _path / _file filtering for object storage, file and url, touching
src/Storages/VirtualColumnUtils.{cpp,h} and src/Storages/ObjectStorage/StorageObjectStorageSource.cpp
(the exact frames above) and adding 04669_object_storage_path_filter_global_in as the regression
test for a globalIn in that prefilter. #116978 changes src/Planner/CollectSets.cpp to stop
recursing into constant node source expressions and adds 05047_collect_sets_deep_default_chain
for the deep chain that exhausts the stack.

None of the five is attributable to this diff, which fixes optimize_aggregation_in_order on a
reverse sorting key and adds one stateless test. It reaches neither the object-storage read path,
nor collectSets, nor the CI harness.

Reports:

Session id: cron:our-pr-ci-monitor:20260830-203000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger follow-up - 4cf329b79bea2c1a0eafd30f17304cfc017f6cba

The one row still owned by a fix task now has a fixing PR.

Check / test Owner / fixing PR
Integration tests (amd_llvm_coverage, 4/8) / Container memory budget exceeded (/docker) fixing PR #117202 (external, open)

Causal link, from this run's own uploaded dmesg.log: the OOM task table holds 10 concurrent
gdb at 4.14 to 4.27 GiB anonymous each, 42.4 GiB and 90% of all anonymous memory in the table,
against a /docker leaf capped at 40.78 GiB. The 13 clickhouse servers those debuggers were
attached to account for 4.5 GiB, 9%. The shutdown stack dump is the demand, not the servers.
#117202 takes that attach under a job-wide lock.

Correction to my earlier row on this head: it said the shard's 758 collected items lose their
signal. That is wrong. CIDB has 752 OK, 7 SKIPPED and 1 ERROR for the shard, the pytest summary
is 751 passed, 7 skipped, and the row set is identical to a green run of the same shard on the
same day. The leaf-OOM row was the only failing row. What the failure actually costs is
Mergeable Check going red on an otherwise passing run, plus has_error suppressing the
coverage profile for 1 of 8 integration shards.

Session id: cron:clickhouse-plan-slot-33:20260830-231200

@nihalzp
nihalzp added this pull request to the merge queue Sep 3, 2026
Merged via the queue into ClickHouse:master with commit 0659665 Sep 4, 2026
175 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 4, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 26.3, 26.7, 26.8. I ran this PR's own regression test against each branch's binary and the bug reproduces there (the fix isn't present yet).

@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

Backport status, measured per branch rather than transcribed.

This PR's own test is a self-oracle: every assertion compares optimize_aggregation_in_order = 1 against the same query at 0, so all 40 output lines must be 1. I ran it against the official per-branch binaries from builds.clickhouse.com, with fixed master as the control.

branch binary wrong / ran source patch
master (control) 26.9.1.732 0 / 39 n/a
26.8 26.8.3.41 15 / 39 applies clean
26.7 26.7.7.28 15 / 39 applies clean
26.6 26.6.5.50 15 / 39 applies clean
26.3 26.3.31.8 14 / 27 2 conflicts

26.8, 26.7 and 26.6 produced byte-identical output (one md5). The 40th assertion reads system.query_log, which clickhouse local does not have, so it is missing on every arm including the clean control. As an independent second arm, sorting_key_reverse_flags and children_directions_agree are absent from optimizeReadInOrder.cpp at all four branches' exact GIT_HASH, and present at the control's.

Two corrections to the suggested target list:

  • 26.6 is affected as well. The test as merged errors there, though: optimize_aggregation_in_order_limit does not exist on 26.6 (test line 257).
  • On 26.3 a reverse sorting key needs allow_experimental_reverse_key = 1 per table, so the wrong result is not reachable in a default configuration. The 26.3 row above is a local copy with that setting added to 10 of the DDLs, and it stops early because optimize_limit_by_in_order is unknown there (line 208).

v26.7-must-backport is therefore the floor that needs no adaptation: select_backport_branches expands it to ['26.8', '26.7'], and both take the fix and the test unchanged. A v26.6 floor carries the fix cleanly too, but its backport CI would red on that one settings line.

@nihalzp could you apply the label? I do not hand-author release-branch PRs.

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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default 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.

optimize_aggregation_in_order over a mixed-direction sorting key (a, b DESC) collapses GROUP BY groups — silent wrong result

6 participants