Skip to content

The _database and _table virtual columns of a Merge table carry the matched child's name again - #115356

Open
alexey-milovidov wants to merge 67 commits into
masterfrom
merge-table-virtual-columns
Open

alexey-milovidov wants to merge 67 commits into
masterfrom
merge-table-virtual-columns

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 18, 2026 •

Copy link
Copy Markdown
Member

Closes: #103631
Related: #113735
Related: #84139
Related: #63665
Related: #102471
Related: #107418
Related: #113242
Related: #116371

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 a WHERE _table = ... or WHERE _database = ... filter over a Merge table silently returning no rows when the matched child reads through another table, for example a Distributed, a nested Merge, or a Buffer child. The _database and _table virtual columns of a Merge table now always carry the name of the matched child, as they did before 25.7, not the name of the table the child delegates its read to.

Description

ReadFromMerge::getSelectedTables prunes the children of a Merge table by evaluating a filter on _database/_table against each child's own name, but the values in the rows were stamped by whatever storage eventually read them - for a Distributed child, the remote table on the shards. The two sides contradicted each other, and every query where both fire silently returned wrong results: a filter naming the child returned no rows (pruning kept the child, but no row carried its name), and a filter naming the remote table returned rows only at processing stages where the pruning happened not to fire.

CREATE TABLE t_leaf (s String) ENGINE = MergeTree ORDER BY s;
CREATE TABLE t_dist AS t_leaf ENGINE = Distributed(test_cluster_two_shards_localhost, currentDatabase(), t_leaf);
CREATE TABLE m (s String) ENGINE = Merge(currentDatabase(), '^t_dist$');
SELECT count() FROM m WHERE _table = 't_dist';  -- 0 on master, all rows with this fix

History. Before #63665 (25.7), the Merge engine substituted the child's own name for _table/_database itself (WITH '<child>' AS _table per child), so the values and the pruning agreed. #63665 gave every table its own _table virtual column, which disabled that gated substitution: the reader deep down stamps the name, and for a delegating child that is a different table. #102471 then removed the dead substitution machinery, and #107418 pinned the new values with a regression test - while the pruning kept matching child names all along.

The fix makes the Merge engine produce these columns itself again, unconditionally: references to them are replaced with a constant carrying the child's name right in the child query tree (so expressions computed on the shards see it too; the action name is pinned via __actionName over a String constant, wrapped into toLowCardinality to keep the type, which keeps the query sent to the shards readable by older servers), and at FetchColumns the constant columns are added to the child plan, inserted at the positions the columns have in the requested header, because a child whose execution names differ from the common header (a Distributed child) is matched by position in convertAndFilterSourceStream. A child that has a physical column of one of these names does not get to keep it: the constant overwrites that column, after the child's own ALIAS expressions and row policy filter have consumed it (they are evaluated against the child's columns, so its value has to survive until they have run). This is what #103631 reports from the other side - there SELECT _table showed the child's physical value while WHERE _table = ... still pruned by child name, so the two contradicted each other. Only the child-name direction can be made consistent, and it is also the historical one: the rewriteEntityInAst that #63665 disabled injected the child's name as a WITH alias with setPreferAliasToColumnName(true), which won over a physical child column of the same name.

This is a deliberate semantic choice, and the alternative is #113735. Only one of the two semantics can be consistent with pruning: the pruning can only ever match the child's name, since the Merge table cannot know which table a child delegates to without classifying every child. #113735 keeps the underlying-table values and therefore has to prove, per storage class and recursively through Buffer/Alias/proxy wrappers, whether a child stamps its own name - with a fail-closed carve-out for streaming engines. Under child-name semantics all of that machinery is unnecessary, streaming children keep being pruned exactly as before, and the docs' claim that "the _table column acts as an index" is actually true. The cost: _table through Merge over Distributed reads t_dist, not t_leaf; each nesting level of Merge reports its own child. Tests 00717 (whose leaf-name expectations were rewritten in #63665 itself), 03094, 04338, 04367, 03031, 01902, 03988, 04104 and 01155 are updated accordingly; the new test 05055_merge_virtual_columns_delegating_children covers the pruning and the values over Distributed, nested Merge and Buffer children. The new test 05055_merge_virtual_columns_shadowed_by_child_column covers the name collisions: a child with a physical _database/_table, a child whose only column is named _table, a row policy that needs that column, an ALIAS computed from it, and a Merge that declares _table itself as a real column (where the child's column correctly wins).

A Distributed child whose remote table has a physical _database or _table column, queried so that the shard reads no other real column (e.g. SELECT _database FROM m or SELECT count() FROM m WHERE _table = 'child'), is handled as well: above FetchColumns the injected constant is pinned to an action name of its own (__merge_virtual_column._table), so the shard's physical column cannot shadow it, and addVirtualColumns renames it back. 05055_merge_virtual_columns_delegating_children and 05397_merge_virtual_columns_in_child_alias_over_distributed cover it for both columns.

Interaction with #116371. A rework of #113735 has since landed on master as #116371: it keeps the underlying-table values and exempts children with readsFromOtherTables from the pruning. This PR replaces that semantics: since the rows now always carry the child's name, the exemption is removed from ReadFromMerge::getSelectedTables (every child is pruned by its own name again), and the tests 05043_merge_prefilter_delegating_children and 05045_merge_prefilter_lazy_load_tables from #116371 are updated to the child-name values. readsFromOtherTables itself stays, as the analyzer and parallel replicas use it.

This also unblocks #113242, whose only functional CI failure was 00717_merge_and_distributed newly reaching the pruning defect at FetchColumns.


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

getSelectedTables prunes the children of a Merge table by evaluating a
`WHERE _table = ...` filter against each child's own name, but the values in
the rows were stamped by whatever storage eventually read them - for a
`Distributed` child, the remote table on the shards. A filter naming the
child then silently returned no rows, and a filter naming the remote table
returned rows only where the child pruning happened not to fire.

The Merge table now substitutes the child's own name for `_database` and
`_table` references in every child query (as a constant in the query tree,
so expressions computed on the shards see it too), and adds the constant
columns to the child plan at FetchColumns, so the row values and the child
pruning agree by construction for every child, including one that delegates
its read: `Distributed`, a nested `Merge`, `Buffer`.

This restores the pre-25.7 semantics: the visible values changed as a side
effect of #63665, which gave every table its own `_table` virtual column and
thereby disabled the Merge-level substitution that existed before, while the
pruning kept matching the child names.

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

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4a7af16]

Summary: ✅


AI Review

Summary

Restores matched-child names for the _database and _table virtual columns of Merge, keeping their values consistent with child pruning across delegating storages. The current code addresses the prior findings, including child-owned ALIAS inputs, substitute reads, identifier quoting, and older-shard compatibility. No actionable findings remain.

Missing context / blind spots
  • ⚠️ Full stateless and integration CI for 4a7af162182e2e9f3a1ff249d4558d9cfcb77549 is still running. The head's Fast test report passes all ten enabled new stateless regressions; the Parquet regression is excluded from Fast test. Remaining CI must provide the Parquet and mixed-version integration results. No local ClickHouse execution was available in this review job.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 18, 2026
alexey-milovidov and others added 5 commits August 19, 2026 06:55
…ge` virtual columns

The `_table` virtual column of a `Merge` table over a `Distributed` child
now carries the `Distributed` child's own name instead of the remote table
name, and rows read through a delegating child are no longer silently
dropped when `_table` is selected: test `01155_rename_move_materialized_view`
gains the previously missing `dist` / `after moving tables` rows.

Fast test report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115356&sha=af4c8f17141e7dc047b9839d949c4a9d6fa89c0b&name_0=PR&name_1=Fast%20test
PR: #115356

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Storages/StorageMerge.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4a7af1621 with master 6d2bccb15 (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.

Object file sizes

7 object files changed (+109.58 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageMerge.cpp.o 1.59 MiB 1.69 MiB +109.57 KiB (+6.75%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

…en the query-info cache guard

Three follow-ups after the CI run of the previous commit:

- `TreeOptimizer` drops literals from `GROUP BY` and, when nothing is left,
  replaces the whole clause with the placeholder key
  `'__unused_group_by_column'`. The bare `WITH 'child' AS _table` literal the
  pre-analyzer path injects therefore vanished from a child that groups by the
  virtual column alone, and the child produced a mergeable block whose key
  column was the placeholder - the `Merge` then filled `_table` with the default
  empty string. Inject `WITH identity('child') AS _table` instead: `identity` is
  neither injective nor suitable for constant folding, so the key survives while
  the value is unchanged. This is what
  `05019_merge_virtual_columns_delegating_children` caught in the old-analyzer
  job.

- The query-info cache guard now keys off every reference to `_table` in the
  query tree, not only its presence among the columns the plan reads: the
  constant substitution in `getModifiedQueryInfo` is not conditioned on the
  column being requested. Addresses the review comment on
  `has_table_virtual_column` and adds the regressions it asks for - a filter-only
  reference across three same-structure children, and an `ALIAS` column over the
  child's own `_table`.

- `SELECT _table, * FROM m3 ORDER BY key ASC` in
  `03094_virtual_column_table_name` has ties on `key` now that the nested `Merge`
  child reports its own name, so the row order was not deterministic. Order by
  `_table` as well; the reference is unchanged.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115356&sha=63fd9a0855d0b0e581f962d443c2634cebd81c05&name_0=PR
Related: #115356
Comment thread src/Storages/StorageMerge.cpp Resolved
…-columns

# Conflicts:
#	tests/queries/0_stateless/04104_56208_merge_distributed_merge_chain.reference
…e remote `GROUP BY` check

`replaceColumns` deliberately stops at `QUERY`/`UNION` boundaries, so a correlated reference to
`_database`/`_table` - e.g. `WHERE EXISTS (SELECT 1 FROM numbers(1) WHERE m._table = 'child')` -
kept its `ColumnNode` and was evaluated by the child itself. For a child that delegates its read
(a nested `Merge`, a `Buffer`) that is the name of the storage which eventually reads the rows,
which is exactly what these columns must not report. Add a second pass that descends into
subqueries and replaces those references with a bare constant.

The reviewer's repro, `WHERE EXISTS(SELECT 1 WHERE _table = 't_dist')`, does not actually
reproduce: an unqualified `_table` there resolves against the subquery's own `system.one`, not
against the outer `Merge`, and the whole `EXISTS` is folded to a constant. A `Distributed` child
is not affected either - correlated subqueries over remote tables are rejected with
`NOT_IMPLEMENTED`. The new test covers the shapes that do reach the rewrite.

Also stop the remote `GROUP BY` check of the new test from depending on whether the initiator
merges the shards' partial aggregates: only the value of the grouping key is under test, and the
plan the distributed aggregation picks is not stable across the randomized settings of the flaky
check (observed once as two `t_dist` rows of 6 instead of one row of 12).
Comment thread src/Storages/StorageMerge.cpp Resolved
`addVirtualColumns` read a child header that already contains `_database` or
`_table` as "the value is already there". That is not a safe reading of that
header. The `Merge` table never requests these columns from a child, but three
other paths can still put a child column of the same name into its stream:

- the substitute for a read of nothing but virtual columns, which
  `ExpressionActions::getSmallestColumn` can pick a physical `_table` for;
- a column a row policy filter needs (`RowPolicyData::extendNames`);
- the child's own `_table` behind one of its `ALIAS` columns.

In each case the step yielded to the child's value, so the contract this branch
is about - the value is the matched child's name, the one the pruning in
`getSelectedTables` matches - did not hold:

```sql
CREATE TABLE child (`_table` UInt8, x UInt8) ENGINE = MergeTree ORDER BY x;
INSERT INTO child VALUES (7, 1);
CREATE TABLE m (x UInt8) ENGINE = Merge(currentDatabase(), '^child$');

SELECT _table FROM m;                          -- 7, not `child`
SELECT count() FROM m WHERE _table = 'child';  -- 0, though the child does match
SELECT _table, x FROM m;                       -- `child` 1: the same value, read differently
```

The constant now replaces such a column instead of yielding to it. The step also
moved into `convertAndFilterSourceStream`, after the child's `ALIAS` expressions
and its row policy filter: both are evaluated against the child's own columns, so
the child's value has to survive until they have run, and only after that does the
name belong to the `Merge`. An `ALIAS` over the shadowing column keeps computing
from the child's value, while `_table` reports the child's name.

Covered by the new test `05045_merge_virtual_columns_shadowed_by_child_column`
over a plain child, a child whose only column is named `_table`, a nested `Merge`,
a `Merge` that declares `_table` itself, a row policy and an `ALIAS` column, with
both analyzers.

One shape stays wrong, exactly as it is on `master`, and is out of scope here: a
`Distributed` child whose remote table has a physical `_table`. Above
`FetchColumns` the child executes the query itself, so this step never runs for
it, and the constant injected into its query tree is pinned by `__actionName` to
`__table1._table` - the column identifier the child's own planner gives that
physical column when it picks it as its own substitute - so the column shadows the
constant inside the child's actions.

Related: #115356 (review)
Both `05019` and `05045` are taken on `master`, and the `new_tests_check.py`
hook in `Finish Workflow` requires the next free number.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status after bringing the branch up to date (ca8401c25694):

  • Merged master into the branch (clean) and rebuilt the clickhouse target — it compiles and links.
  • Renumbered both new tests to 05055_…: 05019 and 05045 are both taken on master now, which is what the new_tests_check.py step of Finish Workflow was failing on.
  • Both new tests pass locally against this build (05055_merge_virtual_columns_delegating_children, 05055_merge_virtual_columns_shadowed_by_child_column).

The two remaining Fast test failures are neither flakes nor mechanically fixable — they are a head-on semantic conflict with the merged alternative:

05043_merge_prefilter_delegating_children and 05045_merge_prefilter_lazy_load_tables are the tests added by #116371, which was merged on 2026-08-29 and backported to 26.8.1.2033, 26.7.6.43 and 26.6.4.42. That PR keeps the leaf-name semantics of #63665 and fixes the pruning instead (IStorage::readsFromOtherTables), so it pins exactly the opposite values to this PR:

SELECT count() FROM merge(currentDatabase(), '^t_dist$') WHERE _table = 't_leaf';  -- master: 3, this PR: 0
SELECT count() FROM merge(currentDatabase(), '^t_dist$') WHERE _table = 't_dist';  -- master: 0, this PR: 3
SELECT DISTINCT _table FROM merge(currentDatabase(), '^t_dist$');                  -- master: t_leaf, this PR: t_dist

Reproduced locally with this branch: both master tests fail exactly and only on those value flips (Merge over Distributed, Merge over Merge, Merge over Buffer, Merge over Alias, and the lazy-proxy case), and nothing else.

As both PR descriptions say, only one of the two semantics can be consistent with the pruning, so this is a decision rather than a fix:

  1. Close this PR as superseded by Fix a _table/_database filter over a Merge table returning no rows for children that read from other tables #116371 — the released behaviour stays as it is.
  2. Keep the child-name semantics — then this PR additionally has to rewrite 05043_merge_prefilter_delegating_children and 05045_merge_prefilter_lazy_load_tables to the child-name expectations (and readsFromOtherTables becomes a pure de-optimization, since a delegating child's rows then always carry its own name), which re-changes user-visible behaviour already shipped in 26.6/26.7/26.8.

I did not touch those two tests, since flipping them back is the decision itself. Everything else on the branch is up to date and green-able.

@clickhouse-gh clickhouse-gh Bot added the comp-storage-merge Merge table engine (logical union over tables) and related mechanics. label Sep 4, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Brought the branch up to date again (5469d1ee840a): merged master (clean, no conflicts, 4369 commits) and rebuilt the clickhouse target — it compiles and links.

Re-verified locally against this build:

  • 05055_merge_virtual_columns_delegating_children — PASS
  • 05055_merge_virtual_columns_shadowed_by_child_column — PASS
  • every other test this PR touches — 00717, 01155, 01902, 03031, 03094, 03988, 04104, 04338, 04367, 04628 — PASS (03217 needs ZooKeeper and was not runnable on the local bare server).

The state of the only real blocker is unchanged and is still a decision rather than a fix: 05043_merge_prefilter_delegating_children and 05045_merge_prefilter_lazy_load_tables, added by the merged alternative #116371, pin exactly the opposite _database/_table values to this PR. Re-ran both against this build: the diffs are still only the value flips (t05043_leaf ↔ t05043_dist, t05045_leaf ↔ t05045_dist, and the corresponding count() 3 ↔ 0), nothing else.

So the two options from my previous comment still stand:

  1. Close this PR as superseded by Fix a _table/_database filter over a Merge table returning no rows for children that read from other tables #116371 — the behaviour released in 26.6/26.7/26.8 stays as it is.
  2. Keep the child-name semantics here — then this PR must additionally rewrite those two master tests to the child-name expectations, which re-changes already-shipped user-visible behaviour.

I have deliberately not touched those two tests, since flipping them is the decision itself.

alexey-milovidov and others added 2 commits September 17, 2026 06:43
…-columns

# Conflicts:
#	src/Storages/StorageMerge.cpp
#	tests/queries/0_stateless/04367_distributed_plan_merge_scatter_multishard.sql
…lumn tests

The old query analysis is rejected with `SETTING_CONSTRAINT_VIOLATION` since
26.9, so the `SETTINGS enable_analyzer = 0` variants of the queries in
`05055_merge_virtual_columns_delegating_children` and
`05055_merge_virtual_columns_shadowed_by_child_column` fail before they
produce a result. Only the analyzer variants remain, together with their
reference lines.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Brought the branch up to date again (d911f5e03ec8): merged master (4443 commits) with two conflicts resolved — the convertAndFilterSourceStream call site in StorageMerge.cpp now takes both master's new query_info argument and this PR's table argument, and 04367_distributed_plan_merge_scatter_multishard.sql keeps this PR's IN filter under master's updated plan comment. The clickhouse target builds and links.

One adaptation was needed: the old query analysis is rejected since 26.9 (SETTING_CONSTRAINT_VIOLATION), so the SETTINGS enable_analyzer = 0 probes were dropped from both 05055_… tests together with their reference lines. Only the analyzer variants remain; the C++ still carries the pre-analyzer WITH identity(...) substitution because that interpreter branch still exists in getModifiedQueryInfo on master.

Re-verified locally against this build: both 05055_… tests and 00717, 01155, 01902, 03031_…_special, 03094, 03988, 04104, 04338, 04367, 04628 PASS (03217 needs ZooKeeper and 03031_read_in_order_optimization_with_virtual_row needs system.query_log, neither available on the local bare server).

The only blocker is unchanged and is still the decision, not a fix: 05043_merge_prefilter_delegating_children and 05045_merge_prefilter_lazy_load_tables from the merged alternative #116371 still fail exactly and only on the _table/_database value flips (t05043_leaf ↔ t05043_dist, t05045_leaf ↔ t05045_dist and the corresponding counts). The two options from my earlier comments stand: close this PR as superseded by #116371, or keep the child-name semantics here and rewrite those two master tests, which re-changes behaviour already shipped in 26.6/26.7/26.8. I have again not touched those two tests.

@groeneai

Copy link
Copy Markdown
Collaborator

Findings for limit_by_with_order #3 (arm, 287ebdf): the slowdown came from where the code of that one binary was placed, not from a code change, and it is gone on the new head 50d6417 (0.56 -> 0.57 s, all 6 arm shards green, report). So there is nothing to fix in the code, and I'm not sending a PR.

  • The hot code is unchanged. MergingSortedAlgorithm::merge, its merge loop (the std::visit over the sorting queue), insertRows and the ColumnVector::compareAt/insertFrom it calls are instruction-identical after normalizing addresses, in this binary and in its reference (bc84324098, the master commit this head merged, built with the same flags). Only the placement differs: this PR adds about 27 KB of code to StorageMerge.cpp, so everything linked after it, the sort and merge code included, moved by 0x6a80 bytes, while the column functions it calls did not move.
  • Same work, different front-end behaviour: the job's own counters show the same instructions (14.82G vs 14.67G) with 4x the branch misses (2.6M vs 10.1M) and 6x the front-end stall cycles (0.11G vs 0.66G); back-end stalls are flat.
  • It belongs to that binary: it stayed slow after both restarts, the 7 other PR builds on the same reference ran it at 0.98-1.01x, and the 7 earlier arm builds of this PR at 0.99-1.02x. The same binary was also 1.37x on limit_by_misc #1 and 1.09-1.14x on three other sort queries, which were flat on all other builds of that reference and are flat again on the new head.

alexey-milovidov and others added 2 commits October 27, 2026 12:04
…e, skip lambda arguments

The check whether a column of a `Merge` child reads any child column kept every
visited `ALIAS` in one set, so an alias reached twice (`c ALIAS 1`,
`y ALIAS c + c`) was taken for a cycle and counted as reading a column, and the
substitute read was omitted again. Keep the active recursion stack separately
from the memoized results of finished visits.

Collect the inputs of an `ALIAS` expression with `RequiredSourceColumnsVisitor`
instead of `IdentifiersCollector`, so the arguments of a lambda
(`arrayMap(p -> p + 1, [1])`) are not taken for columns of the child.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and pushed 77015b0, together with the fix for the latest review thread (shared ALIAS dependencies, lambda arguments). Neither failure on the previous head 50d6417 came from this PR, and neither involves Merge:

Comment thread src/Storages/StorageMerge.cpp Resolved
alexey-milovidov and others added 2 commits October 28, 2026 08:14
…e analyzer, bind the substitute past a `Merge` alias

- Whether the requested `ALIAS` columns of a child read any of its columns is now decided by
  resolving them with `QueryAnalysisPass` against the child table, the way the child query is
  built, instead of walking the alias expressions syntactically. An alias the analyzer folds to a
  constant (`y ALIAS isNullable(p)`, `t ALIAS toTypeName(p)`) reads nothing, so the substitute is
  chosen before the child projection and `initial_storage_snapshot` are built. This also covers
  the shared-dependency and lambda cases handled by the previous syntactic walk.
- A substitute named like an `ALIAS` column of the `Merge` (`m (y UInt8, p UInt8 ALIAS 1)`) is
  now bound to the child's physical column, and replaces that alias in the snapshot the
  `Distributed` child resolves the query against, instead of expanding to the alias expression
  and losing the read.

Both cases threw `NOT_FOUND_COLUMN_IN_BLOCK` (expected `__table1.y`, got only `__table1.p`)
for an `ARRAY JOIN` or `JOIN` over a `Merge` of a `Distributed` child.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The BuzzHouse (arm_asan_ubsan) failure (Unexpected return type in DistributedSink::createSelector, STID 1611-3598) is unrelated to this PR. It is an INSERT into a Distributed table after ALTER TABLE ... MODIFY COLUMN changed the type a sharding key reads, and #127984 fixes it. Build profile diff failed on infrastructure: LogClusterNotReady: the endpoint never became ready.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and pushed 81019bf. The only failure on the previous head 20866e3 was Build profile diff (LogClusterNotReady: the endpoint never became ready), an outage of the CI logs cluster that has nothing to do with this PR. The CI fix, #128067, is now on master, so this merge brings it in. The merge had no conflicts, and StorageMerge.cpp compiles on the merged tree. All review threads are resolved.

alexey-milovidov and others added 3 commits October 30, 2026 04:45
…when choosing the substitute

A subcolumn of a child `ALIAS` column, such as `a.k` of `a Tuple(k UInt8) ALIAS tuple(1)`,
has no default of its own, so it was counted as a readable column and the physical substitute
was added only after the joined projection and snapshot had been built, which led to
`NOT_FOUND_COLUMN_IN_BLOCK` over a `Distributed` child. Send such subcolumns through
`aliasColumnsReadTableColumn` as well, and cover tuple, array-size and null-map subcolumns,
`_database`, an ordinary `JOIN`, and a nested `Merge` in `05452`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (no conflicts) and pushed f734686. The PR's diff against master is unchanged, the merged tree builds, and the PR's Merge virtual-column tests pass locally. No review threads are unresolved. The only red jobs on the previous head f1c9a4b were the Bugfix validation (integration tests) runs: test_cte_distributed failed there with the xfail label, which is the expected result in that job, and the overall report is green.

Resolve the conflict in `StorageMerge.cpp`: master extracted the child column
resolution into the free function `getChildColumnToRead`, which is identical to
the local `resolve_column_in_child` lambda of this PR, so the lambda is replaced
with calls to `getChildColumnToRead`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and pushed 7e664bf, resolving the conflict in StorageMerge.cpp: master moved the child column lookup into the free function getChildColumnToRead (from #103402), and it does the same thing as this PR's local resolve_column_in_child lambda, so I replaced the lambda with calls to getChildColumnToRead. Apart from that, the PR's diff against master covers the same files as before. The merged tree builds. Locally, the PR's Merge virtual-column tests pass, and so do the Merge subcolumn-access tests recently added to master (04511_merge_table_subcolumn_access_per_child, 05569_merge_subcolumn_grant_after_type_conversion). There are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (no conflicts) and pushed 2743c37. The PR's diff against master is unchanged, and StorageMerge.cpp compiles on the merged tree. No review threads are unresolved. The only failure on the previous head 7e664bf, 05047_selected_rows_executable_loop_double_count in Fast test (arm_darwin) (Pipe read timeout exceeded 10000 milliseconds in ShellCommandSource), is unrelated to this PR. It is a known macOS flakiness of executable tests that #130639 fixes.

Comment thread src/Storages/StorageMerge.cpp Resolved
alexey-milovidov and others added 3 commits November 18, 2026 03:47
# Conflicts:
#	src/Storages/StorageMerge.cpp
…`/`_database` columns

`master` now rejects `MergeTree` columns named like a virtual column unless
`allow_reserved_column_names` is enabled. These tests deliberately create children with
physical `_table`/`_database` columns to check that they do not shadow the `Merge` virtual
columns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…`Merge` declares its name

A read of nothing but the `Merge` virtual columns requests a substitute column of each child.
For a plain table query at `FetchColumns`, the substitute was appended to the child projection
only when the `Merge` did not declare a column of that name. With a declared column (e.g. under
another type, which forces `FetchColumns`), the virtual column references became constants and
a `Distributed` child sent a query without any physical read, so the initiator and the shard
chose different read headers and the query failed with `NOT_FOUND_COLUMN_IN_BLOCK`.

Project the chosen substitute regardless of whether the `Merge` declares its name. A column
cannot be appended to the projection of an aggregating query, so such a query is reduced to its
reads, as is already done for a `JOIN`: it is read at `FetchColumns` and aggregated by the `Merge`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageMerge.cpp Resolved
Comment thread src/Storages/StorageMerge.cpp Resolved
alexey-milovidov and others added 6 commits November 21, 2026 07:03
… columns of a `Merge` over `Distributed`

- The substitute read was not appended to the child projection when an output alias
  had its name (`SELECT _table AS p`), which left the shard query without a read and
  failed with `NOT_FOUND_COLUMN_IN_BLOCK`. Check whether the projection actually reads
  the child column instead of comparing output names.
- The child query kept the projection aliases given from outside (the column list of a
  CTE or of a subquery) after its projection changed size, which failed with
  `Number of aliases does not match number of projection columns`. Clear them in the
  child query; the outer plan keeps the original ones.
- At `FetchColumns` the `ALIAS` columns of a child are evaluated by the `Merge` over
  the columns of the child by name, but a `Distributed` child names them by column
  identifiers (`__table1.x`), so any such alias failed with `NOT_FOUND_COLUMN_IN_BLOCK`
  (also on master). Rename these columns to the names they were requested under first.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ntifiers of a `Distributed` child

A `Distributed` child of a `Merge` names its columns by the column identifiers of its
own planner, and `GlobalPlannerContext::createColumnIdentifier` renders the column name
with `backQuoteIfNeed`. The rename in `convertAndFilterSourceStream` compared the raw
tail of the identifier with the requested names, so a tuple subcolumn (`a.k`) or a name
that is not an identifier (`a b`) was not renamed, and the `ALIAS` expression of the
child failed with `NOT_FOUND_COLUMN_IN_BLOCK` at `FetchColumns` (with `ARRAY JOIN` or `JOIN`).

The requested names are now matched in the rendered form. The previous commit has the
code change; this one adds the reference for the new cases in
`05840_merge_child_alias_columns_over_distributed_array_join`.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-storage-merge Merge table engine (logical union over tables) and related mechanics. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

StorageMerge filter WHERE _table='X' returns no rows when underlying table has a physical _table String column shadowing the virtual

2 participants