Repository navigation
Conversation
Internal second-model review (click to expand)Before publishing I reviewed this change with an independent second model in seven rounds, plus my
Session id: cron:clickhouse-review-slot-9:20260802-033500 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-9:20260802-033500 |
|
cc @alexey-milovidov @azat, could you review this? A |
|
Workflow [PR], commit [85d4b9b] Summary: ❌
AI ReviewSummaryThis PR fixes the main Findings❌ Blockers
Final VerdictStatus: Minimum required actions: fix the LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 104/122 (85.25%) · Uncovered code |
| /// 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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
d154ce7 to
9980703
Compare
…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.
CI finish ledger — bc73b91Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task All 175 check-runs completed: 157 success, 18 skipped, 0 red.
The Note this PR is now 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.
CI finish ledger - a0b7d22Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 175 check-runs completed, none with a failure conclusion; Session id: cron:our-pr-ci-monitor:20260804-033000 |
…r-subcolumn-type-mismatch # Conflicts: # src/Storages/StorageMerge.cpp
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 sizes2 object files changed (+23.29 KiB total), 0 added.
737 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 units15 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. |
CI finish ledger — b04895cEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task CI is fully finished on this head: workflow run 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 CIDB for this head: 30413 OK test rows, 1 FAIL row in total (the
The runner-provisioning mode is repo-wide rather than specific to this PR: Session id: cron:our-pr-ci-monitor:20260807-210000 |
|
Follow-up on the runner-infra rows in the CI finish ledger above. I traced the mechanism: those jobs failed on GitHub's 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 ( 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.
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.
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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
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.
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
CI finish ledger - 85d4b9bEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
No test-level failure exists at this head. CIDB has 0 rows for The red is not attributable to this diff: this PR touches Session id: cron:our-pr-ci-monitor:20260824-163000 |
Related: #110844
Changelog category (leave one):
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.size0through aMergetable 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, sosum(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
Mergetable resolves each requested column name against the child independently, so a subcolumnname 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
Mergetable's declared type. One row then carries a converted parentand a subcolumn value contradicting it:
There is no exception, and it reproduces at default settings. It is analyzer-specific: with
enable_analyzer = 0the subcolumn resolves against the child's own type and the query raisesUNKNOWN_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 structuralconversion. A child that genuinely lacks the column keeps its default, which is what makes a
Mergeoverdifferent column sets work; so does a parent outside the child's physical read list.
MATERIALIZEDandDEFAULTparents 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
.nullsibling subcolumn, repeated identically-structured children, a childALIAScolumn, achild 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.
BufferandViewcarry this defect through other mechanisms and ship separately. Reading asubcolumn of an
ALIASparent through aMergeis also wrong today; that predates this change,needs a different fix, and is tracked separately.
Workflow [PR]
Sync PR [sync-upstream/pr/112975]