Skip to content

Fix reinterpret to Decimal/DateTime64 with a different scale - #108878

Merged
cv4g merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-reinterpret-decimal-scale
Jul 2, 2026
Merged

cv4g merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-reinterpret-decimal-scale

Conversation

@groeneai

@groeneai groeneai commented Jun 30, 2026 •

Copy link
Copy Markdown
Collaborator

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 reinterpret(x, 'Decimal128(scale)') (and Decimal32/Decimal64/Decimal256/DateTime64 targets) producing a result column whose internal scale was the source scale instead of the requested target scale when the source and target had the same physical type. The values were correct but the column object was structurally inconsistent with its declared type.

Description

FunctionReinterpret::executeImpl dispatches on the physical TypeIndex of the source and target types. When both sides are the same physical type but have a different scale, for example reinterpret(Decimal(38, 33), 'Decimal128(2)') (both Decimal128), the std::is_same_v<FromType, ToType> branch returned the source column verbatim. That column carries the source scale (33), while the declared result_type is Decimal(38, 2), so the result column's scale diverged from its type. reinterpret is a bit-level relabel of the scale, so the visible SQL output was unaffected, but the column was structurally inconsistent with its type.

The same-type branch now rebuilds the column with the target scale (preserving the raw values) when the scales differ, and keeps the verbatim return when they match. This covers the scale-bearing physical types that are reachable as reinterpret targets and routed through that branch: Decimal32/Decimal64/Decimal128/Decimal256 and DateTime64.

Found by the function property fuzzer (gtest_functions_stress) after #108551 added the strict scale gate to columnMatchesType; reinterpret was a second producer of a scale-divergent column. Public reproducer:

SELECT reinterpret(a, CAST('Decimal128(2)' AS String))
FROM system.one
ARRAY JOIN CAST([0.0816, 1036.36, -0.0200, 0.00265] AS Array(Decimal(38, 33))) AS a;

Regression coverage: a new unit test (gtest_reinterpret_decimal_scale) runs reinterpret through FunctionFactory and asserts the result column matches its declared type with the strict scale gate, for Decimal128/Decimal64/Decimal256 same-width-different-scale and the same-scale passthrough. The test fails without this fix (the result column reports the source scale) and passes with it.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT reinterpret(materialize(toDecimal128('1.23', 33)), 'Decimal128(2)') and the exact fuzzer ARRAY JOIN query reproduce on demand. Unit test ReinterpretDecimalScale.* fails deterministically without the fix.
b Root cause explained? Yes. FunctionReinterpret::executeImpl dispatches via callOnTwoTypeIndexes on the physical TypeIndex. Source Decimal(38,33) and target Decimal128(2) share the Decimal128 TypeIndex, so the std::is_same_v<FromType, ToType> branch fires and returns the source column verbatim. That column carries scale 33 while the declared result_type is scale 2, so the column's internal scale diverges from its type.
c Fix matches root cause? Yes. The same-type branch now rebuilds the column with result_type's scale (raw values preserved) when the scales differ, and keeps the verbatim return when they match. It targets exactly the divergence mechanism in (b), not a symptom.
d Test intent preserved / new tests added? New unit test gtest_reinterpret_decimal_scale.cpp added. It exercises the real reinterpret via FunctionFactory and asserts the result column matches its declared type under the strict scale gate (the #108551 gate), plus a same-scale passthrough case. No existing test weakened.
e Both directions demonstrated? Yes, on the same binary. Without fix: 3/4 tests FAIL (e.g. reinterpret returned Decimal64 for declared type Decimal(18, 3), getScale() = 10). With fix: 4/4 PASS. The same-scale passthrough test passes in both (verbatim return is correct there).
f Fix is general across code paths? Yes. The same-type verbatim return was the only one in the same-physical-type branch (the other result = arguments[0].column at line 185 is in the String-source branch, unrelated). No symptom guard.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. IsDataTypeDecimal<ToType> covers Decimal32/64/128/256, DateTime64, Time64 — all verified (Decimal32(4)->Decimal32(2), DateTime64(3)->DateTime64(6) produce correct declared types). Wrapper matrix: Nullable(Decimal)->Nullable(Decimal(...,2)) OK; const path OK; LowCardinality(Decimal) rejected at type-check (unreachable).
h Backward compatible? Yes. No setting, on-disk, wire, or metadata format change. reinterpret's visible SQL output is unchanged (serialization already used the declared type's scale); only the column object's internal scale is corrected. No SettingsChangesHistory.cpp change needed.
i Invariants and contracts preserved? Yes. The fix restores the column-structure invariant column.getScale() == declared_type.getScale() that executeImpl's other branches already uphold via numericColumnCreateHelper. The same-scale branch is unchanged. getData().assign() copies the raw PaddedPODArray, preserving values and column size.

Session id: cron:clickhouse-worker-slot-5:20260630-011500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @Algunenano — could you review this? reinterpret to a same-physical-type Decimal/DateTime64 target with a different scale (e.g. reinterpret(Decimal(38,33), 'Decimal128(2)')) returned the source column verbatim, so the result column's internal scale stayed 33 while its declared type was scale 2. The fix rebuilds the column with the target scale (raw bits preserved) only when the scales differ.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [aa27ce7]

Summary: ✅


AI Review

Summary

This PR fixes reinterpret for same-physical-type Decimal and DateTime64 targets with a different scale by rebuilding the result column when only the scale label changes, and it adds focused regression tests including the requested DateTime64 positive case and Time64 negative case. I did not find any remaining correctness, test, or changelog issues in the current diff.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 30, 2026
Comment thread src/Functions/reinterpretAs.cpp Resolved
reinterpret dispatches on the physical TypeIndex, so reinterpret to a
same-physical-type target with a different scale (e.g.
reinterpret(Decimal(38, 33), 'Decimal128(2)')) hit the
std::is_same_v<FromType, ToType> branch and returned the source column
verbatim. The returned ColumnDecimal kept the source scale while the
declared result_type had the target scale, leaving the column
structurally inconsistent with its type.

Rebuild the column with the target scale (raw values preserved) when the
scales differ; keep the verbatim return when they match. Covers
Decimal32/64/128/256, DateTime64 and Time64.

Found by the function property fuzzer after ClickHouse#108551 added the strict
scale gate to columnMatchesType.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the groeneai/fix-reinterpret-decimal-scale branch from 85c5e19 to 3f1842d Compare June 30, 2026 03:45
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 3f1842d

Every failure below has an owner: a fixing PR (ours or external). Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Hung check failed, possible deadlock found deadlock (chronic trunk; 109 distinct PRs + 76 master hits in 24h, not caused by this PR) #101680 / #105905 (ours, open)
Stress test (arm_tsan) / Hung check failed, possible deadlock found deadlock (chronic trunk; same family) #101680 / #105905 (ours, open)
PR (rollup) aggregates the stress sub-checks above #101680 / #105905 (ours, open)
CH Inc sync - CH Inc sync (private, not actionable)

Note: the earlier Build (arm_tidy) failure (no-op std::move clang-tidy diagnostic) was already fixed and is success on this HEAD.

Session id: cron:our-pr-ci-monitor:20260630-073000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3f1842d

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_tsan) / Hung check failed, possible deadlock found deadlock (chronic: 370 hits / 125 PRs / 76 master in 24h) #101680 / #105905 (ours, open)
Stress test (arm_tsan) / Hung check failed, possible deadlock found deadlock (chronic) #101680 / #105905 (ours, open)
CH Inc sync private sync CH Inc sync (private, not actionable)

The reinterpret-to-Decimal/DateTime64 scale fix cannot cause a TSan shutdown deadlock; the earlier PR-caused arm_tidy lint and the function_prop_fuzzer Time64 finding are both resolved on this head. Both stress failures are the chronic hung-check family across unrelated PRs and master.

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

@cv4g

cv4g commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

@groeneai src/Functions/reinterpretAs.cpp:163 also covers DateTime64 and Time64 via IsDataTypeDecimal. Can you please add a test for these two as well?

DateTime64 and Time64 both satisfy IsDataTypeDecimal, so the scale-rebuild
branch at reinterpretAs.cpp:163 is instantiated for both. DateTime64 is a
reachable reinterpret target (canBeReinterpretedAsNumeric accepts it), so add
a positive test: DateTime64(9) -> DateTime64(2) relabels the scale and
preserves the raw value. Time64 is not in the gate, so reinterpret rejects it
in getReturnTypeImpl before the branch is reached; add a negative test
asserting it throws ILLEGAL_TYPE_OF_ARGUMENT.

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

Copy link
Copy Markdown
Collaborator Author

Added both in 7f1fcfc (src/Functions/tests/gtest_reinterpret_decimal_scale.cpp):

  • DateTime64SameWidthDifferentScale: positive test for the reachable target. DateTime64(9) -> DateTime64(2) now hits the same scale-rebuild branch as the Decimal cases, relabels the scale to 2, and preserves the raw value. Verified it fails before the fix (returns a DateTime64 column with scale 9 for a declared DateTime64(2)) and passes after.
  • Time64IsNotAReinterpretTarget: negative test. Time64 satisfies IsDataTypeDecimal but is absent from canBeReinterpretedAsNumeric, so reinterpret(x, 'Time64(2)') throws ILLEGAL_TYPE_OF_ARGUMENT in getReturnTypeImpl before the branch is reached. The test documents that gate.

All 6 tests in the suite pass with the fix.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 7f1fcfc

Every failure below has an owner: a fixing PR (ours or external), or the private sync check. No PR-caused failures.

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, parallel) / 04204_global_in_join_max_rows_to_transfer_103333 flaky (Code 102 "Unexpected packet from server 127.0.0.2:9000" connection-pool desync; CI's own diagnosis 155/155 reruns pass, not reproducible) #108854 (external, open)
Stress test (amd_tsan) / Hung check failed, possible deadlock found deadlock (chronic, not PR-caused) #108212 (ours, merged) / #105905 (ours, open)
Stress test (arm_tsan) / Hung check failed, possible deadlock found deadlock (chronic, not PR-caused) #108212 (ours, merged) / #105905 (ours, open)
CH Inc sync - CH Inc sync (private, not actionable)

This PR (reinterpret to Decimal/DateTime64 with a different scale) is a Functions/reinterpretAs change plus a unit + DateTime64/Time64 test; it cannot cause a distributed connection-pool desync or a TSan stress-shutdown deadlock. The 04204 failure is the well-tracked Code-102 distributed-desync family converging on external fix #108854.

Session id: cron:our-pr-ci-monitor:20260630-203000

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, fix 04204_global_in_join_max_rows_to_transfer_103333

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov 04204_global_in_join_max_rows_to_transfer_103333 fails only with the connection-pool desync Code 102 ... (expected TablesStatusResponse, got ProfileInfo) that your #108854 fixes (merged 2026-07-01 13:22Z, now on master HEAD). It is not a 04204-specific bug: 04204 is one of many distributed-test victims of that same desync.

Resolved on master:

  • 04204 on master since the Fix flaky distributed query "Unexpected packet from server (expected TablesStatusResponse, got ProfileInfo)" #108854 merge: 0 FAIL / 85 OK.
  • Family-wide master desync (all victim tests) last hit 08:00Z 07-01; zero after the 13:22Z merge. The last master 04204 hit (08:42Z, commit 32129f7) is 115 commits behind the fix.
  • 42/42 of 04204's failures in the last 7 days are this single desync signature, no other mode.
  • The only two 04204 failures with a post-merge timestamp are on PR branches that do not contain the fix (revert-108814: 5 commits behind; separate-cross-join: 2193 behind), so they predate it.

So there is no separate code bug to fix here, and a test-side patch would only mask the engine bug for 04204 while the other victims stay exposed. If you are seeing a specific residual failure on a branch that already includes #108854, point me at it and I will open a separate PR.

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

Merged current master (675d38f) so this branch now contains #108854 (the connection-pool desync fix, merged 07-01 13:22Z). The prior CI ran on a base 1026 commits behind that merge, which is why 04204_global_in_join_max_rows_to_transfer_103333 was red. On master since the fix: 04204 is 0 FAIL / 24h clean. The re-run should be green.

Master reverted the strict_decimal_scale parameter of columnMatchesType
(commit 9bbbb45, revert of the function-property stress-test scale gate),
so the 3-argument call in this test no longer compiles and broke the
arm_tidy build after the branch was merged with master.

columnMatchesType is now purely structural. Drop the removed
strict_decimal_scale argument; the per-test getScale() assertions already
verify the declared scale, so the scale-regression coverage is unchanged.
@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.50% 85.50% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.70% 77.70% +0.00%

Changed lines: Changed C/C++ lines covered: 55/55 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - aa27ce7

CI fully finished and green. Every stress test passed (no hung-check recurrence this run), and Build (arm_tidy) - the originating failure - is SUCCESS on this head. This head adapts the reinterpret scale test to the scale-blind columnMatchesType after the master merge, and carries the DateTime64/Time64 tests requested earlier.

Check / test Reason Owner / fixing PR
CH Inc sync - CH Inc sync (private, not actionable)

No PR-caused failure.

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

@cv4g
cv4g added this pull request to the merge queue Jul 2, 2026
Merged via the queue into ClickHouse:master with commit 4832efa Jul 2, 2026
174 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 2, 2026
@rschu1ze

rschu1ze commented Jul 5, 2026

Copy link
Copy Markdown
Member

For future PRs, let's ask Groene to write SQL-based tests instead of C++ unit tests. Unit tests are much harder to maintain in the long run.

@groeneai

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

Understood. Going forward I will default to SQL-based stateless tests for regression coverage, and reserve C++ unit tests only for behavior that is not observable from SQL (e.g. internal column-structure invariants like the scale-vs-declared-type check here, which does not surface in query output). Noted as a standing preference.

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…erpret-decimal-scale

Fix reinterpret to Decimal/DateTime64 with a different scale
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 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.

5 participants