Skip to content

fix column order for distributed alias columns - #107675

Merged
vdimir merged 5 commits into
masterfrom
vdimir/distributed-alias-columns-order
Jun 29, 2026
Merged

vdimir merged 5 commits into
masterfrom
vdimir/distributed-alias-columns-order

Conversation

@vdimir

@vdimir vdimir commented Jun 16, 2026 •

Copy link
Copy Markdown
Member

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 incorrect results from distributed queries selecting ALIAS columns that share a common subexpression: columns could be misaligned and values returned under the wrong column

close #106398
close #81631
close #97899

Version info

  • Merged into: 26.7.1.245 (included in 26.7 and later)
  • Backported to: 26.6.2.46, 26.5.6.28, 26.4.5.115, 26.3.17.34, 25.8.29.10

@clickhouse-gh

clickhouse-gh Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e543bba]

Summary: ✅


AI Review

Summary

This PR changes ActionsChainStep::initialize so the available-column list starts with explicit ActionsDAG outputs before appending reusable internal nodes. That matches the positional rename contract used for distributed ALIAS columns, and the added stateless tests cover projection order, duplicate aliases, constants, and ALIAS references from other clauses. I did not find a changed-line code issue that warrants an inline review comment.

PR Metadata

💡 The Bug Fix category is appropriate and the changelog entry is specific and user-facing. The relationship lines at the end of the PR body use lowercase close, so GitHub will not auto-close the linked issues and the related PR is classified as a close target. Suggested replacement:

Related: https://github.com/ClickHouse/ClickHouse/pull/106398
Closes: https://github.com/ClickHouse/ClickHouse/issues/81631
Closes: https://github.com/ClickHouse/ClickHouse/issues/97899
Missing context / blind spots
  • ⚠️ The latest S3 PR report for e543bba393ef9f58278082b2930e5a897590bda5 returned zero individual test rows, and this checkout has no local build directory for running the new stateless tests. A passing run of 04305_distributed_alias_column_order and 04357_distributed_alias_query_clauses would close this gap.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jun 16, 2026
@vdimir vdimir changed the title another attemp on fix column order for distributed alias columns fix column order for distributed alias columns Jun 17, 2026
@vdimir
vdimir marked this pull request as ready for review June 17, 2026 12:56
@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Jun 18, 2026
@vdimir
vdimir enabled auto-merge June 18, 2026 14:51
@vdimir

vdimir commented Jun 18, 2026

Copy link
Copy Markdown
Member Author

BuzzHouse (amd_tsan) ERROR

#107676 + #107689

cursor Bot pushed a commit that referenced this pull request Jun 19, 2026
…rialize_query_plan cases

Broaden the duplicate-ALIAS column-count regression coverage to match the
distributed scenarios exercised by PR #106402:

- `Distributed`-over-`Distributed` (two transport hops), including over the
  query-plan-serialization transport (`serialize_query_plan = 1`);
- `remote` over a `Distributed` table with parallel replicas (the
  `remote` -> `Distributed` -> parallel-replicas second hop);
- single-hop `serialize_query_plan = 1` variant.

These all reproduce `NUMBER_OF_COLUMNS_DOESNT_MATCH` on master and are fixed by
the shard-collapse fan-out in this PR. Column-order scenarios remain covered by
the separate fix in PR #107675; the `GLOBAL IN`/`JOIN` alias-name collision is
tracked separately as a distinct issue.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
… ORDER BY

Extends the distributed ALIAS-column coverage with cases where the alias is
referenced in clauses other than the SELECT projection:

- WHERE + GROUP BY on alias columns sharing a sub-expression;
- JOIN ON referencing an alias column (GLOBAL JOIN);
- an aggregate over an alias column appearing only in ORDER BY (sort-key
  aggregate state that travels in the merge but not in the output).

Each is checked against the equivalent local query, including over the
query-plan-serialization transport (serialize_query_plan = 1).

Co-authored-by: Yakov Olkhovskiy <[email protected]>
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ vdimir
❌ cursoragent
You have signed the CLA already but the status is still pending? Let us recheck it.

@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.30% +0.00%
Functions 92.50% 92.60% +0.10%
Branches 77.50% 77.50% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 9/9 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR is a planner correctness fix: it changes how output columns are ordered when building the available-column set for a projection step, fixing wrong results for ALIAS columns over Distributed tables. It does not alter the query execution hot path and adds no optimization. ClickBench's single-table, non-distributed queries (Q4, Q15, Q28) don't exercise the changed code, so the 6-17% improvements the math flagged are run-to-run variance rather than a real effect of this change, and have been downgraded to not-sure.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 263 217 -17.5% <0.0001 plan_change: PR fixes projection column ordering for distributed ALIAS cols; this single-table AVG doesn't hit that path. Variance.
⚠️ 15 not_sure 246 213 -13.4% <0.0001 plan_change: Planner ALIAS-ordering correctness fix, no execution-cost change; this single-table query is off-path. Run-to-run noise.
⚠️ 28 not_sure 6710 6322 -5.8% <0.0001 plan_change: -5.8% on a 6.3s regex query; planner column-order fix can't speed execution. Off-path, treat as variance.

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: d1697e0d-b929-47bf-8d0f-da8ff626a3b1
  • MIRAI run: f5893745-0d03-47ba-9f23-5198cc4644af
  • PR check IDs:
    • clickbench_381412_1782738906
    • clickbench_381418_1782738906
    • clickbench_381428_1782738906
    • tpch_adapted_1_official_381437_1782738906
    • tpch_adapted_1_official_381451_1782738906
    • tpch_adapted_1_official_381464_1782738906

@vdimir
vdimir added this pull request to the merge queue Jun 29, 2026
Merged via the queue into master with commit 1efaefd Jun 29, 2026
167 checks passed
@vdimir
vdimir deleted the vdimir/distributed-alias-columns-order branch June 29, 2026 14:36
@clickgapai

Copy link
Copy Markdown
Contributor

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

@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 7, 2026
clickhouse-gh Bot added a commit that referenced this pull request Jul 7, 2026
Backport #107675 to 26.6: fix column order for distributed alias columns
robot-clickhouse added a commit that referenced this pull request Jul 8, 2026
Cherry pick #107675 to 25.8: fix column order for distributed alias columns
robot-clickhouse added a commit that referenced this pull request Jul 8, 2026
Cherry pick #107675 to 26.3: fix column order for distributed alias columns
robot-clickhouse added a commit that referenced this pull request Jul 8, 2026
Cherry pick #107675 to 26.4: fix column order for distributed alias columns
robot-clickhouse added a commit that referenced this pull request Jul 8, 2026
Cherry pick #107675 to 26.5: fix column order for distributed alias columns
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 8, 2026
vdimir added a commit that referenced this pull request Jul 8, 2026
Backport #107675 to 25.8: fix column order for distributed alias columns
vdimir added a commit that referenced this pull request Jul 8, 2026
Backport #107675 to 26.3: fix column order for distributed alias columns
vdimir added a commit that referenced this pull request Jul 8, 2026
Backport #107675 to 26.4: fix column order for distributed alias columns
vdimir added a commit that referenced this pull request Jul 8, 2026
Backport #107675 to 26.5: fix column order for distributed alias columns
maxjustus pushed a commit to HockeyStack/ClickHouse that referenced this pull request Jul 17, 2026
zeekay added a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…rialize_query_plan cases

Broaden the duplicate-ALIAS column-count regression coverage to match the
distributed scenarios exercised by PR ClickHouse#106402:

- `Distributed`-over-`Distributed` (two transport hops), including over the
  query-plan-serialization transport (`serialize_query_plan = 1`);
- `remote` over a `Distributed` table with parallel replicas (the
  `remote` -> `Distributed` -> parallel-replicas second hop);
- single-hop `serialize_query_plan = 1` variant.

These all reproduce `NUMBER_OF_COLUMNS_DOESNT_MATCH` on master and are fixed by
the shard-collapse fan-out in this PR. Column-order scenarios remain covered by
the separate fix in PR ClickHouse#107675; the `GLOBAL IN`/`JOIN` alias-name collision is
tracked separately as a distinct issue.

Co-authored-by: Yakov Olkhovskiy <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ed-alias-columns-order

fix column order for distributed alias columns
mkmkme added a commit to Altinity/ClickHouse that referenced this pull request Sep 19, 2026
Tests only, no source changes. Purpose is to establish which of the
`__aliasMarker` regressions from
#1844 still reproduce on
`antalya-26.6`, which already carries the upstream fixes that landed after
that PR was written:

  * ClickHouse#94644  (ALIAS column order)
  * ClickHouse#107675 (distributed ALIAS column order)
  * ClickHouse#107913 (`buildShardCollapseFanOut`)

All 22 distinct test files from #1844 are staged: the 18 active ones plus the
4 unique files kept under `_local_files_and_notes/dropped_tests` there. The
six dropped-test files that duplicate active ones byte-for-byte are staged
once.

Slot numbers from the 26.3 branch that are already taken on 26.6 are
reassigned to the 05053-05063 range:

  03843 -> 05053   03923 -> 05056   04286 -> 05059   03926 -> 05062
  03920 -> 05054   03928 -> 05057   03924 -> 05060   03927 -> 05063
  03921 -> 05055   03930 -> 05058   03925 -> 05061

`03648_alias_marker_with_mergeable_state.sh` is updated to the #1844 revision.
It is a contract test for the reworked marker, not a bug reproducer, so it is
expected to fail until the source change lands.

Related: #1844
Related: ClickHouse#106402
pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request Sep 20, 2026
…istributed table

A window function makes StorageDistributed::getQueryProcessingStage refuse the
optimized stage, so a Distributed read runs up to WithMergeableState. The shard
analyses the query tree with its ALIAS columns inlined and, because a window step
is present, the planner adds no projection step, so the shard's boundary header is
the Before-WINDOW output, ordered by first mention in that inlined tree. The
initiator derives the header it expects from the un-inlined tree. The two headers
therefore disagree, and reconciling them positionally paired unrelated columns:
silently wrong results, or NUMBER_OF_COLUMNS_DOESNT_MATCH, or
CANNOT_PARSE_DATETIME when the pairing casts a String onto a DateTime.

The name-based reconciliation for this boundary, buildShardCollapseFanOut,
declined for two measured reasons, both fixed here.

Its entry guard required the shard header to be strictly smaller than the
expected one, which encoded the deduplication collapse it was written for. With a
window step the header can have the same column count in a different order, so the
guard refused before the name mapping was consulted. Only the zero-column case
returns early now.

An ALIAS column whose declared type differs from its body's type inlines to
_CAST(<body>, '<Type>'), and one declared over an expression inlines to that
expression. Neither is a column the shard emits at the boundary, so a pure name
lookup could not resolve it. The raw columns the body reads are present, so the
inlined body is now evaluated on the initiator over the fan-out DAG and aliased to
the expected name, accepted only when it yields a single uncorrelated output whose
type matches the expected column.

The body is rebuilt from the query tree rather than from the alias ActionsDAGs
stored in TableExpressionData: the recursive only_analyze planner that computes the
expected header shares the PlannerContext and moves those DAGs out, so reading them
afterwards yields a stub. Rebuilding also names the leaves by column identifier,
which is what the shard header carries.

Safety is preserved. Two shard columns sharing a normalized name make the mapping
undecidable, so such names are recorded up front and any expected column resolving
to one is rejected, rather than inferring ambiguity afterwards from an unused-column
count. The unused-shard-column guard is kept, generalized to reachability from the
outputs since a column may now be consumed by a computed expression. A mapping that
is exactly the identity is declined, because the caller's positional reconciliation
already produces it, which keeps existing plans byte-identical. Anything else the
mapping cannot explain still returns nullopt and falls back to the previous
behaviour.

This is initiator-side only, so the mergeable-state wire format is unchanged and
mixed-version clusters are unaffected. ClickHouse#107675 fixed the scalar path, which stops
at FetchColumns and reconciles by name; the window path never reaches it.

Every arm of the regression test is paired with the equivalent single-node query as
its oracle, so the silent wrong-results case fails rather than merely not raising.

Closes: ClickHouse#116333
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
CTE/AN/QP: distributed query selecting ALIAS columns that share a subexpression -> wrong (values under the wrong column).
Effect in the production build a394e92: its upstream test(s) 04305_distributed_alias_column_order, 04357_distributed_alias_query_clauses fail on it and pass on official 26.8.8.8, run on isolated servers (evidence/fix_ci_20260925/upstream_repro/server_triage_PROD263_vs_UP2688.tsv).
Upstream patch unchanged, with its test(s): 04305_distributed_alias_column_order,04357_distributed_alias_query_clauses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 Pull request should be backported intentionally. Use this label with great care! 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 v25.12-must-backport v26.2-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Errors with alias columns and distributed tables and functions Incorrect SELECT results due to mixed order of columns from Distributed engine

8 participants