Skip to content

Do not read a subcolumn that a part's column type does not have - #115964

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-wide-part-missing-subcolumn-read
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-wide-part-missing-subcolumn-read

Conversation

@groeneai

@groeneai groeneai commented Aug 23, 2026 •

Copy link
Copy Markdown
Collaborator

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 or an exception when reading a subcolumn that the column's type in a part does not have, which can happen while an ALTER TABLE ... MODIFY COLUMN is not yet materialized. For example, SELECT length(y) over a part where y is still LowCardinality(String) while the table metadata already says String returned wrong lengths in 26.3 and failed with Expected ColumnLowCardinality, got UInt64 in 26.8, and the same inside Array or Nested failed as well.

Description

Related: #115705, where it failed Stress test (arm_tsan); no related open issue found.

On 26.3.33.24, with a pending MODIFY COLUMN y String over a wide LowCardinality(String) part holding 'a' and 'bb', SELECT length(y) returns 0 and 5; on 26.8.10.6 it fails with Code: 44 ... Expected ColumnLowCardinality, got UInt64. Both return 1 and 2 once the mutation is materialized.

length(y) reads the y.size subcolumn because the metadata already says String, while the part's LowCardinality(String) has no size subcolumn. MergeTreeReaderWide read it anyway, parsing dictionary indexes as string lengths; when y was read too, the substreams cache handed that ColumnVector<UInt64> to it. MergeTreeReaderCompact refused scalar columns but passed an array one to the path meant for arrays the part lacks entirely, which then failed reading the present column's offsets.

This moves the presence check into IMergeTreeReader and uses it in both readers. The wide reader decides it once in the constructor, before any stream name is resolved, and all five per-column loops consult it. A request that share_nested_offsets remapped onto a synthesized Nested group is checked against the member the part stores; a member the part lacks entirely still goes to offsets sharing. The compact reader no longer treats a present column as a missing array.

Read-path only; no format or setting change.

The new test covers scalar, Array and Nested columns in wide and compact parts; every case except the already handled compact scalar one fails before the fix. A control asserts via profile events that a subcolumn the part has is still read from its own stream. subcolumn, nested, lowcardinality, alter, tuple, array, quantize and JSON tests were compared against a pre-fix build: every remaining failure fails identically on both.


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

`SELECT length(y)` is answered from the `y.size` subcolumn, and that rewrite is
keyed on the metadata snapshot type. While an `ALTER TABLE ... MODIFY COLUMN y
String` is pending, the snapshot already says `String` so `y.size` is requested,
while the part on disk still holds `LowCardinality(String)`, a type that has no
`size` subcolumn.

`MergeTreeReaderCompact` refuses such a read and lets the existing
missing-subcolumn path derive the value from the converted parent.
`MergeTreeReaderWide` did not. `getSerializationInPart` fell back to the
requested type's default serialization, which is single stream, so
`SerializationStringSize` parsed the dictionary indexes stream as string lengths
into a `ColumnVector<UInt64>`. The substreams cache is shared per storage column,
so the subsequent full `y` read adopted that column, and the alter-conversion
`_CAST(y, 'LowCardinality(String)')` class-cast it in
`FunctionCast::prepareUnpackDictionaries`:

  Logical error: 'Bad cast from type DB::ColumnVector<unsigned long>
                  to DB::ColumnLowCardinality'

`performRequiredConversions` is where it surfaces, not where it originates. The
query is rejected in every build; debug and sanitizer builds abort. Found by
`Stress test (arm_tsan)` on an unrelated pull request.

Move the presence check into `IMergeTreeReader::isSubcolumnMissingInPart` and use
it from both readers so they cannot diverge again. In the wide reader the decision
is made once in the constructor, before any stream name is resolved: for a
subcolumn absent from the part's type `getStreamNameForColumn` resolves an
existing stream of the parent, so a check made after resolution cannot distinguish
the two cases. Every per-column loop consults that one decision, including the
prefix loop and stream enumeration, so no loop opens or prefixes a stream that the
read loop skips.

The predicate resolves the part's column against the part's own columns list
rather than the Nested-collected view. With `share_nested_offsets`, asking the
synthesized `Nested(...)` group type about a member reports every member the part
lacks as a missing subcolumn, which would suppress a read that the offsets-sharing
path legitimately owns.

Read path only: on-disk data is unaffected and there is no format or setting
change, so existing parts read correctly and no migration is needed.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

An independent cold review plus a second-model pass ran against this diff before it was
opened. Five findings, all nits; no blocker and no major. Nothing changed in the diff as a
result, so this is a record rather than a changelog.

# Finding Verdict
💡 1 The relocated Quantize comment names a pq_codebook subcolumn; the real one is product_quantization_codebook. ⚠️ Accurate, left alone. The wording is pre-existing: it is at MergeTreeReaderCompact.cpp:87-102 and IMergeTreeReader.cpp in getSerializationInPart on the merge base, and this diff only moves one copy into the shared helper verbatim. Two other copies are untouched, so fixing only the moved one would make them inconsistent, and renaming all three would add an unrelated cosmetic change to a read-path bug fix.
💡 2 The visible Related: #115705 should be a full GitHub URL. ❌ Disagreed. The template's full-URL instruction sits inside its leading HTML comment and governs the linked-issues block, which this body already satisfies verbatim there. The short reference is a deliberate second line in the prose, because that comment block does not render and the link has to be visible; GitHub renders it as a live cross-reference. Two of the five most recent merged pull requests carrying a visible reference use the same short form.
💡 3 The Random settings limits: min_bytes_for_wide_part=(0, 0) line in the new test clamps nothing, because the no-random-merge-tree-settings tag on the line above already suppresses merge-tree randomization entirely. ⚠️ Correct, kept. It costs nothing and is the right value if the tag is ever dropped.
💡 4 The profile-event control reads CompressedReadBufferBytes, which is not incremented when a block is served from the uncompressed cache, and use_uncompressed_cache is randomized. ⚠️ Correct about the counter, and the control still holds: the two measured queries read disjoint streams (y.size versus y.bin), so neither can warm the cache for the other, and both tables are created fresh in the test database. Recorded because the reasoning is not obvious from the test text.
💡 5 The relocated 5-line comment exceeds the usual per-block length budget. ❌ Disagreed. It explains why a domain property holds rather than anything about this fix, which is the kind of comment that should stay.

Verified independently during the review rather than taken from the implementation notes:
all five per-column loops in MergeTreeReaderWide now consult the single constructor-time
decision, and there is no sixth; the skipped slot reaches evaluateMissingDefaults and is
derived from the converted parent, which is why correct lengths come back instead of zeros,
and the parent is available because injectRequiredColumns already adds it for exactly
this shape; LowCardinality(String) really has no size subcolumn, since
SerializationLowCardinality emits only the dictionary substreams and none of them is a
subcolumn path; and SYSTEM STOP MERGES holds the mutation off deterministically, because
scheduleDataProcessingJob returns before selecting parts to mutate, so the test is not
racing.

Session id: cron:clickhouse-review-slot-8:20260822-232500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, on the first attempt. Wide part with string_serialization_version = 'with_size_stream', y inserted as LowCardinality(String), then SYSTEM STOP MERGES plus an unmaterialized ALTER TABLE ... MODIFY COLUMN y String, then SELECT x, length(y) FROM t ORDER BY x. Fails every run with Logical error: 'Bad cast from type DB::ColumnVector<unsigned long> to DB::ColumnLowCardinality' and the reported stack (prepareUnpackDictionaries under IMergeTreeReader::performRequiredConversions).
b Root cause explained? length(y) is answered from the y.size subcolumn, and that rewrite keys on the metadata snapshot type, which the pending MODIFY has already moved to String. The part still holds LowCardinality(String), which has no size subcolumn. MergeTreeReaderWide read it anyway: getSerializationInPart fell back to the requested type's default single-stream serialization, SerializationStringSize parsed the dictionary indexes stream as string lengths into a ColumnVector<UInt64>, the per-storage-column substreams cache handed that column to the full y read, and the alter-conversion CAST to LowCardinality(String) class-cast it.
c Fix matches root cause? Yes. It corrects the read-or-derive decision at the point it is made, rather than guarding the cast site. MergeTreeReaderCompact already made that decision correctly; the check is now shared and both readers use it. No widened bounds, no no-random-* tag on the engine side, no defensive check at the failure site.
d Test intent preserved / new tests added? New stateless test 05030_wide_part_subcolumn_missing_in_part. It covers the wide-part defect, asserts the Compact path is unchanged, and adds a control asserting a genuinely present subcolumn is still read from its own size stream. No existing test weakened or removed.
e Both directions demonstrated? Yes, on Build-ID-verified binaries (SELECT lower(buildId()) matched against readelf for both arms). Pre-fix the repro exits 134 with the signature above; post-fix it returns the correct lengths. The new test was also run against the pre-fix build and reddens there, so the reference is sensitive rather than blind.
f Fix is general across code paths? The predicate now lives in IMergeTreeReader and Compact was de-duplicated onto it, so the two readers cannot drift again. In the wide reader it is computed once in the constructor and consulted by all five per-column loops, including the prefix loop and stream enumeration, so no loop opens or prefixes a stream another loop skips. calculateSubcolumnSize / getListOfStreamsForColumn verified unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? Matrix run against both builds: LowCardinality(String), LowCardinality(Nullable(String)), Nullable(String), plain String, both type-flip directions, plus Array(String), Tuple, Map, and the .null / .keys / .a / .size subcolumn paths, on wide and compact parts. Only the LowCardinality(String) to String wide cell differs between builds; every other cell is identical. Confirmed why the sibling cells do not arm rather than assuming it: with a LowCardinality snapshot type the length to .size rewrite never fires, which EXPLAIN shows directly.
h Backward compatible? Yes. Read path only. No setting, default, or serialization-format change, nothing is written differently, and existing parts read correctly, so no SettingsChangesHistory.cpp entry and no migration path are required.
i Invariants and contracts preserved? The skipped slot stays nullptr and flows into the existing missing-subcolumn path, which requests the full parent, converts it, and extracts the subcolumn, which is why correct values are returned rather than defaults. Loop consistency holds by construction: one decision computed before any stream exists. A profile-event control confirms the fast size-only read is preserved for subcolumns the part does have, and that counter was separately shown to discriminate a size-only read from a full data read by two orders of magnitude.

Session id: cron:clickhouse-impl-slot-7:20260822-203800

@clickhouse-gh

clickhouse-gh Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bfb7b8d]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) FAIL
05260_wide_part_subcolumn_missing_in_part FAIL cidb
02346_non_negative_derivative NOT_FAILED cidb
01283_max_threads_simple_query_optimization NOT_FAILED cidb
01513_optimize_aggregation_in_order_memory_long NOT_FAILED cidb
02884_create_view_with_sql_security_option NOT_FAILED cidb
03273_group_by_in_order_still_used_when_group_by_key_doesnt_match_order_by_key NOT_FAILED cidb

AI Review

Summary

This PR centralizes the missing-subcolumn check in IMergeTreeReader, makes MergeTreeReaderWide decide that skip before any stream name is resolved, keeps MergeTreeReaderCompact on the same predicate, and extends the regression coverage to scalar, Array, and Nested cases in both wide and compact parts. After reading the current diff, the affected reader paths, and the prior review threads, I did not find a remaining correctness, cache, or stream-selection issue that warrants a new review comment.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @Avogar, could you review this? A wide-part reader was reading a subcolumn the part's own column type does not have (y.size requested from the String snapshot while the part still holds LowCardinality(String) under an unmaterialized MODIFY COLUMN), so it parsed the dictionary indexes stream as string lengths and the shared substreams cache handed that column to the full read. The compact reader already refused it, so this moves the presence check into IMergeTreeReader for both.

Adjacent to #115670, which touches the same file at a different hunk. It is a distinct defect: the substreams cache key is unchanged here.

@clickhouse-gh

clickhouse-gh Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit bfb7b8d9e425f9c2475905951e2fbb29c9e11209 was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ { "name": "file", "type": "LowCardinality(String)" …).

See the job log for details.

… too

The test reached the reader's subcolumn request through `length(y)`, which only
becomes `y.size` via the FunctionToSubcolumns analyzer pass. That pass reads
`optimize_functions_to_subcolumns` in src/Analyzer/Passes only, so with the old
analyzer the rewrite never happens: the arming probe reported 0, the parent was
read directly, and the reference no longer matched. The same two cells that the
probe guards also flipped, which is what CI reported on the
amd_llvm_coverage/old analyzer arm.

Asking for `y.size` directly reaches the same request under both analyzers, so
the pinned `optimize_functions_to_subcolumns = 1` is no longer needed either.
Measured on the pre-fix master binary: the LOGICAL_ERROR reproduces with the old
analyzer as well, so this widens coverage rather than skipping the arm.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 444cf70 to fix the Stateless tests (amd_llvm_coverage, old analyzer, ...) failure, which was caused by this PR's own new test.

The test reached the reader's subcolumn request through length(y). That only becomes y.size via the FunctionToSubcolumns analyzer pass, and optimize_functions_to_subcolumns is read in src/Analyzer/Passes only, so with the old analyzer the rewrite never happened: the arming probe reported 0 and the parent was read directly. Both cells that flipped in the reference are the ones that probe guards.

The test now asks for y.size directly, which reaches the same request under both analyzers, so the pinned optimize_functions_to_subcolumns = 1 is gone too. The reference file is unchanged.

I checked that this widens coverage rather than skipping the arm, so no no-old-analyzer tag: on the pre-fix master binary the LOGICAL_ERROR reproduces under the old analyzer as well, with the same prepareUnpackDictionaries / performRequiredConversions stack. Measured on Build-ID-verified binaries, via the test runner: pre-fix 0 OK / 1 FAIL on each analyzer, this head 50/50 OK on each.

One residual, disclosed rather than fixed here: when the subcolumn's parent is a dotted Nested member (n.y.size), the storage name is the synthesized group n while the part carries the physical n.y, so the presence lookup misses and the read is not skipped. Master aborts on that shape too, so it is pre-existing and not introduced here; this PR narrows the single-level case only. Fixing it means picking between the Nested-collected and raw column views, which is what caused the 04770 offsets-sharing regression during this PR's implementation, so it needs its own change and its own coverage.

@rschu1ze

Copy link
Copy Markdown
Member

@groeneai Sorry, I still have a backlog of fixes to check and will not find time to review this one soon.

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
groeneai and others added 3 commits September 27, 2026 12:28
…ng-subcolumn-read

Conflict in `MergeTreeReaderCompact::fillColumnPositions`: master added a
metadata lookup of the requested regular subcolumn before the
serialization-based `hasSubcolumn` check (e009889, performance), while
this branch moved that check into `IMergeTreeReader::isSubcolumnMissingInPart`
so the wide reader shares it. Kept the call to the shared helper and moved
master's lookup into the helper, so the compact reader keeps the fast path
and the wide reader gets it too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`05030` is now used by seven other tests on master. The note explained why
the test requests `y.size` directly instead of `length(y)`; the old analyzer
it referred to is removed, and the direct request stays because it does not
depend on `optimize_functions_to_subcolumns`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `share_nested_offsets` the wide reader remaps `n.y.size` to subcolumn
`y.size` of the synthesized group `n`, which is not a column of the part, so
the presence check found nothing and let the read through: with a pending
`MODIFY COLUMN n.y Array(String)` over an `Array(LowCardinality(String))`
member this hit the same logical error as the single-level case. The check
now resolves such a request to the member the part stores and asks the
member's type; a member the part lacks entirely is still left to the
missing-column path, which owns offsets sharing (04770).

The compact reader already reset the position for such subcolumns, but then
handed the column to `findPositionForMissedNested`, which is meant for an
array the part does not have at all, and read the present column's offsets
with the requested type: `Code: 33 CANNOT_READ_ALL_DATA` for both a plain
`Array(LowCardinality(String))` and a Nested member (26.3, 26.8, master),
or wrong lengths in 26.3 when only the subcolumn is read. A present column
whose type lacks the subcolumn is now derived from the converted parent, as
for scalar types.

Found by the second-model review; the dotted-member case was also raised by
the AI reviewer on this PR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Do not read a subcolumn that a wide part's column type does not have Do not read a subcolumn that a part's column type does not have Sep 27, 2026
@groeneai
groeneai requested review from Avogar and CurtizJ September 27, 2026 15:59
@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 3ea37daf-3838-4276-ad03-348aa2d4deda
  • MIRAI run: 1b64d04e-8484-458d-ad60-567632b6f273
  • PR check IDs:
    • clickbench_2642921_1790827426
    • clickbench_2642933_1790827426
    • clickbench_2643142_1790827445
    • tpch_adapted_1_official_2643157_1790827446
    • tpch_adapted_1_official_2643475_1790827718
    • tpch_adapted_1_official_2643587_1790827724

@clickhouse-gh clickhouse-gh Bot removed the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Nov 19, 2026

This branch has not been deployed

No deployments
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-part-formats Formats of MergeTree data parts in the public repository, that is how a part is laid out on disk ... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants