Skip to content

Fix wrong subcolumn value over a Merge table with a mistyped child - #112975

Open
groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-wrapper-subcolumn-type-mismatch
Open

groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-wrapper-subcolumn-type-mismatch

Conversation

@groeneai

@groeneai groeneai commented Aug 2, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #110844

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):

Fixes a wrong result when reading a subcolumn such as arr.size0 through a Merge table whose child table declares that column with a type that does not expose the subcolumn. The subcolumn was filled with a default value while the parent column in the same row was converted correctly, so sum(arr.size0) silently undercounted. It is now derived from the converted parent column, so a parent value that cannot be converted raises an error instead of silently reading as a default.

Description

A Merge table resolves each requested column name against the child independently, so a subcolumn
name is just another name. If the child declares the parent column with a type that does not expose
that subcolumn, the name resolves nowhere in the child and takes the subcolumn's type default, while
the parent is converted to the Merge table's declared type. One row then carries a converted parent
and a subcolumn value contradicting it:

SELECT _table, arr, arr.size0, length(arr) FROM zm ORDER BY _table, arr;
zb   [4,5,6]   0   3     -- subcolumn must be 3
zg   [1,2]     2   2

There is no exception, and it reproduces at default settings. It is analyzer-specific: with
enable_analyzer = 0 the subcolumn resolves against the child's own type and the query raises
UNKNOWN_IDENTIFIER, which the test pins.

The fix derives the subcolumn from the parent the wrapper converts, as a resolved
getSubcolumn(CAST(<parent>, '<declared type>'), '<subcolumn>') evaluated before the structural
conversion. A child that genuinely lacks the column keeps its default, which is what makes a Merge over
different column sets work; so does a parent outside the child's physical read list.
MATERIALIZED and DEFAULT parents derive like ordinary ones. One deliberate change:
an unconvertible parent value now raises an error where the subcolumn read as a default. Reading
that parent alone already raised it.

Validated with a new stateless test covering both settings, every parent column kind, nested arrays,
the .null sibling subcolumn, repeated identically-structured children, a child ALIAS column, a
child engine without subcolumn support, and a row policy hiding an unconvertible parent. A 419-test
A/B sweep with only the fix reverted shows zero regressions.

Buffer and View carry this defect through other mechanisms and ship separately. Reading a
subcolumn of an ALIAS parent through a Merge is also wrong today; that predates this change,
needs a different fix, and is tracked separately.


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

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Before publishing I reviewed this change with an independent second model in seven rounds, plus my
own cold review each round. Verdicts below; the fixes are already in the commits.

# Finding Verdict
❌ The derived cast executed before the child's row-policy filter, so a value in a row the policy removes could make the cast throw. AGREE, fixed. The derivation is registered as a separate alias list materialized after addFilterTransform, while the child's own ALIAS columns deliberately stay before it (a row policy is analyzed against all of the child's columns and may reference them). A mutation moving the derived aliases back before the filter reddens exactly the row-policy cells and nothing else.
❌ Default query-plan optimization could merge the derived expression back into the filter, restoring the same exposure. AGREE, fixed. The regression test pins the ordering with query_plan_merge_expressions = 0, without which the hidden row's cast is never evaluated and the ordering is unobservable.
❌ An EPHEMERAL child parent was treated as readable, turning a correct default into an exception. AGREE, fixed. The parent lookup is narrowed to physical columns, so EPHEMERAL and ALIAS parents keep the type default while MATERIALIZED ones are still derived. All four parent kinds are covered as a test dimension.
⚠️ Several parent-kind cells did not assert that the derived subcolumn agrees with the converted parent, so they could pass without proving the contract. AGREE, fixed where a pair is possible. The MATERIALIZED arm carries the paired assertion; the unreadable-parent arms cannot (the parent term itself throws), so the constant-ALIAS arm carries the pair instead and its reference displays the contradiction explicitly.
⚠️ Comment blocks in the test, and later in the source, exceeded the repository ceiling and obscured the invariants. AGREE, fixed in both. The source diff is now 30 comment lines against 89 code lines with no block over three lines; the mechanism notes, refuted alternatives and cross-file citations moved to the commit messages. Proved comment-only with two independent strippers, each armed by mutating a real code token first so an empty diff is a live negative.
⚠️ The row-policy ordering guarantee is implemented only at FetchColumns; above it the derived cast stays in the child query tree. DISAGREE. The scenario needs a query that succeeds above FetchColumns under a child row policy. Reduced to SELECT count() over a Merge whose stage is raised by a remote child, with every child well-typed and no subcolumn anywhere, that query already fails NOT_FOUND_COLUMN_IN_BLOCK on the unmodified base binary, byte-identically: above FetchColumns the child executes the aggregated query itself, so its header carries aggregate states rather than the predicate column, and the filter is then built over a header lacking it. Two isolations pin this (drop the policy, or move the same policy to FetchColumns, and it succeeds). So the combination admits no successful query for an ordering to corrupt, and there is nothing for a stage guard to protect.
💡 The constant-ALIAS control records a wrong subcolumn value even though that expression is readable and convertible. DISAGREE, and deliberate. A constant ALIAS parent is still not in the child's physical read list, so it must take the type default like any other unreadable parent even though its expression would evaluate by accident. The reference displays the resulting contradiction rather than hiding it, which is what keeps the cell from being vacuous and documents where the guard draws the line.

Session id: cron:clickhouse-review-slot-9:20260802-033500

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local --queries-file <f>.sql on a pristine-master build returns sum(arr.size0) = 3 where 6 is correct, on every run, at default settings. Not probabilistic.
b Root cause explained? Yes. A Merge table resolves each requested name against the child independently, so a subcolumn of a mistyped parent resolves nowhere in the child, is erased from the child's read list, and is then filled with the subcolumn's type default, while the parent column is read and converted correctly in the same row. A second route exists above FetchColumns, where a ConstantNode(type->getDefault()) is substituted.
c Fix matches root cause? Yes. The subcolumn is derived from the parent the wrapper already converts, via a resolved getSubcolumn(CAST(<parent>, '<declared type>'), '<subcolumn>') evaluated before the structural conversion. Not a widened bound, not a tag, not a decline. A storage-predicate gate and a strict type-equality gate were each measured to delete a working optimization and were rejected.
d Test intent preserved / new tests added? New stateless test added. No existing test weakened; no reference file outside the new pair changed. Every new cell is proved live by a targeted mutation, and one cell that failed to redden was traced to a defective fixture (with the parent as the child's only physical column, the smallest-physical-column fallback picks the parent and the read succeeds by accident) and the fixture was corrected rather than the cell weakened. The unreadable-parent arms are proved the same way: a mutation reverting their guard reddens exactly those arms while the MATERIALIZED control stays green, and the rest of the test runs clean against the reduced reference on that mutation binary.
e Both directions demonstrated? Yes, with per-arm servers and each arm's served buildId() asserted equal to its readelf -n Build ID: pristine 7a551db1 gives 3 / 3 / 1 mismatching row, fix 9a1702ab gives 6 / 6 / 0. The row-policy and alias-bearing-child cells were measured the same way against the pre-fix binary, where they raise CANNOT_READ_ARRAY_FROM_TEXT and NOT_FOUND_COLUMN_IN_BLOCK respectively. The ephemeral- and alias-parent arms were measured across three arms (pristine master, the pre-guard build, the fix): master returns the type default, the pre-guard build raises NO_SUCH_COLUMN_IN_TABLE and NOT_FOUND_COLUMN_IN_BLOCK, and the fix restores the default while a MATERIALIZED parent keeps the derived answer.
f Fix is general across code paths? Both routes in StorageMerge go through one shared derivability predicate, so they cannot disagree. Sibling carriers enumerated from the capability predicate (git grep -l supportsOptimizationToSubcolumns src/Storages/): Buffer and View are real carriers through different mechanisms and ship separately (measured unchanged here); Distributed is already opted out; MaterializedView measured not a carrier; StorageProxy covered transitively.
g Fix generalizes across inputs (params/datatypes/wrappers)? Matrix covers Array(UInt8), nested Array(Array(UInt8)), Array(UInt64), Array(Nullable(UInt8)), Map(String, UInt8), the .null sibling subcolumn, empty arrays, a child missing the column entirely, subcolumn-only reads with the parent never mentioned, and both values of optimize_functions_to_subcolumns. Also a child carrying an unrelated ALIAS column (with the parent requested and not), that child through a nested Merge, a row policy hiding an unconvertible parent value, and a row policy whose predicate is a child ALIAS column. The parent's own column kind is covered as a dimension too: EPHEMERAL, ALIAS with a non-constant expression, ALIAS with a constant expression, and MATERIALIZED - the first three cannot be read in the child and keep the type default, while the stored one keeps the derivation.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default changes and no serialization change, so no SettingsChangesHistory.cpp entry is owed. A wrong answer becomes a right one. The only behaviour change is that a mistyped child now reads its parent column, which is strictly more IO for that child alone.
i Invariants and contracts preserved? The genuinely-absent-column default path is untouched and pinned by a test row; a mutation removing its guard reddens that row with Code 47, proving the guard is load-bearing. The original erase predicate is byte-identical. The derivation is registered only where the parent is still in the child's output, so the unconditional alias loop cannot evaluate it against an aggregated header. The positional-conversion contract holds because the cast happens inside the derivation, before conversion. The derived expression is materialized after the child's row policy filter, so a parent value in a row the policy removes can never be cast; the child's own ALIAS columns deliberately stay before the filter, because a row policy is analyzed against all of the child's columns and may reference them. A mutation moving the derived aliases back before the filter reddens exactly the row-policy cells and nothing else. The parent is additionally required to be readable in the child, not merely resolvable by name: an EPHEMERAL or ALIAS parent resolves yet has no data to read, so deriving from it turned a correct default into an exception until the parent lookup was narrowed to physical columns.

Session id: cron:clickhouse-review-slot-9:20260802-033500

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @azat, could you review this? A Merge table resolves each requested name against the child independently, so a subcolumn of a parent the child declares with a type that does not expose it resolves nowhere in the child and is filled with the subcolumn's type default, while the parent column in the same row is converted correctly, so sum(arr.size0) silently undercounts. It is now derived from the converted parent instead, before the structural conversion and after the child's row policy filter.

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

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [85d4b9b]

Summary: ❌

job_name test_name status info comment
Stress test (amd_asan_ubsan) ERROR

AI Review

Summary

This PR fixes the main Merge-table subcolumn/default mismatch and adds unusually thorough coverage across direct, nested, remote, and cache-reuse paths. I am still at request-changes because two user-visible contracts remain open in the current head: ALIAS-backed mistyped parents still return a contradictory subcolumn value, and the row-policy WHERE arr.size0 ... case is only made green by disabling default optimizer behavior.

Findings

❌ Blockers

  • [src/Storages/StorageMerge.cpp:207-213, tests/queries/0_stateless/04666_merge_subcolumn_of_convertible_parent.sql:156-178] [dismissed by author -- https://github.com/Fix wrong subcolumn value over a Merge table with a mistyped child #112975#discussion_r3699992411] tryGetDerivableSubcolumn still rejects every ALIAS parent by forcing GetColumnsOptions::AllPhysical, but the parent is readable through alias expansion and the PR body promises to fix the mistyped-child wrong-result case, not only stored parents. The new t_merge_sub_m_alp and t_merge_sub_m_alpc rows explicitly pin the contradiction: the same Merge row can return the converted parent via length(arr) while arr.size0 still falls back to the default (3 vs 6 in the constant-ALIAS control). That leaves the original correctness invariant broken for alias-backed children.
    Suggested fix: route derivable ALIAS parents through the same alias-expansion machinery used in getModifiedQueryInfo, then derive the requested subcolumn from that post-filter parent output instead of treating Alias as equivalent to EPHEMERAL.

  • [tests/queries/0_stateless/04666_merge_subcolumn_of_convertible_parent.sql:303-312] [dismissed by author -- https://github.com/Fix wrong subcolumn value over a Merge table with a mistyped child #112975#discussion_r3790327263] The row-policy safety argument is only true under non-default settings. The in-file comment already states that default allow_reorder_prewhere_conditions = 1 can move the policy conjunct behind the derived _CAST, and the author confirmed in-thread that the default query throws CANNOT_READ_ARRAY_FROM_TEXT where the correct answer is 1. As written, the implementation does not actually guarantee “a policy-hidden row cannot make the derived cast throw”; it only demonstrates that property after forcing a special plan shape in the test.
    Suggested fix: add a real no-reorder / barrier guarantee for predicates that depend on the derived parent cast, then assert the WHERE arr.size0 = 3 row-policy case at default settings instead of pinning allow_reorder_prewhere_conditions = 0.

Final Verdict

Status: ⚠️ Request changes

Minimum required actions: fix the ALIAS-parent path instead of pinning its current wrong result, and make the row-policy-filtered WHERE arr.size0 ... case correct under default settings rather than only under a forced optimizer configuration.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.20% -0.10%

Changed lines: Changed C/C++ lines covered: 104/122 (85.25%) · 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 2, 2026
Comment thread src/Storages/StorageMerge.cpp Resolved
/// parent resolves yet carries no data, so both keep the default. The requested subcolumn is
/// still looked up with the caller's kind above, so a child declaring `arr.size0` short-circuits.
auto child_parent_options = child_options;
child_parent_options.kind = GetColumnsOptions::AllPhysical;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using AllPhysical here deliberately drops every ALIAS parent from the derivation path, but the parent itself is still readable through the child alias-expansion machinery. The new t_merge_sub_m_alpc arm proves the result: length(arr) returns the converted alias value while arr.size0 still defaults in the same row (3 vs 6 in the aggregate). That leaves the original wrong-result invariant unfixed for Merge children declared as arr String ALIAS .... A fix needs to route derivable ALIAS parents through the alias-expansion path and derive the subcolumn from that output after the row-policy step, rather than rejecting them up front as non-physical.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right that an ALIAS parent is readable and that the invariant is violated for it, and I
have corrected the comment and the PR description, which both claimed an ALIAS parent "carries no
data". That is true of EPHEMERAL but not of ALIAS: the alias is expanded and read. What
AllPhysical actually tests is membership of the child's physical read list, which an ALIAS
column never joins.

Two corrections to the diagnosis, both measured.

The symptom is worse than defaulting. With a non-constant alias the subcolumn returns the value of
the alias expression's dependency column:

arr String ALIAS concat('[', toString(dep), ']'), dep=88   -> arr.size0 = 88, length(arr) = 1
arr String ALIAS concat('[1,2,', s, ']'),        s='123'   -> arr.size0 = 123, length(arr) = 3

Projecting the parent before the subcolumn names the mechanism outright:
TYPE_MISMATCH ... while converting source column dep to destination column arr. The 3 in the
t_merge_sub_m_alpc arm you cite is the mildest case, not the general one: a constant alias has no
input to surface.

The defect is also not limited to a mistyped child, so it is not created by this gate. With no type
mismatch at all:

arr Array(UInt8) ALIAS [1,2,3,4,5], through Merge  -> arr.size0 = 0, length(arr) = 5
the same table read directly                       -> arr.size0 = 5

All of the above is byte-identical on a pre-fix master snapshot containing 0 occurrences of
tryGetDerivableSubcolumn, so it predates this change and this change neither reaches nor worsens
it. That also rules out your proposed location: tryGetDerivableSubcolumn only runs when the child
cannot resolve the requested name and the parent type needs converting, so it cannot see the
well-typed case above. A fix has to sit where Merge builds the child read list for alias columns
and cover both halves, which is a different change from this one; I am tracking it separately rather
than folding a second wrong-results fix into this PR.

The t_merge_sub_m_alpc arm keeps its current value and its comment now says it pins pre-existing
behaviour rather than a correct result.

Separately, a review pass pointed out that an earlier argument of mine on this PR used Log as a
"does not support subcolumns" example. StorageLog.h:82 overrides that capability to true, so
that arm was vacuous. Re-measured with StripeLog, which genuinely inherits the false default:
a mistyped StripeLog child derives correctly here (2 2 per child, against 0 2 pre-fix), and
that arm is now in the test.

…ing it

A `Merge` table resolves each requested column name against the child independently, so
a subcolumn name is just another name. When the child declares the parent with a type
that does not expose the subcolumn, that name resolves nowhere in the child and takes the
subcolumn type's default, while the parent itself is converted to the declared type. The
row then carries a converted parent and a subcolumn contradicting it, with no exception
and at default settings: `sum(arr.size0)` silently undercounts.

Derive the subcolumn from the parent the wrapper already converts, as a resolved
`getSubcolumn(_CAST(<parent>, '<declared type>'), '<subcolumn>')`. The `_CAST` has to be
inside that expression rather than left to the downstream converting actions, which match
positionally. The derivation is registered as an alias off the names requested of the
`Merge` table and materialized after the child row policy, so a policy-hidden row cannot
be exposed and a child whose read list is rewritten by its own alias DAG still derives.

The parent must be in the child's physical read list: an `EPHEMERAL` parent has no data
and an `ALIAS` one is reachable only through alias expansion, so neither derives, while
`MATERIALIZED` and `DEFAULT` do. A child that genuinely lacks the column keeps its
default, which is what makes a `Merge` over different column sets work.

One deliberate behaviour change: an unconvertible parent value now raises an error where
the subcolumn previously read as a default. Reading that parent alone already raised it.

Tested across both `optimize_functions_to_subcolumns` settings, every parent column kind,
nested arrays, the `.null` sibling subcolumn, identically-structured children sharing the
per-structure cache, `Merge` over `Merge`, a child engine that does not support subcolumns,
and row policies including one hiding an unconvertible value. Every assertion carries the
parent term, so the oracle is per-child agreement rather than a total that could cancel.
Three row-policy arms pin `allow_reorder_prewhere_conditions = 0`: with statistics
materialized the policy conjunct can otherwise be reordered after the derived cast, which
throws for the parent form too and predates this change.

A 419-test A/B sweep with only the fix reverted shows zero regressions.
@groeneai
groeneai force-pushed the groeneai/fix-wrapper-subcolumn-type-mismatch branch from d154ce7 to 9980703 Compare August 2, 2026 20:38
Comment thread src/Storages/StorageMerge.cpp Resolved
…wrong value

The wrong-result contract this test guards is specific to the analyzer. With
enable_analyzer = 0 the request cannot be expressed at all: TreeRewriter resolves
a subcolumn against the child's own type (src/Interpreters/TreeRewriter.cpp:1229,
guarded by storage->supportsSubcolumns()), so a child that declares the parent
under a different type has no arr.size0 to resolve and the query raises
UNKNOWN_IDENTIFIER before StorageMerge builds any child plan.

Measured on this build and on a pre-fix master snapshot (build IDs
4052991fc967b2f37fb25b6d8f64c72c6bd8a566 and c5efc69a3aa8b16340de0b006d014bdb998d398a):
with the analyzer off both binaries raise the same error for Array size0, Tuple
element, Nullable null and Map keys parents, through Merge, Merge over Merge, a
StripeLog child, the merge() table function, a subquery alias and a WHERE-only
reference. The default-filling path the derivation hooks into is itself
analyzer-only there: an absent column raises UNKNOWN_IDENTIFIER rather than
filling a default. The implicit length -> size0 rewrite never reaches the child
with the analyzer off, so it stays correct on both binaries.

The three new arms pin that behaviour, and the header comment is corrected: it
described the rejection as happening for a reason the code does not give.
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — bc73b91

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. Only CH Inc sync is exempt.

All 175 check-runs completed: 157 success, 18 skipped, 0 red. Finish Workflow success.
The one CIDB failure row is below.

Check / test Reason Owner / fixing PR
Build (arm_release) / Post Hooks infra (build_profile_hook.py telemetry INSERT INTO build_time_trace rejected MEMORY_LIMIT_EXCEEDED on the shared ci-user budget; check_status is success, so the build itself is green) a fix task is created (investigating at full effort - fixing-PR link to follow on this PR)

The Post Hooks row is not caused by this PR: it is a build-telemetry upload failure that
fires on 203 unrelated PRs across 589 distinct commits in the last 7 days, is confined to the
two *_release build variants, and touches no test in this diff (2 files, test-only).

Note this PR is now CONFLICTING against master and needs a rebase/merge before it can go in.

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

…r-subcolumn-type-mismatch

Resolves one conflict in src/Storages/StorageMerge.cpp. Master (a47bb47, part of
ClickHouse#112128) moved `columnIsPhysical` and `columnDefaultKindHasSameType` out of this file's
anonymous namespace into src/Storages/ColumnDefault.{h,cpp}, and now includes that header
here. This branch had added `DerivableSubcolumn`, `tryGetDerivableSubcolumn` and
`makeDerivedSubcolumnExpression` to the same namespace, so the two sides collided on the
whole block.

Resolution keeps the master side of the relocation (the local copies are dropped, the single
remaining call site resolves against the ColumnDefault.h declaration) and keeps only this
branch's three genuinely new definitions in the namespace. Both master-side additions to
StorageMerge survive untouched: the transitive supportedPrewhereColumns intersection and
`supportedPrewhereColumnsIncludeSubcolumns`.

No functional change on either side.
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a0b7d22

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. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_release) / Post Hooks CI harness, not a test result: build_profile_hook.py fails uploading build telemetry (LogCluster query failed with code 500 on the INSERT INTO build_time_trace). Job-level check_status = success, so the build itself is green. Breadth over 7 d: 887 rows / 301 PRs / 502 master rows a fix task is moved to pending (investigating at full effort - fixing-PR link to follow here)

All 175 check-runs completed, none with a failure conclusion; Finish Workflow and Config Workflow
are green. This supersedes the ledger I posted for bc73b9185c7c, which is no longer the head.

Session id: cron:our-pr-ci-monitor:20260804-033000

…r-subcolumn-type-mismatch

# Conflicts:
#	src/Storages/StorageMerge.cpp
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 85d4b9be0 with master 3c3a54e67 (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 705.71 MiB 702.69 MiB -3.02 MiB (-0.43%)

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.

Object file sizes

2 object files changed (+23.29 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/StorageMerge.cpp.o 1.15 MiB 1.17 MiB +23.30 KiB (+1.98%)

737 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

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

Median compile-time ratio to the baselines is ×1.08 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +9.1 s (+8%) in total before that adjustment.

Job report

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — b04895c

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

CI is fully finished on this head: workflow run 31112794017 attempt 2 reports 175 of 175 jobs completed (16 success, 126 skipped, 18 failure, 15 cancelled). Note the run-level status still reads queued while the attempt itself is completed/failure, so the attempt endpoint is the one to read.

Not one red on this head is attributable to this PR, and no test failed. 14 of the 18 failures failed on GitHub's own Set up job step -- step 1, before Checkout code, so before any ClickHouse source existed on the runner. They span 6 distinct self-hosted runner pools (pr-arm-large 5, pr-amd-medium 3, pr-amd-large 3, pr-arm-small, pr-amd-small-mem, pr-amd-medium-cpu), and 12 other Build (*) flavours on this same head completed successfully, so the code compiles. The remaining 3 Run failures are the mechanical cascade of the 5 dropped builds, and the aggregator turned red with them.

CIDB for this head: 30413 OK test rows, 1 FAIL row in total (the Post Hooks bookkeeping line below), 0 failing test rows anywhere else.

Check / test Reason Owner / fixing PR
Build (amd_msan), Build (amd_binary), Build (arm_asan_ubsan), Build (arm_msan), Build (arm_binary) infra -- GitHub Set up job failed before checkout (runner provisioning); 4-5 min durations, 0 test rows a fix task is moved to pending (investigating at full effort -- fixing-PR link to follow on this PR)
Unit tests (tsan), Unit tests (msan, function_prop_fuzzer), Unit tests (tsan, function_prop_fuzzer), Quick functional tests, Stateless tests (amd_debug, parallel), Stateless tests (amd_tsan/amd_msan/amd_debug/amd_asan_ubsan, flaky check), Stateless tests (amd_asan_ubsan, distributed plan, parallel), Stateless tests (amd_asan_ubsan, db disk, distributed plan, sequential, 1/3 and 3/3), Stateless tests (arm_binary, parallel and sequential), Integration tests (amd_asan_ubsan, targeted), Integration tests (amd_asan_ubsan, db disk, old analyzer, 1/6-6/6), AST fuzzer (amd_debug, targeted and targeted+old_compatibility), Build (amd_release) infra -- same Set up job mode, or cancelled/errored as the direct cascade of the dropped builds (Clickhouse binary not found in any of the paths, zstd: can't stat ci/tmp/unit_tests_dbms.zst) a fix task is moved to pending (same owner as the row above)
Finish Workflow / Post Hooks (new_tests_check.py) infra cascade -- all four Bugfix validation per-arch jobs were DROPPED/SKIPPED because the builds they depend on never produced artifacts, so the hook reports passed: none a fix task is moved to pending (same owner as the rows above)
CH Inc sync -- CH Inc sync (private, not actionable)

The runner-provisioning mode is repo-wide rather than specific to this PR: Build (*) jobs reaching CIDB with check_status = 'error' cover 16 distinct PRs on 2026-08-07 and 8-12/day over the preceding days, and the Post Hooks bugfix-validation-dropped line above appears on 18 to 55 distinct PRs per day over the last week. Re-running the dropped jobs is what clears it; nothing in this PR's diff can influence runner setup.

Session id: cron:our-pr-ci-monitor:20260807-210000

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up on the runner-infra rows in the CI finish ledger above.

I traced the mechanism: those jobs failed on GitHub's Set up job step, so they carry exactly one step and never reached Run. retry_infra_failures.yml already treats that shape as an infrastructure failure ([.steps[] | select(.name == "Run")] | if length == 0 then true), and simulating that heuristic over all 175 jobs of the run gives no false verdict, so the run is eligible for an automatic rerun. The two cascaded arm_binary stateless jobs are covered by the same heuristic through its under-120s branch, at 73s and 97s.

What suppressed the rerun is the candidate selector, not the heuristic. This run is a fork PR whose attempt 1 was consumed by the approval gate (conclusion=action_required), so its first executing attempt is 2, while the selector filtered .attempt == 1.

That is exactly what #113564 fixes, so no separate fix is needed here and I am not opening one. When it merges, the class becomes visible to the hourly auto-retry.

…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.
Comment thread src/Storages/StorageMerge.cpp Resolved
The derived subcolumn expression is sent to the shard as text, so the child
row policy is applied by the shard against its own local table, where it
becomes a row-level filter on the MergeTree read. The policy therefore still
hides a parent value that cannot convert, and the derived cast never sees it.

That path was untested: every existing row-policy arm used a local child, whose
policy is upgraded to a storage filter on the initiator instead. The two
mechanisms differ, so the remote one is now asserted rather than assumed.

Measured on the merged tree against a pristine-master control: the new arms
return 5 and 1 with the fix and 2 and 0 without it, and the throw arm returns a
wrong value instead of throwing on master. Dropping the policy reddens all
three, so they are not vacuous. No tag is added: test_shard_localhost is a
single localhost replica and a shard tag would skip the whole file in the jobs
that pass --no-shard.
Comment thread src/Storages/StorageMerge.cpp Resolved
Merge caches getModifiedQueryInfo per child under a key of database plus the
child's declared column list. Column resolution inside that function runs with
withSubcolumns(storage->supportsSubcolumns()), so two children whose declared
columns are byte-identical but whose engines differ on that capability produce
different plans: one resolves the requested subcolumn natively, the other needs
it derived from the converted parent. Sharing one bucket therefore hands the
second child a plan built for the first one's capability, and which way it goes
depends on child iteration order.

Measured on Merge over MergeTree(k UInt8, arr Array(UInt8)) plus
EmbeddedRocksDB(k UInt8, arr Array(UInt8)), which is false for
supportsSubcolumns:

  high-capability child first: sum(arr.size0) returned 2, true value 5
  low-capability child first:  NOT_FOUND_COLUMN_IN_BLOCK for arr

Making the declared lists differ (an extra column on one child) splits the
bucket and both shapes are already correct, which isolates the key as the
mechanism rather than the derivation itself.

The capability bit joins the key rather than the engine being excluded from
caching: the cache stays effective for the common all-same-engine case, and the
fix does not need extending when another engine changes its answer.
The capability arms use EmbeddedRocksDB, which is unavailable in the fast-test
build and needs excluding from replicated-database configurations. All 29 other
in-tree stateless users of the engine carry use-rocksdb; no-fasttest is the
majority there as well.
The three t_merge_sub_rpr queries described themselves as covering a
Distributed child, but they left prefer_localhost_replica at its default 1.
For a local non-replicated shard SelectStreamFactory then takes
emplace_local_stream(), so the rows re-ran the local MergeTree policy path
already covered by the t_merge_sub_rpd arms above and never reached
ReadFromRemote. Measured on the fixture: the EXPLAIN contains zero
ReadFromRemote nodes at the default and one with the setting pinned to 0.

prefer_localhost_replica is also randomized by the test runner
(tests/clickhouse-test), so the previous coverage was not merely local but
nondeterministic between the two paths.

Pin the setting on all three queries and add a plan-shape arm asserting the
remote node is present, so a future regression to the local path reddens
instead of passing silently. The arm returns 0 without the pin and 1 with it,
and holds under serialize_query_plan = 1, automatic_parallel_replicas_mode = 2
and enabled parallel replicas.

Values on the remote path match the local-child arms exactly: the shard
re-plans the forwarded expression text and applies its own policy, so the
unconvertible row stays hidden. The serverError annotation is unchanged --
CANNOT_READ_ARRAY_FROM_TEXT is still raised, now from the shard.
-- throws the same way, so that ordering is not what this fix covers.
SELECT 'row policy plus a WHERE on the derived subcolumn';
SELECT count() FROM t_merge_sub_rp WHERE arr.size0 = 3
SETTINGS query_plan_merge_expressions = 0, allow_reorder_prewhere_conditions = 0;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is working around a real default-settings hole in the implementation rather than pinning an incidental plan detail. The comment above already notes that allow_reorder_prewhere_conditions can move the policy conjunct behind the derived _CAST, and both allow_reorder_prewhere_conditions and materialize_statistics_on_insert default to true.

That means SELECT count() ... WHERE arr.size0 = 3 can still throw on a row the child row policy should hide, which breaks the contract this change is trying to restore for row-policy-filtered reads. I think this needs a real no-reorder / barrier-style guarantee for predicates that depend on the derived parent cast, then this case should be asserted under default settings instead of forcing allow_reorder_prewhere_conditions = 0.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both defaults check out (Settings.cpp:988 and :2013), and you are right that removing the pin
throws. I measured it: with no SETTINGS clause at all, this arm gives Code: 130 CANNOT_READ_ARRAY_FROM_TEXT on the derived _CAST, where master silently returns 0. The correct
answer is 1. My first probe missed it because I dropped only allow_reorder_prewhere_conditions
and left query_plan_merge_expressions = 0 pinned, which is not defaults either.

Where I disagree is ownership: the hole is pre-existing and not specific to the derivation.

With optimize_functions_to_subcolumns = 0, so tryGetDerivableSubcolumn never runs, the parent
form WHERE length(arr) = 3 throws on both this branch and pristine master, and the same pin
rescues both. On pristine master (none of this PR present) three no-derivation predicates behave
identically:

predicate, pristine master defaults allow_reorder_prewhere_conditions = 0
length(arr) = 3 (optimize_functions_to_subcolumns = 0) throws 1
arr[1] = 4 throws 1
indexOf(arr, 5) > 0 throws 1
empty(arr) = 0 (control) 2 2

5/5 stable. Sweeping materialize_statistics_on_insert = 1,
allow_reorder_prewhere_conditions = 1, optimize_move_to_prewhere = 1,
query_plan_merge_filters = 1 and short_circuit_function_evaluation = 'enable', the derived and
parent forms agree in every arm, so nothing derivation-specific is hiding behind the pin. The
oracle is armed: dropping the row policy makes the pinned arm throw, restoring it returns 1.

So I am not adding the barrier. Scoped to "predicates that depend on the derived parent cast" it
would not fix the arr[1] or indexOf cases, which fail on master today; unscoped it is a
prewhere-ordering change for every Merge read over a converting child, which is a plan-quality
cost on a hot path and belongs with MergeTreeWhereOptimizer rather than a subcolumn fix.
Asserting this case under defaults would also pin master's existing throw as this PR's expected
outcome.

The pin stays, and it is an incidental-plan pin: it selects the ordering under which the
derivation's own behaviour is observable. I have made the in-file comment's reasoning explicit
here rather than expanding it in the test.

Worth stating plainly as a pre-existing issue, which I am not opening a follow-up for: at default
settings a Merge read whose child needs a type conversion can evaluate that conversion on rows a
child row policy hides.

The `distributed plan` CI flavour puts `serialize_query_plan = 1` in the default
profile. The initiator then ships an already-built read plan, and a row policy
that exists only on the shard is not applied to it, so the row the policy should
hide reaches the parent cast and the read throws CANNOT_READ_ARRAY_FROM_TEXT.

That is issue ClickHouse#112891 and is reproducible on pristine master with none of this
change present: a plain `SELECT count()` through a `Distributed` table returns 2
instead of 1 under `serialize_query_plan = 1`. It is unrelated to deriving a
subcolumn from a converted parent, which is what these arms exist to cover, so
they pin the transport that reaches the policy rather than asserting the bypass.

The two policy-independent arms above (plan shape, and the throw with no policy)
are unaffected by the setting and stay unpinned.
@groeneai groeneai added the groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work label Aug 19, 2026
The private CI's flaky check fails a test outright when a single run goes past 180
seconds, and only for tests that are not tagged `long` (see `tests/clickhouse-test`).
This file runs past it under ASan with S3 storage and metadata in Keeper, where every
statement pays an object-storage round trip, so the check reports it as a failure
instead of running the repetitions it exists for.
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: dbb98484-ab01-4af2-bcaa-eec067384848
  • MIRAI run: 34bbea9e-fa57-4148-af9a-9934ac7ecbf3
  • PR check IDs:
    • clickbench_161028_1787550370
    • clickbench_161042_1787550370
    • clickbench_161048_1787550370
    • tpch_adapted_1_official_161336_1787550387
    • tpch_adapted_1_official_161448_1787550398
    • tpch_adapted_1_official_161550_1787550408

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 85d4b9b

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_asan_ubsan) infra: the self-hosted runner lost communication with the server; the Run step ends cancelled about 65 min in, so the job reports failure having published no test results a fix task owns this and is being worked at full effort (fixing-PR link to follow on this PR)

No test-level failure exists at this head. CIDB has 0 rows for Stress test (amd_asan_ubsan)
against a 300,170-row control for the same commit, and the other 9 stress arms are all OK.
praktika records the node as ERROR with "Job failed to produce Result due to a script error or
CI runner issue" and 0 children, so nothing in the engine was exercised or reported.

The red is not attributable to this diff: this PR touches StorageMerge and one stateless test,
the job died during harness teardown rather than in a test, and the same
runner-communication-loss shape is currently hitting unrelated PRs across both architectures.

Session id: cron:our-pr-ci-monitor:20260824-163000

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

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

can be tested Allows running workflows for external contributors comp-storage-merge Merge table engine (logical union over tables) and related mechanics. groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants