Skip to content

Convert a DateTime64 field back to DateTime - #117977

Closed
navneet83 wants to merge 8 commits into
ClickHouse:masterfrom
navneet83:fix-datetime64-to-datetime-field-conversion
Closed

navneet83 wants to merge 8 commits into
ClickHouse:masterfrom
navneet83:fix-datetime64-to-datetime-field-conversion

Conversation

@navneet83

@navneet83 navneet83 commented Sep 3, 2026 •

Copy link
Copy Markdown
Member

Closes: #117903

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 TYPE_MISMATCH being counted in system.errors on every execution of a SELECT comparing a DateTime64 column against a DateTime constant inside an AND.

Documentation entry for user-facing changes

convertFieldToTypeImpl widens a DateTime constant to a DateTime64 column type (convertFieldToType.cpp:501) but had no branch for the other direction. The DateTime case accepts only UInt64 (:399), and WhichDataType(DateTime).isUInt32() is false so the numeric dispatch does not pick it up either, so a DecimalField<DateTime64> aimed at DataTypeDateTime fell through every branch to the TYPE_MISMATCH at :958.

LogicalExpressionOptimizerPass::tryConvertToColumnType round-trips a constant through the column's type to check that widening it lost nothing:

auto round_trip = tryConvertFieldToType(converted, *from_type, expr_type.get(), {}, /*strict=*/true);
if (round_trip.isNull() || !accurateEquals(round_trip, original_value))
    return std::nullopt;

For a DateTime64 column compared against a DateTime constant the reverse leg could only ever fail, and it failed by throwing. tryConvertFieldToType swallows the exception, so results and granule pruning are unaffected - but the count is already recorded, because system.errors is incremented in the Exception constructor. A query of that shape drove TYPE_MISMATCH up on every execution, resettable only by restarting the server:

CREATE TABLE t (A String, Timestamp DateTime64(9)) ENGINE = MergeTree ORDER BY (A, Timestamp);
SELECT count() FROM t WHERE A = 'x' AND Timestamp >= now() - INTERVAL 5 MINUTE;

Adding the branch also lets the folding apply to DateTime64 columns, where it previously bailed out every time.

On the reported reproduction conditions. The issue attributes this to MergeTree key analysis and to the ORDER BY placing the DateTime64 column after a prefix column. Neither holds: KeyCondition::extractAtomFromTree short-circuits this type pair before any conversion (KeyCondition.cpp:4080), and that path converts to the supertype so its message would read Expected: DateTime64(9). The pass that throws runs on the query tree and cannot see the sorting key - what is actually required is an AND plus the type mismatch.

Why 26.7. The round-trip guard came in with 5e12963 ("Fix optimize_redundant_comparisons folding on truncated DateTime64 constants", #99736), which is in 26.7 and not in 26.6. It was added to fix genuinely wrong folding on lossy constants; attempting DateTime64 -> DateTime was incidental.

Why not suppress the counter. Exception::SuppressErrorCodesScope exists for handled exceptions and #111845 is rolling it out broadly, but it does not touch either file involved here, and using it would hide a conversion gap worth closing on its own merits. Time64 -> Time looks like the same gap; I have left it out of this change since nothing exercises it yet.


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

`convertFieldToTypeImpl` widens a `DateTime` constant to a `DateTime64` column type but had no
branch for the other direction: the `DateTime` case accepted only `UInt64`, and
`WhichDataType(DateTime).isUInt32()` is false so the numeric dispatch did not pick it up either.
A `DecimalField<DateTime64>` aimed at `DataTypeDateTime` therefore fell through every branch to
the `TYPE_MISMATCH` at the end of the function.

`LogicalExpressionOptimizerPass::tryConvertToColumnType` round-trips a constant through the
column's type to check that widening it lost nothing, so for a `DateTime64` column compared
against a `DateTime` constant the reverse leg could only ever fail - and it failed by throwing.
`tryConvertFieldToType` swallows the exception and the query is unaffected, but the count has
already been recorded, because `system.errors` is incremented in the `Exception` constructor.
A `SELECT` matching that shape drove `TYPE_MISMATCH` up on every execution, resettable only by
restarting the server.

Add the missing branch. Under `strict` a sub-second part makes the value unconvertible, which is
exactly the lossiness the round trip is checking for, so the guard now answers without an
exception and the folding applies to `DateTime64` columns instead of always bailing out.

The round-trip guard arrived in 26.7 with 5e12963 (ClickHouse#99736), which is why the counter starts
moving there.

Closes: ClickHouse#117903
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8894e71]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, targeted) FAIL
05150_kv_key_filter_date_family_literal FAIL cidb
05150_kv_key_filter_date_family_literal FAIL cidb
05150_kv_key_filter_date_family_literal FAIL cidb
05150_kv_key_filter_date_family_literal FAIL cidb
05150_kv_key_filter_date_family_literal FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) FAIL
05150_kv_key_filter_date_family_literal FAIL cidb
02918_optimize_count_for_merge_tables NOT_FAILED cidb
02156_storage_merge_prewhere NOT_FAILED cidb
02402_merge_engine_with_view NOT_FAILED cidb
02346_non_negative_derivative NOT_FAILED cidb
Stateless tests (amd_llvm_coverage, AsyncInsert, s3 storage, parallel) FAIL
05150_kv_key_filter_date_family_literal FAIL cidb
03008_deduplication_insert_into_partitioned_table NOT_FAILED cidb
03008_deduplication_cases_from_docs NOT_FAILED cidb
00952_insert_into_distributed_with_materialized_column NOT_FAILED cidb
03752_attach_as_replicated_transaction_metadata NOT_FAILED cidb
02912_ingestion_mv_deduplication NOT_FAILED cidb
Stateless tests (amd_debug, parallel) FAIL
05150_kv_key_filter_date_family_literal FAIL cidb
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) FAIL
05150_kv_key_filter_date_family_literal FAIL cidb
Stateless tests (arm_binary, parallel) FAIL
05150_kv_key_filter_date_family_literal FAIL cidb
Stateless tests (amd_asan_ubsan, distributed plan, parallel, selected tests) FAIL
05150_kv_key_filter_date_family_literal FAIL cidb
Stateless tests (amd_tsan, parallel, selected tests) FAIL
05150_kv_key_filter_date_family_literal FAIL cidb
Stateless tests (amd_tsan, s3 storage, parallel, selected tests) FAIL
05150_kv_key_filter_date_family_literal FAIL cidb
Stateless tests (arm_asan_ubsan, azure, parallel) FAIL
05150_kv_key_filter_date_family_literal FAIL cidb

AI Review

Summary

This PR closes the original DateTime64 / Time64 round-trip bug, unwraps Nullable / LowCardinality source hints, and threads plain container element hints through Array, Tuple, and Map. The main DateTime64 and Enum fixes look correct, but the new recursive hint propagation still stops at Variant / Dynamic carriers, so semantically equivalent wrapped container elements can still miss the new conversion branches.

Findings

⚠️ Majors

  • [src/Interpreters/convertFieldToType.cpp:234] Container recursion now forwards declared element types, but it still does not recover the active Variant / Dynamic alternative for each element. A Field loses that carrier information, so Array(Variant(DateTime64(3), String)) -> Array(DateTime) still bypasses the new DateTime64 narrowing, and Array(Variant(Enum8('7' = 3))) -> Array(String) still bypasses enum-name rendering. The fix should resolve the active alternative per element before recursing, or explicitly reject those carriers and test that contract.
Tests
  • Added coverage exercises plain Array / Tuple / Map hints, wrapped Nullable / LowCardinality hints, MongoDB IN / NOT IN, and the system.errors regression, but it does not cover nested Variant / Dynamic element carriers.
Final Verdict

Changes requested: the recursive hint propagation is still incomplete for container elements whose semantic source type is hidden behind Variant or Dynamic.

LLVM Coverage Report

Measured on commit 8894e71.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 56/61 (91.80%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 3, 2026
Comment thread src/Interpreters/convertFieldToType.cpp Resolved
@zlareb1

zlareb1 commented Sep 4, 2026

Copy link
Copy Markdown
Member

The new branch fixes the loud TYPE_MISMATCH shapes nicely, but gating the sub-second rejection on strict makes it the first non-strict lossy conversion toward an integer-domain type in this file, and one non-strict caller turns that into silent wrong results:

if (strict && DecimalUtils::getFractionalPart(from_value.getValue(), from_scale) != 0)
    return {};

The file's convention (see the exact computation for the numeric path, and the comment in convertFieldToType.h about optimizer/pruning callers) is that non-strict callers still get exact-only conversion when the target cannot represent the value, precisely because several callers treat the converted constant as an exact comparison bound.

Concrete consumer: StorageMongoDB::visitWhereFunctionArguments (StorageMongoDB.cpp:392) calls non-strict convertFieldToType to build the BSON filter pushed to MongoDB, and it pushes ordering and negative operators ($ne, $nin, $lt, $gt). With a DateTime column and a sub-second DateTime64 constant, e.g. WHERE ts != toDateTime64('2020-01-01 00:00:00.5', 1), the true result includes a document at 2020-01-01 00:00:00 (the comparison happens in the DateTime64 supertype), but after this change the constant truncates to 00:00:00 and {ts: {$ne: ...}} excludes exactly that document on the MongoDB side. The local re-filter can only remove rows, never restore unfetched ones, so the rows are silently lost. The same under-fetch applies to $lt at the boundary and to $nin. Today this exact call path fails loudly with TYPE_MISMATCH (verified the same type pair through this function on 26.9.1.1 via an EmbeddedRocksDB key comparison), and mongodb_throw_on_unsupported_query does not help because the conversion now succeeds.

Suggested fix: reject a non-zero fractional part unconditionally (drop the strict &&). Nothing is lost for the motivating caller — LogicalExpressionOptimizerPass::tryConvertToColumnType passes strict = true — and the equality shapes this PR fixes (whole-second constants against EmbeddedRocksDB/KeeperMap/MongoDB keys) keep working.

One adjacent hardening: the branch keys on the field type Decimal64 without checking from_type_hint, so a Time64 constant (also carried as DecimalField<Decimal64>, seconds-of-day) aimed at a DateTime column would be reinterpreted as epoch seconds — and DateTime vs Time64 comparisons do resolve, so the same pushdown path can reach it. Gating the branch on from_type_hint && isDateTime64(from_type_hint) would scope it to the intended conversion.

…urce type

Two problems with the branch as first written, both raised in review.

It gated the sub-second rejection on `strict`, which made it the only non-strict
lossy conversion toward an integer-domain type in this file. Non-strict callers
push the converted constant down as an exact comparison bound:
`StorageMongoDB::visitWhereFunctionArguments` builds a BSON filter from it, and
its own comment says the conversion exists because MongoDB cannot cast
implicitly and the `WHERE` result would otherwise be wrong. Truncating a
sub-second constant there turns `!=` or `<` at the boundary into rows that are
never fetched, and the local re-filter can only drop rows, not restore them.
Today that path fails loudly instead. Reject a non-zero fractional part
unconditionally; the motivating caller passes `strict = true` and is unaffected.

It also keyed on the `Field` tag alone. `Time64` is carried as
`DecimalField<Decimal64>` too but counts seconds of day, so a `Time64` constant
aimed at a `DateTime` column would have been reinterpreted as an epoch. Key both
narrowings on the source type via `which_from_type`.

Add the symmetric `Time64` -> `Time` branch while here. `tryConvertToColumnType`
round-trips a `Time` constant through a `Time64` column exactly as it does for
`DateTime`, and `enable_time_time64_type` defaults to true, so that leg was
reachable as well - the earlier claim that nothing exercised it was wrong.
@navneet83

Copy link
Copy Markdown
Member Author

Thank you - both of these were real and I have fixed them in d416ab1.

The strict gate. You are right, and the MongoDB path is the convincing part. StorageMongoDB.cpp:392 calls convertFieldToType(const_value, *column_type, const_type.get()) with no strict argument, and the comment directly above it says the conversion exists precisely because MongoDB cannot cast implicitly and the WHERE result would otherwise be wrong. Truncating a sub-second constant there means the $ne document is never fetched, and a local re-filter cannot put it back. Trading a loud failure for silently missing rows is a bad trade. The fractional part is now rejected unconditionally; tryConvertToColumnType passes strict = true so the motivating case is unaffected.

The from_type_hint gap. Also right, and I had not considered it. Time64 is carried as DecimalField<Decimal64> as well - the existing branch at convertFieldToType.cpp:487 keys on the same Field::Types::Decimal64 - so a Time64 constant aimed at a DateTime column would have been read as an epoch. Both narrowings are now keyed on which_from_type, which the function already computes from the hint.

And the Time64 leg. The bot flagged the same gap for Time64 -> Time, and it is right that I was wrong to leave it out: I wrote in the PR description that nothing exercised it, but enable_time_time64_type defaults to true and tryConvertToColumnType round-trips a Time constant through a Time64 column exactly as it does for DateTime. Added symmetrically, with the same unconditional rejection and an Int32 range check, since Time is Int32-backed with an Int64 canonical Field. The test now covers that leg too.

Worth noting for anyone reading later: the two failure modes you found are opposite in kind. The one this PR started with was noisy but harmless - a counter moving on a correct query. The one you caught would have been silent and wrong. Better to have found it here.

Comment thread src/Interpreters/convertFieldToType.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8894e71d8 with master 718e603a5 (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.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-datetime Date/DateTime/TimeZone datatypes and date-time semantics. label Sep 4, 2026
`convertFieldToType` unwraps `to_type` but passes the source type exactly as the caller
declared it, so a constant typed `Nullable(DateTime64)` arrives wrapped. Every test in
`convertFieldToTypeImpl` reads that hint through `WhichDataType`, so all of them read
false and the conversion falls through to the `TYPE_MISMATCH` this function was just
changed to avoid - reappearing for a query that differs only in naming a wrapped type.
`StorageMongoDB::visitWhereFunctionArguments` (`StorageMongoDB.cpp:392`) passes the
literal's own result type, which is where this is reachable.

Unwrap the pointer rather than only the `WhichDataType`. Several of the branches these
tests guard go on to `static_cast<const DataTypeDateTime &>(*from_type_hint)` to read a
time zone, so correcting the test alone would convert an inert branch into an invalid
cast. A null source is rejected by `convertFieldToType` before this point, so the value
carried under a `Nullable` hint is always a real one.

This also subsumes the identical loop the enum-to-string branch was already running on
its own, which is now removed.

Tested in `gtest_convertFieldToType` rather than the stateless suite: the only caller
that can produce a wrapped hint is the MongoDB predicate pushdown, which needs a server.
Both cases fail against the unpatched function and pass with it; the surrounding
`convertFieldToType` and `convertColumnToType` suites stay at 44/44.
Comment thread src/Interpreters/convertFieldToType.cpp Resolved
The `from_type_hint` handling stopped at the top level: the `Array`, `Tuple` and `Map`
branches of `convertFieldToTypeImpl` recursed with no hint, so each element was converted as
a bare field with no semantic type. `StorageMongoDB` converts the constants of `$in` / `$nin`
with the literal's type as the hint, and an `IN` list arrives as `Array(DateTime64(3))`; its
elements then missed the `DateTime64` -> `DateTime` branch and threw `TYPE_MISMATCH`, which
`visitWhereFunctionArguments` does not catch, so the query failed instead of being pushed
down.

`getElementTypeHint` yields the source type of one element - the nested type of an `Array`
hint, or element `i` of a `Tuple` hint, since an `IN` list is a tuple literal converted to the
set's array type - and the `Map` branch takes the hint's key and value types. The element
hint is passed as written; the recursive call unwraps `Nullable` and `LowCardinality` itself.

The gtest covers `Array`, `Tuple` and `Map` with a `DateTime64(3)` element hint into
`DateTime`; the MongoDB integration test adds the `IN` / `NOT IN` shape against a `DateTime`
column.
The test pinned the old number-instead-of-name value for an `Enum` element
inside an `Array` as a documented limitation, waiting for the element type
hint to be passed down the container recursion. That is what the previous
commit does, so the cell now checks the name.

Fast test report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117977&sha=28962baa5eda5099bea107aa02ea24ad0857e531&name_0=PR&name_1=Fast%20test
PR: ClickHouse#117977
/// tuple literal converted to the set's array type, so a `Tuple` source is paired with an `Array`
/// target as well. Null when the source type is not a container of a known shape, in which case
/// the element is converted with no hint, as before.
const IDataType * getElementTypeHint(const IDataType * container_hint, size_t i)

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.

getElementTypeHint now preserves plain Array / Tuple / Map element declarations, but it still does not recover carrier-hidden element types. A Field loses the active Variant / Dynamic alternative, so an element from Array(Variant(DateTime64(3), String)) or Tuple(Variant(Enum8('7' = 3))) still reaches the recursive call with from_type_hint = Variant(...), not the active DateTime64 / Enum8 type.

That means the new which_from_type.isDateTime64() and enum-name branches are skipped again for semantically equivalent wrapped elements: values('x Array(DateTime)', [CAST(toDateTime64('2020-01-01 00:00:00', 3), 'Variant(DateTime64(3), String)')]) still falls through to TYPE_MISMATCH, and Array(Variant(Enum8('7' = 3))) -> Array(String) still serializes '3' instead of '7'. Please resolve the active alternative per element before recursing (analogous to resolveActiveAlternativeType for scalar Variant / Dynamic constants), or reject these carriers explicitly and cover that contract with a focused test.

@navneet83

Copy link
Copy Markdown
Member Author

Closing to rework and resubmit.

@navneet83 navneet83 closed this Sep 17, 2026
@navneet83
navneet83 deleted the fix-datetime64-to-datetime-field-conversion branch September 19, 2026 18:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-datetime Date/DateTime/TimeZone datatypes and date-time semantics. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TYPE_MISMATCH counted in system.errors during key condition analysis (regression in 26.7.1)

2 participants