Skip to content

Rewrite mutation DateTime literals for folded IN lists, qualified columns and nullIn - #122136

Open
groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/121991-mutation-in-literal-session-timezone
Open

groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/121991-mutation-in-literal-session-timezone

Conversation

@groeneai

@groeneai groeneai commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #121991

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 ALTER TABLE ... DELETE, ALTER TABLE ... UPDATE and lightweight DELETE affecting the wrong rows when session_timezone is set and the predicate compares a DateTime column against a literal list (time IN ('...'), time IN ['...']), against a qualified name (tbl.time = '...'), or uses nullIn. Such a literal was parsed in the server timezone, so the mutation did not match the rows the identical SELECT matched.

Description

On 26.8.10.6, with session_timezone = 'America/Denver' and the server in UTC, ALTER TABLE t DELETE WHERE time IN ('2000-01-01 01:00:00') deletes the row the identical SELECT does not match, and keeps the one it does.

The rewrite that freezes the session timezone into the stored command had three holes:

  • the parser folds a plain literal list into one literal (String/Tuple/Array for IN ('a'), IN ('a','b'), IN ['a']), and the rewrite handled only the explicit tuple(...) spelling;
  • identifiers were looked up under their full dotted name, so tbl.time never resolved;
  • the operator set listed 4 of the 8 IN operators, missing nullIn.

Why these: a folded literal and an explicit tuple(...) are the two spellings a literal list takes; a deferred set (subquery, table, table function) must not be rewritten. Three shapes, unchanged from master, stay out of scope: a function-wrapped column (toStartOfDay(time) = '...'); a constant-expression right-hand side (IN array('...')), where wrapping one element would make array() seek a common element type; and a lambda parameter shadowing the column over a String array, in the bare = and IN tuple('...') spellings. The middle shape and that bare = error NO_COMMON_TYPE rather than deleting silently; the IN tuple('...') spelling completes and deletes nothing.

Each unaliased string becomes the value the identical SELECT's IN set gives it in the session timezone: an epoch for DateTime, decimal seconds read as Decimal(38, S) for DateTime64. CAST would reread a stored string leniently ('2000-01-01T01:00:00Z', which the set rejects, so the ALTER fails like the SELECT) or differently ('20000101': an epoch to the set, a date to CAST). Pruning admits a literal cast to Decimal, not a CAST/toDateTime of a string (a yearless one reads the date). N = 40,000, release build: DateTime 0.93x master's time, DateTime64 1.26x (1.0x at N = 1,000).

Surface matrix: status and evidence
surface status measured by
IN ('lit') / IN ('l1','l2') / IN ['lit'] (folded) fixed 04056 in one, in many, in array
NOT IN, nullIn, GLOBAL [NOT] IN, notNullIn fixed 04056 not in, null in, in operators
IN ('lit', 946688400), IN ('lit', NULL), IN ['lit', NULL] fixed 04056 in mixed, tokyo mixed, in null
numeric string IN ('20000101') set's epoch kept 04056 in numeric*
a string the IN set rejects rejected, as by SELECT 04056 strict
explicit IN tuple('lit') worked; set's reading now kept 05217, 04056 in numeric tuple
tbl.time = 'lit', tbl.time IN ('lit'), db.tbl.time = 'lit' fixed 04056 *qualified*
DateTime64(3), also before 1970 and mixed fixed 04056 in dt64*
ALTER ... UPDATE, lightweight DELETE fixed 04056 in update, lightweight
MergeTree and ReplicatedMergeTree fixed 04056 / 04035 test 11
second session timezone (Asia/Tokyo) fixed 04056 tokyo
IN []; a DateTime('UTC') column exempt 04056 in empty, in explicit
subcolumn x.time / tbl.x.time typed DateTime('UTC') exempt, as the analyzer resolves 04056 sub*
a lambda or alias named like the column or a qualified name's first part; an aliased string as on master 04056 lambda *, in alias*
qualified UPDATE tbl.time = 'lit'; has([...], time) Code: 62; NO_COMMON_TYPE, not silent measured
toStartOfDay(time) = 'lit'; IN array('lit'); bare = vs. a shadowing parameter out of scope above
a mutation after a type change in one ALTER sees the old type, as master's = (#127982) measured

Pruning: rewritten predicates prune (04035 tests 11, 14, 15); a subquery, a zone-less
CAST(..., 'Array(DateTime)') and yearless CAST/toDateTime defer (12, 13, 13b).


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

groeneai and others added 2 commits September 25, 2026 01:24
…umns and nullIn

ALTER TABLE ... DELETE/UPDATE and lightweight DELETE affected different rows
than the identical SELECT matched when session_timezone was set: the mutation
kept a bare string literal, so the background mutation thread, which has no
session context, parsed it in the server timezone. Silent wrong-row deletion,
reproduced on released 26.8.10.6, 26.6.8.7 and 26.5.7.64.

rewriteDateTimeLiteralsWithTimezone missed the predicate in three ways:

- The parser folds a plain literal list into ONE ASTLiteral (String for
  IN ('a'), Tuple for IN ('a','b'), Array for IN ['a']), while tryWrapInLiterals
  accepted only an explicit tuple() function or an ASTExpressionList. The latter
  is never an IN right-hand side at all, so the only shape ever caught was the
  explicit tuple() spelling, which is why a test written against it passed while
  the user-facing spelling was broken.
- getDateTimeColumnType was called with the full dotted identifier name and
  looked it up by exact name, so t.time never resolved. Resolution now follows
  the analyzer: whole name first, then this table's own name as a qualifier,
  then its database and table, with the first reading that names a column or a
  subcolumn deciding. It is subcolumn-aware on purpose: a dotted name that
  resolves must keep its OWN type, or a Tuple(time DateTime('UTC')) element
  would silently take the session timezone from a same-named top-level column.
- The local IN-operator name set listed 4 of the 8 real operators, so
  nullIn(time, ...) was never dispatched. Replaced with the tree's own
  functionIsInOrGlobalInOperator, which deletes the duplicated list rather than
  extending it, and deliberately excludes the *IgnoreSet variants (they return
  zero without reading the set, so rewriting their operand cannot fix a row).

A homogeneous folded list is rewritten as a single
CAST([...], 'Array(DateTime(tz))') rather than per element, which keeps the
stored command O(1) in the element count (+45 bytes at any N) and O(1) in query
tree nodes (the same max_expanded_ast_elements floor of 13 at N = 100, 3000 and
40000). Measured end to end on 1M rows with mutations_sync = 2, it also runs
below master's own wall time (0.68x to 0.92x for N up to 40000), because the set
is built once from typed DateTime values instead of reparsing N strings. Two
alternatives were measured and rejected: arrayMap over the literal array is not
folded to a constant set and cost 236x master at N = 20000, and a per-element
tuple() expansion is linear in query tree nodes, which trips
max_expanded_ast_elements for a large list. A mixed collection has no common
element type, so it keeps the per-element expansion; that is the only remaining
linear path, and it crosses the default limit near 142k elements with a loud
Code: 36 rather than silently.

The rewritten right-hand side would otherwise have lost mutation partition
pruning, including for mutations that are correct and prunable today (a
deployment whose session timezone equals its server timezone, or a
timezone-independent literal such as '946688400'). is_literal_enumeration
therefore accepts a CAST of recursively literal arguments, restricted to a
target type that resolves to Array(DateTime) or Array(DateTime64) with an
explicit timezone. A zone-less Array(DateTime) is still refused, because
DataTypeDateTime would resolve it against the executing server's timezone while
pruning is computed on the initiator, which is exactly the divergence this guard
exists to prevent. Gating the rewrite itself on session_timezone differing from
the server timezone would be unsound: the mutation may replay on a replica whose
server timezone differs, which is the whole premise of the feature.

A lambda binds its parameters as plain ASTIdentifier nodes, so inside its body a
name like `time` is the array element and not the column of that name. The
visitor therefore stops at a lambda and walks its body itself with the names it
binds recorded. When an identifier's first name part is one of those names, the
lookup is RESTRICTED to the plain column reading the rewrite already had, never
the qualifier or subcolumn readings this change adds, and the new folded-literal
branch declines such a name outright. Every shape therefore resolves exactly as
master does outside that branch, which is provable by inspection.

The restriction is owed in both directions. Vetoing the lookup outright, as an
earlier revision of this branch did, also suppressed the pre-existing explicit
tuple() branch, which has been in released builds since ac2d50f: the stored
command kept a bare literal, and over an Array(DateTime) a UTC server then deleted
the row the identical SELECT does not match, where master deleted the right one.
Conversely, letting the comparison arm pass no bound names at all let the new
subcolumn reading resolve a dotted name rooted at a parameter, so x.time in
arrayExists(x -> x.time = '...', arr) over an Array(Tuple(time String)) found the
storage subcolumn x.time, wrapped the literal in the session timezone, and broke
the mutation with NO_COMMON_TYPE where master left it alone.

The comparison arm keeps master's resolution for a bare bound name on purpose. A
bound parameter can itself be an unzoned DateTime, as in
arrayExists(time -> time = '...', arr) over an Array(DateTime), and then the
literal does need the wrap: withholding it stores a bare string whose meaning is
the executing server's timezone. That element type is not knowable at this level,
because a parameter's type comes positionally from the enclosing higher-order
function's array argument, so inferring it would mean enumerating which arguments
of every such function are arrays. Declining inside the new folded-literal branch
is the conservative choice for the same reason. Two shapes stay wrong either way
over an Array(String) element, both unchanged from master: compared with =, the
mutation fails with NO_COMMON_TYPE, and with IN tuple('...') it completes and
deletes nothing. Out of scope here.

The guard tests the FIRST name part, because
arrayExists(x -> x.y = '...', arr) binds x and a dotted name rooted at a bound
parameter is bound too; the scope is popped with resize rather than a fixed pop
count so that nesting and a parameter-less lambda are both correct. This is the
pattern MergeTreeData.cpp already uses for the same hazard in the pruning
analysis, deliberately so. The ASTAssignment overload needs no guard: an
assignment target is never inside a lambda body, since ParserAssignment takes a
non-compound ParserIdentifier.

04056_mutation_session_timezone_datetime_literals covers the affected shapes;
its fixtures each hold the two absolute instants the literal can denote, so
every assertion holds whatever timezone the server runs in, and the oracle is
that the mutation affects exactly the rows the identical SELECT matches.
04035_mutation_partition_pruning gains the pruning cases: a rewritten predicate
prunes to one partition, while a subquery right-hand side and a zone-less cast
still do not, and the same cast with an explicit timezone does. The lambda cases
assert that the row set matches the identical SELECT, that a shadowed literal
list leaves no timezone in the stored command, and that an unzoned DateTime
element still gets one. Two controls keep the guard honest: a real column named
in the same body IS still rewritten, so the guard cannot be satisfied by skipping
lambda bodies outright, and a scope-pop case over IN on both sides, which
regresses if the bound names leak past the lambda. Two further cases pin the
restriction itself: the explicit tuple() spelling over an Array(DateTime), which
must still be converted, and a dotted name rooted at a parameter over an
Array(Tuple(time String)), which must not be. The subcolumn case now uses a Tuple
column named after the table, so it is the qualifier-stripping fallback that would
reach the zone-less top-level column; with the subcolumn reading removed that case
deletes nothing and stores the session timezone, which the previous fixture could
not detect.

Closes: ClickHouse#121991

Co-Authored-By: Claude Opus 5 <[email protected]>
Delete new-code design narration; keep the AST, analyzer and type-system properties as standalone invariants.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (4 passes, on 2f241a98952ec)

Pre-publication review by an independent model, plus my own cold read of the resulting code on each
pass, then per-finding adjudication against the recorded measurements. 23 findings over four passes:
18 agreed and fixed, 4 disagreed with recorded evidence, 1 dropped. Disagreements are terminal per
finding and carry a code citation or a measurement, never prose.

❌ Blockers (all agreed and fixed)

  • Lambda-bound identifiers were resolved against table metadata. On a table with time DateTime
    and arr Array(String), ALTER TABLE t DELETE WHERE arrayExists(time -> time IN ('2000-01-01 01:00:00'), arr)
    resolved the parameter to the storage column, fired the new folded-IN rewrite, and compared a
    String against a DateTime set. That predicate is correct on master, so widening the rewrite would
    have regressed it into deleting the wrong rows.
  • The first two versions of that guard were themselves wrong, in opposite directions, and the rule
    that ships is the third: a bound name keeps exactly the plain column reading the rewrite already had,
    and only the new folded-literal branch declines it. A blanket veto was worse than the defect twice
    over: tryWrapInLiterals resolves the type once and returns early, so it also suppressed the explicit
    tuple(...) branch shipped since 2026-03-25; and where the array elements are themselves unzoned
    DateTime, the declined rewrite was the one that made the mutation agree with the identical SELECT.
    As it ships, no shape resolves differently from master outside the branch this change adds. Six
    assertions pin it, one reddening against each of the two rejected guards.
  • The subcolumn controls were dead. sub and sub qual were cited as the evidence for the
    subcolumn-aware lookup and both passed byte-identically with it reverted. The discriminating case is
    the fall-through this change's own qualifier stripping creates when a Tuple column's name equals the
    table's, and that is the control now. Every refusal assertion owes a positive control.

⚠️ Majors

  • One published claim was factually wrong (agreed, corrected). An earlier note said the folded-IN
    arm "exists in no released build". tryWrapInLiterals was added on 2026-03-25, before the 26.8 cut,
    so it ships in 26.8.10.6; only the folded branch is new. Corrected rather than softened.
  • The shape analysis was overstated (agreed, corrected). An IN right-hand side can also be any
    constant expression (IN array('...'), and IN ['...', concat(...)] lowers to array(...)); both keep
    the defect and the description now says so. Disclosed rather than fixed for a reason worth stating:
    wrapping one element of array(...) would make it seek a common element type and raise
    NO_COMMON_TYPE where today it returns wrong rows. A tuple needs no common element type, which is why
    the pre-existing arm is safe and that one is not.
  • The heterogeneous IN arm had no regression test (agreed, fixed). A list mixing a string with a
    non-string keeps a per-element expansion instead of the single cast, measured correct but unreached by
    the suite. Covered now under two session timezones.
  • Reviewable evidence for the +45 bytes and 0.68-0.92x figures (disagreed, with the measurement).
    These are four measurements rather than an extrapolation, and the functional tests deliberately do not
    assert them: a wall-time number does not belong in a stateless test.
N master wall this PR ratio stored command bytes
100 0.172 s 0.159 s 0.92x 2323 to 2368 (+45)
1,000 0.187 s 0.172 s 0.92x 23023 to 23068 (+45)
20,000 0.509 s 0.364 s 0.72x 460023 to 460068 (+45)
40,000 0.847 s 0.580 s 0.68x 920023 to 920068 (+45)

1M-row MergeTree, mutations_sync = 2, predicate passed via --queries-file (at N = 20k the 460 KB
predicate exceeds the argv limit), two binaries with distinct Build-IDs. At N = 100 the two builds differ
by an id-sum of 2,520,000 = 100 rows x 25,200 s, exactly January's 7-hour Denver offset, so they delete
different rows rather than merely differing in speed. Node count is measured by binary-searching
max_expanded_ast_elements: the floor is 13 at N = 100, 3,000 and 40,000 for a homogeneous list, versus
about 3.50 nodes per element for the heterogeneous arm.

  • A qualified name resolves subcolumn-first, which stops matching the analyzer under
    analyzer_compatibility_prefer_alias_over_subcolumn = 1 (disagreed, with the mechanism).
    The
    divergence is real but it is not this rewrite's, and honouring the setting here would not repair it: a
    mutation is re-analyzed in a context built from the background context and never from the submitting
    query (MutatePlainMergeTreeTask::createTaskContext, then Context::makeQueryContextForMutate, whose
    own comment states as much), so the background binds the subcolumn whatever the literal carries, and a
    literal wrapped for the top-level column would be compared against a DateTime('UTC') subcolumn. The
    same divergence appears with no DateTime and no literal anywhere, for instance
    ALTER TABLE t DELETE WHERE t.x = 5 over t Tuple(x UInt32) beside a top-level x UInt32, which this
    rewrite never touches. It is unchanged from master, and closing it needs the resolved identifier
    serialized into the stored command, or the resolution-affecting settings carried with the mutation. I
    am tracking that separately rather than widening this change.

💡 Nits (not blocking)

  • A heterogeneous literal list loses the partition pruning master had for the folded form, since the
    per-element expansion is not a form the pruning classifier accepts. Correctness is unaffected, because
    all-partitions is the conservative direction, and a homogeneous list keeps pruning through the new
    timezone-pinned CAST.
  • Inside a lambda body the folded and tuple(...) spellings of the same predicate diverge over an
    Array(DateTime) column. Narrow, and not a regression, since master rewrote neither. No sound fix
    exists at this level: the parameter's own type is not knowable here without inferring it positionally
    from each higher-order function's array argument, and reusing the column type as a proxy is what makes
    the comparison arm unsound for String elements.
  • The DateTime64 arm of the pruning type check, and a folded IN over a Nullable or LowCardinality
    column, are reached by construction but not asserted. Both share their logic with asserted paths.

Checked and deliberately not raised

The changelog category was re-tested against all three conditions and stands as Bug Fix: released
26.8.10.6, 26.6.8.7 and 26.5.7.64 all delete the row the identical SELECT does not match.
session_timezone is a validated timezone setting, so building the target type cannot introduce a new
throw at ALTER time. The new spelling round-trips through the formatter and the parser, and the
replicated cases exercise that round trip rather than arguing it. The pruning guard's type check cannot
throw on hostile text, because DataTypeFactory::tryGet returns nullptr on a parse error.
InterpreterUpdateQuery and the two other DELETE branches need no rewrite: they interpret their
commands in the foreground with the submitting context, so the session timezone already applies. No test
in the suite changes behaviour under this diff: the only mutation predicate carrying an IN literal list
against a date-ish column has a Date column, which this rewrite does not touch.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (a-i)
# Check Answer
a Deterministic repro? Yes. One ALTER TABLE t DELETE WHERE time IN ('2000-01-01 01:00:00') with session_timezone='America/Denver' on a UTC server, over a two-row fixture holding both instants the literal can denote. 100% reproducible, and on released 26.8.10.6, 26.6.8.7 and 26.5.7.64, not only on master.
b Root cause explained? Yes. Mutations freeze the session timezone into the stored command by rewriting bare DateTime string literals; three holes let literals reach the background thread unrewritten. The parser folds a plain literal list into one ASTLiteral while only an explicit tuple(...) was accepted; identifiers were resolved under their full dotted name, so tbl.time never matched; the operator set listed 4 of the 8 IN operators, missing nullIn. A fourth hole, found in review, belongs to the new folded arm alone: a lambda binds its parameters as plain ASTIdentifier nodes.
c Fix matches root cause? Yes. The literals are made explicit at the rewrite site that already intends to do so: no widened bound, no no-random-* tag, no size reduction, no guard at the symptom. The one change outside the visitor restores a partition-pruning property the repair would otherwise have cost, gated on the target type pinning its own timezone. A lambda-bound name keeps the plain column reading it already had, and the outright decline is confined to the folded-literal branch this PR adds.
d Test intent preserved / new tests added? Yes. 04056_mutation_session_timezone_datetime_literals goes 55 -> 71 reference lines; one assertion pair is removed (lambda shadow eq, which asserted a pre-existing NO_COMMON_TYPE as though this PR fixed it) and three added, with all 68 surviving pre-existing lines byte-identical (cmp rc=0 with the changed labels filtered out). 04035_mutation_partition_pruning gains 3 pruning cases plus 1 positive control, its 62 pre-existing reference lines byte-identical.
e Demonstrated in BOTH directions? Yes. Three released builds delete the row SELECT does not match; the fix deletes the one it does. Five binaries built in one tree isolate each edit: master reds 11 assertions in 04056, no folded-list arm reds 9, no qualifier fix reds exactly the 2 qualified cases, nullIn goes red to green on the operator-set edit alone, and no pruning arm reds exactly the 2 pruning lines in 04035. Six more cover the lambda arm, including a permanent assertion that reddens on the round-1 wider guard alone. Only the shipped binary is [ OK ] on the whole file.
f Fix is general across CODE paths? Yes. One rewrite serves ALTER ... DELETE, ALTER ... UPDATE and lightweight DELETE, all three measured; the hand-written operator set is replaced by functionIsInOrGlobalInOperator, the tree's own 8-operator predicate, deliberately excluding the *IgnoreSet variants. Qualifier resolution follows the analyzer, including the x.x.time-on-table-x.x fallthrough. The two wrapping paths are deliberately asymmetric and that asymmetry is the fix; the ASTAssignment overload needs no guard, because ParserAssignment takes a non-compound ParserIdentifier.
g Fix generalizes across INPUTS? Yes. All three folded shapes, IN/NOT IN/nullIn, DateTime and DateTime64(3), qualified and unqualified, N from 1 to 40,000, homogeneous and heterogeneous lists, the empty list, numeric-string literals, Nullable/LowCardinality, and a second session timezone so at least one case discriminates for every possible server timezone. For the lambda guard: a bare parameter and a tuple parameter list, a bound name versus a real column in the same body, a dotted name rooted at a parameter, and nested or parameter-less lambdas (the scope is popped by resize, not a fixed count).
h Backward compatible? Yes. No setting is added or defaulted differently, so no SettingsChangesHistory.cpp entry is owed. The stored mutation entry format is unchanged: the rewrite emits plain SQL an older server parses identically, and MutationCommands::writeText round-trips every shape idempotently, which is why persisting the timezone on the entry was rejected. Correcting an earlier answer of mine: the IN arm itself is not new (ac2d50fee194b, 2026-03-25, an ancestor of both 26.7 and 26.8), so only the folded-literal branch is, and the released tuple(...) arm keeps its resolution rather than being withheld.
i Invariants and contracts preserved? Yes. The scalar and heterogeneous-element wrapper is unchanged, the unreachable ASTExpressionList arm is left in place rather than cleaned up in a bug-fix PR, and only top-level String elements are rewritten. The pruning change narrows rather than widens the guard: arity pinned at 2, the payload checked through the existing literal recursion so it can never be a subquery, table or table function, the type argument a String literal, and the type must resolve non-throwingly to Array(DateTime[64]) with an explicit timezone. The lambda parameter stack is push/visit/pop via resize(enclosing), balanced on every path including the early return for a malformed lambda.

Also: 50 randomized runs of the three affected tests (105 in total) gave 87 [ OK ] and 18 failures,
every one a zoneinfo/UTC timezone-name artifact of the machine used, whose /etc/localtime points at
a top-level zone file, so the runner's get_localzone() heuristic (tests/clickhouse-test:1726) yields
a name absent from system.time_zones. It reproduces on a bare SELECT 1 with that setting and hit the
untouched sibling test 05217 exactly as often as 04056 (9 and 9). Local style checks pass 16/17; the
one failure is settings_changes_history, which cannot determine changed files outside CI and is not
owed an entry here. clang-tidy-22 on the changed translation unit returns rc=0.

@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c52c599]

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

Reviewed #122136 at c52c599b3ab5c72f61afe777d454d03fd9957ae4. The change freezes session-dependent DateTime literals in folded IN lists, handles qualified columns and additional IN operators, and preserves partition pruning for the rewritten values. The new numeric and decimal representations were traced through MutationCommand::parse, MutationCommands::writeText/readText, MutationsInterpreter, set construction, and partition pruning; these consumers evaluate existing SQL forms. The latest alias-binding examples are fixed, and their bot-authored thread was resolved. No new inline findings were added; the dismissed wrong-row case below remains.

Findings

❌ Blockers

  • src/Interpreters/MutationsDateTimeLiteralVisitor.cpp:307 [dismissed by author -- https://github.com/Rewrite mutation DateTime literals for folded IN lists, qualified columns and nullIn #122136#discussion_r4667190691] An aliased string still bypasses convertAsSetMember and takes wrapWithTimezone. With session_timezone = 'UTC', time IN tuple('20000101' AS lit) AND length(lit) = 8 selects epoch 20000101, while the stored toDateTime expression matches epoch 946684800 under the default parsing mode, so a mutation can delete a different row. The author confirms this behavior also exists on master and deliberately leaves it unchanged; the selected-versus-mutated-row invariant remains violated. Preserve the original alias value and the strict set-conversion result together, or link a separate issue explicitly tracking this retained case. No further thread reply was posted after the dismissal.
Missing context / blind spots
  • ⚠️ The head's Fast test report passes 04056_mutation_session_timezone_datetime_literals and 05217_mutation_datetime_reversed_and_in_clause, but skips 04035_mutation_partition_pruning. A completed stateless CI run executing 04035 would close the remaining verification gap for the replicated pruning cases. No local tests were run, as required for this CI job.
Final Verdict

Status: ❌ Block

Fix the retained aliased numeric-string mismatch with a focused selected-versus-mutated-row regression, or link a dedicated tracking issue for the explicitly deferred behavior.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). labels Sep 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7daabdc23 with master 4ce893869 (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

6 object files changed (+92.65 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/MutationsDateTimeLiteralVisitor.cpp.o 83.09 KiB 172.87 KiB +89.78 KiB (+108.06%)

719 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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 84a154b

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
Stress test (amd_asan_ubsan) / UndefinedBehaviorSanitizer STID 2060-5018 sanitizer report: null FutureSet deref in serializeConstant (ActionsDAG.cpp:4744) reached from calculateHashTableCacheKeys; on master and 6 code-disjoint PRs since 2026-09-24 16:05Z #122140 (external, merged 02:54:20Z), ABSENT from the tested tree 2f1c20299bce so rule 3c: merged master @ 711ba8fd
Upgrade check (amd_release) / mutation_across_upgrade_error.txt the pre-upgrade release persists the quantile parameter untyped as quantile('0.5'), so 26.10.1 refuses to attach t_pfl_05079 at startup (Code 70, CANNOT_CONVERT_TYPE); 53 code-disjoint PRs in 14 days, 0 master rows #119810 (mine, merged) is PRESENT in the tested tree, so rule 3d: it fixes the write side only, and the writer here is the 26.9 server, so the requested 26.9 backport on #119810 is what closes this
Upgrade check (amd_release) / upgrade_error_messages.txt the same startup failure as the row above, reported from the server log #119810 (mine, merged), same rule 3d reading: write side only, closed by the 26.9 backport requested on it
CH Inc sync - CH Inc sync (private, not actionable by me)

Mergeable Check and PR are aggregators of the rows above, not separate failures.

Neither failure comes from this diff, which touches only mutation DateTime literal rewriting.
I merged master to pick up #122140, so CI is re-running on 711ba8fd. The Upgrade check rows
cannot go green on my side while the 26.9 line still writes the untyped parameter.

Session id: cron:our-pr-ci-monitor:20260925-070026

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 711ba8f

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
Upgrade check (amd_release) / Part all_3_3_1 intersects next part all_3_10_1 in PartLoadingTree::add (STID 3562-39cd) logical error at startup, so the server never comes up; the intersecting parts are written by the PREVIOUS-release binary the check installs for its stress phase, before the upgrade runs at all, by a TRUNCATE TABLE that fails to commit and leaves parts on disk; 9 code-disjoint PRs in 30 days #121708 (mine, open)
Upgrade check (amd_release) / Cannot start clickhouse-server the startup consequence of the row above, not a second defect #121708 (mine, open)
Upgrade check (amd_release) / Check failed the job-level roll-up of the two rows above #121708 (mine, open)
Performance Comparison (arm_release, master_head, 4/6) / timeseries_to_grid_aggregation_functions #3/#4/#9 slower, set_index #1 unstable arm fixture noise: this shard was GREEN on my previous head 84a154bfd47a and red on 711ba8fd2a13, whose only difference is a master merge; the four queries carry master-side slower/unstable rows in 30 days, and this shard reds 119 distinct PRs in 7 days a fix task is created (investigating at full effort - fixing PR link to follow on this PR)
Sync - CH Inc sync (private, not actionable by me)

Mergeable Check and PR are aggregators of the rows above, not separate failures.

Neither failure comes from this diff, which touches only mutation DateTime literal rewriting and
cannot reach part loading or timeseries grid aggregation. The quantile('0.5') Upgrade check rows
that the previous ledger reported are gone at this head; the part-intersection failure is a
different, pre-existing shape.

Session id: cron:our-pr-ci-monitor:20260925-123326

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Performance Comparison (arm_release, master_head, 4/6) row of the ledger above: #122319 (mine, open). It pins the part layout of the timeseries_to_grid_aggregation_functions fixture, whose slower rows turned this shard red; the set_index #1 unstable row on its own does not fail the shard.

…ation-in-literal-session-timezone

# Conflicts:
#	src/Storages/MergeTree/MergeTreeData.cpp
@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 12449ce

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
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05055_string_filters_move_to_prewhere flaky, not from this PR (it changes mutation DateTime literal rewriting, not string filters or parallel replicas): the StringValueFilter ProfileEvents check reads only the initiator's query_log row, so it prints 0 0 instead of 1 1 when a remote replica does the read. 1/142 reruns fail; 8 PRs hit it in this lane since 2026-10-09 03:09Z #124911 (mine, open)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05316_secret_arguments_declared_by_engines test regression from merged #123364, not from this PR: under DatabaseReplicated the CREATE DICTIONARY row is counted twice in system.query_log. 111 PRs hit it in this lane since 2026-10-09 09:47Z #124928 (external, merged 17:58Z, after this run was built; the next master merge picks it up, the row above still needs #124911)
Mergeable Check, PR praktika rollups of the two rows above #124911 (mine, open) and #124928 (external, merged)
CH Inc sync - CH Inc sync (private, not actionable by me)

The PR's own tests (04035, 04056, 05217) passed in every lane that ran them, in all five flaky checks and in both Bugfix validation jobs.

Session id: cron:our-pr-ci-monitor:20261009-180009

@Ergus

Ergus commented Nov 6, 2026

Copy link
Copy Markdown
Member

@groeneai merge master and check if failing tests are related with the changes

@Ergus Ergus left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

  • ⚠️ The database-qualified offset (db.tbl.time, MutationsDateTimeLiteralVisitor.cpp:66) has no test. Smallest case: ALTER TABLE mut_tz_qual DELETE WHERE {CLICKHOUSE_DATABASE:Identifier}.mut_tz_qual.time = '2000-01-01 01:00:00'.
  • ⚠️ The per-element array(...) branch (a mixed Array literal, e.g. IN ['2000-01-01 01:00:00', NULL] on a Nullable(DateTime) column) has no test. Only the mixed Tuple branch is covered (in mixed, tokyo mixed).
  • ⚠️ Folded IN ('…', NULL) with a Nullable column has no test.
  • ⚠️ No globalIn/globalNotIn/notNullIn case exists; only nullIn is covered. These are reached through the same branch, so the risk is low.

@Ergus Ergus self-assigned this Nov 6, 2026
groeneai and others added 2 commits November 6, 2026 11:54
Review feedback on the session-timezone rewrite of mutation IN lists:

- A list mixing strings with numbers or NULL is rewritten element by element
  into `toDateTime('...', 'tz')` / `toDateTime64('...', s, 'tz')` calls, which
  the deferred-set guard of mutation partition pruning refused, so such
  mutations touched every partition. The guard now also accepts those two
  functions over literals when the timezone argument is a non-empty string
  literal. An empty or missing timezone still refuses pruning, because it is
  resolved by the reading host.
- `CAST` and `toDateTime` parse strings more leniently than the conversion an
  IN set uses (`2000-01-01T01:00:00Z`, a trailing space, `2000-01-01 01:00`),
  so an ALTER could be accepted where the identical SELECT is rejected. The
  folded-list rewrite now first converts each string with the planner's own
  set conversion (`getSetElementsForConstantValue`) and lets its error
  propagate, so the ALTER fails with the same error as the SELECT. The
  explicit `tuple(...)` spelling, whose strings were already wrapped in
  `toDateTime`, gets the same check.

Tests: a database-qualified column, NULL in a folded tuple and array on a
Nullable column, GLOBAL IN / GLOBAL NOT IN / notNullIn, the rejected
strings, and a mixed list in the pruning test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master and pushed 5f112e2. The two failures on the previous head are not related to this change (neither test touches mutations or DateTime literals), and both fixes are now in the branch:

The test gaps from the review are added to 04056 in the same commit, each red on master and green here:

  • db qualified: {CLICKHOUSE_DATABASE:Identifier}.mut_tz_db_qual.time = '...'.
  • in null: IN ('...', NULL) and IN ['...', NULL] on a Nullable(DateTime) column, covering the tuple and array per-element branches.
  • in operators: GLOBAL IN, GLOBAL NOT IN, notNullIn.

The PR description is updated with these and the two fixes in the review threads.

@Ergus

Ergus commented Nov 9, 2026

Copy link
Copy Markdown
Member

@groeneai Merge master and solve conflicts

@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master (4ce893869dd3) and pushed 7daabdc. Git reported no conflicts: master's changes to MergeTreeData.cpp and InterpreterAlterQuery.cpp merged automatically without touching the lines this PR changes. The one that shares a function with this PR (the storage snapshot getPartitionIdsPrunedByPredicate resolves against) is covered by 04035. On the merged build 04035, 04056 and 05217 pass, also over 20 randomized runs.

I also resolved your two review threads from the last round, since both changes are in 5f112e2. Please reopen either one if something is still missing.

{
if (element.getType() != Field::Types::String)
continue;
checkConvertibleAsSetMember(element, zoned_type);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The strict check converts one string per call.

rewriteCollectionWithTimezone calls getSetElementsForConstantValue once per string element, each time building a DataTypeString, a size-1 const column and the full set-construction path.

For a homogeneous list this is N planner conversions whose results are discarded, followed by one more parse of the same strings by the emitted CAST at execution.

Perf claim (0.76–1.0x master up to N = 40 000) predates this commit, so the cost of the per-element path at large N is not measured.

Isn't it better to call over the whole string subset, passing an Array(String) const column and then fall back to the existing per-element shape only for the mixed case?

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.

Measured on release builds (CMAKE_BUILD_TYPE=None): ALTER TABLE t DELETE WHERE time IN (<N strings>) with session_timezone set, median server-side query_duration_ms, the four binaries interleaved:

case master this PR one call over Array(String) no strict check
N = 20,000, 1M rows (9 runs) 349 ms 268 ms 298 ms 229 ms
N = 40,000, 1M rows (9 runs) 669 ms 457 ms 454 ms 415 ms
N = 40,000, empty table (15 runs) 472 ms 345 ms 347 ms 282 ms

The strict check costs 40-65 ms at N = 40,000, and a single call does not reduce it. getSetElementsForConstantValue batches only native numbers (nativeBatchApplicable, SetUtils.cpp:519), so an Array(String) against DateTime goes through membersFromArray (:709) and still converts one member at a time (:310), the same N conversions. So I kept the per-element call.

The per-element shape of a mixed list is the expensive part: 40,000 elements, half of them strings, take 1.85 s against 0.30 s on master (which reads the strings in the server timezone), and the check is 75 ms of that. Master's explicit tuple(...) spelling of the same list takes 3.3 s.

I updated the description to the release numbers: 0.68-1.0x master's wall time up to N = 40,000.

…ation-in-literal-session-timezone

# Conflicts:
#	src/Interpreters/MutationsDateTimeLiteralVisitor.cpp
Comment on lines +189 to +190
if (strings == elements.size())
return castCollectionWithTimezone(Array(elements.begin(), elements.end()), datetime_type, timezone);

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] Preserve the value produced by strict set conversion

An accepted string can produce different timestamps in set conversion and CAST. With the default cast_string_to_date_time_mode = 'best_effort', time IN ('20000101') treats the string as epoch seconds 20000101, but the emitted CAST(['20000101'], 'Array(DateTime(\'America/Denver\'))') treats it as a calendar date and produces epoch 946710000. The new validation succeeds and discards the correctly converted value.

For a table with time DateTime and rows at those two epochs, setting session_timezone = 'America/Denver' makes the original SELECT match the first row, while this rewrite makes ALTER ... DELETE delete the second row. Comparing the original and emitted expressions confirms the same mismatch for DateTime64(3) and for the per-element toDateTime form. This also regresses the formerly correct, timezone-independent numeric-string case.

Persist the values returned by strict set conversion, preserving their scale, so the stored command cannot reparse the original strings differently. Add a regression comparing the selected and deleted rows for this numeric string.

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.

Fixed in 1ccc3be: each string is now replaced by the value the IN set gives it (an epoch for DateTime, decimal seconds read as Decimal(38, S) for DateTime64), with in numeric* regressions in 04056 for both spellings.

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] The latest alias fix reintroduces this issue at src/Interpreters/MutationsDateTimeLiteralVisitor.cpp:304-307: an aliased string takes wrapWithTimezone and bypasses convertAsSetMember.

For (id UInt8, time DateTime) with rows (1, 20000101) and (9, 946684800), set session_timezone = 'UTC' and use:

time IN tuple('20000101' AS lit) AND length(lit) = 8

The original SELECT matches row 1, but the emitted time IN tuple(toDateTime('20000101' AS lit, 'UTC')) AND length(lit) = 8 matches row 9: the original numeric-string-to-calendar-date divergence is back. Confirmed by comparing these expressions on 26.10.3.7; the current source emits the latter shape. Please preserve both the alias's original string value and the strict set-conversion result, and add the numeric-string regression with an alias.

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.

Not changed here: master stores the same time IN tuple(toDateTime('20000101' AS lit, 'UTC')) and deletes the same row (measured on current master). Storing the set value instead would change what lit binds, so an aliased string keeps master's wrap; keeping both needs typed alias resolution, which is out of scope for this PR.

…ation

The rewrite validated each string of an `IN` list with the set conversion of
the identical `SELECT`, then discarded the result and stored a `CAST` of the
original strings. `CAST` and `toDateTime` read strings with
`cast_string_to_date_time_mode` (`best_effort` by default), which can give a
different instant than the set: `time IN ('20000101')` selects the epoch
20000101, but the stored `CAST(['20000101'], 'Array(DateTime(tz))')` reads
2000-01-01 00:00:00 in the session timezone, so the mutation deleted a
different row than the `SELECT` matched. On master that numeric string was
read correctly, since an epoch does not depend on the timezone.

Each string is now replaced by the value the set gives it in the session
timezone: the epoch for `DateTime`, and for `DateTime64` its decimal seconds
read back through `Decimal128(S)`. A `DateTime64` text reading would again
depend on the parsing mode, and loses the sign of an instant in the second
before 1970 (`'-0.500'` reads as +0.5).

Partition pruning admitted a cast to a zoned `DateTime` array and
`toDateTime(<literal>, '<tz>')` for the old spelling. With a string such as
`'Nov 24 12:00:00'` they are not stable: the missing year comes from the
current date, so the partitions recorded at submission can differ from the
rows the predicate matches when the mutation runs. Those arms are removed;
the rewritten `DateTime` list is a plain literal that already prunes, and
the `DateTime64` one is a literal cast to `Decimal`, which the guard now
admits because reading a decimal does not depend on the date or the server.

The explicit `tuple(...)` spelling, which master already wrapped in
`toDateTime`, takes the same set values, so its numeric strings are read
as the `SELECT` reads them too.

Tests: 04056 gains the numeric-string case for `DateTime` and
`DateTime64(3)` in both spellings, a `DateTime64` instant before 1970 and a
mixed `DateTime64` list; its rewrite oracles now look for the original string,
since a rewritten command no longer carries the timezone name. 04035 test
13b checks that the yearless cast and `toDateTime` keep every partition,
and test 15 that a rewritten `DateTime64` list still prunes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 2 commits November 23, 2026 22:48
Replacing a string of an IN list by its set value dropped an alias on
that string or on the list (`time IN ('...' AS tag) AND length(tag) = 1`
then read the `tag` column and deleted a row the identical SELECT does not
select, or failed with UNKNOWN_IDENTIFIER without such a column), and it
also took a name bound by an alias, such as `('...' AS time)`, for the
column of that name.

Such strings now get master's `toDateTime(..., tz)` wrap, which keeps the
alias on the literal, and a folded literal list is left as written, as on
master. Aliases are collected per scope as the analyzer does: a lambda
body adds its own while it is visited, and nothing inside a lambda or a
subquery is visible outside it. 04056 gains `in alias*` cases.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Two names an alias binds were still taken for the stored column. With
`x Tuple(time String)`, `length((x.time AS time)) = 19 AND time NOT IN
('...')` was stored as `time NOT IN [<epoch>]` and deleted a row the
identical SELECT does not select: the collector skipped `x.time AS time`
as if it were `time AS time`. And an alias `x` shadowing a stored
`x Tuple(time DateTime)` made `x.time NOT IN ('...')` and `x.time = '...'`
read the stored subcolumn's type, because the alias check skipped
qualified names.

Only an identifier aliased to its own full name is now skipped, and the
check applies to the first part of a qualified name too, in comparisons as
well as in IN. Such a name gets exactly master's handling. An alias named
like the table therefore also keeps `tbl.time` at master's handling now:
whether the analyzer reads `tbl.time` through that alias depends on the
alias's type.

04056: the two shapes above as regressions, plus a `Tuple(time String)`
alias named like the table, which `tbl.time` does read; `in alias column`
keeps only the self-alias case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

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-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Mutation IN literal list skips session-timezone rewrite: wrong rows deleted

2 participants