Skip to content

Fix JSONExtract into Variant silently truncating fractional JSON numbers - #103620

Merged
Avogar merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-103617-json-extract-variant-truncation
May 12, 2026
Merged

Avogar merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-103617-json-extract-variant-truncation

Conversation

@groeneai

@groeneai groeneai commented Apr 27, 2026 •

Copy link
Copy Markdown
Collaborator

JSONExtract into a Variant that contained both an integer and a floating-point member silently truncated fractional JSON numbers: the integer member won and the fractional part was lost. Reported and root-caused by @fm4v in #103617.

SELECT
    JSONExtract('{"x": 3.14}', 'x', 'Variant(String, Int64, Float64)') AS v,
    variantType(v) AS active;
-- Before:  v=3,    active=Int64    (silent data loss)
-- After:   v=3.14, active=Float64

The same code path also applies to STRING JSON elements that parse as non-integral floats (e.g. "3.14"), which previously truncated to Int64=3 as well.

Root cause (lines from master 7df6513e4d29)

  1. SerializationVariant::getVariantsDeserializeTextOrder orders variants by priority — integers > big integers > decimals > floats > strings (SerializationVariant.cpp:899-958).
  2. VariantNode::insertResultToColumn iterates variants in that order and accepts the first member whose extractor returns true (JSONExtractTree.cpp:1514).
  3. For an integer target, the JSON DOUBLE branch in tryGetNumericValueFromJSONElement calls accurate::convertNumeric<Float64, NumberType, false> (JSONExtractTree.cpp:141). With strict=false, only the overflow check fires — 3.14 -> 3 returns true and the Int64 member wins.
  4. The STRING-as-fractional-float fallback inside the same function uses the same lossy convertNumeric call.

Fix

Add JSONExtractInsertSettings::no_int_truncation_from_double (default false, preserves legacy behavior). When set, tryGetNumericValueFromJSONElement rejects DOUBLE -> integer and STRING-as-fractional-float -> integer conversions whose round-trip is lossy.

VariantNode::insertResultToColumn now performs a strict first pass with this flag enabled so a Float/Decimal member can claim the value, and falls back to the legacy lenient pass only when the strict pass found no match (e.g. Variant(Int64, Int32) + 3.14 still returns 3 for backward compatibility). Direct integer extraction (JSONExtract(json, 'Int64'), JSONExtractInt, etc.) is unchanged — the fix is scoped to the Variant path.

This mirrors the established pattern used in DynamicNode::insertResultToColumn for try_existing_variants_in_dynamic_first — try strictly first, fall back to lenient.

Also fixes a pre-existing copy-paste error in the error message: "cannot read Map value" -> "cannot read Variant value".

Intentional broader scope (raised in review)

The strict first pass runs across all variant members, not only numeric ones. This means a Variant that contains both String and an integer member (without a Float/Decimal) also benefits from the fix: a fractional JSON DOUBLE now lands in String instead of being silently truncated into the integer member.

Query Before After
JSONExtract('{"x": 3.14}', 'x', 'Variant(String, Int64)') Int64=3 (silent data loss) String="3.14" (lossless)
JSONExtract('{"x": 3.14}', 'x', 'Variant(String, Int32)') Int32=3 String="3.14"
JSONExtract('{"x": 3.14}', 'x', 'Variant(String, Int32, Int64, Int128)') Int128=3 String="3.14"

This is intentional: the bug being fixed is silent data loss, and capturing the value as String is strictly better than dropping the fractional part. Users who explicitly want integer truncation must remove String from the variant — Variant(Int64, Int32) + 3.14 still returns 3 via the legacy lenient pass. Integer JSON literals (3) continue to pick the integer member even when String is present, because the strict pass accepts an exactly representable value before reaching String.

Tests 16-19 in the regression suite codify this behavior.

Behavior matrix

Query Before After
JSONExtract('{"x": 3.14}', 'x', 'Variant(Int64, Float64)') Int64=3 Float64=3.14
JSONExtract('{"x": 3.14}', 'x', 'Variant(Float64, Int64)') Int64=3 Float64=3.14
JSONExtract('{"x": "3.14"}', 'x', 'Variant(Int64, Float64)') Int64=3 Float64=3.14
JSONExtract('{"x": -2.5}', 'x', 'Variant(Int64, Float64)') Int64=-2 Float64=-2.5
JSONExtract('{"x": 1.5}', 'x', 'Variant(Int64, Decimal(10, 4))') Int64=1 Decimal=1.5
JSONExtract('{"x": 3.14}', 'x', 'Variant(String, Int64)') Int64=3 (silent data loss) String="3.14" (lossless)
JSONExtract('{"x": 3}', 'x', 'Variant(String, Int64)') Int64=3 Int64=3 (unchanged)
JSONExtract('{"x": 3}', 'x', 'Variant(Int64, Float64)') Int64=3 Int64=3 (unchanged)
JSONExtract('{"x": 3.14}', 'x', 'Variant(Int64, Int32)') Int32=3 Int32=3 (legacy fallback)
JSONExtract('{"x": 3.14}', 'x', 'Int64') 3 3 (unchanged)
JSONExtractInt('{"x": 3.14}', 'x') 3 3 (unchanged)

Tests

New regression test tests/queries/0_stateless/04141_json_extract_variant_no_int_truncation.sql covering 19 cases: declaration order independence, negative fractional, small fractional, integer literals, overflow, string-as-fractional, decimal members, fall-through to truncation when only integer variants exist, direct extraction backward compat, big int variants, bool, the original reproducer, and the four Variant(String, IntT) cases that codify the broader-scope behavior described above.

Existing test 04121_json_extract_types_edges had its .reference updated for the Variant(String, Int64, Float64) + 3.14 case (3 -> 3.14). The issue explicitly called out this test as codifying the bug; @fm4v's PR #103618 also rewrites that case (using Variant(String, Float64) to sidestep the bug). Both approaches converge on 3.14 as the correct output, so this update is forward-compatible with #103618.

Closes #103617

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

Fix JSONExtract into a Variant type silently truncating fractional JSON numbers. Previously, JSONExtract('{"x": 3.14}', 'x', 'Variant(Int64, Float64)') returned Int64=3 and JSONExtract('{"x": 3.14}', 'x', 'Variant(String, Int64)') returned Int64=3, dropping the fractional part. The fractional value is now preserved losslessly: a Float64/Decimal member claims it when present, otherwise a String member captures the original JSON. Variant types containing only integer members (e.g. Variant(Int64, Int32)) and direct integer extraction (JSONExtract(json, 'Int64'), JSONExtractInt, etc.) are unchanged.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.572
  • Backported to: 26.4.3.14

`JSONExtract` into a `Variant` that contained both an integer and a floating-point
member silently truncated fractional JSON numbers: the integer member won and the
fractional part was lost. For example,

  JSONExtract('{"x": 3.14}', 'x', 'Variant(String, Int64, Float64)')

returned `Int64=3` instead of `Float64=3.14`.

Root cause: the JSON DOUBLE -> integer branch in `tryGetNumericValueFromJSONElement`
called `accurate::convertNumeric<Float64, NumberType, false>` with `strict=false`,
which only checks overflow rather than equality. `VariantNode::insertResultToColumn`
iterates variants in priority order and accepts the first member whose extractor
returns true, so the integer member always claimed the value. The same path
truncated `STRING` JSON values whose contents parse as a non-integral float
(e.g. `"3.14"`).

Fix: add `JSONExtractInsertSettings::no_int_truncation_from_double` (default false,
preserves legacy behavior). When set, `tryGetNumericValueFromJSONElement` rejects
DOUBLE -> integer and STRING-as-fractional-float -> integer conversions whose
round-trip is lossy. `VariantNode::insertResultToColumn` now performs a strict
first pass with this flag enabled so a Float/Decimal member can claim the value,
and falls back to the legacy lenient pass only when the strict pass found no
match (e.g. `Variant(Int64, Int32)` + `3.14`). Direct integer extraction
(`JSONExtract(json, 'Int64')`, `JSONExtractInt`) is unchanged.

Also fixes a pre-existing copy-paste error in the Variant error message
("cannot read Map value" -> "cannot read Variant value").

Closes ClickHouse#103617
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (per task workflow):

a) Deterministic repro? Yes. Single SQL JSONExtract('{"x": 3.14}', 'x', 'Variant(String, Int64, Float64)') deterministically returns Int64=3 without the fix and Float64=3.14 with it. No randomization required.

b) Root cause explained? Yes.

  1. SerializationVariant::getVariantsDeserializeTextOrder ranks variants by priority: integers > floats > strings.
  2. VariantNode::insertResultToColumn iterates in that order, accepts the first member whose extractor returns true.
  3. The JSON DOUBLE -> integer branch in tryGetNumericValueFromJSONElement calls accurate::convertNumeric<Float64, NumberType, false> with strict=false, which only checks overflow (not equality), so 3.14 -> 3 succeeds and the integer member always wins.
  4. The STRING-as-fractional-float fallback inside the same function uses the same lossy call.

c) Fix matches root cause? Yes. The fix adds no_int_truncation_from_double to JSONExtractInsertSettings, which when set causes tryGetNumericValueFromJSONElement to reject lossy DOUBLE/STRING -> integer conversions. VariantNode enables this in a strict first pass and falls back to the legacy lenient pass only when the strict pass found no match. This directly addresses the mechanism in (b) at the conversion site, not as a downstream guard.

d) Test intent preserved? / New tests added? Yes. New 04141_json_extract_variant_no_int_truncation.sql (15 cases: declaration order, negative fractional, small fractional, integer literals, overflow, string-as-fractional, decimal members, fall-through to truncation when only integer variants exist, direct extraction backward compat, big int variants, bool, and the original reproducer). Existing 04121_json_extract_types_edges.reference updated for the buggy case (3 -> 3.14).

e) Demonstrated in both directions? Yes.

  • Without fix (master binary at session start): JSONExtract('{"x": 3.14}', 'x', 'Variant(String, Int64, Float64)') -> Int64=3 (silent data loss).
  • With fix (rebuilt binary): -> Float64=3.14.
  • 04141 passes 20/20 with --test-runs 20 randomization. 26 unrelated JSON+Variant/Dynamic tests all pass.

f) Fix is general, not a narrow patch? Yes.

  • Both code paths covered: JSON DOUBLE branch AND JSON STRING-as-fractional-float fallback inside tryGetNumericValueFromJSONElement.
  • All 4 callers of the function audited: 2 in VariantNode-path get the new flag from insert_settings; 2 for direct extraction explicitly pass false to preserve legacy behavior.
  • Fix is at the conversion source, not a defensive check downstream. The Variant-level pass enables stricter semantics only when alternatives exist; falls back to the legacy lenient pass when they don't, preserving backward compat for Variant(Int64, Int32) + 3.14.

Session id: cron:clickhouse-ci-task-worker:20260427-214500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @CurtizJ — could you review? This fixes silent data loss when JSONExtract extracts a fractional JSON number into a Variant(IntT, FloatT): the integer member used to win and truncate to e.g. Int64=3 for input 3.14. The fix adds an internal no_int_truncation_from_double flag on JSONExtractInsertSettings and uses a strict-then-lenient two-pass loop in VariantNode::insertResultToColumn (mirroring the existing pattern in DynamicNode for try_existing_variants_in_dynamic_first). Direct integer extraction (JSONExtract(json, 'Int64'), JSONExtractInt) is unchanged. Closes #103617.

@clickhouse-gh

clickhouse-gh Bot commented Apr 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c474a1f]

Summary: ❌

job_name test_name status info comment
Unit tests (tsan, function_prop_fuzzer) FAIL IGNORED
AST fuzzer (amd_debug) FAIL
Logical error: Invalid binary search result in MergeTreeSetIndex (STID: 3252-3a4a) FAIL cidb IGNORED
AST fuzzer (amd_tsan) FAIL
Logical error: AggregateFunctionArray: parameters mismatch between Array wrapper 'A' and nested function 'B'. Wrapper has C parameter(s): [D], nested function has E parameter(s): [F] (STID: 4870-4f07) FAIL cidb, issue ISSUE EXISTS

AI Review

Summary

This PR fixes real silent data loss in JSONExtract with Variant targets by preventing lossy fractional-to-integer coercion during variant selection, and the implementation/tests are consistent with the stated intent (including the intentional Variant(String, IntT) behavior). I did not find additional correctness, safety, performance, or compatibility issues beyond what was already discussed in-thread.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 27, 2026
@fm4v fm4v added the can be tested Allows running workflows for external contributors label Apr 27, 2026
{
auto strict_settings = insert_settings;
strict_settings.no_int_truncation_from_double = true;
for (size_t i : order)

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.

VariantNode now runs the strict first pass across all variants, including String. That changes behavior beyond the stated int-vs-float fix: for example, JSONExtract('{"x": 3.14}', 'x', 'Variant(String, Int64)') now picks String in the strict pass (Int64 rejects non-integral), while previously it picked Int64=3 in the single legacy pass.

Concrete trace on this path:

  1. strict pass sets no_int_truncation_from_double=true;
  2. Int64 branch fails at the new non-integral check;
  3. String branch succeeds via jsonElementToString;
  4. function returns before the legacy pass.

If this broader behavior change is intentional, please add an explicit test and document it in PR/changelog. If not, the strict pass should avoid letting String/other non-numeric fallbacks preempt the legacy numeric behavior.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Thanks — that's a real behavior change beyond Variant(IntT, FloatT) and you're right that it deserves explicit coverage.

This is intentional. The bug being fixed is silent data loss, and for Variant(String, IntT) + a fractional JSON DOUBLE, capturing the value as String="3.14" is strictly better than the previous Int64=3 (which silently dropped the fractional part). Restricting the strict pass to numeric variants only would preserve the truncation for Variant(String, IntT) shapes — that's exactly the failure mode @fm4v reported in #103617.

Concrete reasoning:

Variant shape Behavior with strict-only-on-numeric Behavior with strict-on-all (current PR)
Variant(String, Int64, Float64) + 3.14 Float64=3.14 ✅ Float64=3.14 ✅
Variant(String, Int64) + 3.14 Int64=3 ❌ (still silent data loss) String="3.14" ✅
Variant(String, Int64) + 3 Int64=3 ✅ Int64=3 ✅ (integer literal still picks Int64)
Variant(Int64, Int32) + 3.14 Int64=3 (legacy fallback) Int64=3 (legacy fallback)

Users who explicitly want integer truncation must remove String from the variant — Variant(IntT, IntT) + 3.14 continues to truncate via the legacy lenient pass (test 10).

I added four explicit regression cases in commit c474a1f and updated the PR description with a new "Intentional broader scope" section + behavior-matrix entries:

  • Test 16: Variant(String, Int64) + 3.14 → String="3.14" (your exact case)
  • Test 17: Variant(String, Int32) + 3.14 → String="3.14" (narrower integer)
  • Test 18: Variant(String, Int64) + 3 → Int64=3 (integer literal unchanged)
  • Test 19: Variant(String, Int32, Int64, Int128) + 3.14 → String="3.14" (multiple integer widths still preempted by String)

50/50 passes locally with tests/clickhouse-test --test-runs 50 04141_json_extract_variant_no_int_truncation.

PR ClickHouse#103620 review by clickhouse-gh[bot] flagged that the strict first
pass in `VariantNode::insertResultToColumn` runs across all variants,
not only numeric ones, so `Variant(String, IntT)` + a fractional JSON
DOUBLE now picks `String` instead of silently truncating to `IntT`.

This is intentional: the bug being fixed is *silent data loss*, and
capturing the value as `String` is strictly better than dropping the
fractional part. Restricting the strict pass to numeric variants would
preserve the bug for `Variant(String, IntT)` shapes, which is exactly
the failure mode the issue reporter (@fm4v) described.

Add four explicit cases (16-19) to the regression test:

  16. Variant(String, Int64)  + 3.14 -> String="3.14" (bot's exact case)
  17. Variant(String, Int32)  + 3.14 -> String="3.14"
  18. Variant(String, Int64)  + 3    -> Int64=3      (integer literal unchanged)
  19. Variant(String, Int32, Int64, Int128) + 3.14 -> String="3.14"

50/50 passes locally with `--test-runs 50` randomization.

PR description updated with a new "Intentional broader scope" section
and behavior-matrix entries documenting the change.
@clickhouse-gh

clickhouse-gh Bot commented Apr 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.00% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 90.48% (38/42) · Uncovered code

Full report · Diff report

@Avogar Avogar self-assigned this Apr 28, 2026
@Avogar
Avogar added this pull request to the merge queue May 12, 2026
Merged via the queue into ClickHouse:master with commit 95b90bb May 12, 2026
161 of 165 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label May 12, 2026
robot-ch-test-poll3 added a commit that referenced this pull request May 12, 2026
Cherry pick #103620 to 26.4: Fix JSONExtract into Variant silently truncating fractional JSON numbers
robot-clickhouse added a commit that referenced this pull request May 12, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore labels May 12, 2026
fm4v added a commit that referenced this pull request May 12, 2026
Backport #103620 to 26.4: Fix JSONExtract into Variant silently truncating fractional JSON numbers
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…3620

Backport ClickHouse#103620 to 26.4: Fix JSONExtract into Variant silently truncating fractional JSON numbers
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

JSONExtract into Variant silently truncates fractional JSON numbers when an integer member exists

5 participants