Repository navigation
Conversation
… 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]>
Internal second-model review (REVIEW r1-r6)
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20261105-214900 |
|
cc @yariks5s @nihalzp, could you review this and add the |
|
Workflow [PR], commit [adc830c] Summary: ❌
AI ReviewSummaryThe PR applies declared time zones to view and Findings
Tests
Missing context / blind spots
Final VerdictStatus: 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. |
… 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]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes10 object files changed (+51.12 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units16 translation units recompiled, 127 s compile time in total, 16 of them have a recent master baseline. |
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]>
Bool| QueryTreeNodePtr projection_node; | ||
|
|
||
| if (!view_columns[i].type->equals(*subquery_columns[i].type)) | ||
| if (needsConvertingCast(*subquery_columns[i].type, *view_columns[i].type)) |
There was a problem hiding this comment.
[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.
…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]>
…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]>
|
|
||
| /// 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)) |
There was a problem hiding this comment.
[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]>
`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]>
CI finish ledger - adc830cEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261125-003031 |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results when a view (or a
Mergetable) declares a column type that differs from the source column only by the time zone, e.g.DateTime('UTC')over a plainDateTime:toTypeNamereported 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 srcover plainDateTimerendersxand computestoHour(x)andWHERE toHour(x) = 0in the session time zone (0 rows instead of 1), whiletoTypeName(x)saysDateTime('UTC'). Same forDateTime64and zones nested inArray/Map/Tuple.Root cause:
ActionsDAG::makeConvertingActionscast the view's result only whenIDataType::equalsfailed, which ignores the time zone, so the column kept the source type while the analyzer used the declared one.Change:
needsConvertingCastalso casts equal types whose names differ when the cast only relabels: a time zone or anAggregateFunctionstate version (it gets the target version). Not forBoolorSimpleAggregateFunction(f, Bool)overUInt8(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 toDistributed, theMergecolumns allowed inPREWHERE(an explicitPREWHEREon one now throwsILLEGAL_PREWHERE) and the stage aMergedelegates to a child likeDistributed(nowFetchColumns, as for order-breaking conversions, also when the zone changes underNullable/LowCardinality/Arrayor in a widening toDateTime64).CASTbetweenVarianttypes differing only by a nested zone, which threwCANNOT_CONVERT_TYPE, reuses the column, unless two alternatives differ only by zone (allow_suspicious_variant_types).Not changed:
BoolorSimpleAggregateFunction(f, Bool)declared overUInt8(view column,INSERT ... SELECT) keeps the raw value as on master (aTupleholding such a member is not cast, zones included); converters with their ownequalscheck (MATERIALIZED VIEW ... TOwith a column list,Buffer,UNION ALLbranches differing only by zone). A view keeps itsCREATE-time types after anALTERof 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]