Skip to content

Fix session_timezone ignored during server-side DateTime parsing - #100647

Merged
CheSema merged 14 commits into
masterfrom
test-async-insert-session-timezone
Mar 31, 2026
Merged

CheSema merged 14 commits into
masterfrom
test-async-insert-session-timezone

Conversation

@CheSema

@CheSema CheSema commented Mar 24, 2026 •

Copy link
Copy Markdown
Member

When a DateTime column has no explicit timezone, SerializationDateTime used the timezone baked into table metadata (captured at CREATE TABLE time). This caused session_timezone to be ignored for all server-side parsing paths: async inserts over TCP, and both sync and async inserts over HTTP.

The fix moves timezone resolution into DataTypeDateTime::doGetSerialization and DataTypeDateTime64::doGetSerialization. When a column has no explicit timezone, these methods call DateLUT::instance() (which respects session_timezone from the current thread's query context) and create a SerializationDateTime with the effective timezone. The serialization object pool deduplicates by timezone hash, so only one instance exists per distinct timezone.

This approach avoids calling DateLUT::instance() per-row (which caused mutex contention under parallel formatting with ASan, leading to timeouts in 00159_parallel_formatting_http). Instead, the timezone is resolved once per column per chunk in doGetSerialization, and the serialization objects remain immutable and safe for concurrent use.

Closes #100614

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 session_timezone being ignored when parsing DateTime values during async inserts (TCP) and all inserts over HTTP.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.4.1.433
  • Backported to: 26.3.3.20, 26.2.7.22

@clickhouse-gh

clickhouse-gh Bot commented Mar 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8d57655]

Summary: ❌

job_name test_name status info comment
Stress test (arm_asan_ubsan) failure
Logical error: Unexpected return type from A. Expected B. Got C (STID: 3262-3dce) FAIL cidb
Stress test (arm_msan) failure
Cannot start clickhouse-server FAIL cidb
Parse failure error failure cidb
Check failed failure cidb
Stress test (arm_ubsan) failure
Logical error: '(isConst() || isSparse() || isReplicated()) ? getDataType() == rhs.getDataType() : typeid(*this) == typeid(rhs)' (STID: 2508-3e6f) FAIL cidb

AI Review

Summary

This PR fixes session_timezone handling for server-side DateTime / DateTime64 text parsing by resolving effective timezone during serialization creation, and adds coverage for HTTP/TCP async paths plus mutation predicate rewriting. High-level verdict: good direction and substantial test coverage, but there is one correctness issue in mixed multi-command ALTER execution that can rewrite mutation datetime literals using stale column metadata.

Missing context
  • ⚠️ No CI logs/results were provided in this review context.
Findings

⚠️ Majors

  • [src/Interpreters/InterpreterAlterQuery.cpp:143] rewriteDateTimeLiteralsWithTimezone is fed by table->getInMemoryMetadata().columns during command parsing, before earlier segments in the same ALTER query are applied. In mixed statements (e.g. MODIFY COLUMN + DELETE), mutation literals may be rewritten using outdated timezone semantics, causing incorrect predicate evaluation.
    • Suggested fix: perform rewrite against a metadata snapshot that reflects preceding ALTER segment effects, or defer rewrite to just before table->mutate with a fresh snapshot.

💡 Nits

  • [tests/queries/0_stateless/04057_async_insert_session_timezone.sh:67-68] Duplicate adjacent comment line (The column's explicit timezone is used for parsing plain string literals.) should be de-duplicated.
Tests
  • ⚠️ Add a stateless test for a mixed multi-command ALTER where an earlier command changes DateTime timezone semantics and a later DELETE/UPDATE predicate uses datetime string literals, to verify rewrite uses post-change metadata.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ⚠️ Mixed-segment ALTER rewrite uses pre-segment metadata in parseAlterCommandSegments.
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ⚠️ Potential incorrect mutation predicate behavior in mixed ALTER statements due to stale metadata-based rewrite.
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ⚠️ Needs mixed-command regression coverage before confident rollout.
Compilation time ✅
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Fix mutation datetime literal rewrite to use correct (post-segment) metadata in mixed ALTER command sequences.
    • Add a regression test covering that mixed-command case.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Mar 24, 2026
CheSema and others added 2 commits March 25, 2026 10:19
… the bug

The bug affects all server-side parsing paths, not just async insert.
HTTP sync inserts are also broken because `DataTypeDateTime` in table
metadata bakes in the timezone at CREATE TABLE time. Compare unix
timestamps to avoid the display-masking effect where wrong timezone on
INSERT is cancelled out by the same wrong timezone on SELECT.

Reference reflects current buggy behavior (3 of 4 cases wrong).

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…-side parsing

When a `DateTime` column has no explicit timezone, `SerializationDateTime`
used the timezone baked into table metadata (captured at CREATE TABLE time).
This caused `session_timezone` to be ignored for all server-side parsing
paths: async inserts over TCP, and both sync and async inserts over HTTP.

Add `getEffectiveTimeZone` that dynamically resolves the timezone via
`DateLUT::instance()` (which respects `session_timezone` from the current
thread's query context) when the column has no explicit timezone, and
returns the baked timezone when it does (e.g. `DateTime('UTC')`).

#100614

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@CheSema CheSema changed the title Add reproducer test for async insert ignoring session_timezone Fix session_timezone ignored during server-side DateTime parsing Mar 25, 2026
@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Mar 25, 2026
When session_timezone is active it should override the column's timezone
for text parsing, even for columns with an explicit timezone like
`DateTime('America/New_York')`. Updated `getEffectiveTimeZone` to check
whether `DateLUT::instance()` differs from the server default.

Extended the test to cover both `DateTime` (no explicit timezone) and
`DateTime('America/New_York')` (explicit timezone) cases.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
CheSema and others added 2 commits March 25, 2026 12:51
Apply `session_timezone` fix to `SerializationDateTime64` (same pattern
as `SerializationDateTime`). Split `getEffectiveTimeZone` into
`getInputTimeZone` and `getOutputTimeZone`:

- Both respect explicit column timezone (e.g. `DateTime('UTC')`) — it
  takes precedence over `session_timezone`.
- For columns without explicit timezone, both use `DateLUT::instance()`
  which dynamically resolves `session_timezone`.

Extended the test to cover `DateTime64`, `DateTime64` with explicit
timezone, and `DateTime` with explicit timezone. Updated test
`02737_session_timezone` with section labels for easier debugging.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…etEffectiveTimeZone`

Both methods had identical logic, so a single method is sufficient.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
CheSema and others added 3 commits March 25, 2026 13:45
Co-authored-by: clickhouse-gh[bot] <173705893+clickhouse-gh[bot]@users.noreply.github.com>
The pooled serialization cache keys did not include the
`has_explicit_time_zone` flag. When two `DataType`s resolve to the same
timezone name but differ in whether the timezone was explicitly specified
(e.g. `DateTime('UTC')` vs plain `DateTime` on a UTC-default server),
they shared the same pooled `SerializationDateTime` object. With the
`getEffectiveTimeZone` change, `has_explicit_time_zone` now controls
whether the baked timezone or the dynamic `DateLUT::instance()` is used,
so the flag must be part of the cache key to avoid cross-contamination.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…House/ClickHouse into test-async-insert-session-timezone
Co-authored-by: clickhouse-gh[bot] <173705893+clickhouse-gh[bot]@users.noreply.github.com>
…plicit timezone

PR #100647 makes `SerializationDateTime` respect `session_timezone` via
`DateLUT::instance()`, which is thread-context-dependent. Mutation background
threads lack the original session context, so string literals like
'2000-01-01 02:00:00' resolve to different Unix timestamps than intended.

This adds an AST visitor that runs at ALTER time (alongside
`replaceNonDeterministicToScalars`) and wraps DateTime string literals with
explicit `toDateTime`/`toDateTime64` calls including the session timezone,
making interpretation deterministic regardless of execution context.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@yariks5s yariks5s self-assigned this Mar 25, 2026
…r-row

The previous approach called `DateLUT::instance` in `getEffectiveTimeZone`
on every row during serialization. Under parallel formatting with ASan,
this caused extreme mutex contention in `DateLUT::getImplementation` (1M+
lock/unlock cycles per column), leading to timeouts in tests like
`00159_parallel_formatting_http`.

Move timezone resolution to `DataTypeDateTime::doGetSerialization` and
`DataTypeDateTime64::doGetSerialization`, which are called once per column
per chunk. The serialization object pool deduplicates by timezone hash,
so only one instance exists per distinct timezone. The serialization
objects remain immutable and safe for concurrent use.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…iter

`getDateTimeColumnType` used `typeid_cast` directly on the column type,
which missed wrapped variants like `Nullable(DateTime)` and
`LowCardinality(DateTime)`. Unwrap via `removeNullable`/`removeLowCardinality`
before the cast so mutation predicates on these columns are also rewritten
with the session timezone.

#100647 (comment)

Co-Authored-By: Claude Opus 4.6 <[email protected]>
{
const auto & source_ast = *mutation_command->ast->as<ASTAlterCommand>();
auto tz_rewritten_ast = rewriteDateTimeLiteralsWithTimezone(
source_ast, table->getInMemoryMetadata().columns, session_tz);

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.

session_timezone rewriting uses table->getInMemoryMetadata().columns from the table state before executing earlier segments in the same ALTER query.

That makes the rewrite stale for mixed statements like:
ALTER TABLE t MODIFY COLUMN time DateTime('UTC'), DELETE WHERE time >= '2000-01-01 02:00:00'.

In this case the mutation predicate can be rewritten with the wrong timezone rule (or not rewritten when it should), because the column type/timezone may have just changed in the preceding ALTER command. Please derive rewrite metadata from the post-alter snapshot used for mutation execution, or defer the rewrite until right before table->mutate with a fresh metadata snapshot.

@clickhouse-gh

clickhouse-gh Bot commented Mar 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 90.90% 90.90% +0.00%
Branches 76.70% 76.70% +0.00%

Changed lines: 75.49% (154/204) · Uncovered code

Full report · Diff report

@CheSema
CheSema deleted the test-async-insert-session-timezone branch March 31, 2026 08:46
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @CheSema @yariks5s — while reviewing this PR I found the following:

Happy to discuss — close anything that's wrong or already addressed.

@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 31, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Mar 31, 2026
robot-clickhouse added a commit that referenced this pull request Mar 31, 2026
robot-clickhouse added a commit that referenced this pull request Mar 31, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Mar 31, 2026
yariks5s added a commit that referenced this pull request Mar 31, 2026
PR #100647 changed `doGetSerialization` to respect `session_timezone`.
Since `convertFieldToType` (used for all implicit string→DateTime
coercion in comparisons) calls `getDefaultSerialization`, bare string
literals in WHERE/BETWEEN/IN should now use session timezone for
columns without explicit timezone.

Add test `04061_session_timezone_where_between_in` covering:
- WHERE =, >=, < with bare strings and toDateTime (consistency check)
- BETWEEN with bare strings
- IN with bare string list
- DateTime64 variants
- Round-trip: INSERT string, SELECT back, verify same string
- Explicit-tz column negative test (column tz takes priority)
- Partition pruning with session_timezone

Also add a TODO note in `KeyCondition.cpp` about the conservative
bail-out for `toDateTime(string_col)` key expressions.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
CheSema added a commit that referenced this pull request Apr 1, 2026
Backport #100647 to 26.2: Fix session_timezone ignored during server-side DateTime parsing
CheSema added a commit that referenced this pull request Apr 1, 2026
Backport #100647 to 26.3: Fix session_timezone ignored during server-side DateTime parsing
@clickgapai

Copy link
Copy Markdown
Contributor

Apologies for the duplicate notification — we had a race condition in our notification system where multiple processes posted simultaneously. The duplicate has been removed and we've added a strict 3-layer dedup guard (DB lock + immediate key + GitHub comment check) to ensure this cannot happen again.

zvonand added a commit to Altinity/ClickHouse that referenced this pull request Jul 19, 2026
…r-side DateTime parsing

Test 04401_async_insert_use_client_time_zone (from ClickHouse#109051) requires the
server to respect session_timezone when parsing DateTime text into columns
without an explicit timezone. Upstream has this since PR ClickHouse#100647 (26.4,
backported to 26.3/26.2) but stable-25.8 does not, so async inserts (TCP)
and all inserts over HTTP were parsed in the server timezone.

- DataTypeDateTime/DataTypeDateTime64: resolve the effective timezone
  (respects session_timezone via DateLUT::instance()) when creating the
  default serialization. Adapted from upstream doGetSerialization() to
  25.8's doGetDefaultSerialization() API (no serialization object pool).
- MutationsDateTimeLiteralVisitor: wrap DateTime string literals in
  mutation predicates/assignments with explicit toDateTime(..., tz) at
  ALTER time, since background mutation threads lack the session context.
  Adapted make_intrusive -> std::make_shared for 25.8 AST pointers.
- Tests from the upstream PR: 02737 update, 04056, 04057.

Co-Authored-By: Claude Fable 5 <[email protected]>
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Jul 19, 2026
…r-side DateTime parsing

Test 04401_async_insert_use_client_time_zone (from ClickHouse#109051) requires the
server to respect session_timezone when parsing DateTime text into columns
without an explicit timezone. Upstream has this since PR ClickHouse#100647 (26.4,
backported to 26.3/26.2) but stable-25.8 does not, so async inserts (TCP)
and all inserts over HTTP were parsed in the server timezone.

- DataTypeDateTime/DataTypeDateTime64: resolve the effective timezone
  (respects session_timezone via DateLUT::instance()) when creating the
  default serialization. Adapted from upstream doGetSerialization() to
  25.8's doGetDefaultSerialization() API (no serialization object pool).
- MutationsDateTimeLiteralVisitor: wrap DateTime string literals in
  mutation predicates/assignments with explicit toDateTime(..., tz) at
  ALTER time, since background mutation threads lack the session context.
  Adapted make_intrusive -> std::make_shared for 25.8 AST pointers.
- Tests from the upstream PR: 02737 update, 04056, 04057.

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
PR ClickHouse#100647 changed `doGetSerialization` to respect `session_timezone`.
Since `convertFieldToType` (used for all implicit string→DateTime
coercion in comparisons) calls `getDefaultSerialization`, bare string
literals in WHERE/BETWEEN/IN should now use session timezone for
columns without explicit timezone.

Add test `04061_session_timezone_where_between_in` covering:
- WHERE =, >=, < with bare strings and toDateTime (consistency check)
- BETWEEN with bare strings
- IN with bare string list
- DateTime64 variants
- Round-trip: INSERT string, SELECT back, verify same string
- Explicit-tz column negative test (column tz takes priority)
- Partition pruning with session_timezone

Also add a TODO note in `KeyCondition.cpp` about the conservative
bail-out for `toDateTime(string_col)` key expressions.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.2-must-backport v26.3-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Different stored/displayed DateTime for same INSERT between 26.2.3 and 26.2.4 with session_timezone

5 participants