Repository navigation
Send a DateTime constant to a secondary server as an exact instant - #117837
alexey-milovidov merged 5 commits into
Conversation
A folded DateTime constant was serialized into the query text sent to another
server as local date-time text. Two distinct UTC instants inside a DST
fall-back overlap share one such text, so the receiving side re-parsed the
earlier one and the query succeeded while returning the wrong rows:
SELECT toUnixTimestamp(dt), tag FROM remote('127.0.0.1:9000', db, 'dst')
WHERE dt = toDateTime(1698541800, 'Europe/Berlin')
SETTINGS prefer_localhost_replica = 0;
-- 1698538200 CEST-early <- one hour early
-- single node: 1698541800 CET-late
The wire text was _CAST('2023-10-29 02:10:00', 'DateTime(\'Europe/Berlin\')').
Measured lossy the same way: a Distributed engine table, dt IN (<const>), and
a DateTime leaf under Array / Tuple / Map key or value / Nullable / a typed
JSON path, each also under serialize_query_plan = 1. The defect is
analyzer-only; enable_analyzer = 0 was already correct.
getFieldFromColumnForASTLiteralImpl rendered a DateTime leaf with
serializeText. Its sibling DateTime64/Time64 case already answers a flag
introduced for exactly this hazard, whose comment notes that a bare number
round-trips losslessly and is unambiguous across DST overlaps; the
Date/Date32/DateTime case ignored it. The second walker,
columnConstantToExactLiteralASTImpl, hands every decimal-free subtree to that
same path, so a DateTime sharing a constant with a decimal leaf was affected
too.
A DateTime leaf is now rendered as its raw Unix timestamp in both walkers,
propagated by every branch and cleared wherever the consumer infers the type
from the literal instead: the plain walker's Variant recursion (which emits no
member cast, so a bare number there is CANNOT_CONVERT_TYPE), both Dynamic
recursions, dynamic JSON paths, shared data and JSON object names.
Date and Date32 keep their text form, which round-trips exactly.
ConvertToASTOptions::date_time_constants_as_numbers defaults to true rather
than being opted into per call site: a census of the toAST call sites found
four separate shard-bound conversions, so an opt-in list is one the next
change falls off silently. The single consumer that parses the text itself,
the external-database pushdown, clears it; deleting that opt-out was confirmed
to make TransformQueryForExternalDatabase.Issue7245 fail with
("create_time" > 1545699723) in place of the expected quoted text.
ReadFromRemote's exact-serialization branch passes the flag too, so it now
agrees with its own else branch, which already preferred the raw field for
this hazard.
Four statements are appended to 03381_remote_constants, one per code branch
the fix touches plus an in-range control pinning the other instant of the same
overlap. The lambda inside arrayMap is load-bearing: toUnixTimestamp(<const>)
folds on the initiator and would assert nothing. The 42 pre-existing reference
lines are unchanged.
Not fixed here: a DateTime inside a decimal-free Variant still crosses as
text, because that walker returns a Field and cannot emit the member-type cast
a bare number would need there.
Co-Authored-By: Claude Opus 5 <[email protected]>
The previous commit on this branch changed six code paths but shipped arms for only three of them. `03381_remote_constants` now also covers: * `ConstantNode::toASTImpl`'s cast-free `IN` exit, which emits a bare tuple with no `_CAST` around it, so the receiving server takes the set element type from the left-hand expression instead of from the literal. It is reached by an `or` chain of three equalities, which `LogicalExpressionOptimizerPass` folds into an `in` whose right operand is built with the `ConstantNode(value, type)` constructor and therefore has no source expression. A hand-written `dt IN (<const>)` leaves through the `_CAST` exit instead, because a folded `toDateTime` constant does have one. * the exact walker's `Object` branch, which needs a `Decimal64` sibling path to be entered at all: `typeMayContainDecimal` is false for a `JSON` whose only typed path is a `DateTime`, so the existing `JSON` arm reaches the plain walker. * the exact walker's `Variant` branch, which needs the `Decimal64` to be a member of the `Variant` itself rather than a sibling of it, and is the only one of the three that wraps the value in a cast to the member type. Each arm was confirmed to reach its branch by reading the query text the receiving server logged, not by inferring it from the shape. Also names `JSONExtractTree`'s per-type nodes as the reader of a bare number in a typed `JSON` path, since `SerializationJSON` routes the document through them, so neither serializer the comment previously named is on that path.
…orwards Arm 5 of `03381_remote_constants` asserts the value an `or` chain of three equalities produces, but not the shape that value depends on. It reaches the cast-free literal exit only while `LogicalExpressionOptimizerPass` folds that chain into one `in`. If the fold stops happening, the three surviving `equals` each render their constant through the already covered `_CAST` exit and the arm still prints the same result, so the coverage would lapse with nothing red. An `EXPLAIN QUERY TREE` assertion now pins the `Tuple(DateTime(...))` constant that pass builds with the `ConstantNode(value, type)` constructor, which is the node that carries no source expression and therefore takes that exit. Raising `optimize_min_equality_disjunction_chain_length` by one turns the assertion to 0, which is what keeps it from holding for the wrong reason. It matches on a binary without this branch's fix too, since the fold is orthogonal to what the fix changed. Two flag forwards in `getFieldFromColumnForASTLiteralImpl` also had no arm. A `Map` nested in an `Array` holding a `Nullable(DateTime)` covers the map recursion and the nullable recursion in one statement. Giving a map a `Decimal64` value instead routes it into exact serialization, where the key is its own recursion; that arm projects the decimal next to the key, so an edit that "fixes" the key by breaking the decimal path reddens the same line. The exact walker's own `Nullable` recursion is unreachable for a `DateTime` leaf and deliberately has no arm: exact serialization short-circuits when the type contains no decimal-backed leaf, which `Nullable(DateTime)` does not, so that recursion is entered only for `Nullable(Decimal)`, `Nullable(DateTime64)` and `Nullable(Time64)`. Each arm was confirmed to reach its intended branch by reading the query text the receiving server logged, not by inferring it from the type: the map and nullable arm crosses as a bare nested literal, the decimal-keyed arm as `array(map(...))` function calls. Also backticks one literal type name in a comment of the same block, which the lines below it already did. Co-Authored-By: Claude Opus 5 <[email protected]>
…me forwards
Correction to `ee745bffc8c2177`: its message claims the exact walker's `Nullable`
recursion is unreachable for a `DateTime` leaf, entered only for
`Nullable(Decimal)`, `Nullable(DateTime64)` and `Nullable(Time64)`. That is wrong.
`DataTypeNullable::forEachChild` recurses into the type it wraps, so
`typeMayContainDecimal(Nullable(Tuple(DateTime, Decimal64)))` is true, the
decimal-free short-circuit does not fire, and the recursion does forward the flag
down to a `DateTime` leaf. Only the narrower statement holds: a
`Nullable(DateTime)` nested inside an exact carrier short-circuits into the plain
path, which is what the earlier measurement covered.
Three flag forwards changed here therefore had no arm, and flipping any of them to
`false` left every existing arm green: the exact walker's `Nullable` recursion, its
`Map` value recursion (the earlier arm pins only the key, whose value is a bare
`Decimal64`), and the plain walker's `Map` value recursion inside a `JSON` typed
path. One new arm reaches each, confirmed by reading the query text the receiving
server logged instead of inferring the route from the type.
The predicate-AST pushdown had no `DateTime` arm either. The
`DateTime('Europe/Berlin')` case already in
`04409_distributed_filter_pushdown_exact_decimal` carries no decimal, so it leaves
through the raw-literal branch this change does not touch. A `Decimal64` sibling
selects the exact serialization of the whole carrier instead. The column is a whole
`Tuple`, because an equality between two tuple constructions is split into
per-element comparisons before it is pushed, which sends each leaf on its own. The
value alone would be a blind oracle, since a pushdown that declines leaves the
filtering to the initiator and returns the right row anyway, so the arm also
asserts that the carrier appears in the text each shard was sent, and that it is
absent with the pushdown off.
Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model reviewReviewed cold by a second model over four rounds before publishing. No behaviour change was asked Validation: both test files fail on the base binary and pass on the fixed one, and each new arm was |
|
cc @KochetovNicolai @CurtizJ, could you review this? A folded |
|
Workflow [PR], commit [5ea7ae9] Summary: ✅
AI ReviewSummaryThis PR fixes analyzer-side distributed query serialization for Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit 5ea7ae9.
Changed lines: Changed C/C++ lines covered: 138/140 (98.57%) · Uncovered code |
|
This fixes #117835, filed this morning on exactly this mechanism ( I audited the patch source-side (the PR ARM build was not published yet at the time of writing); the census claims check out:
One nit on the changelog entry: |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units894 translation units recompiled, 6275 s compile time in total, 893 of them have a recent master baseline. |
|
Added: You audited before a build was published, so I ran your rig against this head's binary (build id
Shard query text for the first leg: On the |
The exact-serialization walker renders a `DateTime` leaf as local date-time
text, and two instants share one such text across a DST fall-back overlap, so
the receiving server re-parses the earlier one. Admitting `Variant` to that
walker makes compounds like `Tuple(DateTime, Variant(UInt64, String))` reach it
instead of failing with `CANNOT_CONVERT_TYPE`, which turns an error into a value
one hour early. Measured on a query that is correct on a single node:
SELECT toUnixTimestamp(t.1)
FROM (SELECT (toDateTime(1698541800, 'Europe/Berlin'),
42::UInt64::Variant(UInt64, String)) AS t
FROM remote('127.0.0.1:9000', system.one))
SETTINGS prefer_localhost_replica = 0;
-- 1698538200 <- one hour early
-- single node: 1698541800
A consumer that re-applies the constant's declared type now asks for the raw
Unix timestamp. The leaf names its own type, so the value is exact with no
enclosing cast, which is the form the `Variant` member branch already emitted. A
consumer that suppresses the cast keeps the text form, because it may parse that
text itself, as the external-database pushdown does.
`Dynamic`, shared data and `JSON` paths keep the text form for a second reason:
the value's type is inferred from the literal there, so a bare number would be
read back as a number. Both were measured identical either side of this change,
as was an ordinary `Tuple(DateTime, UInt64)`, which never reaches this walker
and still loses the hour through the plain literal path. ClickHouse#117837 fixes that path
and carries the same rendering behind a `ConvertToASTOptions` field, so whichever
of the two merges second keeps one copy.
Reported by @ zlareb1 on the pull request.
Co-Authored-By: Claude Opus 5 <[email protected]>
The `OR`-to-`IN` rewrite builds a constant whose enclosing cast
`FunctionNode::toASTImpl` suppresses, and that AST still goes to a ClickHouse
shard, so tying the rendering to `add_cast_for_constants` left the leaf as
ambiguous local date-time text there. Measured on a
`Tuple(DateTime('Europe/Berlin'), Variant(UInt64))` column holding both instants
of a Berlin DST fall-back overlap: a three-way equality chain matches one row on
a single node and none of them through `remote`.
`ConvertToASTOptions::date_time_constants_as_numbers` carries the answer instead,
and only the external-database pushdown clears it, because that consumer parses
the text itself. The field, its comment and the pushdown hunk are byte-identical
to ClickHouse#117837, which adds the same field for the plain literal walker, so the two
merge without a conflict.
Also narrows the helper's wrapper list: an `Object` renders its subtree as JSON
text, whose tokens carry no discriminator, so a `Variant` below it keeps the
plain form rather than being named.
Co-Authored-By: Claude Opus 5 <[email protected]>
CI finish ledger - d490df9Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260903-150000 |
…17837 ClickHouse#117837 merged the DateTime-as-exact-instant work this branch also carried, and landed all six of the source files touched here, which is what made the branch conflict. Its ConvertToASTOptions::date_time_constants_as_numbers option, the plumbing through both walkers and the external-database clear are taken from master, so IQueryTreeNode.h and transformQueryForExternalDatabaseAnalyzer.cpp are now byte-identical to it, and the exact walker no longer needs a DateTime case or a typeMayContainDateTime predicate of its own: a DateTime leaf inside a Variant-carrying compound is already rendered as a raw timestamp by getFieldFromColumnForASTLiteral. What remains here is the nested-Variant fix. typeMayContainDecimal becomes typeNeedsExactLiteralSerialization and answers for Variant too, so a Variant below the top level of a constant reaches the exact walker at all; that walker names the active member type and the whole Variant; and the top-level-only Variant branch of ConstantNode::toASTImpl becomes redundant and is removed. 05059 keeps its 16 arms. Its OR-to-IN plan oracle now matches the rendering the merged option produces, a raw timestamp for the DateTime sibling rather than a per-leaf cast.
Two conflicts in `convertColumnToType`, both because ClickHouse#117837 landed `resolveActiveAlternativeType` on master after this branch was cut. That change reads the active alternative's type back from a `Variant`/`Dynamic` column and passes it as the source type of the delegated `convertFieldToType`, so a `Variant` SOURCE is now faithful. This branch is the other direction, a `Variant` TARGET, and both are kept: the anonymous namespace now holds `resolveActiveAlternativeType` alongside `carriesAmbiguousVariant`, `variantAlternativeIsChosenByType` and `tryConvertVariantColumnNative`, and `convertColumnToTypeOrNull` runs the column-native `Variant` path before falling back to the `Field` path that resolves the alternative. The header's two paragraphs conflicted for the same reason: this branch still carried the pre-ClickHouse#117837 claim that a `Variant` source is unrecoverable, which is now false. Master's paragraph and its `Array(Dynamic)` composite limitation are kept, the stale claim is dropped, and the `Variant` target divergence stays. The rewrite in `LogicalExpressionOptimizerPass` merged cleanly on top of ClickHouse#117854, which renamed the `in` family the passes emit by `transform_null_in`; the merged sites keep that name lookup. Co-Authored-By: Claude Opus 5 <[email protected]>
Closes: #117835
Related: #116537
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results for a distributed query whose folded constant contains a
DateTimevalue. Such a constant was serialized into the query text sent to a secondary server as local date-time text, which two distinct instants share across a DST fall-back overlap, so the receiving server re-parsed the earlier instant and the query returned the wrong rows. ADateTimeconstant is now sent as its raw Unix timestamp wherever the receiving side re-applies the literal's declared type.Date,Date32and query text built for an external database are unchanged.Description
SELECT ... FROM remote(...) WHERE dt = toDateTime(1698541800, 'Europe/Berlin')returns the wrong row (1698538200, one hour early). Both instants format to the local text2023-10-29 02:10:00, the Berlin DST fall-back hour, and that ambiguous text is what crosses the wire. Also lossy: aDistributedtable,dt IN (<const>), and aDateTimeleaf underArray/Tuple/Mapkey or value /Nullable/ a typedJSONpath, each also underserialize_query_plan = 1. Analyzer-only:enable_analyzer = 0is correct.Root cause: in
src/Analyzer/Utils.cppthe constant-serialization walker renders aDateTimeleaf withserializeText. The siblingDateTime64/Time64case already carries a flag added by #95055 for exactly this hazard; theDate/Date32/DateTimecase ignored it.Both serialization walkers now render a
DateTimeleaf as its raw Unix timestamp, except where the type is inferred from the literal instead (Variantin the plain walker,Dynamic, dynamicJSONpaths, shared data,JSONobject names). The newConvertToASTOptions::date_time_constants_as_numbersdefaults totrue, because a census of thetoASTcall sites found four shard-bound conversions; the one consumer that parses the text itself, the external-database pushdown, clears it.DateandDate32keep their text form, which round-trips exactly.#116537 reports this same bare-number form rounding a
DateTime64leaf throughFloat64. A plainDateTimeis not exposed to that: a typed path reads a non-negative integer as a Unix timestamp directly, and4294967295is exact in adoubleanyway.Not fixed here: a
DateTimeinside a decimal-freeVariantstill crosses as text; that walker returns aFieldand cannot emit the member-type cast a bare number would need there. My #117831 reworks the same walker and closes that case.Side effect: a receiving server's
system.query_lognow shows_CAST(1698541800, ...)instead of the date-time text.Workflow [PR]
Sync PR [sync-upstream/pr/117837]