Skip to content

Fix ALIAS column of a GLOBAL JOIN side shipped by parallel replicas - #113364

Closed
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-112246-parallel-replicas-alias-column
Closed

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-112246-parallel-replicas-alias-column

Conversation

@groeneai

@groeneai groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

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 NO_SUCH_COLUMN_IN_TABLE when a query with parallel replicas selects an ALIAS column of a table that is shipped as a GLOBAL JOIN temporary table. Closes #112246.

Description

Closes: #112246

Under parallel replicas, selecting an ALIAS column of the table expression shipped as a GLOBAL JOIN temporary table failed:

Code: 16. DB::Exception: There is no column or subcolumn a_v in table. (NO_SUCH_COLUMN_IN_TABLE)

The issue title names RIGHT/RIGHT SEMI/RIGHT ANTI with parallel_replicas_prefer_local_join = 0, but none of that is required: a GLOBAL INNER JOIN at default settings fails too, on either side. What matters is only that the alias-owning table expression is the shipped one.

Root cause: rebuilding the shipped subquery reduces each referenced column to a name and a type, dropping the ALIAS column's resolved expression. The column is then classified as physical, because that classification tests exactly whether the expression is present, and MergeTree fails to read it. The plain distributed path is unaffected because it inlines alias columns beforehand; neither parallel-replicas caller does.

The fix carries the resolved expression into the shipped subquery, so the analyzer's existing handling computes the alias right after reading, as on every path that does not ship. It then clears the expression on the columns that now point at the materialized temporary table, so the alias is evaluated exactly once whichever way the query is dispatched.

Validation: both reported reproducers fail before and pass after; a 45-shape matrix (either side, five join kinds, Nullable, LowCardinality, alias-on-alias, alias over MATERIALIZED, a declared type differing from the body's, ARRAY JOIN, GLOBAL IN, JOIN USING, nested subqueries, all dispatch modes) goes from 29 failures to none, and 21 neighbouring distributed and alias tests are byte-identical. The two added tests assert values, names and types, and the alias evaluation count.

The MULTIPLE_EXPRESSIONS_FOR_ALIAS failure the plain distributed path has with the same alias name on both sides of a join is #107990, which has its own open PR; it is untouched here.

groeneai and others added 2 commits August 4, 2026 14:45
…el replicas

Selecting an ALIAS column of the table expression that parallel replicas ship as a
GLOBAL JOIN temporary table failed with

  Code: 16. DB::Exception: There is no column or subcolumn a_v in table.
  (NO_SUCH_COLUMN_IN_TABLE)

The issue reports it for RIGHT / RIGHT SEMI / RIGHT ANTI with
parallel_replicas_prefer_local_join = 0, but none of that is required: a GLOBAL INNER
JOIN at default settings fails too, with the alias on either side. What matters is
that the alias-owning table expression is the one being shipped.

CollectColumnSourceToColumnsVisitor reduced every referenced column to a
NameAndTypePair, so the resolved expression of an ALIAS ColumnNode was discarded
before buildSubqueryToReadColumnsFromTableExpression rebuilt the projections. The
shard therefore received a ColumnNode with no expression child, isAliasColumn returned
false because it tests exactly that, CollectSourceColumnsVisitor took the
ordinary-column branch instead of addAliasColumn, and MergeTree tried to read the
alias as a physical column. The plain distributed caller is unaffected because
StorageDistributed runs ReplaseAliasColumnsVisitor first, which leaves no alias
ColumnNode to lose; neither parallel-replicas caller has such a pre-pass.

Record the resolved expression alongside the name and type, under isAliasColumn's own
source-type guard so a JOIN / CROSS_JOIN / ARRAY_JOIN sourced ListNode is not mistaken
for an alias body, and re-attach it to the rebuilt projections. Both construction
sites need it: the table branch via ColumnNode::setExpression, and the ARRAY_JOIN
branch via the three-argument constructor. Reverting only the second one reintroduces
the failure for ARRAY JOIN queries, so it is not redundant.

cloneAndReplace copies a node's children and only rewires the weak source, so a
preserved expression would survive onto columns whose source is now the materialized
temporary table. That table is built from a plain column list with no ALIAS defaults,
so the value is already computed there, and leaving the expression attached makes the
alias evaluated a second time on the local-plan path while the AST path reads the
stored value. Clear it again on exactly the temporary tables created here, matched by
identity rather than by temporary-table name: CREATE TEMPORARY TABLE, recursive CTEs
and materialized CTEs also set that name and must not be touched.

The MULTIPLE_EXPRESSIONS_FOR_ALIAS failure that the plain distributed path has when
the same alias name resolves on both sides of a join is issue ClickHouse#107990 and has its own
open PR; no line it touches is modified here.

Tests: 04760 asserts values, column names and types over the alias, join-kind and
dispatch matrix, including nested subqueries which route through the other shipping
caller. 04761 asserts the alias evaluation count, which is what catches the second
evaluation described above; a value-only test cannot see it. Both pin
automatic_parallel_replicas_mode and parallel_replicas_local_plan, otherwise the test
runner's randomization moves the queries off the path under test.

Closes: ClickHouse#112246
The shipping path these tests exercise (buildQueryTreeForShard, reached from
ClusterProxy/executeQuery.cpp and findParallelReplicasQuery.cpp) exists only on
the analyzer path: with allow_experimental_analyzer = 0 the query is planned by
InterpreterSelectQuery and never enters that file.  Two stateless CI jobs run
with that profile (ci/defs/job_configs.py:762,775, linked by
tests/config/install.sh:296-298).

Measured on a 1-shard/3-replica localhost cluster with the old-analyzer profile
active: unpinned, both tests FAIL there with
"Code: 47 UNKNOWN_IDENTIFIER: Unknown column: a_v", because the old resolver
cannot resolve a table-qualified ALIAS column across a JOIN - a shape every
query in both tests uses.  With the pin they pass, and they still fail with the
PR's own "Code: 16 NO_SUCH_COLUMN_IN_TABLE" on a binary without the fix, so
liveness is preserved.

enable_analyzer is pinned rather than the test being skipped with
no-old-analyzer, because a skip would buy no coverage in those jobs.  In the
laziness test the flag goes on every arm including the enable_parallel_replicas=0
control, so the three arms differ in the dispatch mode alone.

No reference byte and no source line changes.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds; 1 major agreed and fixed, 2 nits agreed, 1 nit disagreed)

An independent cold review plus a second-model gate ran over this change twice
before it was published. Verdicts below.

Agreed and fixed

⚠️ The two new tests did not force the analyzer. The changed code is
analyzer-only: buildQueryTreeForShard takes a planner context and a query
tree, and its two parallel-replica callers exist only on that path. An
old-analyzer stateless job exists (install.sh --analyzer links
users.d/analyzer.xml, which sets allow_experimental_analyzer = 0 in the
default profile with no constraints), and CIDB shows it running the closest
sibling of these tests,
03452_array_join_global_right_join_parallel_replicas, 6648 times in 21 days.
Both tests now pin enable_analyzer = 1 on every arm, including the
no-parallel-replicas control arm, following
03634_subcolumns_in_temporary_table_parallel_replicas. Pinning was chosen
over the no-old-analyzer tag because the tag skips the test where coverage is
wanted. Measured afterwards on a server started with that job's profile: without
the pin these tests do not merely under-test, they fail there with
Code: 47 UNKNOWN_IDENTIFIER on both binaries, because the old resolver cannot
resolve a table-qualified ALIAS column across a JOIN at all. With the pin
they fail on pristine master with this PR's own Code: 16 and pass with the fix.

⚠️ PR description was over the length budget. Condensed before publishing.

Agreed, noted, not blocking

💡 The parallel_replicas_prefer_local_join = 0 block of 04760 runs only
under parallel_replicas_local_plan = 1. The fix site is dispatch-independent
and the later block covers parallel_replicas_local_plan = 0 for the GLOBAL
shapes, so this is a matrix gap rather than a coverage gap in the fix.

💡 Draft PR #107700 touches the same file and adds an alias-inlining pre-pass at
both parallel-replica call sites. It is a different fix layer for a different
issue (#107696, NUMBER_OF_COLUMNS_DOESNT_MATCH on duplicate alias names) and
does not restore the dropped expression, so it is not a duplicate; recorded here
so the overlap is not a surprise.

Disagreed, with evidence

💡 A suggestion to memoize the new tree walk in
demoteAliasColumnsOfMaterializedTables was declined. setExpression(nullptr)
is idempotent so repeat visits are harmless, and the two pre-existing walks in
the same file (the ARRAY JOIN projection walk and
rejectUnshippableJoinUsingKeys) are equally unmemoized on master; adding a
visited set would make the new function the only exception.

Checked and clean

The alias-column guard is byte-equivalent to the planner's own isAliasColumn
predicate. The demotion is required and correctly ordered: cloneAndReplace
copies a node's children and retargets only the weak source, so without it a
preserved expression would survive onto a column now sourced from the
materialized temporary table, whose column description carries no ALIAS
default, and the alias would be computed twice. A mutation arm that removed the
demotion reproduced exactly that, 20 / 40 / 20 sleep calls across the three
dispatch modes. The predicate is an identity set over the two temporary tables
this function creates, so CREATE TEMPORARY TABLE, recursive CTEs and
materialized CTEs cannot be affected. Attaching an expression does not change
ColumnNode hashing or equality, so the shipped temporary-table name and the
SQL text sent to replicas are unaffected. Analyzer/Utils.cpp and
StorageDistributed.cpp are untouched, so the other callers of the shared
subquery builder are unaffected and this composes with #108025 in either merge
order.

Session id: cron:clickhouse-review-slot-50:20260804-171931

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Both reported reproducers fail on every attempt on pristine master 8c925c5bbe977b5 on a 1-shard/3-replica localhost cluster, with no randomization needed: the GLOBAL INNER JOIN self-join at default settings, and the RIGHT ANTI JOIN with parallel_replicas_prefer_local_join = 0. Both give Code: 16 ... a_v.
b Root cause explained? Yes. When a GLOBAL JOIN side is shipped, the collected columns are reduced to names and types, dropping the ALIAS column's resolved expression. The rebuilt projection therefore has no expression child; isAliasColumn tests exactly that, so on the shard the column takes the ordinary-column branch and MergeTree throws NO_SUCH_COLUMN_IN_TABLE. Confirmed from the shipped subquery text in a trace log. The plain distributed path inlines alias columns before this point; neither parallel-replicas caller does.
c Fix matches root cause? Yes. The resolved expression is preserved across the lossy conversion, so the analyzer's existing alias handling computes it right after reading, as on every path that does not ship. No widened bound, no reduced dataset, no new setting, no guard at the throw site.
d Test intent preserved / new tests added? Yes. No existing test is modified, weakened or removed. Two new tests: one asserting values, column names and toTypeName across four dispatch sections, one asserting the alias evaluation count.
e Both directions demonstrated? Yes, at three levels. A 45-shape matrix: 29 failures before, 0 after. clickhouse-test on the new tests: both fail before, both pass after. --test-runs 50: 20 consecutive failures before (the runner stopped at its failure-chain limit), 100/100 passes after. All runs on Build-ID-verified binaries.
f Fix is general across code paths? Yes. All three callers of the shipping helper are accounted for: both parallel-replicas callers are fixed (the second one, reachable when parallel replicas are pushed into a subquery, was verified by instrumentation and now has test rows), and the plain distributed caller is provably inert because its own pre-pass removes every alias column first. All three construction sites of the shipped subquery were checked: the table and ARRAY JOIN sites are fixed, the subquery site is not a carrier. Reverting only the ARRAY JOIN site reintroduces a failure, so it is independently necessary.
g Fix generalizes across inputs? Yes. Covered: Nullable, LowCardinality, an alias whose declared type differs from its body's (so the cast wrapper is carried), alias over another alias, alias over a MATERIALIZED column, an alias body containing its own inner AS alias, two aliases with identical bodies selected together, the same alias name on both sides of the join, alias in ON only, alias in ON and the projection, JOIN USING, GLOBAL IN, ARRAY JOIN on either side, nested subqueries, and all three dispatch modes.
h Backward compatible? Yes. No setting default changes, no serialization or wire format change, no new validation on existing data, so no SettingsChangesHistory.cpp entry and no experimental gate.
i Invariants and contracts preserved? Yes, and the invariant has two halves, both tested. Inside the shipped subquery an ALIAS column must arrive with its resolved expression, so the shard computes it instead of reading it. Outside it, every column retargeted to the materialized temporary table must carry no expression, so the alias is evaluated exactly once and identically on all dispatch paths; the retargeting keeps children while only rewiring the source, so this needed an explicit step. Removing that step makes the evaluation-count test report the alias computed twice on one path and once on another, while the value-only matrix stays green, which is why the second test exists. The predicate is an identity set of the temporary tables created here, not a name test, so user CREATE TEMPORARY TABLE and CTE aliases are untouched (verified).

Session id: cron:clickhouse-impl-slot-41:20260804-115000

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @yakov-olkhovskiy @nickitat, could you review this? Shipping a GLOBAL JOIN side under parallel replicas rebuilds the subquery projections from names and types only, which drops an ALIAS column's resolved expression, so the shard classifies it as physical and MergeTree throws NO_SUCH_COLUMN_IN_TABLE; the fix carries the expression through and then clears it on the columns retargeted to the materialized temporary table so the alias is still evaluated exactly once.

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

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [00a48df]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) FAIL
Logical error: ColumnBLOB should be converted to a regular column before usage (STID: 3059-4608) FAIL cidb
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: Duplicate announcement received for replica number A (STID: 8765-7341) FAIL cidb
Stress test (amd_msan) FAIL
Logical error: 'column->size() == num_rows' (STID: 2508-562d) FAIL cidb

AI Review

Summary

This PR preserves resolved ALIAS expressions when buildQueryTreeForShard materializes a shipped GLOBAL JOIN side for parallel replicas, then clears those expressions from the retargeted outer-tree columns so the alias is still evaluated exactly once. I traced the changed TABLE, TABLE_FUNCTION, ARRAY JOIN, and nested-subquery carriers, checked the interaction with cloneAndReplace, CollectTableExpressionData, and the existing distributed alias-inlining path, and I did not find a remaining correctness, compatibility, or test-coverage issue in the current code. CI for PR #113364 is all green.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.80% +0.10%

Changed lines: Changed C/C++ lines covered: 69/71 (97.18%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 4, 2026
The amd_debug flaky check failed 2 of 100 runs of
04760_parallel_replicas_global_join_alias_column with "Test runs too long
(> 180s)". Both failing runs drew --max_threads 32, which the runner
picks with probability 0.03 (tests/clickhouse-test: "max_threads":
lambda: 32 if random.random() < 0.03 else random.randint(1, 3)).

Per-run durations from the job report: 48 passing runs spanned
69.7-104.1s while the two failures were 198.2s and 210.8s, so the
distribution is bimodal rather than a threshold straddle, and the two
outliers coincide exactly with the only setting drawn at ~3%.

The cost is per-query cluster dispatch overhead, not data volume:
recreating the fixture at 10 rows instead of 100 leaves the per-query
cost unchanged (0.166s vs 0.174s), so shrinking the fixture cannot help.
Oversubscription is what amplifies max_threads=32: pinning the server to
8 CPUs instead of 96 moves the 32-vs-4 ratio from 1.09x to 1.36x, and the
CI runner is smaller still, which matches the ~2.1x seen there.

Clamping the setting is the per-setting remedy the maintainers ask for
instead of a blanket no-random-settings tag, and max_threads has in-tree
precedent in 03469_json_read_subcolumns_combined_2_compact_merge_tree.
Measured over 200 forced-failure samples each: without the clamp
max_threads=32 is drawn 11 times, with it 0 times and one clamped 4.

Every assertion and the .reference file are unchanged, and the test still
reddens on the pre-fix binary with the Code: 16 this PR fixes.
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

Fixed the flaky-check runtime failure on 04760

Stateless tests (amd_debug, flaky check) failed 2 of 100 runs of
04760_parallel_replicas_global_join_alias_column with Test runs too long (> 180s).
Pushed 00a48df, which adds one line to that test and changes nothing else.

The per-run durations show the shape of the problem: 48 passing runs span 69.7-104.1s, then
there is a gap to the two failures at 198.2s and 210.8s. That is bimodal rather than a
threshold straddle, and both failures drew --max_threads 32, which the runner selects with
probability 0.03 (tests/clickhouse-test:1442).

Two measurements decided the remedy:

  • Shrinking the fixture would not help. Recreating it at 10 rows instead of 100 leaves the
    per-query cost unchanged (0.166s vs 0.174s), because the cost is per-query cluster dispatch
    overhead, not data volume. Statement-level timing is flat: slowest 0.21s, median 0.15s.
  • max_threads=32 hurts more the smaller the machine. Pinning the server to 8 CPUs instead of
    96 moves the 32-vs-4 ratio from 1.09x to 1.36x, and the CI runner is smaller and shares cores,
    which is consistent with the ~2.1x seen there. That is also why a 50x local run during
    development did not surface it.

So the fix clamps that one setting instead of tagging the test no-random-settings:

-- Random settings limits: max_threads=(None, 4)

03469_json_read_subcolumns_combined_2_compact_merge_tree already clamps max_threads the
same way.

The oracle is untouched: .reference is byte-identical, every assertion is unchanged, and the
test still reddens on the pre-fix binary with the Code: 16 ... no column or subcolumn a_v
this PR fixes, both at the default max_threads and at the clamped value of 4.

Validation: over 200 forced-failure samples per arm, max_threads=32 is drawn 11 times without
the clamp and 0 times with it (plus one 4, which can only be a clamped 32, since the randomizer
never draws 4 natively). --test-runs 50 is 50/50 OK. Neighbours re-run green, including
01834_alias_columns_laziness_filimonov and 03452_array_join_global_right_join_parallel_replicas.

I did not add the long tag: it exempts the test from the cap entirely
(tests/clickhouse-test:3450-3455), which would hide the signal rather than fix it.

Session id: cron:clickhouse-maint-slot-19:20260804-202100

@yakov-olkhovskiy yakov-olkhovskiy self-assigned this Aug 4, 2026
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 00a48df

CI fully finished on this head: 174 of 174 check-runs completed (154 success, 17 skipped,
3 failure), 0 queued or in progress, Config Workflow and Finish Workflow both green,
past the 20-minute CIDB ingestion buffer.

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / Logical error: ColumnBLOB should be converted to a regular column before usage (STID 3059-4608) pre-existing trunk defect: a ColumnBLOB reaches a consumer requiring a materialized column. Failing query SELECT DISTINCT __table1.a_cast, __table1.v, __table1.k FROM clusterAllReplicas(...), produced by the fuzzer #111997 (mine, merged 2026-08-04T21:56:55Z) fixes this family. It is not on this head: comparing its merge commit a6827f5554f9 against this head reports diverged, 747 commits behind, so this build predates the fix and the failure is already resolved in master
AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: Duplicate announcement received for replica number 2 (STID 8765-7341) pre-existing parallel-replicas announcement defect reached through a fuzzer-rewritten merge(currentDatabase(), 't_alias') join with a window clause; unrelated to this PR's diff a fix task is moved to pending (investigating at full effort, fixing-PR link to follow on this PR)
Stress test (amd_msan) / Logical error: column->size() == num_rows (STID 2508-562d) pre-existing trunk defect where a produced column's row count disagrees with the block's; reached by the stress thread fuzzer, 1 failure out of 5 in that job #113225 (mine, open) fixes this family
Build (arm_release) / Post Hooks build-profile telemetry INSERT INTO build_time_trace got LogCluster query failed with code 500. The build itself passed: the job's check_status is success and the check-run concluded success, so it gates nothing infra, not this PR. A fix task is moved to pending (investigating at full effort, fixing-PR link to follow on this PR)

None of these is reachable from this PR's diff: two are fuzzer-generated queries against tables
this change does not define, one is a stress-only sanitizer assertion, and one is build telemetry.
This head is also 747 commits behind the master commit that carries the ColumnBLOB fix, so the
first row is expected to clear on a fresher base.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113364&sha=00a48dfbf080f00f75f18890cca059ec85ae3884&name_0=PR

Session id: cron:our-pr-ci-monitor:20260805-023000

cursor Bot pushed a commit that referenced this pull request Aug 5, 2026
`04757` grows the shapes it was missing relative to #113364's own matrix: two `ALIAS` columns with
identical bodies, `ARRAY JOIN` on either side, `GLOBAL RIGHT JOIN`, and `GLOBAL JOIN ... USING` both
selecting the key and selecting an `ALIAS` column beside it.

`04758` is the #107990 regression test from #108025,
covering the same-named `ALIAS` column referenced from `JOIN ON` / `WHERE` / `GROUP BY` / `ORDER BY` /
a projection expression / a `GLOBAL JOIN` subquery over real `Distributed` tables. It reports six
`MULTIPLE_EXPRESSIONS_FOR_ALIAS` on master.

`04759` is the laziness test from #113364: an `ALIAS`
column of a shipped table expression must be computed once per row on every dispatch path. Inlining
keeps that property, so the reference is identical to that pull request's. On master the
`parallel_replicas_local_plan=1` arm throws instead of reporting a count.

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

Copy link
Copy Markdown
Member

closing in favor of #107700
@groeneai check the superseding PR fully covers this PR

cursor Bot pushed a commit that referenced this pull request Aug 5, 2026
The SQL rewrite read `SleepFunctionCalls` from `system.query_log`, which does not hold up. Which entry
carries the counter depends on the dispatch path - the initiator aggregates the replicas' events when
shipping a plan but not when shipping SQL - so the replicas' own entries have to be summed, and in CI
they are not reliably in `query_log` by the time the initiator's query returns: the arm that ships SQL
reported 0 instead of 20. The runner also sets its own `log_comment` per test, which the prefix filter
picked up as a spurious extra row.

The client's `--print-profile-events` aggregate is delivered in band with the query, so it has neither
problem. Restore the shell form, which is the one #113364 has already had green in CI.

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

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Checked by measurement rather than by reading the two diffs: #107700 fully covers this PR, and covers strictly more. No objection to the close.

Method: three debug builds in one worktree, same server config and the same fixture data. Base is pristine master at my base 8c925c5; "mine" is this PR's head; "yours" is your src/ delta transplanted onto that same base, which is sound because 4 of the 6 files you touch are byte-identical between our two bases, including all of buildQueryTreeForShard.cpp. For the other two I compared the deltas instead of the files, and both are byte-identical. Each server's buildId() was asserted against its binary before every verdict.

45-shape matrix (5 join kinds, both sides, Nullable/LowCardinality/declared-type-differs/alias-on-alias/alias-over-MATERIALIZED, ARRAY JOIN, GLOBAL IN, JOIN USING, nested subqueries, both dispatch modes; full TSVWithNames compared against the same query with enable_parallel_replicas = 0, so wrong results count and not only errors):

  • base: 16 ok / 29 FAIL
  • mine: 45 ok
  • yours: 45 ok, and the output is byte-identical to mine

My two tests on your build: 04760 and 04761 both pass unmodified. Both FAIL on base, so they do discriminate.

Your four tests on my build: 04757 and 04758 FAIL with Code: 179. That is the real difference between the two patches and it is in your favour. On my build 04757 reaches statement 54 of 59 and fails there: all 53 preceding statements pass, including every parallel-replicas shape in the file, and 54 is the first SELECT after SET enable_parallel_replicas = 0, over remote(). Both failing shapes fail identically on base, so this is MULTIPLE_EXPRESSIONS_FOR_ALIAS on the Distributed path (issue #107990), which my PR never addressed. Routing both paths through one inlineAliasColumns is what buys that.

Regression sweep: clickhouse-test alias parallel_replica distributed, 682 tests, identical invocation on both arms. Zero tests fail on yours that pass on base; 5 are genuinely fixed. Ten more looked fixed but are concurrency flakes of my single-slot harness: 9 of them pass on base when re-run serially, and 04064_grouping_function_distributed_single_shard passes on both arms with --no-random-settings, my minimal config having no process_query_plan_packet.

Double evaluation, the one thing I expected inlining could get wrong given mine carries the resolved expression instead. Measured with a sleepEachRow alias body, no LIMIT, and the full result set checksummed against ground truth: values are identical on every arm. Your build reports 20 SleepFunctionCalls where ground truth reports 40, but that is common-subexpression elimination of the textually identical subexpression in my fixture, not a dropped evaluation: giving the two sides different sleep durations restores 40/40. So inlining evaluates the body fewer times, never more, and never changes a value.

Two findings that are properties of the bug rather than of either patch, both already handled in your tests, recorded here only so they are not lost:

  • The reported RIGHT / parallel_replicas_prefer_local_join = 0 framing is too narrow. A plain GLOBAL INNER JOIN at default settings fails as well, on either side. Your 04757 already covers both sides and five join kinds.
  • A test for this must pin enable_analyzer = 1, and not merely to avoid under-testing: without it the old-analyzer jobs FAIL with Code: 47 UNKNOWN_IDENTIFIER, because the old resolver cannot resolve a table-qualified ALIAS column across a JOIN at all. All four of your tests pin it.

04759 is my 04761 with reworded comments, which is fine by me under your numbering.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the STID 8765-7341 Duplicate announcement received for replica number 2 logical
error on my CI finish ledger above: #110972 (external, open).

Root cause: merge(currentDatabase(), 't_alias') also matched Distributed clones, which makes the
Merge storage remote. A remote non-leftmost table expression is wrapped in a subquery that is
planned with a fresh, empty GlobalPlannerContext (PlannerJoinTree.cpp:2177), so the initiator's
designated parallel-replicas table is erased, while nothing clears enable_parallel_replicas. The
Distributed sibling also raises the Merge processing stage above FetchColumns, so the
MergeTree child is re-planned by a nested Planner that designates the same physical table again
and arms a second coordinated read. Both derive the same stream id, the coordinator sees one stream,
and the second announcement throws at ParallelReplicasReadingCoordinator.cpp:227.

The safety check at PlannerJoinTree.cpp:1901-1905 was written for exactly this ("a non-trivial
storage like View might create its own Planner inside read(), run findTableForParallelReplicas() and
find some other table"), but it could not fire: in the nested Planner the merge is a
TableFunctionNode, so table_node is null, and the fresh context makes
parallel_replicas_table null too, leaving nullptr != nullptr. #110972 substitutes the non-null
table_function_node as that comparison's left operand, so the guard fires and the nested read falls
back to an uncoordinated read. I verified this by building its src/ delta on the failing base: the
reproducer and a 10-arm carrier matrix are clean at default settings, and armed coordinated reads per
replica go from 2 to 1.

Two notes for whoever picks this up later. Its repair of this particular shape is incidental: its new
fail-closed checks are gated on parallel_replicas_allow_merge_tables (default false), but the
operand substitution is not, and none of its tests exercise the default path. And the failure is
unrelated to this PR's diff, which only contributed the fixture table the targeted fuzzer reused.

Reproducer, for the record: a MergeTree table joined against merge(db, '^t') where the regex also
matches a Distributed table. A regex matching only the joined table is correct, which is the
control.

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
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

Projects

None yet

3 participants