Skip to content

Fix case-insensitive JSONExtract functions on JSON Object type columns - #102039

Draft
antaljanosbenjamin wants to merge 63 commits into
masterfrom
fix-case-insensitive-json-extract-functions-with-json-type
Draft

antaljanosbenjamin wants to merge 63 commits into
masterfrom
fix-case-insensitive-json-extract-functions-with-json-type

Conversation

@antaljanosbenjamin

@antaljanosbenjamin antaljanosbenjamin commented Apr 8, 2026 •

Copy link
Copy Markdown
Member

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

The JSONExtract* functions now handle several previously broken call shapes on columns of the JSON data type: case-insensitive functions such as JSONExtractStringCaseInsensitive match keys case-insensitively instead of silently returning a default value; JSONLength, JSONType and the structural extractors (JSONExtractKeys, JSONExtractKeysAndValues, JSONExtractKeysAndValuesRaw, JSONExtractArrayRaw) no longer return a default value or fail with ILLEGAL_TYPE_OF_ARGUMENT; and the root form without a path, an integer index, and a non-constant key work as well. Other documented differences between JSON columns and JSON strings remain.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

The JSONExtract* functions accept a value of the JSON data type as their first argument, and they take a fast path for it: instead of parsing a JSON document, the value stored at the requested path is read as a subcolumn and cast to the function's result type. That fast path is what the value-extracting functions need, and only they, which is where the reported misbehavior came from.

  • Case-insensitive value extraction (the linked issue). runForObjectColumn was called without propagating the case_insensitive template parameter of the Executor, so the subcolumn lookup was case-sensitive and the function silently returned a default value. The requested path is now matched against typed paths, dynamic paths and shared-data paths without regard to case. Because two keys that differ only in case can both be present, and each row may carry either of them, the path is resolved per row, preferring a candidate that carries a real value over a typed path that only holds its default (which is indistinguishable from an absent key, see JSONExtractRaw returns empty string for typed JSON paths when value equals type default (0 for UInt32, '' for String) #101721).
  • The root form with no path at all (JSONExtractRaw(json_column)) has no subcolumn to read and used to fall into an empty-path branch that returned the default value. Each row is now serialized back to JSON text — with the caller's FormatSettings, so that a setting such as json_type_escape_dots_in_keys round-trips — and handled by the ordinary string implementation.
  • The functions that navigate the document rather than read one value out of it cannot use the fast path either, and used to be silently wrong or to fail outright on a JSON column: JSONLength(j, 'a') returned 0 and JSONType(j, 'a') returned Null for a value that is a real object or array, and the structural extractors failed with Type Array(...) is not supported for accurateCastOrNull because it cannot be inside Nullable. They now go through the JSON text of the row as well.
  • Paths a subcolumn name cannot express — an integer index such as JSONExtractRaw(j, 'a', 1) or JSONKey(j, 1), and a non-constant key — used to throw supports only constant string path arguments. They take the same route, so the restriction is gone.
  • Result types the stored value cannot be cast to — Array, Map and Tuple, as in JSONExtract(j, 't', 'Tuple(n UInt8, m UInt8)') — used to throw ILLEGAL_TYPE_OF_ARGUMENT or to silently return the default tuple. They are produced from the JSON text as well, so json_extract_named_tuples_as_objects applies to them as it does to a JSON string. The same holds for a path that descends into a typed path (JSON(Obj Map(String, Int64)), JSON(Obj Dynamic), ...), whose inner keys are not stored paths of the column.
  • An empty string is a legal JSON key, and is now looked up as one instead of being mistaken for the root form.

These changes make the repaired call shapes behave consistently with JSON strings where the JSON data type retains the necessary information. Other documented differences remain, including dropped null keys, the type storage order of object keys, and native JSON conversion semantics.

Every case is covered in 04092_json_extract_case_insensitive_object_column by asserting the JSON-column result against the same call on the equivalent JSON string.

Closes #102018
Related: #102079


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

JSONExtractStringCaseInsensitive and all other CaseInsensitive variants silently returned empty/default values when used with JSON Object type columns, because runForObjectColumn was called without propagating the case_insensitive template parameter from the Executor class.

The fix adds case-insensitive path resolution inside runForObjectColumn: when the function is case-insensitive, the user-provided path is matched against typed paths, dynamic paths, and shared data paths using character-by-character comparison before the subcolumn lookup.

Closes #102018
@clickhouse-gh

clickhouse-gh Bot commented Apr 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [50d3eaa]

Summary: ❌

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

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 8, 2026
Comment thread src/Functions/FunctionsJSON.cpp Resolved
@antaljanosbenjamin

Copy link
Copy Markdown
Member Author

I found some bigger issues with JSONExtract* functions, I created an issue for that #102079

@Avogar Avogar self-assigned this Apr 8, 2026
Comment thread src/Functions/FunctionsJSON.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

The 02346_text_index_bug101913 test failure is fixed by #102108 (already merged). Please rebase or merge master to pick up the fix.

@antaljanosbenjamin
antaljanosbenjamin marked this pull request as draft April 9, 2026 13:36
@alexey-milovidov

Copy link
Copy Markdown
Member

The Fast test (arm_darwin) failure is unrelated to this PR — the fix is in #102184.

@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

@alexey-milovidov

Copy link
Copy Markdown
Member

The remaining CI failure on Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) is the unrelated flaky test 02180_group_by_lowcardinality. The test uses LIMIT 10 without an ORDER BY together with group_by_overflow_mode='any', which produces non-deterministic output ordering, and it has been failing on dozens of unrelated PRs and on master itself over the last two days (41 failures on 2026-05-18, 74 failures on 2026-05-17 across many PRs, including PR=0 i.e. master).

@groeneai, please investigate the flaky 02180_group_by_lowcardinality failure and provide a fix in a separate PR — the failure on this PR is not caused by these JSON-extract changes.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=102039&sha=eb773718e41db7bafe973e9a67a6a3a195b48fe9&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov — fix PR opened at #105194.

Confirmed the diagnosis exactly: locally, running the inner SELECT with max_threads = 4 produces the same diff seen on this PR's Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) run (extra {"val":null,...} at the top, missing {"val":"232.4",...} at the bottom). The max_threads = 1 in the test's SETTINGS clause does not constrain ParallelReplicas.

The fix wraps the inner query in SELECT count() FROM (...), which is always 10 — the underlying crash-regression intent (LowCardinality(Nullable(String)) + group_by_overflow_mode='any' must not crash) is preserved verbatim. CIDB: 112 distinct PRs and 20 master hits over the last 30 days. Closes #36069 (the original 2022 flaky issue for this test).

@antaljanosbenjamin

Copy link
Copy Markdown
Member Author

Please do not merge this PR as is. It fixes some things, but not properly. See this comment.

pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request May 18, 2026
The test asserted a deterministic row-by-row output from:

  SELECT val, avg(toUInt32(val))
  FROM t_group_by_lowcardinality
  GROUP BY val
  LIMIT 10
  SETTINGS max_threads = 1, max_rows_to_group_by = 100, group_by_overflow_mode = 'any';

With `group_by_overflow_mode = 'any'`, only the first `max_rows_to_group_by` distinct
keys make it into the hash table — and which keys those are depends on the order in
which rows arrive at the aggregator. `LIMIT 10` without `ORDER BY` then selects ten of
those keys in hash-iteration order. The `max_threads = 1` clause does not help under
`ParallelReplicas` (where the table is sharded across replicas and partial aggregations
are merged) or under S3 storage (where reads can be split into independent ranges), so
the resulting row set varies between runs.

Originally tracked in ClickHouse#36069 (2022). The `-- Tags: no-random-settings` workaround masked
the issue for random-settings randomization but the underlying non-determinism returned
once `ParallelReplicas` was enabled by default in some CI configurations. Concretely the
test now fails ~10–20 times per day on master under
`Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel)` —
@alexey-milovidov flagged this on ClickHouse#102039.

The test is a crash-regression test for
"Avoid crash in case of GROUP BY LowCardinality(Nullable(String)) column and
group_by_overflow_mode='any'" (PR ClickHouse#29637 / ClickHouse#56057). The query is preserved verbatim,
including all the problematic settings; only the assertion is changed to
`SELECT count() FROM (...) `, which is always 10. If the underlying crash ever returns,
the test will detect it; the specific row values were never deterministic to begin with.

Verified locally that the old reference fails under `max_threads = 4` (extra null bucket
appears, last row drops — exact diff matches the CI report). The new assertion returns
`{"count()":10}` for all parallelism levels.

Closes ClickHouse#36069
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged the latest master (clean merge; FunctionsJSON.cpp and SerializationNumber.cpp build). The only red checks on the previous head were Build profile diff (an infrastructure error: LogClusterNotReady) and a merge_tree_small_blocks perf regression on ARM. This PR only touches the JSON functions and JSON float serialization, which that test does not use. @groeneai, please investigate the merge_tree_small_blocks regression: https://s3.amazonaws.com/clickhouse-test-reports/PRs/102039/8cc10885ff479cfcdbb7dbc78b3dc50b80c5fa62/pr/performance_comparison_arm_release_master_head_3_6/report.html and fix it in a separate PR. It may be related to #127836. If a fix is already in progress, link it here.

Comment thread src/Functions/FunctionsJSON.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

This one is not caused by this PR. The numbers come from CIDB (query_metrics_v2, arm, client_time):

  • The whole test moved, not just one query. All five merge_tree_small_blocks queries were 9% to 19% slower in this run, even though they read different columns (UInt64, sparse UInt8, String, Array). The confirmation restart reproduced it (+16.5%), so the slowdown belongs to the binary, not to the run.
  • Against the same reference 9a348d8c, 113 runs from 104 other PRs gave new/old between 0.88x and 1.17x on query Repair subtree2 #2.
  • In the last 20 days the same whole-test shift (all five queries at least 9% slower) showed up in 27 arm runs across 21 PRs. Five of those were master runs comparing a master commit with the previous one. The opposite shift (all five at least 8% faster) showed up in 73 runs.

The test measures the fixed cost per block at max_block_size = 16, so it reacts to small differences between binaries that have nothing to do with the code a PR changes. #127836 deletes tests/performance/merge_tree_small_blocks.xml as part of reverting #124816, so that is the in-progress change for this red. I don't have a separate fix to send. The new head is on a newer master, so its run is an independent sample.

alexey-milovidov and others added 2 commits November 5, 2026 04:49
# Conflicts:
#	src/Functions/FunctionsJSON.cpp
…itive `JSON` path matching

With `json_type_escape_dots_in_keys` the requested key `.` is stored as `%2E`, and the
case-insensitive matcher folded that escape sequence too, so it matched an unrelated
literal key `%2e`. Compare the escape sequence `%2E` as a unit: on either side it only
matches `%2E` on the other.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Functions/FunctionsJSON.cpp Resolved
Comment thread src/Functions/FunctionsJSON.cpp Resolved
# Conflicts:
#	src/Formats/FormatSettings.h
@groeneai

Copy link
Copy Markdown
Collaborator

@antaljanosbenjamin one call shape is still broken on this head (a93170bb4c6a, CI amd_release binary): JSONExtract with a key path and a Tuple, Array or Map result type.

CREATE TABLE t (id UInt32, j JSON) ENGINE = MergeTree ORDER BY id;
INSERT INTO t VALUES (1, '{"t": {"n": 5, "m": 6}, "a": [1, 2]}');
SELECT JSONExtract(j, 't', 'Tuple(n UInt8, m UInt8)') FROM t;           -- (0,0), toString(j) gives (5,6)
SELECT JSONExtract(j, 't', 'Nullable(Tuple(n UInt8, m UInt8))') FROM t; -- NULL
SELECT JSONExtract(j, 'a', 'Array(Int64)') FROM t;                      -- Code: 43 ... cannot be inside Nullable
SELECT JSONExtract(j, 't', 'Map(String, UInt8)') FROM t;                -- Code: 43

supportsObjectSubcolumnExtraction() keeps JSONExtract on runForObjectColumn. There the sub-object is a JSON value in the Dynamic subcolumn j.@t, CAST(JSON AS Tuple) is not supported, so castColumnAccurateOrNull returns NULL and removeNullable exposes the default; Array and Map cannot be inside Nullable, so the cast throws. Master gives the same four results, and released 26.10.2.103 and 26.3.33.24 also return (0,0) for the Tuple query. The root form, JSONExtract(j, 'Tuple(t Tuple(n UInt8, m UInt8))'), is fixed here.

Which do you prefer: (1) this PR also sends JSONExtract with such a result type to the serializeObjectColumnToJSONText fallback (the "fall back to cast to String" from #102079), or (2) I open a follow-up PR that reuses it once this one is merged?

…Extract*`

- Write a narrower floating-point value (`Float32`, `BFloat16`) promoted to `Float64`
  in the internal round-trip serialization, because the text is parsed back as `Float64`:
  the shortest representation of `Float32` `1234567808` is `1234567800`.
- Choose the subcolumn route only when the result type can be produced by
  `accurateCastOrNull`; `Array`, `Map`, and tuples containing them go through the parser.
- When the requested path descends into a typed path holding a whole object
  (`JSON(Obj JSON)`, `JSON(Obj Tuple(Key Int64))`), read it from the JSON text, both for
  the case-insensitive and the case-sensitive functions; `runForObjectColumn` returns
  `nullptr` for such paths.

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

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failures: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=102039&sha=a93170bb4c6a88471d2eddb19414a11a072800fc&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29 (Inconsistent AST formatting for a backquoted identifier containing remote(...) and .COLUMNS, STID 1941-1bfa) and https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=102039&sha=a93170bb4c6a88471d2eddb19414a11a072800fc&name_0=PR&name_1=La%20Casa%20Del%20Dolor%20%28amd_debug%29 (Server node0 did not shut down gracefully). Please provide a fix in a separate PR. If the fix is already in progress, link it here. The 05495_part_moves_between_shards_step_retry failure was fixed on master by #129409, and the branch now includes that fix.

Comment thread src/Functions/FunctionsJSON.cpp Resolved
Comment thread src/Functions/FunctionsJSON.cpp Resolved
Comment thread src/Functions/FunctionsJSON.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

Both failures are already fixed on master by merged PRs of mine. Neither fix was in the build tested at a93170bb, and both are in the current head f4dd8322.

  1. Inconsistent AST formatting (STID 1941-1bfa): fixed by Keep a compound function name parsable when one of its parts contains a dot #129405, merged 2026-11-05 16:09 UTC, after this run (build c192448a, 06:28 UTC). The fuzzer's function name ` remote('[::{1..2}]:9000', '', hostName()) FINAL`.COLUMNS has .. inside a quoted part. Since Resolve a database-qualified parameterized view call in INSERT SELECT and EXPLAIN SYNTAX the same way as in SELECT #128992 the name was split at every dot, so the empty part was written as ``, which does not parse. On current master (21809eaa, debug build) the same query formats as ` remote('[::{1`.`.2}]:9000', '', hostName()) FINAL`.`COLUMNS`, parses back, and fails with an ordinary UNKNOWN_SETTING instead of the abort. All 20 CIDB failures with this empty-part shape (2026-11-04 and 2026-11-05) come from builds without Keep a compound function name parsable when one of its parts contains a dot #129405; there are none since.

  2. La Casa Del Dolor Server shutdown: in gdb.log the main thread is in DDLWorker::shutdown, joining the DDL worker, whose executor runs the distributed DDL entry OPTIMIZE TABLE d17.t1000 PARTITION tuple() parked in StorageReplicatedMergeTree::waitForProcessingQueue. That wait ignored the killed query until receive_timeout. Make SYSTEM SYNC REPLICA and OPTIMIZE of ReplicatedMergeTree cancellable while they wait for the replication queue #129283 (merged 2026-11-05 15:07 UTC, after this 07:38 UTC run) makes it cancellable. None of the 17 La Casa Del Dolor (amd_debug) Server shutdown failures since that merge has this wait in its stacks; 3 earlier ones did, including this one.

alexey-milovidov and others added 3 commits November 20, 2026 23:13
…ts constant in `JSONExtract*`

- A `Tuple` result type is always produced by the parser: the stored value
  is an object, which cannot be cast to a `Tuple`, so
  `JSONExtract(j, 't', 'Tuple(n UInt8, m UInt8)')` silently returned `(0,0)`.
- Every path that descends into a typed path is read from the JSON text,
  whatever the type of the typed path is (`Map`, `Dynamic`, ... in addition
  to `JSON` and `Tuple`).
- With non-constant keys, a group of rows that cannot be read from
  subcolumns goes through the parser alone; the other groups keep the
  results of the subcolumn route, so the result of a row no longer depends
  on the keys of the other rows of the block.
- `runForObjectColumn` no longer expands a constant `JSON` object to one
  copy per row: the value is extracted once from its single row and the
  result is constant.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…lts from `JSON` columns

The test, added on master after this branch was created, pinned the
default `(0,0)` that `JSONExtract` returned for a `Tuple` result from an
untyped path of a `JSON` column. That default came from an unsupported
cast of the stored value, and this pull request intentionally replaces it:
a `Tuple` result is now produced from the JSON text of the stored value,
the same as for the equivalent JSON string. So
`json_extract_named_tuples_as_objects` applies to such values as well;
the description of the setting is updated accordingly.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, option (1) is done here: in 7e3ac49 JSONExtract with any Tuple result type goes through the JSON text of the value (the Array and Map results already did), so all four queries from your comment now give the same result as for toString(j). No follow-up is needed for that.

The same commit addresses the four review threads (constant object kept constant, parser fallback local to a key group, any typed parent). 50d3eaa updates 05045_jsonextract_named_tuples_from_objects, which was added on master meanwhile and pinned the old (0,0) for a Tuple result from an untyped path; json_extract_named_tuples_as_objects now applies to such values as it does to a JSON string, and the description of the setting says so.

The only test failure on the previous head, 03634_autopr_output_bytes_estimation, was fixed on master by #131358, and the branch now includes that fix through the merge of master.

@groeneai

Copy link
Copy Markdown
Collaborator

Verified on a debug build of 50d3eaa1: the four queries and the root form give the same result as for toString(j), and so do the other Tuple, Array and Map shapes I tried (unnamed and partial tuples, Array(Tuple), Map(String, Tuple), nested paths).

Two result types still differ from toString(j) at a key path, on this head and on master (e627fea5):

CREATE TABLE t (id UInt32, j JSON) ENGINE = MergeTree ORDER BY id;
INSERT INTO t VALUES (1, '{"s": "x"}');
SELECT JSONExtract(j, 's', 'LowCardinality(String)') FROM t;      -- Code: 43 ... not supported for accurateCastOrNull, toString(j) gives 'x'
SELECT JSONExtract(j, 'e', 'Enum8(''a'' = 1, ''b'' = 2)') FROM t; -- Code: 691 Unexpected value 0 in enum, toString(j) gives 'a'

canCastObjectSubcolumnTo checks the type after removeLowCardinality, but runForObjectColumnImpl then casts to the LowCardinality type itself (LowCardinality(Nullable(String)) fails the same way). For the absent key, removeNullable exposes the column zero, while the String path inserts the type default since #131213.

Should this PR also cover these two, or should I send a follow-up once it is merged?

This branch was successfully deployed

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

Labels

comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CaseInsensitive JSONExtract functions perform case-SENSITIVE matching on JSON Object type columns

5 participants