Skip to content

Parse unquoted JSON numbers for DateTime64 and DateTime as Unix timestamps - #108091

Merged
Avogar merged 53 commits into
masterfrom
fix-59443-json-datetime64-float
Jul 28, 2026
Merged

Avogar merged 53 commits into
masterfrom
fix-59443-json-datetime64-float

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 22, 2026 •

Copy link
Copy Markdown
Member

A JSON number with a fractional part such as 1703363853.035 was rejected when inserted into a DateTime64 column via JSONEachRow, raising CANNOT_PARSE_INPUT_ASSERTION_FAILED at the decimal point — even though the same number is accepted by the Values format, and the docs advertise that floating-point epochs cast to DateTime64.

The unquoted-number branch of SerializationDateTime64 (and SerializationDateTime) used readIntText, which stops at the . and leaves the fractional part unparsed. For DateTime64 it also read a bare integer straight into the raw underlying (scaled) value, so 1703363853 was interpreted as ticks (1970-01-20 ...) instead of seconds — inconsistent with Values, CAST and toDateTime64.

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, 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.

Backward incompatible note: a bare unquoted integer fed to a DateTime64 column in JSONEachRow (and the other JSON/Quoted text paths) is now interpreted as seconds since the epoch instead of the raw scaled value. For example 1703363853 for DateTime64(3) now yields 2023-12-23 20:37:33.000 instead of 1970-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):

  • Backward Incompatible Change

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

An unquoted JSON number for a DateTime64/DateTime column in JSONEachRow and similar formats is now interpreted as a Unix timestamp (seconds since the epoch) with optional sub-second precision, consistent with the Values format, CAST and toDateTime64. Previously a number with a fractional part (e.g. 1703363853.035) was rejected with CANNOT_PARSE_INPUT_ASSERTION_FAILED, and a bare integer (e.g. 1703363853) was read into the raw scaled value of a DateTime64, producing a 1970-... timestamp. This is a backward incompatible change for unquoted integers fed to DateTime64 columns; quoted strings and ClickHouse's own (always quoted) JSON output are unaffected.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

…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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [50f9d0c]

Summary: ✅


AI Review

Summary

This PR makes unquoted numeric DateTime/DateTime64 input in the JSON, Values/Quoted, and DOM JSONExtract/typed-JSON paths follow Unix-timestamp-seconds semantics, adds input_format_read_datetime_number_as_raw_value as the rollback knob, keeps YTsaurus on raw ticks, and adds focused regressions around overflow, DOM parity, quoted-format callers, and compatibility behavior. I did not find a surviving correctness, compatibility, or documentation issue on the current head.

Missing context / blind spots
  • ⚠️ There is no built ClickHouse binary in this workspace, so I could not execute targeted repro queries locally; the review relies on code tracing and the added regression coverage in 04492, 04508, 04522, 04622, and 04628.
Final Verdict

✅ Approve. No new inline findings to post.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 22, 2026
@clickhouse-gh clickhouse-gh Bot added pr-backward-incompatible Pull request with backwards incompatible changes and removed pr-bugfix Pull request with bugfix, not backported by default labels Jun 22, 2026
alexey-milovidov and others added 7 commits June 29, 2026 16:14
… 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed the work that addresses the AI Review ❌ Block (the commits were prepared but not yet on the branch): 109c5da1fa6..8e2c74edb06.

Minimum required actions from the verdict, all done:

  1. DateTime64 19-digit overflow (164348fad66): the unquoted number is now read into a Decimal128 temporary (readDecimalText with precision max_precision<Decimal128> = 38 digits), the remaining scale is applied in Int128 with common::mulOverflow, and the result is range-checked against the Int64 ticks of DateTime64 before storing. Out-of-range values raise DECIMAL_OVERFLOW instead of wrapping. A 128-bit accumulator covers the whole valid DateTime64 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 (matching the Values fallback), which fixes the 03797_convert_field_to_type_decimal_overflow regression.
  2. Boundary tests (04489_json_datetime64_number_input): Int64 max/min are stored exactly; 9223372036854775808 / -9223372036854775809 and the scale-multiplied DateTime64(3) case are rejected with DECIMAL_OVERFLOW. Also covers exponent notation, negative epochs, fractional truncation, multi-column delimiters, and the Nullable/Variant try-paths.
  3. Docs (6a3c426b376): docs/en/sql-reference/data-types/datetime64.md and the source doc in src/DataTypes/registerDataTypeDateTime.cpp now describe an inserted number as a Unix timestamp in seconds (fractional part = sub-second precision), with a Backward incompatible change note.

The existing tests broken by the behavior change were updated to keep their original intent: 00927_asof_join_other_types, 01516_date_time_output_format, 01732_more_consistent_datetime64_parsing, 02519_monotonicity_fuzz.

Also merged the latest master (clean, net diff unchanged) and resolved the two open review threads. The two changed serialization translation units pass -fsyntax-only.

alexey-milovidov and others added 3 commits June 30, 2026 16:45
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed 8e2c74edb06..d2145f5ce59 addressing the CI failures and the AI Review ⚠️ Request changes verdict.

1. Docs (the sole blocking action / unresolved thread, 1dab91a80a1). Reworded the stale sentence "Contrary to inserting, the toDateTime64 function will treat all values as the decimal variant" in both docs/en/sql-reference/data-types/datetime64.md and the mirrored source documentation in src/DataTypes/registerDataTypeDateTime.cpp. It now reads that toDateTime64 treats a numeric argument as a number of seconds, like inserting, so it no longer contradicts the new contract. Thread resolved.

2. YTsaurus DateTime64 regression (0ab5d2f4c3c) — fixes integration test test_ytsaurus/test_tables.py::test_ytsaurus_primitive_types[timestamp0]/[timestamp1]. The YTsaurus engine reads YT data via JSONEachRow and maps timestamp/timestamp64 (microseconds since the epoch) to DateTime64(6), relying on an unquoted JSON number being stored as the raw underlying value (ticks). With this PR an unquoted number means seconds, so a real YT timestamp such as 1703363853000000 would overflow with DECIMAL_OVERFLOW. Added an internal read_datetime64_number_as_raw_value JSON format setting (default off) that restores the raw-ticks reading, enabled only by YTsaurusSource; user-facing JSON/Quoted parsing is unchanged.

3. 01098_msgpack_format (d2145f5ce59) — its VALUES insert used raw millisecond ticks (1639872000000, 1639872891123, 42) which now shift/overflow. Replaced with the equivalent seconds form (1639872000, 1639872891.123, 0.042); readDecimalText parses these exactly, so the stored ticks, the MsgPack round-trip and the .reference are bit-identical.

Remaining red — Stress test (amd_tsan/arm_tsan)/Hung check failed, possible deadlock found is the known open flake #107941; this PR has no concurrency/threading changes.

Verification: the three changed translation units pass -fsyntax-only against the codebase. A full build/integration run was not possible in this environment (submodules are not initialized in the worktree), so the 01098/test_ytsaurus fixes rest on the exact-decimal arithmetic above and on CI re-running.

… `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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed d2145f5ce59..e2bc6a5e9c7 addressing the AI Review ⚠️ Request changes verdict (the single remaining DateTime finding).

1. DateTime exponent-form numbers (b30316944aa). 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 JSONEachRow rejected the row — even though the DateTime64 path already accepts it and the PR contract promises unquoted JSON numbers behave like Unix timestamps matching CAST. It now parses the number with the same decimal-aware readDecimalText logic as 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.

2. Test (e2bc6a5e9c7). Added the requested DateTime exponent cases (1.703363853e9, 1703363853.0e0) next to the existing DateTime64 exponent case, asserting they match CAST(1.703363853e9 AS DateTime). Also renumbered the test from 04489 to 04492: 04489_max_threads_auto_parsing_compat, 04490, and 04491 are now all taken on master, so 04492 is the next free prefix.

The unresolved review thread is resolved. The changed translation unit passes -fsyntax-only; the parsing reuses the exact readDecimalText machinery already exercised by the DateTime64 path. A full build was not possible in this worktree (submodules not initialized), so the behavior rests on that shared arithmetic and on CI re-running.

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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed e2bc6a5e9c7..4102d1178e6 addressing the AI Review ⚠️ Request changes verdict and the Build (arm_tidy) failure.

1. Malformed unquoted numeric tokens (the AI Major / unresolved thread). readDecimalText with digits_only = false stops at the first non-numeric character (so the ,/} after a JSON value is left for the format layer), but it also accepted a token with no digits at all — ., -, e9 were each consumed as the value zero, so a row such as {"t":.} was silently loaded as the Unix epoch. readDigits/readDecimalText now optionally report whether at least one digit character was read; the DateTime64/DateTime readers reject the value when none was (throwing path raises CANNOT_PARSE_DATETIME, try-path returns false). A bare 0 still parses (it has a digit even though the meaningful-digit count is 0), and the new out-parameter defaults to null so every other readDecimalText caller is unaffected.

2. Build (arm_tidy). Dropped the redundant static from datetime_number_precision in the anonymous namespace, which readability-static-definition-in-anonymous-namespace (warnings-as-errors) had failed on.

3. Tests. Added the requested malformed-token cases ({"t":.}, {"t":-}, {"t":e9}) for both DateTime64 and DateTime to 04492_json_datetime64_number_input, asserting CANNOT_PARSE_DATETIME.

The documentation checkbox is now checked (the DateTime64 docs were already updated in this PR). The unresolved review thread is resolved.

Verification: the two changed serialization translation units pass -fsyntax-only, and I confirmed that an exception thrown from deserializeTextJSON surfaces through format(JSONEachRow, …) with its original CANNOT_PARSE_DATETIME code (so the new test annotations are correct). A full build was not possible in this worktree (it is not configured), so the behavior rests on that shared decimal-parsing arithmetic and on CI re-running.

alexey-milovidov and others added 2 commits July 1, 2026 03:20
…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]>
@groeneai

Copy link
Copy Markdown
Collaborator

@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 matchesExactContinuousRange for the wider-typed-CAST-in-chain class (x = toUInt256(3)); that class has stayed at its steady 1-3/day background rate and did not spike. The 07-24 spike is a different path. CIDB shows this signature flat at 1-3 hits/day, 0 on master, for the preceding 10 days, then 45 hits / 37 PRs + 6 master hits on 07-24 (the day #111059 merged, 08:39 UTC) and 24 more on 07-25. #111059 rewrote the reverse-key branches of forAnyHyperrectangle / forAnySparseHyperrectangle (the key_order.isReversed(...) bound swaps) plus MergeTreeDataSelectExecutor, and the one spike failure whose query I could recover has a descending key (ORDER BY (a, b, c DESC, d)). So this points to a new reverse-sorting-key exact-range regression from #111059, not the #109023 class. No fix-forward PR exists yet. I will open a separate PR and link it here.

2. Upgrade check (amd_release) part_loading_tree_rollback. Confirmed from the server log: 04417_..._evict_reinsert_contains fabricates parts for test_3.t_plt_evict_reinsert with storing_version: 0, and on the upgrade restart the part loader cannot parse their txn_version.txt (Cannot parse input: expected '\n' before: 'version: 1\nstoring_version: 0...' -> Failed to read version metadata for part all_1_5_4_1 -> Part all_5_6_1_0 intersects previous part all_1_5_4_1 ... (CORRUPTED_DATA)). Same class as #111053. #111055 / #111661 / #111730 hardened the Stress-restart mode and 04624_..._startup_recovery, but 04417 in the Upgrade-check path is still unhardened (38 PRs on 07-24, 12 on 07-25). No open fix PR for it. I will open a separate PR mirroring that pattern and link it here.

Agreed that neither fix is on master yet, so re-merging master now would not clear these reds.

@groeneai

Copy link
Copy Markdown
Collaborator

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 04612_reverse_key_index_analysis.sql from #111059 merely gave the stress AST fuzzer material it mutates into that shape at scale. Same conclusion as #111421 (comment), which also verified the reduced variant aborts on a pre-#111059 debug build.

Evidence from the full stress logs of this PR's two failures (the CIDB excerpt truncates before the decisive lines):

  • amd_debug (qid 88d54987): the aborting query is the ASTFuzzer mutation SELECT count() FROM t_big WHERE (g = toNullable(toUInt256(5))) AND (r = 0); canary condition (_CAST(column 0) in ['5', '5']), (column 1 in [0, 0]).
  • arm_debug (qid f2d3fb14): mutation g = toUInt256(1) AND r = 5 on t_nan_asc, whose key is ascending ORDER BY (g, r) - no reverse key involved at all.
  • Three more sampled spike runs (one on master, two on other PRs) all carry the same _CAST(column 0) canary signature; I found none without it. The unfuzzed 04612 test passes everywhere.
  • Properly fix primary key index analysis for reverse sorting keys #111059 did not touch matchesExactContinuousRange(), whose POINT classification is what the debug canary cross-checks.

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.

@groeneai

Copy link
Copy Markdown
Collaborator

Failure 2 (the t_plt_evict_reinsert startup CORRUPTED_DATA on the Upgrade check) now has two PRs, as promised:

You were right that merging master would not clear this: master's 04417 already had DETACH TABLE ... PERMANENTLY from #111055, which fixed the stress-restart poisoning but not the object-storage mismatch. No file overlap and no ordering constraint between the two PRs.

@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 91.80% -0.20%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 267/307 (86.97%) · Uncovered code

Full report · Diff report

@Avogar
Avogar added this pull request to the merge queue Jul 28, 2026
Merged via the queue into master with commit 47baf01 Jul 28, 2026
179 checks passed
@Avogar
Avogar deleted the fix-59443-json-datetime64-float branch July 28, 2026 19:14
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

Follow-up on 01666_merge_tree_max_query_limit: #111528 was not the whole story, and a second fix is up as #112385.

#111528 (holder pinned to max_threads = 1) is merged and correct for the mode it addressed. But the test then started failing deterministically, 3 out of 3 reruns, on Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel), on master as well as on PRs. That pin is present on every one of those failing commits, so it is not the operative variable.

This is a different mode with a different trigger. #111230 removed the test from tests/parallel_replicas_blacklist.txt, where it had been since January 2025 under the reason !!!Reason: Timeout!, which put it back on the ParallelReplicas lane. The throttle the test asserts is a per-table counter keyed on query id (checkLimits -> getQueryIdHolder -> insertQueryIdOrThrowNoLock). ReadFromParallelRemoteReplicasStep::createPipeForSingeReplica builds each secondary RemoteQueryExecutor without calling setQueryId, so the id is sent empty and Context::setCurrentQueryId replaces an empty id with a random UUID. With max_concurrent_queries = 1 the holder therefore becomes several differently-keyed reads of the same table on the same server, competes against itself for the one slot, and is rejected instead of holding it, so the final assertion sees code 0. system.query_log shows two secondary reads of the holder's own statement rejected with 202 and then the holder itself, within 204 ms. When the rejection lands before read_rows becomes visible, wait_for_query_to_start spins on a sum over zero rows instead, which is the timeout form the 2025 blacklist entry recorded.

#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.

@clickgapai

Copy link
Copy Markdown
Contributor

Hi @alexey-milovidov @Avogar — while reviewing this PR I found the following:

Could you review the test PR and add the can be tested label if it looks good?
Happy to discuss — close anything that's wrong or already addressed.

pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Aug 2, 2026
pull Bot pushed a commit to sowelswl/ClickHouse that referenced this pull request Aug 17, 2026
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
Algunenano added a commit that referenced this pull request Nov 18, 2026
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]>

This branch was successfully deployed

1 active deployment
staging - docs — 50f9d0c0 Deployed Jul 28, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backward-incompatible Pull request with backwards incompatible changes 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.

JSONEachRow rejects float as DateTime64 (works in Values)

5 participants