Skip to content

Fix DateTime64 and Time64 output truncation for scale above 6 with the groups-of-thousands setting - #112854

Merged
yariks5s merged 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-datetime64-time64-cut-trailing-zeros-scale-gt6
Aug 27, 2026
Merged

yariks5s merged 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-datetime64-time64-cut-trailing-zeros-scale-gt6

Conversation

@groeneai

@groeneai groeneai commented Aug 1, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #104997

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 silent truncation of DateTime64 and Time64 values with a scale above 6 when date_time_64_output_format_cut_trailing_zeros_align_to_groups_of_thousands is enabled. The printed fraction was capped at 6 digits, so a DateTime64(9) value of 00:00:00.000000700 rendered as 00:00:00.000000 even though the stored value was not zero. The documented output range of the setting widens from [0, 3, 6] to [0, 3, 6, 9].

Description

The setting rounds the printed fraction up to the next multiple of three that keeps every significant digit, but the round-up carried a hardcoded ceiling of 6, so a significant digit at position 6 or beyond was never written. The symptom is not lost trailing precision but a non-zero fraction rendering as all zeros.

The same expression exists twice, in writeDateTime64FractionalText and writeTime64FractionalText, so Time64 has the identical defect. Both are fixed; separate mutations confirm each is load-bearing.

The fix removes only the ceiling and keeps the existing round-up rule. It deliberately does not clamp the width to the declared scale, because master already pads past it: a DateTime64(1) of .7 prints .700 today. Over all 45 scale and last-significant-digit combinations the new rule matches master in 39 and differs only in the 6 where master loses a digit, always emitting a multiple of three, at most 9. Clamping would break that invariant at scales 1, 2, 4 and 5, so the test pins those rows.

The new SQL test fails on master and passes with the fix; a sweep against a baseline with the fix reverted shows 0 regressions over 488 tests. The setting defaults to false, so nothing changes unless it is enabled. The description is updated, since it documented a hard 6.

Three pre-existing scope limits are left unchanged, each pinned by a test row: row output honors the setting only under the default date_time_output_format = 'simple'; for Time64 only a direct scalar toString or CAST trims, since a nested value and the row formats reach SerializationTime64::serializeText, which discards its FormatSettings; and an all-zero Time64 fraction keeps three digits where DateTime64 drops it. Each is its own change.


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

Version info

  • Merged into: 26.9.1.203 (included in 26.9 and later)

groeneai added 2 commits July 31, 2026 21:55
With date_time_64_output_format_cut_trailing_zeros_align_to_groups_of_thousands
enabled, the printed fraction of a DateTime64 or Time64 value was capped at 6
digits. The setting rounds the width up to the next multiple of three that keeps
every significant digit, but the round-up was written as a hardcoded two-way
choice with a ceiling of 6:

    size_t new_scale = (last_non_zero_pos >= 3) ? 6 : 3;

so any last-significant-digit position at 3 or beyond collapsed to exactly 6 and
writeString emitted only 6 characters, dropping digits 7 to 9. The clearest
symptom is not lost trailing precision but a non-zero fraction rendering as all
zeros: a DateTime64(9) holding 700 nanoseconds printed .000000 while
toUnixTimestamp64Nano of the same value modulo 1000000000 is 700.

Removing only the ceiling keeps the documented rule intact. The expression exists
twice, in writeDateTime64FractionalText and in writeTime64FractionalText, so
Time64 carried the identical defect; both are fixed and reverting either site
alone reddens a disjoint set of test rows.

The width is deliberately not clamped to the declared scale. Master already pads
past the declared scale, which is what aligning to groups of thousands does: a
DateTime64(1) value of .7 prints .700 today, and .00007 at scale 5 prints
.000070. Enumerating all 45 combinations of scale and last-significant-digit
position, the new rule is byte-identical to master in 39 and differs only in the
6 where master loses a significant digit, always emitting a width that is a
multiple of three, at most 9. A clamp would instead change 9 combinations at
scales 1, 2, 4 and 5 and emit widths that are not multiples of three, so it would
regress scales below the ones this bug concerns, including the DateTime64(6)
neighbourhood the setting was introduced for. The new test pins those rows.

The setting's own description documented the output range as [0, 3, 6] and is
updated in the same change, since it is the user-facing contract reported by
system.settings. The default stays false, so no SettingsChangesHistory entry is
needed and nothing changes for anyone who has not opted in.

Closes: ClickHouse#104997
…tring and CAST

Round 1 review found that rewriting the description of
date_time_64_output_format_cut_trailing_zeros_align_to_groups_of_thousands
introduced the word Time64 unqualified. The word is new in this branch: on
master that description does not mention Time64 at all.

Time64 honours the setting only on the toString and CAST routes
(FunctionsConversion.h), not in the row output formats:
SerializationTime64::serializeText discards its FormatSettings argument and
calls the plain writeTime64Text, whereas SerializationDateTime64 reads the
setting. The description is user-facing (system.settings.description), so an
unqualified promise there overstates what the code delivers.

Name the routes instead of dropping Time64 entirely, since Time64 genuinely is
fixed on toString and CAST and the test asserts exactly those rows. Wiring the
serializer is a separate behaviour change and is tracked separately.

Measured with the rebuilt binary: for a Time64 value with trailing zeros,
toString and CAST trim it while TSV and JSONEachRow do not, and the
DateTime64 controls trim on both routes.
@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Two independent cold reviews plus two second-model gate passes ran over this diff before it
was published. The first gate pass returned one blocking finding, which was fixed and then
re-reviewed; the second returned none. Verdicts below; findings I disagreed with carry the
measurement that settled it.

# Finding Verdict
❌ 1 The rewritten setting description promised Time64 trimming without qualification, although Time64 honours the setting only via toString/CAST and not in the row output formats (SerializationTime64::serializeText discards its FormatSettings). AGREE, fixed
💡 2 The test asserts Time64 rows without pinning enable_time_time64_type, which flipped false -> true in the 25.12 block and can be reverted by the stress lane's compatibility='NN.N' injection. DISAGREE, not a carrier
💡 3 The A/B sweep artifacts record the test under its earlier number 04667 while the shipped file is 04671. DISAGREE, naming only

1. Real and introduced here: on master that description contains the standalone word
Time64 zero times. Time64 is genuinely fixed by this change on the string-conversion
path (FunctionsConversion.h:2408, :2441), but SerializationTime64::serializeText
takes const FormatSettings & /*settings*/ and calls the plain writer, and none of its
five serializeText* overloads reads the setting, so the row output formats keep the full
declared scale. The description now names the routes that do honour it, and I re-verified
each half of the replacement sentence from source after the fix. Wiring the serializer is a
separate behaviour change and is deliberately not in this PR.

2. The Time64 gate lives only in validateDataType
(parseColumnsListForTableFunction.cpp:122-139), whose four call sites are
CastOverloadResolver (a CAST to a named type), InterpreterCreateQuery and two in
AlterCommands. This test never casts to Time64 and declares no Time64 column: it
calls the registered toTime64 function and casts from Time64 to String. Of the 31
existing stateless tests using toTime64, 21 do not pin the setting, and all 10 that do
either declare a Time64 column or cast to Time64.

3. The rename is recorded, and it changed the filename only, not a byte of SQL. The
post-rename state was re-verified: the test passes, a tag-free 50-run pass is 50 OK / 0
FAIL, and the real check_gaps_in_tests_numbers predicate reports no gaps with or without
the file.

Independently re-derived while reviewing: the two changed expressions are the only
fraction-width ceilings in src/; every other instantiation of both helpers passes
cut = false and so cannot reach the changed line, since it sits inside
if constexpr (cut_trailing_zeros_align_to_groups_of_thousands). Re-implementing both
functions from the source text and running the full scale-by-position grid reproduces the
claimed delta exactly: 45 cells, 39 byte-identical, 6 changed, every new width a multiple
of three with a maximum of 9. The rejected alternative that clamps the width to the declared
scale instead produces a width that is not a multiple of three in 9 cells, at scales 1, 2,
4, 5, 7 and 8. The buffer holds 18 initialised characters against a worst case of 18 at the
decimal precision limit, and the type-level scale cap is 9. The wider scale-7 and scale-8
output still round-trips, because the reader consumes at most scale fractional digits and
explicitly ignores the rest. Of the shipped test's rows, 23 change output if the fix is
reverted, and every must-not-change and setting-off row stays green in that arm; the existing
gtest cases pin scales 0, 3 and 6 only, so none of the 6 changed cells moves an expectation.

Session id: cron:clickhouse-review-slot-50:20260801-022200

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A single clickhouse local --queries-file run, rc=0, no fixture, no server, no randomization: with the setting on, toString(toDateTime64('2024-01-01 00:00:00.000000700', 9, 'UTC')) prints 2024-01-01 00:00:00.000000 while toUnixTimestamp64Nano(...) % 1000000000 is 700.
b Root cause explained? Yes. The align-to-groups-of-thousands round-up was written as (last_non_zero_pos >= 3) ? 6 : 3, a hardcoded ceiling of 6, so every last-significant-digit position at 3 or beyond collapsed to 6 and writeString(&data[0], new_scale, buf) emitted only 6 characters, dropping digits 7 to 9. The zero-fraction case is decided by the caller and is unaffected.
c Fix matches root cause? Yes. The ceiling itself is deleted and the existing round-up rule is kept: ((last_non_zero_pos / 3) + 1) * 3. No widened bound, no test tag, no reduced dataset, no guard masking an upstream bug. The obvious alternative min(6, scale) was rejected because it still prints 6 digits for a scale 9 value, so it does not fix the report at all.
d Test intent preserved / new tests added? Yes. A new SQL stateless test ships and no existing expectation moves: the five scale 0/3/6 cases pinned by DateTimeToStringParamTestDateTime64TrimZeros are byte-identical before and after (asserted through SQL with the same tick inputs), 00357_to_string_complex_types is OK in both arms, and every scale 0 to 6 cell of the exhaustive grid is unchanged.
e Both directions demonstrated? Yes. Through the real test runner on Build-ID-verified binaries: FAIL before the fix, OK after. In the failing arm 23 rows redden and zero of the must-not-change or setting-off rows do, so the test discriminates rather than merely being red.
f Fix is general across code paths? Yes. The defect is duplicated and both copies are fixed, in writeDateTime64FractionalText and writeTime64FractionalText. Reverting each site alone reddens a disjoint row set, so each hunk is independently load-bearing. After the fix no hardcoded fraction-width ceiling remains in src/. The false instantiations, including the MySQL wire protocol path which hardcodes 6 by protocol, take the other branch and structurally cannot reach the changed expression.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, measured in both directions for Nullable, Nullable holding NULL, Array, Map, Tuple and a non-const column. LowCardinality(DateTime64) is rejected at construction with Code: 43, so that cell cannot exist. Boundaries covered: all nines, minimum fraction, zero fraction, epoch, pre-epoch negative, Time64 extremes and negatives. The parameter matrix is the full 45 cell grid over scale and last-significant-digit position, plus both values of the setting.
h Backward compatible? (maintainer-approved exception only) Yes. The setting default is and remains false, so nothing changes for anyone who has not opted in, and no SettingsChangesHistory.cpp entry is required. 03999_stateless_settings_history passes. No serialization format, no on-disk format and no wire protocol is touched. The scale 7 to 9 output change is stated in the description as a user-visible change.
i Invariants and contracts preserved? Yes. The invariant being repaired is that the printed fraction width is the smallest multiple of three retaining every significant digit; across all 45 grid cells every post-fix width is a multiple of three, at most 9. Buffer bound proven: the reachable maximum width is 9 against char data[20] with static_assert(sizeof(data) >= MaxScale), and scale 10 is rejected with Code: 69. There is no lock, allocation or early-return path involved: two integer operations replace a comparison inside a branch that only runs when the setting is enabled, so there is no performance implication.

Session id: cron:clickhouse-review-slot-50:20260801-022200

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @yariks5s @Algunenano, could you review this? The align-to-groups-of-thousands round-up in writeDateTime64FractionalText and writeTime64FractionalText had a hardcoded ceiling of 6, so a DateTime64(9) holding 700 nanoseconds printed .000000 while the stored value was not zero; removing only the ceiling keeps every scale 0 to 6 output byte-identical.

@PedroTadim PedroTadim self-assigned this Aug 1, 2026
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 1, 2026
@PedroTadim
PedroTadim enabled auto-merge August 1, 2026 11:01
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a3ccf02]

Summary: ✅


AI Review

Summary

This PR fixes the hardcoded 6-digit ceiling in the grouped-thousands trimming path for DateTime64 and direct-scalar Time64, and the new stateless coverage is thorough. The writer changes themselves look correct, but the updated setting description still documents a broader DateTime64 contract than the implementation provides, so I would not merge it as-is.

Findings

⚠️ Majors

  • [src/Core/FormatFactorySettings.h:761] The updated description says the setting trims DateTime64 values in general, but SerializationDateTime64::serializeText only honors it in the simple output mode; iso and unix_timestamp still print the declared scale. Because this string feeds system.settings, help, and the autogenerated settings page, users enabling the setting under non-simple row output still get behavior that contradicts the documented contract. Suggested fix: narrow the text to simple text output, or teach the non-simple branches to honor the setting too.

💡 Nits

  • [src/Core/SettingsChangesHistory.cpp:1012] [dismissed by author -- https://github.com/Fix DateTime64 and Time64 output truncation for scale above 6 with the groups-of-thousands setting #112854#discussion_r3702596273] The behavior change from [0, 3, 6] to [0, 3, 6, 9] is still absent from system.settings_changes, so the history shown in system.documentation and other compatibility-audit surfaces is stuck at the 24.8 contract. A no-op history row is still the only way to make that carrier reflect the new behavior without moving any user value.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.30% 87.30% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.40% +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 1, 2026
Comment thread src/Core/FormatFactorySettings.h Resolved
groeneai and others added 3 commits August 1, 2026 12:32
The AI reviewer noted that `date_time_64_output_format_cut_trailing_zeros_align_to_groups_of_thousands`
carried only its 24.10 introduction row, which still describes the old
`(0, 3, 6)` output scale. `system.settings_changes` exposes that `reason`
text directly, so the compatibility audit path reported pre-fix semantics
for a setting whose contract this change widens to `[0, 3, 6, 9]`.

Add a 26.8 row recording the semantics change. `previous_value` equals
`new_value` (`false`), so `applyCompatibilitySetting` skips it and no user
value moves: the row is a history record, not a default flip. This is the
established shape for a semantics-only change - 31 settings already carry
an older introduction row plus a later value-noop row, for example
`allow_experimental_delta_lake_writes` (25.9 then 26.7, "Delta Lake writes
were moved to Beta.") and `enable_full_text_index` (25.12 then 26.2, "The
text index is now GA").

Behavior is unchanged: `src/IO/WriteHelpers.h` is untouched and the
exhaustive scale by last-non-zero-position grid is byte-identical.

Co-Authored-By: Claude Fable 5 <[email protected]>
…oute assertions discriminating

Two findings from the second-model re-review, both reproduced locally.

The setting description claimed row output formats are trimmed. They are
only under the default `date_time_output_format = 'simple'`:
`SerializationDateTime64::serializeText` consults the setting in the
`Simple` branch alone, so `iso` and `unix_timestamp` always print the full
declared scale. Measured with the setting on and a `DateTime64(9)` value of
`.123000000`: `simple` prints `.123`, `iso` prints `.123000000Z`,
`unix_timestamp` prints `1704067200.123000000`. Conversion with `toString`
and `CAST` is trimmed in all three modes, so the description now separates
the two.

The `Time64` and multi-route assertions all used a scale 9 value whose every
digit is significant. Such a value prints nine digits whether or not the
route consults the setting, so ten of those rows would have stayed green if
a route silently stopped honouring it. Each route gains a scale 7 twin,
which reads `.123456` before the fix, `.123456700` after it, and `.1234567`
if the route bypasses the setting. Rows that change when the setting is
forced off went from 26 to 34, and every new row reddens when the
pre-fix six-digit ceiling is restored at both call sites.

Added rows only; no existing expectation moved, and `src/IO/WriteHelpers.h`
is untouched by this commit.

Co-Authored-By: Claude Fable 5 <[email protected]>
The second-model re-review found that the new description sentence claims
`Time64` is trimmed the same way as `DateTime64`, which overclaims for an
all-zero fraction. Measured: with the setting on, a zero-fraction
`DateTime64(9)` prints `2024-01-01 00:00:00` while a zero-fraction
`Time64(9)` prints `100:00:00.000`. The cause is the caller, not the new
rule: the `DateTime64` writer emits the delimiter only when the fraction is
non-zero, while the `Time64` writer always emits it for a positive scale.

This is pre-existing and unchanged here - for an all-zero fraction the old
and the new formula both yield width three, and neither caller is touched by
this change - so only the wording is corrected, in both the setting
description and the history reason. Three assertions pin the asymmetry so
the two descriptions cannot drift from the behavior. Aligning the `Time64`
writer with the `DateTime64` one is a separate behavior change and is left
out of this change.

Co-Authored-By: Claude Fable 5 <[email protected]>
auto-merge was automatically disabled August 1, 2026 14:21

Head branch was pushed to by a user without write access

Comment thread src/Core/FormatFactorySettings.h Resolved
The setting description and the 26.8 history reason both said Time64 is
trimmed by toString and CAST without qualification. That over-promises: only
a DIRECT scalar conversion reaches
writeTime64TextCutTrailingZerosAlignToGroupOfThousands via
FunctionsConversion.h. A Time64 nested in a tuple, array or map is
serialized by ConvertImplGenericToString through
SerializationTime64::serializeText, which discards its FormatSettings and
always calls writeTime64Text, so the declared scale is printed.

Measured on a build whose served buildId was asserted against its own ELF
Build ID, setting enabled, scale 7 value .1234567:

  toString(toTime64(...))          100:00:00.123456700   trimmed
  toString(tuple(toTime64(...)))   100:00:00.1234567     not trimmed
  toString([toTime64(...)])        100:00:00.1234567     not trimmed
  toString(map('k', toTime64(...)) 100:00:00.1234567     not trimmed

The DateTime64 twins of those composite queries DO trim, because
SerializationDateTime64::serializeText reads the setting, so the gap is
specific to Time64 rather than to composite output.

Corrects the wording in both carriers and pins the contract with five test
rows, using a scale 7 value that discriminates three ways: .123456 under the
pre-fix ceiling, .123456700 when the route consults the setting, .1234567
when it does not. Restoring the setting read in
SerializationTime64::serializeText reddens exactly those three Time64 rows
and nothing else, so they are not vacuous.

Teaching SerializationTime64 to honor the setting is a behavior change
across every nested and row-output carrier and belongs in its own PR; this
change only stops the documentation from promising it.
Comment thread src/Core/FormatFactorySettings.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.80% +0.10%

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

Full report · Diff report

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — b561f72

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.

174 check-runs, 0 incomplete (paginated check-runs API), Config Workflow and Finish Workflow both green, last completion 23:57:13Z.

Check / test Reason Owner / fixing PR
Stress test (arm_asan_ubsan, s3) / Logical error: Query context must be created after authentication (STID 3197-391f) trunk defect, not PR-caused: PostgreSQLHandler::cancelRequest (PostgreSQLHandler.cpp:867) calls Session::makeQueryContext on the unauthenticated second connection a PostgreSQL client opens to send CancelRequest, so Session::makeQueryContextImpl (Session.cpp:690) throws. 61 rows / 36 PRs / 7 master runs in the last 24 h, first seen 15:04Z today #112940 (external, open)

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112854&sha=b561f7247c3950d534921a6ce72d3187ad1e2790&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29

Not PR-caused: this PR only changes DateTime64 and Time64 fractional-text output, and the failing path is the PostgreSQL wire handler. This build's base master still contained #110760, which is what made CI reach the pre-existing defect; #112935 reverted #110760 at 17:25:28Z and #112940 reapplies it together with the actual fix. No push here.

Session id: cron:our-pr-ci-monitor:20260802-000000

DECLARE(Bool, date_time_64_output_format_cut_trailing_zeros_align_to_groups_of_thousands, false, R"(
Dynamically trim the trailing zeros of datetime64 values to adjust the output scale to [0, 3, 6],
corresponding to 'seconds', 'milliseconds', and 'microseconds')", 0) \
Dynamically trim the trailing zeros of `DateTime64` values, rounding the output scale up to the next

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.

@groeneai this has to be trimmed. It's way too long

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Trimmed to 3 lines / 305 chars in b223f34 (was 8 lines / 826). Kept the contract: the widened [0, 3, 6, 9] round-up, the dropped all-zero fraction, and one sentence on Time64. The scope caveats it carried are in the PR description and pinned by the test, so they do not belong in a user-facing description.

I audited the rest of the diff for the same problem and found two more spots:

  • the new SettingsChangesHistory.cpp note was 603 chars, the longest of all 1230 rows (median 51) - trimmed to 161, recorded values untouched;
  • two test comment blocks were 4 lines - trimmed to 3.

No behaviour change: all 140 query-result lines in the reference are byte-identical, and 01324_settings_documentation still passes. The reference is regenerated only because -- { echo } echoes the edited comments.

groeneai and others added 2 commits August 2, 2026 13:35
@PedroTadim asked for the description of
date_time_64_output_format_cut_trailing_zeros_align_to_groups_of_thousands
to be trimmed: at 826 characters over 8 lines it was the 10th longest of the
295 descriptions in FormatFactorySettings.h, against a median of 106.

The scope caveats it carried (which conversion routes trim, the
date_time_output_format interaction, the nested-Time64 and Time64 row-format
gaps) are already documented in the PR description and pinned row by row by
the test, so they do not belong in a user-facing setting description. What
remains is the contract: the widened [0, 3, 6, 9] round-up, the dropped
all-zero fraction, and the one-sentence Time64 qualification.

Audited the rest of the diff for the same problem:

- SettingsChangesHistory.cpp: the new row's note was 603 characters, the
  longest of all 1230 rows (median 51). Trimmed to 161. The recorded values
  are untouched, so the compatibility audit path is unaffected.
- The test had two comment blocks of four lines, over the three-line-per-block
  convention. Trimmed to three; the rationale they carried is in the PR body.

No behavior change: every one of the 140 query-result lines in the reference is
byte-identical. The reference is regenerated only because `-- { echo }` echoes
the edited comments. No test asserts this description text; 01324 (descriptions
start with a capital letter) still passes.

Co-Authored-By: Claude Fable 5 <[email protected]>
The `date_time_output_format` group said the 'simple'-mode limit was documented
by the setting, which was true before the previous commit trimmed that sentence
out. State the limit in the test instead of citing the description for it.

The limit itself is unchanged and pre-existing: `iso` and `unix_timestamp` never
consulted the setting (SerializationDateTime64.cpp:51-56), which is what these
rows pin. Results are byte-identical.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

⚠️ AI verdict: not_sure — no significant changes across 38 queries analysed

This change only widens DateTime64/Time64 trailing-zero output trimming from [0,3,6] to [0,3,6,9], gated behind a setting that defaults to off, plus doc/history/test additions. The single flagged row, clickbench Q15, is a GROUP BY aggregation that never touches that formatting path, and its CPU time is essentially unchanged (2618.5 vs 2623.8 ms) even though wall-clock median moved -11.5%. The deterministic gate already marked it not_sure due to an unstable baseline for this query, which is consistent with the data: the delta is run-to-run variance, not a PR effect. No action needed.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 15 not_sure 222 196 -11.5% <0.0001 This PR only touches DateTime64/Time64 trailing-zero output formatting behind a default-off setting, which Q15's GROUP BY aggregation never exercises; CPU is flat (~2620 ms), so the -11.5% wall delta is baseline instability, not a PR effect.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 6285408b-59a3-4185-8776-6b8f8a446043
  • MIRAI run: 17404982-1e65-4024-81c9-0bb5f676153c
  • PR check IDs:
    • clickbench_1384619_1785687138
    • clickbench_1384632_1785687138
    • clickbench_1384639_1785687138
    • tpch_adapted_1_official_1384650_1785687138
    • tpch_adapted_1_official_1384675_1785687138
    • tpch_adapted_1_official_1384689_1785687139

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — b223f344077f9d0e05fa4a7fc0d7b1b45e5c6b81

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.

174 check-runs, 0 incomplete, Config Workflow and Finish Workflow both success, past the
20-minute CIDB ingestion buffer. No failing check on this head (18 skipped, rest green).

The previous ledger covered b561f7247c3950, whose only red (Stress test (arm_asan_ubsan, s3),
STID 3197-391f, owned by #112940) does not recur here.

Session id: cron:our-pr-ci-monitor:20260802-200000

Comment thread src/Core/SettingsChangesHistory.cpp Outdated
{"input_format_read_datetime_number_as_raw_value", true, false, "From 26.8, an unquoted number for a `DateTime`/`DateTime64` column in the `JSON` and `Values`/`Quoted` paths (and in `JSONExtract` and typed `JSON`) is a Unix timestamp in seconds, consistent with the `Values` format, `CAST` and `toDateTime64`. Set this to `true` (or `SET compatibility = '26.7'`) to restore the pre-26.8 behavior, where a bare unquoted integer fed to a `DateTime64` column was read as the raw scaled value (ticks). The tab-separated, CSV and other escaped/whole-text formats are not governed by this setting."},
{"query_plan_short_circuit_constant_false_join", false, true, "New setting to short-circuit a JOIN with a constant-false ON condition so the non-contributing side is not read. previous_value=false so `compatibility` with versions before 26.8 restores the pre-existing behavior (no short-circuit)."},
{"distributed_cache_min_inflight_bytes_to_discard_connection_on_seek", 0, 4 * 1024 * 1024, "New setting to drop and reopen a distributed cache connection on a seek when too many in-flight bytes would otherwise be discarded. Defaults to 4 MiB; 0 restores the previous behavior (always reuse the connection via the read range id)."},
{"date_time_64_output_format_cut_trailing_zeros_align_to_groups_of_thousands", false, false, "The trimmed output scale widened from [0, 3, 6] to [0, 3, 6, 9], so a `DateTime64` or `Time64` value with scale 7 to 9 no longer loses the digits past the sixth. The default is unchanged; this row records the semantics change for the compatibility audit path."},

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.

@groeneai you just changed the setting description, why do need to add at the settings history?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right, removed in 290109d.

The row was inert on top of being unnecessary: applyCompatibilitySetting skips any entry whose previous_value equals the current value, and this one recorded false -> false because the default did not move. The behaviour change is unconditional code in writeDateTime64FractionalText, not a setting value, so SET compatibility = '26.7' still prints .000000700. Measured, so the row described a restore path that does not exist.

The 24.10 row that introduced the setting stays, so system.settings_changes still lists it and 03999_stateless_settings_history still passes.

Comment thread src/Core/FormatFactorySettings.h Outdated
corresponding to 'seconds', 'milliseconds', and 'microseconds')", 0) \
Dynamically trim the trailing zeros of `DateTime64` values, rounding the output scale up to the next
multiple of three that keeps every significant digit: [0, 3, 6, 9]. An all-zero fraction is dropped.
`Time64` is trimmed only by a direct scalar `toString` or `CAST`, and keeps three digits when all-zero.)", 0) \

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.

@groeneai remove the time64 reference here. This setting only applies to Datetime?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed in 290109d.

To answer the question though: it does apply to Time64, and it already did before this PR. FunctionsConversion.h routes Time64 through the same trimming writer on master, so toString(toTime64('100:00:00.123000', 6)) returns 100:00:00.123 with the setting on there too. What it does not reach is row output and nested values, because SerializationTime64::serializeText discards its FormatSettings.

None of that is new here, and master's description never mentioned Time64 either, so documenting the split belongs in its own change rather than in a description you asked to keep short. The asymmetry stays pinned by the test rows.

…ption

Two review asks on the same pair of lines.

The 26.8 SettingsChangesHistory.cpp row is inert. applyCompatibilitySetting
skips any entry whose previous_value equals its current value, and this row
records false -> false because the default did not move. The behaviour change
is unconditional code in writeDateTime64FractionalText, not a setting value, so
SET compatibility = '26.7' still prints .000000700. The row therefore described
a restore path that does not exist. The 24.10 row that introduced the setting
stays, so system.settings_changes still lists it and 03999 still passes.

The Time64 sentence is dropped from the setting description. The setting does
reach Time64 through a scalar toString or CAST, but that routing predates this
change (FunctionsConversion.h already called the trimming writer for Time64 on
master), so documenting it here mixes an unrelated pre-existing scope note into
a description that was asked to stay short. The asymmetry remains pinned by the
test rows and explained in the PR description.

Co-Authored-By: Claude Fable 5 <[email protected]>
@yariks5s yariks5s self-assigned this Aug 3, 2026
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 290109d

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (arm_asan_ubsan) / UndefinedBehaviorSanitizer: undefined behavior (STID 3587-3c65) float-to-Int64 overflow at WorkloadSettings.cpp:366 (1.47574e+20 cast to long) a fix task is moved to pending (investigating at full effort, fixing-PR link to follow on this PR)
Build (arm_release) / Post Hooks telemetry INSERT in build_profile_hook.py, job-level check_status = success a fix task is moved to pending (investigating at full effort, fixing-PR link to follow on this PR)

175/175 check-runs completed; Finish Workflow completed successfully.

The UBSan report is in WorkloadSettings::initFromChanges, the CPU-scheduler workload path. My diff
touches FormatFactorySettings.h and WriteHelpers.h (DateTime64/Time64 trailing-zero formatting)
plus one test, and no CREATE WORKLOAD code, so it cannot produce that cast. A fix task already owns
this signature and is being worked at full effort.

Session id: cron:our-pr-ci-monitor:20260803-163000

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the AST fuzzer (arm_asan_ubsan) / STID 3587-3c65 line on my CI finish ledger above: #113206.

That line read "a fix task is created" because no fixing PR existed at the time. It now does, so the owner column resolves to a PR link. The failure is a trunk bug in WorkloadSettings::initFromChanges (a bare static_cast<Int64> of an unbounded Float64 product), unrelated to this PR's diff.

Session id: cron:clickhouse-review-slot-11:20260803-223900

@PedroTadim

Copy link
Copy Markdown
Member

@yariks5s you can review this better than me. Thank you 🙏

@PedroTadim PedroTadim removed their assignment Aug 4, 2026
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

While working in this file I also noticed writeTimeTextCutTrailingZerosAlignToGroupOfThousands (src/IO/WriteHelpers.h:1149) passes three template arguments to the four-parameter writeTime64Text, so they bind as delimiter1=':', delimiter2='.', fractional_delimiter=(char)true and the cut flag keeps its default false: the function named for the cut does not perform it and would emit a \x01 byte in place of the . separator. It has no callers (git grep finds only its own definition, against three and five hits respectively for the working writeTime64TextCutTrailingZerosAlignToGroupOfThousands and writeDateTimeTextCutTrailingZerosAlignToGroupOfThousands siblings), so nothing reaches it, and scanning the reachable Time64 text surfaces with the setting on returns zero occurrences of that byte. I am not raising it as a separate issue or PR, since there is no user-reachable consequence, and the neighbouring SerializationTime64::serializeText gap is already described and pinned by the controls in this PR.

@yariks5s
yariks5s enabled auto-merge August 26, 2026 15:51
@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a3ccf022d with master 3eb72756a (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 711.97 MiB 708.91 MiB -3.06 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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a43bfd8

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
Docs examples / Function/catboostEvaluate#0 trunk defect, not from this PR: the docs-examples known-failures list still carries an entry for an example that no longer exists, so the job fails with "1 known failure(s) no longer exist and must be removed" #116566 (external, merged 2026-08-26T20:09:12Z). This run predates the fix, so merging master clears it.

Two independent measurements put the fix outside the tested tree: this run was dispatched at
2026-08-26T19:56:44Z, before #116566 merged, and the job's own output reports 2207 examples of 1603 entities (2089 ok, 118 not ok), which is the count without catboostEvaluate restored (it becomes 2208 of
1604 with the fix present). No other check failed on this head.

Session id: cron:our-pr-ci-monitor:20260827-043000

The only failure on the previous head was `Docs examples`. It tripped on a
known-failure entry for `catboostEvaluate`, whose example stopped existing when
the CatBoost integration was removed from master. ClickHouse#116566 reverted that removal
13 minutes after the previous run was dispatched, so the merge commit that run
tested predated the fix.

Co-Authored-By: Claude Opus 5 <[email protected]>
Comment on lines +761 to 762
multiple of three that keeps every significant digit: [0, 3, 6, 9]. An all-zero fraction is dropped.)", 0) \
DECLARE(Bool, input_format_read_datetime_number_as_raw_value, false, R"(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This description still over-promises the setting's DateTime64 contract. SerializationDateTime64::serializeText only consults date_time_64_output_format_cut_trailing_zeros_align_to_groups_of_thousands in the simple branch; the iso and unix_timestamp branches still ignore it and always print the declared scale. The new test already pins that divergence, so system.settings / help now tell users this trims generic DateTime64 output even in modes where it does not. Please narrow the wording to simple text output, or extend the non-simple branches to honor the setting.

@yariks5s
yariks5s added this pull request to the merge queue Aug 27, 2026
Merged via the queue into ClickHouse:master with commit c33fa1d Aug 27, 2026
179 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 27, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 25.8, 26.3, 26.5, 26.6, 26.7. I ran this PR's own regression test against each branch's binary and the bug reproduces there (the fix isn't present yet).

@groeneai

Copy link
Copy Markdown
Collaborator Author

The ask is right, the branch list is not.

Measured just now with one builds.clickhouse.com/<X.Y>/amd64/clickhouse binary per branch, running this PR's own 04671 test file. Affected and active (open release PR): 26.8, 26.7, 26.6, 26.3. All four produce byte-identical output and differ from a post-fix master binary (26.9.1.228, git 56c70e30f228, which has this PR's merge as an ancestor) in 32 result lines; that master binary reproduces the PR's .reference byte for byte, so the harness is honest. 25.8 and 26.5 do carry the buggy line, but their release PRs (#86119, #105429) are closed, so the automation cannot deliver to them. 26.8 was missing from the list and it is the current LTS.

The worst row is not the loss of trailing digits, it is a non-zero value printing as zero:

toDateTime64('2024-01-01 00:00:00.000000700', 9, 'UTC')
  26.8 / 26.7 / 26.6 / 26.3 ->  2024-01-01 00:00:00.000000
  fixed master             ->  2024-01-01 00:00:00.000000700

Port risk, from a 3-way merge per file against each branch tip with base c33fa1d8d459^1:

  • src/IO/WriteHelpers.h, which is the whole behaviour fix (two identical one-line changes): clean on all four, both lines land, no stale line left behind. It introduces no new symbol, there is no SettingsChangesHistory row, and every case in the one gtest_DateTimeToString instantiation that reaches the changed code is scale 6 or below, so none of them move.
  • src/Core/FormatFactorySettings.h, the setting description: clean on 26.8, one conflict on 26.7/26.6/26.3. The cause is only that the master side carries a neighbouring 26.8-era setting block (input_format_read_datetime_number_as_raw_value) which does not exist there; the two changed lines are identical on both sides, so the resolution is mechanical.
  • The test file is absent on every branch, so it is a pure add, and it runs end to end against the 26.3 binary (rc 0, all 167 result lines, toTime64 included).

@yariks5s could you apply v26.3-must-backport? Computed against the active set with select_backport_branches, that single label expands to exactly 26.8, 26.7, 26.6, 26.3. I am not hand-authoring release-branch PRs.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Hi @yariks5s, gentle ping: could you apply v26.3-must-backport here? It expands to exactly 26.8, 26.7, 26.6, 26.3, and all four print a non-zero DateTime64 sub-microsecond value as zero. Thanks.

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-request PR origin: a maintainer pinged or directed groeneai 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.

writeDateTime64FractionalText truncates significant digits for scale > 6

5 participants