Repository navigation
Conversation
`IDataType::equals` answers whether two types are interchangeable for
storage and assignment, so `DataTypeDateTime::equals` ignores the time
zone on purpose and says so in its own comment, and
`DataTypeDateTime64::equals` compares only the scale. `updateHash` does
not reach the zone either.
Constant folding replaces `toDateTime(0, 'UTC')` with a constant holding
`0` typed `DateTime('UTC')`, discarding the `'UTC'` argument node that
carried the zone. Three sites that decide whether two expressions are
the same then reuse the storage relation to answer that different
question: `ConstantNode::isEqualImpl` / `updateTreeHashImpl`,
`ActionsDAG`'s `ConstantKeyHash` / `ConstantKeyEqual`, and `matchTrees`,
which pairs an outer expression with an inner one at plan level. The UTC
and the Asia/Tokyo constant become one node, so whole chains over them
are indistinguishable while a date or time function reads the zone from
its argument's type and computes 0 and 9. Five optimizations produce
wrong results from that, in both directions: the comparison filter map
in `LogicalExpressionOptimizerPass`, the inequality chain rewritten to
`NOT IN`, `OrderByLimitByDuplicateEliminationPass` dropping a live sort
key, `ActionsDAG::deduplicateSubtrees` merging two filters, and an
aggregate projection keyed on the hour in UTC answering a query that
asks for the hour in Asia/Tokyo, which is how `matchTrees` was reached.
State the finer relation once and use it where an expression's identity
is decided. What an expression reads is the effective time zone rather
than the way it was written, so for a `DateTime` or a `DateTime64` the
relation compares the zone the type resolved at construction, which
`TimezoneMixin` supplies for a spelled out and for an omitted zone
alike; every other type is compared by `getName`, the canonical
round-trippable spelling and the only accessor that exposes the
parameters `equals` ignores. The hash splits the same two ways, because
the containers involved look a key up by hash before comparing it.
`IDataType::equals` and `IDataType::updateHash` are both left alone, so
type compatibility for reads, inserts and schema matching is unchanged,
and `ActionsDAG::Node::updateHash` already hashes the result type's
`getName` one layer down, which is why the action-name layer kept the
two constants apart while these three layers merged them.
Provenance is two-part. `matchTrees` has decided constant identity with
`equals` since 8139d7d, 2023-03-22, "Fix match for constants
with same values but different types.", so the aggregate projection
carrier is about three years old and present in many stable releases.
That commit is also the closest precedent for this one: it already
required constant identity to include type agreement, and reached for
`equals` to express it. The analyzer `AND` shapes are recent by
comparison, the comparison filter map having arrived in e6ac0ef
and first shipped in v26.7.1.1315-stable.
The same relation also feeds validation that reports a difference as an
error rather than as a slower plan: duplicate alias detection, the
`GROUP BY` key check and the `GROUPING` argument check. Two zones under
one alias are rejected there now, which is what that alias deserves,
having previously been accepted while returning a different value in
each column. A zone left out of the type means the session zone, so
leaving it out and spelling it out are one expression and those queries
keep working. One residual: the same two spellings nested inside another
type, `Nullable(DateTime)` against `Nullable(DateTime('UTC'))`, are
compared by name and stay apart, where equality and the hash agree, so
it costs a de-duplication and nothing else.
Scope. The zone difference originates in the folded constant, which is
why the fix goes there. Applying the same change to
`FunctionNode::isEqualImpl` instead was measured: it separates the
carriers that have an enclosing zone-typed function, because the
enclosing `plus` node's own result type differs, but it cannot separate
two folded constants used directly as two `ORDER BY` keys. It is a
strictly weaker seam, so `FunctionNode` stays unchanged, and so do
`ColumnNode` (name and source already discriminate), the `ActionsDAG`
function-merge loop (equivalence classes diverge once the constants do)
and `QueryNode`. The two other type comparisons in `actionsDAGUtils.cpp`
ask about monotonicity and about nullability and width preservation, not
about identity, so they are left alone too. The added test asserts that
the shapes those sites could otherwise reach are covered.
No serialized format, no persisted hash and no setting default change,
so no `SettingsChangesHistory.cpp` entry is needed.
Co-Authored-By: Claude Opus 5 <[email protected]>
`haveSameExpressionIdentity` excuses exactly one difference between two
`equals`-equal types: a time zone left out of the type, against that
same zone spelled out. A zone left out means the session zone, so both
resolve the same `DateLUTImpl` and every date or time function reading
the zone from its argument computes the same values from either.
Nothing else may take that shortcut. `SimpleAggregateFunction(any,
DateTime('UTC'))` is a `DataTypeDateTime` carrying an explicit `'UTC'`
zone plus a custom name, so it reached the shortcut and compared equal
to plain `DateTime('UTC')`, while `IDataType::updateHash` hashes
`custom_name` on that side only. Equal with different hashes is what the
declaration promises does not happen, and `ConstantKeyHash` together
with `ConstantKeyEqual` looks a key up by hash before comparing it, so
such a pair was never even compared there. A custom name is a declared
identity of its own, and it stays part of the relation because it is
already part of the hash. Both halves now skip the shortcut when either
side carries one and fall back to `getName`, which the hash reflects.
The declared name is what makes an omitted zone observable at all:
`toTypeName` reads `getName`, so an implicit `DateTime` and an explicit
`DateTime('UTC')` stay distinguishable by name even where this relation
calls them one expression. The header comment says that now, instead of
claiming the two types are indistinguishable.
`getDateLUTTimeZone` replaces the member call on `DateLUTImpl`.
`DataTypes/TimezoneMixin.h` reaches only the forward declaration through
`Common/DateLUT.h`, so the member call compiled through an unrelated
transitive include and would break the day that include is cleaned up.
The free function takes its argument by reference and returns
`const std::string &`, so it needs no complete type and builds no
string.
Two test arms, one per half of the relation: the pair under one alias is
rejected as the two expressions it is, and the pair used as two
`ORDER BY` keys stays two sort keys.
Co-Authored-By: Claude Opus 5 <[email protected]>
The expression-identity relation excuses exactly one difference between two `equals`-equal types, an omitted time zone against that same zone spelled out, and it now excuses it whether or not the type also carries a declared name of its own. A type with a declared name was routed to `getName`, and the declared name of an implicit-zone `DateTime` omits the zone, so two such types could compare equal while their effective zones differ. `SimpleAggregateFunction(any, DateTime)` is a `DataTypeDateTime` object carrying a custom name, so it took that route. The relation now requires the declared names to agree and then compares the effective zone in both cases. That keeps it a strict subset of the previous relation and keeps equality consistent with the identity hash: `IDataType::updateHash` already hashes the declared name, so appending the effective zone separates every pair the equality separates. This changes no result reachable from SQL. Restoring the previous spelling leaves all 37 arms of the new test identical, so it is a consistency guarantee for the hash containers in `ActionsDAG.cpp` and `HashUtils.h` rather than a fix. In particular it does not close an aggregate projection that answers an implicit-zone query in another zone: that reproduces identically on master and on every commit of this branch, because both sides resolve the omitted zone to the querying session and the stale hour is in the projection's stored rows rather than in the comparison. A zone reachable only through a wrapper stays outside the relation. `DataTypeNullable::equals` recurses into the coarse nested `equals` and its `updateHashImpl` forwards to a nested `updateHash` that carries no zone, so two `Nullable(DateTime)` types whose implicit zones resolved differently share both a name and a hash. Closing that needs a recursive zone-canonicalised identity for every parametric type, a core `IDataType` change of its own, and it would still not reach inside a declared name, whose interior is an opaque string. It is pre-existing: master conflates the same pair and more. New arms: a `NOT IN` rewrite liveness pair, two projection arms for a query that omits the zone, an omitted zone against that zone spelled out as one sort key, and `Bool` against `UInt8` in both the equality and the hash half. Nineteen of the thirty-seven arms fail on master.
`ActionsDAG::Node::updateHash` hashed a node's result type by its name, and the name of a `DateTime` omits a time zone that was not spelled out. A filter whose truth depends on the session time zone therefore hashed identically in every session. That hash is the query condition cache key, so a part's "no row matched in these marks" verdict computed under `session_timezone = 'Asia/Tokyo'` was reused under `'UTC'`, where the same filter matches every row, and every matching row was silently dropped. The node hash now goes through `updateExpressionIdentityHash`, so it separates two sessions exactly where the equality already did. Three sites consume this hash and all three are that cache: `updateQueryConditionCache` writes the MergeTree key, `MergeTreeDataSelectExecutor` reads it, and `FormatFilterInfo` keys file and object storage formats with it. All three are in memory and keyed by `(table_uuid, part_name, condition_hash)`, with no on-disk format and no agreement needed between nodes, so a finer hash can only turn a hit into a miss and a recompute; it can never produce a false hit. A same-session arm of the new test asserts `QueryConditionCacheHits` is still non-zero on a re-run, so the finer key is not a cache disable. `optimizeTopK` also hashes a type by its name and is left alone deliberately: it only salts entries by the TopK plan, and a `DateTime` orders by its timestamp, which no time zone changes. A predicate's own zone reaches the key through the node hash above. This is also what makes the preceding commit load-bearing rather than a consistency guarantee for the hash containers. A declared name can omit the zone just as `DateTime` does, so the type of `CAST(x, 'SimpleAggregateFunction(any, DateTime)')` is spelled identically in every session while its effective zone differs. Reverting only that commit on top of this one leaves the plain carrier fixed and reddens the declared-name carrier alone. The new test needs `auto_statistics_types = ''` on its table: the implicit per-column statistics index otherwise prunes the part before the filter runs, so nothing is ever written to the cache and neither carrier is armed. Its number is 05055 because 05053 and 05054, the next free numbers in master, are both already taken by open pull requests.
Internal review: adjudication log (click to expand)Pre-publication review over five rounds. Each round is one independent cold read of the resulting The six that changed the fix, not just the tests:
Fourteen further findings were upheld and fixed on the tests and the text: arms that asserted a Refused, with evidence:
Noted, not blocking. The node hash has two consumers besides the query condition cache, a hash Severity: Blocker / Major / Nit. DISAGREE verdicts carry recorded evidence and are terminal per Session id: cron:clickhouse-review-self-slot-58:20260830-133300 |
|
Workflow [PR], commit [fa290f3] Summary: ❌
AI ReviewSummaryThe PR makes expression identity distinguish time zones and the runtime types and layouts held by constants. On head Findings❌ Blockers
Tests
Missing context / blind spots
Final Verdict❌ Block. Preserve constant storage identity through planner action naming and add regressions for both demonstrated carriers. |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20260830-111900 |
|
cc @Avogar @yariks5s, could you review this? |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes246 object files changed (+20.97 KiB total), 0 added.
711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units3229 translation units recompiled, 17846 s compile time in total, 3229 of them have a recent master baseline. |
`haveSameExpressionIdentity` and `updateExpressionIdentityHash` looked for a time
zone on the type itself and left everything else to the declared name. A wrapper
such as `Nullable`, `Array`, `Tuple`, `Map` or `LowCardinality` keeps a nested
`DataTypeDateTime` whose omitted zone resolves to the session zone, and the
wrapper's name spells no zone out, so under a wrapper both halves were wrong, in
opposite directions.
The name is the same in every session, so the identity hash was too. That hash is
the query condition cache key, so a part's "no row matched in these marks" verdict
for `toHour(CAST(x, 'Nullable(DateTime)')) = 0` computed under `session_timezone =
'Asia/Tokyo'` was reused under `'UTC'`, where the same filter matches every row,
and every matching row was silently dropped. The new arm of 05055 reads 0 instead
of 1000000 on the preceding commit and on master.
The name also differs between an omitted zone and that same zone spelled out, so
the relation told two spellings of one expression apart. Alias analysis reports a
difference there as an error rather than as a slower plan: in a UTC session
`SELECT CAST(0, 'Nullable(DateTime)') AS a, CAST(0, 'Nullable(DateTime(''UTC''))')
AS a` raised `MULTIPLE_EXPRESSIONS_FOR_ALIAS` on the preceding commit while master
accepts it. Seven shapes measured, every one of them a regression of the preceding
commit: `Nullable`, `Array`, `Tuple`, `Map`, `LowCardinality`,
`Array(Nullable(...))` and `Nullable(DateTime64)`.
Both halves now walk `IDataType::forEachChild`, which descends the whole type, and
record one component for every type visited: the effective time zone of a temporal
type, and a name for a type whose interior this walk cannot see. The components are a
sequence and never a set, because a position is part of the type.
`Tuple(DateTime('UTC'), DateTime('Asia/Tokyo'))` and the same two zones swapped are
`equals`-equal and stay two expressions, and so do
`Tuple(Bool, UInt8, DateTime('UTC'))` and `Tuple(UInt8, Bool, DateTime('UTC'))`, whose
declared name sits at another position: a position is part of the type, and a name
read without one lets an unrelated sibling decide the comparison. Comparing a name at its own
position is also what keeps one from deciding for a zone elsewhere in the type, so
`Tuple(Bool, DateTime)` and `Tuple(Bool, DateTime('UTC'))` are one expression in a UTC
session while `Tuple(Bool, DateTime('UTC'))` and `Tuple(UInt8, DateTime('UTC'))` stay
two.
A name stands in for a zone this walk cannot reach, which is what keeps the relation
from ever being coarser than the name it refines. A zone spelled inside a declared
name is out of reach, since the interior of that name is an opaque string, and so is
a zone inside a type that keeps its nested types without handing them to
`forEachChild`: the argument types of an aggregate function and of a lambda, and a
QBit element type. So
`Tuple(DateTime('UTC'), AggregateFunction(any, DateTime('UTC')))` and the same type
with `DateTime('Asia/Tokyo')` inside the aggregate stay two expressions, while
`Tuple(AggregateFunction(any, UInt8), DateTime)` and the same type with
`DateTime('UTC')` are one, the aggregate state there carrying no zone to disagree
about. Master separates the first pair where it hashes a node, which is by name, and
joins it where it compares two types, which is `equals` alone; under one alias master
accepts it and this reports the alias as ambiguous.
`DataTypeObject::forEachChild` now walks its typed paths in sorted order, like the
name and the hash of the same type already do, and `updateHashImpl` sorts the paths
the type skips, like it already sorts the typed ones. Both sets are unordered
containers, while `equals` compares them as sets and the name sorts them, so two
objects holding the same paths are one type with one name and have to be handed out,
and hashed, in one order. Comparing the zones positionally otherwise rejected two
spellings of one type: `JSON(a DateTime('UTC'), b DateTime('Asia/Tokyo'))` and the
same two paths declared in the other order print the same `toTypeName` and raised
`MULTIPLE_EXPRESSIONS_FOR_ALIAS`; two `SKIP` paths declared in the other order are
one type by name and by `equals`, whose hash disagreed. A sort key arm reads that hash:
the two spellings collapse to one key here and stay two on the preceding commit.
The header states which way the two halves may disagree instead of claiming they agree.
`IDataType::updateHash` reads what `equals` does not, a tuple's element-name mode and an
explicitly supplied aggregate state version, so it still separates a few pairs this
relation joins: a one-element tuple whose element is named `1` against the same tuple
unnamed, and `AggregateFunction(0, any, UInt8)` against `AggregateFunction(any, UInt8)`,
which print one `toTypeName`. Both consumers look the hash up before comparing, so a hash
finer than the relation costs a de-duplication, while a coarser one would answer from
another expression's result. Tightening the relation to close that gap would reject more of
what master accepts, and hashing an aggregate state version that was left implicit would
pin the running build's default into a type's hash.
One collector feeds both halves deliberately: every round of defects fixed here was
a disagreement between the equality and the hash, so the two are not worth splitting
to save a `std::function`.
Co-Authored-By: Claude Opus 5 <[email protected]>
`updateExpressionIdentityHash` produced a whole digest of its own for every type, including one with no temporal position anywhere, so the digest of every constant moved. `CNFAtomicFormula::operator<` orders atoms by the query tree hash, which makes the order of `AND` conjuncts after CNF conversion a function of it, as the first line of `01625_constraints_index_append` records. That test read the constraint's `indexHint` conjunct last where master reads it first. Each of the three hashing sites now keeps the digest it produced before, `updateHash` or `getName`, and the helper appends the effective time zones only for a type that carries one the walk can reach. A digest is therefore either the one master produces or that one plus the zones, never a third, so the key stays at least as fine as master's where the hash alone is the key, in the query condition cache. Measured on master, on the published head and here, in `clickhouse local` with no server: only the published head departs from that test's reference, and a fingerprint of CNF conjunct order over eleven zone-free constant types is identical to master here while differing from it in six shapes on the published head. Co-Authored-By: Claude Opus 5 <[email protected]>
CI finish ledger -
|
| Check / test | Reason | Owner / fixing PR |
|---|---|---|
Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6) / Container memory budget exceeded (/docker) |
same leaf OOM as above | #117202 (external, merged 2026-08-31), absent from this tree |
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) / Container memory budget exceeded (/docker) |
/docker cgroup leaf OOM kills the concurrent shutdown gdb attaches; job ERROR, no test failed |
#117202 (external, merged 2026-08-31), absent from this tree |
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) |
same leaf OOM as above | #117202 (external, merged 2026-08-31), absent from this tree |
Integration tests (amd_tsan, 2/6) / Container memory budget exceeded (/docker) |
same leaf OOM as above | #117202 (external, merged 2026-08-31), absent from this tree |
CH Inc sync |
- | CH Inc sync (private, not actionable) |
The Container memory budget exceeded (/docker) rows are one signature, not several. The
/docker cgroup leaf that bounds the nested test containers is capped at 40.78 GiB, and
docker compose stop signals every node of a cluster at once, so each node that outlives the
60 s deadline attaches gdb at the same moment. On an ASan build each attach holds about
3.4 GiB of anonymous memory, so a nine-node cluster asks for roughly the whole leaf and the
kernel kills the debuggers. #117202 serializes that attach and is merged, but
fixpresence puts it OUTSIDE the tree this run built (compare(fix...head) reports this head
behind the fix commit 7fc3004ed25a, and the fix symbol GDB_ATTACH_LOCK is absent at
e6934a7fe1df while present at 7fc3004ed25a), so the run predates it. These rows clear when the
branch next picks master up. I am not merging master here purely to re-run CI, to keep the
review load down.
Measured caveat, stated so it is not a surprise later: on true-master trees that DO contain
#117202, the 2/6 and 5/6 shards are clean (0 of 4 post-fix trees) but 6/6 still fires
(4 of 4). So a 6/6 row may return after the master merge. That residual is tracked, and its
fixing-PR link will be posted here if it does.
All four failures are the same signature on four shards. Every other check on this head is
green, and this PR's diff is a time-zone constant-folding change in the analyzer, which cannot
reach the integration harness's cgroup sizing.
Mergeable Check, Finish Workflow and PR are praktika aggregators. They report the rows
above and carry no separate defect. Config Workflow, Style check and Code Review are all
success on this head.
Session id: cron:our-pr-ci-monitor:20260831-183000
…ession-zone-117186
A type that names no time zone means the session's, and that is not the zone the type object carries: `DataTypeFactory` hands out one cached object per type name, so the zone in it belongs to whichever session first asked for the name, while a date or time function reads the session's zone when it runs. The identity of such a type therefore has to come from the session, or `toHour(CAST(x, 'Nullable(DateTime)'))` hashes alike in two sessions that compute different values - and the query condition cache serves one session's granule verdicts to the other, dropping every matching row from its result. Closes: ClickHouse#117186
The cache is written by a query plan optimization the old analyzer never reaches, so on an old-analyzer job nothing is cached and the test's two entry counts read 0 where it expects 1. It failed 3 out of 3 reruns in Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, sequential, 1/2). Pinning costs no coverage, because an empty cache is also a cache no session can serve its granule verdicts from to a session in another time zone: measured on a pristine master binary, the first section returns the correct 100000 under the old analyzer and the wrong 0 under the new one, so only the new analyzer can see the wrong result this test guards. The sibling 05055_query_condition_cache_datetime_time_zone, and every other test asserting on this cache, pins the analyzer the same way. Co-Authored-By: Claude Opus 5 <[email protected]>
… revert The PR's sequential stateless lanes failed in 05243_query_condition_cache_top_k_parquet, a master regression from ClickHouse#123903. Master reverted it in ClickHouse#124977 (c380b02), so this merge brings the revert in. Master did not touch any file this PR changes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 1a34a69Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261010-093003 |
|
@KochetovNicolai could you review this one? Master The query condition cache case (#117186) is already fixed on master by #117803, so I updated the description to say so. |
Master reworked `ActionsDAG::Node::updateHash` into `updateOwnHash` and now hashes every string through the length-prefixed `updateHashWithString`. The PR's hunk in that function added the time zone identity after the result type name. The resolution keeps master's `updateHashWithString` for the type name and hashes the time zone identity right after it, as before. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`updateExpressionIdentityHash` returned early for a type with no zone the type-tree walk can reach,
and the argument types of `AggregateFunction` and `Function` are not children of the walk. So two
constant aggregate states that differ only in a zone were equal in the query tree hash, while
`haveSameExpressionIdentity` already told them apart through the declared name of that position.
An `IN` set is looked up by that hash alone, so two subqueries over such constants shared one set:
`number IN (SELECT toUInt64(toHour(finalizeAggregation(materialize(arrayReduce('argMaxState',
[toDateTime(0, 'UTC')], [1]))))) AS v) OR number IN (<the same with 'Asia/Tokyo'>)` over
`numbers(10)` counted 1 row instead of 2.
The gate now also looks inside those two types. A type that carries no zone anywhere keeps
exactly the digest it had, so no hash-ordered plan shape moves for it.
Tests: 05052 gains the `IN` case and the plain-constant one next to it, and the `Bool` alias case
now uses the literal `1`: `toUInt8(1)` is a function at alias collection and is refused on master
too, while `true AS a, 1 AS a` is accepted on master and refused here.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
`ColumnDynamic::updateHashFast` hashes the variant columns without their
type names, and the type of a `Dynamic` constant is just `Dynamic`, so two
constants that hold the same timestamp in different time zones got the same
`ConstantNode` tree hash. `ConstantNode::isEqualImpl` already tells them
apart (`ColumnDynamic::compareAt` compares the type names), but an `IN`
subquery's set is looked up by the hash alone (`CollectSets`), so the second
subquery reused the first one's set:
SELECT count() FROM numbers(10)
WHERE number IN (SELECT toUInt64(toHour(materialize(toDateTime(0, 'UTC')::Dynamic))) AS v)
OR number IN (SELECT toUInt64(toHour(materialize(toDateTime(0, 'Asia/Tokyo')::Dynamic))) AS v);
returned 1 instead of 2, the same for `Array(Dynamic)` and `Tuple(Dynamic)`.
Master returns 1 as well.
For a constant whose type contains `Dynamic`, also hash the value with
`updateHashWithValue`, which includes the type name of every `Dynamic` value
at any depth. A constant without `Dynamic` keeps its digest.
Reported by the automated review on ClickHouse#117161 (r4558470075).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
`matchTrees` compared two constant arguments by their `Field`, which
for a `Dynamic` value is the held value without its type. So
`toDateTime(0, 'UTC')::Dynamic` and `toDateTime(0, 'Asia/Tokyo')::Dynamic`
matched, and an aggregate projection or a sorting key built on one zone
answered a query on the other: the projection returned UTC hours for a
Tokyo `GROUP BY`, and reading in order skipped the sort for a Tokyo
`ORDER BY` over a UTC sorting key. For a constant holding a `Dynamic`
anywhere, also compare the columns, which compares the held type names
first. Other constants keep the `Field` comparison, since
`ColumnAggregateFunction::compareAt` treats every state as equal.
The query tree hash of a `JSON` constant had the same gap as `Dynamic`:
`ColumnObject::updateHashFast` hashes the path columns without the path
names, so `{"a":1}` and `{"b":1}` hashed alike and an `IN` subquery over
one reused the set of the other. Hash the value of a `JSON` constant as
well, through `updateHashWithValue`, which includes the paths.
Both were reported by the clickhouse-gh review on 478f0aa
(r4559168326, r4559168333) and are wrong on master too.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The previous commit appended the value hash after the fast hash. The
fast hash of a `JSON` column walks its path columns in storage order,
so `'{"a":1,"b":2}'::JSON` and `'{"b":2,"a":1}'::JSON`, which compare
equal, still hashed apart and stayed two sort keys. `updateHashWithValue`
is canonical for both types (the held type name plus the value for
`Dynamic`, sorted paths for `JSON`), so use it instead of the fast hash
rather than after it. Every other constant keeps the fast hash.
Found by the second-model review of the previous commit.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
`Field` drops the type a `Variant` or `JSON` value holds, as it does for
`Dynamic`: `[toDateTime(0, 'UTC')::Variant(DateTime('UTC'), Bool)]` and
`[false::Variant(DateTime('UTC'), Bool)]` are both `[UInt64(0)]`, and a
`JSON` path holding the `Date` 2020-01-01 or the `DateTime`
1970-01-01 05:04:22 is `UInt64(18262)` either way. Their declared types
are identical, so `matchTrees` matched them: the minmax and count
projection answered a query on the partition key with the other
constant's value, and reading in order over a sorting key with the other
constant returned unsorted rows (a `LOGICAL_ERROR` from
`checkVirtualRowBoundary` in debug builds). All of it is wrong on master
too.
Extend the column comparison added for `Dynamic` to every constant with a
`Dynamic`, `Variant` or `JSON` anywhere in its type. `ColumnVariant` and
`ColumnObject` compare the held discriminator or path type first, and the
`Field` comparison still runs before it, so aggregate states stay
compared by value.
Reported by the clickhouse-gh review on ac7e066 (r4560264082). Also
rewords three test comments that called test cases "arms".
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The `JSON` sorting-key case in 05052 asserts only the rows, which a fallback sort also gets right, so it would not notice in-order reading of `JSON` constants silently turning off. Assert `Read type: InOrder` for the table's own sorting expression, as the `Variant` case does. Found by the second-model review of the previous commit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`ColumnVariant::updateHashFast` hashes the local discriminators and the columns in their local order, but not the mapping to the global ones. A `CAST` that widens a `Variant` keeps the local order, so `toDate(0)::Variant(Date)::Variant(Date, UInt16)` and `0::UInt16::Variant(UInt16)::Variant(Date, UInt16)` had one query tree hash. `CollectSets` looks a subquery's set up by that hash alone, so two `IN` subqueries over them shared one set and the rows of the other were dropped: count 1 instead of 2 with default settings, the same for two zoned `DateTime` members under `allow_suspicious_variant_types`, and for both nested in a `Tuple`. Master gives 1 as well. `updateHashWithValue` hashes the global discriminator. Which constants need it is now one function, `holdsATypeOfItsOwn`, shared by the constant hash and by `matchTrees`, which already compared the columns of such constants. Reported in ClickHouse#117161 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
The previous round hashed these constants with `updateHashWithValue`, which
has two defects as an identity: it concatenates JSON paths, type names and
values with no lengths, so `{"a":7161677110969590627,"b":2}` and
`{"aInt64ccccccccb":2}` feed SipHash the same bytes, and it ignores where a
value is stored, which `JSONDynamicPaths` and `isDynamicElementInSharedData`
return. `CollectSets` reuses a set by hash alone and the logical optimizer
merged the two operands of an `AND`, so both returned wrong results on the
previous head while master did not. `matchTrees` and the constant
deduplication of `ActionsDAG` compare with `Field` / `compareAt`, which have
the same blind spot for storage: the `_minmax_count_projection` answered a
partition key built from the same JSON stored the other way, and two filters
merged into one DAG shared one of two such constants (both wrong on master
too).
The Native format is read back into the same column, so for one type equal
bytes mean one value stored one way. `haveSameStoredValue` and
`updateStoredValueHash` compare and hash those bytes. For a type that
`holdsATypeOfItsOwn`, the constant tree hash, `matchTrees` and
`ConstantKeyEqual` use them; other constants keep the fast hash and `Field`.
`ConstantNode::isEqualImpl` keeps comparing values, as on master: the bytes
also carry types and paths a column can hold but this row does not use, so
comparing them there rejected `arrayElement([toUInt8(1)::Dynamic, 'a'::Dynamic], 1) AS a,
toUInt8(1)::Dynamic AS a` with MULTIPLE_EXPRESSIONS_FOR_ALIAS. A tree hash that
tells more apart than `isEqualImpl` is what master already has with the fast
hash; it costs at most a missed deduplication. Native writes paths in sorted
order, so the same object written with its keys in another order is still one
sort key.
05052 gets the two hash-only `IN` cases from the review, the `AND` case, a
`Dynamic` value in and out of the shared variant, both in merged filters, a
partition key built from a `JSON` value stored the other way, the duplicate
alias above, and liveness checks that the projection is still used for the
table's own layout and for an omitted zone under a session in the
projection's zone.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
… Native bytes
`ActionsDAG::Node::updateOwnHash` hashed a constant's value with
`updateHashWithValue`, which leaves out whether a `Dynamic` value sits in
the shared variant. Two such constants that a planner names alike then gave
one DAG hash, and the query condition cache, keyed by that hash alone,
served the first query's granule verdicts to the second:
`isDynamicElementInSharedData(materialize('a'::Dynamic(max_types=1))) != x`
followed by the same filter over
`arrayElement([1, 'a']::Array(Dynamic(max_types=1)), 2)` returned 0 rows
instead of all of them. Measured identically on master 21809ea and on the
previous head.
Such a constant is now hashed with `updateStoredValueHash`, the identity
the query tree hash, `matchTrees` and the constant key of the expression
merge already use. Every other constant keeps its digest, and the gate
that leaves a large or aggregate-state value out of a cache key is
unchanged. 05055 gains the two queries, plus a control that the repeated
first query still hits the cache.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
| constant_value.getColumn()->updateHashFast(hash_state); | ||
| /// The fast hash can leave out the type such a value holds. | ||
| if (holdsATypeOfItsOwn(*constant_value.getType())) | ||
| updateStoredValueHash(*constant_value.getType(), constant_value.getColumn()->getDataColumn(), hash_state); |
There was a problem hiding this comment.
[Blocker] Preserve stored-value identity in planner action names too
The new hash separates these constants, but PlannerActionsVisitor still names them through ConstantNode::getValueName and reuses the first addConstantIfNecessary entry by name alone. ColumnDynamic::getValueNameImpl renders shared and ordinary variants identically, so the second constant disappears before the updated DAG hash/comparison can help.
Reproduced on the Fast test binary for fa290f383beb (build ID c492d0fa24a4f00c7fb946d499db6c57406b22b7):
SELECT count() FROM numbers(1)
WHERE isDynamicElementInSharedData(
materialize('a'::Dynamic(max_types=1))) = 0
AND isDynamicElementInSharedData(materialize(
arrayElement([1, 'a']::Array(Dynamic(max_types=1)), 2))) = 1;This returns 0, although both conditions independently hold and the expected count is 1. Selecting the two functions together gives false, false; the second alone gives true. EXPLAIN actions = 1 shows one constant and one function serving both expressions.
The same path affects long JSON constants with default settings: IColumn::getValueName switches to updateHashWithValue above optimize_const_name_size = 256, again discarding layout. Reversing the keys of {"a":"<300 x characters>","b":2} with JSON(max_dynamic_paths=1) makes both JSONDynamicPaths calls return ['a'] instead of ['a'], ['b'].
Please carry the shared representation-aware identity into planner constant/action naming, including the size-limited hash path, and add a same-DAG regression. The merged-filter tests build separate DAGs and miss this remaining instance of the identity problem.
There was a problem hiding this comment.
Not changing this here: both cases give the same result on master 21809eaaa93e (0, and ['a'] ['a']), and they come from the planner's constant naming (PlannerActionsVisitor, IColumn::getValueName), which this PR does not touch. In both, the two constants are equal values that differ only in where they are stored.
|
Dear @yariks5s, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
Related: #117186 (fixed on master by #117803)
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results when one query used two
DateTimeorDateTime64constants holding the same value but declaring different time zones, such astoHour(toDateTime(0, 'UTC') + x) = 0 AND toHour(toDateTime(0, 'Asia/Tokyo') + x) = 9. Query analysis treated them as one expression, so a conjunction of two true conditions could evaluate to false and silently drop matching rows, the reverse could return non-matching rows, a duplicate-elimination pass could drop a liveORDER BYkey, and an aggregate projection or a sorting key read in order, built on the hour in one zone, could answer a query asking for another.Description
p = 1,q = 1,p AND q = 0. As aWHEREclause this drops every matching row.IDataType::equalsanswers storage interchangeability and ignores theDateTimezone. Foldingmoves the zone into the type, and four sites deciding expression identity reuse it:
ConstantNode,ActionsDAG's constant key, its node hash, andmatchTrees. The two constantsbecome one node while a date or time function reads the zone from its argument and computes 0
and 9. Five optimizations turn that into wrong results.
The fix states the finer relation once in
IDataTypeand uses it at those sites: every temporalposition of a type, at any depth, by the effective zone
TimezoneMixinresolved, spelled out oromitted, plus a declared name at its own position. A zone out of reach, inside a declared name's
opaque interior or inside a type that keeps its nested types to itself, is compared through that
position's own declared name; a pair carrying no zone at all is left to
equals.equalsandupdateHashare untouched. TheANDshapes shipped in v26.7.1.1315-stable, theprojection shape in 8139d7d.
Validation and blast radius
Two zones under one alias, or a group key in another zone, are now rejected; they were accepted
while returning a different value per column. One zone written both ways stays one expression,
under a wrapper as well; a custom-named type, or one whose zone sits inside an aggregate function
state, is not joined with another spelling, also not where an
INsubquery's set is looked upby its hash alone. A
Dynamic,VariantorJSONconstant's query tree hash is the hash of its Native bytes, which cover thetype a
Dynamicvalue holds, the member aVariantis, the paths of aJSONone and where each is stored, which the column's fasthash can leave out, so two zones inside
Dynamicor a widenedVariant, and two differentJSONobjects or layouts, keep their ownINsetstoo.
matchTreesandActionsDAG's constant key compare those bytes as well, so a projection, apartition key or a sorting key built on one zone inside
Dynamic, oneVariantmember or oneJSONpathtype or layout does not answer a query on another, and merged filters keep two such constants apart. The node hash, which keys the query condition cache, hashes those bytes too. Unchanged: a projection whose key omits the zone
answers with the hour its rows were written with.
The node hash is also the query condition cache key. Since #117803 that key carries
session_timezone, which fixes the cross-session cache case (#117186) on master by itself, forevery wrapper;
05055and05186now pass on master and stay as regression tests. The hash's other consumers, a size hint and a join condition hash, live inmemory and are keyed consistently on write and read, so a finer key only costs a recompute.
No test regresses: across 1034 analyzer, optimizer, projection and time zone tests and all 176
query condition cache tests, the set failing on the fix is a subset of the set failing on base,
compared by reason rather than by name. My two tests, 05052 and 05055, pass 50 of 50
randomized runs; 05052 still fails on master. 05186 arrived with the fix for #117186;
it needs
enable_analyzer = 1because the query condition cache is written by a planoptimization the old analyzer never reaches, so on an old-analyzer job it holds nothing and
the test's entry counts read 0. Pinning costs no coverage there: measured on a pristine master
binary, that test's first section returns the correct answer under the old analyzer and the
wrong one under the analyzer, so only the analyzer can reach the wrong result it guards.
A type with no zone in it keeps the digest each site already produced for it, apart from a
Dynamic,VariantorJSONconstant's query tree hash (above) and the canonicalization below, so nothing derived from that digest moves;ANDconjunct order after CNFconversion is one such thing.
One canonicalization is deliberate and not about zones: a
JSONtype's paths to skip are anunordered set, and sorting them, so that two objects holding the same ones hash alike, moves
such a type's digest even when it carries no zone.
The identity hash still separates a few pairs the comparison joins: it reads a tuple's
element-name mode, an explicitly supplied aggregate state version, and how a
Dynamic,VariantorJSONcolumn stores a constant. That direction only costsa de-duplication or a cache hit.
Related: #92208 (open, different mechanism), #105987 (also edits
ConstantKeyEqual), #113781(same family).
A type that spells no zone out is a case of its own:
DataTypeFactoryhands out one cached object per type name, so the zone the object carries belongs to whichever session first asked for that name, while a date or time function reads the session's zone when it runs. The identity of such a type therefore comes from the session, which is what makestoHour(CAST(x, 'Nullable(DateTime)'))a different expression in a session with a differentsession_timezone- the query condition cache used to serve one session's granule verdicts to the other and drop every matching row from its result (#117186).Workflow [PR]
Sync PR [sync-upstream/pr/117161]