Skip to content

Re-resolve a nested subcolumn name at the array level it was resolved at - #113752

Merged
alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-nested-array-level-size-subcolumn
Sep 12, 2026
Merged

alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-nested-array-level-size-subcolumn

Conversation

@groeneai

@groeneai groeneai commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC) or LOGICAL_ERROR

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

Fix a segfault and silently wrong results when reading a sizeN subcolumn of a nested Array(JSON) path; in debug and sanitizer builds the same read aborted with a LOGICAL_ERROR in IColumn::assertTypeEquality. Closes #113686.

Description

What breaks. Reading a sizeN subcolumn of a nested Array(JSON) path aborts in IColumn::assertTypeEquality, from SerializationDynamicElement::deserializeBinaryBulkWithMultipleStreams:

CREATE TABLE t (json JSON) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t FORMAT JSONAsObject {"a" : [{"b" : [42, 43]}]}
SELECT json.a.:`Array(JSON)`.b.:`Array(JSON)`.size1 FROM t;

Release builds. The check is compiled out, so the read proceeds. Measured on stock release master 26.9.1.880: a segfault (Address: 0x58), PARAMETER_OUT_OF_BOUND from ColumnArray::insertRangeFrom, or a wrong size ([110459705806544] instead of [2]).

Root cause. The digit in a sizeN name is the array depth from the column root, so the same name denotes a different subcolumn at each level. SerializationDynamicElement and SerializationObjectSharedDataPath keep such a name and resolve it again at array level 0 when the value comes from the shared variant or from shared data. The kept name carried the number it was resolved with, so the two resolutions disagreed on the type.

What the change does. The name is renumbered when it is stored. IDataType::getSubcolumnNameForZeroArrayLevel reads the substreams path getSubcolumnInfo reports, since only that tells whether the name really resolved to the array sizes, and rewrites the digit to the array level inside it. No level is stored and no public signature changes.

Validation. On a debug build of the head the regression test output is byte-identical to its .reference; on master it aborts.

Not fixed here. .size0 on such a path is an ordinary path at the level it was resolved at and the array sizes at level 0, so the renumbering does not fire and the read still aborts at the same assertion. That is unchanged from master and is a separate ambiguity, since size0 can then mean two subcolumns; it is addressed in #116393.

Reported on #112945. The fix in its present form is @ Avogar's rework of my original change.


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

Reading a "sizeN" subcolumn of a nested Array(JSON) path aborted the server
with a LOGICAL_ERROR from IColumn::assertTypeEquality, reached through
SerializationDynamicElement::deserializeBinaryBulkWithMultipleStreams.

A "sizeN" name is not fixed: the digit is the array depth counted from the
column root, so the same name denotes a differently shaped subcolumn at each
level. Resolution threads that level correctly, but the level was dropped when
the remaining subcolumn name was stored for later re-resolution, and every
public IDataType::getSubcolumn entry point hardcoded it to zero. One name was
therefore resolved twice at two different levels, yielding two different types,
and insertRangeFrom appended a mismatched column.

The level is not stored anywhere. SerializationArray keeps one ArrayElements
entry on settings.path for the whole of nested deserialization, one per array
wrapper, so the depth is already available at each re-resolution site and is
derived there with the existing ISerialization::getArrayLevel. Deriving it per
call also keeps the serialization pooling hash unchanged, which storing it
would not have done.

IDataType::getSubcolumn and tryGetSubcolumn take a defaulted
initial_array_level, forwarded through their ColumnConst recursions so a
wrapped column does not silently reset the level. The default keeps every other
call site behaving exactly as before: git grep -nE
'(->|\.)(getSubcolumn|tryGetSubcolumn)\(' -- src/ finds 15 non-test member
calls, and only the three nested re-extraction sites pass a level, where the
previous code passed a literal zero.

The array level was measured at each of the three sites before the fix was
trusted: 1 and 2 for two- and three-level paths through
SerializationDynamicElement, and 1 for both shared-data sites. Mutants that
drop the level at one site, replace it with a constant, or replace it with zero
each redden only the arms belonging to that change.

The ColumnConst recursion of the resolving API cannot be reached from any site
that passes a level, so it is covered by two gtests rather than by the
stateless test, one per entry point, each pinned by its own mutant.

No stream names and no on-disk layout change: the part file list is identical
before and after on the same fixture.
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 5 findings adjudicated)

Two independent review rounds ran before this PR was opened: a cold code review plus an independent
second-model pass in each, then adjudication against the recorded evidence. Round 1 bounced the
branch back for fixes; round 2 published. The code has been byte-identical since round 1:
git diff over the four changed logic files between the two reviewed commits is empty, so both
rounds' clean code verdict describes the tree that ships here. Every finding in both rounds was in
published text or in test coverage, never in the fix itself.

Round 2 findings

Finding Verdict
⚠️ Five figures in the PR body's Validation sentence were stale: the matrix grew from 18 cells to 26 (11 witnesses, 15 controls), the mutant count from 5 to 8, and the regression slice from 195 tests to 339, all because round 1 added arms and mutants without re-deriving the sentence that describes them. Agreed, corrected. All five re-measured from the shipped artifacts.
⚠️ This validation comment said the new test has "3 fixture-check arms"; it has 2 (10 witnesses, 8 controls, 2 fixture checks, 1 that prints the expression types = 21 labelled arms, which matches the reference file positionally). 10+8+3 also summed to 21, which is why the wrong figure survived a round. Agreed, corrected.
⚠️ This comment repeated the stale 195-test slice size, and its failure breakdown accounted for 4 of the 8 residual environmental failures. Agreed, corrected to 339 with the full 3 timeouts / 2 return-code-124 / 3 stderr breakdown.
💡 The mutant preamble said M1 and M2 "redden only their own arm" while the table two rows below correctly recorded 5 and 2 arms respectively. Agreed, corrected to "only the arms belonging to the site they change, and those sets are disjoint".
❌ The second-model pass asked to move ### Description above the changelog fields, move Closes outside the HTML comment, and reword the changelog entry to "Fixes an exception ...". Disagreed, all three parts, on measurement. The upstream PULL_REQUEST_TEMPLATE.md has no Description section at all, so reordering would mean altering upstream ### headers, which breaks Config Workflow parsing (PRs #103738, #106934); the body keeps both upstream headers byte-identical, in upstream order, and appends the only extra one. Closes is already outside the comment as Closes #113686., and that form does register a closing reference: of 300 recent merged PRs, the two whose only bare form is Closes #N in prose both have exactly one closing-issue reference naming that issue. And "exception" would be inaccurate: assertTypeEquality is a chassert, which on debug and sanitizer builds calls abortOnFailedAssertion (base/base/defines.h:85-93) and exits with 128 + SIGABRT (src/Common/Exception.cpp:69-77); every one of the 11 aborting cells shows <Fatal> : Logical error and server died, not a thrown exception.

Round 1 findings (all agreed, all fixed in round 1)

The commit message, this comment and the evidence claimed "nine existing callers" of the changed
API, which reproduces under no predicate; the authoritative census is 15 non-test member calls
across 12 files, identical on master and on this branch. A witness arm was labelled as pinning the
ColumnConst recursion, which no site reachable from SQL can exercise; it is really a second
dynamic-element witness, and the recursion is now pinned by two gtests with one mutant each. One
arm was labelled CONTROL while the measured table records that cell as aborting before the fix;
a mechanical checker now scores all 21 labels against the measured pre-fix liveness table, and
fails on the pre-round file, so it is a real tripwire. Two coverage gaps the second model found were
also closed: every SerializationDynamicElement expectation was a default value, so an
always-defaulting implementation of that branch would have kept the reference intact. A new arm now
reads a non-zero extracted size, and a mutant that makes the extraction always default reddens only
that arm.

Noted, not fixed here. Under the advanced shared data version, requesting the subcolumn on its
own reaches a separate pre-existing stream-enumeration defect
(SerializationObjectSharedData.cpp:1059), measured identically on the unpatched binary. Two open
PRs (106643, 102499) add new getSubcolumn(nested_subcolumn, ...) call sites in the function this
fix repairs and pass no level; whichever merges second will need getArrayLevel(settings.path) at
those sites too, and 102499 also deletes the line this PR edits, so a textual conflict there is
likely regardless of order.

Every countable claim in the PR body, this comment and the commit message was re-derived from the
shipped artifacts before publication and the three agree on all of them; all cited file:line
references were verified against origin/master, the tree a reviewer greps.

Session id: cron:clickhouse-review-slot-10:20260807-010200

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (a-i)
# Check Result
a Deterministic repro? Yes. Two statements at default settings, no fuzzer and no SET: CREATE TABLE t (json JSON) ENGINE = MergeTree ORDER BY tuple(), INSERT INTO t FORMAT JSONAsObject {"a" : [{"b" : [42, 43]}]}, then SELECT json.a.:`Array(JSON)`.b.:`Array(JSON)`.size1 FROM t. The server aborts; clickhouse-test reports Reason: server died 32. 11 of the 26 measured cells abort on the unpatched binary, each on every attempt.
b Root cause explained? Yes. A sizeN name is not fixed: getNameForSubstreamPath emits ".size" + toString(array_level) and increments array_level at each ArrayElements (ISerialization.cpp:312-320), so the digit is the array depth from the column root. Resolution threads the level (IDataType.cpp:175/194/221, DataTypeArray.cpp:95 adds one per wrapper), but DataTypeDynamic::getDynamicSubcolumnData stores the remainder as a bare string with no level (DataTypeDynamic.cpp:990), and every public IDataType::getSubcolumn* hardcoded {} = 0. One name, two levels, two types, so insertRangeFrom appends a mismatched column and assertTypeEquality aborts.
c Fix matches root cause? Yes: the level is restored at the three points where it was dropped, so deserialization agrees with resolution by construction for every name and depth. No widened bound, no no-random-* tag, no guard at the crash site, and no resolution behaviour changed.
d Test intent preserved / new tests added? New stateless test 04812_json_nested_array_size_subcolumn with 21 labelled arms — 10 witnesses, 8 controls, 2 fixture checks and 1 that prints the expression types — plus two new gtests in gtest_IDataType_getSubcolumn_const.cpp. Every -- WITNESS arm maps to a cell that aborts on the unpatched binary and every -- CONTROL arm to one that does not; that mapping is checked mechanically against the measured pre-fix table rather than asserted. One witness arm reads a non-zero extracted size ([2]), so the extraction is pinned by value and not only by the absence of an abort. 03813_size_subcolumn_of_dynamic_subcolumn, which states the intended semantics for arrays outside the dynamic value, is unmodified and still passes.
e Demonstrated in BOTH directions? Yes, on separately built binaries with the server restarted per arm and SELECT lower(buildId()) asserted equal to that binary's NT_GNU_BUILD_ID first (clickhouse-test --binary X does not restart the server). Pre-fix a72eba992db5a0ed: [ FAIL ] Reason: server died 32. Post-fix 8a3baef4580029bd: [ OK ].
f General across CODE paths? All three re-resolution sites are fixed: SerializationDynamicElement.cpp:299 and SerializationObjectSharedDataPath.cpp:305 (map) and :348 (advanced), as they are numbered on master. Each was proven separately load-bearing by its own mutant. SerializationObjectDynamicPath needs no change (it never re-resolves its path_subcolumn; grep getSubcolumn returns 0). DataTypeMap::getDynamicSubcolumnData discards its initial_array_level parameter, but the shape reproduces and is repaired by this fix, so that discard is not a separate defect; the test covers it.
g Generalizes across INPUTS? Depths 1, 2 and 3 (including the non-obvious depth-3 alternation, where size0 and size2 aborted while size1 and size3 were already clean), at-level, below-level and above-level names, a non-reserved name, an expression that also produces a constant column, a Map between the array wrappers and the dynamic path, shared data in both the map and advanced versions, a type evicted into the shared variant so the extracted size is non-zero, and plain Array(Array(Array(UInt64))) as a control. The ColumnConst recursion of the resolving API is covered at unit level, since no level-passing site can reach it from SQL.
h Backward compatible? Yes. No setting default changes, so no SettingsChangesHistory.cpp entry. The parameter is defaulted, so every other call site is source-compatible and behaves identically: git grep -nE '(-&gt;|\.)(getSubcolumn|tryGetSubcolumn)\(' -- src/ finds 15 non-test member calls across 12 files, and only the three nested re-extraction sites pass a level. That count is identical on master and on this branch; the previous code passed a literal {} = 0 at exactly those three, and the new default is 0, so no unchanged caller can observe a difference. (The totals including src/*/tests/ are 19 on master and 23 here, the four extra being this PR's own new gtest calls.) The level selects among existing streams: on the same fixture the part file list is md5-identical before and after.
i Invariants and contracts preserved? The repaired invariant is that a subcolumn name stored for later re-resolution must travel with the array level it was resolved at. Nothing is stored, so no serialization object gains a member and the ISerialization::pooled hash inputs are unchanged (storing a level without hashing it would have let two levels share one pooled object). The derived level was measured at each site before the fix was trusted: 1 and 2 for two- and three-level paths through SerializationDynamicElement, and 1 for both shared-data sites; the depth-1 case never reaches the site, which is why it was already correct. The level is also forwarded through both ColumnConst recursions of the resolving API; that path is unreachable from every level-passing site (all three pass a freshly created column), so it is pinned by two gtests instead, each with its own mutant.

Mutants. M1-M4 and M6-M7 are applied to the server (shipping Build ID 8a3baef4580029bd), M8-M9 to unit_tests_dbms (08cb77d3b030157c). Each was rebuilt with its Build ID asserted to move, and after restoring, both binaries returned to their shipping Build IDs byte-exactly. M1, M2, M3, M7, M8 and M9 each redden only the arms belonging to the site they change, and those sets are disjoint; M4 and M6 are deliberately applied at all three sites, so they redden a group.

Mutant Change Cells reddened
M1 drop the level at SerializationDynamicElement.cpp the 4 dynamic-element cells plus the ColumnConst cell; both shared-data cells stay green
M2 drop the level at SerializationObjectSharedDataPath.cpp (map version) only the 2 map-version shared-data cells
M3 drop the level at SerializationObjectSharedDataPath.cpp (advanced version) only the advanced-version cell
M4 hardcode the level to 1 at all three sites the depth-3 cells, proving the value is derived rather than a constant that fits the reported case
M6 hardcode the level to 0 at all three sites exactly the witnesses, which is the anti-vacuity guard for the derivation itself
M7 make the shared-variant type-name comparison unsatisfiable, so the late extraction can only see defaults only the non-zero shared-variant arm and its adjacent control; every other arm keeps its verdict, which is precisely why that arm was added
M8 drop the level from the ColumnConst recursion of getSubcolumn only only the getSubcolumn gtest assertion; the tryGetSubcolumn one and the stateless test stay green
M9 drop the level from the ColumnConst recursion of tryGetSubcolumn only only the tryGetSubcolumn gtest assertion; the mirror of M8

Other runs. 50 randomized plus 50 plain runs of the new test all pass. A 339-test subcolumn slice run on both binaries with the same explicit test list gives identical failure sets and identical reasons: the same 8 tests fail on both, in the same buckets (3 Timeout! Killing process group on a loaded box, 2 return code: 124, 3 having stderror — an iceberg/S3 case and two filesystem-cache-resize cases). 0 only-in-fix failures, 0 only-in-base failures, 0 reason changes. The base arm runs 338 of the 339, the one absentee being the new test, which does not exist there.

Noted, not fixed here (one concern per PR). Under the advanced shared data version, requesting the subcolumn on its own reaches a different pre-existing defect, Substream ... is requested but not found in substreams list (SerializationObjectSharedData.cpp:1059), which reproduces identically on the unpatched binary. The test therefore pins the shared data version and selects the whole path alongside the subcolumn in the advanced arm.

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @CurtizJ, could you review this? A sizeN subcolumn name only means something together with the array nesting level it was resolved at, but the level was dropped when the remaining name was stored for later re-resolution and every public IDataType::getSubcolumn hardcoded it to zero, so a nested Array(JSON) path resolved one name at two levels and insertRangeFrom appended a mismatched column. The level is now derived at each re-resolution site from the live substream path with ISerialization::getArrayLevel, so nothing is stored.

@PedroTadim

Copy link
Copy Markdown
Member

cc @Avogar

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c8c01a6]

Summary: ✅


AI Review

Summary

This PR reworks the nested Array(JSON) sizeN fix so later extraction stores a zero-level name instead of threading initial_array_level through getSubcolumn. The at-level sizeN case looks covered, but the helper still lets off-level sizeN names change meaning when they are re-resolved at level 0, so I cannot approve the patch yet.

Missing context / blind spots
  • ⚠️ The PR body still describes the reverted initial_array_level plumbing rather than the shipped getSubcolumnNameForZeroArrayLevel approach, so the effective contract had to be reconstructed from the code and the latest commit message.
Findings

❌ Blockers

  • [src/DataTypes/IDataType.cpp:241-250] getSubcolumnNameForZeroArrayLevel only rewrites names when the first resolution already ended on ArraySizes. For below-level names such as ...size0 one wrapper below the column root, the first getSubcolumnInfo resolves the string as an ordinary nested name, the helper stores it unchanged, and the later getSubcolumn(..., /*initial_array_level=*/0) in SerializationDynamicElement / SerializationObjectSharedDataPath reinterprets the same string as ArraySizes. That recreates the same “resolved subcolumn type vs extracted subcolumn type” mismatch this PR is meant to eliminate, so wrong results or insertRangeFrom assertions are still reachable.
    Suggested fix: store enough information to reproduce the original substream identity even when the original string was not ArraySizes at the first level. The removed 04812 “below level” witnesses are the focused regression cases to keep green.
Tests
  • ⚠️ Restore a focused stateless witness for the removed below-level sizeN case (for example ...size0 under the nested Array(JSON) path, plus the shared-data variant if it still differs). The current test keeps only the at-level path, so it no longer proves that late level-0 re-resolution agrees with the original resolution when the stored string becomes an array-size name only after extraction.
Final Verdict

Status: ⚠️ Request changes
Minimum required actions:

  • Preserve the original substream identity for off-level sizeN names instead of rewriting only the already-ArraySizes case.
  • Restore a regression test for that path.

LLVM Coverage Report

Measured on commit c8c01a6.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 28/28 (100.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 Aug 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c8c01a6b4 with master a61a24c6a (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

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

Job report

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e2d7952

Every failure below has an owner: a fixing PR (ours 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
Stress test (arm_release) / Logical error: Reading from materialized CTE 'A' before its materialization completed - DelayedPortsProcessor gate is missing in the query plan (STID 2467-3539) trunk bug, not PR-caused. Breadth over 30 days for the message (position(test_context_raw, 'DelayedPortsProcessor gate is missing in the query plan') > 0): 69 rows / 56 distinct PRs / 6 master, most recent 2026-08-07 12:18:20. The seven-file diff here is nested-subcolumn array-level resolution in IDataType and two serializations, nothing on the materialized-CTE planning path. #102308 (external, open)
Bugfix validation (unit tests) harness limitation, not a test failure. The job declares itself inconclusive: the before-binary cannot COMPILE the overlaid gtest because the new API does not exist yet on the base (error: too many arguments to function call, expected 2, have 3 for getSubcolumn/tryGetSubcolumn, four times). A PR that adds a parameter and a gtest exercising it can never satisfy this check, and the harness reds it rather than reporting the inconclusive outcome as a warning. a fix task is moved to pending (investigating at full effort - fixing-PR link to follow on this PR)
Sync - CH Inc sync (private, not actionable by me)

All 175 check-runs completed (156 success, 17 skipped, 2 failure); Config Workflow and
Finish Workflow both success. CIDB records 331,807 result rows across 160 checks on this commit;
both Bugfix validation (functional tests, amd64/aarch64) jobs concluded success.

Neither failure is caused by this diff, so nothing is fixed in this PR for them.

Session id: cron:our-pr-ci-monitor:20260807-130000

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
Two conflicts, both in the deserialization sites this branch edits. Master
refactored `deserializeBinaryBulkWithMultipleStreams` to take `IColumn &`
instead of `ColumnPtr &` and dropped `rows_offset` (a1e364e, 40656cb),
and it stopped keeping the shared-variant / shared-data map columns in the
deserialization state. Both conflicted files were reseeded from master verbatim
and the three `getArrayLevel(settings.path)` arguments re-applied on top, so
every refactor line survives byte-for-byte:

  - SerializationDynamicElement.cpp: unchanged apart from the added argument.
  - SerializationObjectSharedDataPath.cpp: `dynamic_column` is now an
    `IColumn &` rather than a `MutableColumnPtr`, so the MAP-branch call reads
    `dynamic_column.getPtr()`; the ADVANCED-branch call is unchanged.

`getArrayLevel` and `getSubcolumnData(..., size_t initial_array_level, ...)`
are byte-identical on master, and `Substream::Bucket` is not an
`ArrayElements` substream, so the level computed at each site is unchanged.
`IDataType.cpp`/`.h` auto-merged; master's `getSerializationInfo` overload
split and `createColumn` de-virtualization are preserved.

The merged tree differs from master by exactly this PR's own 7 files
(+266/-11) and moves no submodule pin.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Two measured things a reviewer needs before spending time here.

The red AST fuzzer (amd_debug, targeted, old_compatibility) is not caused by this PR. The fuzzer selected the subcolumn on its own, SELECT DISTINCT jd.a.:`Array(JSON)`.size1 ..., on this PR's own new fixture. That spelling aborts identically on a master build without this PR (Substream .Array(JSON(...)).size1 for path a is requested but not found in substreams list, from SerializationObjectSharedData.cpp), while the whole-path-plus-subcolumn spelling the new test ships returns the right answer here and aborts on master. This PR strictly shrinks the failing set; the fuzzer's spelling is a separate pre-existing defect in the subcolumn-only shared-data read, see the thread on SerializationObjectSharedDataPath.cpp above. Full CI ledger once the remaining checks finish.

#116393 overlaps this PR and should decide how it lands. It replaces getSubcolumnData with getSubcolumnInfo on the two lines this PR edits, IDataType::getSubcolumn and tryGetSubcolumn, and keeps the array-level argument there as {}. So the two conflict textually, and the level-0 re-resolution this PR fixes at SerializationDynamicElement.cpp:270 and SerializationObjectSharedDataPath.cpp:292,335 is not covered: neither file is in its diff, and its EnumerateStreamsSettings::array_level and getDynamicSubcolumnInfo(..., initial_array_level, ...) stop short of those two entry points.

Its reference file records toTypeName(arr2.size0) and toTypeName(arr2.size1) on Array(Array(JSON)) as Array(Array(Dynamic)), so a generated sizeN is no longer offered where the data can claim the name. If that covers the .:`Array(JSON)`.sizeN spelling too, every JSON arm of this test changes meaning. The defect stays reachable through a variant the data cannot claim: on jd Array(JSON) holding {"a":[[1,2],[3]]}, jd.a.:`Array(Array(Int64))`.size1 aborts on master with assertTypeEquality and returns the default [0] here.

@Avogar, your call and I will do either: rebase this test onto the non-JSON spelling so it survives #116393, or close this PR if you would rather carry the level at those two call sites inside that refactor.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d0650fb

CI is fully finished at this commit. One check failed, and it has an owner.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: Substream A for path B is requested but not found in substreams list (STID: 4755-633a) pre-existing defect on master, server abort in a debug build, not caused by this PR. The throw is in SerializationObjectSharedData.cpp, which is not one of the 7 files this PR touches. I measured it directly with 4 arms: on the failing spelling, which selects the subcolumn alone, my head and a master snapshot that provably lacks this fix both abort with a byte-identical message; on the whole-path spelling master aborts in assertTypeEquality while my head returns the correct answer. So this PR strictly shrinks the failing set and unmasks nothing. Detail and the exact arms are in issuecomment-5442608136. Note for anyone re-checking the breadth: the fuzzer mutated this PR's own new fixture, so no other pull request can produce this signature and its 1 row / 1 pull request / 0 master count is guaranteed by construction rather than evidence either way. a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113752&sha=d0650fb73f3f68ec60b2e261e4264650779f6caf&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

Everything else at this commit is green: 177 praktika nodes, 155 OK and 19 SKIPPED, and Config Workflow, Style check and Finish Workflow all OK. Gate reads at this commit are 0 incomplete check runs of 174 distinct names, and 175 raw runs matching the reported total. This commit has a single parent workflow run, 33080322706, so no run supersedes another here.

Session id: cron:our-pr-ci-monitor:20260827-200000

@Avogar Avogar self-assigned this Sep 1, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-json-datatype JSON/Dynamic/Object datatype: semi-structured column storage, typed and dynamic paths, sub-object... label Sep 4, 2026
The level was threaded into the public IDataType::getSubcolumn and
tryGetSubcolumn so that the three sites which re-resolve a stored
subcolumn name could re-resolve it at the level it was resolved at. The
next commits reach the same result without a level at those sites, by
storing the name in the form that resolves to the same substream at
array level 0.

The functional test is kept and adapted later; the gtests only pinned
the ColumnConst forwarding of the reverted parameter.
"sizeN" counts Array wrappers from the root of the column, so the array
sizes get a different number at every array nesting level.
SerializationDynamicElement and SerializationObjectSharedDataPath keep
such a name to resolve it again against the type of a dynamically typed
value alone, that is at array level 0, when the value comes from the
shared variant or from shared data. The name kept the number it was
resolved with, so the two resolutions disagreed on the type and
insertRangeFrom aborted in IColumn::assertTypeEquality, or, in a release
build, segfaulted or returned a wrong size.

The name is now renumbered when it is stored. The substreams path that
getSubcolumnInfo reports tells whether it really resolved to the array
sizes - a name alone cannot, since a Tuple element or a JSON path can be
spelled the same - and the array level inside that path is the number the
sizes get against the type alone.

The user-facing names do not change: they stay relative to the root of
the column, as 03813_size_subcolumn_of_dynamic_subcolumn pins them.

A name that is not the array sizes is stored unchanged. Such a name can
still mean different substreams at different levels, which is the subject
of ClickHouse#116393 rather than of
this fix.
@Avogar

Avogar commented Sep 11, 2026

Copy link
Copy Markdown
Member

@groeneai I reworked the fix, made it simpler based on #115777 work

Comment thread src/DataTypes/IDataType.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks, that is much smaller than mine, and keeping the level inside getSubcolumnInfo is nicer than threading it through getSubcolumn.

I rebuilt c8c01a6b (debug, amd64) before saying anything. The committed test passes byte-identically to its .reference, and it still aborts on master (c108e273b), so the oracle holds.

One case the rework does not cover, which I think is why the four arms had to come out of the test:

CREATE TABLE t (json JSON) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t FORMAT JSONAsObject {"a" : [{"b" : [42, 43]}]}
SELECT json.a.:`Array(JSON)`.b.:`Array(JSON)`.size0 FROM t;

That still gives Logical error: ... typeid(*this) == typeid(rhs) in IColumn::assertTypeEquality, from insertRangeFrom at SerializationDynamicElement.cpp:274 under MergeTreeReaderCompact::readData, the same frames as the report. The three other removed arms abort too:

SELECT json.a.:`Array(JSON)`.b.:`Array(JSON)`.c.:`Array(JSON)`.size0 FROM t04812_json3;
SELECT jd.a.:`Array(JSON)`.size0 FROM t04812_shared;
SELECT mp.values.values.a.:`Array(JSON)`.size0 FROM t04812_map;

All four abort on master as well, so none of this comes from your commits. It is the other half of #113686, and nothing covers it now.

All four are .size0, and that is not a coincidence: at level 0, size0 is the array sizes of any Array, whatever the name meant at the level it was resolved at. getSubcolumnNameForZeroArrayLevel renumbers only when the resolved path is the array sizes, and here it is not (toTypeName is Array(Array(Dynamic(max_types=8))), an ordinary non-existent JSON path), so the name is stored unchanged and the level-0 resolution returns the sizes instead. That is the mirror image of the direction you fixed, and I do not think a rename can express it, since no number spells "ordinary path" at level 0. Your new depth-3 arm passes for exactly that reason: .size1 is an ordinary path at both levels.

Two ways out, and the choice is yours:

  1. keep the level for the level-0 re-resolution, which is what 5655945a2145 reverted, or
  2. at SerializationDynamicElement.cpp:274 and the shared-data equivalent, notice that the re-resolved subcolumn is not the type the name was resolved to and insert defaults, which is what those arms returned in my version.

I am happy to push either on top of your commit with the four arms restored. Tell me which you want. Merging this as it stands and handling the remaining direction separately also works for me.

@Avogar

Avogar commented Sep 11, 2026

Copy link
Copy Markdown
Member

One case the rework does not cover, which I think is why the four arms had to come out of the test:

I believe this should cover it: #116393

@groeneai

Copy link
Copy Markdown
Collaborator Author

It does cover them. I built your branch head 617641d4 (debug; its base is 0a7157ee, so it contains neither this PR nor your rework of it, and every value below is #116393 alone). All five of these abort on master c108e273b with the same fixtures, the first four in assertTypeEquality:

arm master 617641d4
depth 2 .size0 abort [[]]
depth 3 .size0 abort [[[]]]
shared data .size0 abort [[NULL]]
Map .size0 abort [[[[]]]]
advanced shared data, subcolumn requested alone (Substream ....size1 for path a is requested but not found in substreams list, the case the test comments disclose) abort [[NULL]]

One consequence, since it decides what 04812 should look like afterwards: isHiddenByDynamicSubcolumn also claims the names this PR is about, so on 617641d4 the arms that are still in the test stop meaning the array sizes.

  • depth 2 .size1: [0] becomes [[]]
  • depth 3 .size2: [[0]] becomes [[[]]]
  • shared data .size1: [1] becomes [[NULL]]
  • shared variant .size1: [0] [0] [0] [2] becomes [[]] [[]] [[]] [[NULL,NULL]], identical to its .size2 arm
  • Map .size3: [[[0]]] becomes [[[[]]]]
  • depth 1 .size0, .size1: 1 [NULL] becomes [NULL] [NULL]
  • and jd.size0 on a plain Array(JSON): UInt64 2 becomes Array(Dynamic) [NULL,NULL]. Plain Array(Array(Array(UInt64))) is unchanged, so it is scoped to arrays that can claim the name.

So whichever of the two merges second owes 04812_json_nested_array_size_subcolumn.reference an update, and after #116393 that file no longer reaches the re-resolution it was written for. If #116393 is second, I will send the reference update, with the four arms back in their new meaning, as a follow-up. The array sizes of an Array(JSON) losing their spelling reads as user-visible to me, so it may want a changelog line, but that is your call.

Nothing outstanding from me on this PR.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
Merged via the queue into ClickHouse:master with commit aa121aa Sep 12, 2026
175 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 12, 2026
@clickgapai

clickgapai commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor
Reproducer
CREATE TABLE t (json JSON) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t SELECT '{"a":[{"b":[42,43]}]}'::JSON;
SELECT json.a.:`Array(JSON)`.b.:`Array(JSON)`.size1 FROM t;

-- 26.8.2.7 / 26.7.6.57 / 26.6.4.55 / 26.3.33.24 (release, aarch64): [55766552] -- a garbage size; expected [0]
-- sanitizer/debug build: the same SELECT aborts (SIGABRT) in IColumn::assertTypeEquality
-- 26.1.12.23 and older: [[]] -- the name never resolved to the array sizes, no bad read

Results:

  • Culprit PR: Fix reading size subcolumn from dynamic subcolumns Fix reading size subcolumn from dynamic subcolumns #95573
  • Reproduces on: 26.8, 26.7, 26.6, 26.3
  • Does not reproduce on: master
  • Tested versions: master, 26.8, 26.7, 26.6, 26.3
  • ✓ 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.8, 26.7, 26.6, 26.3.

CC introducing PR reviewer: @yariks5s

CC component owner: @alexey-milovidov

Analysis metadata

comp-json-datatype · Severity P2 · Finding phase_d_pr113752

@PedroTadim PedroTadim added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 14, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 14, 2026
alexey-milovidov added a commit that referenced this pull request Sep 14, 2026
Adapt #113752 to 26.3, which has no `SubcolumnInfo` with a resolved substream path:
`IDataType::getSubcolumnData` marks a resolved subcolumn as the array sizes in
`SubstreamData::is_array_sizes_subcolumn` (forwarded through the `Array` and
`Nullable` wrappers), and `getSubcolumnNameForZeroArrayLevel` derives the level-0
number by subtracting the array level the name was resolved with.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 14, 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-json-datatype JSON/Dynamic/Object datatype: semi-structured column storage, typed and dynamic paths, sub-object... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Segfault and silently wrong results reading a sizeN subcolumn of a nested Array(JSON) path (LOGICAL_ERROR in debug)

8 participants