Skip to content

Fix DateTime64 Protobuf range and preserve subsecond precision - #111920

Open
RamiDarwiche wants to merge 6 commits into
ClickHouse:masterfrom
RamiDarwiche:fix_datetime_serialization_overflow
Open

RamiDarwiche wants to merge 6 commits into
ClickHouse:masterfrom
RamiDarwiche:fix_datetime_serialization_overflow

Conversation

@RamiDarwiche

@RamiDarwiche RamiDarwiche commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #111860

DateTime64 was incorrectly being mapped to a uint64 during Protobuf auto schema resolution, causing an overflow error when values prior to the Unix epoch (negative values) were serialized. This effectively restricted the lower bound of DateTime64 values writable through auto-generated Protobuf schemas to 1970-01-01 00:00:00 rather than 0000-01-01 00:00:00, as suggested by the type's documentation.

Originally, DateTime64 used ProtobufSerializerDecimal, which was unaware of tick precision. The decimal serializer would call getWholePart and discard subseconds. This PR introduces ProtobufSerializerDateTime64 to retain subsecond time values during Protobuf serialization/deserialization. input_format_protobuf_datetime64_scale/output_format_protobuf_datetime64_scale settings were added to opt into scaled ticks when set to the DateTime64 column precision (mismatches are rejected). Left at -1 (the default), integer fields stay Unix seconds, so a file written at one precision still decodes to the same instant at another.

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 DateTime64 Protobuf auto-schema (maps to int64 instead of uint64) so pre-epoch values no longer raise DECIMAL_OVERFLOW. Serializes DateTime64 integer fields as Unix seconds by default so a precision change does not reinterpret the payload (set input_format_protobuf_datetime64_scale/output_format_protobuf_datetime64_scale to the column precision to keep subseconds as scaled ticks; mismatches are rejected).


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

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [235f63d]

Summary: ✅


AI Review

Summary

The PR maps DateTime64 to signed Protobuf integers and adds explicit scale settings for preserving subseconds while keeping Unix seconds as the default. At head 235f63d103b20e03972fa4a4b29c53468200e621, the default writer still shifts negative fractional timestamps into the following second. This existing finding remains unresolved.

Findings

❌ Blockers

  • src/Formats/ProtobufSerializer.cpp:1976 — Default integer output does not preserve the timestamp's whole Unix second before the epoch. DecimalUtils::getWholePart divides toward zero: 1969-12-31 23:59:59.500 in DateTime64(3) has ticks -500, which serialize as 0. Reading those bytes returns 1970-01-01 00:00:00.000, rather than 1969-12-31 23:59:59.000. Every negative timestamp with a fractional part is rounded into the following second. Compute seconds using division toward negative infinity; leave the opt-in tick path unchanged. Existing inline finding; no duplicate comment posted.
Tests
  • ⚠️ 04628_datetime64_protobuf_serializer_range.sh covers negative whole seconds and positive fractions, but misses their combination. Add a default-settings round-trip for 1969-12-31 23:59:59.500 and assert the wire integer is -1 and the decoded timestamp is 1969-12-31 23:59:59.000. This directly distinguishes the fix from the current implementation. No local tests were run; no ClickHouse binary or build directory was available.
Final Verdict

Status: ❌ Block. Correct the default conversion of negative fractional timestamps and add the focused regression above.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 28, 2026
@PedroTadim PedroTadim self-assigned this Jul 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.30% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.40% +0.10%

Changed lines: Changed C/C++ lines covered: 0/0 (nothing coverable) · Uncovered code

Full report · Diff report

@PedroTadim

Copy link
Copy Markdown
Member

@RamiDarwiche are you going to continue on this?

@RamiDarwiche

Copy link
Copy Markdown
Contributor Author

@PedroTadim Yes! Just a quick question, would it be better to separate the Time/Time64 implementations into their own PR? I believe they'd need their own serializers as well.

I'm finishing up the commit so that the DateTime64 extremes match the range in the documentation, the decimal serializer path doesn't handle subseconds.

@PedroTadim

Copy link
Copy Markdown
Member

@PedroTadim Yes! Just a quick question, would it be better to separate the Time/Time64 implementations into their own PR? I believe they'd need their own serializers as well.

I'm finishing up the commit so that the DateTime64 extremes match the range in the documentation, the decimal serializer path doesn't handle subseconds.

Sure, for Time/Time64 you can create another PR, and I can review it

@RamiDarwiche

Copy link
Copy Markdown
Contributor Author

@PedroTadim This latest commit introduces a new Protobuf serializer specifically for DateTime64 that enables sub-second precision and allows DateTime64 to reach the upper bound referenced in the documentation.

The value 0000-01-01 is causing an error where the year gets reset to the current year. I believe this is an issue with the best effort DateTime parsing path, where year is a UInt16 defaulted to 0 and !year is used to signify that a year was not supplied in the input. Parsing the literal year 0000 leaves year == 0, so the parser later treats it as unspecified and substitutes the current/previous year:

if (!year)
{
if constexpr (strict)
return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: year is required");
/// If year is not specified, it will be the current year if the date is unknown or not greater than today,
/// otherwise it will be the previous year.
/// This convoluted logic is needed to parse the syslog format, which looks as follows: "Mar 3 01:33:48".
/// If you have questions, ask Victor Krasnov, https://www.linkedin.com/in/vickr/
time_t now = time(nullptr);
auto today = local_time_zone.toDayNum(now);
UInt16 curr_year = local_time_zone.toYear(today);
year = local_time_zone.makeDayNum(curr_year, month, day_of_month) <= today ? curr_year : curr_year - 1;
}

Would you want the fix for this to be addressed as another commit in this PR?

@PedroTadim

Copy link
Copy Markdown
Member

@PedroTadim This latest commit introduces a new Protobuf serializer specifically for DateTime64 that enables sub-second precision and allows DateTime64 to reach the upper bound referenced in the documentation.

The value 0000-01-01 is causing an error where the year gets reset to the current year. I believe this is an issue with the best effort DateTime parsing path, where year is a UInt16 defaulted to 0 and !year is used to signify that a year was not supplied in the input. Parsing the literal year 0000 leaves year == 0, so the parser later treats it as unspecified and substitutes the current/previous year:

if (!year)
{
if constexpr (strict)
return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: year is required");
/// If year is not specified, it will be the current year if the date is unknown or not greater than today,
/// otherwise it will be the previous year.
/// This convoluted logic is needed to parse the syslog format, which looks as follows: "Mar 3 01:33:48".
/// If you have questions, ask Victor Krasnov, https://www.linkedin.com/in/vickr/
time_t now = time(nullptr);
auto today = local_time_zone.toDayNum(now);
UInt16 curr_year = local_time_zone.toYear(today);
year = local_time_zone.makeDayNum(curr_year, month, day_of_month) <= today ? curr_year : curr_year - 1;
}

Would you want the fix for this to be addressed as another commit in this PR?

You can address in this PR and update the description.

@RamiDarwiche RamiDarwiche changed the title Fix DateTime64 mapping to int64 in Protobuf auto schema Fix DateTime64 Protobuf range and preserve subsecond precision Jul 31, 2026
Comment thread src/Formats/ProtobufSerializer.cpp Resolved
Comment thread src/IO/ReadHelpers.h Resolved
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
@PedroTadim

Copy link
Copy Markdown
Member

@RamiDarwiche the tidy build failed

@RamiDarwiche

RamiDarwiche commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor Author

@PedroTadim Currently, the standard DateTime parsing can map 0000-00-00 00:00:00 to the Unix epoch when saturate on overflow is enabled:

if (unlikely(year == 0))
datetime = 0;
else
datetime = makeDateTime(date_lut, year, month, day, hour, minute, second);
}

Best-effort parsing throws an error for the same date:

else if (year == 0)
{
/// Calendar year 0 is only representable in DateTime64. For DateTime, accepting it produces a negative
/// time_t that convertFromTime later clamps to the Unix epoch, which looks like a successful parse of
/// 1970-01-01 (e.g. parseDateTimeBestEffortOrNull('0000')) despite year 0 being out of supported range.
// Throw an explicit error instead.
if constexpr (!is_64)
return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: year 0 is out of supported range");
}

For 0000-00-00 00:00:00 specifically, should best-effort parsing match standard parsing or continue to throw a range error?

@PedroTadim

Copy link
Copy Markdown
Member

@PedroTadim Currently, the standard DateTime parsing can map 0000-00-00 00:00:00 to the Unix epoch when saturate on overflow is enabled:

if (unlikely(year == 0))
datetime = 0;
else
datetime = makeDateTime(date_lut, year, month, day, hour, minute, second);
}

Best-effort parsing throws an error for the same date:

else if (year == 0)
{
/// Calendar year 0 is only representable in DateTime64. For DateTime, accepting it produces a negative
/// time_t that convertFromTime later clamps to the Unix epoch, which looks like a successful parse of
/// 1970-01-01 (e.g. parseDateTimeBestEffortOrNull('0000')) despite year 0 being out of supported range.
// Throw an explicit error instead.
if constexpr (!is_64)
return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: year 0 is out of supported range");
}

For 0000-00-00 00:00:00 specifically, should best-effort parsing match standard parsing or continue to throw a range error?

I would say it should match, This may become a backwards incompatible change, but it's fine because it's a very edge case.

Comment thread src/IO/parseDateTimeBestEffort.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 235f63d10 with master 4741b0dc4 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

504 object files changed (+91.38 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Formats/ProtobufSerializer.cpp.o 2.53 MiB 2.55 MiB +21.12 KiB (+0.81%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

3348 translation units recompiled, 18485 s compile time in total, 3347 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.8 s

Job report

Comment thread src/IO/ReadHelpers.h Resolved
@RamiDarwiche

Copy link
Copy Markdown
Contributor Author

@PedroTadim Can I get your thoughts on this approach to DateTime vs DateTime64 parsing paths? I'm not sure if these are the resolutions we want for the edge cases, but the impact on backward compatibility seems to be minimal so far.

SELECT
toDateTimeOrNull('0000-00-00 00:00:00', 'UTC'),
toDateTimeOrNull('0000-01-00 00:00:00', 'UTC'),
toDateTimeOrNull('0000-00-01 00:00:00', 'UTC'),
toDateTimeOrNull('0000-01-01 00:00:00', 'UTC');
SELECT toDateTime('0000-01-01 00:00:00', 'UTC'); -- { serverError CANNOT_PARSE_DATETIME }
SELECT
parseDateTimeBestEffortOrNull('0000-00-00 00:00:00', 'UTC'),
parseDateTimeBestEffortOrNull('0000-01-00 00:00:00', 'UTC'),
parseDateTimeBestEffortOrNull('0000-00-01 00:00:00', 'UTC'),
parseDateTimeBestEffortOrNull('0000-01-01 00:00:00', 'UTC'),
parseDateTimeBestEffortOrNull('0000', 'UTC'),
parseDateTimeBestEffortOrNull('0000-05', 'UTC');
SELECT
parseDateTime64BestEffortOrNull('0000-00-00 00:00:00', 3, 'UTC'),
parseDateTime64BestEffortOrNull('0000-01-00 00:00:00', 3, 'UTC'),
parseDateTime64BestEffortOrNull('0000-00-01 00:00:00', 3, 'UTC'),
parseDateTime64BestEffortOrNull('0000-01-01 00:00:00', 3, 'UTC'),
parseDateTime64BestEffortOrNull('0000', 3, 'UTC'),
parseDateTime64BestEffortOrNull('0000-05', 3, 'UTC');
SELECT *
FROM format(TSV, 't DateTime(\'UTC\')', '0000-01-00 00:00:00')
SETTINGS date_time_input_format = 'basic';
SELECT *
FROM format(TSV, 't DateTime(\'UTC\')', '0000-01-01 00:00:00')
SETTINGS date_time_input_format = 'basic'; -- { serverError CANNOT_PARSE_DATETIME }
SELECT *
FROM format(TSV, 't DateTime64(3, \'UTC\')', '0000-01-00 00:00:00')
SETTINGS date_time_input_format = 'basic';
SELECT *
FROM format(TSV, 't DateTime64(3, \'UTC\')', '0000-01-01 00:00:00')
SETTINGS date_time_input_format = 'basic';

1970-01-01 00:00:00 1970-01-01 00:00:00 1970-01-01 00:00:00 \N
1970-01-01 00:00:00 1970-01-01 00:00:00 1970-01-01 00:00:00 \N \N \N
1970-01-01 00:00:00.000 1970-01-01 00:00:00.000 1970-01-01 00:00:00.000 0000-01-01 00:00:00.000 0000-01-01 00:00:00.000 0000-05-01 00:00:00.000
1970-01-01 00:00:00
1970-01-01 00:00:00.000
0000-01-01 00:00:00.000

@PedroTadim

Copy link
Copy Markdown
Member

@PedroTadim Can I get your thoughts on this approach to DateTime vs DateTime64 parsing paths? I'm not sure if these are the resolutions we want for the edge cases, but the impact on backward compatibility seems to be minimal so far.

SELECT
toDateTimeOrNull('0000-00-00 00:00:00', 'UTC'),
toDateTimeOrNull('0000-01-00 00:00:00', 'UTC'),
toDateTimeOrNull('0000-00-01 00:00:00', 'UTC'),
toDateTimeOrNull('0000-01-01 00:00:00', 'UTC');
SELECT toDateTime('0000-01-01 00:00:00', 'UTC'); -- { serverError CANNOT_PARSE_DATETIME }
SELECT
parseDateTimeBestEffortOrNull('0000-00-00 00:00:00', 'UTC'),
parseDateTimeBestEffortOrNull('0000-01-00 00:00:00', 'UTC'),
parseDateTimeBestEffortOrNull('0000-00-01 00:00:00', 'UTC'),
parseDateTimeBestEffortOrNull('0000-01-01 00:00:00', 'UTC'),
parseDateTimeBestEffortOrNull('0000', 'UTC'),
parseDateTimeBestEffortOrNull('0000-05', 'UTC');
SELECT
parseDateTime64BestEffortOrNull('0000-00-00 00:00:00', 3, 'UTC'),
parseDateTime64BestEffortOrNull('0000-01-00 00:00:00', 3, 'UTC'),
parseDateTime64BestEffortOrNull('0000-00-01 00:00:00', 3, 'UTC'),
parseDateTime64BestEffortOrNull('0000-01-01 00:00:00', 3, 'UTC'),
parseDateTime64BestEffortOrNull('0000', 3, 'UTC'),
parseDateTime64BestEffortOrNull('0000-05', 3, 'UTC');
SELECT *
FROM format(TSV, 't DateTime(\'UTC\')', '0000-01-00 00:00:00')
SETTINGS date_time_input_format = 'basic';
SELECT *
FROM format(TSV, 't DateTime(\'UTC\')', '0000-01-01 00:00:00')
SETTINGS date_time_input_format = 'basic'; -- { serverError CANNOT_PARSE_DATETIME }
SELECT *
FROM format(TSV, 't DateTime64(3, \'UTC\')', '0000-01-00 00:00:00')
SETTINGS date_time_input_format = 'basic';
SELECT *
FROM format(TSV, 't DateTime64(3, \'UTC\')', '0000-01-01 00:00:00')
SETTINGS date_time_input_format = 'basic';

1970-01-01 00:00:00 1970-01-01 00:00:00 1970-01-01 00:00:00 \N
1970-01-01 00:00:00 1970-01-01 00:00:00 1970-01-01 00:00:00 \N \N \N
1970-01-01 00:00:00.000 1970-01-01 00:00:00.000 1970-01-01 00:00:00.000 0000-01-01 00:00:00.000 0000-01-01 00:00:00.000 0000-05-01 00:00:00.000
1970-01-01 00:00:00
1970-01-01 00:00:00.000
0000-01-01 00:00:00.000

So far it seems good to me.

@RamiDarwiche

Copy link
Copy Markdown
Contributor Author

@PedroTadim Is there anything remaining that you'd want addressed in this PR? I'm also not sure how to resolve the Bugfix validation check failure. Thanks!

@PedroTadim

Copy link
Copy Markdown
Member

@RamiDarwiche can you merge with master and fix the conflicts for a final run? @yariks5s can also give a final look

@RamiDarwiche
RamiDarwiche force-pushed the fix_datetime_serialization_overflow branch from e1f3d13 to 25d9d46 Compare August 29, 2026 04:09
Comment thread src/IO/parseDateTimeBestEffort.cpp Resolved
Comment thread src/IO/ReadHelpers.h Resolved
Comment thread src/IO/parseDateTimeBestEffort.cpp Resolved
@PedroTadim

PedroTadim commented Sep 3, 2026 •

Copy link
Copy Markdown
Member

@RamiDarwiche this PR is too big, we should split in 2:

  1. Protobuf-only PR — StructureToProtobufSchema.cpp int64 mapping, ProtobufSerializer tick-scaled DateTime64, the two *_protobuf_datetime64_legacy_seconds settings, SettingsChangesHistory, and the Protobuf tests. That's the bug in the title, it's independently reviewable, and it should be uncontroversial. This one.

  2. Year-zero parser PR — the ReadHelpers.h / parseDateTimeBestEffort.cpp / getValidUntilFromAST.cpp changes, labelled Backward Incompatible Change, with the toDateTime vs toDateTimeOrNull inconsistency stated as the motivation and the 03145 change explained. In a new PR.

@RamiDarwiche

Copy link
Copy Markdown
Contributor Author

@PedroTadim I definitely agree, I'll separate the changes and leave this PR focused on Protobufs.

@clickhouse-gh clickhouse-gh Bot added the comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). label Sep 4, 2026
Comment thread src/Formats/ProtobufSerializer.cpp Resolved
Comment thread src/Formats/ProtobufSerializer.cpp Resolved
Comment thread src/Formats/ProtobufSerializer.cpp Resolved
@PedroTadim

Copy link
Copy Markdown
Member

@RamiDarwiche merge with master one more time. I want to get this merged this week at most.

🕵️
The new integer wire format depends on the writer’s DateTime64 precision, but neither the .proto nor the payload records it.
The test already shows 2020-01-01 written as DateTime64(0) becoming 1970-01-19 06:17:16.800 when read as DateTime64(3).
This silently changes timestamps when producers and consumers use different precisions, including during schema evolution.
The legacy-seconds switch cannot describe arbitrary source precisions, such as microseconds read into a millisecond column.
Could we keep seconds as the default and make ticks opt-in with an explicit matching-precision requirement, or carry source-scale metadata and rescale on read?

Comment thread src/Formats/ProtobufSerializer.cpp Outdated
{
switch (field_typeid)
{
case FieldTypeId::TYPE_INT32: {

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.

@RamiDarwiche could you use a c++ template to remove the duplicate code?

Comment thread src/Formats/ProtobufSerializer.cpp Outdated
}

case FieldTypeId::TYPE_FLOAT: {
/// Float/double schemas always store fractional Unix seconds.

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.

another template could be possible for the floating-point types

Comment thread src/Core/FormatFactorySettings.h Resolved
@PedroTadim

Copy link
Copy Markdown
Member

@RamiDarwiche please squash the commits

@RamiDarwiche
RamiDarwiche force-pushed the fix_datetime_serialization_overflow branch from 5474bd7 to add9c8e Compare September 22, 2026 15:02
if (!output_scaled_ticks)
{
/// Integer protobuf fields store whole Unix seconds unless scaled ticks were explicitly selected.
return DecimalUtils::getWholePart(value, scale);

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.

The default integer-seconds path still misencodes negative fractional DateTime64 values here. DecimalUtils::getWholePart truncates toward zero, so with scale = 3 the timestamp 1969-12-31 23:59:59.500 (value.value == -500) writes 0 instead of -1; ticksFromNumericField then reads that back as 1970-01-01 00:00:00.000 instead of 1969-12-31 23:59:59.000.

That means the new "Unix seconds by default" contract is still wrong for every pre-epoch value with a fractional part. Can we floor toward negative infinity before emitting the integer seconds (or reuse a helper that already does that split for DateTime64 elsewhere) and add a focused regression on the default -1 path?

@PedroTadim

Copy link
Copy Markdown
Member

@yariks5s can you help to give a final look?

…ization_overflow

Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Dear @PedroTadim, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@PedroTadim PedroTadim self-assigned this Oct 26, 2026
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026

This branch has not been deployed

No deployments
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 comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). external Author is not a member of the ClickHouse organization pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Convert overflow Serializing DateTime64 < epoch to Protobuf

4 participants