Skip to content

Check column structure against the declared type in collectOffsetsColumns - #114087

Merged
alexey-milovidov merged 16 commits into
masterfrom
nested-offsets-type-check
Aug 18, 2026
Merged

alexey-milovidov merged 16 commits into
masterfrom
nested-offsets-type-check

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 10, 2026 •

Copy link
Copy Markdown
Member

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

Changelog category (leave one):

  • Improvement

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

When a column's declared type and its data diverge during a MergeTree read (mixed type provenance, e.g. after an ALTER TABLE ... MODIFY COLUMN whose mutation has not finished), the server now reports a clear exception naming the column and both structures, instead of an unchecked cast: debug and sanitizer builds previously aborted with a bare Bad cast from type A to B naming no column, and release builds walked mismatched memory silently.

Description

The type-directed enumerateStreams walk in collectOffsetsColumns (src/Interpreters/inplaceBlockConversions.cpp) 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 #113925 - the walk assert_casts the column to the wrong class at the first diverging wrapper. In debug/sanitizer builds that is an abort whose message names two column classes and no column (the crash-classifier issue #113891, STID 4256-3fc1, took a cross-file hunt to attribute); in release builds assert_cast does not check at all, so the walk misbehaves on memory-unsafe reinterpretation.

The new columnMatchesTypeStructure check runs right before the walk, only on the missing-columns path where the walk already happens. It descends exactly the levels whose serializations pair the declared type's structure with the column's:

  • Array, Nullable, Tuple, Map - the wrappers whose serializations assert_cast the column;
  • Variant - SerializationVariant::enumerateStreams walks every alternative declared by the type and pairs it with the column's variant of the same global discriminator, so the alternative list has to match in length and element-wise;
  • typed paths of Object - SerializationObject::enumerateStreams walks every typed path declared by the type and looks it up in the column, so the typed paths have to match by name and structure. Dynamic paths and shared data are taken from the column itself and need no check;
  • ColumnReplicated is unwrapped.

Dynamic is checked by class only, because its enumerateStreams takes both the type and the column of its variant from the column itself (column_dynamic->getVariantInfo().variant_type), so the two cannot diverge. Every leaf the check does not know is accepted - leaf divergence, such as a part storing UInt32 for a column widened to UInt64, is legitimate. Because the checked structure mirrors exactly what the enumerateStreams implementations themselves assert, the check cannot fire on any pairing that debug CI does not already abort on (or, for Object, fail with a raw typed-path lookup) - it only converts that failure into a diagnosable exception and closes the release-build hole.

With the #113925 reproducer on a RelWithDebInfo build of master before that fix, the witness query fails with:

Code: 49. DB::Exception: Column `arr.n` is listed with type Array(Nullable(String)) among available columns, but its data has
incompatible structure Array(size = 1, UInt64(size = 1), String(size = 2)). It is likely that a type resolved from the table's
metadata was combined with a column read from a data part with an older type: (while reading from part .../all_1_1_0/ ...)

instead of silent unchecked-cast behavior. #113925 (which fixes the type selection) has since merged and is included here, so this check now guards the invariant against future regressions of the same family.

Validation. Witness reproduced as above on a local RelWithDebInfo build. False-positive sweep: all 381 stateless tests matching nested/subcolumn run against that binary - 294 passed, 87 failed for documented bare-server environmental reasons (no Keeper, no clusters, no protoc, no /var/lib/clickhouse), and the check's message appears zero times in the whole run. After the Variant/Object extension, all 826 stateless .sql tests matching variant/dynamic/json/nested/subcolumn/object were run again - the check's message and Bad cast both appear zero times - plus a targeted check that reads old parts through newly added Variant, JSON, Dynamic, Tuple, Map and Nested columns and through unfinished ALTER TABLE ... MODIFY COLUMN mutations of Variant and JSON. The Memory-engine caller of fillMissingColumns always casts columns to the requested types first (tryGetColumnFromBlock), so it cannot trip the check either.

🤖 Generated with Claude Code

Version info

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

…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 #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: #113925
Related: #113225
Related: #113891

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

clickhouse-gh Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [09aa43f]

Summary: ✅


AI Review

Summary

This PR adds a structural preflight check in collectOffsetsColumns so mixed-provenance MergeTree reads fail with a targeted exception instead of reaching unchecked casts during stream enumeration. I reviewed the current PR head together with all prior discussion and do not see a remaining correctness issue: the previously reported Variant, typed Object, QBit, ColumnSparse, and LowCardinality gaps are closed in the current code, and the committed tests are consistent with the intended behavior.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.80% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 47/58 (81.03%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 09aa43ffa with master 2409fdca3 (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
Binary Master PR Δ
programs/clickhouse-stripped 694.46 MiB 691.44 MiB -3.01 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

… too

`SerializationVariant::enumerateStreams` walks every alternative declared by
the type and pairs it with the column's variant of the same global
discriminator, and `SerializationObject::enumerateStreams` does the same for
every typed path declared by the type. Treating both as class-only therefore
left the hole open one frame deeper: a part carrying an older alternative set
or an older typed-path shape passed the guard and still reached an unchecked
nested `assert_cast`, or failed in the raw typed-path lookup with no
indication of the column.

`columnMatchesTypeStructure` now validates both recursively, mirroring what
`ColumnVariant::structureEquals` and `ColumnObject::structureEquals` check
statically: the alternative list has to match in length and element-wise by
global discriminator, and the typed paths have to match by name and
structure. `Dynamic` stays class-only, because its `enumerateStreams` takes
both the type and the column of its variant from the column itself, so the
two cannot diverge.

False-positive sweep: all 826 stateless `.sql` tests matching
`variant`/`dynamic`/`json`/`nested`/`subcolumn`/`object` run against a local
`RelWithDebInfo` build with this change - the guard's message and `Bad cast`
both appear zero times - plus a targeted check that reads old parts through
newly added `Variant`, `JSON`, `Dynamic`, `Tuple`, `Map` and `Nested` columns
and through unfinished `ALTER TABLE ... MODIFY COLUMN` mutations of `Variant`
and `JSON`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI triage for commit 8c6330c — all four failures are unrelated to this change, which touches only src/Interpreters/inplaceBlockConversions.cpp:

@groeneai, if #113926 is not the right fix for STID 2169-17fd, please take a look at that leak: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114087&sha=8c6330c031f79ee3d8d5bad616369e842f1fd8b6&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29

@groeneai

Copy link
Copy Markdown
Collaborator

Yes, #113926 is the right fix for STID 2169-17fd.

I reproduced this arm on a master ASAN build and the stack matches the CI report frame for frame: ArenaAllocator.h:89 -> PODArray.h:499 -> AggregateFunctionGroupArray.cpp:250 -> IAggregateFunction.h:218 -> AggregateFunctionForEach.h:258. The leaked buffer is allocated by the migration merge inside ensureAggregateData itself: it grows the new element's PODArray past MixedArenaAllocator's 4096 byte threshold, so the buffer comes from the real heap and not the arena. The next regrow turns that array into old_state, the pointer swap abandons it, and destroyImpl walks only array_of_aggregate_datas. The average leaked object in the report is 5268 bytes, which is the same above-threshold class.

The fix destroys every old_state element after the swap through nested_func->destroy(), so it covers any nested function rather than just quantilesExact. Control on master: the same allocation with no regrow leaks nothing, which confirms that groupArray's destroy() frees exactly this block. -Distinct and -OrFill above the frame are only callers and do not change the path.

Nothing extra is needed for this one.

alexey-milovidov and others added 2 commits August 11, 2026 18:13
`SerializationQBit::enumerateStreams` does an unchecked `assert_cast` of
both the type to `DataTypeQBit` and the column to `ColumnQBit` before
descending into the nested tuple, so `columnMatchesTypeStructure` must
not let `QBit` fall through to the unconditional leaf case. Recurse into
`ColumnQBit::getTuple` vs `DataTypeQBit::getNestedType`, mirroring the
pairing done by the serialization.

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

Copy link
Copy Markdown
Member Author

🕵 CI triage for commit 173112c — all four failures are unrelated to this change (the PR touches only src/Interpreters/inplaceBlockConversions.cpp), and each has an open tracker:

The branch has been updated with the latest master and the AI-review blocker (missing QBit branch in columnMatchesTypeStructure) is fixed in e38ab7e.

alexey-milovidov and others added 2 commits August 12, 2026 13:22
…arse is legitimate

The stress test (arm_tsan) on this PR caught a false positive of the new check
(STID: 2459-4106): a column of type `Tuple(Nullable(Int32))` whose element is
stored sparse was rejected, because the check paired the `Nullable` type with a
`ColumnSparse`. The serialization used for the walk is built from the column's
own serialization info, so `SerializationSparse::enumerateStreams` pairs the
same type with the sparse column's values column - a sparse column at any
nesting level is a legitimate pairing and must be unwrapped, like
`ColumnReplicated`.

Reproduced locally with `nullable_serialization_version = 'allow_sparse'` and a
mostly-NULL `Tuple(Nullable(Int32))` element read together with a column
missing from the part; added as a stateless test.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114087&sha=e38ab7e6ac7cf673f8e2102a49c7ac58e74c9cd0&name_0=PR&name_1=Stress%20test%20(arm_tsan)
PR: #114087

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

Copy link
Copy Markdown
Member Author

🕵 CI triage for commit e38ab7e — one failure was a real false positive of the new check (now fixed), two are unrelated with open trackers:

Also merged master (commit 5eaa004).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI triage for commit 3783f80 — all three failures are unrelated to this change (the PR touches only src/Interpreters/inplaceBlockConversions.cpp plus its test):

  • AST fuzzer (amd_debug, targeted) and (targeted, old_compatibility) — Logical error: Not-ready Set is passed as the second argument for function 'in' / 'globalNotIn' (STID: 0250-4e52): the long-standing known issue Logical error: Not-ready Set is passed as the second argument for function 'A (STID: 0250-41a5) #107619.
  • BuzzHouse (amd_tsan) — Fuzzer exit code is 143: the job hit its 18000 s timeout and the fuzzer was killed with SIGTERM. There is no Logical error or sanitizer report in the log; two fuzzer-generated queries over merge(REGEXP('^system$'), '^constraints$') FINAL ... INTO OUTFILE ... TRUNCATE were stuck for ~3260 s when the timeout fired. This PR only affects the missing-column fill path of MergeTree reads and cannot cause a hang in system.constraints scans. BuzzHouse (amd_tsan) fails on unrelated PRs almost daily with distinct fuzzer-found problems.

@groeneai, investigate the BuzzHouse hang: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114087&sha=3783f809a92ab46f114f112759fecef3788780c7&name_0=PR&name_1=BuzzHouse%20%28amd_tsan%29 (job log: https://s3.amazonaws.com/clickhouse-test-reports/PRs/114087/3783f809a92ab46f114f112759fecef3788780c7/buzzhouse_amd_tsan/job.log — hung SELECT count() FROM merge(REGEXP('^system$'), '^constraints$') FINAL WHERE ... INTO OUTFILE ... TRUNCATE) and provide a fix in a separate PR. If a fix is already in progress, link it here.

I merged the current master into the branch to freshen the base for the next CI run.

@groeneai

Copy link
Copy Markdown
Collaborator

Two corrections to the BuzzHouse (amd_tsan) reading, then the defect I found.

The fuzz phase did not hang. Fuzzer exit code is 143 is the 60m budget expiring on schedule: run-fuzzer.sh runs the client under timeout --verbose --signal TERM --preserve-status "${remaining_seconds}s", the pass started at 16:08:57 with fuzz_budget_seconds=3600 and the TERM landed at 17:08:57, exactly 3600 s. 143 = 128+15. The server answered the SELECT 1 liveness probe immediately afterwards.

The 18000 s job timeout was spent in teardown, not in fuzzing. The last log line is 17:08:58, which is the first statement of stop_server (the system.processes dump). The next line is the 21:06:40 job timeout. That is 14262 s of silence after teardown began, against 3600 s of fuzzing.

The merge(REGEXP) / FINAL shape is not the discriminator. Of the two long-running queries, one has no merge() in it at all:

3261.492299  SELECT count() FROM "system"."constraints" WHERE "database" = 'd2' AND "table" = 't18' INTO OUTFILE ...
3261.413096  SELECT count() IGNORE NULLS FROM merge(REGEXP('^system$'), '^constraints$') FINAL WHERE ...

The plain scan is the older of the two, by 0.08 s. The common factor is system.constraints, not merge(), so this is not the ReadFromMerge plan-time cancellation family that #113415 addressed.

The defect: a system.constraints scan has no cancellation point. In ConstraintsSource::generate() (src/Storages/System/StorageSystemConstraints.cpp):

  • applyFilters builds block_to_filter with the database column only, so the table predicate is not pushed down, and the source calls tables_it.table() and getInMemoryMetadataPtr() for every table of each matching database;
  • a table without constraints returns early without incrementing rows_count, so the while (rows_count < max_block_size) walk can cross the whole catalog without ever emitting a block;
  • there is no checkTimeLimit() or isCancelled() call anywhere in the function, and ISource::work() only observes cancellation between generate() calls.

The whole catalog walk is therefore uninterruptible: neither a killed client nor an expired time limit can stop it mid-walk. Four sibling system tables already call query_status->checkTimeLimit() inside their loops (StorageSystemReplicas, StorageSystemDatabaseReplicas, StorageSystemZooKeeper, StorageSystemRemoteDataPaths), so the pattern for the fix is established.

This is log plus source analysis. I have not reproduced it yet, so I am not opening a PR on a mechanism I cannot demonstrate. I am building the repro (many tables in one database, then cancel a system.constraints scan), and I will open the fix PR with the cancellation check plus the table pushdown and link it here.

The Not-ready Set failures are the known #107619, agreed.

@groeneai

Copy link
Copy Markdown
Collaborator

First, a correction to my earlier comment here: the ConstraintsSource::generate() catalog-walk mechanism I described is wrong, and so is "the common factor is system.constraints". Query 2's database literal matches no database, so the source gets an empty column and generate() returns an empty chunk without entering the loop (StorageSystemConstraints.cpp:162-165). No PR was opened on it.

Your change is exonerated at code level: the same signature occurs on #107292 4289b13b and #114131 988ab5e2, whose trees contain 0 occurrences of columnMatchesTypeStructure, and src/Storages/System/ never references inplaceBlockConversions.

Where the 18000 s went: the fuzz pass ended exactly on its 3600 s budget, so exit 143 is a completed budget, not a hang. The remaining 14262 s is stop_server blocked on its own first statement, the unbounded clickhouse-client --query "select elapsed, query from system.processes" at run-fuzzer.sh:109, before it reaches clickhouse stop. query-fuzzer-tweaks-users.xml gives that client ast_fuzzer_runs=5 with ast_fuzzer_any_query=true, and the mutated follow-ups run as finish callbacks in BlockIO::onFinish, which TCPHandler calls before sendEndOfStream. The client prints its rows and keeps waiting, since a Data packet does not end the receive loop.

Controls: in all five affected runs the rows print and + clickhouse stop never appears, while in a run where that client failed fast with Code: 210 the clickhouse stop line follows in the same second. The liveness probe also answered SELECT 1 instantly one second earlier, so the server was not degraded.

It is recurring and author-independent. Of 223 BuzzHouse* error runs in 90 days, 5 stalled there (this one, #107292, #114106, #114131, and my #114405) across five authors and three build variants; 211 reached the same dump and finished normally. Two of the five had no long-running query at all, so a stuck query is neither necessary nor sufficient.

The fix is already in progress and it is yours: #113248 adds --ast_fuzzer_runs=0 to exactly this command in 0c772a54, and is not on master yet, so this build predates it. I am not opening a separate PR. My #111934 bounds the parent wait for a different teardown mode and does not cover this call.

Not explained: why five mutated system.processes queries would run that long. These runs are not replayable, as the seed is in fuzz.json, one of the artifacts lost with status.tsv when the wait never returns.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI triage for commit c6a7348 — both failures are unrelated to this change (the PR touches only src/Interpreters/inplaceBlockConversions.cpp plus its stateless test), and each has an open tracker:

The AI Review on c6a7348 reported ✅ no new findings, and there are no unresolved review threads.

I merged the current master into the branch (commit 063d3f7, clean merge), rebuilt the affected target incrementally (clean) and re-verified 04869_sparse_tuple_element_missing_column_read locally (142 141 0).

The test did not preserve an old part through ALTER, so it expected a `LOGICAL_ERROR` from a query that correctly succeeds. Remove it while retaining the `LowCardinality` structure validation in `columnMatchesTypeStructure`.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114087&sha=aaf7d9010609fc7572f09e38391d84554e0e0787&name_0=PR&name_1=Fast%20test
@alexey-milovidov alexey-milovidov self-assigned this Aug 18, 2026
if (res_columns[i]->isSparse())
continue;

if (!columnMatchesTypeStructure(*res_columns[i], *available_column->type))

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok. So this is just a diagnostic improvement.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

In debug and sanitizer builds, yes. assert_cast already aborted there, and the new check raises LOGICAL_ERROR, which also aborts (Common/Exception.cpp:112-115), so the only thing that changes is that the message names the column and both structures.

In release builds it is more than diagnostics. assert_cast compiles to a bare static_cast (Common/assert_cast.h:45), so nothing was checked and the walk went on to read ColumnArray::getOffsetsPtr() off a column that is not a ColumnArray (SerializationArray.cpp:280-281). The check throws before the walk starts, so that reinterpretation is now a normal exception.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 18, 2026
Merged via the queue into master with commit 30ce90e Aug 18, 2026
182 checks passed
@alexey-milovidov
alexey-milovidov deleted the nested-offsets-type-check branch August 18, 2026 03:24
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements 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