Skip to content

Fix rows dropped by key analysis when a DateTime constant's declared timezone differs from the key column's - #113781

Merged
alexey-milovidov merged 23 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-keycondition-dag-timezone-attribute
Oct 4, 2026
Merged

alexey-milovidov merged 23 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-keycondition-dag-timezone-attribute

Conversation

@groeneai

@groeneai groeneai commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #117766

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fix rows silently dropped by primary key and partition pruning when a MergeTree key expression applies a timezone-observing function such as toYYYYMM, toString or a CAST to String to a DateTime/DateTime64 column and a compared constant declares a different timezone. Both a scalar comparison constant and an IN-set element are affected, including when the differing timezone sits under an Array, Map, Tuple, Nullable, LowCardinality or Variant wrapper that only one side carries, when a custom type name such as SimpleAggregateFunction wraps that composite on one side only, and when a sibling leaf differs only by a custom type name (Bool against UInt8). Also fix the same loss when a compared Tuple and the key column's disagree on explicit element names, which toJSONString renders as an object against an array; no timezone difference is needed.

Description

SET session_timezone = 'Asia/Kolkata';
CREATE TABLE t (d Nullable(DateTime('UTC'))) ENGINE = MergeTree ORDER BY d::String;
INSERT INTO t VALUES (toDateTime(1675195200, 'UTC'));
SELECT count() FROM t WHERE d = toDateTime(1675195200, 'UTC');  -- 0, expected 1

Root cause. applyDeterministicDagToColumn normalizes the constant to the type the key transform DAG was built against, but only when the two are not equals-equal. DataTypeDateTime::equals ignores the timezone, so the transform reads its zone off the constant and names a mark or partition the row does not live in.

The change. Rebuild the constant's type with every DateTime/DateTime64 leaf replaced by the corresponding leaf of the key column's type, looking through the wrappers named above on either side. That structural walk lives beside callOnNestedSimpleTypes as replaceNestedTypesInPair, so this file keeps only the leaf policy; Variant is covered by the walk rather than by a seventh branch here. The result keeps the constant's structure, so this relabels rather than converts. A custom name over a composite only renames it, so such a pair is relabeled whole once the recursion has cleared its children; on a leaf the name can change the value map (Bool renders every nonzero UInt8 as true), so it is refused and the atom is declined as before.

Validation. 05240 compares 116 rows against a Memory-engine oracle, including rows that pin the key as still USED (Granules: 1/2) rather than declined, and that a Variant holding two equals-equal alternatives is refused rather than relabelled. 05257 covers the naming-mode class: its three mismatch rows read 0 on 26.3, 26.8 and master against an oracle of 1, and 1 here, while the same-mode controls still prune (Parts: 1/2).

Affected: 26.3, 26.6, 26.7 and 26.8 all contain both c4ebb3c7320e64f and a0a00157398d840. v26.3-must-backport appreciated.

Four-arm matrix for the wrapper carrier

session_timezone = 'Asia/Kolkata', key SimpleAggregateFunction(anyLast, Array(DateTime('UTC'))),
PARTITION BY arraySum(arrayMap(x -> toYYYYMM(x), a)), element [toDateTime(1675195200)]; the Bool
rows use key SimpleAggregateFunction(anyLast, Array(Bool)) with PARTITION BY toString(a) and an
element [2], whose oracle is 2:

row master previous head outer name restored early this head
carrier rows returned (want 1) 0 1 1 1
partition key used for the carrier yes no yes yes
NOT IN rows returned (want 2) 2 2 1 2
!= rows returned (want 2) 2 2 1 2

A neighbouring shape is deliberately left alone: a DateTime64 scale mismatch under a wrapper the key
column alone carries still takes the direct-CAST fast path. Measured identical on pristine master and
on every arm above, so it is pre-existing and a separate axis from the timezone one.


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

Version info

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

A MergeTree key expression that applies a timezone-observing function to a
DateTime column silently dropped rows when an IN-subquery element's type
declared a different timezone than the key column's:

    SET session_timezone = 'Asia/Kolkata';
    CREATE TABLE t (ts DateTime('UTC'))
        ENGINE = MergeTree PARTITION BY toYYYYMM(ts) ORDER BY tuple();
    INSERT INTO t SELECT toDateTime(1675195200, 'UTC');
    SELECT count() FROM (SELECT ts FROM t WHERE ts IN (SELECT toDateTime(1675195200)));

returned 0 where 1 is correct. No error, no Nullable, no cross-type width
change; the same instant read from a Memory table returns 1.

applyDeterministicDagToColumn normalizes a set element to the type the DAG
was built against, guarded by !input_type->equals(*dag.input_type). But
DataTypeDateTime::equals deliberately ignores the timezone, on the grounds
that types differing only in timezone are interchangeable, and
DataTypeDateTime64::equals compares only the scale. So the guard evaluated
false, the normalization was skipped, and the block handed to the DAG carried
the element's type. A timezone-observing function resolves its timezone from
that type at execute time, via extractTimeZoneFromFunctionArguments, falling
back to DateLUT::instance() when the type declares none. toYYYYMM therefore
computed 202302 under the session zone where the key's own zone gives 202301.
The row is physically in 202301, so the transformed value named a partition
the row is not in and pruning discarded the only part holding it.

Adopt dag.input_type for a DateTime or DateTime64 input whose type is
equals-equal to the DAG's, testing the family through removeNullable because
DataTypeNullable::equals delegates to the nested type and so hides the timezone
one wrapper up in exactly the same way. equals() being true is exactly the
guarantee that they share a physical representation, so this is a relabel
rather than a conversion: only the local DataTypePtr moves, the column is never
re-materialized, nothing can fail and no NULL can be introduced. The relabel
fires only where the existing !equals guard was already false, so it changes
no branch decision in either direction. On the path that guard would otherwise
take, canBeSafelyCast is true for an equals-equal pair, so the cast is
castColumnAccurate, and castColumn returns the argument column untouched for
such a pair unless the cast is accurateOrNull; the relabel is that same
guarantee stated as code. There is no measurable cost either way: it is one
shared_ptr assignment, once per set index or constant preparation.

Relabeling the whole equals-equal pair, rather than rebuilding the type inside
the wrapper, is what keeps that argument intact: equals() on a Nullable already
guarantees both sides are Nullable over equals-equal nested types, so only the
nested label moves and the wrapper structure is identical. The corrected zone
still reaches the transform, because useDefaultImplementationForNulls is on by
default and its wrapper unwraps through columnGetNested, which takes the nested
DataTypePtr straight off the DataTypeNullable. A LowCardinality(Nullable(...))
key is covered by the existing removeLowCardinality on the line above, and was
measured correct on both arms for a different reason: DataTypeLowCardinality
reports isNullable() false, so such an element never becomes the Nullable pair
this guard sees. Array and Tuple delegate equals() to their nested types too,
but a set element of those types is not a DateTime input to a key transform and
both shapes were measured correct on both arms.

The timezone is not the only attribute equals() is blind to, but it is the
only one where relabeling is sound, so the change is restricted to it rather
than adopting dag.input_type unconditionally. IDataType::custom_name is
equally invisible to equals(), and relabeling there is not
semantics-preserving: Bool is UInt8 plus a custom name whose serialization
renders every nonzero value as true, so a bare-UInt8 element relabeled to
Bool would collapse the transform's value map. toString reports itself
injective, neither caller then marks the condition relaxed, and an exact
NOT IN prunes the partition holding the matching row -- trading this bug for
a wrong-results bug on negative predicates. Measured: with the relabel
unrestricted, b NOT IN (SELECT 2::UInt8) over a two-partition Bool table
returns 1 where 2 is correct. Restricting it to DateTime and DateTime64 keeps
the pruning fix, because relabeling a DateTime type changes which value the
transform produces one-for-one and so preserves injectivity on the element
set. The custom_name axis has a pre-existing defect of its own, independent of
this change: with the element already typed Bool, the same NOT IN returns 1
against an oracle of 2 on unmodified master.

The captured-timezone case matters in practice, since TimezoneMixin binds
DateLUT::instance() at construction while doGetName() returns the constant
"DateTime" when no timezone is explicit, so two DateTime types can differ in
the timezone the DAG observes while reporting identical names. A predicate
gated on a name difference skips exactly that pair and leaves it wrong. Both
of the narrower designs considered, widening the two equals tests and gating
on getName(), are pinned as mutants by the new test, as is dropping the
DateTime restriction.

The function is static with two call sites, both in this file, so there is no
Replicated or Shared sibling copy to keep in step, and skip indexes inherit
the fix through the same KeyCondition. The scalar, literal-IN and range paths
do not route through it and were measured unaffected.

The new test asserts wrong results against a Memory-engine oracle rather than
a pruning delta, since a pruning-delta oracle would pass on a conservative
regression. It covers four key transforms, partition key and primary key,
DateTime64, both directions of the asymmetry, the both-explicit shape, the
same-name captured-timezone shape and has(), against controls that read
correct before the fix. Three further carriers cover the Nullable wrapper,
over IN, has() and DateTime64; they need transform_null_in = 1, because at its
default of false the same queries read correct even before the fix, and
allow_nullable_key = 1, which is a MergeTree setting and so goes in the DDL
rather than a query-level SET. Their own two controls read correct before the
fix, the second of them by turning transform_null_in back off, which is what
shows that co-factor is real rather than decoration. Two of the timezone
controls assert NOT IN and != on that axis, which the restriction above leaves
correct in both arms, and one asserts the Bool negative predicate that pins
the restriction itself.
Because those rows assert answers, they also pass if the transform is declined
rather than corrected, so one further row asserts SelectedParts on a
two-partition table to pin that pruning is still used. Its two hours are
interleaved across two days so the element's instant lies inside the ts range
of both parts, which stops the min-max index standing in for the partition
index. The leading SET session_timezone is load-bearing: the runner randomizes
that setting and one of its draws is the local zone, which would make the
session zone equal the key zone and collapse the discriminator; a query-level
SET beats the runner's client argv injection, and carrier 5's
index_granularity is pinned in its DDL for the same reason. The has() carrier
disables optimize_rewrite_has_to_in, because at its default that pass rewrites
the predicate to a literal IN which never reaches the changed helper.

That SelectedParts row reads ProfileEvents from the initiator's query_log, so
the test is tagged no-parallel-replicas and pins enable_parallel_replicas and
automatic_parallel_replicas_mode off immediately before it. SelectedParts is
counted where each read executes, so with parallel replicas the value stops
being a function of whether the partition index ran on the initiator: measured
on a local server with a parallel_replicas cluster, forcing parallel replicas
on with parallel_replicas_local_plan = 0 collapses the row to 0 for both a
pruned and an unpruned read while the answer stays correct, and the pin
restores it to 1. The tag is what the CI flavour that enables parallel
replicas in the default profile honours, since that is server-side and a
query-level pin cannot be what opts the test out of it; the pin covers any
other path that reaches the test with them enabled. Neither that tag nor the
pin suppresses settings randomization, and no no-random-settings or
no-random-merge-tree-settings tag is needed.
…g wrappers

The previous shape of this fix tested `isDateTimeOrDateTime64(removeNullable(input_type))`,
so it recognized a timezone only at depth 0 and 1. `DataTypeArray::equals`,
`DataTypeMap::equals`, `DataTypeTuple::equals` and `DataTypeLowCardinality::equals` all
delegate to their children, so a `DateTime` timezone is exactly as invisible to `equals`
one or more wrappers down, while a higher-order function takes its lambda argument type
from the runtime wrapper type (`FunctionArrayMapped` builds each argument from
`array_type->getNestedType()`). An `Array(DateTime('UTC'))` key read with an
`Array(DateTime)` set element therefore still transformed under the session timezone and
named a partition the row does not live in: silent wrong results, the same class the
changelog entry already promises to fix.

Rather than adding one wrapper per round, the type test is now a small structural helper
that rebuilds the element type with every `DateTime`/`DateTime64` leaf replaced by the
corresponding leaf of the DAG's type, refusing (and changing nothing) if any other leaf
differs. Ten measured carriers close: `Array`, `Map` via `mapApply`, `Array(DateTime64)`,
`Array(Nullable)`, `Map(String, Nullable)`, `Array(Tuple)`, `Array(Array)`,
`Array(LowCardinality)` through the constant-equality caller, and both
`SimpleAggregateFunction` shapes.

Two design points, both settled by measurement rather than preference.

The obvious remedy -- adopting the pair wholesale when `equals` is true -- is unsound:
`DataTypeNumber<UInt8>::equals` is a bare `typeid` test and `Bool` is `UInt8` plus a
`DataTypeCustomFixedName`, so `Array(Bool)->equals(Array(UInt8))` is true and a wholesale
relabel would swap a `Bool` label onto a bare `UInt8` leaf inside the wrapper, collapsing
the transform's value map. The helper is therefore leaf-selective: only a `DateTime` or
`DateTime64` leaf is ever replaced, and a non-DateTime leaf is returned unchanged. There
is additionally a per-level custom-name refusal, in the spirit of
`DataTypeVariant::equals` ("The same data types with different custom names considered
different. For example, UInt8 and Bool."). Measured, those two guards are redundant for
`Bool`: each alone keeps the negation control green.

The leaf test runs BEFORE the custom-name refusal, and that order is load-bearing rather
than incidental. `SimpleAggregateFunction` is a custom name whose storage type is its
argument type verbatim, so a `SimpleAggregateFunction(max, DateTime('UTC'))` key carries a
genuine `DateTime` leaf under a differing name. With the refusal first, that key regressed
to the pre-fix behaviour; with the leaf test first it is fixed, along with the
`Array(SimpleAggregateFunction(...))` shape no previous round handled.

The relabel still fires only where `!input_type->equals(*dag.input_type)` was already
false, so it changes no branch decision in either direction, and it remains a relabel
rather than a conversion: `equals`-equal implies `canBeSafelyCast` (`DataTypes/Utils.cpp`)
and `castColumn` returns the argument column untouched for an `equals`-equal target
(`Interpreters/castColumn.cpp`).

`Variant` and `Object`/`JSON` are deliberately absent from the recursion. Both were
measured: an `IN` against a differently-parameterized `Variant` fails with
`CANNOT_CONVERT_TYPE` before any pruning, and `IN` over a `JSON` column is
`ILLEGAL_TYPE_OF_ARGUMENT` even for the identical type, so neither can reach the helper.

The regression test grows from 14 to 24 carriers and from 13 to 21 controls, deleting
none. Ten mutants pin the shape: reverting the relabel or inverting its direction reddens
all 24 carriers plus the pruning-count row; restoring the previous predicate reddens the
nine wrapper carriers alone; dropping both `Bool` guards together reddens the negation
control alone; and declining the pair instead of relabelling reddens only the
pruning-used row, which is what keeps the rejected alternative distinguishable.
`adoptDateTimeLeafTimezones` returns nullptr when a leaf other than
`DateTime`/`DateTime64` differs between the set element's type and the type the
transform DAG was built against, meaning the pair is not interchangeable. The
call site discarded that answer and continued with the element's own type, which
is the behaviour the normalization exists to remove: the DAG then runs under the
element's timezone and the partition index prunes a part that does hold matching
rows.

`equals` is blind to a custom name inside a wrapper, so this is reachable from
ordinary SQL. `DataTypeNumber<T>::equals` is a bare `typeid` test and `Bool` is
`UInt8` plus a `DataTypeCustomFixedName`, so `Array(Tuple(DateTime('UTC'), Bool))`
and `Array(Tuple(DateTime, UInt8))` are equals-equal while the `Bool` leaf refuses
relabelling. A bare `Bool` key reaches it the same way.

Make a refusal decline the transformation instead. `applyDeterministicDagToColumn`
already documents itself as conservative, returning false when the transformation
cannot be proven safe, and both callers handle that by declining the atom, so
every part is scanned and the answer stays correct. Measured on the pristine
master snapshot, on the pre-recursion binary and on the reverted-relabel binary,
the affected reads are wrong on all three, so this repairs a pre-existing wrong
result rather than one introduced with the recursion.

Adds three carriers for the refusal (one wrapped, two bare) with two controls,
and a wrapper-shaped pruning-USE oracle. The existing pruning oracle is built on
a bare `DateTime` key, so it pins no recursive branch; every wrapper row asserts
only `count()`, which a declined transform also satisfies via a full scan. The new
oracle reads `SelectedParts` for an `Array(DateTime('UTC'))` key over two parts
whose min-max ranges both contain the element, so a decline moves it from 1 to 2.
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

An independent model reviewed this diff cold against the ClickHouse review checklist, and its
findings were adjudicated against the source. Seven rounds ran on this PR; the notes below cover the
final one, and the residuals are listed rather than silently dropped.

⚠️ A pre-existing wrong result on an adjacent axis, disclosed not fixed. DataTypeTuple::equals
compares element types and element names but not the named/anonymous flag, while
doGetSerialization passes that flag to SerializationTuple and serializeTextJSON keys on it. An
anonymous one-element tuple auto-assigns the name 1, and the explicit name 1 is legal, so
Array(Tuple(`1` DateTime('UTC'))) and Array(Tuple(DateTime)) are equals-equal while
toJSONString renders one as an object and the other as an array. A PARTITION BY toJSONString(a)
key over that pair therefore prunes the matching part.

This is not introduced here, and the reasoning is worth stating because it also bounds the change.
Since the pair is equals-equal, the existing !equals normalization is skipped on master too, so
master hands the transform the element's type verbatim: anonymous form and the session timezone.
This PR fixes the timezone half, so the rendered value goes from wrong-in-two-attributes to
wrong-in-one. The object and array forms differ in their first two bytes, so no timezone value can
make either arm's rendering equal the stored value: master is wrong for this shape as well, and no
shape that was correct before can become wrong. The residual attribute is the tuple's named/anonymous
flag, not the timezone.

⚠️ One stale sentence in a test comment. The comment above the SimpleAggregateFunction carriers
says that checking the custom-name refusal before the DateTime-leaf test "silently reintroduces the
bug" for those two rows. That was measured before this round made a refusal decline the transform
rather than fall through; with the decline in place the reversed order declines and loses pruning
instead of returning a wrong answer. The shipped order is the correct one either way; only the
comment's wording is now imprecise.

💡 Two comment characters. Lines 405-406 of the test write count() where the repo convention is
count when naming a function rather than applying it.

A request to add a SelectedParts assertion for every wrapper branch individually was declined. The
wrapper handling is one recursion over the types that delegate equals to their children, not
several independent implementations, and the existing pruning oracle already pins it generically:
declining the transform moves both SelectedParts rows, and reverting the recursion reddens the
wrapper carriers plus pruning_arr_count. Per-branch rows would each add an OPTIMIZE, a
SYSTEM FLUSH LOGS and a query_log read to a file that already runs 82 assertions.

Fixed during review: the PR body's carrier, control and mutant counts and its shipping Build ID were
from an earlier round and were re-derived from the test file; the validation-gate comment said one
row asserts SelectedParts where there are two.

Session id: cron:clickhouse-review-slot-10:20260807-082400

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, and deterministic rather than statistical: every one of the twenty-seven carriers reads the wrong count on every run of the pristine-master-behaviour binary. Command: run tests/queries/0_stateless/04770_keycondition_dag_timezone_attribute_pruning.sql against a local server. Minimal shape: SET session_timezone='Asia/Kolkata', a MergeTree table keyed PARTITION BY toYYYYMM(ts) over ts DateTime('UTC'), one row at toDateTime(1675195200,'UTC'), then SELECT count() FROM (SELECT ts FROM t WHERE ts IN (SELECT toDateTime(1675195200))) reads 0 where 1 is correct. The wrapper carriers use the same shape one or more wrappers up, e.g. a Array(DateTime('UTC')) keyed PARTITION BY arraySum(arrayMap(x -> toYYYYMM(x), a)) against an Array(DateTime) element. The Nullable carriers additionally need the key created SETTINGS allow_nullable_key = 1; the bare ones need SET transform_null_in = 1 while the Array(Nullable) and Map(String, Nullable) ones do not, which was measured rather than assumed. The Array(LowCardinality(...)) carrier is reachable only through constant equality, not IN, for the reason in row (f). Counts here are the number of SELECT '<label>' rows whose label starts with partition_ or primary_key_; controls are those starting with control_.
b Root cause explained? Yes, and the new half is one level deeper than the previously fixed half. applyDeterministicDagToColumn normalizes an IN-set element to the type the key-transform DAG was built against, guarded by !input_type->equals(*dag.input_type). DataTypeDateTime::equals deliberately ignores the timezone (DataTypeDateTime.cpp:33-38) and DataTypeDateTime64::equals compares only the scale (DataTypeDateTime64.cpp:57-62), so the guard is false, the normalization is skipped, and the block handed to the DAG carries the element's type; a timezone-observing function then resolves its zone from that type at execute time (extractTimeZoneFromFunctionArguments.cpp:65-75, falling back to DateLUT::instance()), so toYYYYMM yields 202302 where the key's zone yields 202301 and pruning discards the only part holding the row. The new finding is that the same blindness holds at every wrapper level, because DataTypeArray::equals (DataTypeArray.cpp:49-52), DataTypeMap::equals (DataTypeMap.cpp:143-150), DataTypeTuple::equals (DataTypeTuple.cpp:268-284) and DataTypeLowCardinality::equals (DataTypeLowCardinality.cpp:144-151) all delegate to their children, while a higher-order function takes its lambda argument type from the runtime wrapper type (FunctionArrayMapped.h:362-378 builds each argument from array_type->getNestedType() or type_tuple.getElement(j)). A predicate testing only the top-level type id therefore cannot see a nested timezone at all.
c Fix matches root cause? Yes, and it closes the axis rather than adding one wrapper. The previous shape tested isDateTimeOrDateTime64(removeNullable(input_type)), which recognizes depth 0 and 1 only; that is the incremental-widening pattern, and it is why Array and Map were still broken after Nullable was fixed. The fix replaces the predicate with a structural helper that returns a copy of the element type with every DateTime/DateTime64 leaf replaced by the corresponding leaf of the DAG's type, recursing through exactly the equals-delegating set (Nullable, LowCardinality, Array, Map, Tuple) and returning nullptr if any other leaf differs. A nullptr refusal makes the whole transform DECLINE (return false), which is the function's own documented channel -- its contract comment says it "is intentionally conservative and returns false if the transformation cannot be proven safe" -- and both callers then decline the atom, so every part is scanned and the answer stays correct. Falling through on a refusal instead, as an earlier revision did, leaves the DAG running under the element's timezone: that is the same wrong prune, and it reads 0 on the pristine master snapshot too, so this half repairs a PRE-EXISTING wrong result rather than one this PR introduced. Two design points, both measured. Adopting the pair wholesale on equals alone is unsound: DataTypeNumber<UInt8>::equals is a bare typeid test (DataTypesNumber.h:24) and Bool is UInt8 plus a DataTypeCustomFixedName (DataTypeDomainBool.cpp:11-15), so Array(Bool)->equals(Array(UInt8)) is true and a wholesale relabel would swap a Bool label onto a bare UInt8 leaf inside the wrapper, collapsing the transform's value map. And the DateTime-leaf test runs BEFORE the per-level custom-name refusal, which is load-bearing rather than incidental: SimpleAggregateFunction is a custom name whose storage type is its argument type verbatim (DataTypeCustomSimpleAggregateFunction.cpp:157), so a SimpleAggregateFunction(max, DateTime('UTC')) key carries a genuine DateTime leaf under a differing name; with the refusal first that key regressed to pre-fix behaviour (measured 1 to 0 against the previous binary), with the leaf test first it is fixed. No band-aid: nothing is post-filtered, no bound is widened, no no-random-* tag is added, no defensive check sits at the symptom, and pruning is not given up. The one tag the test carries, no-parallel-replicas, opts out of a CI flavour whose profile enables parallel replicas server-side, under which the SelectedParts row is counted where each read executes rather than on the initiator; it suppresses no randomization.
d Test intent preserved / new tests added? Yes. No existing row is modified, weakened or deleted: the file carries 27 carriers and 24 controls, with zero deletions on either count, re-derived by diffing the label SETS against the previous commit (3 carriers and 3 controls added in the final round; one row was renamed from control_bool_in_false to partition_bool_in_false because it was measured to read 0 pre-fix and so is a carrier, not a control). The test asserts wrong results against a Memory-engine oracle rather than a pruning delta, because a pruning-delta oracle would pass on a conservative regression. Because those rows assert answers, they also pass if the transform is declined rather than corrected, so two rows assert ProfileEvents['SelectedParts'] on two-partition tables to pin that pruning is still used: one on a bare DateTime key and one on an Array(DateTime('UTC')) key, the latter because the bare one pins no recursive branch. Eight mutants pin the shape, each rebuilt with a distinct Build ID and run through the same file, and each arm's red-row SET is reported rather than a pass/fail bit. Three asymmetries are load-bearing. Reverting the relabel entirely reddens 29 rows (every carrier plus both pruning_*_count rows). Restoring the pre-recursion predicate reddens 13 -- the ten wrapper carriers, the two bare Bool carriers and pruning_arr_count -- leaving every earlier carrier and every control green. And reverting ONLY the refusal-declines-the-transform half reddens exactly the three rows that half repairs and nothing else. Note which SimpleAggregateFunction row is in that thirteen: only the Array-wrapped one. The bare form was already correct under the previous predicate, because a SimpleAggregateFunction over DateTime has a DateTime storage type and so passed the old top-level test; only its wrapped form needed the recursion. Of the two mutants that each break one of the two Bool protections, the one removing the per-level custom-name refusal now reddens two rows (it survived before the decline was added, because a refusal used to be silently discarded); the one changing the non-DateTime leaf fallback still survives, because for a Bool leaf the refusal fires before the fallback is reached. The mutant that drops both together reddens control_bool_negation alone. That redundancy is stated rather than glossed: it is why neither single-guard mutant reddens, and it was confirmed on a separate build with the custom-name refusal deleted outright, where breaking the remaining guard does redden that row.
e Both directions demonstrated? Yes, on the same tree with only the helper differing, both arms restarted per binary with SELECT lower(buildId()) asserted equal to that binary's own readelf -n NT_GNU_BUILD_ID before any verdict. Post-fix (Build ID d0d5cf566e20965510b75e33d47603d52493a1dd, built from the committed tree): output byte-identical to the committed reference, and the full file [ OK ] through the real clickhouse-test runner. Pre-fix arm for the recursion half (Build ID 26ba677e93f03a31c43b0a44f8d9b30b5bc7f5f9, the previous predicate restored): thirteen rows read wrong, every other row green. Pre-fix arm for the whole fix (Build ID 763875012cf40075786b7cf185b11f36dff271fe, pristine-master behaviour): all 27 carriers plus both pruning_*_count rows wrong, all 24 controls correct. The three carriers the refusal half repairs were additionally measured on the shared pristine master snapshot (Build ID 0502ee8df849bfcb439c04b60c0879b53245a021, proven distinct by `strings
f Fix is general across code paths? Yes. applyDeterministicDagToColumn is static with exactly two call sites, both in this file (the scalar-constant path and the set path), so the blast radius is closed by construction and the relabel sits above both; the new helper is likewise file-local static with a single call site. Both DAG routes are covered by carriers: the ordinary dag.actions->execute route and the single-CAST direct route. The two callers differ in one respect the test now covers: the set path builds its element type through Set, which runs recursiveRemoveLowCardinality over it (Set.cpp:121), so a nested LowCardinality can never arrive there, whereas the constant-equality path delivers it intact. Instrumenting the call site confirmed this rather than inferring it, and the Array(LowCardinality(...)) carrier is written against the constant path for exactly that reason, with the IN form kept as a control. Skip indexes reach key analysis through the same KeyCondition and inherit the fix. There is no Replicated or Shared sibling copy of this logic.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, and the wrapper set is closed by construction rather than enumerated by hand: the recursion covers exactly the types that delegate equals to their children, which is the same set that overrides forEachChild. Covered by carriers: both timezone-carrying leaf types (DateTime, DateTime64), both directions of the asymmetry, both-explicit and both-implicit same-named shapes, four key transforms, partition key and primary key, two granularities, has(), the bare Nullable wrapper, and at depth 2 or more Array, Array(DateTime64), Array(Nullable), Array(Tuple), Array(Array), Map via mapApply, Map(String, Nullable), Array(LowCardinality) and both SimpleAggregateFunction shapes. Five shapes were measured NOT to be carriers and are kept as controls: a Tuple or Map whose key expression takes the leaf out before the transform (t.1, m['x'], arrayMap(x -> toYYYYMM(x.1), a)), a Map whose DateTime sits in the KEY type rather than the value, and the IN form of the LowCardinality shape. Variant and Object/JSON are deliberately absent from the recursion and that absence is measured, not assumed: an IN against a differently-parameterized Variant fails CANNOT_CONVERT_TYPE before any pruning, and IN over a JSON column is ILLEGAL_TYPE_OF_ARGUMENT even for the identical type, so neither can reach the helper and a branch for them would be dead code. Negative predicates are covered on both axes: NOT IN and != over a two-partition DateTime('UTC') table read correctly in both arms, and the Bool negative predicate pins the leaf selectivity.
h Backward compatible? (maintainer-approved exception only) Yes. No setting is added or altered, so no SettingsChangesHistory.cpp entry is owed; no serialization format moves and no experimental gate is needed. The behaviour change is from silently wrong to correct, which needs no compatibility shim. Affected branches, by ancestry of the commit that added this helper and its guard (c4ebb3c7320e64f): master, 26.7, 26.6, 26.5, 26.3; 25.8 predates it and has no applyDeterministicDagToColumn at all, which is a fact about that helper's age rather than a claim about 25.8's different code shape.
i Invariants and contracts preserved? Yes, and the soundness argument is unchanged in kind from the previous rounds. The relabel still fires only where input_type->equals(*dag.input_type) already held, i.e. exactly where the existing !equals guard was false, so it changes no branch decision in either direction; and it remains a relabel rather than a conversion, because equals-equal implies canBeSafelyCast (DataTypes/Utils.cpp:18-19) and castColumn returns the argument column untouched for an equals-equal target (Interpreters/castColumn.cpp:17-18). What this round adds is that the rebuilt type is structurally identical to the element's own: equals on an Array already guarantees both sides are arrays over equals-equal nested types, on a Map that both key and value types are equals-equal, and on a Tuple that the sizes AND the element names match, so reconstructing the wrapper from the element side and substituting only DateTime leaves cannot change the physical layout, the row count or the column. Tuple names are carried from the element type explicitly, and only when it has explicit names, so an unnamed tuple stays unnamed. No allocation per value, no cast that can fail and no NULL introduced, therefore no new error path; the function's early-return and false-return paths are untouched. The helper is a bounded recursion over the type tree, runs once per set-index or constant preparation rather than per row, and is not concurrency-relevant.

Session id: cron:clickhouse-review-slot-10:20260807-082400

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @hanfei1991 @Avogar, could you review this? The key transform DAG reads a timezone off the type it is handed, but DataTypeDateTime::equals ignores the timezone (and the wrapper types delegate equals to their children), so an IN-set element declaring a different zone was transformed under the wrong one and partition pruning discarded the part holding the row.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0940a01]

Summary: ✅


AI Review

Summary

No actionable correctness, safety, or performance issues remain on the current head. The PR fixes the KeyCondition wrong-result class by relabeling DateTime/DateTime64 leaves through nested wrappers before running deterministic key transforms, and it adds focused stateless coverage for the timezone, tuple naming-mode, wrapper-customization, and Variant cases discussed during review.

Missing context / blind spots
  • ⚠️ I did not rerun the new stateless tests locally because this workspace has no ready ClickHouse build or clickhouse-local binary; this review is based on the current diff, the checked-in tests, and the full GitHub discussion.
Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 0940a01.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 69/111 (62.16%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 7, 2026
@yariks5s yariks5s self-assigned this Aug 7, 2026
Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d21b532

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) / Error message in clickhouse-server.log benign error-log leak: StorageFileLog (test_1.filelog_bad_path_attach): The absolute data path should be inside user_files_path. On server restart the table is re-attached with SECONDARY_CREATE, where StorageFileLog.cpp:193-201 deliberately logs at <Error> and continues instead of throwing, so the log scanner flags an expected test condition. 2 rows / 2 unrelated PRs / 0 master in 30d a fix task is created (investigating at full effort - fixing PR link to follow on this PR)
Build (arm_release) / Post Hooks infra: the build_profile_hook telemetry INSERT INTO build_time_trace exhausts its retries against the CI logs cluster (Code: 241 ... would use 711.40 GiB, maximum: 29.80 GiB. OvercommitTracker decision). The 8 retry warnings confirm this build already carries merged #113409, so that PR is present and does not resolve it. Build (arm_release) itself is green; this row is CIDB-only and does not gate the merge a fix task is moved to pending (investigating at full effort - fixing PR link to follow on this PR)

Neither failure is PR-caused: this PR touches only src/Storages/MergeTree/KeyCondition.cpp and one
stateless test pair, and nothing under src/Storages/FileLog/ or the CI build-profile hook.

Session id: cron:our-pr-ci-monitor:20260807-143000

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Upgrade check (amd_release) / Error message in clickhouse-server.log line on this PR's CI finish ledger (the benign StorageFileLog ... The absolute data path should be inside \user_files_path`` reattach error): #113983

@groeneai groeneai added the groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work label Aug 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0940a0183 with master c662045b0 (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

5 object files changed (+19.50 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/DataTypes/transformTypesRecursively.cpp.o 129.93 KiB 146.18 KiB +16.24 KiB (+12.50%)

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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 88db130040b9c69a12d8808dcd6fd1166f0d4981

Every failure below has an owner: a fixing PR (ours 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_msan) / Logical error: Not-ready Set is passed as the second argument for function 'globalIn' (STID 0250-41a5), Failures: 1/5 not PR-caused, trunk defect on the object-storage path pre-filter. The abort frames are StorageObjectStorageSource::createFileIterator (src/Storages/ObjectStorage/StorageObjectStorageSource.cpp:581) into VirtualColumnUtils::filterByPathOrFile (src/Storages/VirtualColumnUtils.h:136) into getFilterByPathAndFileIndexes (src/Storages/VirtualColumnUtils.cpp:419) into filterBlockWithExpression (:163) into FunctionIn::executeImpl (src/Functions/in.cpp:128), reached from ReadFromObjectStorageStep::initializePipeline under an AST fuzzer query. The diff here is src/Storages/MergeTree/KeyCondition.cpp plus one stateless test, and key analysis is not on that call path. #112968 (external, open)

That PR is the remedy for this exact call site rather than a same-area coincidence: it rewrites
StorageObjectStorageSource::createFileIterator and VirtualColumnUtils.{cpp,h}, the two frames
above the aborting function, and its regression tests are named
04669_object_storage_path_filter_global_in and 04907_file_url_path_filter_global_in.

No other check failed at this head, and Config Workflow, Style check and Finish Workflow are
all success with 0 nodes DROPPED.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113781&sha=88db130040b9c69a12d8808dcd6fd1166f0d4981&name_0=PR&name_1=Stress%20test%20%28amd_msan%29

Session id: cron:our-pr-ci-monitor:20260831-083000

…wCardinality wrapper

The adopt added earlier in this PR is gated on `input_type->equals(*dag.input_type)`. A bare
comparison constant is never `Nullable`, so on a `Nullable(DateTime(tz))` key column the pair is
`DateTime('UTC')` vs `Nullable(DateTime(tz))`, `DataTypeNullable::equals` is false, and the adopt
never runs. `LowCardinality` behaves the same way, and so does a wrapper that differs one level
down, as in `Array(Nullable(DateTime))` against an `Array(DateTime)` element.

Only one of the two unequal-type routes was actually wrong. The general route casts the constant to
`dag.input_type` and that round trip already moves it onto the key column's zone, which is why
`toString`, `toHour` and `cityHash64` keys were correct. `try_apply_direct_cast_fast_path` exists to
skip that round trip, so it cast the constant straight to the CAST's result type and rendered it in
the constant's own zone, naming a mark or partition the row does not live in. Measured on a
`Nullable(DateTime('America/New_York'))` key with a `DateTime('UTC')` constant, the condition read
`CAST(d, 'String') in ['2024-11-03 05:30:00', ...]` while the stored key was `01:30:00`, and the
matching row was dropped with no error.

`adoptDateTimeLeafTimezones` now looks through a wrapper only the key column carries, at any depth,
and no longer relies on an `equals` precondition: every leaf checks the kinds it is about to
combine. The returned type always keeps the element's own structure, so it still describes the
column it is attached to and only timezones move. The call site stays additive: an adopt that
refuses on an `equals` pair declines the atom exactly as before, and one that refuses on an unequal
pair leaves the existing casts to reconcile it, so no atom is newly declined and no pruning is lost.

The DateTime leaf test deliberately stays ahead of the custom-name refusal. With the order reversed,
`SimpleAggregateFunction(anyLast, DateTime(tz))` key columns hit the refusal because their
`getName()` embeds the zone, which silently gave up the pruning the earlier commits had won.

Closes: ClickHouse#117766

Six new carriers in 04770 cover a `Nullable` key with `=` and with `IN`, `PARTITION BY`,
`DateTime64`, a `LowCardinality` key, and the wrapper mismatch inside an `Array`; all six return 0
before this commit and 1 after. The `LowCardinality` carrier uses `IN` because a scalar comparison
resolves a common supertype for its arguments and retypes the constant before key analysis runs, so
the `=` form reads 1 either way and would witness nothing. Controls pin that the zeros were dropped
rows rather than an empty fixture, that an absent instant still reads 0, and that the index still
prunes rather than the atom being declined.
…uning test

The carrier block added for key-only wrappers reused the numbers 23-24 and sat between blocks 12-14
and 15-22, so the numbering no longer read in file order. Renumber it 15-20 and shift the two blocks
after it.

Two comments no longer described the code. The custom-name ordering note claimed the reverse order
"silently reintroduces the bug"; since an adopt refusal on an `equals` pair declines the transform,
the reverse order returns the right count and loses the pruning instead, which is what the note now
says. And two references to `count` as a value carried call parentheses, which the repository
convention reserves for applying a function.
Relabelling rebuilt every composite it walked, so a key column typed as a custom name over a
composite came back as the plain composite: `Point` became `Tuple(Float64, Float64)`. `wkb` picks its
implementation from the runtime type name, so it threw on the rebuilt type, key analysis turned that
into a refusal, and the table silently stopped pruning. Measured on a 16-granule `Point` key,
`ORDER BY wkb(p)`: master reads `Granules: 2/16` with a real condition, this branch read
`Condition: true` over `16/16`. The rows returned were correct throughout, which is why only a plan
assertion catches it.

Each composite branch now returns the element type untouched unless a leaf actually moved, detected
by comparing the recursed child against the original. Nothing else in the walk changes.

The `DateTime` leaf keeps adopting unconditionally, and deliberately does not skip when the two type
names match: a `DateTime` binds the session zone at construction and reports the bare name `DateTime`
either way, so two types with the same name can still carry different zones. Skipping on equal names
was tried and it silently un-fixed the existing `partition_same_name` carrier, which exists for
exactly that case.
The note grew to four lines and carried why a stripped type name matters at runtime, which belongs in
the commit that made the change rather than at the call site. Keep the two invariants a reader needs
here: a timezone under a wrapper is as invisible to `equals` as a bare one, and rebuilding a composite
would drop its customizations.
@groeneai groeneai changed the title Fix rows dropped by key analysis when an IN-set element's DateTime type declares another timezone Fix rows dropped by key analysis when a DateTime constant's declared timezone differs from the key column's Sep 3, 2026
@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

Rescoped this round, so title, changelog entry and description are updated: the fix now also covers a wrapper carried by the key column alone, which is the shape reported in issue 117766, and 04770 grew to 95 rows.

One neighbouring shape is deliberately left alone, because it is pre-existing and sits on a different axis (representation, not timezone): a DateTime64 set element whose scale differs from the key column's is still mispruned. It reads MergeTree 0 against an ENGINE = Memory oracle 1 identically on a pristine master build, on the previous head of this branch and on this head, and it reproduces with no wrapper at all. Declining every unequal type pair would cover it, but that refusal is the normal case for a legitimate cross-type transform: a UInt32 element against a DateTime('UTC') key with ORDER BY toYYYYMM(ts) returns the right row at Granules: 1/16 on all three arms. Declining there would turn correct pruning into full scans, so that one needs its own change rather than a wider refusal here.

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

Splitting the scale axis out of this PR turned up a second defect in
applyDeterministicDagToColumn, and I do not think I should pick a repair for it
unilaterally: the two sound options differ in how much of #92952's pruning they give up.

The invariant is that a constant handed to a deterministic key transform has to be a value
the key column could itself present. Two ways it breaks, both measured on master (debug,
clickhouse local, one-row table, Memory oracle, plus a control asserting the stored row
really does satisfy the predicate):

  1. Typed keys. With d DateTime64(6, 'UTC') and ORDER BY d::String,
    d IN (SELECT toDateTime64(1675195200, 3, 'UTC')) returns 0 where 1 is correct: the
    direct-cast fast path renders the element at scale 3 (.000) while the key renders at
    scale 6 (.000000). The scalar =, the Nullable variants, and a Nullable(Bool) key
    against a bare UInt8 all read 0 by the same mechanism. This axis is independent of the
    timezone axis, since it survives an explicit 'UTC' on both sides with
    SET session_timezone = 'UTC'.

  2. Dynamic keys. With x Dynamic holding toDateTime64(1675195200, 6, 'UTC') and
    ORDER BY x::String, x = toDateTime64(1675195200, 3, 'UTC') returns 0 where 1 is correct.

Case 1 is fixable: prefer the route through dag.input_type, gated on an exactness check
(cast there, cast back, compare). That check also declines the Decimal64(2) to
Decimal64(1) rounding and the UInt8 2 to Bool collapse, neither of which
accurateCastOrNull flags, and it keeps the pruning that #92952's own tests assert.

Case 2 is not fixable at that layer. Dynamic carries no scale, so the rendering depends on
the stored value's active type, which analysis cannot know; normalizing the element is exact
and still renders at the wrong scale. The only sound repair is to decline when the transform
input is variant-like, which switches off the JSON subcolumn key pruning that #92952 added
and rewrites three of its EXPLAIN references.

So: fix case 1 and leave case 2, or fix both and give up that pruning? I lean towards the
first, leaving case 2 to whoever owns #92952, but that is a call for the owner of that
feature rather than mine. I have not opened a PR for either.

`adoptDateTimeLeafTimezones` refused every pair whose custom names differ, so a
key column of type `SimpleAggregateFunction(anyLast, Array(DateTime('UTC')))`
against an element typed `Array(DateTime)` fell into the caller's
`equals`-refusal branch and the atom was declined. Correctness was preserved by
reading every part, which is the pruning the rest of this change exists to keep:
`PARTITION BY arraySum(arrayMap(x -> toYYYYMM(x), a))` on that key answered
`Condition: true` over all parts where master built the real key condition.

A custom name is representation-neutral, so an `equals`-equal pair is
interchangeable and `dag_type` is the exact type to hand the transform: it
carries the timezones, the custom name and the tuple element names that `equals`
ignores, none of which the rebuild below can reproduce. The refusal still stands
on a leaf, where a custom name can change what the transform computes -
relabelling a `UInt8` element to `Bool` would render every nonzero value as
`true` and collapse the value map an exact `NOT IN` relies on.

Measured on three binaries with the new test rows. Pristine master answers 0
rows for the carrier (wrong results) and prunes; the previously published head
answers 1 row and stops pruning; this change answers 1 row and prunes.
`control_bool_negation`, which pins the leaf refusal, reads 2 on all three.
No result-level change across 355 tests of the geometry, `Nested`,
`SimpleAggregateFunction`, `Bool`, key-condition and partition-pruning families,
run on both arms.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5c00e7a

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
Fast test (arm_darwin) / 05076_error_trace_file_offsets oracle column 2 is unsatisfiable on Darwin by construction: StackTrace::resolveAddress is compiled only under __ELF__, so Darwin stores raw runtime addresses, while the Mach-O collector extends each dyld image's last symbol to that image's max_addr, putting the bound above every captured frame. The test carries no Tags: line, so it runs on the darwin Fast test. Not caused by this PR; the test has never passed on this arm since my #117449 merged #119145 (mine, open) tags the test no-darwin
Integration tests (amd_tsan, 2/6) / test_storage_nats/test_nats_jet_stream.py (11 tests, all failing in nats_setup_teardown at line 199 on DROP DATABASE IF EXISTS test SYNC) teardown hangs the full 600 s client timeout because of a js_maybeFetchMore lock-order inversion in the vendored NATS client; the failures are a teardown cascade, not body assertions. Wholly unrelated to this PR's KeyCondition timezone diff, and measured at 51 true-master hits plus 255 rows across 18 distinct PRs on this shard in 14 days my open upstream fix ClickHouse/nats.c#6 in the vendored client; the ClickHouse-side submodule bump follows its merge
Integration tests (amd_tsan, 2/6) / test_nats_jet_stream_hands_back_the_backlog_of_a_consumer_a_direct_select_left_subscribed the one body assertion, at line 2253 in wait_for_mv_attached_to_table: a readiness wait that the same NATS client stall starves, and it co-fires with the teardown hang on every carrier my open upstream fix ClickHouse/nats.c#6 in the vendored client
Integration tests (amd_tsan, 2/6) / Timeout job-level ERROR: session-timeout occurred during test execution: the shard's 7200 s session_timeout_parallel is exhausted, and the +600 s per hung NATS teardown above is what pushes this shard over it #118384 (mine, open) raises the parallel session timeout
Mergeable Check aggregator reflecting the reds above #119145 and ClickHouse/nats.c#6 and #118384
PR workflow aggregator reflecting the reds above #119145 and ClickHouse/nats.c#6 and #118384
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20260910-053056

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 79694fb

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
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) / test_bucket_partition_pruning[local,s3,azure] + test_partition_pruning_with_functions_before_epoch[local,s3] master regression from merged #118606 (pre-epoch partition values), not from my diff, which only touches KeyCondition timezone handling: 143 to 162 distinct PRs and 16 to 27 true-master hits per test over 30 days #119298 (external, merged), merged master @ 4d6bfea6d799
Finish Workflow / Post Hooks (new_tests_check.py) cascade of the row above: both Bugfix validation (functional tests, *) jobs were DROPPED by that integration failure, so no per-arch job could report OK or XFAIL #119298 (external, merged), merged master @ 4d6bfea6d799
Mergeable Check, PR aggregators reflecting the two rows above #119298 (external, merged), merged master @ 4d6bfea6d799
CH Inc sync - CH Inc sync (private, not actionable by me)

The revert merged at 2026-09-10T17:26:35Z, 55 minutes after the master merge this run was built
from, so it could not be present here (03bf3a961a74 is not an ancestor of 79694fb2). It is on
master now and no true-master hit remains after 2026-09-10, so I merged master to re-run CI with it.

Session id: cron:our-pr-ci-monitor:20260912-123103

Comment thread src/Storages/MergeTree/KeyCondition.cpp Resolved
alexey-milovidov and others added 3 commits September 18, 2026 21:34
…bcolumn_shared_offsets_continuation` on master

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…refusal

The AI review asked for a `Bool` carrier on the direct-`CAST` path, where the
transform DAG is a bare `CAST` on the input rather than a function call. The
existing bare-`Bool` carrier goes through `PARTITION BY toString(b)`, so
`try_apply_direct_cast_fast_path` was not exercised by the test.

A key of `b::String` reaches that fast path, and the new carrier pins that the
leaf refusal in `adoptDateTimeLeafTimezones` is evaluated before it: `b = 1::UInt8`
and `b IN (1::UInt8)` both return the oracle's 8 rows instead of the 0 rows master
returns, while an element that carries the key's own name (`b = true`) still prunes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
groeneai and others added 2 commits September 18, 2026 23:05
The carrier added in cc6f73a printed the oracle's 8 rows on master as
well, so it pinned nothing. Two independent reasons, both measured against
master 01b8f1c and this head:

  - `SELECT count() FROM k_bool_cast WHERE b = 1::UInt8` is answered by the
    trivial-count-with-sparsity path (`ReadFromPreparedSource`), which never
    runs key analysis. Reading the rows instead, through the subquery wrapper
    the other 79 rows of this test use, returns 0 on master against an oracle
    of 8, with `Condition: (CAST(b, 'String') in ['1', '1'])` and
    `Granules: 0/16`.

  - A one-element literal `IN (1::UInt8)` list is coerced to the key's own
    type before the transform sees the element, so it builds
    `CAST(b, 'String') in 1-element set` and prunes to 9/16 correctly on both
    arms. `IN (SELECT 1::UInt8)`, the form the sibling `partition_bool_in`
    row already uses, reaches the refusal and returns 0 on master.

Both key rows now flip 8 -> 0 on master and stay at the oracle's 8 here.

The two exact-name controls move to the same reading shape, and one plan row
is added for the property their comment claims: a count cannot distinguish
"the atom still prunes" from "the atom was blanket-declined", while
`Granules: 9/16` can. The two fixtures are also added to the test's
DROP lists, which every other fixture is in.

Co-Authored-By: Claude Opus 5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 19, 2026
… check

`Upgrade check (amd_release)` intermittently fails its `Error message in
clickhouse-server.log` sub-test on one benign line:

  <Error> StorageFileLog (test_1.filelog_bad_path_attach): The absolute data
  path should be inside `user_files_path`(/var/lib/clickhouse/user_files/)

04202_filelog_attach_path_outside_user_files has an explicit ATTACH query for a
FileLog table whose path is outside `user_files_path`. ATTACH is
LoadingStrictnessLevel::ATTACH, which is >= SECONDARY_CREATE, so the constructor
takes the relaxed branch in src/Storages/FileLog/StorageFileLog.cpp: it logs at
<Error> and returns instead of throwing BAD_ARGUMENTS. That branch is what the
test covers, since refusing to load at reattach time would break server startup.
The table outlives the test because stress threads run with a fixed
--database=test_N (ci/jobs/scripts/stress/stress.py) and clickhouse-test skips
its per-test teardown whenever --database is set, so the shared database is never
dropped. The upgrade restart re-attaches the table, the relaxed branch fires
again, and the line lands in the scanned log, where the post-restart scrub had no
entry for it.

The matcher keys on the StorageFileLog logger plus the message and carries no
table or database name, so the same message is allowlisted for any FileLog table.
The `): ` boundary keeps the discriminating cases visible: a different message
from the same logger, this message from another storage, and a Code: 36 throw of
the same text (the strict-mode path, a real failure) all still fail the job.

Validated against the failing run's own 12.6 MB clickhouse-server.upgrade.log
(PR ClickHouse#117355, sha cff5510): with the entry the scan artifact is empty, and
with it removed the artifact is the 189-byte line CI reported as the failure.

Related: ClickHouse#113781
Co-Authored-By: Claude Opus 5 <[email protected]>
alexey-milovidov and others added 2 commits September 23, 2026 20:00
It creates and drops dozens of tables, so under the flaky check with
`meta in keeper` and `s3 storage` it runs over the 180 s limit
(`Test runs too long (> 180s)`) and fails the `CH Inc sync` check.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…analysis

`DataTypeTuple::equals` ignores `hasExplicitNames` (an anonymous tuple compares
by its ordinal names), while `SerializationTuple::serializeTextJSON` writes a
named tuple as an object and an anonymous one as an array. So with a key like
`PARTITION BY toJSONString(a)` over `Array(Tuple(`1` DateTime('UTC')))`, a set
element `Array(Tuple(DateTime))` passed `equals`, was run through the key
transform under its own naming mode, and the matching part was pruned away.

`replaceNestedTypesInPair` now refuses such a pair, so an `equals`-equal pair
makes `convertColumnForDeterministicDag` decline the atom instead of mispruning.
This is only ever more conservative than before. New test `05257` covers both
mode directions with and without a timezone difference (0 rows without the
fix, the oracle's 1 with it) and proves same-mode pairs still prune.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b71bf72

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.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_release, oracle) / TLP Aggregate oracle mismatch, fuzzed query SELECT count() FROM tab__fuzz_3 WHERE hasAnyTokens(val, '') wrong results, pre-existing and unrelated to this diff: over a text index on a Nullable column the direct-read path drops the predicate's null map, so NOT hasAnyTokens(val, ...) returns the rows whose value is NULL and the three TLP branches over-count by exactly the NULL count. Reproduced on a build of master 68694750fb283, which contains none of this diff: 10000 rows / 3334 NULL, TLP sum 13334, NOT branch 10000 instead of 6666; the same NOT count answers 0 with use_skip_indexes = 0 and countIf(NOT ...) answers 0, so it is the index path, not the function #113332 (external, open)
Mergeable Check aggregator reflecting the row above #113332 (external, open)
PR aggregator reflecting the row above #113332 (external, open)

This PR's diff is KeyCondition / transformTypesRecursively timezone and tuple-naming handling, with no text-index code and no reachable path to hasAnyTokens; the fuzzed query contains no DateTime constant and no tuple comparison.

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

@alexey-milovidov

Copy link
Copy Markdown
Member

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

AST fuzzer (amd_release, oracle) reports a TLP aggregate mismatch for SELECT count() FROM tab__fuzz_3 WHERE hasAnyTokens(val, ''). That is the text-index path, not the KeyCondition timezone handling this PR changes. It may be related to #106922 (NOT hasToken over a Nullable direct read).

I merged the latest master into the branch (0940a018338). The PR files build, and 05257_keycondition_tuple_name_mode_pruning plus the non-query_log part of 05240_keycondition_dag_timezone_attribute_pruning match their references locally. The remaining open review thread is waiting on the feature owner to pick a design for the try_apply_direct_cast_fast_path fix, as explained in that thread.

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

The fix is already in progress: #113332 (open), which fixes #106922. The empty needle is incidental.

val in tab__fuzz_3 is LowCardinality(Nullable(String)). Direct read from the text index replaces NOT hasAnyTokens(val, '') with NOT CAST(__text_index_idx_hasAnyTokens_... AS LowCardinality(Nullable(UInt8))), so a NULL row reads 0 and passes the not(...) arm, while the isNull(...) arm still evaluates hasAnyTokens on val and counts the same row again.

CREATE TABLE tab (id UInt64, val LowCardinality(Nullable(String)), INDEX idx (val) TYPE text(tokenizer = 'asciiCJK', preprocessor = lower(val))) ENGINE = MergeTree ORDER BY id;
INSERT INTO tab SELECT number, if(number % 3 = 0, NULL, 'foo bar') FROM numbers(30);
SELECT (SELECT count() FROM tab WHERE hasAnyTokens(val, '')), (SELECT count() FROM tab WHERE NOT hasAnyTokens(val, '')),
       (SELECT count() FROM tab WHERE isNull(hasAnyTokens(val, ''))), (SELECT count() FROM tab WHERE NOT hasAnyTokens(val, 'foo'));
build p NOT p isNull(p) TLP sum (30 rows) NOT hasAnyTokens(val, 'foo')
master b1f44e396c4 0 30 10 40 10
same + #113332 0 20 10 30 0

The CI table shape (Array(Nullable(UInt128)) key, dictionary_block_frontcoding_compression = 1) also gives 40 vs 30 on master and 30 with #113332. Note that #113332 now conflicts with master in one hunk of MergeTreeIndexTextPreprocessor.h (c3fca9b renamed is_lower_or_upper to is_ascii_lower_or_upper); I resolved it only locally for this measurement.

@alexey-milovidov alexey-milovidov 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.

Ok, a little bit complicated though.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 3, 2026
Merged via the queue into ClickHouse:master with commit d082821 Oct 4, 2026
149 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 4, 2026
@clickhouse-gh clickhouse-gh Bot added comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-key-condition Analysis of a filter against a key. KeyCondition turns a WHERE condition into ranges over the pri... groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

WHERE d = const silently returns 0 rows over a CAST(DateTime_with_tz, 'String') primary key — data loss via granule mispruning

5 participants