Skip to content

Fix a logical error and an ILLEGAL_COLUMN on json['key'] over a LowCardinality path - #119892

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-arrayelement-json-nullable-key-lowcardinality
Sep 18, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-arrayelement-json-nullable-key-lowcardinality

Conversation

@groeneai

@groeneai groeneai commented Sep 14, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #107039

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Not required: the json['key'] overload this fixes is unreleased.

Description

json['key'] on a JSON column whose typed path is a non-nullable LowCardinality(T) fails two ways:

  • from a table with a constant Nullable(String) key: Logical error: 'Unexpected return type from arrayElement. Expected LowCardinality(Nullable(IPv6)). Got LowCardinality(IPv6)', at the planner's partial-result fold (master CI report, query_id a68771de-1b69-44d3-a831-199f0ee3ef52);
  • from a constant JSON source: ILLEGAL_COLUMN (Invalid column type for ColumnUnique::insertRangeFrom, or cannot be inside Nullable column).

getReturnTypeImpl promotes a nullable-key result with makeExtractedSubcolumnsNullableOrLowCardinalityNullableSafe, which puts the Nullable inside the dictionary, but executeImpl's nullable-index branch spelled the matching column-side promotion in plain-Nullable terms: DataTypeLowCardinality::isNullable() is false and removeNullable does not descend into it, so neither the strip nor the wrap happened and executeJSON returned the raw dictionary column. Separately, an all-constant call is dispatched with that wrapper already stripped from result_type, while executeJSON still returned a ColumnLowCardinality.

So: spell that branch's rule with the LowCardinality-aware helpers, and let the extracted path drop its own wrapper when the caller asked for a type without one. getReturnTypeImpl is unchanged, and the result now matches json.key everywhere I measured.

The first shape only surfaces in randomized runs: optimize_functions_to_subcolumns (default on, randomized in CI) rewrites the read to a subcolumn and casts it back, hiding the mismatch. The test pins it, with the enabled arm as a control.

Noticed, not changed: the mixin's delegate guard tests argument types, so a LowCardinality result with no such argument bypasses the adapter; harmless now that the function produces its declared type.

Not for changelog: the bracket overload and its nullable-key support both landed on master on 2026-09-13, and no 26.* release branch contains either. Relabel if you prefer.


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

Version info

  • Merged into: 26.10.1.86 (included in 26.10 and later)

groeneai and others added 2 commits September 14, 2026 05:12
`json['key']` on a `JSON` column whose typed path is a non-nullable
`LowCardinality(T)` failed two ways.

With a constant `Nullable(String)` key over a table column, the server hit
`Unexpected return type from arrayElement. Expected LowCardinality(Nullable(T)).
Got LowCardinality(T)` at the planner's partial-result fold
(`ActionsDAG.cpp:1491`). `getReturnTypeImpl` promotes such a result with
`makeExtractedSubcolumnsNullableOrLowCardinalityNullableSafe`, which puts the
`Nullable` inside the dictionary, but the nullable-index branch of
`executeImpl` spelled the matching column-side promotion in plain-`Nullable`
terms: `DataTypeLowCardinality::isNullable()` is `false` and `removeNullable`
does not descend into `LowCardinality`, so neither the strip nor the wrap
happened and `executeJSON` returned the raw dictionary column. Nothing
upstream repaired it, because `FunctionWithLowCardinalityFastPath` delegates
only when an argument type carries `LowCardinality` or every argument is
constant, and here the `LowCardinality` sits inside the `DataTypeObject`,
which `recursiveRemoveLowCardinality` does not descend into.

With an all-constant call the mixin does delegate, and the delegate's
`LowCardinality` adapter strips the wrapper from `result_type` before
dispatch, while `executeJSON` ignored its `result_type` and still returned a
`ColumnLowCardinality`. Depending on the consumer that surfaced as
`Invalid column type for ColumnUnique::insertRangeFrom` or as
`LowCardinality(T) cannot be inside Nullable column`.

Fix both by keeping the two sides of the promotion in the same vocabulary:
hand the recursion `removeNullableOrLowCardinalityNullable(result_type)` and
restore with `makeNullableOrLowCardinalityNullableSafe` when the declared
result is LC-nullable, and let the extracted path drop its own
`LowCardinality` when the caller asked for a type without one.
`getReturnTypeImpl` is unchanged, and the result now matches `json.key` for
every source and key shape.

The first shape only ever appeared in randomized stress runs because
`optimize_functions_to_subcolumns` (on by default, randomized 0/1 by
`clickhouse-test`) rewrites the read to a subcolumn and casts it back to the
declared type, hiding the mismatch. The regression test therefore pins the
setting and keeps the enabled arm as a control.

Co-Authored-By: Claude Opus 5 <[email protected]>
`recursiveRemoveLowCardinality` descends into `ColumnArray`, `ColumnTuple`,
`ColumnMap`, `ColumnNullable` and `ColumnConst`, so it also stripped a
`LowCardinality` nested inside the path's own type, which the declared result
type keeps. `DataTypeArray`, `DataTypeMap` and `DataTypeTuple` all inherit
`IDataType::lowCardinality() == false`, so the guard let those types through
and the recursion then removed a wrapper they were entitled to:
`json['arr']` on a `JSON(arr Array(LowCardinality(String)))` path produced
`Array(String)` against a declared `Array(LowCardinality(String))`, aborting
the same declared-vs-produced check this commit's parent set out to satisfy.

The wrapper the caller removed is the top-level one: the `LowCardinality`
adapter dispatches with `result_type`'s dictionary type, one level off. So
remove exactly one level. Only `ColumnLowCardinality` and `ColumnConst`
override `convertToFullColumnIfLowCardinality`, which leaves the container
columns alone by construction rather than by a type test, and makes the
narrowing inert on every shape that already worked: after `applyOuterNullMap`
a promoted path is a top-level `ColumnLowCardinality` and is still converted.

The regression test gains one column pair in the existing all-constant
scenario. The table-column route reaches the same guard with the same
`result_type`, and the guard reads only `result_type`, never the input
column's shape or constness, so a second query there would add no coverage.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 14, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Reviewed cold against the resulting code, then re-reviewed by a second model, then adjudicated. Two
rounds. Round 1 found and fixed a defect this PR's own first attempt had introduced; round 2 came back
clean on both passes.

Round 1

❌ executeJSON stripped LowCardinality recursively, but only tested for it at the top level.
recursiveRemoveLowCardinality descends into Array/Tuple/Map, so json['arr'] on a
JSON(arr Array(LowCardinality(String))) path returned Array(String) against a declared
Array(LowCardinality(String)): a fresh Unexpected return type from arrayElement, on a read that
works on master. The wrapper the caller removed is the top-level one (the executable-function adapter
dispatches with the result type's dictionary type, one level off), so
convertToFullColumnIfLowCardinality() is what mirrors it, and IColumn.h documents exactly that
split. Fixed, with the nested-path case added to the existing all-constant test scenario and a mutation
arm restoring the recursive spelling, which reddens with a message naming a type only that new column
pair produces.

⚠️ Two in-diff comments asserted more than held: one described a top-level unwrap for recursive code,
one attributed a constant-key guarantee to the generic nullable-index branch rather than to the JSON
overload. Reworded.

Round 2

Clean: no findings from either pass. I re-derived the two load-bearing claims myself rather than taking
them from the fix notes. The new executeImpl comment says a JSON path is the only source that can
declare an LC-nullable result there, so no NULL index row needs merging, and that is exact: every
non-JSON branch of getReturnTypeImpl passes the element or value type through
recursiveRemoveLowCardinality before any makeNullable, so none of them can declare
LowCardinality(Nullable(T)), and the JSON branch rejects a non-constant key during type deduction.
The narrowing is inert on shapes that already worked, because an extracted LowCardinality element is
never wrapped into ColumnNullable (ColumnLowCardinality does not override
IColumn::canBeInsideNullable()), so it stays a top-level ColumnLowCardinality and is still
converted.

💡 Kept as-is after checking: one commit per root cause; and Not for changelog, because
src/Functions/array/arrayElement.cpp on all six live 26.x release branches contains no
executeJSON at all, so the bracket overload does not exist in any released version and
Bug Fix (user-visible misbehavior in an official stable release) would be false. Relabel if you
prefer.

@clickhouse-gh clickhouse-gh Bot closed this Sep 14, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 14, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, on demand, rc=134 every time: clickhouse local + CREATE TABLE t (json JSON(s LowCardinality(String))) ENGINE = MergeTree ORDER BY tuple(), then SELECT json[CAST('s','Nullable(String)')] AS s, toTypeName(s) FROM t SETTINGS optimize_functions_to_subcolumns = 0. Same frames as both CI occurrences (ActionsDAG.cpp:1491 <- :1782 <- :1616 <- ExpressionStep.cpp:70 <- Planner.cpp:699); only the leaf type differs, since LowCardinality(String) needs no allow_suspicious_low_cardinality_types.
b Root cause explained? Yes. getReturnTypeImpl promotes a nullable-key result with makeExtractedSubcolumnsNullableOrLowCardinalityNullableSafe, putting the Nullable inside the dictionary; executeImpl's nullable-index branch spells the column-side promotion in plain-Nullable terms only (DataTypeLowCardinality::isNullable() is false, removeNullable does not descend into LowCardinality), so neither the strip nor the wrap happens and executeJSON returns the raw dictionary column. Onset 23bb17888a05; before it the query was rejected at analysis with ILLEGAL_TYPE_OF_ARGUMENT. A second shape: an all-constant call is dispatched with the LowCardinality wrapper already stripped from result_type, and executeJSON still returned a ColumnLowCardinality.
c Fix matches root cause? Yes: the branch that owns "a nullable index promotes the result" is taught the LowCardinality spelling of its own rule, and executeJSON is given the one fact its caller already had. The unwrap in executeJSON is top-level only (convertToFullColumnIfLowCardinality), mirroring the single level the adapter removed from result_type (IFunction.cpp:533 getDictionaryType()); a wrapper nested inside the path's own type is part of the declared result and is kept. No widened columnMatchesType, no relaxed LOGICAL_ERROR, no no-random-settings tag, no cast at the ActionsDAG layer; that guard caught a real contract violation and keeps doing so.
d Test intent preserved / new tests added? Both. The 5 existing scenarios of 05210_json_bracket_nullable_key and their .reference lines are byte-identical. 3 scenarios added, each a demonstrated-live oracle: lowcardinality_typed_path (reddens under M1/M2/M7), ..._constant_source (M1/M5/M8; its third column pair is the sole oracle for the nested-wrapper case, and M8's abort text names Array(LowCardinality(String)), a type only that pair produces), ..._nullable_json (M7 in isolation).
e Both directions demonstrated? Yes, on every arm. Base Build-ID 1f60a30d...: the test file aborts with Expected LowCardinality(Nullable(String)). Got LowCardinality(String). Fix Build-ID 71608a8d...: rc=0, output byte-identical to .reference. Separately for the top-level-only unwrap: SELECT CAST('{"arr": ["x"]}', 'JSON(arr Array(LowCardinality(String)))')['arr'] returns ['x'] / Array(LowCardinality(String)) on base and on the fix, and aborts under mutation M8. Every mutation arm was asserted to carry a distinct Build-ID before its result was believed.
f Fix is general across code paths? Both dispatch routes into the JSON overload are fixed (direct Base::executeImpl, and the constant/LC delegate). Siblings audited and deliberately untouched with reasons: Array/Map/QBit apply recursiveRemoveLowCardinality before deciding nullability so they never declare an LC-nullable result; arrayElementOrNull throws for JSON in both type deduction and execution; tupleElement already pairs the promotion helper with NullableSubcolumnCreator and is the correct precedent. Fixed at the source, not guarded at the abort site. The one residual (FunctionWithLowCardinalityFastPath's argument-only delegate guard) is disclosed in the PR body.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured matrix: source JSON / Nullable(JSON), constant / non-constant; key String / Nullable(String) / NULL literal / CAST(NULL,'Nullable(String)') / non-constant (still correctly rejected); path type LowCardinality(String) / UInt32 / Dynamic / Array(UInt32) / Array(LowCardinality(String)) / Map(String, LowCardinality(String)); rows present / missing path / outer NULL; both optimize_functions_to_subcolumns values. Types agree across all of them and match the json.key dot spelling (asserted equal, not just same-typed); values equal json['key'] on every row. The two mechanisms compose: a nested-LowCardinality path read with a Nullable(String) key gives Array(LowCardinality(String)), an Array being uncontainable in Nullable exactly as the pre-existing arr scenario already asserts.
h Backward compatible? (maintainer-approved exception only) Yes, and nothing is owed: no setting added or changed (so no SettingsChangesHistory.cpp entry), no serialization or version change. The user-visible type of json[<nullable key>] on a LowCardinality path goes from aborting or throwing to LowCardinality(Nullable(T)), which is what json.key and Nullable(JSON) already produce.
i Invariants and contracts preserved? Yes. Restored invariant: when the nullable-index branch declares a promoted result, the column carries the promotion where the type does (in the dictionary for LowCardinality(Nullable(T)), in an outer null map for Nullable(T)). Second invariant, held by construction: the column gives up exactly the LowCardinality levels the declared type gave up (one, at the top), so a wrapper nested in the path's type survives; only ColumnLowCardinality and ColumnConst override convertToFullColumnIfLowCardinality, so ColumnArray/ColumnTuple/ColumnMap/ColumnNullable are left alone without a type test. The already-promoted composed Nullable(JSON) case is not double-wrapped (outer NULL preserved, s IS NULL = 1). No block-structure, sort-order, size or locking contract is touched; the function is pure with no partial-column error path. The same declared-vs-produced check at ExpressionActions.cpp:698 and resolveFunction.cpp:3407 is satisfied by the same change.

Verification: 05210_json_bracket_nullable_key OK, .reference matched byte for byte; 50/50 randomized
runs pass, with the per-query SETTINGS pin confirmed from system.query_log at both values (150
queries pinned to 0, 50 at the 1 control, and the new nested-wrapper query pinned to 0 in all 50
runs) and randomization provably live (up to 104 settings per query, 51 distinct max_block_size across
1600 logged queries); regression neighbourhood 366/373 over every test that subscripts a JSON column,
every test declaring a typed JSON path and every test using LowCardinality inside Array/Map/
Tuple, with zero result differs anywhere and all 7 failures re-measured as failing identically
on the pristine base binary (5 remote('127.0.0.{1,2,3}'), 1 url(...:8123), 1 needing a TLS
certificate, none reachable from a single-node sandbox server); local style checks 14/15, the one
failing leg being settings_changes_history, which fails closed without CI workflow context and whose
subject this diff does not touch.

Session id: cron:clickhouse-impl-slot-40:20260914-054900

@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [597685f]

Summary: ✅


AI Review

Summary

This PR fixes arrayElement for json['key'] reads from typed JSON paths stored as LowCardinality(...), so the produced column matches the declared type across the nullable-key path and the all-constant low-cardinality adapter path. I re-read the current diff together with the surrounding nullable and LowCardinality helpers and did not find any remaining correctness, compatibility, or test-contract issues in the patched code.

Missing context / blind spots
  • ⚠️ I could not re-run tests/queries/0_stateless/05210_json_bracket_nullable_key.sql locally because this checkout does not include a usable build artifact; the remaining proof point is CI on commit 597685fd58e3a77bc073b5e4fc0c31e1b96a30ed.
Final Verdict

✅ No new review findings.

LLVM Coverage Report

Measured on commit 597685f.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 15/16 (93.75%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 14, 2026
@groeneai
groeneai requested review from Avogar and nihalzp September 14, 2026 07:04
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 597685fd5 with master 62e5fdb33 (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.

Compile time of recompiled translation units

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

Job report

@Avogar Avogar self-assigned this Sep 14, 2026
@Avogar

Avogar commented Sep 14, 2026

Copy link
Copy Markdown
Member

@groeneai investigate integration tests failure.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 45c16d7

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
Integration tests (arm_binary, distributed plan, 1/4) / test_userspace_page_cache/test_incorrect_limits.py::test_limits infra, not caused by this diff: ClickHouseCluster.start() runs docker compose pull unconditionally, so the shard re-contacted the registry 88 minutes after the job had already prefetched the same pinned image, and got pull access denied for minio/minio; the fixture died before the case under test ran, reddening a shard whose other 2,022 tests passed a fix task is created (investigating at full effort, fixing PR link to follow on this PR)

How to read this head:

  • CI is fully finished. The live check-suite 94281053222 completed at 11:47:21Z with Finish Workflow = success: 151 pass, 20 skipped, 1 failure, nothing queued or in progress. Mergeable Check and PR are aggregators reporting only the single leg above, so they carry no separate owner.
  • The 171 CANCELLED names also visible on this head belong to suite 94280862685, the dispatch superseded 61 seconds later. Count suites before reading any per-check verdict.
  • Breadth over 30 days in CIDB: pull access denied matches exactly 1 row (this one), and the test itself has 3 rows across 2 pull requests with 0 true-master hits. So the trigger is a first-seen registry transient, and what the fix task removes is the unconditional pull that let a 09:39:39Z prefetch success be re-litigated at 11:08:11Z.

Session id: cron:our-pr-ci-monitor:20260914-133210

@groeneai

Copy link
Copy Markdown
Collaborator Author

Investigated. Not caused by this PR: the diff is src/Functions/array/arrayElement.cpp plus the two 05210_json_bracket_nullable_key files, and it touches no integration helper.

Docker Hub was denying minio/minio this morning. CIDB has 3,308 rows carrying pull access denied for minio/minio, from checks started between 09:28:39Z and 11:03:09Z, spread over 56 pull requests and 48 integration checks, 739 of them on master. There is nothing after 11:03Z, and integration CI has been at its baseline failure rate since.

Of those 3,308 rows, 3,306 are SKIPPED, one is OK, and exactly one is a red test: mine. _is_infrastructure_error relabels a FAIL only when the message carries both an infrastructure pattern and docker context, and it tests for docker context as 'docker' or images_pull_cmd (ci/jobs/integration_test_job.py:832-833). This row carries pull access denied 8 times but renders the argv as Command [docker compose ...], unquoted, so the guard misses it and the row stays FAIL.

The mechanism I want to fix is upstream of that: ClickHouseCluster.start() pulls unconditionally (cluster.py:3746, :3756) although the job has already prefetched every image of the batch, fail-closed (integration_test_job.py:1869-1871), so a prefetch that succeeded gets re-litigated at the registry later in the same job. That fix is implemented and measured in both directions (0 pull commands and 10/10 green with it, 5/5 red without); I will post its PR link here. The classifier stays as it is.

Separately, for whoever owns CI registry access: minio/minio, minio/mc and minio/aistor are all absent from Docker Hub's public repository API right now and answer 401 to an anonymous pull on every tag, while library/alpine answers 200 through the identical probe.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the ledger's one open line: #120107. It stops the per-module docker compose pull from re-contacting the registry for an image the job already prefetched, which is what killed the test_userspace_page_cache/test_incorrect_limits.py::test_limits fixture on this head.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 18, 2026
Merged via the queue into ClickHouse:master with commit 80e03d8 Sep 18, 2026
178 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 18, 2026
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-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-not-for-changelog This PR should not be mentioned in the changelog 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.

4 participants