Repository navigation
Fix wrong results for duplicate-ALIAS GROUP BY on a Distributed table under two-level aggregation - #108855
Conversation
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260629-190500 |
|
cc @yakov-olkhovskiy @KochetovNicolai — could you review this? It's a follow-up to the duplicate-ALIAS-on-Distributed family (#107913 / #108725) fixing a distinct silent wrong-results variant: under two-level distributed aggregation the shard collapses the duplicate GROUP BY keys to one and buckets by one key, but the initiator merged by two, so equal groups from different shards landed in different two-level buckets and were never merged. The fix makes the initiator merge by only the representative key set and reconstructs the duplicates after the merge. |
|
Workflow [PR], commit [46155a3] Summary: ✅
AI ReviewSummaryThis PR fixes the duplicate- Findings❌ Blockers
Final VerdictRequest changes. The main merge fix is on the right track, but the duplicate-key collapse must survive plan composition, and the LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 113/115 (98.26%) · Uncovered code |
… under two-level aggregation When a Distributed table has several ALIAS columns expanding to the same expression (e.g. a1, a2 both = toString(x)) and they are used as GROUP BY keys, the shard inlines them into one expression and deduplicates the GROUP BY to a single key before computing its two-level aggregation bucket numbers. The initiator, however, keeps the columns distinct and merged the partial aggregation states by the full (duplicated) key set. Two-level bucket numbers are computed from a hash of the key columns, so hashing one key and hashing two identical keys give different buckets. When the per-shard partial states mix single-level and two-level blocks (e.g. shards with different data sizes straddling group_by_two_level_threshold, or under sanitizer/concurrency timing), the initiator re-buckets single-level blocks by two keys while two-level blocks from the shard were bucketed by one key. Equal groups then land in different buckets and are never merged, so one logical group is returned once per shard with its count split, instead of one merged row. The initiator now merges (and buckets) by only the representative key columns, matching the shard's collapsed key set: buildShardCollapseFanOut reports which reconstructed columns are duplicates of an earlier one, and addMergingAggregatedStep drops the duplicate keys before MergingAggregated and reconstructs them after the merge. The post-merge reconstruction emits the canonical aggregated layout (all original GROUP BY keys first, in their declared order, then the aggregate-state columns) rather than appending the dropped duplicate keys at the end. WITH ROLLUP / WITH CUBE reach this path with an empty grouping_sets_parameters_list, and the following RollupStep / CubeStep read the merged block positionally (the first keys_size columns as keys, the rest as aggregate states). Appending the duplicates at the end made the count() state be read as a key and a reconstructed key be read as the aggregate state, throwing 'Bad cast ... to ColumnAggregateFunction' or producing wrong rollup/cube totals; emitting the canonical layout keeps that path correct. Co-Authored-By: Claude Opus 4.8 <[email protected]>
09a8892 to
a67a794
Compare
…-ALIAS two-level merge fix The existing 04357_distributed_alias_same_expression regression lines for this wrong-results variant pin group_by_two_level_threshold = 1, which forces BOTH localhost shards to two-level aggregation. With consistent bucketing on both shards the bug cannot reproduce, so the changed test passed on master HEAD and the per-arch Bugfix Validation jobs reported "bug does not reproduce on this arch" (SKIPPED). The merge-blocking new_tests_check.py post-hook requires at least one per-arch job to actually validate the bug (is_success, not SKIPPED), so the PR was blocked. The bug only manifests when one shard converts to two-level while another stays single-level, so equal groups from the two shards are bucketed differently and never merged. That single-level/two-level mix needs genuinely asymmetric per-shard data, which test_cluster_two_shards_different_databases provides (shard_0 with 1000 groups goes two-level, shard_1 with 10 groups stays single-level). This new test reproduces the wrong result deterministically on master HEAD (1010 rows / 0 merged groups) and passes with the fix (1000 rows / 10 merged groups), validated through the clickhouse-test harness against the exact master-HEAD amd_asan_ubsan and amd_debug binaries used by CI. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Pushed The The wrong-result only happens when one shard goes two-level while another stays single-level, so the per-shard states are bucketed differently and the collapsed duplicate-ALIAS groups are never merged. That mix needs asymmetric per-shard data, which
Verified through the |
GROUP BY GROUPING SETS where one set holds two ALIAS columns that expand to the same expression (collapsed by the shard, e.g. GROUPING SETS ((a1, a2), (a1)) with a1, a2 both = toString(x)) hit the same two-level bucketing mismatch this PR fixes for plain GROUP BY, but it bypassed the fix. The non-grouping-sets branch of addMergingAggregatedStep merges on the shard's collapsed key set and reconstructs the duplicate columns afterwards. That path is guarded by grouping_sets_parameters_list.empty(), so GROUPING SETS stayed on the old full-key merge: the shard deduplicates the set to one key before computing its two-level bucket numbers, while the initiator's per-grouping-set Aggregator is built from grouping_sets_parameters_list.used_keys and buckets by both keys. With a single-level/two-level partial mix across shards the same group lands in different buckets and is never merged, silently returning split counts. Carrying the collapsed representative set through the grouping-sets merge machinery (GroupingSetsParamsList + makeCreatingMissingKeysForGroupingSetDAG + MergingAggregatedTransform) is out of scope here, so reject the combination with NOT_IMPLEMENTED instead of returning wrong results. Only a grouping set that actually contains both a collapsed duplicate and its representative is rejected; sets that keep one such key each (e.g. ((a1), (a2))) bucket consistently with the shard and are unaffected, as is any non-distributed or non-collapsed query. Adds GROUPING SETS coverage to 04357_distributed_alias_same_expression (the rejected forms plus a safe ((a1), (a2)) form). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate — GROUPING SETS fixup (85192f4)Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-1:20260630-054600 |
…sentatives
The previous rejection in addMergingAggregatedStep only fired when a single
grouping set literally contained a collapsed duplicate key AND its
representative (the first expected column for that shard column). With three or
more ALIAS columns all expanding to the same expression, a grouping set can
hold two collapsed duplicates without naming the representative, e.g.
GROUPING SETS ((a1), (a2, a3)) with a1, a2, a3 all = toString(x) yields the
collapse map {a2 -> a1, a3 -> a1}: the (a2, a3) set contains neither a1 nor a
duplicate of an in-set representative by the old check, so it slipped past the
rejection. The shard still deduplicates that set to one key before computing
two-level bucket numbers while the initiator buckets it by two keys, so a
single/two-level partial mix splits the same group across buckets and returns
wrong (split) counts.
Each used key of a grouping set is now canonicalized through the collapse map
(a duplicate maps to its representative; any other key maps to itself), and the
set is rejected when two of its keys share a canonical representative. This
subsumes the old representative-presence check and closes the representative-
absent shape.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate, GROUPING SETS 3-alias generalization (e6109a1)Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260630-075900 |
CI finish ledger — e6109a1Every failure below has an owner: a fixing PR (ours or external). No failure is PR-caused (the diff is the distributed two-level-aggregation duplicate-ALIAS planner fix; none of these tests are in that path or reproduce the wrong-results bug). Only
The Session id: cron:our-pr-ci-monitor:20260630-130000 |
|
@groeneai, we fixed many unrelated tests. Please update the branch. |
|
The PR is green on the current head and one narrow decision is the only thing outstanding, so here is what a reviewer needs. The guard debated in the open The decision: keep the conservative The "I would prefer the exact merge-side fix" comment in that thread is from Cost of the flake over 30 days, flaky-check reruns excluded: 132 failures across 124 distinct pull requests, plus 12 on master, still firing today. |
|
@PedroTadim, the delay is because I'm actually trying to read this... |
I think this is tolerable. |
|
Confirmed: the conservative CI is green on the current head The branch is 6308 commits behind master since I last merged it on 7 August. I will refresh it if you prefer, otherwise it is ready as it stands. |
alexey-milovidov
left a comment
There was a problem hiding this comment.
This is a band-aid like fix.
Refresh the branch against master d466df7 so it is ready to review. The two CI failures the finish ledger owned have since been fixed on master (ClickHouse#108855 and ClickHouse#112484), which is what was blocking Mergeable Check. No conflict: the clone() triple copy still applies verbatim and master's newer restores in the same function are preserved.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix wrong results for
GROUP BYon aDistributedtable over duplicateALIAScolumns that expand to the same expression (e.g. two columns both defined astoString(x)) under two-level / memory-efficient distributed aggregation. The duplicate keys were collapsed into one on the shards but merged by the full key set on the initiator, so under two-level aggregation equal groups from different shards landed in different buckets and were not merged, returning a group once per shard with a splitcount().Description
Closes: #112987
Continuation of the duplicate-
ALIAS-on-Distributedfamily (issue #106403, PR #107913, PR #108725). Those PRs fixedNUMBER_OF_COLUMNS_DOESNT_MATCHin the shard query-tree reconstruction. This PR fixes a distinct, silent wrong-results variant in the aggregation-state merge that those changes did not touch (it reproduces on a build that already contains them).Root cause. For
SELECT a1, a2, count() FROM dist GROUP BY a1, a2wherea1anda2areALIAScolumns both equal totoString(x), the shard query tree inlinesa1/a2to the same expression and deduplicates theGROUP BYto a single key, so the shard aggregates and computes its two-level bucket numbers from one key. On the initiator the columns stay distinct, soMergingAggregatedwas configured with two keys. Two-level bucket numbers arehash(keys) % 256, and hashing one key versus two identical keys yields different buckets. When the per-shard partial states mix single-level and two-level blocks (shards with different data sizes straddlinggroup_by_two_level_threshold, or sanitizer/concurrency timing), the initiator re-buckets single-level blocks by two keys while the shards' two-level blocks were bucketed by one key. Equal groups land in different buckets and are never merged — one logical group is returned once per shard with itscount()split.Fix. The initiator now merges (and buckets) by only the representative key columns, matching the shard's collapsed key set:
buildShardCollapseFanOutadditionally reports which reconstructed columns are fan-out duplicates of an earlier column (several expected columns mapping onto the same shard column), propagated throughJoinTreeQueryPlan.addMergingAggregatedStepdrops the duplicate key columns beforeMergingAggregated(so the merge sees the shard's single-key layout) and reconstructs them after the merge as aliases of their representative, leaving the output header unchanged.Affects both the memory-efficient and the simple
Aggregator::mergeBlocksmerge paths. A deterministic regression test (asymmetric per-shard data forcing the single/two-level mix) and a settings-pinned variant on the existing symmetric cluster (the form originally surfaced by the sanitizer flaky-check) are added to04357_distributed_alias_same_expression.A deterministic local reproduction (two localhost shards reading tables of different sizes,
group_by_two_level_threshold = 50,prefer_localhost_replica = 0): a query with 1000 distinct groups returned 1010 rows before the fix (10 shared groups split across shards) and the correct 1000 rows after.Version info
26.8.1.1660(included in26.8and later)