Skip to content

Apply a view column's declared type when it differs from the source only by time zone - #129642

Open
groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:fix-view-declared-type-time-zone-bool
Open

groeneai wants to merge 12 commits into
ClickHouse:masterfrom
groeneai:fix-view-declared-type-time-zone-bool

Conversation

@groeneai

@groeneai groeneai commented Nov 5, 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):

Fixed wrong results when a view (or a Merge table) declares a column type that differs from the source column only by the time zone, e.g. DateTime('UTC') over a plain DateTime: toTypeName reported the declared type, but values were formatted and computed (toHour, WHERE) in the source column's time zone. Closes #129459.

Description

On 26.8 and 26.10, CREATE VIEW v (x DateTime('UTC')) AS SELECT ts AS x FROM src over plain DateTime renders x and computes toHour(x) and WHERE toHour(x) = 0 in the session time zone (0 rows instead of 1), while toTypeName(x) says DateTime('UTC'). Same for DateTime64 and zones nested in Array/Map/Tuple.

Root cause: ActionsDAG::makeConvertingActions cast the view's result only when IDataType::equals failed, which ignores the time zone, so the column kept the source type while the analyzer used the declared one.

Change: needsConvertingCast also casts equal types whose names differ when the cast only relabels: a time zone or an AggregateFunction state version (it gets the target version). Not for Bool or SimpleAggregateFunction(f, Bool) over UInt8 (those casts change values) or for states of different aggregate functions or parameters (quantile, quantiles(0.9)). Same check where conversion is skipped: analyzer_inline_views, the trivial view pushdown to Distributed, the Merge columns allowed in PREWHERE (an explicit PREWHERE on one now throws ILLEGAL_PREWHERE) and the stage a Merge delegates to a child like Distributed (now FetchColumns, as for order-breaking conversions, also when the zone changes under Nullable/LowCardinality/Array or in a widening to DateTime64). CAST between Variant types differing only by a nested zone, which threw CANNOT_CONVERT_TYPE, reuses the column, unless two alternatives differ only by zone (allow_suspicious_variant_types).

Not changed: Bool or SimpleAggregateFunction(f, Bool) declared over UInt8 (view column, INSERT ... SELECT) keeps the raw value as on master (a Tuple holding such a member is not cast, zones included); converters with their own equals check (MATERIALIZED VIEW ... TO with a column list, Buffer, UNION ALL branches differing only by zone). A view keeps its CREATE-time types after an ALTER of its source.

Validation: the test fails on master and passes with the fix (50/50 randomized); ~1,600 related tests: no fix-specific failure.


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

groeneai and others added 5 commits November 5, 2026 15:16
… or `Bool`

`StorageView::readImpl` converts the inner query result to the view's
declared structure with `ActionsDAG::makeConvertingActions`, which added a
`_CAST` only when `IDataType::equals` failed. `equals` ignores the time zone
(`DateTime`, `DateTime64`) and custom names (`Bool` is `UInt8` with a custom
name), so for `CREATE VIEW v (x DateTime('UTC')) AS SELECT ts AS x FROM t`
over a plain `DateTime` the input column passed through with the source type.
The analyzer resolved the outer query against the declared type, so
`toTypeName(x)` said `DateTime('UTC')` while formatting, `toHour` and
`WHERE` used the session time zone, and a `Bool` over a `UInt8` holding 2
stayed 2 (`b = true` was false).

`makeConvertingActions` now also casts when the type names differ. For an
`equals`-equal pair `FunctionCast` is an identity relabel (time zones, also
nested in `Array`/`Map`/`Tuple`/`Nullable`/`LowCardinality`) or the usual
`UInt8 -> Bool` normalization. The same comparison is used in the three
places that decide by `equals` whether the conversion may be skipped or
bypassed: the `analyzer_inline_views` wrapper, the trivial view pushdown to
`Distributed`, and the ORDER BY/LIMIT pushdown into a view (the pushed sort
would run before the now normalizing `Bool` conversion).

Through the shared converter this also fixes a `Merge` table declaring such a
type, and `INSERT ... SELECT` of `UInt8` values into a `Bool` column, which
now stores 0/1 like `CAST`. `MATERIALIZED VIEW ... TO` with a column list,
`Buffer`, and `UNION ALL` branches differing only by zone skip the converter
through their own `equals` checks and are not changed here.

Closes ClickHouse#129459.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`FunctionCast::prepareUnpackDictionaries` sends every `Variant` pair to
`createVariantWrapper` before the identity shortcut of `prepareImpl`, and
`createVariantToVariantWrapper` matches alternatives by name. So
`Variant(DateTime, String)` -> `Variant(DateTime('UTC'), String)` threw
`CANNOT_CONVERT_TYPE` although the two types are `equals`-equal. With the
previous commit the view converter now casts such a pair, so a view read,
an inlined view or an `INSERT ... SELECT` between these columns would throw
where it worked before (the same for a `Variant` nested in
`SimpleAggregateFunction` or `Array`).

`DataTypeVariant::equals` compares the alternatives pairwise in the global
order and treats custom-name differences as unequal, so for an equal pair the
discriminators are identical and the column is reused as is.

The test gains a `Variant` block and two plan checks: the inlined view carries
the `_CAST`, and the trivial pushdown to `Distributed` is not used for a view
whose declared types differ only by name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`IDataType::equals` ignores the state version of `AggregateFunction` types,
so `Array(AggregateFunction(uniq, UInt64))` equals
`Array(AggregateFunction(1, uniq, UInt64))`, and the same for `Map`, `Tuple`
and `Variant`. For such a pair `FunctionCast` returned the column unchanged
(the identity branch of `prepareImpl` checks the version only for a top-level
`AggregateFunction`, and the `Variant` identity in `createVariantWrapper` not at
all), so the result column kept the source version under the target type. A
column serializes its states with its own version when they pass through an
arena, so reading such a view, `INSERT ... SELECT` or `CAST`, followed by a
`groupArray`/`arrayJoin` round trip, failed with `Code: 117 ... Extra bytes
found after deserializing aggregation state`.

`FunctionCast::prepareUnpackDictionaries`, the entry of every cast wrapper,
top-level and nested, now relabels the versions with
`relabelAggregateStateVersions` when the types are equal but their state
versions differ, as `castColumn` and `NativeReader` already do.

The test gains rows for such states in a `Variant` (view read and `CAST`) and
in an `Array` (view read), and the `Merge` arm reads a `MergeTree` table with
an outer `WHERE` on the declared type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ild only by name

`StorageMerge::supportedPrewhereColumns` kept a column in the set allowed in
`PREWHERE` when the `Merge` type `equals` the child's, which ignores the time
zone and custom names. An explicit `PREWHERE toHour(x) = 0` on a
`DateTime('UTC')` `Merge` column over a plain `DateTime` child was then
evaluated in the child read with the child type, before the conversion, and
returned no rows. The check now also compares the type names, so such a
column is treated like any other type difference and an explicit `PREWHERE`
on it throws `ILLEGAL_PREWHERE`. The test gains that row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`StorageMerge::getQueryProcessingStage` let a child such as `Distributed`
compute a later stage when `conversionPreservesOrder` held for every column,
which is true for an `equals`-equal pair that differs only by the time zone or
a custom name. The child then evaluated `toHour`, `WHERE` and `DISTINCT` in its
own type before the conversion to the `Merge` type. For an `equals`-equal pair
the stage check (and its re-check in `createChildrenPlans`) now also requires
equal type names, so such a `Merge` reads its children at `FetchColumns`. The
test gains three `Merge` over `Distributed` rows.

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

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (REVIEW r1-r6)
Finding Verdict
❌ Variant cast between types differing only by a nested zone threw CANNOT_CONVERT_TYPE AGREE, fixed: equal Variant types reuse the column
❌ Equal types differing only by an AggregateFunction state version kept the old version (Code 117 on an arena round trip), in Variant/Array/Tuple/Map AGREE, fixed: one guard in FunctionCast::prepareUnpackDictionaries reusing relabelAggregateStateVersions, as castColumn does
❌ Explicit PREWHERE on a Merge column differing only by zone filtered with the child type AGREE, fixed: StorageMerge::supportedPrewhereColumns compares type names too, so it throws ILLEGAL_PREWHERE as for other type differences
❌ A Merge table over a Distributed child let the child compute toHour/WHERE/DISTINCT with its own type before the conversion AGREE, fixed: a name-only type difference refuses the delegated stage, as an order-breaking conversion does
⚠️ Bool over UInt8 from a remote shard stays raw under that Merge DISAGREE: castColumn's own equals shortcut in the remote read, pre-existing, separate root; listed under "Not changed"
❌ Bool nested in Array/Tuple/Map keeps the raw byte DISAGREE: identical to an explicit CAST on master and 26.8, separate root in prepareImpl; disclosed in the description
💡 Merge WHERE over a MergeTree child test row added
💡 CAST from Variant(UInt8, ...) to Variant(Bool, ...) with aligned alternatives now reuses the column instead of throwing noted: the nested-Bool case above; listed in the description

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue's SQL with TZ=Asia/Kolkata on master: x renders 2026-01-01 05:30:00, toHour(x) = 5, WHERE toHour(x) = 0 returns 0 rows.
b Root cause explained? makeConvertingActions added a _CAST only when IDataType::equals failed; equals ignores the time zone and custom names (Bool), so the column kept the source type at runtime while the analyzer used the declared type.
c Fix matches root cause? Yes. The converter also casts when type names differ, and the places that skip or bypass the conversion by equals use the same comparison.
d Test intent preserved / new tests added? New 05508_view_declared_type_time_zone_and_bool: views, inlined views, Distributed pushdown, ORDER BY pushdown, INSERT ... SELECT into Bool, Merge (over MergeTree and Distributed, explicit PREWHERE), Variant, AggregateFunction state versions, EXPLAIN checks, controls. No existing test changed.
e Both directions demonstrated? Master fails every target row, the fix passes 50/50 randomized; reverting each of the eight changes alone fails exactly its own rows.
f Fix is general across code paths? Fixed at the shared converter; the Merge PREWHERE columns and the stage a Merge delegates use the same comparison. MATERIALIZED VIEW ... TO, Buffer, UNION ALL branches and castColumn in a remote read keep their own equals checks: measured still wrong, listed in the description.
g Fix generalizes across inputs (params/datatypes/wrappers)? DateTime, DateTime64, zones inside Array/Map/Tuple/LowCardinality(Nullable)/Variant, Bool and Nullable(Bool), constants, empty source, NULL. Nested Bool over values > 1 keeps the raw byte, as an explicit CAST does, and is not claimed.
h Backward compatible? (maintainer-approved exception only) No setting or format change; only equals-equal but differently named pairs behave differently. An explicit PREWHERE on such a Merge column now throws ILLEGAL_PREWHERE, and such a Merge reads its children at FetchColumns. Four A/B sweeps (view/datetime/bool, Variant/cast, merge/prewhere, merge/distributed): no difference caused by the fix.
i Invariants and contracts preserved? makeConvertingActions produces exactly the requested result types, so header and data agree; primary key analysis still prunes (1/1000 granules). Equal Variant casts reuse the column; AggregateFunction state versions are relabeled as in castColumn. A Merge child computes only with exactly the Merge type or an order-preserving conversion.

Session id: cron:clickhouse-impl-slot-5:20261105-214900

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @yariks5s @nihalzp, could you review this and add the can be tested label so CI runs? makeConvertingActions cast a view's result only when IDataType::equals failed, which ignores the time zone and Bool, so a declared DateTime('UTC') over DateTime was a label without a conversion; the fix also compares type names there and in the view and Merge paths that skip the conversion, plus the CAST changes this needs for equal Variant and AggregateFunction types.

@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [adc830c]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, parallel) FAIL
05632_kafka_insert_undelivered_messages FAIL cidb
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) FAIL
05632_kafka_insert_undelivered_messages FAIL cidb
Stateless tests (arm_binary, parallel) FAIL
05632_kafka_insert_undelivered_messages FAIL cidb
Stateless tests (amd_debug, ParallelReplicas, s3 storage, parallel) FAIL
05632_kafka_insert_undelivered_messages FAIL cidb
01513_optimize_aggregation_in_order_memory_long NOT_FAILED cidb
00542_access_to_temporary_table_in_readonly_mode NOT_FAILED cidb
01414_push_predicate_when_contains_with_clause NOT_FAILED cidb
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) FAIL
05632_kafka_insert_undelivered_messages FAIL cidb
05137_join_fixed_string_zero_bytes_runtime_filter NOT_FAILED cidb
05076_promql_fused_aggregation_pair NOT_FAILED cidb
05299_promql_offset_sample_timestamps NOT_FAILED cidb
05234_promql_streaming_aggregation_memory NOT_FAILED cidb
05241_prometheus_query_timestamp NOT_FAILED cidb
05059_promql_empty_by_group NOT_FAILED cidb
05320_promql_duplicate_series_one_to_one_matching NOT_FAILED cidb
05033_lazy_materialization_column_function_structure_equals NOT_FAILED cidb
05293_promql_constant_scalar_arithmetic NOT_FAILED cidb
17 more test cases not shown

AI Review

Summary

The PR applies declared time zones to view and Merge columns, adds guarded Variant relabelling, and preserves aggregate state versions during conversion. Two previously reported Major findings remain in the current code; no new inline findings were identified. Reviewed consumer boundaries include ordinary view conversion and inlining, view pushdown to Distributed, Merge stage selection and stream conversion, variantElement, aggregate state relabelling, and common-header conversion. Whole-column paths apply target metadata or preserve compatible discriminators; the two view boundaries below remain inconsistent.

Findings

⚠️ Majors

  1. Inlined projection metadata must match unconverted expressions. src/Analyzer/Resolve/QueryAnalyzer.cpp:6976: a time zone conversion on one column creates the wrapper, but another column excluded by needsConvertingCast still receives its declared type in projection_columns at line 6987. For a view declaring ts DateTime('UTC'), s AggregateFunction(quantile, UInt64) over an implicit-zone timestamp and quantilesState(0.9), inlined finalizeAggregation(s) consequently throws ILLEGAL_TYPE_OF_ARGUMENT; without the unrelated timestamp, it retains the source type and succeeds. Preserve the actual expression type for excluded columns, or decline inlining this mixed view. Existing thread.

  2. Renamed subcolumns must be resolved after parent conversion. src/Interpreters/ActionsDAG.cpp:2927: StorageView::readImpl forwards requested subcolumn names to the inner interpreter before reaching the new cast. A view declaring x Variant(DateTime('UTC'), String) over Variant(DateTime, String) therefore cannot directly read x.`DateTime('UTC')` with analyzer_inline_views = 0: the inner query cannot resolve that alternative. Reading the whole column takes the conversion path. Aggregate state version changes inside Variant have the same renamed-subcolumn boundary. Read and convert the parent first, then extract the requested subcolumn. Existing thread.

Tests
  • ⚠️ Add a mixed converted/excluded-column regression for view inlining, checking that adding the timestamp does not change aggregate finalization.
  • ⚠️ Add a direct read of the renamed Variant subcolumn with view inlining disabled, alongside whole-column extraction.
Missing context / blind spots
  • ⚠️ No local binary is available in this review job; the remaining cases were verified by tracing current code. The existing 05508_view_declared_type_time_zone test passes for adc830c0274df29d0a1ee1528a226ccd2bbe7001 in the Fast test report, but does not cover either boundary above.
Final Verdict

Status: ⚠️ Request changes

Keep projection metadata consistent with unconverted expressions, perform parent conversion before resolving renamed subcolumns, and add the two focused regressions. Both findings already have open inline threads; no duplicate comments were posted.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Nov 5, 2026
… implicit casts

`IDataType::equals` compares the normalized states and argument types of
`AggregateFunction` types, so `AggregateFunction(quantile, UInt64)` equals
`AggregateFunction(quantiles(0.9), UInt64)`, and a state of states equals one
whose nested state has another function or state version. The name comparison
added to `makeConvertingActions` and to the analyzer's view inlining then cast
such pairs, which relabels the states. A UNION of `quantileState` and
`quantilesState(0.9)` with different column aliases was then finalized as a
median instead of failing with ILLEGAL_TYPE_OF_ARGUMENT
(`04629_finalize_aggregation_mismatched_state`); the result depended on the
aliases, because equal-named branch headers skip the conversion. An inlined
view of a state of states finalized the nested states as the declared function,
or kept their old version under the new one and failed with INCORRECT_DATA
after a round trip through an arena.

The name comparison now casts only when the nested `AggregateFunction` types
differ at most in their own state versions, so time zones, custom names such as
`Bool` and state versions are still applied, and everything else keeps the
behaviour it has on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
Comment thread src/Planner/PlannerJoinTree.cpp Resolved
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing adc830c02 with master c9dc272bf (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

10 object files changed (+51.12 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/DataTypes/Utils.cpp.o 59.17 KiB 96.56 KiB +37.39 KiB (+63.19%)

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

Compile time of recompiled translation units

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

Job report

The name comparison added a `UInt8 -> Bool` cast to view reads, `Merge`
reads, `INSERT ... SELECT` and `UNION` conversions. Unlike a time zone or
`AggregateFunction` state version relabel, that cast changes values, and
the optimizers treat `CAST(x AS Bool)` as value-preserving: over
`MergeTree`, statistics/primary key pruning keeps `CAST(u AS Bool) = true`
from matching `u = 2`, and read-in-order treats the cast as strictly
monotonic, so `ORDER BY CAST(u AS Bool), k LIMIT 1` returns the wrong row.
Both reproduce with an explicit `CAST` on master, so a view column
declared `Bool` over `UInt8` would have inherited them. In a `UNION` only a
branch whose alias differs from the first branch reached the cast.

`needsConvertingCast` now decides the cast at all five sites, and keeps
the source column for equal types that differ in `Bool` or in an aggregate
function, as before this PR. The `pushOrderByIntoView` guard only existed
for `Bool` and is reverted. The test drops its `Bool` rows, asserts that a
`Bool` view adds no `_CAST`, and gains a view over `MergeTree` (primary key
literal, read in order, `toHour`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Apply a view column's declared type when it differs from the source only by time zone or Bool Apply a view column's declared type when it differs from the source only by time zone Nov 6, 2026
Comment thread src/Functions/FunctionsConversion.cpp Resolved
QueryTreeNodePtr projection_node;

if (!view_columns[i].type->equals(*subquery_columns[i].type))
if (needsConvertingCast(*subquery_columns[i].type, *view_columns[i].type))

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.

[P2] Preserve the actual types of columns excluded from conversion

Once a time zone difference makes needs_type_conversion true, this loop can leave another column uncast, but still advertises view_columns[i] in projection_columns. This breaks the stated decision to keep states of other aggregate functions unrelabelled:

SET session_timezone = 'Asia/Kolkata';
CREATE VIEW v (ts DateTime('UTC'), s AggregateFunction(quantile, UInt64))
AS SELECT toDateTime(1767225600) AS ts,
          quantilesState(0.9)(number) AS s FROM numbers(5);
SELECT finalizeAggregation(s) FROM v
SETTINGS analyzer_inline_views = 1;

On the head's fast-test binary this throws ILLEGAL_TYPE_OF_ARGUMENT: the wrapper declares s as quantile, while its uncast column still finalizes as quantiles. Without the unrelated ts column the same inlined state returns [3.6], as the added v_qaf test expects. Before this PR neither equal-type difference created a wrapper. Keep the projection metadata consistent with the actual expression type for excluded columns, or decline inlining the mixed view. Add a test containing both a converted and an excluded column.

Comment thread src/DataTypes/Utils.cpp Resolved
…on master

`IDataType::equals` treats `AggregateFunction(quantiles(0.9), UInt64)` and
`AggregateFunction(quantiles(0.1), UInt64)` (or `quantile`) as equal. Two
shortcuts this PR added for equal types therefore reused or relabelled states of
one function under another:
- the `Variant` identity: an explicit `CAST` to
  `Variant(AggregateFunction(quantiles(0.1), UInt64), String)` returned the 90th
  percentile, where master threw `CANNOT_CONVERT_TYPE`; it also kept a raw `UInt8`
  under a nested `Bool` alternative;
- the state-version relabel in `prepareUnpackDictionaries`: with a version
  difference too, `Variant`/`Array` states of `quantiles(0.9)` finalized as
  `quantile`, where master threw.
Both now require `isRelabellingCast`, the predicate `needsConvertingCast`
already uses, so those pairs behave as on master while time zones and state
versions are still relabelled.

The relabelling check compared aggregate functions by `getNameWithoutVersion`,
which includes the argument types, so `AggregateFunction(any, DateTime)` declared
as `AggregateFunction(any, DateTime('UTC'))` was not cast and an inlined view
(`analyzer_inline_views = 1`) finalized it in the session time zone. The function
is now compared by name and parameters and its arguments node by node; states
nested in the arguments also keep their versions, which the cast cannot relabel.

Found by the automated review on ClickHouse#129642.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 2 commits November 24, 2026 14:56
…ype-time-zone-bool

# Conflicts:
#	src/Functions/FunctionsConversion.cpp
…Bool)

Since ClickHouse#129731, a CAST into `SimpleAggregateFunction(f, Bool)` normalizes the
value like a CAST into `Bool`. `needsConvertingCast` kept only a node named
`Bool` out of the relabelling casts, so `UInt8 -> SimpleAggregateFunction(any, Bool)`
counted as a relabel and got a `_CAST`: an INSERT ... SELECT toUInt8(2) and a view
over a `UInt8` column now stored/returned 1 for that type while `Bool` kept 2.
That is what made `05556_cast_to_simple_aggregate_function_bool` fail after the
master merge (its correlated block relies on the raw value).

Keep the full name of such a node, so it is relabelled neither from `UInt8` nor
from `Bool`, exactly as on master.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageMerge.cpp Resolved

/// Add CAST function to convert into result type if needed.
if (!res_elem.type->equals(*dst_node->result_type))
if (needsConvertingCast(*dst_node->result_type, *res_elem.type))

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.

[Major] Apply the view conversion before resolving renamed subcolumns

The new conversion handles a whole Variant column, but the direct subcolumn read reaches the inner query before this cast:

CREATE VIEW v_sub (x Variant(DateTime('UTC'), String)) AS
SELECT toDateTime(1767225600)::Variant(DateTime, String) AS x;

SELECT x.`DateTime('UTC')` FROM v_sub
SETTINGS analyzer_inline_views = 0;

StorageView::readImpl passes the requested name x.DateTime('UTC') to InterpreterSelectQueryAnalyzer. Its normalizeAndValidateQuery projects that name from the original body, whose alternative is still named DateTime, so identifier resolution fails before makeConvertingActions is reached. Reading the whole x and extracting the alternative with variantElement instead goes through the new cast and succeeds.

Please read and convert the parent view column before extracting a subcolumn whose name changes during relabelling, and cover this direct read alongside the whole-column case. Aggregate-state version changes inside Variant have the same renamed-subcolumn boundary.

`childCanProcessBeforeConversion` checked for a time zone relabel only when
the child and declared types compare equal. A declared
`Nullable(DateTime('UTC'))`, `LowCardinality(DateTime('UTC'))`,
`Array(Nullable(DateTime('UTC')))` or `DateTime64(3, 'UTC')` over a child
`DateTime` is not equal, and `conversionPreservesOrder` accepts it by
unwrapping the wrappers or the `DateTime` to `DateTime64` widening. A
`Distributed` child then evaluated `toHour`, `WHERE` and `GROUP BY` keys in
its own zone before the conversion: `toHour(ts)` was 5 instead of 0 with
`session_timezone = 'Asia/Kolkata'`, and `WHERE toHour(ts) = 0` returned
no rows, for both values of `prefer_localhost_replica`.

The non-equal branch now also requires the explicit time zones of the
`DateTime`/`DateTime64` nodes to match in type-tree order. Pairs that keep
the zone (e.g. `DateTime` to `DateTime64(3)`, `DateTime('UTC')` to
`Nullable(DateTime64(3, 'UTC'))`) are still delegated.
`conversionPreservesOrder` is unchanged: `StorageDistributed` uses it too.

Reported by the clickhouse-gh review:
ClickHouse#129642 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Functions/FunctionsConversion.cpp Resolved
`DataTypeVariant::equals` pairs alternatives by position, and the position
is only the canonical name order. With two alternatives that are `equals`
to each other (e.g. `DateTime('Asia/Tokyo')` and `DateTime('Europe/London')`,
admitted by `allow_suspicious_variant_types`), several pairings satisfy
`equals`, so the relabelling shortcut in `createVariantWrapper` could keep a
discriminator that names another alternative in the target:

    CAST(CAST(toDateTime(1767225600, 'Europe/London')
              AS Variant(DateTime('Asia/Tokyo'), DateTime('Europe/London')))
         AS Variant(DateTime('Europe/London'), DateTime('Pacific/Honolulu')))

returned the London value as `DateTime('Pacific/Honolulu')`, while master
throws CANNOT_CONVERT_TYPE.

Such a Variant now keeps its full name in `getNamesKeptByRelabelling`, so
neither `isRelabellingCast` nor `needsConvertingCast` treats a change of it
as a relabel, and every path behaves as on master. The check reuses
`hasEqualsAmbiguousAlternatives`, moved from `transformTypesRecursively.cpp`
(`replaceNestedTypesInPair` refuses the same pairs for the same reason) to
`DataTypes/Utils`.

Found by the clickhouse-gh review of ClickHouse#129642 (r4686359321).

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - adc830c

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
Stateless tests (amd_debug, parallel) / 05632_kafka_insert_undelivered_messages master breakage, not from this PR: since 18:10Z the test's CREATE TABLE ... ENGINE = Kafka(<named collection>) fails with Code: 36 ... Kafka property topic.metadata.propagation.max.ms can only be specified in a named collection defined in the server configuration file on every master commit (master report). The fix merged at 23:51Z, after this run started, so it is absent from the tested tree; master is green on this test since #134255 (external, merged)
Stateless tests (arm_binary, parallel) / 05632_kafka_insert_undelivered_messages same master breakage #134255 (external, merged)
Stateless tests (amd_debug, ParallelReplicas, s3 storage, parallel) / 05632_kafka_insert_undelivered_messages same master breakage #134255 (external, merged)
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) / 05632_kafka_insert_undelivered_messages same master breakage #134255 (external, merged)
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) / 05632_kafka_insert_undelivered_messages same master breakage #134255 (external, merged)

Mergeable Check and PR are the praktika rollups of the rows above.

Session id: cron:our-pr-ci-monitor:20261125-003031

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-view Logical (non-materialized) views. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A view column declared DateTime('UTC') over a DateTime column is returned in the session's time zone, while toTypeName says UTC

1 participant