Repository navigation
Parse unquoted JSON numbers for DateTime64 and DateTime as Unix timestamps - #108091
Conversation
…tamps An unquoted JSON number such as `1703363853.035` was rejected when inserted into a `DateTime64` column via `JSONEachRow` (and the other JSON/Quoted text paths), because the unquoted-number branch used `readIntText`, which stops at the decimal point and leaves `.035` unparsed, raising `CANNOT_PARSE_INPUT_ASSERTION_FAILED`. The same number is accepted by the `Values` format. For `DateTime64`, `readIntText` also read a bare integer straight into the raw underlying (scaled) value, so `1703363853` was interpreted as ticks (`1970-01-20 ...`) rather than seconds, inconsistent with `Values`, `CAST` and `toDateTime64`. Now an unquoted number is parsed as a decimal value at the column scale, i.e. a Unix timestamp (seconds since the epoch) with optional sub-second precision, matching `Values`, `CAST`, `toDateTime64` and the `Decimal` type (`DateTime64` is a `Decimal` underneath). One more digit than `Decimal`'s precision is allowed so that a 10-digit second count is still valid at scale 9. `DateTime` truncates the fractional part to whole seconds, also matching `CAST`. Closes: #59443 Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Workflow [PR], commit [50f9d0c] Summary: ✅
AI ReviewSummaryThis PR makes unquoted numeric Missing context / blind spots
Final Verdict✅ Approve. No new inline findings to post. |
… detect Int64 overflow The unquoted-number branch read the value straight into the `Int64` ticks of `DateTime64` with one extra digit of precision allowed. As the AI review noted, `readDecimalText` accumulates into the destination type, whose `Decimal` operators wrap, so a 19-digit input just above the `Int64` boundary (e.g. `9223372036854775808` for `DateTime64(0)`) could wrap during accumulation and then pass the final scale-multiplication check as a bogus, often negative, timestamp. Read into a `Decimal128` temporary instead, apply the remaining scale in `Int128`, then range-check the result against the `Int64` ticks of `DateTime64` and raise `DECIMAL_OVERFLOW` if it does not fit. A 128-bit accumulator holds up to `max_precision<Decimal128>` (38) digits, which spans the whole valid range at every scale, so no in-range value is rejected and no out-of-range value wraps. This also makes a too-large value report `DECIMAL_OVERFLOW` rather than `ARGUMENT_OUT_OF_BOUND`, matching the error the `Values` expression fallback produces (fixes the `03797_convert_field_to_type_decimal_overflow` regression). Adds boundary coverage to `04402_json_datetime64_number_input`: `Int64` max/min are stored exactly, and values one step outside the range are rejected instead of silently wrapped. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…mantics A bare unquoted integer for a `DateTime64` column in the `Values`/Quoted text path is now a Unix timestamp in seconds rather than the raw scaled value, so tests that fed such an integer to a `DateTime64` column need their inputs (or references) adjusted: - `01516_date_time_output_format`: `1602709200123` (raw ms ticks) becomes `1602709200.123`, which is the same instant under the new rule, keeping the reference unchanged. - `02519_monotonicity_fuzz`: `1000` (one second of ticks) becomes `1`, one second since the epoch, keeping the reference unchanged. - `01732_more_consistent_datetime64_parsing`: the integer row is now whole seconds (`1111111111`); the other forms are unchanged. - `00927_asof_join_other_types`: the `DateTime64(3)` rows now read `1`, `3`, `5` as seconds, which incidentally makes them consistent with the `DateTime` rows in the same test. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The backward-incompatible parser change makes a bare unquoted integer for a `DateTime64` column a Unix timestamp in seconds (matching `DateTime`, the `Values` format, `CAST` and `toDateTime64`) instead of the raw scaled ticks. The user doc `docs/en/sql-reference/data-types/datetime64.md` and the matching source documentation in `src/DataTypes/registerDataTypeDateTime.cpp` still described the old contract (an integer interpreted as scaled ticks, e.g. `1546300800000` at precision 3), which would now parse to a different instant. Update both to describe a number as a Unix timestamp in seconds with optional sub-second precision, change the example insert from `1546300800123` to `1546300800`, and add a backward-incompatible-change note pointing out that a bare integer used to be interpreted as raw ticks before version 26.7. Quoted strings and ClickHouse's own (always quoted) output are unaffected. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The 04402 prefix now has many tests in master after the merge; move the new DateTime64 number-input test to the free 04489 slot. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed the work that addresses the AI Review ❌ Block (the commits were prepared but not yet on the branch): Minimum required actions from the verdict, all done:
The existing tests broken by the behavior change were updated to keep their original intent: Also merged the latest |
The sentence "Contrary to inserting, the `toDateTime64` function will treat all values as the decimal variant" described the pre-26.7 behavior, where an inserted number was the raw scaled value while `toDateTime64` interpreted a number as seconds. Now that an inserted number is also a Unix timestamp in seconds, the contrast no longer holds and the sentence contradicted the new insertion contract. Reword it in both `docs/en/sql-reference/data-types/datetime64.md` and the mirrored source documentation in `src/DataTypes/registerDataTypeDateTime.cpp`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The `YTsaurus` engine reads YT data via `JSONEachRow` and maps the YT `timestamp`/`timestamp64` types (microseconds since the epoch) to `DateTime64(6)`, relying on an unquoted JSON number being stored as the raw underlying value (ticks). This PR changed an unquoted number to mean a Unix timestamp in seconds, so a real YT timestamp such as `1703363853000000` would be interpreted as seconds and rejected with `DECIMAL_OVERFLOW`. Add a `read_datetime64_number_as_raw_value` JSON format setting that restores the raw-ticks interpretation of an unquoted number for `DateTime64` columns, and enable it in `YTsaurusSource`. The setting is internal (set only by the `YTsaurus` reader) and defaults to off, so the user-facing JSON/Quoted parsing behavior is unchanged. Fixes the integration test `test_ytsaurus/test_tables.py::test_ytsaurus_primitive_types[timestamp0]` and `[timestamp1]`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
An unquoted number for a `DateTime64` column is now interpreted as a Unix timestamp in seconds. The `VALUES` insert in this test used raw millisecond ticks (`1639872000000`, `1639872891123`, `42`) which under the new semantics overflow or shift to a different instant. Use the equivalent seconds form (`1639872000`, `1639872891.123`, `0.042`) so the stored ticks, the `MsgPack` round-trip and the reference output are all unchanged. `readDecimalText` parses these exactly, so the stored values are bit-identical to before. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed 1. Docs (the sole blocking action / unresolved thread, 2. 3. Remaining red — Verification: the three changed translation units pass |
… `DateTime64` The `DateTime` unquoted-number path used `readIntText` followed by a manual `.`-only fraction skip, so a valid JSON number in exponent form such as `1.703363853e9` or `1703363853.0e0` left the `e...` suffix unread and the row was rejected by `JSONEachRow` - even though the `DateTime64` path (which uses `readDecimalText`) already accepts it and the PR contract promises unquoted JSON numbers behave like Unix timestamps matching `CAST`. Parse the `DateTime` number with the same decimal-aware `readDecimalText` logic used by `DateTime64`, but at scale 0: `DateTime` has whole-second resolution, so any sub-second part (from a fraction or a net-negative exponent) is truncated to whole seconds, matching `CAST`, `toDateTime` and the `Values` format. The value is accumulated in a 128-bit temporary and clamped to the `DateTime` range, as before for out-of-range numbers. Addresses the AI Review finding on `SerializationDateTime.cpp`.
Add exponent-notation cases (`1.703363853e9`, `1703363853.0e0`) for an unquoted `DateTime` number to `04489_json_datetime64_number_input`, alongside the existing `DateTime64` exponent case, and assert they match `CAST(1.703363853e9 AS DateTime)`. Renumber the test from `04489` to `04492`: `04489` is now taken on `master` by `04489_max_threads_auto_parsing_compat`, and `04490`/`04491` are also taken, so `04492` is the next free prefix.
|
Pushed 1. 2. Test ( The unresolved review thread is resolved. The changed translation unit passes |
The unquoted-number paths of `SerializationDateTime64` and `SerializationDateTime`
parse a Unix timestamp with `readDecimalText` and `digits_only = false`, which stops
at the first non-numeric character so the `,`/`}` that follows the value in JSON is
left for the format layer. That same leniency, however, also accepted a token with no
digits at all: `.`, `-` and `e9` were each consumed as the value zero, so a malformed
row such as `{"t":.}` was silently loaded as the Unix epoch instead of being rejected.
The previous `readIntText`-based code left such suffixes unread, so those rows did not
become data.
`readDigits`/`readDecimalText` now optionally report whether at least one digit
character was read. A bare `0` reads as zero but still has a digit, so the meaningful
`digits` output (which is 0 for a leading zero) cannot be used for this. The
`DateTime64`/`DateTime` readers pass this flag and raise `CANNOT_PARSE_DATETIME` (or
fail the try-path) when no digit was present. The new out-parameter defaults to null,
so every other `readDecimalText` caller is unaffected.
Also drop the redundant `static` from `datetime_number_precision` in the anonymous
namespace, which broke the `Build (arm_tidy)` check with
`readability-static-definition-in-anonymous-namespace`.
Adds malformed-token regression coverage (`{"t":.}`, `{"t":-}`, `{"t":e9}`) for both
`DateTime64` and `DateTime` to `04492_json_datetime64_number_input`.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108091&sha=e2bc6a5e9c78758d3641312329512492d405c0ed&name_0=PR
PR: #108091
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed 1. Malformed unquoted numeric tokens (the AI Major / unresolved thread). 2. 3. Tests. Added the requested malformed-token cases ( The documentation checkbox is now checked (the Verification: the two changed serialization translation units pass |
…tamp parsing change The `Fast test` failed on `03371_dynamic_values_parsing_templates` with `result differs with reference`. This fuzzer-generated test inserts a large heterogeneous set of values into a `Dynamic` column via the `VALUES` format, which uses the constant-expression template parser (hence the test name). For one garbage row whose field is the array literal `['你们', '认识你很高兴', x'E28228FF', '哪国人']`, the template deduced from an earlier row reads the field through the unquoted-number `DateTime` path. On `master` the old `readIntText`-based path read the leading `[` as zero digits and silently produced the epoch (`1970-01-01 00:00:00`). This PR's malformed-token rejection (`readDecimalText` now reports whether at least one digit was read, and the `DateTime`/`DateTime64` readers reject a token with none) correctly refuses the no-digit token, so the value falls back and is stored as `Float64` `0`. This is the intended, more-correct behavior (a token with no digits is not a valid number), and it is the sole difference in the output: the reference now drops the spurious epoch `DateTime` and gains a `0` in the `Float64` group, matching the exact diff produced by CI on the branch. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108091&sha=4102d1178e6f101e37d6df23d9a13853cb5b1644&name_0=PR&name_1=Fast%20test Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
@alexey-milovidov Thanks for the detailed triage. Findings on both: 1. Inconsistent KeyCondition behavior (Stress amd_debug/arm_debug). Not covered by #109023. #109023 only changes 2. Upgrade check (amd_release) part_loading_tree_rollback. Confirmed from the server log: Agreed that neither fix is on master yet, so re-merging master now would not clear these reds. |
|
Correction on failure 1 after full-log analysis: I am not opening a separate PR. This is not a reverse-key regression from #111059 - it is the pre-existing widening-CAST class that #109023 fixes, and the new Evidence from the full stress logs of this PR's two failures (the CIDB excerpt truncates before the decisive lines):
Coverage: #109023 demotes a leading-key atom with a non-empty cast chain from POINT to RANGE, so every observed shape (widened cast on the leading key with a point or range condition on the second column, ascending or DESC key - the classification is direction-independent) stops taking the binary-search exact-range path that aborts and uses generic exclusion search instead. I am verifying the reduced reverse-key variant empirically against the #109023 binary and will post the result on #111421. Ledger for failure 1: Stress test (amd_debug) / Stress test (arm_debug) -> fixing PR #109023 (ours, open). Failure 2 (04417 Upgrade check) is unchanged and still gets its own PR. |
|
Failure 2 (the
You were right that merging master would not clear this: master's 04417 already had |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 267/307 (86.97%) · Uncovered code |
|
Follow-up on #111528 (holder pinned to This is a different mode with a different trigger. #111230 removed the test from #112385 pins parallel replicas off for the test's client, so all three 202 assertions keep running on every lane. Measured on one server both ways: unpinned 0 of 30 runs match the reference, pinned 30 of 30; with randomization on, 50/50 pass on local disk and 50/50 on S3 with nothing skipped. One thing worth flagging separately: the blacklist mechanism rewrites a blacklisted FAIL to SKIPPED and only nags on a pass, so while the entry existed the lane showed no failures for this test at all. That is why the entry looked stale. I have that filed as its own item and it is not part of #112385. |
|
Hi @alexey-milovidov @Avogar — while reviewing this PR I found the following:
Could you review the test PR and add the |
A matched capture group is a complete field, and unlike the stream formats Regexp has no delimiter whose parsing would reject bytes the value did not consume. RegexpFieldExtractor::parseRow uses RE2::FullMatchN, so readField checks field_buf.eof() after the reader returns as the only possible detector of a partial parse. That check was conjoined with escaping_rule == Quoted, so for every other rule the bounded buffer was destroyed with bytes still in it: the unparsed tail was discarded and the partial parse reported as success. Under Escaped, CSV and JSON the readers stop at the first character that cannot belong to the value, so v=-1 into Nullable(UInt64) read 0, v=1abc read 1, v=[1,2]xyz read [1,2], and v=2020-01-01junk into Date under JSON read 1975-07-14, which is not even a prefix of the input. The guard now applies to every rule. The CSV and JSON rules first consume the trailing whitespace they legitimately permit, because their documented analogues CSV and JSONEachRow accept it: v=1 still reads 1 under those two rules, while v=1 abc is rejected. Escaped now rejects a trailing space, matching TSV. No wrong-results case had a whitespace-only tail, so the carve-out costs no coverage. Raw fails through a second mechanism and is the more reachable half, since it is the default rule and needs no setting at all. ISerialization:: deserializeTextRaw calls readString, documented as reading until \t or \n, which leaves the position at the tab and whole-texts only the prefix, so v=abc<TAB>junk into String read abc. A tab is legal inside a String, so rejecting such a capture would be a new bug: it is now read as a whole instead. A tab that cannot belong to the value, as in v=1<TAB>junk into Nullable(UInt64), is rejected. A capture equal to tsv.null_representation keeps the existing reader, so Raw's null tokens are unchanged by construction; that equality test also fixes v=\N<TAB>x, which previously read as NULL with <TAB>x silently discarded because null_representation matching accepts a tab as a terminator. The change is deliberately format-local. The other two callers of deserializeFieldByEscapingRule, CustomSeparatedRowInputFormat and TemplateRowInputFormat, operate on the whole input stream and have delimiters, so a leftover already fails their subsequent delimiter check and !buf.eof() is their normal case; pushing the check into the shared helper would fire on every well-formed row. TSV, TSKV, CSV, TabSeparatedRaw, JSONEachRow and CustomSeparated were all measured to reject these bytes already, so Regexp was the only format that accepted them. ErrorCodes::INCORRECT_DATA is kept rather than switched to UNEXPECTED_DATA_AFTER_PARSED_VALUE: the existing contract test from ClickHouse#108091 asserts INCORRECT_DATA on the Quoted path, and both codes are in isParseError so input_format_allow_errors_num/ratio behaves identically either way. This rejects input that was previously accepted, which is the point of the fix. No setting default changes and no setting is added, so SettingsChangesHistory.cpp needs no entry, matching how the Quoted half shipped in ClickHouse#108091. Both directions were measured across a 67-row matrix on two independently built binaries: 39 rows change, all in the intended direction, and the Raw null contract is byte-identical on 9 rows including LowCardinality(Nullable(String)). The new test fails on unpatched master with 25 of its 27 error assertions unmet and passes 50/50 under randomized settings. Array, Tuple and Map element interiors are deliberately out of scope: the guard is per top-level field, and a tail inside a nested element is owned by the element serializations. Related: ClickHouse#108091
Take the target versions of `Field.cpp` and `gtest_field.cpp` with the new `readQuoted` and tests from the cherry-picked change. The branch lacks the optional `has_digits` argument of `readDigits` (from #108091), so take the master version of `readDecimalText.h`, which adds it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A JSON number with a fractional part such as
1703363853.035was rejected when inserted into aDateTime64column viaJSONEachRow, raisingCANNOT_PARSE_INPUT_ASSERTION_FAILEDat the decimal point — even though the same number is accepted by theValuesformat, and the docs advertise that floating-point epochs cast toDateTime64.The unquoted-number branch of
SerializationDateTime64(andSerializationDateTime) usedreadIntText, which stops at the.and leaves the fractional part unparsed. ForDateTime64it also read a bare integer straight into the raw underlying (scaled) value, so1703363853was interpreted as ticks (1970-01-20 ...) instead of seconds — inconsistent withValues,CASTandtoDateTime64.Now an unquoted number is parsed as a decimal value at the column scale: a Unix timestamp (seconds since the epoch) with optional sub-second precision, matching
Values,CAST,toDateTime64and theDecimaltype (DateTime64is aDecimalunderneath). One more digit thanDecimal's precision is allowed so that a 10-digit second count is still valid at scale 9.DateTimetruncates the fractional part to whole seconds, also matchingCAST.Backward incompatible note: a bare unquoted integer fed to a
DateTime64column inJSONEachRow(and the other JSON/Quoted text paths) is now interpreted as seconds since the epoch instead of the raw scaled value. For example1703363853forDateTime64(3)now yields2023-12-23 20:37:33.000instead of1970-01-20 17:09:23.853. This only affects unquoted numbers; quoted strings and ClickHouse's own JSON output (which is always quoted) are unaffected.Closes: #59443
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
An unquoted JSON number for a
DateTime64/DateTimecolumn inJSONEachRowand similar formats is now interpreted as a Unix timestamp (seconds since the epoch) with optional sub-second precision, consistent with theValuesformat,CASTandtoDateTime64. Previously a number with a fractional part (e.g.1703363853.035) was rejected withCANNOT_PARSE_INPUT_ASSERTION_FAILED, and a bare integer (e.g.1703363853) was read into the raw scaled value of aDateTime64, producing a1970-...timestamp. This is a backward incompatible change for unquoted integers fed toDateTime64columns; quoted strings and ClickHouse's own (always quoted) JSON output are unaffected.Documentation entry for user-facing changes