Skip to content

Compute a MergeTree table's keys, skip indexes and TTL on INSERT in the time zone merges use - #130066

Open
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:insert-table-expressions-server-timezone
Open

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:insert-table-expressions-server-timezone

Conversation

@groeneai

@groeneai groeneai commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #129923
Related: #122631

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 an INSERT with session_timezone into a MergeTree table whose sorting key, partition key, skip index, projection or TTL depends on the implicit time zone (for example ORDER BY toDate(toDateTime(ts)) or ORDER 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 on INSERT exactly 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 with ORDER BY (toDate(toDateTime(ts)), id) writes an unsorted part, and count() with a filter on the key returns 3 instead of 12 rows, also after OPTIMIZE FINAL. Partition keys (two partitions for one date), minmax indexes and TTL infos break too. Debug builds abort in a merge with Sort 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::instance takes 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:

  • getCombinedIndicesExpression uses the metadata key expression (what MergeTask executes) and composes the skip indexes with ActionsDAG::merge. It falls back to the old analysis when that expression does not compute every key column. Its other callers (projection key on INSERT, primary key of a mutation rewriting a part) get it too. It also removes the Bad cast of 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.
  • A new SessionTimezoneBlockerInThread makes DateLUT::instance use the zone of merges (the background profile's session_timezone, else the server zone) around the INSERT-time computation of the sorting key, skip indexes, optimize_on_insert merge, partition key, TTL and projections (whose query runs on the calling thread); DataTypesCache is cleared on entry and exit. Input parsing and DEFAULT values are unchanged.

Unchanged (pre-existing, KeyCondition): a query with its own session_timezone prunes 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_config case (background profile with session_timezone).


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

…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]>
@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review - rounds 1-3
  • ❌ Projection data was still computed in the INSERT's session_timezone (merges and MATERIALIZE PROJECTION recompute it in the server zone): AGREE, fixed (blocker + the projection query runs on the calling thread).
  • ⚠️ Skip-index and projection-key test arms did not force the index/projection: AGREE, fixed; the projection sorting key arm now reads c0 = '1970-01-01' through the forced projection (master 0/1/0 with the server in New York/Tokyo/UTC, fix 2 in six zones).
  • 💡 Skip-index arms could race a background merge: not reachable with the current merge selector defaults; merges of those two tables are stopped anyway.
  • ⚠️ Restart rebuilds a key bound at CREATE under a session zone: DISAGREE, identical on master (the INSERT binds the same zone there); this is Inconsistent work with non-explicit timezone #93613.
  • ⚠️ TTL ... IN (SELECT ...) sets are built on pool threads without the blocker: DISAGREE, not reproducible as described and identical on master; noted.
  • Round 3: no findings.

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Server in America/New_York, two INSERT INTO t SELECT CAST(number AS Date) FROM numbers(349) SETTINGS session_timezone = 'Europe/Saratov' into ORDER BY toRelativeMinuteNum(c0), then OPTIMIZE TABLE t FINAL: master debug aborts every run with Sort order of blocks violated for column number 1, left: UInt64_501420, right: UInt64_300, the CI values.
b Root cause explained? DateLUT::instance takes the zone from the query context. The INSERT re-analysed the key AST (an intermediate DateTime type binds the session zone) and executed zone-reading functions in the session zone; background merges run with the storage context and compute the key with the metadata expression, in the server zone. Same rows, different key values, unsorted part.
c Fix matches root cause? Yes. The INSERT computes the key with the metadata expression that merges execute, and a SessionTimezoneBlockerInThread makes DateLUT::instance return the merge-thread zone around the INSERT-time computation of the table's expressions. No bound, tag or guard.
d Test intent preserved / new tests added? New test 05570_insert_table_expressions_session_timezone: one block per INSERT-time site (sorting key x2, projection key, aggregate projection data, skip index before/after the optimize_on_insert merge, partition key, TTL, Graphite rollup) plus guards for a table created in a session, lambdas, literal IN sets and a key rebuilt under transform_null_in.
e Both directions demonstrated? Yes. Master fails blocks 1-8 (wrong counts, three aborts) with the server in New York, Tokyo and UTC; the fix passes all blocks with the server in six zones (New York, Tokyo, UTC, Kolkata, Kiritimati, Pago Pago). Eight ablations (no metadata expression, no blocker, no fallback, mergeNodes instead of merge, no exclusion of index expressions equal to the key, no blocker around the projection query, a multi-threaded projection pipeline, no blocker around the projection part's sorting key) each fail the predicted blocks. 50/50 randomized runs pass with the server in New York and in Tokyo.
f Fix is general across code paths? Covers every INSERT-time computation of the table's expressions (sorting key and skip indexes, skip indexes after the optimize_on_insert merge, the merge itself, partition key, TTL, projection sorting key and projection query) and the mutation primary key through the same function. The projection query runs on the calling thread, also for the projection rebuild of merges and MATERIALIZE PROJECTION; measured on a release build, no slowdown (INSERT of 1M rows into a table with an aggregate projection, MATERIALIZE PROJECTION of 10M rows). Regression sweeps of ~3,500 key, index, partition, TTL, projection and session-zone tests: no failure that master does not have.
g Fix generalizes across inputs (params/datatypes/wrappers)? Date, UInt32 and DateTime sources; functions reading the zone at analysis and at execution; sorting, partition and projection keys, minmax index, TTL, GraphiteMergeTree; two session zones 17 hours apart against three server zones. Empty keys (ORDER BY tuple()) keep the old path.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no format change. Parts already written keep their data; new INSERTs compute the values merges compute.
i Invariants and contracts preserved? Invariant: an INSERT writes the part a merge of the same rows would write; it now holds for the sorting key (also for a table whose metadata was built in a session zone), skip indexes, partition key, TTL and the rollup. The blocker is RAII, per thread and fiber, and spans only synchronous computation on the INSERT thread; the projection query pipeline now runs on that thread.

Session id: cron:clickhouse-impl-slot-7:20261108-020600

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @PedroTadim @CurtizJ, could you review this and add the can be tested label so CI runs? An INSERT with session_timezone computed the sorting key, partition key, skip indexes, projections and TTL in the session zone while merges recompute them in the server zone, which wrote unsorted parts (the La Casa Del Dolor Sort order of blocks violated abort) and returned too few rows for key filters on 26.8; the INSERT now uses the metadata key expression and ignores the session zone for these computations.

@clickhouse-gh

clickhouse-gh Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [10bba26]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The 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 Dynamic values still retain the insert session's implicit time zone, producing incorrect indexed results and projection groups. One blocker remains at head 10bba26ee4d78d5414d26fb493a39b01355340c6.

Findings

❌ Blockers

  • src/Storages/MergeTree/MergeTreeDataWriter.cpp:896: The time zone guard does not normalize types already embedded in ColumnDynamic. ExecutableFunctionDynamicAdaptor::executeImpl obtains the nested DateTime type directly from the column, bypassing the guarded lookup. On the PR-head Fast test binary in UTC, inserting eight hourly timestamps as scalar Dynamic with session_timezone = 'Asia/Tokyo' into ORDER BY toString(d) makes a key-filtered count return 0, while a full scan returns 1. A minmax skip index has the same discrepancy. An aggregate projection groups these rows under 09:00–16:00, while a base scan groups them under 00:00–07:00. This is the acknowledged remaining case, distinct from the resolved serialization-cache thread. Normalize implicit variant time zones before table-expression evaluation, preserving explicit zones; alternatively, explicitly track the deferred correctness gap in a linked issue.
Tests
  • ⚠️ Add scalar Dynamic regression coverage comparing primary/skip-index counts with a full scan and forced-projection group keys with a base scan. The added Array(Dynamic) serialization-cache arm passes but does not cover the direct function-adaptor path. The discrepancies above were reproduced locally with the exact PR-head Fast test binary; scripts and logs are in tmp/review_130066/ and build_review_130066/.
Final Verdict

Status: ❌ Block

Handle the captured implicit time zone in scalar Dynamic variants and cover the affected key/index/projection paths, or link a dedicated issue explicitly tracking the deferred correctness gap.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. can be tested Allows running workflows for external contributors labels Nov 8, 2026
Comment thread src/Common/DateLUT.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 10bba26ee with master 6f06fe03d (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.

Object file sizes

24 object files changed (+18.09 KiB total), 1 added.

Object file Master PR Δ

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

1666 translation units recompiled, 8630 s compile time in total, 1665 of them have a recent master baseline.

Job report

… 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]>
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai just tag me La Casa Del Dolor failures only if the failures are related to the fuzzer, testing infrastructure or the CI itself.

@PedroTadim

Copy link
Copy Markdown
Member

@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?

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

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 now() / current_time. The candidates I found:

If you meant another PR, could you link it?

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f399ce9

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: Bad cast from type A to B (STID: 1499-5685) trunk bug, not from this PR: it reproduces on master. A nullable IN sorting key whose metadata is rebuilt by an ALTER under transform_null_in = 1 makes every later INSERT abort in primary-index serialization. The targeted fuzzer reached it from this PR's new test a fix task is created (investigating at full effort, fixing-PR link to follow here)
PR praktika rollup of the row above a fix task is created (the owner above)

Session id: cron:our-pr-ci-monitor:20261108-120006

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the ledger line AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: Bad cast from type A to B (STID: 1499-5685) (a master bug, not from this PR): #130154.

opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 9, 2026
…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]>
@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

This PR does not cover one case of the same split: a Dynamic value. The column carries the variant types the INSERT built in its session_timezone, and toString(d) takes the zone from that type rather than from DateLUT::instance, so SessionTimezoneBlockerInThread does not reach it. A part stores only the type names, and a merge rebuilds them in the server zone. With a UTC server, on master and on this PR's head:

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;        -- 1

After OPTIMIZE TABLE t FINAL the first query returns 1. The fix rebuilds the Dynamic variant types by name under SessionTimezoneBlockerInThread before the INSERT computes the table's expressions, as a merge reading the part does (a small change in MergeTreeDataWriter).

@CurtizJ, should I add it to this PR, or open it as a separate PR after this one is merged?

groeneai and others added 2 commits November 23, 2026 13:50
…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;

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.

[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; -- 1

A 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants