Skip to content

Fix wrong results reading a re-added Nested member subcolumn - #113225

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-nested-member-subcolumn-shared-offsets
Aug 5, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-nested-member-subcolumn-shared-offsets

Conversation

@groeneai

@groeneai groeneai commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #112769
Closes: #113411

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix wrong results and a LOGICAL_ERROR when reading a subcolumn of a dropped-and-re-added Nested member together with a present member of the same group, on a MergeTree table with share_nested_offsets = 1. The present members returned values from a later block whenever the read spanned more than one block.

Description

No open issue. I hit this while validating #112997; it is separate and pre-existing - it reproduces at local_filesystem_read_prefetch = 0, where that PR is inert.

What breaks. MergeTree, share_nested_offsets = 1 (the default), ordinary settings. A Nested member was dropped and re-added, so it is missing from the part, and a query reads a subcolumn of it (arr.nested.b) beside a present member (arr.id) - both read one shared offsets stream. Once the range spans two blocks the present members come back with right lengths but wrong values; debug and sanitizer builds abort on column->size() == num_rows.

Root cause. MergeTreeReaderWide::readRows keys the substreams cache by getNameInStorage, so a shared stream is read once per call. getSubcolumnsOfNested skipped subcolumn entries, so a member requested only as a subcolumn never reached the group, Nested::convertToSubcolumns skipped its conditional remap, and the subcolumn landed in a different cache bucket. The stream was then read twice, and a continuation call suppresses the mark seek (correctly - it cannot rewind), so the second reader short-reads. That exposed a latent second half: fillMissingColumns' offsets branch derives its type from the same accessors.

The change. getSubcolumnsOfNested contributes a subcolumn's member (never the subcolumn's own name, which would build an invalid Nested type), de-duped. fillMissingColumns resolves the metadata shape from storage_snapshot by full name, as the neighbouring guard from #112769 does, falling back to today's behavior without a snapshot. This also fixes previously-aborting reads at depth 3 and over nested Array, Map, Nullable and Tuple value types.

Validation. New 04770_nested_subcolumn_shared_offsets_continuation, verified to fail without the fix; reverting any one of the three hunks reddens it. 03742_test_flattened_crash passes byte-identically. 50/50 randomized runs at jobs 8 and 1. Compact parts, merges, mutations and object storage also covered. 26.4-26.7 look exposed, but a backport needs #112769 first.

Version info

  • Merged into: 26.8.1.800 (included in 26.8 and later)

On a MergeTree table with share_nested_offsets = 1, a Nested member that was
dropped and re-added is missing from the part. Reading a subcolumn of that
member together with a present member of the same group returned wrong values
for the present members whenever the range needed more than one readRows call,
and aborted on 'column->size() == num_rows' in debug and sanitizer builds when
the short read left a non-empty residue.

MergeTreeReaderWide::readRows keys the substreams cache by getNameInStorage so
a stream shared by a Nested group is read once per call and the other consumers
are served from the cache. getSubcolumnsOfNested skipped subcolumn entries, so
when the missing member was requested only as a subcolumn nothing contributed
it to the group, tryGetSubcolumnType failed, the conditional remap in
Nested::convertToSubcolumns was skipped, and the subcolumn kept a cache bucket
of its own. The shared offsets stream was then read twice per call, and on a
continuation call the mark seek is suppressed because it would rewind to the
granule start, so the second reader got fewer rows than it asked for.

Make getSubcolumnsOfNested contribute the member of a Nested group for a
subcolumn entry, using the member's name and storage type and never the
subcolumn's own, which would rebuild the invalid Nested type that 16d7bab
removed. The contribution is de-duped so a co-requested parent cannot produce a
duplicate element.

That alone exposed a latent second defect. fillMissingColumns satisfies a
column absent from the part either by deferring to evaluateMissingDefaults or
by synthesizing a default from a Nested sibling's shared offsets, and the
offsets branch derived the slot's type and residual subcolumn name from
getTypeInStorage and getSubcolumnName. Those are exactly the accessors the
remap rewrites, so the branch walked the group type instead of the member type,
getBaseTypeOfArray silently stopped descending, and the result was a Tuple
under a declared element type or a residual path the truncated type could not
resolve. 9f656f3 documents this coupling and fixed the branch-selection
consumer through the storage snapshot; this fixes the type-computation one the
same way. It was latent only because the first defect suppressed the remap for
these shapes, so the branch got correct types by accident.

Resolve the metadata shape from the storage snapshot by full name, which the
remap preserves, and drive tuple_elements, getBaseTypeOfArray and
removeTupleElementsFromSubcolumn off it. num_dimensions and the collected
offsets columns are deliberately left alone: they must keep matching the
reader's stream names, which the remap normalizes on purpose. Without a
snapshot the code falls back to the requested pair, which the Memory engine
caller relies on.

Beyond the reported shape this also repairs previously aborting member
subcolumn reads over Array, Map, Nullable and Tuple value types and at
subcolumn depth 2 and 3.
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (independent cold review + gate, all findings adjudicated)

Two independent reviews of this diff: a cold read of the resulting code (no access to the
implementer's evidence), then a separate gated re-review. The gate returned 0 findings. The cold
read produced 3 nits and 1 PR-body defect. Every verdict below is backed by a code citation or a
measurement, not prose.

⚠️ Major - PR body (fixed before publishing, no source change)

  • AGREE - the Related: #112769 line was inside the leading HTML comment, so it would not have
    rendered. Moved out.
  • AGREE - the description claimed the change also fixes previously-aborting reads at depth 2.
    Measured, the depth-2 cell (arr.t.a.size) returns 20000 0 on unfixed master and only aborts on
    the 3a-only arm - so depth 2 is a regression the second hunk prevents, never a pre-existing
    abort this PR fixes. Depth 3 is genuinely repaired (rc=134 -> 20000 0). Claim narrowed to
    depth 3.

💡 Nits - all DISAGREE, with evidence

  • No test for a DEFAULT/MATERIALIZED re-added member, whose lookup hasDefault now resolves
    through the snapshot. DISAGREE: the change only replaces the fallback name (previously the group
    name arr for a remapped pair) with the real metadata parent, leaving the first-priority
    getDefault(column.name) check untouched - more correct in both directions. A defaulted member also
    never reaches the offsets branch, because hasDefault short-circuits before it.
  • local_filesystem_read_prefetch = 0 and max_threads = 1 are pinned in every test query. DISAGREE:
    both are measured non-preconditions, so the pins remove noise rather than coverage. The runner
    randomizes max_block_size only over [8000, 100000] and does not randomize
    preferred_block_size_bytes, so the test's explicit settings survive randomization and the
    continuation condition cannot be neutered.
  • The .size0 subcolumn of a missing member is not in the new test. DISAGREE: it is already
    asserted by 03742_test_flattened_crash ("size0 and parent"), which this PR keeps byte-identical,
    and the Compact reader path that special-cases it measured identical before and after.

Independently verified while reviewing

  • The first hunk contributes a subcolumn's member name and member storage type, never the
    subcolumn's own name, so it does not rebuild the invalid Nested type that 16d7bab8a3e26ea
    removed; the de-dup guard makes a member + subcolumn co-request idempotent.
  • Nested::collect's 11 call sites are provably inert, not merely untouched by tests: every one
    passes a list built without subcolumn pairs (format headers filtered by name prefix,
    getAllPhysical(), getColumns() without .withSubcolumns()), so the new branch cannot fire there.
  • The second hunk is necessary from the source alone: getBaseTypeOfArray stops descending on any
    tuple-element name that does not resolve, so a remapped pair makes the built column and the
    declared element type disagree - the exact shape 03742 exists to catch.
  • The null-snapshot fallback restores pre-change behavior exactly; fillMissingColumns has only two
    callers and the Memory-engine one is the null case.
  • Comment budget: 49 added code lines vs 11 comment lines in src/, each block a local invariant.

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One clickhouse local script, no runner, no concurrency, no randomization: Wide MergeTree, share_nested_offsets = 1, index_granularity = 8192 with index_granularity_bytes = 0, 20000 rows, DROP + ADD of arr.nested, then read arr.nested.b beside arr.id and arr.s at max_block_size 8192 / 8000 / 1000. The realized mark layout is asserted from system.parts (3 marks) rather than assumed, since adaptive granularity makes index_granularity only a row-count maximum.
b Root cause explained? Yes. MergeTreeReaderWide::readRows keys the substreams cache by getNameInStorage, so a stream shared by a Nested group is read once per call. getSubcolumnsOfNested skipped subcolumn entries, so a member requested only as a subcolumn never reached the group, Nested::convertToSubcolumns skipped its conditional remap, and the subcolumn kept a different cache bucket from its siblings. The shared offsets stream was then read twice per call; on a continuation call the mark seek is suppressed (correctly, since it would rewind to the granule start), so the second reader short-reads. Zero residue gives an empty column that is nulled and refilled with defaults (wrong values); a partial residue survives beside full-length columns and trips checkInternalConsistency.
c Fix matches root cause? Yes. Both hunks make a consumer agree with the remap at its own layer: the cache-bucket key stops disagreeing with the shared stream, and fillMissingColumns stops deriving a type from accessors the remap rewrites. No widened bounds, no no-random-* tag, no reduced dataset, no swallowed exception, no relaxed type check, and no guard at the failure site.
d Test intent preserved / new tests added? Yes. New stateless test 04770_nested_subcolumn_shared_offsets_continuation plus a new NestedUtils gtest for the grouping, which SQL cannot observe directly. The existing 03742_test_flattened_crash is untouched and passes byte-identically against its current .reference; it is the second hunk's acceptance bar, so weakening it was not an option.
e Both directions demonstrated? Yes, on Build-ID-verified binaries. Unfixed: max_block_size 8192 and 8000 abort, 1000 returns 11000 10000 10000 9000 where clean is 20000 0 0 0. Fixed: all four cells clean. Three mutation arms: reverting hunk 1 reddens the new test with the original assertion; reverting hunk 2 reproduces Bad cast from type DB::ColumnTuple to DB::ColumnVector<double> and There is no subcolumn size in type Tuple(a String, b Float64); forcing the new resolver's no-snapshot fallback reproduces the pre-fix arm byte-identically across every measured cell. The unfixed control is a separate build at the same base commit.
f Fix is general across code paths? Yes. Fixed at the two sources rather than at the failure site. Measured: Nested::collect (which shares the changed helper and shapes part_columns for every MergeTree read), Log engine, Compact parts, OPTIMIZE FINAL and a mutation, Memory engine, and an object-storage disk. hasDefault, the one other consumer in the same function reading a remap-sensitive accessor for a metadata purpose, now goes through the same resolver.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Nullable, LowCardinality, LowCardinality(Nullable), Nullable(Tuple), Tuple, Map and Array(Array) member value types; subcolumn paths at depth 1, 2 and 3; max_block_size 100000 / 8192 / 8000 / 1000, covering both an exact-multiple and a partial final granule; fixtures of 16384 and 20000 rows. Pre-existing ILLEGAL_COLUMN cells for genuinely absent subcolumns were checked to return the same message rather than silently changing.
h Backward compatible? Yes. No setting default change, so no SettingsChangesHistory.cpp entry; no serialization or on-disk format change; no new experimental gate. The new resolver falls back to today's behavior when there is no storage snapshot, which the third mutation arm confirms is byte-identical rather than merely believed.
i Invariants and contracts preserved? Yes. The Nested-group contribution uses the member name and the member's storage type, never the subcolumn's own name, so the invalid-Nested-type invariant that the conditional remap exists to protect still holds; its regression test passes. The contribution is de-duped, so requesting a member and its subcolumn together cannot produce a duplicate element. num_dimensions and the collected offsets columns are deliberately not rebased, because they must keep matching the reader's stream names, which the remap normalizes on purpose. No lock or concurrency contract is touched.

Session id: cron:clickhouse-impl-slot-45:20260804-004100

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @alesapin, could you review this? Under share_nested_offsets a Nested member requested only as a subcolumn never reached its group, so it got a different substreams-cache bucket from its siblings and the one shared offsets stream was read twice per readRows; on a continuation call the mark seek is correctly suppressed, so the second reader short-reads and the present siblings come back with right lengths but wrong values.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai isn't this fix the same as in #112997 ?

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

No, they are different defects, and the two diffs have no file in common. #112997 changes prefetch
stream ownership in MergeTreeReaderWide. This one changes the substreams-cache bucket key in
Nested::convertToSubcolumns, plus the fillMissingColumns type computation that #112769 left
unfixed.

What separates them is local_filesystem_read_prefetch = 0. Every write to prefetched_streams is
reached only through prefetchForAllColumns, which returns early at MergeTreeReaderWide.cpp:124
when prefetch is off, so the map stays empty there and #112997 cannot change behaviour. Measuring
the #112997 build against a pristine master build at the same commit, every prefetch = 0 cell is
byte-identical between them and still wrong on both: 16000 mismatched rows at
max_block_size = 1000, 32000 at 8000. The prefetch = 1 cells are where #112997 differs, and there
it is strictly better.

On this PR's base 8c925c5, with prefetch = 0 throughout, the defect fixed here aborts at
max_block_size = 8192 and returns silent wrong results at 1000 (11000 10000 10000 9000 instead
of 20000 0 0 0).

The split was agreed on #112997 itself: the automated reviewer re-derived this mechanism from that
diff and filed it there (discussion_r3699237053). I conceded the mechanism, declined to widen that
PR, and narrowed its changelog entry instead. This is the follow-up that thread promised.

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

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [99c9554]

Summary: ✅


AI Review

Summary

This PR fixes a real Nested-subcolumn read bug by making subcolumn-only requests participate in the Nested remap and by deriving missing-column synthesis from the storage metadata shape instead of the remapped pair. After reviewing the current diff and full code paths, reading the existing PR discussion and inline thread, and checking the all-green CI run, I did not find a remaining correctness, compatibility, or coverage issue in the patch.

Final Verdict

✅ No findings. No new inline review comments to post.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.80% -0.10%
Branches 78.80% 78.70% -0.10%

Changed lines: Changed C/C++ lines covered: 48/49 (97.96%) · 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 4, 2026
@PedroTadim PedroTadim self-assigned this Aug 4, 2026
GTEST_TEST(NestedUtils, subcolumnOfNestedMember)
{
DataTypePtr uint_type = std::make_shared<DataTypeUInt32>();
DataTypePtr array_type = std::make_shared<DataTypeArray>(uint_type);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai remove this gtest, I prefer the SQL test.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Removed, in 99c9554.

Before deleting it I checked what it was pinning, since the PR description claimed reverting either
half reddens a test. It was covering only the getSubcolumnsOfNested change. Reverting just that
hunk and keeping everything else, 04770 alone aborts on column->size() == num_rows, so the SQL
test carries that half on its own and no regression power is lost.

The same commit also fixes a Map path in getBaseTypeOfArray, which the AST fuzzer found on this
branch by wrapping the test's own query in materialize. The descent walked Array and Tuple but not
Map, so arr.m.keys on a missing member was synthesized as
Array(Array(Map(String, UInt64))) under a declared Array(Array(String)). The old assertions used
sum(length(...)), which passes on a wrongly typed column, so they are now wrapped in
materialize and a Map reached through a Tuple element is covered too.

getBaseTypeOfArray descended only Array and Tuple, so a path through a Map
stopped at the Map itself and never consumed its keys/values element. For a
missing Nested member `arr.m Array(Map(String, UInt64))` the synthesized
`arr.m.keys` column therefore carried Array(Array(Map(String, UInt64))) under a
declared Array(Array(String)). A length aggregate does not force the check, so
the mismatch stayed latent until an action re-materialized the column, where
ExpressionActions reports the declared and actual types disagree. The AST fuzzer
found it by wrapping the new test's own query in materialize.

Map keys and values are already enumerated as Substream::TupleElement by
DataTypeMap::getSerialization, so they belong on the tuple_elements path like any
other tuple element; teaching the descent to walk into the Map's nested tuple is
all that is needed. getBaseTypeOfArray has a single caller, the missing-column
synthesis branch in fillMissingColumns.

The test asserted these paths with sum(length(...)) alone, which passes on a
wrongly typed column. Every wrapped path is now asserted through materialize as
well, and a Map reached through a Tuple element of the member is covered.

Remove the NestedUtils gtest per review request: the SQL test alone reddens for
the getSubcolumnsOfNested change, verified by reverting only that hunk
(04770 aborts on 'column->size() == num_rows'), so no regression power is lost.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 99c9554

CI is fully finished on this head with zero failures to own: 174 check-runs, 157 success,
17 skipped, 0 failed. Both aggregators, Config Workflow and Finish Workflow, completed
successfully.

The two AST fuzzer (amd_debug, targeted*) checks that were red on the previous head
678981e1511d21a are green here, so that PR-caused failure is resolved by this head.

Session id: cron:our-pr-ci-monitor:20260804-190000

alexey-milovidov added a commit to rorylshanks/ClickHouse that referenced this pull request Aug 11, 2026
Systematic stateless tests sweeping {column spelling} x {wrapper evolution:
Nullable, Tuple, Dynamic, widening, LowCardinality} x {part state after the
ALTER: compact/wide unrewritten, rewritten, no shared offsets, mixed parts,
multi-member} x {projection shape of the read}. A part written before a
MODIFY COLUMN keeps its own older type until the mutation rewrites it, and
bugs in this family are order- and state-sensitive: the regression fixed by
ClickHouse#113925 lived in exactly one such cell (unrewritten part x dotted Nested
member x subcolumn-first read) that no hand-written test covered. Split
into four test files so no single one risks a timeout.

The suite passes on a binary with ClickHouse#113925 applied and the first witness
cell reproduces the abort (STID 4256-3fc1) on current master without it,
so this must be merged after ClickHouse#113925.

Related: ClickHouse#113925
Related: ClickHouse#113225

Co-Authored-By: Claude Fable 5 <[email protected]>
bacek pushed a commit to bacek/ClickHouse that referenced this pull request Aug 12, 2026
A part written before an ALTER keeps its own older type (or misses the
column) until the mutation rewrites it. Tests pin their results with
mutations_sync = 2, so the corpus systematically avoids the pending-
mutation state, and background mutations normally close the window in
milliseconds - which is why bugs living in that state (e.g. the
regression fixed by ClickHouse#113925, which the full pre-merge CI of ClickHouse#113225
missed) reach master untested.

The new failpoint mutate_task_random_sleep_in_prepare sleeps a random
0-3 s in MutateTask::prepare, covering plain, replicated and shared
MergeTree mutations. The stress test enables it right after the smoke
check (never in upgrade check: the old binary may not know it) and
disables it in prepare_for_hung_check, next to stopping the thread
fuzzer, so pending mutations drain at full speed before the hung check.
Disabling a registered failpoint that was never enabled is a no-op.
With the failpoint on, every test that ALTERs without waiting reads
parts the mutation has not rewritten yet, under the stress runner's
random settings and the server-side AST fuzzer's query mutations.

Measured on a RelWithDebInfo build: a mutations_sync = 2 UPDATE takes
0.12 s with the failpoint off and 0.65-1.67 s with it on.

Related: ClickHouse#113925
Related: ClickHouse#113225

Co-Authored-By: Claude Fable 5 <[email protected]>
alexey-milovidov added a commit to ai-mountain/ClickHouse that referenced this pull request Aug 18, 2026
…umns

The type-directed enumerateStreams walk in collectOffsetsColumns pairs
each available column's declared type with its data. When an entry's type
was resolved from the table's metadata while the column was read from a
data part with an older type (the mixed type provenance behind ClickHouse#113925),
the walk casts the column to the wrong class at the first diverging
wrapper: in debug and sanitizer builds that aborted with a bare
'Bad cast from type A to B' naming no column, and in release builds
assert_cast does not check at all, so the walk silently misbehaved on
memory-unsafe reinterpretation.

The new check descends exactly the wrapper levels whose serializations
assert_cast the column (Array, Nullable, Tuple, Map, and class-only
Dynamic, Variant, Object), accepts every leaf it does not know (leaf
divergence such as a part storing UInt32 for a column widened to UInt64
is legitimate), and reports a LOGICAL_ERROR naming the column, the
declared type and the column structure. Debug builds get a one-frame
diagnosis instead of a cross-file hunt; release builds now fail close
instead of walking mismatched memory.

Related: ClickHouse#113925
Related: ClickHouse#113225
Related: ClickHouse#113891

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

Stress tests fleet-wide: Logical error: 'column->size() == num_rows' reading a re-added Nested member beside present siblings (test 04756)

4 participants