Repository navigation
Conversation
…he time zone merges use An INSERT with `session_timezone` computed the sorting key, partition key, skip indexes, projections, TTL and the `optimize_on_insert` merge of a MergeTree table in the session time zone, while background merges compute them in the server time zone (they run with the storage context, which has no session). `DateLUT::instance` reads the zone from the query context in two places: when the INSERT re-analyses the key AST (an intermediate `DateTime` type such as `toDateTime(ts)` binds the zone), and when a function with a `Date` argument such as `toRelativeMinuteNum` runs. The same rows then got different key values in a part written by an INSERT and in the merge of that part: the part is unsorted, `WHERE` on the key, partition pruning and minmax indexes skip matching rows (also after merges), TTL infos are shifted, and debug builds abort in `CheckSortedTransform` with "Sort order of blocks violated". Two changes make an INSERT compute what a merge computes: 1. `getCombinedIndicesExpression` starts from the key expression of the table metadata, which merges execute (`MergeTask`), instead of re-analysing the key AST in the INSERT's context. A table created under a session time zone binds that zone into its metadata until a restart; reusing the metadata expression keeps such a table's INSERTs consistent with its merges. Skip indexes are analysed separately and composed with `ActionsDAG::merge`, which binds only the index inputs to the key outputs by name (`mergeNodes` would also bind the per-analysis `__lambda` / `__set` names of the two DAGs to each other). An index expression that equals a key column is served by the key column, as in the combined analysis before. When the metadata expression does not compute every key column (its outputs are named differently after a rebuild under `transform_null_in = 1`), the old re-analysis is kept. 2. A new `SessionTimezoneBlockerInThread` (a FiberLocal counter, like the other *BlockerInThread classes) makes `DateLUT::instance` skip the query's `session_timezone`, which gives the zone a merge thread sees. It is set only around INSERT-time computation of the table's own expressions: the sorting key and skip indexes, the skip indexes after the `optimize_on_insert` merge, that merge itself (GraphiteMergeTree rounds a `UInt32` time by day), the partition key, TTL, the projection sorting key and the projection query. Input parsing and DEFAULT/MATERIALIZED values are not affected. A projection query ran its pipeline on pool threads, which do not carry the blocker; it now runs with one thread, on the calling thread. That also applies to the projection rebuild of merges and `MATERIALIZE PROJECTION`, which compute one block per call as well. The new test has an arm per site, including an aggregate projection (each fails on master, measured with the server in America/New_York, Asia/Tokyo and UTC) and guard arms for the composition (lambda, literal IN set, index equal to the key), the fallback and a table created in a session. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review - rounds 1-3
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20261108-020600 |
|
cc @PedroTadim @CurtizJ, could you review this and add the |
|
Workflow [PR], commit [10bba26] Summary: ❌
AI ReviewSummaryThe PR reuses metadata key expressions and computes insert-time keys, skip indexes, TTLs, and projections in the background-operation time zone. The earlier serialization-cache finding is addressed, but direct Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block Handle the captured implicit time zone in scalar |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes24 object files changed (+18.09 KiB total), 1 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 units1666 translation units recompiled, 8630 s compile time in total, 1665 of them have a recent master baseline. |
… or left A `DateTime` without an explicit time zone resolves the zone of its serialization when the serialization is created (`DataTypeDateTime:: doGetSerialization` calls `DateLUT::instance`). The thread-local `DataTypesCache`, which `SerializationDynamic` uses for the text of each value, is keyed by the type name and was invalidated only when the query context or its `session_timezone` changed, so a serialization created on one side of the blocker was reused on the other side within one INSERT: - created while the INSERT computed the sorting key, it made the INSERT's own SELECT write `toString` of a `Dynamic` value in the server time zone instead of the session time zone (a wrong value in a stored column; master is correct here); - created by the SELECT first, it made the sorting key, the skip indexes and the projections over such a value use the session time zone, which this change set out to remove (wrong primary key pruning and projection group keys). The cache now also records whether it was filled under the blocker and is cleared when that changes. The test gets a block for each direction. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@groeneai just tag me La Casa Del Dolor failures only if the failures are related to the fuzzer, testing infrastructure or the CI itself. |
|
@groeneai there is another PR from you related to a timezone issue with now and current_time functions. Does that PR and this one share the same root cause? |
|
Noted, I'll cc you on La Casa Del Dolor failures only when the cause is in the fuzzer, the testing infrastructure or the CI itself. I couldn't find a PR of mine about a time zone issue in
If you meant another PR, could you link it? |
CI finish ledger - f399ce9Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261108-120006 |
|
Fixing PR for the ledger line |
…e ALTER's session `AlterCommands::apply` re-derived the sorting, primary and partition keys and the `minmax_count` projection in the context of the session that issued the `ALTER`, while `CREATE`, a reload of the table and the part writers derive them in the global context. A session setting that changes key analysis therefore installed in-memory keys that the table does not really have. With `transform_null_in = 1`, `in` is rewritten to `nullIn`, which renames the key column and, for a `Nullable` argument, changes its type from `Nullable(UInt8)` to `UInt8`. After such an `ALTER` (even a comment-only one): - an INSERT into a table with a Nullable key under `IN` serialized the writer's `ColumnNullable` with the stored `UInt8` serialization: `Bad cast from type DB::ColumnNullable to DB::ColumnVector<char8_t>` in debug builds, a primary index of garbage bytes in release builds; - every merge failed with `NOT_FOUND_COLUMN_IN_BLOCK: Not found column in(x, ...)`; - a partition key wrote `partition.dat` with the session type, so after a restart the parts were detached as `broken-on-start`. Derive these keys in the global context, as ClickHouse#119799 already does for skip indices in the same function, and carry `isAnalyzingBackgroundExpressions` into it so that AI functions stay rejected in keys (ClickHouse#127057). The sampling key, projections and column TTLs keep the session context: the sampling key is re-analysed in the query context at read time, and projections and TTLs are separate derivations. Found by the targeted AST fuzzer on PR ClickHouse#130066 (STID 1499-5685). Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
This PR does not cover one case of the same split: a CREATE TABLE t (id UInt32, d Dynamic) ENGINE = MergeTree ORDER BY toString(d) SETTINGS index_granularity = 1;
INSERT INTO t SELECT number, CAST(toDateTime(1704067200 + number * 3600) AS Dynamic) FROM numbers(8) SETTINGS session_timezone = 'Asia/Tokyo';
SELECT count() FROM t WHERE toString(d) = '2024-01-01 04:00:00'; -- 0
SELECT countIf(toString(d) = '2024-01-01 04:00:00') FROM t; -- 1After @CurtizJ, should I add it to this PR, or open it as a separate PR after this one is merged? |
…sions-server-timezone Conflict in src/Common/FiberLocal.h: master added the HTTP_CONNECTION_INFO and QUERY_CANCELLATION_BLOCKED slots next to this PR's SESSION_TIMEZONE_BLOCKER_COUNTER; all three are kept. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ble expressions Merges and mutations run in a context built from the background profile, so a function that reads the time zone when it runs (e.g. `toDate` of an `Int64`) is computed in that profile's `session_timezone`. Under `SessionTimezoneBlockerInThread` `DateLUT::instance` fell back to the global context instead, so with a background profile that sets `session_timezone` an INSERT still wrote parts sorted in another zone than merges recompute (measured: an INSERT under the same `session_timezone` as the background profile, which merged on master, aborted with `Sort order of blocks violated`). Without a background profile its settings are those of the system profile, which the global context also has, so nothing changes there. Tests: an integration case with a background profile that sets `session_timezone` (fails on master and without this change, passes with it); in 05570 the Graphite block also checks that the rollup happened, and the `transform_null_in` table, which merges since ClickHouse#130154, now gets two parts, a merge and a primary key read. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| if (metadata_snapshot->hasSortingKey() || metadata_snapshot->hasSecondaryIndices()) | ||
| { | ||
| /// The table's expressions are computed in the time zone of background merges, which recompute them. | ||
| SessionTimezoneBlockerInThread session_timezone_blocker; |
There was a problem hiding this comment.
[Blocker] Normalize the time zone captured by Dynamic variants
The blocker changes calls to DateLUT::instance, but a direct Dynamic argument takes its DateTime type from ColumnDynamic::variant_info. ExecutableFunctionDynamicAdaptor::executeImpl passes that already constructed type to the nested function, so toString(d) still uses the insert session's zone. Reading the part reconstructs the type by name in the server zone. Consequently, the key/index/projection describes different values from the stored rows.
Reproduced with this head's Fast test binary and a UTC process:
CREATE TABLE t (id UInt32, d Dynamic)
ENGINE = MergeTree ORDER BY toString(d)
SETTINGS index_granularity = 1;
SYSTEM STOP MERGES t;
INSERT INTO t
SELECT number, CAST(toDateTime(1704067200 + number * 3600) AS Dynamic)
FROM numbers(8) SETTINGS session_timezone = 'Asia/Tokyo';
SELECT count() FROM t
WHERE toString(d) = '2024-01-01 04:00:00'; -- 0
SELECT countIf(toString(d) = '2024-01-01 04:00:00') FROM t; -- 1A minmax skip index on toString(d) with ORDER BY id also returns 0 versus 1. An aggregate projection grouping by toString(d) returns 09:00–16:00, while the base scan with outermost SETTINGS optimize_use_projections = 0 returns 00:00–07:00. The existing Array(Dynamic) cache test passes because it exercises serialization rather than this direct function-adaptor path.
This is the remaining case identified in the discussion. Normalize implicit variant time zones under the table-expression context before computing these expressions, preserving explicitly specified zones, and add a scalar Dynamic regression that compares indexed/base results and projection/base group keys. If deliberately deferred, please link a dedicated tracking issue for this remaining correctness gap.
There was a problem hiding this comment.
Deliberately deferred: this is pre-existing on master (the same 0 vs 1 and 09:00-16:00 vs 00:00-07:00 with a master build), and its fix is a different change (rebuilding the Dynamic variant types by name before the INSERT computes the table's expressions), while this PR only changes what DateLUT::instance returns. It is tracked in #130066 (comment), where I asked whether to add it here or open it as a separate PR after this one.
Related: #129923
Related: #122631
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed an
INSERTwithsession_timezoneinto aMergeTreetable whose sorting key, partition key, skip index, projection or TTL depends on the implicit time zone (for exampleORDER BY toDate(toDateTime(ts))orORDER BY toRelativeMinuteNum(d)): it wrote an unsorted part, and queries filtering on the key returned too few rows, also after merges. These expressions are now computed onINSERTexactly as background merges compute them.Description
On 26.8 (and 26.10), an
INSERT ... SETTINGS session_timezone = 'Asia/Tokyo'on a server in another zone into a table withORDER BY (toDate(toDateTime(ts)), id)writes an unsorted part, andcount()with a filter on the key returns 3 instead of 12 rows, also afterOPTIMIZE FINAL. Partition keys (two partitions for one date), minmax indexes and TTL infos break too. Debug builds abort in a merge withSort order of blocks violated, CI job https://github.com/ClickHouse/ClickHouse/actions/runs/42370903826/job/128415273333 (La Casa Del Dolor, on an unrelated PR).Cause:
DateLUT::instancetakes the zone from the query context. The INSERT re-analysed and executed the table's expressions in the session zone, while merges use the context of the background profile and compute the sorting key with the metadata expression.Change:
getCombinedIndicesExpressionuses the metadata key expression (whatMergeTaskexecutes) and composes the skip indexes withActionsDAG::merge. It falls back to the old analysis when that expression does not compute every key column. Its other callers (projection key onINSERT, primary key of a mutation rewriting a part) get it too. It also removes theBad castof the INSERT with use_legacy_to_time = 1 writes legacy toTime values into a Time key: wrong results, LOGICAL_ERROR in debug builds #122631 repro (a sorting key); skip indexes still re-analyse.SessionTimezoneBlockerInThreadmakesDateLUT::instanceuse the zone of merges (the background profile'ssession_timezone, else the server zone) around the INSERT-time computation of the sorting key, skip indexes,optimize_on_insertmerge, partition key, TTL and projections (whose query runs on the calling thread);DataTypesCacheis cleared on entry and exit. Input parsing andDEFAULTvalues are unchanged.Unchanged (pre-existing,
KeyCondition): a query with its ownsession_timezoneprunes as if the key were computed in that zone.The new test fails on master (server in America/New_York, Asia/Tokyo, UTC) and under ablation of each part, and passes with the fix, as does a new
test_background_operations_configcase (background profile withsession_timezone).Workflow [PR]
Sync PR [sync-upstream/pr/130066]