Repository navigation
The _database and _table virtual columns of a Merge table carry the matched child's name again - #115356
The _database and _table virtual columns of a Merge table carry the matched child's name again#115356alexey-milovidov wants to merge 67 commits into
_database and _table virtual columns of a Merge table carry the matched child's name again#115356Conversation
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]>
|
Workflow [PR], commit [4a7af16] Summary: ✅
AI ReviewSummaryRestores matched-child names for the Missing context / blind spots
Final VerdictStatus: ✅ Approve |
…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]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes7 object files changed (+109.58 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units21 translation units recompiled, 169 s compile time in total, 21 of them have a recent master baseline. |
…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
…-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).
`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.
|
🕵 Status after bringing the branch up to date (
The two remaining
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_distReproduced locally with this branch: both master tests fail exactly and only on those value flips ( 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:
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. |
|
🕵 Brought the branch up to date again ( Re-verified locally against this build:
The state of the only real blocker is unchanged and is still a decision rather than a fix: So the two options from my previous comment still stand:
I have deliberately not touched those two tests, since flipping them is the decision itself. |
…-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]>
|
🕵 Brought the branch up to date again ( One adaptation was needed: the old query analysis is rejected since 26.9 ( Re-verified locally against this build: both The only blocker is unchanged and is still the decision, not a fix: |
|
Findings for
|
…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]>
|
🕵 Merged
|
…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]>
|
🕵 The |
|
🕵 Merged |
…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]>
|
🕵 Merged |
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]>
|
🕵 Merged |
|
🕵 Merged |
# 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]>
Fixes the `modernize-use-nodiscard` error of the clang-tidy build: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115356&sha=b901cb088a5e8790fe4ed5141d2013ae814b47b0&name_0=PR&name_1=Build%20%28arm_tidy%2C%201%2F4%29 #115356 Co-Authored-By: Claude Fable 5.2 <[email protected]>
… 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]>
Closes: #103631
Related: #113735
Related: #84139
Related: #63665
Related: #102471
Related: #107418
Related: #113242
Related: #116371
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a
WHERE _table = ...orWHERE _database = ...filter over aMergetable silently returning no rows when the matched child reads through another table, for example aDistributed, a nestedMerge, or aBufferchild. The_databaseand_tablevirtual columns of aMergetable 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::getSelectedTablesprunes the children of aMergetable by evaluating a filter on_database/_tableagainst each child's own name, but the values in the rows were stamped by whatever storage eventually read them - for aDistributedchild, 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.History. Before #63665 (25.7), the
Mergeengine substituted the child's own name for_table/_databaseitself (WITH '<child>' AS _tableper child), so the values and the pruning agreed. #63665 gave every table its own_tablevirtual 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
Mergeengine 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__actionNameover aStringconstant, wrapped intotoLowCardinalityto keep the type, which keeps the query sent to the shards readable by older servers), and atFetchColumnsthe 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 (aDistributedchild) is matched by position inconvertAndFilterSourceStream. 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 ownALIASexpressions 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 - thereSELECT _tableshowed the child's physical value whileWHERE _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: therewriteEntityInAstthat #63665 disabled injected the child's name as aWITHalias withsetPreferAliasToColumnName(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
Mergetable 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 throughBuffer/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_tablecolumn acts as an index" is actually true. The cost:_tablethroughMergeoverDistributedreadst_dist, nott_leaf; each nesting level ofMergereports its own child. Tests00717(whose leaf-name expectations were rewritten in #63665 itself),03094,04338,04367,03031,01902,03988,04104and01155are updated accordingly; the new test05055_merge_virtual_columns_delegating_childrencovers the pruning and the values overDistributed, nestedMergeandBufferchildren. The new test05055_merge_virtual_columns_shadowed_by_child_columncovers 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, anALIAScomputed from it, and aMergethat declares_tableitself as a real column (where the child's column correctly wins).A
Distributedchild whose remote table has a physical_databaseor_tablecolumn, queried so that the shard reads no other real column (e.g.SELECT _database FROM morSELECT count() FROM m WHERE _table = 'child'), is handled as well: aboveFetchColumnsthe injected constant is pinned to an action name of its own (__merge_virtual_column._table), so the shard's physical column cannot shadow it, andaddVirtualColumnsrenames it back.05055_merge_virtual_columns_delegating_childrenand05397_merge_virtual_columns_in_child_alias_over_distributedcover it for both columns.Interaction with #116371. A rework of #113735 has since landed on
masteras #116371: it keeps the underlying-table values and exempts children withreadsFromOtherTablesfrom the pruning. This PR replaces that semantics: since the rows now always carry the child's name, the exemption is removed fromReadFromMerge::getSelectedTables(every child is pruned by its own name again), and the tests05043_merge_prefilter_delegating_childrenand05045_merge_prefilter_lazy_load_tablesfrom #116371 are updated to the child-name values.readsFromOtherTablesitself stays, as the analyzer and parallel replicas use it.This also unblocks #113242, whose only functional CI failure was
00717_merge_and_distributednewly reaching the pruning defect atFetchColumns.Workflow [PR]
Sync PR [sync-upstream/pr/115356]