Skip to content

Fix formatDateTime with a LowCardinality time zone - #117006

Merged
alexey-milovidov merged 10 commits into
masterfrom
formatdatetime-lowcardinality-timezone
Sep 20, 2026
Merged

alexey-milovidov merged 10 commits into
masterfrom
formatdatetime-lowcardinality-timezone

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 29, 2026 •

Copy link
Copy Markdown
Member

Closes: #117437

formatDateTime, formatDateTimeInJodaSyntax, fromUnixTimestamp and fromUnixTimestampInJodaSyntax accept a non-constant time zone argument. When that argument is a LowCardinality column, the function is executed on the column's dictionary, which always contains the default value - the empty string - even when no row references it. The empty string is not a valid time zone, so the query failed before reading a single row:

:) WITH number % 2 ? 'UTC' : 'Europe/Amsterdam' AS tz SELECT DISTINCT formatDateTime(now(), '%F %T', toLowCardinality(tz)) FROM numbers(1e8)

Received exception:
Code: 43. DB::Exception: Provided time zone must be non-empty: while executing function formatDateTime on arguments
_CAST(1787961521_DateTime, 'DateTime'_String) DateTime Const(size = 0, UInt32(size = 1)),
'%F %T'_String String Const(size = 0, String(size = 1)),
toLowCardinality(if(modulo(__table1.number, 2_UInt8), 'UTC'_String, 'Europe/Amsterdam'_String)) LowCardinality(String)
LowCardinality(size = 0, UInt8(size = 0), Unique(size = 1, String(size = 1))). (ILLEGAL_TYPE_OF_ARGUMENT)

The same query without toLowCardinality works.

The fix reports that these functions cannot be executed on default arguments, the same way CAST already does, so that only the values the rows actually reference are formatted. An empty time zone in the data is still an error.

canBeExecutedOnDefaultArguments is asked without the arguments, so it cannot on its own tell a LowCardinality time zone from a LowCardinality date or integer, for which the dictionary default is harmless. To keep the dictionary-only execution of formatDateTime(lc_datetime, '%F') and of the one-argument fromUnixTimestamp(lc_uint32), the family is registered through FunctionWithLowCardinalityFastPath and implements tryExecuteLowCardinality, which declines - and so asks for a minimal dictionary of the referenced values - only when the third timezone argument is a non-constant LowCardinality column, and otherwise redoes the call on a delegate that keeps canBeExecutedOnDefaultArguments enabled.

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):

Fix the error Provided time zone must be non-empty when the time zone argument of formatDateTime, formatDateTimeInJodaSyntax, fromUnixTimestamp or fromUnixTimestampInJodaSyntax is a LowCardinality column.


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

Version info

  • Merged into: 26.10.1.295-master (included in 26.10 and later)

`formatDateTime`, `formatDateTimeInJodaSyntax`, `fromUnixTimestamp` and
`fromUnixTimestampInJodaSyntax` accept a non-constant time zone argument. When
that argument is a `LowCardinality` column, the function is executed on the
column's dictionary, which always contains the default value - the empty string
- even when no row references it. The empty string is not a valid time zone, so
the query failed before reading a single row:

    :) WITH number % 2 ? 'UTC' : 'Europe/Amsterdam' AS tz
       SELECT DISTINCT formatDateTime(now(), '%F %T', toLowCardinality(tz)) FROM numbers(1e8)

    Code: 43. DB::Exception: Provided time zone must be non-empty:
    while executing function formatDateTime ... (ILLEGAL_TYPE_OF_ARGUMENT)

Report that these functions cannot be executed on default arguments, the same
way `CAST` and `toString` already do, so that only the values the rows actually
reference are formatted. An empty time zone in the data is still an error.
@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3be07a3]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR fixes the LowCardinality timezone handling for formatDateTime, formatDateTimeInJodaSyntax, fromUnixTimestamp, and fromUnixTimestampInJodaSyntax by narrowing the expensive minimal-dictionary path to the non-constant timezone case and preserving the old dictionary fast path for value-only LowCardinality arguments. I did not find a remaining blocker in the execution logic, but there is still one user-facing documentation mismatch to clean up before this is fully consistent.

Missing context / blind spots
  • ⚠️ No local build directory was available in this checkout, so I could not execute the new stateless test or a targeted query locally; the verdict relies on code-path tracing against the current PR head plus the regression coverage added in the PR.
Findings

💡 Nits

  • [src/Functions/formatDateTime.cpp:2265] The structured docs for fromUnixTimestamp and fromUnixTimestampInJodaSyntax still describe the third argument as a constant timezone string, even though the code and the new regression test rely on non-constant timezone columns being supported. That leaves the generated reference docs and system.functions contract wrong after the fix.
    Suggested fix: update the affected FunctionDocumentation::Description and FunctionDocumentation::Arguments strings in the same file to describe a non-constant timezone argument consistently with formatDateTime.
Final Verdict

Needs one documentation follow-up. I found no remaining correctness or performance blocker in the LowCardinality execution fix itself.

LLVM Coverage Report

Measured on commit 3be07a3.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 80.70% 80.60% -0.10%

Changed lines: Changed C/C++ lines covered: 36/37 (97.30%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit 3be07a36c266e31ec9e967ff4427c6e75fd6a8f7 with master failed: RuntimeError: CI logs cluster query failed: SELECT file, symbol, sumIf(size, side = 'pr….

See the job log for details.

The fix lives in the shared `FunctionFormatDateTimeImpl<support_integer, format_syntax>`,
so add a regression query for the remaining `support_integer` + Joda instantiation -
`fromUnixTimestampInJodaSyntax` - which was the only one of the four entrypoints named in
the description without direct coverage.

Renumber the test from `05048` to `05054`: `05048` was taken on master in the meantime.
@clickhouse-gh clickhouse-gh Bot added comp-datetime Date/DateTime/TimeZone datatypes and date-time semantics. comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... and removed comp-datetime Date/DateTime/TimeZone datatypes and date-time semantics. labels Sep 4, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117006&sha=d2ec1eaef74e8f12048cd4261d262736ce4f5cef&name_0=PR&name_1=AST%20fuzzer%20%28amd_release%2C%20oracle%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

It is a TLP WHERE oracle mismatch on a table that has nothing to do with this pull request (the reproducer is SELECT ' iryaP:kmrey' FROM \03581_data__fuzz_16` WHERE key = toNullable(2000)— no date/time function is involved, while this pull request only changescanBeExecutedOnDefaultArgumentsof theformatDateTimefamily). The partitionedUNION ALL` returns 3000 rows against the reference query's 2000, so one of the three partitions over-counts.

AST fuzzer (amd_release, oracle) errors on roughly 2–3% of all runs fleet-wide over the last week (CIDB, per day: 4/141, 7/269, 14/410, 5/349, 9/301, 4/228, 5/239 on 2026-09-11 … 2026-09-05), so this is not specific to this branch.

I have merged master (4493 commits) into the branch and re-ran the regression test plus 11 related formatDateTime/fromUnixTimestamp tests locally — all pass.

Comment thread src/Functions/formatDateTime.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

AST fuzzer (amd_release, oracle): not caused by this PR, and #118484 already covers it

The job's own fuzzer.log carries the two definitions the report needs:

CREATE TABLE `03581_data__fuzz_16` ENGINE = Buffer(currentDatabase(), '03581_data__fuzz_3', 1, 1, 10, 10000, 1000000, 10000000, 100000000)
CREATE TABLE `03581_data__fuzz_3` (`key` LowCardinality(UInt32), ...) ENGINE = SummingMergeTree ORDER BY key SETTINGS index_granularity = 10, ...

So the relation the oracle read twice is an in-memory buffer unioned with a merge-collapsing destination read without FINAL, over a fixture that inserts the same 1000 keys (03581_data: insert into 03581_data select number, number, number from numbers(1000)). Its visible row count is a function of flush and merge state, not of its contents.

No partition over-counts. The arms partition on p, NOT p and p IS NULL, which is exhaustive for every value key = toNullable(2000) can take, so a wrong value can only move a row between arms, never add one. 2000 to 3000 is exactly one insert unit, which predicate evaluation cannot produce; the sign of the difference is set by where the change lands between the two executions.

Reproduced on master c108e273b6087 (debug) with the same oracle and the same message, without fuzzing any definition, in 1 of 6 attempts at 300 fuzzer runs each:

reproducer and output
CREATE TABLE s (key UInt32, val_minmax UInt32, val_set UInt32) ENGINE = SummingMergeTree ORDER BY key SETTINGS index_granularity = 10;
SYSTEM STOP MERGES s;
INSERT INTO s SELECT number, number + 1, number + 1 FROM numbers(1000);   -- x 150
SELECT count() FROM s;         -- 150000
SELECT count() FROM s FINAL;   -- 1000
SYSTEM START MERGES s;
-- clickhouse local --ast_fuzzer_runs=300 --ast_fuzzer_oracle=1 --ast_fuzzer_any_query=0
SELECT ' iryaP:kmrey' FROM s WHERE key = 2000;
Code: 906. DB::Exception: TLP WHERE oracle mismatch!
Reference query (150000 rows): SELECT ' iryaP:kmrey' FROM s
Partitioned query (100000 rows): SELECT ' iryaP:kmrey' FROM s WHERE key = 2000 UNION ALL SELECT ' iryaP:kmrey' FROM s WHERE not(key = 2000) UNION ALL SELECT ' iryaP:kmrey' FROM s WHERE isNull(key = 2000)

The fix for this report is already in progress: #118484 rejects a query naming a table whose readsFromOtherTables() is true, and StorageBuffer::readsFromOtherTables() is static_cast<bool>(destination_id) (src/Storages/StorageBuffer.h:91), so 03581_data__fuzz_16 is screened and none of the nine oracles run on it.

That is not the whole hole, and I will send the rest as a separate PR: the reproducer above names no Buffer, nothing screens a merge-collapsing engine read without FINAL, and only Subquery wrap protects itself, by re-executing the reference and skipping when it is not stable (QueryOracleChecker.cpp:2512). The other eight oracles compare a single reference execution. I will post that PR here.

@clickhouse-gh clickhouse-gh Bot added comp-datetime Date/DateTime/TimeZone datatypes and date-time semantics. and removed comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Sep 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

The separate fix PR is up: #119465.

It generalizes the reference-stability guard checkSubqueryWrap already carried (59efd8be4ca73) to the other eight oracles: on the mismatch path only, the reference read is executed once more, and a mismatch is reported only if it reproduces. That closes the residual my earlier comment left open, where a merge-collapsing engine read without FINAL, a concurrent INSERT, or a non-canonical AggregateFunction state changes the relation between an oracle's two reads.

The report on this pull request needs nothing further: #118484 already skips a query whose read reaches a Buffer destination.

alexey-milovidov and others added 4 commits September 18, 2026 13:26
The AI review pointed out that `canBeExecutedOnDefaultArguments` is global for
the whole `FunctionFormatDateTimeImpl`, so returning `false` also dropped the
dictionary-only execution for a call whose only `LowCardinality` argument is the
value itself, such as `formatDateTime(lc_datetime, '%F')` or the one-argument
`fromUnixTimestamp(lc_uint32)`. Those went through
`getMinimalDictionaryEncodedColumn`, which remaps every row index, even though
the dictionary default is harmless for a date, a date with time or an integer.

The hook is asked without the arguments, so it cannot make the distinction by
itself. Register the family through `FunctionWithLowCardinalityFastPath` and add
a `tryExecuteLowCardinality` that declines only when the third `timezone`
argument is a non-constant `LowCardinality` column - the one case whose
dictionary holds the empty string - and otherwise redoes the call on a delegate
that keeps `canBeExecutedOnDefaultArguments` enabled.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Update on 2026-09-18.

AI Review blocker adopted. canBeExecutedOnDefaultArguments is asked on IExecutableFunction without the arguments, so the function cannot answer it per argument. The family is now registered through FunctionWithLowCardinalityFastPath and implements tryExecuteLowCardinality, which declines - and so pays for getMinimalDictionaryEncodedColumn - only when the third timezone argument is a non-constant LowCardinality column, and otherwise redoes the call on a delegate whose canBeExecutedOnDefaultArguments is left enabled. formatDateTime(lc_datetime, '%F'), the one-argument fromUnixTimestamp(lc_uint32) and a constant LowCardinality time zone therefore keep the dictionary-only execution: SELECT max(formatDateTime(toLowCardinality(toDateTime('2026-08-29 00:00:00', 'UTC') + number % 2), '%F %T %e %M %j')) FROM numbers_mt(200000000) takes 0.129 s against 0.069 s for SELECT max(number) over the same source, i.e. no per-row formatting and no per-row index remapping.

The test covers the preserved path for all four entrypoints, a constant and a non-constant LowCardinality time zone over a LowCardinality value, and the result type. Locally the test plus 14 other formatDateTime/fromUnixTimestamp tests pass, and an extra battery confirms that LowCardinality(Nullable) values and time zones, a NULL time zone, the all-constant case, zero rows and 200000-row scans produce exactly the same results as the non-LowCardinality spellings.

master merged (3955 commits, no conflicts), which clears the two reds of the previous run:

  • 03100_lwu_deletes_4_index in Stateless tests (amd_debug, distributed plan, s3 storage, parallel) - fleet-wide on 2026-09-11: 189 failures that day across ~67 different pull requests and master itself (CIDB checks, test_name = '03100_lwu_deletes_4_index', pull_request_number = 0 OR base_ref = 'master'), then 1 failure on 2026-09-16 and none since. Not specific to this branch and already fixed on master.
  • Upgrade check (amd_release), Logical error: Got read request from replica A for unknown stream B. - Logical error: Got read request from replica A for unknown stream B. (STID: 5217-5b3d) #110518, still open, unrelated to date and time formatting.

AST fuzzer (amd_release, oracle) - thanks @groeneai, that matches what the report shows; nothing further is needed here since #118484 screens a read that reaches a Buffer destination, and #119465 closes the residual for a merge-collapsing engine read without FINAL.

{description_fromUnixTimestamp, syntax_fromUnixTimestamp, arguments_fromUnixTimestamp, {}, returned_value_fromUnixTimestamp, examples_fromUnixTimestamp, introduced_in_fromUnixTimestamp, category_fromUnixTimestamp};

factory.registerFunction<FunctionFromUnixTimestamp>(documentation_fromUnixTimestamp);
factory.registerFunction<FunctionWithLowCardinalityFastPath<FunctionFromUnixTimestamp>>(documentation_fromUnixTimestamp);

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.

The PR contract and the new regression test both rely on a non-constant timezone argument here, but the structured FunctionDocumentation for fromUnixTimestamp and fromUnixTimestampInJodaSyntax still says the third argument is an optional constant time zone string.

Because those strings feed the reference docs and system.functions, users will still be told that the fixed call shape is unsupported. Please update those descriptions and argument docs in the same change.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Sep 20, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 20, 2026
Merged via the queue into master with commit bceadd7 Sep 20, 2026
174 of 176 checks passed
@alexey-milovidov
alexey-milovidov deleted the formatdatetime-lowcardinality-timezone branch September 20, 2026 20:25
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 20, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

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 pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

formatDateTime rejects any LowCardinality(String) time zone column

4 participants