Skip to content

Read a subcolumn of an ALIAS parent through a Merge table instead of a default - #114673

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-merge-subcolumn-of-alias-parent
Aug 15, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-merge-subcolumn-of-alias-parent

Conversation

@groeneai

@groeneai groeneai commented Aug 13, 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):

Fix reading a subcolumn (.size0, .null, a tuple element, String.size) through a Merge table when the underlying table declares the parent column as ALIAS. Such a read returned the type default, and when the parent was selected in the same query it could return the value of an unrelated column.

Description

Selecting arr.size0 from a Merge table returns 0 when the child declares arr as an ALIAS column, while the same query against the child returns the correct 5:

CREATE TABLE ag (n UInt64, arr Array(UInt8) ALIAS [1,2,3,4,5]) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO ag (n) VALUES (77);
CREATE TABLE mg (arr Array(UInt8), n UInt64) ENGINE = Merge(currentDatabase(), '^ag$');
SELECT arr.size0 FROM mg;  -- 0, should be 5

Root cause: ColumnsDescription::add registers no subcolumns for an ALIAS column, because the value has to be extracted after the expression is evaluated. So arr.size0 does not resolve against the child, but does against the Merge table, where arr is ordinary. ReadFromMerge::getModifiedQueryInfo reads that as "the child does not have this column": it substitutes a constant default, and its with_aliases loop skips the column, so the child is never asked for the data. With the parent also selected, alias expansion put the alias's dependency column in the child read list, and the misaligned read surfaced that value under the subcolumn's name.

The analyzer already implements the extract-after-evaluation contract, turning such a name into getSubcolumn over the alias expression. This teaches both guards to recognise the case and route it to the existing alias branch with the full identifier, adding no new carrier.

Also wrong for Tuple.a, String.size and Nullable.null (a NULL read back as non-NULL), under optimize_functions_to_subcolumns 0 and 1, and it mis-scoped a row policy. Map subcolumns raise NO_SUCH_COLUMN_IN_TABLE before and after. The old analyzer raises UNKNOWN_IDENTIFIER and is unchanged, hence the no-old-analyzer tag. MATERIALIZED and DEFAULT parents were already correct, and the default substitution for a child genuinely lacking a column is preserved; both have test arms.

A mistyped child (String ALIAS under an Array(UInt8) Merge column) stays as it is, because String has no size0. That conversion case is #112975.

Version info

  • Merged into: 26.8.1.1454 (included in 26.8 and later)

…a default

Selecting arr.size0 from a Merge table returned the type default (0) when the
underlying table declared arr as an ALIAS column, while the same read from that
table returned the correct value. With the parent selected in the same query it
could return the value of an unrelated column instead.

ColumnsDescription::add intentionally registers no subcolumns for an ALIAS
column, because the value has to be extracted after the alias expression is
evaluated. As a result arr.size0 does not resolve against the child but does
resolve against the Merge table, where arr is an ordinary column.
ReadFromMerge::getModifiedQueryInfo read that asymmetry as "the child does not
have this column" and took its differing-schemas path twice over: it substituted
a constant default, and its with_aliases loop skipped the column, so the child
was never asked for the data. When the parent was also selected, the alias
expansion placed the alias's dependency column in the child read list and the
misaligned read surfaced that value under the subcolumn's name.

The analyzer already implements the extract-after-evaluation contract, turning
such a name into getSubcolumn over the alias expression. Both guards now
recognise a name that splits to a child ALIAS parent whose type has that
subcolumn and route it to the existing alias branch with the full identifier, so
no new carrier is introduced. That branch's resolution check has to accept two
shapes now: an ALIAS column resolves to a ColumnNode carrying its expression,
whereas a subcolumn of one resolves to a FunctionNode owning no expression.

Array.size0, Tuple.a, String.size and Nullable.null were each affected, under
optimize_functions_to_subcolumns 0 and 1, and a row policy on the child was
mis-scoped. Map subcolumns raise NO_SUCH_COLUMN_IN_TABLE before and after. The
old analyzer raises UNKNOWN_IDENTIFIER and is unchanged, hence the test's
no-old-analyzer tag. MATERIALIZED and DEFAULT parents keep registered subcolumns
and were already correct, and the default substitution for a child that
genuinely lacks a column is preserved; both have test arms.

A mistyped child, such as a String ALIAS under an Array(UInt8) Merge column, is
left as it is: String has no size0, so nothing is derivable from the child's own
type. That conversion case is a separate concern.
Every alias expression in 04738 was a constant, so no arm reached the case
where the alias reads a physical column of the child. That is the case where a
Merge read surfaced the alias's dependency value under the subcolumn's name,
which is what the changelog entry describes, and it is also the only shape that
puts the alias's dependencies into the read list the fix corrects: a constant
contributes no ActionsDAG input.

The new arms use ALIAS range(dep + 2) rather than range(dep) so that the size0
truth (9), dep (7) and first (11) are three distinct values. With range(dep) the
truth equals dep, so a read landing on dep returns the correct number and the
arm passes on a binary that still has the defect.

Verified against a pre-fix binary: the three new arms fail there, and the
with-parent arm returns 7, the value of dep, where 9 is correct.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

An independent cold review plus two second-model gate rounds ran against this change before it
was published. Verdicts and evidence below.

# Finding Verdict
❌ The regression test's ALIAS expressions were all constants, so the cross-column case named in the changelog entry had no arm, and the alias's own dependencies never entered the planner's required-column DAG AGREE, fixed. A dependency-carrying arm was added: ALIAS range(dep + 2) over dep = 7, first = 11. Before the fix that arm returns 7, the value of dep, against a truth of 9. The plain range(dep) form was measured and rejected as vacuous, because there the size0 truth equals dep, so a read landing on dep looks correct
⚠️ Modifying an ALIAS column's metadata re-registers subcolumns it does not have, so the promised read fails until reload DISAGREE on scope, and the mechanism is real: ColumnsDescription::modify removes and then unconditionally re-adds subcolumns, without the Alias guard that add has. It is not reachable from this change and not altered by it: both new guards are consulted only where the child lookup already failed, so a name that resolves short-circuits past them, and on both revisions such a name takes the same pre-existing branch. It also breaks the direct read of the underlying table, not only the Merge read, and it is a loud NO_SUCH_COLUMN_IN_TABLE rather than a wrong value. git blame dates the two sides of the asymmetry to 2022 and to January. A test arm here would be red before and after, which is not admissible evidence
⚠️ Map/JSON/Dynamic subcolumns of an ALIAS parent still fail through Merge DISAGREE, out of contract. Dynamic lookup returns a non-empty pair for such a name, so it continues before the new predicate is consulted and takes the pre-existing branch: identical before and after, and a NO_SUCH_COLUMN_IN_TABLE error rather than a wrong value. The expected-error arm records it and the description states it
⚠️ The later-stage default-substitution guard is not pinned, because every child in the test is a plain MergeTree DISAGREE. That loop carries no processing-stage condition, and both loops insert into one std::unordered_map, whose emplace does not overwrite an existing key. With the guard removed, the constant default inserted by the first loop wins and the existing arms return 0 instead of the true value. Measured: the test reddens on a pre-fix binary, 12 of 17 output lines

Both remaining objections share one core: a name the child can already resolve keeps its existing
behaviour. That is deliberate. The new branch admits only names that resolve neither as a column
nor as a registered subcolumn of the child, because those are the names this code path used to
answer with a silent default.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, no randomization or timing needed. CREATE TABLE ag (n UInt64, arr Array(UInt8) ALIAS [1,2,3,4,5]) ENGINE = MergeTree ORDER BY tuple(); INSERT INTO ag (n) VALUES (77); CREATE TABLE mg (arr Array(UInt8), n UInt64) ENGINE = Merge(currentDatabase(), '^ag$'); SELECT arr.size0 FROM mg; returns 0; the same read from ag returns 5. Fires on every run.
b Root cause explained? ColumnsDescription::add registers no subcolumns for an ALIAS column, so arr.size0 fails tryGetColumn(withSubcolumns(), ...) on the child while succeeding on the Merge table, where arr is ordinary. ReadFromMerge::getModifiedQueryInfo treats that as "the child lacks this column" and takes its differing-schemas path: it emplaces a ConstantNode(type->getDefault()), and its with_aliases loop continues on the same failed lookup, so the name never reaches filter_actions_dag and column_names_as_aliases omits what the value needs. EXPLAIN actions=1 shows Output: materialize(materialize(0)) with the child contributing Output: Empty.
c Fix matches root cause? Yes. Both guards learn to recognise a name that splits to a child ALIAS parent whose type has that subcolumn, and route it to the existing alias branch with the full identifier. No widened bound, no tag, no defensive check, and no new extraction carrier: the analyzer already emits the getSubcolumn wrapper this reuses.
d Test intent preserved / new tests added? New test 04738_merge_subcolumn_of_alias_parent. Its oracle is per-arm agreement between the Merge read and the direct child read, never a hardcoded literal, and every arm's truth differs from the type default so a default-returning read cannot pass. No existing test was modified or weakened.
e Both directions demonstrated? Yes. Against the pre-fix master binary (build id 594b0c0e..., asserted at runtime) the test FAILS with 12 of 17 lines reddened, all of them the wrong-value arms. Against the fixed binary (3db99f69...) it PASSES, and 50/50 randomized runs pass. The 5 control lines stay green on both, so they are genuine controls. One arm pins the cross-column case specifically: with the parent also selected, arr.size0 returned 7, the value of the alias's dependency column dep, against a truth of 9.
f Fix is general across code paths? Both affected guards are fixed, not just the one the repro hits: the default-substitution loop and the with_aliases loop, including its exact-name getDefault test that decides is_alias. The old-analyzer twin was checked and deliberately left alone: it raises UNKNOWN_IDENTIFIER, which is loud rather than wrong, and a test arm asserts it still does. merge() was verified already correct.
g Fix generalizes across inputs? Array.size0, Tuple.a, String.size and Nullable.null were each measured wrong and are each fixed and tested; a nested tup.a.b multi-dot name too. Both alias shapes are covered: a constant expression, and one that reads a physical column (ALIAS range(dep + 2)), which is the shape that produced the cross-column value. Covered under optimize_functions_to_subcolumns 0 and 1, with a row policy on the child, and via the merge() function. Map subcolumns raise NO_SUCH_COLUMN_IN_TABLE before and after, asserted so they can never become silently wrong. MATERIALIZED and DEFAULT parents keep registered subcolumns, were already correct, and have control arms.
h Backward compatible? Yes. No new setting, no default change, no serialization or on-disk format change, so no SettingsChangesHistory.cpp entry is needed. It only replaces a wrong value with the correct one; no query that works today starts failing, which the old-analyzer and Map arms exist to detect.
i Invariants and contracts preserved? The invariant added: a requested subcolumn of a child ALIAS parent is produced from the evaluated alias expression, never from a default and never from a positional read. The new branch fires only when the name fails child resolution AND splits to an ALIAS parent whose type has that subcolumn, so the default substitution for a child that genuinely lacks a column is untouched, with its own regression arm. The alias branch's resolution assertion is kept for both shapes: an ALIAS column must still resolve to a ColumnNode carrying an expression, and a subcolumn of one to a FunctionNode, so neither silently degrades to a null node.

Session id: cron:clickhouse-impl-self-slot-57:20260813-170500

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cad3508]

Summary: ✅


AI Review

Summary

This PR fixes the analyzer path in StorageMerge so a subcolumn of a child ALIAS column is routed through alias-expression evaluation instead of being treated as a missing child column and replaced with a type default. I traced the changed logic through default substitution, alias expansion, row-policy handling, cached child planning, and the new stateless coverage, and I did not find a remaining correctness issue in the current diff.

Final Verdict

✅ No findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 40/40 (100.00%) · 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 13, 2026
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @KochetovNicolai, could you review this? Reading a subcolumn like arr.size0 through a Merge table returned the type default when the child declares arr as ALIAS, because ColumnsDescription::add registers no subcolumns for an alias while the Merge table has them, so getModifiedQueryInfo took its differing-schemas path and never asked the child; with the parent also selected it surfaced the alias's dependency column value instead.

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing cad350876 with master fb565a7db (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
Binary Master PR Δ
programs/clickhouse-stripped 691.76 MiB 688.75 MiB -3.01 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - cad3508

CI is fully finished on this commit with no failing checks, so there is nothing to own.

Check / test Reason Owner / fixing PR
(none failing) - -
Sync - CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260813-233000

@alexey-milovidov alexey-milovidov self-assigned this Aug 15, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 15, 2026
Merged via the queue into ClickHouse:master with commit b047697 Aug 15, 2026
355 of 357 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 15, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 15, 2026
…r-subcolumn-type-mismatch

Three conflicts in src/Storages/StorageMerge.cpp, all with the merged sibling
fix ClickHouse#114673 (subcolumn of an ALIAS parent), which landed on master. Both sides
kept in every case:

- The anonymous namespace gained isSubcolumnOfAliasColumn upstream and
  DerivableSubcolumn/tryGetDerivableSubcolumn/makeDerivedSubcolumnExpression
  here; the two are independent helpers.
- storage_columns is now hoisted above the replacement loop upstream; the
  comment continuation here is unrelated to that move.
- Both guards sit in the same replacement loop and are disjoint by the parent's
  default kind: isSubcolumnOfAliasColumn requires ColumnDefaultKind::Alias,
  while tryGetDerivableSubcolumn looks the parent up with
  GetColumnsOptions::AllPhysical (Ordinary | Materialized), which excludes
  aliases. Neither can shadow the other, so upstream's guard runs first and
  ours handles what falls through.

Verified content-preserving: the added/removed line multisets of
master..HEAD are identical to those of the pre-merge base..old-head
(+133/-11 in StorageMerge.cpp, 0 lines lost, 0 invented), and the delta
against master is the same 4 files, +770/-12, with no submodule movement.
@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
CREATE TABLE t (n UInt64, arr Array(UInt8) ALIAS [1,2,3,4,5]) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t (n) VALUES (77);
CREATE TABLE m (arr Array(UInt8), n UInt64) ENGINE = Merge(currentDatabase(), '^t$');

SELECT arr.size0 FROM m;  -- returns 0; SELECT arr.size0 FROM t returns 5

Results:

  • Reproduces on: 26.7, 26.6, 26.5, 26.3
  • Does not reproduce on: 25.8
  • Tested versions: master, 26.7, 26.6, 26.5, 26.3, 25.8
  • Also tested (unsupported, context only): 26.2 reproduces
  • Fix merged on master (not re-verified: tested master build predates this PR's merge — a clean verdict is not attributable to the fix). The releases listed above still have the bug and need the backport.

Backport the fix to 26.7, 26.6, 26.5, 26.3.

CC component owner: @alexey-milovidov @CurtizJ

Analysis metadata

comp-storage-merge · Severity P2 · Finding phase_d_pr114673

  • Could not test: master
Introducing change: not identified
  • Secondary components: comp-testing

@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed independently, and the request is correct: 26.7, 26.6, 26.5 and 26.3 still carry this.

I measured each release build rather than relying on the report above, printing the Merge read next to the direct read (the truth), with a fixed master build as a control so a 0 cannot come from a blind probe:

build through Merge direct (truth)
26.7.4.48 0 5
26.6.3.44 0 5
26.5.7.57 0 5
26.3.18.32 0 5
25.8.30.20 5 5
master with the fix (control) 5 5

25.8 is clean because the defect postdates that branch, not because the fix is there, so it is out of scope.

I do not hand-author release-branch PRs. The label that expands to exactly those four branches is v26.3-must-backport (computed with select_backport_branches from tests/ci/cherry_pick_branches.py against the active release set; pr-must-backport would also target 25.8). @alexey-milovidov, you merged this one, so could you apply it?

git merge-tree conflicts on all four in src/Storages/StorageMerge.cpp, so two notes for the cherry-picks:

  • 26.7 and 26.6 are trivial. The only conflict is the include anchor: the fix adds #include <DataTypes/NestedUtils.h> above #include <Databases/IDatabase.h>, which those branches do not have. The changed region itself is byte-identical to the merge base.
  • 26.3 needs a hand resolution. Taking the master side of every conflict silently drops the branch-only line get_column_options.withVirtuals(), which master no longer has because it sets virtuals inline in the initializer.

After resolution each branch carries the full fix (all 3 isSubcolumnOfAliasColumn occurrences and all 4 is_subcolumn_of_alias uses, matching master), and both helper APIs it calls already exist on every target.

@groeneai groeneai added the groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR 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-review-bot PR origin: review-bot finding on a groeneai PR pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants