Repository navigation
Fix wrong optimize_aggregation_in_order results on a reverse sorting key - #112200
Conversation
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.
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 Rounds: Gate A (approach) 2 rounds, 1 finding. Review 3 rounds: my own cold review produced ❌ Fixed after review (bounced back to implementation)Test liveness, raised twice, fixed twice. Every value assertion in the new test compares the A claim in this PR's own description that the measurements contradicted. The description
|
Pre-PR validation gate (a-i)
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. |
|
cc @davenger @antaljanosbenjamin — could you review this? |
|
Workflow [PR], commit [45ccdd9] Summary: ✅
AI ReviewSummaryThis PR fixes two real order-description bugs in Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit 45ccdd9.
Changed lines: Changed C/C++ lines covered: 36/37 (97.30%) · Uncovered code |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 31/36 (86.11%) · Uncovered code |
CI finish ledger - 3f0afa8CI has fully finished on this head: 174 check-runs, all completed, 0 queued, 0 in progress,
Both rows are one event with one owner. The Not PR-caused: this PR changes Owner justification: #112267 states that it fixes the hang half of exactly these 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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 20 s compile time in total, 7 of them have a recent master baseline. |
…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.
Head branch was pushed to by a user without write access
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
CI finish ledger -
|
| 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:
- https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112200&sha=4cf329b79bea2c1a0eafd30f17304cfc017f6cba&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29
- https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112200&sha=4cf329b79bea2c1a0eafd30f17304cfc017f6cba&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29
- https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112200&sha=4cf329b79bea2c1a0eafd30f17304cfc017f6cba&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29
- https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112200&sha=4cf329b79bea2c1a0eafd30f17304cfc017f6cba&name_0=PR&name_1=Integration%20tests%20%28amd_llvm_coverage%2C%204%2F8%29
Session id: cron:our-pr-ci-monitor:20260830-203000
CI finish ledger follow-up -
|
| 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
|
Hi — this looks like a backport candidate for |
|
Backport status, measured per branch rather than transcribed. This PR's own test is a self-oracle: every assertion compares
26.8, 26.7 and 26.6 produced byte-identical output (one md5). The 40th assertion reads Two corrections to the suggested target list:
@nihalzp could you apply the label? I do not hand-author release-branch PRs. |
Closes: #111901
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes silently wrong
GROUP BYresults withoptimize_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 aFloatsorting-key column, around theNaNboundary. This affected a singleMergeTreetable and aMergetable over such tables. For aMergetable 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
InputOrderbuilder forGROUP BY/DISTINCT/LIMIT BY. It described the stream wronglyin two independent ways, and
AggregatingInOrderTransformcompares keys with a direction-aware andnulls-aware
lessinsidestd::upper_bound, so a wrong description makes it miss the key change andcollapse a whole run into one group with wrong aggregate values.
KeyDescription::reverse_flags, hardcoding direction1, while the read sideemits
direction * -1for a reversed key column. TheORDER BYsibling builder in the same filealready multiplies in a
reverse_indicator; that asymmetry is the bug. Any reversed column in thematched prefix is affected, not only the mixed-direction key from the issue.
nulls_directionwas left at its default1while the direction carried the monotonicity. Asorting-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
Mergetable whose children read the matched prefix in opposite physical directions cannot bedescribed by any single direction, so aggregation in order is now declined there. The decline is
recorded on the file-local
InputOrderstruct and consumed only in theAggregatingStepbranch;DISTINCTandLIMIT BYcompare for equality only and keep their optimization.No query loses the optimization otherwise.
ORDER BY a DESC NULLS FIRST ... LIMIT nover a reversedkey now additionally matches the LIMIT push-down (64 rows read against 1000).
Recovering aggregation in order for the disagreeing
Mergeneeds per-child direction normalization inReadFromMergeandAggregatingStep; happy to follow up separately if wanted.Measurements and test accounting
Before this PR,
optimize_aggregation_in_orderoff against on:(a, b DESC)a, b(a DESC)a(a, b DESC, c)a, b(a DESC, b)a, b(x DESC, y DESC),GROUP BY negate(y), negate(x)ReplacingMergeTree ... FINAL,(a, b DESC)a, bFloat64+NaN,x DESC,GROUP BY negate(x)Float64+NaN,x,GROUP BY negate(x)(a, b)(control)a, b(a, b DESC), prefix only (control)aNullablekeys composed with a monotonic function are not eligible for aggregation in order at all,so only the
Float/NaNshapes are reachable for defect 2.Every assertion in
04651_aggregation_in_order_reverse_keycompares the query atoptimize_aggregation_in_order = 1against the same query at0, so no result constant is hardcoded.The 40 reference lines are 21 value oracles, one
read_rowspush-down oracle, and 18 plan assertions(17 positive eligibility pins plus one inverse pin for the
Mergedecline). A master-HEAD binary fails15 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.hitsdataset).The reverse-flag half was written and then reverted inside PR #105135 (
ff21d560c6a560, reverted byd0214678ad6d28), which went on to delete the sorted merge fromLimitByStepentirely. Reading thecommit sequence, it was dropped as no longer needed by that PR rather than as wrong; the
GROUP BYconsumer still performs a direction-aware merge and was never covered by its tests. That is a
reconstruction from the commits, not a quote.
ReadFromObjectStorageStepis fixed by the same change; it already builds itsInputOrderInfohonouring
reverse_flags, so the two now agree. That path is reasoned, not measured.Workflow [PR]
Sync PR [sync-upstream/pr/112200]