Skip to content

Fix UNION/INTERSECT/EXCEPT branches keeping their own Decimal precision or time zone - #129666

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-set-operation-branch-equals-only-type
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-set-operation-branch-equals-only-type

Conversation

@groeneai

@groeneai groeneai commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator

Related: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118399&sha=4c7f1dc0fc711071ed57fe2fa869fef475d00838&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29
Related: #129642

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 UNION, INTERSECT and EXCEPT returning a branch's own Decimal precision or DateTime time zone instead of the common type. This gave wrong results of time-zone-dependent functions such as toHour, a wrong result column type, and a Cannot convert nested result of function exception when a Variant result was computed over such a union.

Description

On v26.10.2.103-stable, SELECT toHour(x) FROM (SELECT materialize(toDateTime(1767225600, 'UTC')) AS x UNION ALL SELECT materialize(toDateTime(1767225600, 'Asia/Tokyo'))) returns 0 and 9 for the same instant, and a + b over (Int64, Decimal(35, 7)) UNION ALL (Float64, UInt32) fails with Code: 49 ... Cannot convert nested result of function plus (a LOGICAL_ERROR that aborted the AST fuzzer server, report above). Same on 26.8 and 26.3.

IDataType::equals ignores a Decimal precision and a DateTime/DateTime64 time zone, and addConvertingToCommonHeaderActionsIfNeeded skipped a branch whose header was equals to the common one (makeConvertingActions adds no CAST between equals types either). Such a branch kept its own type while the analyzer and the union header announced the common one.

Now each branch column that is equals to the common type but not identical to it gets a target type built with replaceNestedTypesInPair: a Decimal leaf takes the common precision, a DateTime/DateTime64 leaf the common zone (including a zone a bare DateTime captured from session_timezone), also inside containers and in the typed paths of JSON, and an explicit CAST to it is added. A leaf that would need a value conversion rather than a relabel (Bool over UInt8, a differently named aggregate state) and a top-level Variant keep today's behaviour.

The same LOGICAL_ERROR through a Merge table is fixed by #129642.

Validation: new test 05556_set_operation_branch_type_equal_by_equals: every case fails or aborts on master and passes with the fix, 50/50 with randomized settings. 969 stateless tests matching union, intersect, except, variant, decimal, datetime or timezone give identical results with and without the fix.


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

groeneai and others added 2 commits November 6, 2026 01:18
…mon type

`addConvertingToCommonHeaderActionsIfNeeded` skipped a UNION / INTERSECT / EXCEPT branch whose header
passed `blocksHaveEqualStructure`, and `makeConvertingActions` adds no CAST between `equals` types.
`IDataType::equals` ignores a `Decimal` precision and a `DateTime` / `DateTime64` time zone (also one
captured from `session_timezone` by a bare `DateTime`), so such a branch kept its own type while the
analyzer and the union header announced the common one:

- `Decimal(35, 7)` + `UInt32` branches: analyzer `Decimal(38, 7)`, the first branch emits
  `Decimal(35, 7)`. The Variant adaptor rebuilds `plus(Int64, Decimal(35, 7))` from the runtime type,
  gets `Decimal(35, 7)`, which is not an alternative of the declared
  `Variant(Decimal(38, 7), Float64)`: LOGICAL_ERROR (STID 1927-5bc8, AST fuzzer), `Code: 49` on release
  builds.
- `DateTime('UTC')` + `DateTime('Asia/Tokyo')`: `toHour` returns 0 and 9 for the same instant.
- `Decimal(5, 2)` + `UInt8`: the client receives `Decimal(5, 2)` instead of `Decimal(9, 2)`.

Each branch column that is `equals` to the common type but not the same type object now gets a target
type from a paired walk (`replaceNestedTypesInPair`) over the branch and common types: a `Decimal` leaf
adopts the common precision, a `DateTime` / `DateTime64` leaf the common zone unless name and captured
zone already match, and any other difference refuses the walk, keeping the branch's type for the whole
column (custom names such as `Bool`, aggregate states, `Dynamic` parameters). A top-level `Variant` is
kept, since a CAST to a `Variant` matches alternatives by name. The converter receives the per-branch
target header, and an explicit CAST by type object is added for every adopted column, because
`makeConvertingActions` casts neither `equals` types nor a same-name zone difference.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The unsorted-`Variant` refusal in `getBranchTargetType` also refused `Geometry`, a custom-named
`Variant` with a fixed discriminator order, so `Tuple(Geometry, Decimal(35, 7))` UNION ALL
`Tuple(Geometry, UInt32)` kept `Decimal(35, 7)` while the analyzer announced `Decimal(38, 7)`.
The paired walk only ever produces the common type's names in the common type's order, so the
refusal had no case of its own: remove it.

Tests: a `Tuple(Geometry, Decimal)` case and a `DateTime64` time-zone case.

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

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, head 28fbc9c): 2 findings fixed, 1 noted
  • ❌ Tuple(Geometry, Decimal(...)) was refused whole by a sorted-Variant guard (Geometry keeps a fixed discriminator order), so its Decimal kept the branch precision. AGREE: guard removed (it could not fire for its purpose), test case added.
  • ⚠️ No DateTime64 time-zone case in the test. AGREE: added.
  • 💡 Bool over UInt8 stays as today: it needs a value conversion, not a relabel, and a CAST inside a container is an identity. Not in this PR.

Round 2 on the fixed head: no findings.

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. a + b over (Int64, Decimal(35, 7)) UNION ALL (Float64, UInt32) aborts a debug build every time with the CI message; toHour over a UTC + Asia/Tokyo union returns 0, 9. Eight cases, each in a fresh clickhouse local.
b Root cause explained? IDataType::equals ignores a Decimal precision and a time zone. addConvertingToCommonHeaderActionsIfNeeded skipped a branch equals to the common header and makeConvertingActions adds no CAST between equals types, so the branch kept its own type while the analyzer and the union header announced the common one.
c Fix matches root cause? Yes. The set-operation conversion now casts such a column to a target type built with replaceNestedTypesInPair (common precision, common zone). No change in the Variant adaptor or in tests' settings.
d Test intent preserved / new tests added? New test 05556_set_operation_branch_type_equal_by_equals (Variant result via UNION ALL and EXCEPT ALL, explicit and captured zones, DateTime64, result type, Tuple(Variant, Decimal), Tuple(Geometry, Decimal)).
e Both directions demonstrated? Every case fails or aborts on master and passes with the fix; the test aborts a master server and passes 50/50 randomized on the fix. Three mutations of the fix redden the expected cases.
f Fix is general across code paths? UNION ALL/DISTINCT, INTERSECT and EXCEPT share the function. The Merge/view path goes through makeConvertingActions, fixed by #129642 (measured on the Merge reproducer).
g Fix generalizes across inputs (params/datatypes/wrappers)? Nullable, LowCardinality(Nullable), Array, Map, Tuple, nested Variant, DateTime64, constants, NULL and empty branches measured. Bool, aggregate states and a top-level Variant keep today's behaviour by design.
h Backward compatible? (maintainer-approved exception only) No setting or format change. A set operation now returns the common type the analyzer already reported; 969 related stateless tests give identical results with and without the fix.
i Invariants and contracts preserved? Each target column stays equals to the common one, so UnionStep::checkHeaders holds; the CAST is an identity relabel, positions and names are unchanged, and a branch with nothing to adopt gets no extra step.

Session id: cron:clickhouse-impl-slot-4:20261106-015000

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @novikd @KochetovNicolai, could you review this and add the can be tested label so CI runs? IDataType::equals ignores a Decimal precision and a DateTime time zone, so addConvertingToCommonHeaderActionsIfNeeded skipped a set-operation branch differing only in those and the branch kept its own type under the common header (toHour 0 vs 9 over a UTC + Tokyo union, a logical error in the Variant adaptor); the fix casts such a column to the common precision and zone.

@clickhouse-gh

clickhouse-gh Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [de239cb]

Summary: ✅


AI Review

Summary

PR #129666 normalizes Decimal precision and DateTime/DateTime64 time zones to the common type before UNION, INTERSECT, and EXCEPT, including nested containers and typed JSON paths. Reviewed head de239cb69fab757682d4945d6ad7b4fd51ba94b9. The prior typed JSON finding is fixed and its thread has been resolved. The regression test and eight focused boundary probes pass with the current-head Fast test binary. No unresolved findings.

Final Verdict

Status: ✅ Approve

@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 6, 2026
Comment thread src/Planner/Utils.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing de239cb69 with master b51445ef4 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 831894676; 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.

Compile time of recompiled translation units

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

Job report

…anch

`replaceNestedTypesInPair` treats `JSON` as a leaf, but `DataTypeObject::equals`
compares the typed paths with `equals`, so a branch of type
`JSON(p Decimal(5, 2))` matched a common `JSON(p Decimal(9, 2))` and kept its own
type: the result header said `Decimal(5, 2)`, `JSONAllPathsWithTypes` reported
`Decimal(5, 2)` for that branch's rows, and `toString` of a
`JSON(t DateTime('Asia/Tokyo'))` branch rendered the instant in Tokyo time under
a `JSON(t DateTime('UTC'))` column.

The leaf callback now walks the typed paths of an `equals` JSON pair with the
same rules (paths line up by position because an `equals` pair has the same
paths) and rebuilds the branch type through `cloneWithChildren`, which keeps the
other JSON parameters. The `KeyCondition` caller of `replaceNestedTypesInPair`
is unchanged.

Found by the AI review on ClickHouse#129666.

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

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-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant