Skip to content

Fix reading a re-added Nested subcolumn with its parent column - #112769

Merged
PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-nested-subcolumn-refill-after-drop-add
Aug 1, 2026
Merged

PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-nested-subcolumn-refill-after-drop-add

Conversation

@groeneai

@groeneai groeneai commented Jul 31, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #112668

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

Fixes a wrongly typed read of a Nested element subcolumn whose column was dropped and re-added. Selecting such a subcolumn together with its own parent column returned the whole element in the subcolumn's slot while the block still declared the element type, which produced arbitrary values in release builds and a logical error in debug and sanitizer builds.

Description

SELECT of a Nested element subcolumn together with its own parent column, after the column was
DROPped and re-ADDed, returned a column of the wrong type:

CREATE TABLE t (`id` UInt64, `arr.id` Array(UInt64), `arr.nested` Array(Tuple(a String, b Float64)))
ENGINE = MergeTree ORDER BY (id);
INSERT INTO t VALUES (1, [1], [('y', 2.5)]);
ALTER TABLE t DROP COLUMN `arr.nested`;
ALTER TABLE t ADD COLUMN `arr.nested` Array(Tuple(a String, b Float64));
SELECT arr.nested.b, arr.nested FROM t;   -- expected [0] [('',0)]

On a release build this returned a different value on every run while the parent
column read correctly, so nothing indicated the subcolumn value was fabricated. Debug and sanitizer
builds raised Logical error: 'Bad cast from type DB::ColumnTuple to DB::ColumnVector<double>'.

Root cause: fillMissingColumns decides between deferring to evaluateMissingDefaults and synthesizing a default from a Nested sibling's shared
offsets. IMergeTreeReader first runs its column lists through Nested::convertToSubcolumns, which
moves the subcolumn delimiter, so arr.nested.b becomes {name_in_storage = "arr", subcolumn = "nested.b"}. The deferral compared that name_in_storage against lists keyed by full name, never
matched, and the offsets branch then produced the whole Tuple under a declared element type.

The fix resolves the requested column through the storage snapshot, which is authoritative about
where the subcolumn delimiter belongs, and matches the resolved parent's full name against the
availability sets. Three consumers were observed reading the wrongly typed column (output
formatting, merging via ORDER BY, and function execution), and all three are repaired by this
single change at the point where the block is built. Reads that were already correct are covered as
controls in the test.

Found by the AST fuzzer, which mutated the existing 03742_test_flattened_crash test to read the
element subcolumn instead of the whole column (AST fuzzer (amd_debug), STID 2508-368d):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112668&sha=3f7020cf4114402a81c9d3dd6e7bef755802e34b&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%29

Version info

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

A SELECT that reads a Nested element subcolumn together with its own parent
column, after that column was dropped and re-added, put the whole element in
the subcolumn's slot while the block still declared the element type.

fillMissingColumns can satisfy a column absent from the part either by
deferring to evaluateMissingDefaults, which derives a subcolumn from its
parent, or by synthesizing a default from a Nested sibling's shared offsets.
IMergeTreeReader first runs its column lists through
Nested::convertToSubcolumns, which moves the subcolumn delimiter, so
`arr.nested.b` becomes {name_in_storage = "arr", subcolumn = "nested.b"}. The
deferral compared that name_in_storage against lists keyed by full name, so it
never matched and the offsets branch produced a Tuple under a declared element
type.

Resolve the requested column through the storage snapshot, which is
authoritative about where the subcolumn delimiter belongs, require the resolved
pair to be a subcolumn, and match its parent's full name against both
availability sets. Requiring isSubcolumn on the resolved pair is what keeps the
parent's own slot on the offsets branch, where it belongs.

In release builds the mistyped column was read through an unchecked
static_cast, so the query returned a different arbitrary value on every run
while the parent column read correctly. Debug and sanitizer builds raised
`Bad cast from type DB::ColumnTuple to DB::ColumnVector<double>`. Any element
type is affected; three consumers were observed reading the mistyped column
(output formatting, merging, and function execution) and all are repaired by
this single change at the point where the block is built.

Extend 03742_test_flattened_crash with the subcolumn shapes: Float64 and String
elements, the ORDER BY form, function execution over the subcolumn, a two-part
case, Wide and Compact arms, and controls for the reads that were already
correct.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Two independent cold reviews of the resulting code (carriers enumerated from source before reading
the author's evidence) plus one adversarial gate pass. 5 findings, all nits, no blockers and no
majors. Verdicts below; each was verified against the code before being recorded.

# Finding Verdict
💡 The commit message omits the CI report URL and the carrier PR URL, which .claude/CLAUDE.md asks for when a report URL is supplied. ⚠️ Agreed in part, and fixed where it matters. The PR body now carries both the canonical report URL and the Related: link. The commit-message half is not fixed: it needs a new commit, and amending is not allowed. Happy to push a metadata-only follow-up commit if you would like the URLs in the history as well.
💡 The new predicate uses withSubcolumns, which also enables dynamic-subcolumn resolution, so a miss falls through to a per-name-split scan. ❌ Dropped. It runs at most once per missing column per read step, never per row, and the producer side that injects the parent (injectRequiredColumns) uses the same option semantics. Narrowing it here would make consumer and producer disagree about dynamic subcolumns, which is the divergence class this change fixes.
💡 The deferral leaves the column null and relies on tryGetSubcolumnFromBlock, which can return null. ❌ Disagreed, pre-existing and unreachable for the new cases. The previous guard deferred into the identical path with the identical contract. That function's only "parent missing" early return cannot fire for a deferred column here, because the guard fires only when the resolved parent name is present in one of the availability sets, which are the names the block carries.
💡 toTypeName, .size0 and .null rows are controls rather than regression detectors. ⚠️ Agreed as a description of the test, no change needed. toTypeName is answered from the declared type, .size0 on a wide part is redirected to the Nested parent's own offsets stream, and .null of Array(Nullable(T)) is not a tuple element. The 6 detector rows and 7 controls are separated explicitly below so this comment does not overstate coverage.
💡 The helper comment could also state that the full column name is unchanged by the delimiter move. ❌ Disagreed. The comment already shows the same full name split two ways in its worked example, and the reasoning is spelled out in the commit message, which is where explanation belongs.

What the two cold passes verified independently, beyond the author's own evidence:

  • The change is not a pure widening. It adds a subcolumn requirement on the metadata-resolved pair,
    so cases the previous guard fired on must still fire. Checked for that guard's original target, a
    .null subcolumn after a metadata-only T to Nullable(T) change: such a column is not an
    Array, so Nested::convertToSubcolumns skips it entirely, the requested pair is unremapped, and
    the new lookup key is identical to the old one. Its regression suite is in tree and untouched.
  • A column whose name collides with another column's subcolumn resolves safely, because
    ColumnsDescription::tryGetColumn searches declared columns before subcolumns, so the declared
    column wins, the predicate declines, and the previous behaviour is kept.
  • Not consulting alter_conversions in the predicate is correct: both availability sets and the
    metadata snapshot are keyed by current names, and the translation to a part's older name belongs
    to the part lookup. injectRequiredColumns resolves in the same order.
  • The strongest argument for this shape, which is not stated in the diff: the code that injects the
    parent column already resolves through the storage snapshot, checks the resolved pair for being a
    subcolumn, and takes its parent's name. This change makes the consumer's deferral test agree with
    the producer's injection test. A disagreement between those two is the whole bug.
  • Test liveness, cross-checked against the author's per-row matrix: reverting only the predicate
    reddens 6 rows with 4 distinct signatures (ColumnTuple to ColumnVector<double>, ColumnTuple
    to ColumnString, DataTypeNumber<double> to DataTypeTuple, and Code: 44 from arraySum),
    covering four different consumers, while 7 must-not-change controls stay byte-identical.
  • No durability or persistence surface: no acknowledged state transition, no on-disk format change
    and no recovery path, so restart behaviour is unaffected. The change only alters how one in-memory
    block column is built during a read.

One row drafted for this test was removed rather than asserted: reading a never-dropped sibling
column beside the re-added subcolumn diverges in about 10% of randomized runs and reproduces at the
same rate on an unmodified master build, so it is a pre-existing defect tracked separately. Asserting
it here would encode existing behaviour as this change's contract and make the test flaky on arrival.

Post-fix release behaviour is inferred from the shared construction site rather than measured; the
pre-fix release symptom was measured on an official release binary.

Session id: cron:clickhouse-review-slot-48:20260731-155920

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Question Answer
a Deterministic repro? Yes. One command, 100% reproducible: the DROP+ADD fixture then SELECT arr.nested.b, arr.nested FROM t gives RC=134 and Bad cast from type DB::ColumnTuple to DB::ColumnVector<double> before the fix, RC=0 and [0] [('',0)] after. The aborting binary's build id in the log was asserted equal to readelf -n on the binary under test.
b Root cause explained? Yes. IMergeTreeReader runs its column lists through Nested::convertToSubcolumns, which moves the subcolumn delimiter, so arr.nested.b becomes {name_in_storage = "arr", subcolumn = "nested.b"}. The deferral in fillMissingColumns compared that name_in_storage against lists keyed by full name, never matched, and the shared-offsets branch produced the whole Tuple under a declared element type. Confirmed with a temporary probe that printed the diverging names, then fully reverted.
c Fix matches root cause? Yes, it repairs the comparison itself: resolve the requested column through StorageSnapshot::tryGetColumn, require the resolved pair to be a subcolumn, and match its parent's full name against both availability sets, which are keyed by full name. No consumer is guarded, no setting disabled, no bound widened. All three observed consumers are repaired by the single change at the construction site.
d Test intent preserved, new tests added? Yes. The existing full-column assertion and its reference line are unchanged; the file gains the subcolumn shapes it lacked. Values are asserted rather than mere absence of an abort, which is required here because the release build does not abort.
e Both directions demonstrated? Yes, per row. Reverting only the guard changed the Build ID and reddened exactly six rows with four distinct signatures (ColumnTuple to ColumnVector<double>, ColumnTuple to ColumnString, DataTypeNumber<double> to DataTypeTuple, and Code: 44 from arraySum), while all seven must-not-change controls stayed byte-identical. Restoring the fix relinked bit-identically to the shipping Build ID, so no mutation residue ships.
f General across code paths? Yes. fillMissingColumns has exactly two callers: the MergeTree reader (affected) and ReadFromMemoryStorageStep, which passes no storage snapshot and is verified unchanged by a Memory-engine control. Both availability sets get identical treatment, and the second one was exercised for real with a pending on-fly mutation plus multi-step prewhere. Wide and Compact parts both reproduce and are both fixed, with part_type asserted. StorageLog and TableFunctionMergeTreeIndex also call Nested::convertToSubcolumns but neither calls fillMissingColumns. A repo-wide search for the same comparison pattern found no other site.
g Generalizes across inputs? Yes, measured. Element wrappers all read correctly and consistently with the parent: Float64, String, Nullable(Float64), LowCardinality(String), LowCardinality(Nullable(String)), a nested Tuple, an Array element, a Map element, and the middle field of a three-element tuple. Container shapes: two-dimensional Array(Array(Tuple)) and the real Nested(...) syntax. Boundaries: array lengths 0, 1 and 3 all follow the sibling's offsets. Non-carriers .null and .size0 are served from the offsets and stay correct. The shipped rows cover both Float64 and String.
h Backward compatible? Yes. No on-disk format change, no serialization version change, no new setting and no changed default, so no SettingsChangesHistory.cpp entry is owed. The only behaviour change is that a read which previously returned a wrongly typed column now returns the correct default; every previously correct shape is a control and all are identical in both arms.
i Invariants and contracts preserved? Yes. The new predicate is pure: no allocation, mutation, locking or ownership transfer, and a missing metadata entry falls through to the previous behaviour instead of asserting. The guard's existing order is kept, so a column with a DEFAULT or MATERIALIZED expression still never reaches it. The block invariant the bug violated, that the declared type matches the runtime column, is restored.

Performance: the predicate runs once per missing column per read step and replaces one name scan with a metadata hash lookup plus the same scan. Same complexity class, no hot loop touched.

Validation: tag-free --test-runs 50 --jobs 8. A back-to-back comparison on the same server gave 32 OK / 18 FAIL for the unmodified test and 39 OK / 11 FAIL for the extended one, with zero output mismatches on the added rows; every failure in both arms is the same pre-existing sandbox condition on the test's original statement, caused by this single-node sandbox lacking a local replica in the randomized parallel_replicas cluster. No tags were added: each run gets its own database, and the two load-bearing settings are pinned per CREATE rather than disabling randomization wholesale.

One row that was drafted for this test was removed after measurement: reading a never-dropped sibling column beside the re-added subcolumn diverges in about 10% of randomized runs, and reproduces at the same rate on an unmodified master build, so it is a pre-existing defect tracked separately rather than something this change should assert.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @Avogar, could you review this? The deferral in fillMissingColumns compared name_in_storage against lists keyed by full column name, but Nested::convertToSubcolumns had already moved the delimiter (arr.nested.b becomes name_in_storage arr), so it never matched and the shared-offsets branch put the whole Tuple in the element subcolumn's slot. It now resolves the parent through the storage snapshot, which is the same way injectRequiredColumns picks the parent to inject.

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

clickhouse-gh Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4ed598c]

Summary: ❌

job_name test_name status info comment
Fast test (arm_darwin) ERROR IGNORED

AI Review

Summary

This PR fixes the original mistyped read when a re-added Nested element subcolumn is selected together with its parent, and the new no-DEFAULT coverage exercises the main affected consumers. I still see one remaining correctness gap: on wide parts, selecting only element subcolumns of a re-added Nested column that has a DEFAULT still goes through the offsets/type-default path instead of evaluating the parent column's DEFAULT. The new DEFAULT regression rows do not cover that layout because their one-row fixtures run as Compact parts under the default wide-part thresholds. Verdict: changes requested.

Findings

❌ Blockers

  • [src/Interpreters/inplaceBlockConversions.cpp:395-404] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/112769#discussion_r3692104734] The DEFAULT case is still wrong on wide parts when the query reads only element subcolumns. IMergeTreeReader::getColumns switches to converted_requested_columns only for wide parts (src/Storages/MergeTree/IMergeTreeReader.h:75), and Nested::convertToSubcolumns rewrites arr.nested.b so its getNameInStorage() becomes arr (src/DataTypes/NestedUtils.cpp:527-543). hasDefault still only probes arr.nested.b and arr, never the real parent arr.nested, while the new isSubcolumnOfAvailableColumn helper only defers when that parent is already present in the availability sets (src/Interpreters/inplaceBlockConversions.cpp:409-427). For SELECT arr.nested.b or SELECT arr.nested.b, arr.nested.a on an old wide part, neither condition holds, so fillMissingColumns still synthesizes the element from shared offsets or the storage-type default instead of evaluating the declared DEFAULT. Suggested fix: resolve the parent through StorageSnapshot in hasDefault too, so converted Nested element subcolumns inherit the parent's DEFAULT even when the parent is not requested. The new DEFAULT regression at tests/queries/0_stateless/03742_test_flattened_crash.sql:111-143 should also force a wide part (min_bytes_for_wide_part = 0 or min_rows_for_wide_part = 0), because with the default thresholds a one-row part is Compact (src/Storages/MergeTree/registerStorageMergeTree.cpp:1354) and never exercises this path.
Final Verdict

❌ Changes requested

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 31, 2026
&& requested_column->isSubcolumn()
&& (available_columns.contains(requested_column->getNameInStorage())
|| additional_available_columns.contains(requested_column->getNameInStorage())))
if (isSubcolumnOfAvailableColumn(storage_snapshot, *requested_column, available_columns, additional_available_columns))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This only fixes the "parent already available" branch. fillMissingColumns still decides whether to leave a slot for evaluateMissingDefaults via hasDefault(storage_snapshot, *requested_column) above, and for a converted Nested element subcolumn that helper still probes arr.nested.b and arr, never the real parent arr.nested.

That means ALTER TABLE ... ADD COLUMN \arr.nested` Array(Tuple(...)) DEFAULT ...is still wrong on old parts: the element subcolumn will be synthesized from sibling offsets here instead of deferring to the parent'sDEFAULT, so arr.nested.breturns the type default rather than the DDL default. Can we resolve the parent throughStorageSnapshot` for the default check as well, and add a regression for that shape?

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.

You are right about the code: for a converted Nested element subcolumn hasDefault really does probe arr.nested.b and arr and never arr.nested, because Nested::convertToSubcolumns moves the delimiter and ColumnsDescription::getDefault only indexes declared columns.

The predicted symptom does not happen, though. I measured that fixture on an unmodified master build and the DDL default wins in every shape but one:

shape master with this change
arr.nested.b [42.5] [42.5]
arr.nested.a ['dflt'] ['dflt']
arr.nested.size0 1 1
arraySum(arr.nested.b) 42.5 42.5
arr.nested [('dflt',42.5)] [('dflt',42.5)]
arr.nested.b, arr.nested Bad cast [42.5] [('dflt',42.5)]

The reason is that injectRequiredColumnsRecursively asks the same default question one layer earlier, on the pre-conversion name, and resolves the parent through StorageSnapshot: MergeTreeBlockReadUtils.cpp:142-149 falls back to getDefault(column_in_storage->getNameInStorage()), which for arr.nested.b is exactly getDefault("arr.nested"). To show that path really runs rather than the offsets branch, I made the default depend on a sibling column, so only an evaluated expression can produce the right answer:

ALTER TABLE t ADD COLUMN `arr.nested` Array(Tuple(a String, b Float64))
    DEFAULT arrayMap(x -> ('sib', toFloat64(id)), `arr.id`);   -- row has id = 7
SELECT arr.nested.b FROM t;   -- master: [7], not the type default [0]

So the hasDefault miss is inert on the reachable paths, and I have not changed it. Resolving the parent there as well would be a reasonable hardening, but with no observable difference it is a separate change rather than part of this one.

The single failing shape is worth having, and it is not a second defect: it aborts with Bad cast from type DB::ColumnTuple to DB::ColumnVector<double>, the same signature this PR fixes, so the DEFAULT variant is another carrier of the same bug. I pushed the regression you asked for in 4ed598c90403bb, covering the element alone, the element beside its parent, the parent alone, the string element, and the sibling-dependent default above. Verified in both directions: the rows pass with the change and the second one aborts once the change to fillMissingColumns is reverted. Tag-free 50 runs with --jobs 8: 50 passed.

I also dropped a toTypeName row I had added earlier. It reads Array(Float64) with and without the change, so it could not witness a ColumnTuple stored under that declared type.

groeneai and others added 3 commits July 31, 2026 18:26
The re-added Nested element subcolumn was read with the wrong type whether or
not the re-added column carried a DEFAULT expression, but the shipped rows only
covered the no-DEFAULT case. On master the DEFAULT variant reaches the same
wrongly typed slot: reading `arr.nested.b` beside `arr.nested` fails with
`Bad cast from type DB::ColumnTuple to DB::ColumnVector<double>` in a debug
build, while every other shape of that fixture (the element alone, the parent
alone, the string element, `arraySum` over the element) already returns the DDL
default correctly.

The last case makes the default expression depend on a sibling column, so a
correct result is only possible when the expression is evaluated with its
dependencies read, rather than the element being synthesized from the shared
offsets. That distinguishes the deferral this change relies on from the offsets
branch, which would yield the type default instead.

Verified in both directions: the five new rows pass on the fixed build
(Build ID 1bad264eb6dea51a81260f6cb265480872baddab) and the second one aborts
with the signature above once the change to `fillMissingColumns` is reverted
(Build ID 9c015e77e67462927ce482def7b7de871cef1a79). Tag-free 50/50 run with
`--jobs 8`: 50 passed, 0 failed.

Co-Authored-By: Claude Fable 5 <[email protected]>
`toTypeName` reports the analyzed argument type without evaluating the column,
so that row reads `Array(Float64)` both before and after the change and cannot
witness the defect, which is a `ColumnTuple` stored under an advertised
`Array(Float64)` type. Measured identical on a pristine build and on the fixed
one. The paired value assertions around it already fail without the change, so
removing the row loses no coverage.

Co-Authored-By: Claude Fable 5 <[email protected]>
The five-line block restated the root cause that the commit message and the PR
description already carry. Only the delimiter-moving detail matters at the call
site, so keep that and drop the rest.

Rebuilt and re-verified after the edit (Build ID
33757c01d12cc60d7c39277b19abe2de83c8e221): the regression test still passes.

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

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 12/12 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4ed598c

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
Fast test (arm_darwin) job-level runner kill at 29.6 min (the Run step ends with a null conclusion, result_pr.json reports status: ERROR with an empty info, results: [] and no artifacts, and CIDB ingests no rows at all). Not the Server died mode: the merged workaround #112267 is already present on this head, so it is not the owner here a fix task is moved to pending (investigating at full effort - fixing-PR link to follow here)

The other 173 checks are green (155 success, 18 skipped) and both aggregators, Config Workflow and Finish Workflow, completed successfully.

Session id: cron:our-pr-ci-monitor:20260801-073000

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