Skip to content

Use the type default for values missing from JSON in the JSON type and JSONExtract - #131213

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:json-extract-tree-type-defaults
Nov 13, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:json-extract-tree-type-defaults

Conversation

@groeneai

@groeneai groeneai commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #130898

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

Fixed JSONExtract functions and the JSON data type filling a value missing from the input (an absent key, an invalid Array or Map element, a missing Tuple element) with 0 instead of the default of its type. An Enum without a 0 element no longer gets a value outside its elements, which made SELECT fail with UNKNOWN_ELEMENT_OF_ENUM.

Description

On 26.10.2.103 and 26.9.19.9, JSONExtract('{}', 'status', 'Enum8(''a'' = 1, ''b'' = 2)') returns 0, which is not an element of the Enum (Code: 691 UNKNOWN_ELEMENT_OF_ENUM when printed), and a JSON(t Tuple(n UInt8, status Enum8('a' = 1, 'b' = 2))) column stores 0 for {"t": {"n": 5}}, after which SELECT * fails while CHECK TABLE passes.

Root cause: the container nodes of JSONExtractTree (ArrayNode, TupleNode, MapNode) and the per-row fallback of the JSON functions insert IColumn::insertDefault, the column zero, for every value they do not take from the input.

Change: the builder passes the element types to those nodes, and they insert IDataType::insertDefaultInto when the type's default is not the column zero (isDefaultInsertTrivial, as ObjectJSONNode already does for typed paths); the String-input executor does the same with the result type. Accepted and rejected inputs are unchanged: Nullable(Tuple) from {} is still NULL, Variant still picks Map, and the JSON type still rejects {"t": {}} for a typed Tuple path. For an Enum where 0 is an element but not the smallest one, such as Enum8('n' = -1, 'z' = 0), the result changes from 'z' to 'n', the value an INSERT that omits the column stores.

JSONExtract on a native JSON argument has the same problem in a different code path that #102039 is restructuring; it is left for a separate fix. The same class on other surfaces is fixed in #131189 (input formats), #131186 (CAST to a named Tuple), #131190 (null_as_default), #131198 (VALUES (DEFAULT)) and #130975 (CSV/TSV).

Validation: the new test fails on master with Code: 691 and passes with the fix, 50/50 with randomized settings; 816 JSON-related stateless tests show no new failure; single-threaded parsing of 2M JSON rows and 5M JSONExtract rows is unchanged within noise.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.2242-master (included in 26.11 and later)

groeneai and others added 2 commits November 13, 2026 06:36
…JSONExtractTree and JSON functions

The container nodes of `JSONExtractTree` (used by the `JSON` data type for
typed paths and by `JSONExtract*`) and the per-row fallback of the JSON
functions inserted `IColumn::insertDefault` for every value they did not take
from the input: a missing `Tuple` element, a null `Tuple`, an invalid `Array`,
`Map` or `Tuple` element, and a failed `JSONExtract` row. That is the zero of
the column, which for an `Enum` without a 0 element is not a member, so a
`JSON` column with a typed `Tuple(..., Enum8(...))` path stored an
out-of-domain value (`SELECT` failed with `UNKNOWN_ELEMENT_OF_ENUM` while
`CHECK TABLE` passed) and `JSONExtract('{}', 'k', 'Enum8(...)')` returned 0.

`ArrayNode`, `TupleNode` and `MapNode` now get their element types from the
builder and insert `IDataType::insertDefaultInto` for a type whose default is
not the column zero, and the String-input executor does the same with the
result type. `isDefaultInsertTrivial` is evaluated once at construction, so
every other type keeps `IColumn::insertDefault` (the pattern `ObjectJSONNode`
already uses for typed paths). Which inputs a node accepts or rejects is
unchanged: `Nullable(Tuple)` from `{}` is still NULL, `Variant` still picks the
`Map` alternative, and the `JSON` type still rejects `{"t": {}}` for a typed
`Tuple` path.

`JSONExtract` on a native `JSON` argument (`runForObjectColumn`) is not
changed here.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Make the getTypeForDefault comment precise: an Enum default is its smallest value, so zero differs from it whenever that value is not 0.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings; 1 full pass), plus my own cold review of the same tree.

# Sev Finding Verdict Evidence / action
1 💡 The PR description did not state that an Enum whose 0 element is not the smallest value now gets the type default AGREE added one sentence to the description
2 💡 Same defect class on other surfaces (CAST, input formats, null_as_default, VALUES (DEFAULT)) AGREE listed by surface in the description; each is a different code path

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-self-slot-58:20261113-072500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05637_json_extract_tree_type_defaults fails on every run against the unfixed master binary, with or without randomized settings: Code: 691 UNKNOWN_ELEMENT_OF_ENUM at the first SELECT.
b Root cause explained? ArrayNode, TupleNode and MapNode in JSONExtractTree hold only an IColumn & and insert IColumn::insertDefault (the column zero) for a missing, null or invalid element, and the JSON functions do the same for a failed row. For an Enum without 0 that value is not a member, so a JSON typed Tuple path stores it and JSONExtract returns it.
c Fix matches root cause? Yes. The default is taken from the type (IDataType::insertDefaultInto) at the sites that insert it, gated by isDefaultInsertTrivial evaluated at construction. No guard, setting or tag.
d Test intent preserved / new tests added? New SQL test: the JSON type in a MergeTree table (object, null and positional input), Array/Map/nested Tuple typed paths, JSONExtract absent and invalid values in scalar, Tuple, Array, Map, JSON results, JSONExtractKeysAndValues, RapidJSON, plus controls for Nullable, Variant and the {"t": {}} rejection.
e Both directions demonstrated? Yes. Unfixed: FAIL, and run statement by statement every bug line fails (Code: 691, or 'z' instead of 'n') while the control lines match. Fixed: OK, and 50/50 with random settings and random MergeTree settings.
f Fix is general across code paths? Yes. Every insertDefault in JSONExtractTree.cpp and FunctionsJSON.cpp checked: scalar nodes have trivial types, Nullable/Variant/Dynamic insert NULL, ObjectJSONNode already uses the typed path types. NULL argument rows return NULL for Tuple and JSON results. JSONExtract on a native JSON argument is left to #102039.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Enum8, Enum16, an Enum whose 0 element is not the lowest, Nullable(Enum), Array/Map/Tuple nesting, named and unnamed Tuple, array and object input, constant and non-constant input, simdjson and RapidJSON, store plus merge in MergeTree.
h Backward compatible? (maintainer-approved exception only) Yes. Only the value of a default that was already inserted changes, and only where it was not a valid value (or, for an Enum whose 0 element is not the lowest, now matches what an INSERT omitting the column stores). Accepted and rejected inputs are unchanged, and stored rows are not rewritten.
i Invariants and contracts preserved? Yes. One value per padded element as before, so nested column sizes stay equal. The false return contract and every rollback path are untouched, and DataTypeTuple::insertDefaultInto uses addElementSafe. 816 JSON-related stateless tests show no new failure against the unfixed binary.

Session id: cron:clickhouse-impl-self-slot-57:20261113-062000

@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [84f0cdd]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
ThreadSanitizer: data race (STID: 4761-4859) FAIL cidb IGNORED

AI Review

Summary

Reviewed #131213 at 84f0cdd8256b3471d86053f28bac4788b2bbcfde. The change uses type defaults for missing or invalid values in JSONExtractTree and string-input JSON functions, preventing invalid Enum values in scalar and nested results. No actionable findings. The focused regression passed 50/50 targeted ASan/UBSan runs and bugfix validation before the final merge from master.

Final Verdict

✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). labels Nov 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 84f0cdd82 with master 06ad563d2 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.59, programs/clickhouse-keeper ×0.65 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.0 s 8.8 s +5.3 s (+150%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.5 s 7.1 s +5.0 s (+244%)
Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c51b3d4

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, s3 storage, DBReplicated, sequential) / 05339_filelog_shared_watch_thread flaky: threads grew by less than the number of tables printed 0 instead of 1, the runner's same-settings reruns passed, and the same diff failed in this check on 3 master runs and 11 other PRs since 2026-11-11; this PR does not touch FileLog #131241 (ours, open)
Mergeable Check, PR praktika rollups of the row above #131241 (ours, open)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261113-113012

@PedroTadim PedroTadim self-assigned this Nov 13, 2026
@PedroTadim
PedroTadim enabled auto-merge November 13, 2026 13:53
@PedroTadim

Copy link
Copy Markdown
Member

The CI failure is unrelated. @groeneai you should fix it in another PR

@PedroTadim
PedroTadim added this pull request to the merge queue Nov 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed, the Stress test (amd_tsan) data race (MultiplexedConnections::hasActiveConnections read vs invalidateReplica write in the distributed read path) is not touched by this diff. I'll fix it in a separate PR and post its link here.

Merged via the queue into ClickHouse:master with commit f50e945 Nov 13, 2026
202 of 204 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 Nov 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

The fix for the Stress test (amd_tsan) data race on active_connection_count is in #131436.

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 comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). 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.

3 participants