Skip to content

Make JSONExtract honour cast_string_to_date_time_mode when parsing DateTime values - #109252

Merged
alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
Utkal059:fix-jsonextract-cast-mode-109126
Aug 22, 2026
Merged

alexey-milovidov merged 9 commits into
ClickHouse:masterfrom
Utkal059:fix-jsonextract-cast-mode-109126

Conversation

@Utkal059

@Utkal059 Utkal059 commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

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 to CHANGELOG.md):

JSONExtract now honours cast_string_to_date_time_mode when converting string JSON values to DateTime/DateTime64, consistently with CAST. Closes #109126.


Extracting a string JSON value into DateTime/DateTime64 is a string-to-type cast, but JSONExtract keyed its parsing mode off date_time_input_format (an input-format parsing setting), while the equivalent CAST honours cast_string_to_date_time_mode. With date_time_input_format = 'basic' and cast_string_to_date_time_mode = 'best_effort' (reproduced on current master):

SELECT JSONExtract('{"date":"2020-01-01 00:00:00.123Z"}', 'date', 'DateTime64(3)');
-- 1970-01-01 00:00:00.000  (silently returns default)
SELECT toDateTime64('2020-01-01 00:00:00.123Z', 3);
-- 2020-01-01 00:00:00.123

<!-- CI automatic block start :ci_links: -->

---
Workflow [[PR](https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109252&sha=latest&name_0=PR)]
Sync PR [[sync-upstream/pr/109252](https://github.com/search?q=head%3Async-upstream%2Fpr%2F109252+org%3AClickHouse+type%3Apr&type=pullrequests)]
<!-- CI automatic block end :ci_links: -->


<!-- ch-version-info:start -->
### Version info
- Merged into: `26.8.1.1921` (included in `26.8` and later)
<!-- ch-version-info:end -->

Copilot AI review requested due to automatic review settings July 3, 2026 03:40
@CLAassistant

CLAassistant commented Jul 3, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Copilot AI left a comment

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.

Pull request overview

This pull request fixes JSONExtract parsing of DateTime/DateTime64 extracted from JSON string values so it follows cast_string_to_date_time_mode (consistent with CAST), rather than incorrectly keying off date_time_input_format.

Changes:

  • Update FunctionsJSON to override FormatSettings::date_time_input_format from cast_string_to_date_time_mode for JSON extraction.
  • Add a stateless query test covering best_effort, basic, and best_effort_us behavior for JSONExtract into DateTime/DateTime64.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
src/Functions/FunctionsJSON.cpp Switch JSONExtract DateTime parsing mode to honor cast_string_to_date_time_mode.
tests/queries/0_stateless/04498_json_extract_cast_string_to_date_time_mode.sql New stateless regression test for DateTime/DateTime64 extraction respecting cast mode.
tests/queries/0_stateless/04498_json_extract_cast_string_to_date_time_mode.reference Expected outputs for the new stateless regression test.

@Utkal059

Utkal059 commented Jul 3, 2026

Copy link
Copy Markdown
Contributor Author

Friendly ping for review — this is a small, self-contained fix for #109126 with a stateless test. Happy to adjust the approach if maintainers prefer keying off date_time_input_format instead.

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6276cab]

Summary: ✅


AI Review

Summary

This PR makes the string-JSON parser path for JSONExtract use cast_string_to_date_time_mode and adds a regression test for that path. The remaining native JSON fast path still performs string-to-DateTime casts without a Context, so the implementation does not fully satisfy the stated contract that JSONExtract now honors the setting.

Findings

❌ Blockers

  • [src/Functions/FunctionsJSON.cpp:321, src/Interpreters/castColumn.cpp:33, src/Functions/FunctionsConversion.h:151] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/109252#discussion_r3518190027] Native JSON input still bypasses the new setting. runForObjectColumn converts the extracted subcolumn with castColumnAccurateOrNull, and that helper builds the internal cast with a nullptr Context, so FunctionConvertSettings falls back to Basic. As a result, JSONExtract(json_col, 'date', 'DateTime64(...)') still ignores the session's cast_string_to_date_time_mode whenever the extracted value needs a string-to-date/time cast. The author marked this out of scope, but the current code at these lines is unchanged, so the user-visible divergence remains.
    Suggested fix: thread the current Context or equivalent cast settings through the object-column fast path, or avoid castColumn there so the cast uses the same settings as the string parser path.
Tests
  • ⚠️ Add a focused stateless test that casts a native JSON value, for example CAST('{"date":"2020-01-01 00:00:00.123Z"}' AS JSON), through JSONExtract(..., 'DateTime64(3, ''UTC'')') under both best_effort and basic. The current test only exercises the string-input parser path, so it cannot prove the fixed contract for the object-column fast path.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 3/5 (60.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 3, 2026
/// Extracting a string JSON value into a DateTime/DateTime64 column is a string-to-type
/// cast, so we honour `cast_string_to_date_time_mode` (rather than `date_time_input_format`),
/// same as HivePartitioningUtils::buildHiveFormatSettings.
format_settings.date_time_input_format = context->getSettingsRef()[Setting::cast_string_to_date_time_mode];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This only fixes the string-input parser path. When the first argument is native JSON, runForObjectColumn still converts the extracted subcolumn via castColumnAccurateOrNull ([src/Functions/FunctionsJSON.cpp:321]), and castColumn builds that internal cast with ContextPtr{} ([src/Interpreters/castColumn.cpp:33]). That falls back to cast_string_to_date_time_mode = Basic ([src/Functions/FunctionsConversion.h:151]), so JSONExtract(json_col, 'date', 'DateTime64(...)') still ignores the session setting whenever the JSON path is stored as String. The PR contract says JSONExtract now honours cast_string_to_date_time_mode, but native JSON input remains divergent. Please thread the current Context/cast settings through the object-column fast path and add a regression test for JSON-typed input.

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.

This sent me down a bit of a rabbit hole, it seems that the castColumn function that eventually does the casting doesn't even accept a context object and so cannot honor any of these settings without some non-trivial changes. However, I think this is outside the scope of this PR. There is an issue already tracking it: #102079.

@george-larionov george-larionov self-assigned this Jul 16, 2026

@george-larionov george-larionov left a comment

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.

This change looks good to me, it's a bit hacky but I agree it's the best fix currently. Now we just need to deal with any failing tests (we have a new policy to not merge PRs without a green CI).

Comment thread src/Functions/FunctionsJSON.cpp Resolved
/// Extracting a string JSON value into a DateTime/DateTime64 column is a string-to-type
/// cast, so we honour `cast_string_to_date_time_mode` (rather than `date_time_input_format`),
/// same as HivePartitioningUtils::buildHiveFormatSettings.
format_settings.date_time_input_format = context->getSettingsRef()[Setting::cast_string_to_date_time_mode];

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.

This sent me down a bit of a rabbit hole, it seems that the castColumn function that eventually does the casting doesn't even accept a context object and so cannot honor any of these settings without some non-trivial changes. However, I think this is outside the scope of this PR. There is an issue already tracking it: #102079.

@clickhouse-gh

clickhouse-gh Bot commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 3/5 (60.00%) · Uncovered code

Full report · Diff report

@george-larionov

Copy link
Copy Markdown
Member

The failing test is a flaky test with an issue that is assigned and is actively being discussed. Merging master and rerunning tests.

@Utkal059

Utkal059 commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Merged current master (the base was 303 commits behind) to get a clean CI run.

For the record, both red checks on 5cacdae are pre-existing CI problems and neither is reachable from this diff, which only changes JSONOverloadResolver's format_settings. Numbers are from the checks table on play.clickhouse.com.

Integration tests (amd_msan, 4/8) — the only check that gates Mergeable Check

test_rename_column/test.py::test_rename_distributed_parallel_insert_and_select: 20 failures in 80,936 runs (0.025%) over the last 60 days, spread over 19 different PRs, 2 of them on master (2026-07-18, 2026-07-25). It fails at the same place every time — select(nodeN, table_name, "num2") at test.py:846/847. There is no open issue for this test, which is why CI does not auto-match it as a known flaky failure.

AST fuzzer (amd_debug, targeted) — allow_failure=True (ci/workflows/pull_request.py:86), so it does not gate Mergeable Check; noting it only for completeness.

The failing query was:

SELECT __table1.x AS x FROM merge('.*[0-9].*')

which is #111945 — a ColumnBLOB reaching ConvertImplGenericFromString through merge() over marshalled blocks — with a fix already proposed in #111997. Over the last 45 days that logical error accounts for 201 failures across 126 PRs and 15 master runs, in 16 different jobs, under 17 distinct STIDs. It surfaced here as an unknown failure only because the STID is new: the existing auto-issue #113165 is 3059-3663, this run produced 3059-5345, and matching is an exact suffix compare (ci/praktika/issue.py:268).

Why a JSONExtract PR fuzzed a parallel-replicas query at all — the targeted corpus for this run was two files:

[targeted-fuzzer] Step 1 — changed/new tests (1): 04498_json_extract_cast_string_to_date_time_mode
[targeted-fuzzer] Step 2 — previously failed tests (1): 02764_parallel_replicas_plain_merge_tree

02764 flaked once on this PR back on 2026-07-26 (the 300 s parallel-replicas teardown tracked in #109265), so step 2 pulled it into this PR's fuzz corpus; fuzzing its SELECT x FROM parallel_replicas_plain into merge('.*[0-9].*') then hit the open ColumnBLOB bug. Nothing in the JSONExtract test can produce a marshalled block.

If the rename flake reappears on this run, the data above should be enough to treat it as known rather than as a regression from this PR.

@george-larionov

Copy link
Copy Markdown
Member

CI on 98b17f68 has two failures, neither related to this PR:

  • AST fuzzer (amd_debug, targeted) — Logical error: ColumnBLOB should be converted to a regular column before usage (STID: 3059-5345): pre-existing bug where a nested in-process plan keeps its BlocksMarshallingStep, so a ColumnBLOB reaches columnMatchesType. Fixed on master by Do not marshal blocks of a local shard plan in a distributed query #111997, merged 2026-08-04 21:56 — three hours after this
    branch's head commit, so it is not in this run. Zero occurrences fleet-wide since 2026-08-05.
  • Stress test (arm_debug) — Hung check failed, possible deadlock found: generic stress-test bucket; an AST-fuzzer query runs uninterruptibly inside analyzer constant folding (QueryAnalyzer → resolveFunction → IFunction), so it outlives the run and trips the hung check. Not fixed — root cause Uninterruptible CPU-bound function evaluation over a large value #112203 is still open. 89 failures on master in
    the last 7 days.

I will take a look at failure 2, in the meantime merging master.

@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6276cab38 with master 58cb242a3 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 704.45 MiB 701.40 MiB -3.05 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@george-larionov

Copy link
Copy Markdown
Member

CI is green apart from Stress test (arm_debug), which is unrelated to this pull request.

The failure is Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization in SerializationNullable::deserializeBinaryBulkWithMultipleStreams (src/DataTypes/Serializations/SerializationNullable.cpp:178), reached from MergeTreeIndexGranuleSet::deserializeBinary - a stale set skip index read. This pull request only changes src/Functions/FunctionsJSON.cpp and adds one stateless test, so it cannot reach that code path.

It is pre-existing and fleet-wide: 3 failures on master itself in the last 7 days, and ~25 across unrelated pull requests in the last 3 days.

Tracked by #112213 (root cause) and #114368 (CI matcher). Fix in progress: #112484

Merging master to re-run CI.

@Utkal059

Copy link
Copy Markdown
Contributor Author

@george-larionov @alexey-milovidov The CI checks are fully green and the PR is approved. Could we go ahead and get this merged? Thanks for the help getting it across the line.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 22, 2026
Merged via the queue into ClickHouse:master with commit 1562fec Aug 22, 2026
176 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 22, 2026
@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
SET cast_string_to_date_time_mode = 'best_effort', date_time_input_format = 'basic';
SELECT JSONExtract('{"date":"2020-01-01 00:00:00.123Z"}', 'date', 'DateTime64(3, ''UTC'')');
-- 26.7.5.10: 1970-01-01 00:00:00.000   (CAST of the same string: 2020-01-01 00:00:00.123)

SET cast_string_to_date_time_mode = 'basic', date_time_input_format = 'best_effort';
SELECT JSONExtract('{"date":"2020-01-01 00:00:00.123Z"}', 'date', 'DateTime64(3, ''UTC'')');
-- 26.7.5.10: 2020-01-01 00:00:00.123   (date_time_input_format must not apply here)

▶ Run on ClickHouse Fiddle

Results:

  • Reproduces on: 26.7, 26.6, 26.5, 26.3, 25.8
  • Does not reproduce on: master
  • Tested versions: master, 26.7, 26.6, 26.5, 26.3, 25.8
  • Also tested (unsupported, context only): 26.2 reproduces
  • ✓ Fix is on master — this PR's change fixes the bug on master. The releases listed above still have the bug and need the backport.

Backport the fix to 26.7, 26.6, 26.5, 26.3, 25.8.

CC component owner: @alexey-milovidov @bharatnc

Analysis metadata

comp-regular-function · Severity P2 · Finding phase_d_pr109252

  • Verified against master build 1562fec97aea (aarch64)
Introducing change: not searched

⚠ affects matrix shows regression boundary but bisect did not converge — introducing PR is unverified

  • No search for the introducing change was run — master is already clean (the fix landed there), so there is no regression boundary to search within the supported releases.
  • Walked 6 release(s) below the supported window: still reproduces down to 25.6.

@clickgapai

Copy link
Copy Markdown
Contributor

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

@clickgapai

Copy link
Copy Markdown
Contributor

@Utkal059 @george-larionov @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@Utkal059

Copy link
Copy Markdown
Contributor Author

@george-larionov Thanks again for reviewing this — following up to ask if there's a path for a Jan 2027 internship or junior role on Core given current openings are senior-level.

@george-larionov

Copy link
Copy Markdown
Member

@Utkal059 thanks for contributing! Unfortunately we currently don't have an intern program, however there are currently a few Core Software Engineer (non senior) jobs open on clickhouse.com/careers, your best bet is to apply there. Best of luck!

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 pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

JSONExtract(DateTime64) returns wrong value with best_effort setting

8 participants