Skip to content

Fix wrapped Time64 values from an overflowing scale conversion in convertFieldToType - #114546

Merged
vdimir merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-time64-convert-field-scale-overflow
Aug 13, 2026
Merged

vdimir merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-time64-convert-field-scale-overflow

Conversation

@groeneai

@groeneai groeneai commented Aug 12, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #94537
Related: #111534

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):

Fixes incorrect, often sign-flipped, Time64 literals and IN-list constants produced when rescaling a lower-scale Decimal64 overflowed Int64. Such a conversion now reports DECIMAL_OVERFLOW, matching the DateTime64 branch and explicit CAST.

Description

convertFieldToTypeImpl rescales a Decimal64-backed field into a Time64 column at src/Interpreters/convertFieldToType.cpp:473-476. The scale-increasing arm multiplied without a range check, so value * scale_multiplier_diff could exceed Int64 and wrap. The wrapped product was then handed to decimalFromComponentsWithMultiplier<Time64>(value, 0, 1), whose own mulOverflow check is a no-op at multiplier 1, so the corrupted value became the field.

Observed on master (bb1bd307): Values 'x Time64(6)' (253402207200000::Decimal64(0)) returned -999:59:59.722624, and INSERT persisted it. The wrapped Int64 of 253402207200000 * 1000000 is -4852209831933722624, which renders as exactly that; the negated input wraps to +4852209831933722624, so a negative input returned a positive time. Explicit CAST(... AS Time64(6)) already reported DECIMAL_OVERFLOW here, so the literal path disagreed with CAST.

The file carried this same statement twice, for DateTime64 and Time64, both unguarded. The related PR above guarded the DateTime64 one and added test 03797; its Time64 twin was left as it was. This change mirrors that guard onto the twin. The operand also becomes Int64, which the guard requires: mulOverflow on an unsigned operand reports overflow for every negative value, which would reject in-range negative times.

Reporting rather than returning Null matches the DateTime64 twin, which 03797 asserts, and explicit CAST. The neighbouring Date32 branches keep their Null contract and are untouched.

Found by a UBSan signed-overflow report on this line; there is no open issue for it. It keeps reproducing on master, in both asan_ubsan stress jobs, as signed integer overflow: 253402239600000 * 1000000 cannot be represented in type 'long' at src/Interpreters/convertFieldToType.cpp:475:

Only inputs that were producing wrong values change: 9223372036854 at scale 6, the largest whose rescale still fits, is still accepted and returns 999:59:59.000000 identically. Verified by building both arms and diffing: every overflow arm goes from a wrong value to DECIMAL_OVERFLOW, while 30 in-range controls across scales 0/3/6/9, both signs and both scale directions are byte-identical. 03797 and 04837 still pass. New test 04883 fails on master and is green here over 100 randomized runs.

… overflow

The Time64 <- Decimal64 branch of convertFieldToTypeImpl rescaled the source
value with an unchecked multiply, so a value above INT64_MAX / scale_multiplier
wrapped. The wrapped product was then handed to
decimalFromComponentsWithMultiplier<Time64>(value, 0, 1), whose own mulOverflow
check is vacuous at multiplier 1, so the single downstream guard could not catch
it and the corrupted value became the field. Values 'x Time64(6)'
(253402207200000::Decimal64(0)) returned -999:59:59.722624, a positive input as
a negative time, and INSERT persisted it; the IN-set path silently matched
nothing. Explicit CAST to Time64 already reported DECIMAL_OVERFLOW for the same
input, so the literal path disagreed with CAST.

This file carried the same statement twice, for DateTime64 and Time64, both
unguarded. 2f482ef guarded the DateTime64 one
with Int64 + common::mulOverflow + DECIMAL_OVERFLOW and added test 03797,
leaving its Time64 twin below untouched. Mirror that guard here so the two
branches agree.

The operand also becomes Int64, which the guard requires: common::mulOverflow on
an unsigned operand reports overflow for every negative value, so keeping UInt64
would reject in-range negative times. The previous UInt64 was not itself losing
information, since the helper takes const Int64 & and the conversion is modular.

Only inputs that were producing wrong values change behaviour. The largest value
whose rescale still fits, 9223372036854 at scale 6, is still accepted and
returns 999:59:59.000000 exactly as before; 9223372036855 is now reported.
Verified by building both arms and diffing them: every overflow arm goes from a
wrong value to DECIMAL_OVERFLOW while thirty in-range controls across scales
0/3/6/9, both signs and both scale directions are byte-identical. Tests 03797
and 04837 pass unchanged; the deliberately-Null Date32 branches are untouched.

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

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

Two independent cold reviews plus two second-model gate passes, adjudicated before publishing.
The code, the test and the validation were accepted unchanged in both rounds. Everything found
was in the PR-facing text.

# Finding Verdict
❌ 1 A draft claimed the pre-existing const UInt64 operand "lost the sign" and attributed the sign-flipped output of a negative input to that. False: the helper takes const Int64 &, so the round trip is modular and value-preserving, and the overflow wrap alone accounts for both observed values exactly (253402207200000 * 1000000 wraps to -4852209831933722624, the negated input to +4852209831933722624). The 30 in-range controls include three negatives and are byte-identical between the two binaries, which is what settles it. Int64 is still required, for the reason now stated: mulOverflow on an unsigned operand reports overflow for every negative value, so keeping UInt64 would reject in-range negative times. AGREE, rewritten
❌ 2 A draft claimed the Time64 branch was "added later as a copy" of the guarded DateTime64 statement. The order is the reverse: the Time64 branch is from 2025-03-03, the DateTime64 guard from 2026-01-18, and the guard commit does not touch Time64. The file already carried the identical unguarded statement twice; one was guarded and the other was left as it was. Corrected, and the line-distance number dropped. AGREE, rewritten
❌ 3 The validation-gate table above still carried that dropped line-distance number in row (c), and it was wrong in either revision (the two guards are 32 lines apart now, 19 in the pre-fix parent). Caught by re-checking the artifact itself rather than the previous round's summary of it. AGREE, corrected
⚠️ 4 The changelog entry was past tense; docs/changelog_entry_guidelines.md asks for present tense and names that exact form as its counter-example. Related pull requests were referenced inline in prose rather than as full URLs on relationship lines. AGREE, fixed
⚠️ 5 The description had been revised after the gate pass that certified it, so the reviewed contract and the publishable one were not the same text. Re-gated against the frozen description: same tree, same patch-id, zero findings. AGREE, re-gated
💡 6 The body did not say why this path reports instead of returning Null, given the neighbouring Date32 branches were changed to Null shortly before, and did not state provenance. Both added. AGREE, added
💡 7 An earlier draft of the validation-gate table miscounted the new test's arms (9 and 8, not 8 and 6). AGREE, corrected

Reviewer never edits source: the tree is byte-identical to what the gate reviewed, verified by
tree hash and patch-id across both rounds.

Session id: cron:clickhouse-review-slot-10:20260812-205500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on demand: clickhouse local -q "select * from format(Values, 'x Time64(6)', '(253402207200000::Decimal64(0))')" returns -999:59:59.722624 on master. Not a probabilistic repro.
b Root cause explained? Yes. The Time64 <- Decimal64 branch multiplied by scale_multiplier_diff unchecked, so the product could exceed Int64 and wrap. The wrapped value was then passed to decimalFromComponentsWithMultiplier<Time64>(value, 0, 1), whose own mulOverflow check is a no-op at multiplier 1, so the only downstream guard cannot catch it. The wrap alone accounts for both observed values, in both signs: 253402207200000 * 1000000 wraps to -4852209831933722624 (-999:59:59.722624) and the negated input to +4852209831933722624.
c Fix matches root cause? Yes. The guard is at the overflowing statement itself, mirroring 2f482efc1, which applied the identical Int64 + common::mulOverflow + DECIMAL_OVERFLOW remedy to the same statement for DateTime64 in the branch above. No widened bound, no tag, no downstream defensive check.
d Test intent preserved / new tests added? Yes. No existing test modified or weakened. New 04883_time64_convert_field_scale_overflow adds 9 overflow arms and 8 asserted in-range outputs, including the exact Int64 boundary pair and an arm pinning the DateTime64 sibling.
e Both directions demonstrated? Yes. Two binaries from the same worktree, distinct Build IDs, server identity asserted via lower(buildId()) before each verdict. The new test reports Having 1 errors! on the base binary ("query succeeded but the server error '407' was expected") and passes on the fixed one.
f Fix is general across code paths? Yes. grep -rn "scale_multiplier_diff" src/ base/ yields 10 hits, all in this file, in exactly two branches: DateTime64 (already guarded) and Time64 (this change). Both are now structurally identical. Adjacent carriers were each measured rather than argued: Date -> DateTime64/Time64 pass a real multiplier so the helper guard is live; the isDateTime64/isTime64 integer branches route through decimalFromComponents -> common::mulOverflow; convertIntToDecimalType is fronted by canStoreWhole. All byte-identical before and after.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Nullable(Time64) and Array(Time64) overflow arms report the error (both in the test); Tuple/Map reject the shape earlier with unchanged errors; LowCardinality(Time64) is rejected by DataTypeLowCardinality itself, identically on both binaries. Scales 0/3/6/9, both signs, both scale directions, and boundaries 0, +/-1, +/-3599999, INT64_MAX/1e6 and one tick past it. 30 in-range controls are byte-identical.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no default change, so no SettingsChangesHistory.cpp entry is needed; no serialization format change; no signature or header change. The only behaviour change is that inputs which previously produced a wrong value now report DECIMAL_OVERFLOW, which is the same error the DateTime64 branch and explicit CAST already produced for those inputs. The largest value whose rescale still fits is still accepted and returns the identical result.
i Invariants and contracts preserved? Yes. The function contract (return a Field of the target type or report) holds; the change is on a pure-arithmetic path with no locks, allocation, or resource acquisition, so no error-path leak surface. The deliberately-Null Date32 -> DateTime64/Time64 contract is untouched and its test passes on both binaries. Int64 is required by the guard rather than a separate fix: the previous UInt64 round trip was value-preserving (the helper takes const Int64 &), but mulOverflow on an unsigned operand reports overflow for every negative value, so keeping UInt64 would reject in-range negative times. The 30 byte-identical in-range controls include three negatives, which is what pins this.

Session id: cron:clickhouse-impl-slot-41:20260812-183700

@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e74ea7e]

Summary: ✅


AI Review

Summary

This PR closes the unchecked Decimal64 -> Time64 rescale in convertFieldToType by mirroring the existing DateTime64 overflow guard and adds focused stateless coverage for VALUES, IN, nested types, and persistence. I did not find an unresolved correctness, compatibility, or evidence gap in the current diff; the behavior change is narrowly scoped to inputs that previously wrapped, and the current PR CI run is all-green.

Final Verdict

✅ No new review findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 11/11 (100.00%) · 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 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @yariks5s @KochetovNicolai, could you review this? The Time64 <- Decimal64 branch of convertFieldToTypeImpl rescaled with an unchecked multiply, so a value past INT64_MAX/scale_multiplier wrapped and a positive literal became a negative time that INSERT persisted; the one downstream guard is a no-op because that call passes multiplier 1. This mirrors the Int64 + common::mulOverflow guard already applied to the DateTime64 twin in #94537.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 13, 2026

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

Good. Thanks for the quick fix!

@alexey-milovidov alexey-milovidov self-assigned this Aug 13, 2026
The `insert into t_04883 values (253402207200000::Decimal64(0))` arm expected
`serverError DECIMAL_OVERFLOW`, but an inline `VALUES` list of an `INSERT` is
parsed by `clickhouse-client`, so the guard fires inside the client and the
overflow is reported as a client error. `Fast test` failed with `Expected server
error code '407' but got no server error`.

Which process performs the conversion is not what this test pins down, so the
arm now goes through `format`, like every other arm in the file, which keeps the
conversion on the server. Verified against a binary without the guard: the same
`INSERT` persists `-999:59:59.722624` there, so the arm still fails on master
and still asserts that no wrapped value is persisted.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114546&sha=c06656ca2d3a2ba0618998737a438d1581e3b199&name_0=PR&name_1=Fast%20test
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed e74ea7e to make Fast test green. The code fix itself is untouched.

The failing arm was the persistence one:

insert into t_04883 values (253402207200000::Decimal64(0)); -- { serverError DECIMAL_OVERFLOW }
→ Expected server error code '407' but got no server error

An inline VALUES list of an INSERT is parsed by clickhouse-client, so the new guard fires inside the client and the overflow is a client exception — the Error on processing query: prefix in the report is only used for client_exception (programs/client/Client.cpp:125), and the hint is checked in ClientBase (ClientBase.cpp:3397), which is why it read as "no server error".

Which side performs the conversion is not stable per type, so it is not worth pinning: against a running server, the same query text targeting DateTime64(6) is forwarded and the server throws (Numeric value is out of range for DateTime64), while Time64(6) throws in the client. The arm now goes through format, like every other arm in the file, which keeps the conversion on the server:

insert into t_04883 select * from format(Values, 'x Time64(6)', '(253402207200000::Decimal64(0))'); -- { serverError DECIMAL_OVERFLOW }

Both halves verified against a running server: this shape reports Received exception from server ... (DECIMAL_OVERFLOW), and on a binary without the guard the same INSERT persists -999:59:59.722624, so the arm still fails on master and still asserts that no wrapped value is persisted. The reference file is unchanged.

The new_tests_check.py failure was downstream of this — the per-arch Bugfix validation jobs were DROPPED once Fast test failed.

Also added to the description the two master reports where this keeps reproducing:

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e74ea7e1f with master 2485f1496 (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
Binary Master PR Δ
programs/clickhouse-stripped 692.21 MiB 689.20 MiB -3.01 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e74ea7e

CI has fully finished on this head with no failures. The praktika report is OK at the
top level (177 leaves: 159 OK, 18 SKIPPED, 0 DROPPED), all 160 executed GitHub
checks are green, Finish Workflow concluded at 08:06:56Z, and CIDB records 0
FAIL/ERROR test rows across 162 checks for this commit. The 18 skipped jobs each carry a
config reason ("Not affected by the changed files", "not labeled with 'pr-performance'",
"no integration tests updates", "not labeled with 'ci-toolchain'", "reused from cache"),
so this is real coverage rather than a dropped matrix.

Check / test Reason Owner / fixing PR
(none) - -

The earlier Fast test red on 04883_time64_convert_field_scale_overflow was on the
superseded head c06656ca2d3a2ba0618998737a438d1581e3b199 and is resolved by
e74ea7e1fa5, which routes the persistence arm through format(Values, ...) so the
conversion happens server-side. I verified that fix independently on both binaries and in
both async_insert modes: it passes on the guarded build and the test still reddens
without the guard, so the arm still asserts that no wrapped value is persisted.

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

@vdimir
vdimir added this pull request to the merge queue Aug 13, 2026
Merged via the queue into ClickHouse:master with commit ef9f96b Aug 13, 2026
182 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 13, 2026
@groeneai groeneai added the groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet label Aug 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet 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.

4 participants