Skip to content

Update ReadHelpers.h (parse small decimal timestamps correctly) - #86431

Open
egbaydarov wants to merge 104 commits into
ClickHouse:masterfrom
egbaydarov:master
Open

egbaydarov wants to merge 104 commits into
ClickHouse:masterfrom
egbaydarov:master

Conversation

@egbaydarov

@egbaydarov egbaydarov commented Aug 31, 2025 •

Copy link
Copy Markdown

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

Fixed parsing of small decimal and short numeric DateTime64 strings as Unix timestamps.

Details

Closes: #86430
Closes: #118354


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

@CLAassistant

CLAassistant commented Aug 31, 2025 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@alexey-milovidov

Copy link
Copy Markdown
Member

A test?

@egbaydarov

egbaydarov commented Aug 31, 2025 •

Copy link
Copy Markdown
Author

I found many more corner cases, in same logical part in parsing, in the method
template <typename ReturnType, bool dt64_mode> ReturnType readDateTimeTextFallback.
The code isn’t ready yet for that specific cases, but I’ll work on fixing it soon

https://github.com/clickhouse/ClickHouse/blob/2e44f6fdca7d557879be586e96d847136c0347a9/src/IO/ReadHelpers.cpp#L1460-L1482

@egbaydarov egbaydarov changed the title Update ReadHelpers.h wip: Update ReadHelpers.h Aug 31, 2025
@egbaydarov
egbaydarov force-pushed the master branch 2 times, most recently from 1681eb9 to b13e686 Compare August 31, 2025 19:41
@egbaydarov egbaydarov closed this Aug 31, 2025
@egbaydarov egbaydarov reopened this Aug 31, 2025
@egbaydarov

egbaydarov commented Aug 31, 2025 •

Copy link
Copy Markdown
Author

I suppose it's done for now.
I also have added some functional tests.. @alexey-milovidov

tldr

After calling the method:

inline ReturnType readDateTimeTextImpl(DateTime64 & datetime64, UInt32 scale, ReadBuffer & buf, const DateLUTImpl & date_lut, const char * allowed_date_delimiters = nullptr, const char * allowed_time_delimiters = nullptr)

the execution may proceed along three distinct paths.

  1. Optimistic Path

    Input must contain at least 19 characters.
    The timestamp is expected to follow the ISO 8601 format:

    YYYY-MM-DDThh:mm:ss

    Example:

    2025-08-31T15:33:38

  2. Integer Parsing Path

    Length is sufficient, but the byte sequence does not match
    the expected ISO 8601 pattern.
    The parser assumes the value represents a Unix integer timestamp.

  3. Short Buffer Path

    Triggered when fewer than 19 bytes are available in the buffer.
    This case is handled in:

    template <typename ReturnType, bool dt64_mode>

    The routine performs a slower parse capable of handling both
    ISO 8601 and Unix integer formats.

Buffer Semantics

After parsing, the buffer may still contain metadata (depending on
the format) or at least a separator character between columns.

The current implementation attempts to optimize by avoiding
explicit boundary checks, parsing everything in a single pass.
This approach can produce incorrect behavior in certain corner
cases, such as reading into the next column and misinterpreting
those bytes as an ISO 8601 timestamp. Similar issues are possible
in the short buffer path.

Proposed Modification

ISO 8601 parsing should be made more conservative.
A validity check on the separator characters between year,
month, and day will be enforced:

YYYY-MM-DD

This measure prevents most false positives, including small
integer values that are unlikely to contain valid separators.

Future Work

In the longer term, parsing could be refactored with a stricter
separator validation scheme. Some helper functions already expose
parameters suggesting support for this, but the implementation does
not yet enforce it.

Current Changes

The short buffer path has been removed as redundant.
Observed behavior remains unchanged.

The compatible flow is now defined as:

a) Attempt ISO 8601 optimistic parse if length is sufficient.
b) If not, attempt optimistic date-only format.
c) Otherwise, parse as Unix integer timestamp.

The calling method:

inline ReturnType readDateTimeTextImpl(DateTime64 & datetime64, UInt32 scale, ReadBuffer & buf, const DateLUTImpl & date_lut, const char * allowed_date_delimiters = nullptr, const char * allowed_time_delimiters = nullptr)

already implements a workaround for decimal Unix timestamps with
fractional components. This logic has not been modified.

I was curious and looked for further optimizations to improve both correctness
and performance. I found some pretty interesting implementations of bulk ASCII integer parsing in simdjson and Apache Arrow around datetime buffer parsing (possibly not as valid for row-oriented formats):

Comment thread src/IO/ReadHelpers.cpp Resolved
@egbaydarov egbaydarov changed the title wip: Update ReadHelpers.h Update ReadHelpers.h Aug 31, 2025
@egbaydarov egbaydarov changed the title Update ReadHelpers.h Update ReadHelpers.h (parse small decimal timestamps correctly) Aug 31, 2025
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1a5e828]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR fixes small numeric DateTime64 timestamps, preserves negative subseconds, and tightens whole-value parsing in import adapters. Reviewed head 1a5e828af6206551c2f1f17de0cb01d08e09052d, the full diff, and all prior discussion. All 66 local parser probes passed across six precisions and eleven buffer sizes, but the two existing import findings remain unresolved. No duplicate inline comments were posted.

Findings

❌ Blockers

  • src/Processors/Sources/SQLiteStatementReader.cpp:88: The new EOF check rejects previously readable SQLite timestamps ending in lowercase z or whitespace after the time-zone indicator, including 2024-01-02 03:04:05z, 2024-01-02 03:04:05Z , and 2024-01-02 03:04:05+00:00 . assertSQLiteDateTimeFullyParsed accepts only uppercase Z and skips spaces only before the indicator. These are accepted SQLite timestamp forms, so existing SQLite tables mapped to DateTime('UTC') become unreadable. Preserve the accepted suffix grammar, including trailing whitespace, and extend 05621_sqlite_datetime_time_zone_indicator. Existing unresolved thread.

⚠️ Majors

  • src/Core/PostgreSQL/insertPostgreSQLValue.cpp:61: assertPostgreSQLDateTimeFullyParsed unconditionally skips fractional seconds even after readDateTime64Text has already consumed them. A PostgreSQL text value of 1234.5.6 is consequently accepted as 1970-01-01 00:20:34.500; 2025-01-02 03:04:05.5.6 has the same problem. Both scalar and array DateTime64 readers call this helper. Skip the fraction only for plain DateTime; after DateTime64, allow only the optional PostgreSQL offset and EOF. Add scalar and array rejection cases for a second fraction. Existing unresolved thread.
Final Verdict

Status: ❌ Block

Preserve SQLite's accepted timestamp suffixes and prevent the PostgreSQL DateTime64 readers from discarding a second fractional tail, with focused regression coverage.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 1, 2025
@egbaydarov

Copy link
Copy Markdown
Author

Hi, could one of the maintainers take a look at this PR?
At first, I only wanted to highlight the issue, but now it already includes a working fix.
@alexey-milovidov @azat

@rienath rienath added the can be tested Allows running workflows for external contributors label Sep 8, 2025
@egbaydarov

egbaydarov commented Sep 10, 2025 •

Copy link
Copy Markdown
Author

@rienath Hi, it looks like all the tests passed successfully

@clickhouse-gh

clickhouse-gh Bot commented Oct 21, 2025

Copy link
Copy Markdown
Contributor

Dear @yariks5s, this PR hasn't been updated for a while. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

Dear @serxa, 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.

alexey-milovidov and others added 4 commits October 19, 2026 15:13
# Conflicts:
#	src/Core/PostgreSQL/insertPostgreSQLValue.cpp
…eSQL UTC offset

`assertPostgreSQLDateTimeFullyParsed` validated only the shape of the UTC offset suffix,
so values like `2025-01-02 03:04:05+03:60` or `+03:30:60` were accepted. PostgreSQL never
renders a minutes or seconds group of 60 or more, so reject such values.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eys in `05217`

The test was added on master and expects `CANNOT_PARSE_TEXT` when a `String`
like `bad` is converted to a `DateTime` dictionary key. This PR intentionally
makes the `DateTime` text parser reject a value starting with a character that
can be neither a date nor a timestamp with `CANNOT_PARSE_DATETIME`, instead of
leaving the unix epoch and relying on the caller to report trailing characters.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=86431&sha=latest&name_0=PR&name_1=Fast%20test
ClickHouse#86431

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged current master (clean) and fixed the only real CI red (Fast test, 05217_inverse_dictionary_lookup_conversion_semantics). That test was added on master after the last run here, and it expects CANNOT_PARSE_TEXT when the String bad is converted to a DateTime dictionary key under cast_string_to_date_time_mode = 'best_effort'. This PR makes the DateTime text parser reject a value that starts with a character that can be neither a date nor a timestamp, so it now throws CANNOT_PARSE_DATETIME. That is the intended behavior, so the four affected expectations now say CANNOT_PARSE_DATETIME (f7c9315). Ran it locally, together with all 15 stateless tests this PR touches: all pass. The Finish Workflow / bugfix-validation red came only from the Fast test failure.

Comment thread src/IO/ReadHelpers.h Resolved
Comment thread src/IO/ReadHelpers.cpp Resolved
alexey-milovidov and others added 3 commits October 27, 2026 04:07
# Conflicts:
#	src/IO/ReadHelpers.h
… a broken-down date

Matching separators at positions 4 and 7 alone let a small decimal `DateTime64`
timestamp such as `1234.5` followed by a leading-dot field (`1234.5<TAB>.25`)
be read as a `YYYY.MM.DD` date across the field delimiter. Require the digits of
the year, month and day as the fallback does, on the throwing path too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rtition literal

`convertPartitionFieldToType` classified `'1234.5'` as a broken-down date because
of the fifth character, and rejected a value that the parser reads as a unix
timestamp. Treat it as a timestamp unless it has the `YYYY.MM.DD` layout, so that
the fractional-precision check applies to it. Add a test for both review findings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=86431&sha=f7c9315f1da2f8f17d2cdc6970b9c78c81d5d064&name_0=PR&name_1=Stateless%20tests%20(amd_debug%2C%20distributed%20plan%2C%20s3%20storage%2C%20parallel) (04950_distributed_plan_runtime_filter_delivery_from_join_stage is flaky, 9 of 67 reruns failed, even after a113d43) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is #126385 (merged 2026-10-20 02:09 UTC). The failed run here was created 2026-10-19 17:36 UTC for f7c9315, before the merge, so its tree did not have the fix. Your new head 56677d6 contains it (its run started 04:50 UTC today).

Cause: a113d43 fixed a different race (a build task dropping its partial filter). This one: when the random MergeTree setting auto_statistics_types includes tdigest, the merged per-part TDigests were left unsorted, so the range estimate for the big side could be 0 rows and the planner refused to transport the runtime filter (both checks print 0). The failed job here had auto_statistics_types tdigest,countmin,uniq_v2.

Since the merge: 0 failures in 4,186 master runs; the only failure in about 29,000 PR runs was a re-run of a workflow created before the merge.

@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
alexey-milovidov and others added 2 commits November 4, 2026 00:30
…t layout

Since 2887cc2 the `DateTime` text parser takes the broken-down date path
only when the year, month and day digits are present, so garbage such as
`'20/4-03-01 00:00:00'` and `'\0930-12-12 ...'` is now rejected with
`CANNOT_PARSE_DATETIME` / `TYPE_MISMATCH` instead of being read as a nonsense date.

- `05258_drop_partition_invalid_date_literal`: expect the parser error for `'20/4-03-01 00:00:00'`.
- `02269_to_start_of_interval_overflow`: the garbage literal only served to produce a
  far-out-of-range value; use the valid `'2299-12-31 23:59:59.999'` instead, which still
  triggers `DECIMAL_OVERFLOW` in `toStartOfInterval` with a nanosecond interval.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=86431&sha=56677d61ee38b0109e19b5dacc51ceb08c588d83&name_0=PR&name_1=Fast%20test
PR: ClickHouse#86431

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged current master and fixed the Fast test red on 56677d6 (2968f8c). Since 2887cc2 the DateTime parser takes the broken-down date path only when the date digit layout is present, so garbage strings are now rejected by the parser instead of being read as a nonsense date:

  • 05258_drop_partition_invalid_date_literal: '20/4-03-01 00:00:00' now gets CANNOT_PARSE_DATETIME (DateTime) / TYPE_MISMATCH (DateTime64) instead of INVALID_PARTITION_VALUE.
  • 02269_to_start_of_interval_overflow: '\\0930-12-12 ...' was only there to produce an out-of-range value. I replaced it with the valid '2299-12-31 23:59:59.999', which still raises DECIMAL_OVERFLOW.

All 13 stateless .sql tests this PR touches pass locally on the merged tree. The Finish Workflow red was a cascade of the Fast test failure. @groeneai: thanks, #126385 is now included through the merge.

The Delta protocol permits timestamp partition values such as
`2024-01-02T03:04:05.123456Z`. The new `assertEOF` in
`DeltaLakeMetadata::getFieldValue` rejected them because
`readDateTime64Text` leaves the trailing `Z` unread. Strip a trailing `Z`
and parse the value in UTC; other trailing characters are still rejected.

Add a regression test for the legacy reader (`allow_delta_kernel_rs = 0`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/IO/ReadHelpers.h Resolved
alexey-milovidov and others added 3 commits November 11, 2026 20:17
`DeltaLakeMetadata.cpp` (the legacy Delta Lake reader) was removed in master, so the PR's
change to it and its legacy-only test `05497_delta_lake_legacy_timestamp_partition_utc`
are dropped.
Schema inference (`tryInferDateTime`, `tryInferDateTime64`) passes `-/:` as the allowed
date delimiters and infers a value like `2024:01:02 03:04:05` as `DateTime`, but the
deserializer calls the parser without explicit delimiters, and the default set (`-`, `/`,
`.`) rejected it, so a value that is inferred could not be read. Add ':' to the default set
in both the optimistic and the fallback paths (the digit-layout checks are kept).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
SQLite date and time values may end with `Z` or `[+-]HH:MM`
(https://www.sqlite.org/lang_datefunc.html#time_values). They were silently ignored before,
but the new end-of-input check rejected them. Accept a well-formed time zone indicator
(not applied, as before) and keep rejecting malformed ones and other trailing characters.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/IO/ReadHelpers.h Resolved
alexey-milovidov and others added 3 commits November 19, 2026 21:38
…ed partition literals like the parser

The `DateTime64` text parser recovered from any exception of the whole part when positioned at a dot,
which turned malformed values whose date-shaped prefix was consumed across a buffer refill (e.g.
`1234.56..78`, `2025-01-.5`) into unrelated timestamps. Leading-dot fractions are handled explicitly by
both the optimistic path and the fallback, so the recovery is removed.

The partition literal check now classifies a `DateTime`/`DateTime64` literal as a broken-down date with
the same digit-layout and sign rule as `readDateTimeTextImpl`, so a signed timestamp like `+123.5` can
be used as a partition literal.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
throw Exception(ErrorCodes::CANNOT_PARSE_DATETIME, "Invalid minutes in the time zone indicator of a date and time value");
}

assertEOF(in);

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.

[Blocker] Preserve SQLite's accepted time-zone suffix syntax

This EOF check rejects existing SQLite timestamp values such as 2024-01-02 03:04:05Z , 2024-01-02 03:04:05+00:00 and 2024-01-02 03:04:05z. SQLite accepts all three as the same timestamp: its parseTimezone accepts lowercase z and skips whitespace before and after the indicator. Here only uppercase Z and spaces before the indicator are handled, so selecting these values through a SQLite table declared with DateTime('UTC') now throws CANNOT_PARSE_INPUT_ASSERTION_FAILED; the previous reader accepted them.

Please preserve that suffix grammar before enforcing EOF, including whitespace after the indicator, and extend 05621_sqlite_datetime_time_zone_indicator with these cases. Genuine trailing text should still fail.

/// rather than waved through as "digits and colons in some order".
void assertPostgreSQLDateTimeFullyParsed(ReadBuffer & in)
{
skipDateTimeFractionalSeconds(in);

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.

[Major] Do not skip a second fraction for DateTime64

This helper is also called after readDateTime64Text, which has already consumed the fractional seconds. With a PostgreSQL text value of 1234.5.6, the parser consumes 1234.5, this unconditional call discards .6, and EOF validation succeeds: the imported value is silently 1970-01-01 00:20:34.500. The same happens for 2025-01-02 03:04:05.5.6 and for Array(DateTime64(3, 'UTC')) mapped from PostgreSQL text[].

Only skip fractional seconds for the plain DateTime callers. After a DateTime64 parse, accept only the optional PostgreSQL offset and EOF, and add scalar/array regressions for a second fractional tail.

@nickitat

Copy link
Copy Markdown
Member

I merged master into this branch to pick up #133069.

Since 2026-11-19, stateless tests randomize the MergeTree setting enable_adaptive_codec_selection, and 05293_autopr_statistics_plan_based failed in this PR's CI because of that, not because of the changes here. The fix pins the setting in the test; it is in master now, so the next CI run should not hit it.

🤖 Generated with Claude Code

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-datetime Date/DateTime/TimeZone datatypes and date-time semantics. external Author is not a member of the ClickHouse organization pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet