Skip to content

Fix skip index used with incompatible type after ALTER MODIFY COLUMN - #100526

Merged
alexey-milovidov merged 32 commits into
masterfrom
fix-nullable-deserialization-error-code
Apr 30, 2026
Merged

alexey-milovidov merged 32 commits into
masterfrom
fix-nullable-deserialization-error-code

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 24, 2026 •

Copy link
Copy Markdown
Member

getAllUpdatedColumns() in StorageMergeTree::MutationsSnapshot and ReplicatedMergeTreeQueue::MutationsSnapshot had an early-return when !hasDataMutations(). But ALTER TABLE MODIFY COLUMN creates a READ_COLUMN mutation, classified as an alter mutation, not a data mutation. So hasDataMutations() returned false, getAllUpdatedColumns returned an empty set, and can_use_index in filterPartsByPrimaryKeyAndSkipIndexes allowed using skip indexes on old parts whose index data was serialized with the old column type.

When the index data (e.g. serialized as String) was deserialized with the new type (e.g. Nullable(UInt64)), the null map and nested column sizes diverged, triggering a LOGICAL_ERROR exception that aborted the process in sanitizer builds.

The fix adds && !hasAlterMutations() to the early-return condition so that columns modified by ALTER mutations are correctly reported.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100434&sha=69b1304f16cd6c73d58db2ace9a7120b5c49b506&name_0=PR&name_1=Stress%20test%20%28amd_msan%29
#100434

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 skip index being used with incompatible data after ALTER TABLE MODIFY COLUMN changes the column type, which could cause server crashes in sanitizer builds or incorrect query results.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.198

alexey-milovidov and others added 2 commits March 24, 2026 01:34
`getAllUpdatedColumns()` in `StorageMergeTree::MutationsSnapshot` and
`ReplicatedMergeTreeQueue::MutationsSnapshot` had an early-return when
`!hasDataMutations()`. But `ALTER TABLE MODIFY COLUMN` creates a
`READ_COLUMN` mutation, classified as an alter mutation, not a data
mutation. So `hasDataMutations()` returned false, `getAllUpdatedColumns`
returned an empty set, and `can_use_index` in
`filterPartsByPrimaryKeyAndSkipIndexes` allowed using skip indexes on
old parts whose index data was serialized with the old column type.

When the index data (e.g. serialized as `String`) was deserialized with
the new type (e.g. `Nullable(UInt64)`), the null map and nested column
sizes diverged, triggering a `LOGICAL_ERROR` exception that aborted
the process in sanitizer builds.

The fix adds `&& !hasAlterMutations()` to the early-return condition
so that columns modified by ALTER mutations are correctly reported.

Also changed the error code in `SerializationNullable` deserialization
check from `LOGICAL_ERROR` to `INCORRECT_DATA`, since a size mismatch
during deserialization can be caused by incompatible data, not only by
a programming error.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100434&sha=69b1304f16cd6c73d58db2ace9a7120b5c49b506&name_0=PR&name_1=Stress%20test%20%28amd_msan%29

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7580593]

Summary: ✅


AI Review

Summary

This PR fixes a real correctness issue where skip indexes could be evaluated against stale on-disk index data after ALTER TABLE ... MODIFY COLUMN, causing wrong filtering (and previously sanitizer-only exceptions in one manifestation). The change is coherent across both MergeTree and ReplicatedMergeTree mutation snapshots, and it adds focused stateless coverage for both engines with forced skip-index usage in the affected phase.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 24, 2026
alexey-milovidov and others added 5 commits March 28, 2026 16:26
`SYSTEM SYNC MUTATIONS` is not a valid ClickHouse command. Replace it with
`OPTIMIZE TABLE ... FINAL SETTINGS mutations_sync = 2` which correctly waits
for the mutation to complete before verifying results.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The previous test had only 3 rows with the default `index_granularity` (8192),
so everything fit in a single granule. Skip indexes can only skip entire
granules, meaning the set index was never actually evaluated during query
execution, and the type-mismatch deserialization bug was not triggered on master.

Use `index_granularity = 128` with 256 rows split across two granules (one with
value '10', one with '300') so the set index is populated and the query for 300
must evaluate it — triggering the `LOGICAL_ERROR` on the old code path.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…ilure

The previous test used String → Nullable(UInt64), which happened to not
throw in release builds on ARM because the garbled deserialization produced
values that did not affect query results. The bugfix validation failed
because the test passed on both master and PR binaries.

Switch to UInt64 → String conversion: when the `set(0)` index's UInt64
data is deserialized as String (varint-length-prefixed), the first byte
of the UInt64 value is interpreted as the string length, which exceeds
the available data and throws reliably on all architectures.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
-- Without the fix, the skip index is used on old parts and the UInt64 data
-- is deserialized as String (varint-length-prefixed), which throws.
-- With the fix, the index is correctly skipped for old parts.
SELECT count() FROM test_skip_index_alter WHERE value = '300';

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.

SELECT count() ... WHERE value = '300' does not guarantee that idx_value is actually applied, so this test can pass even if the skip-index path is never executed (false negative for this bug).

Please force index usage in the assertions that are meant to validate this fix, for example with:

SELECT count()
FROM test_skip_index_alter
WHERE value = '300'
SETTINGS force_data_skipping_indices = 'idx_value';

(and similarly for the pre-ALTER check).

alexey-milovidov and others added 2 commits March 29, 2026 07:40
…ces`

Without this setting, the query may succeed even when the skip index
path is broken because the optimizer might choose not to use the index.
This also fixes bugfix validation, which needs the test to fail on
master (without the fix) and pass on the PR branch.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The previous `UInt64 → String` conversion did not reliably reproduce the
bug in release builds: the `set` index catches deserialization errors and
falls back to including all granules, producing correct results despite
the incompatible data.

Switch to `UInt64 → Float64` which uses the same 8-byte fixed-width
serialization. The old UInt64 bytes are silently reinterpreted as tiny
denormalized Float64 values, causing the `set` index to incorrectly skip
granules (returning 0 rows) rather than throwing. This ensures the test
fails on unfixed code and passes with the fix.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
SYSTEM START MERGES test_skip_index_alter;
OPTIMIZE TABLE test_skip_index_alter FINAL SETTINGS mutations_sync = 2;

-- After mutation completes, the index should work with the new type

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 regression test only covers plain MergeTree, but the fix also changes ReplicatedMergeTreeQueue::MutationsSnapshot::getAllUpdatedColumns.

Without a replicated-path test, we can still regress the code that reads mutation commands from ZooKeeper queue entries (different snapshot construction and iteration) while this test keeps passing.

Please add a ReplicatedMergeTree variant of this scenario (same ALTER TABLE MODIFY COLUMN + forced skip index usage before and after mutation application) to verify the replicated snapshot path as well.

alexey-milovidov and others added 3 commits March 29, 2026 11:11
… check

The primary filtering phase in `filterPartsByPrimaryKeyAndSkipIndexes`
correctly skips incompatible skip indexes for parts with pending ALTER
mutations via the `can_use_index` lambda. However, when
`use_skip_indexes_on_data_read` is enabled (the default), the data-read
phase in `MergeTreeSkipIndexReader::read` re-applied all useful indexes
without the same per-part check, causing incorrect query results.

Add a `disabled_skip_indexes` set to `RangesInDataPart` that is populated
when `can_use_index` rejects an index in the primary phase. The data-read
phase now checks this set and skips disabled indexes for each part.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Add a ReplicatedMergeTree variant to verify that the replicated snapshot
path in `ReplicatedMergeTreeQueue::MutationsSnapshot::getAllUpdatedColumns`
also correctly reports columns changed by ALTER mutations.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

/// Skip indexes that should not be applied during the data-read phase for this part,
/// because the part has pending ALTER mutations that change the indexed column type.
NameSet disabled_skip_indexes;

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 adds per-part state (disabled_skip_indexes) to RangesInDataPart, but that state is not represented in RangesInDataPartDescription and therefore is not propagated through the parallel-replicas coordinator protocol.

In parallel-replicas mode, MergeTreeIndexBuildContext reads skip indexes from read_ranges built from result.parts_with_ranges, while execution tasks are constructed from coordinator responses (RangesInDataPartsDescription) that only carry info/ranges/projection_name/min_marks_per_task. As a result, remote replicas can rebuild tasks without this disable-list and re-apply an index that was intentionally rejected during PK analysis on the initiator.

That makes the fix incomplete for parallel-replicas reads (the original incompatible-index behavior can still be hit there).

Please propagate this decision through the coordinator path (for example by extending RangesInDataPartDescription with disabled index names, or by moving this state into MergeTreeIndexBuildContext keyed by part/index and consulting it there) so all replicas enforce the same skip-index exclusions.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

alexey-milovidov and others added 11 commits April 6, 2026 17:49
Numbers 04056 and 04064 now have multiple tests on master; renaming to
04104 and 04105 so the two new tests have unique prefixes.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…tions

Replace the per-part `disabled_skip_indexes` plumbing with a single check
in `supportsSkipIndexesOnDataRead`: return false whenever there are any
pending ALTER mutations, mirroring the existing handling of data
mutations and patch parts.

The previous approach stored per-part disable decisions in
`RangesInDataPart::disabled_skip_indexes`, populated during PK analysis
on the initiator. This state was not serialized in
`RangesInDataPartDescription` and so was not propagated through the
parallel-replicas coordinator protocol — remote replicas could still
re-apply an index that was rejected on the initiator.

By disabling the data-read phase of skip-index application for any
pending ALTER mutation, the fix works uniformly on all replicas without
a protocol change. Primary-key analysis continues to exclude
incompatible indexes per-part via `can_use_index`, so queries still run
correctly; they just do not get the extra data-read phase optimization
while a type-changing mutation is in flight.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Numbers 04104 and 04105 now have multiple tests on master; renaming to
04113 and 04114 so the two new tests have unique prefixes.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…s with master

The previous numbers 04113 and 04114 collided with newly-merged tests in
master (`04113_has_subsequence_empty_haystack` and
`04114_coalesce_two_column_index_pruning`). Use 04117 and 04118 instead.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alexey-milovidov and others added 8 commits April 26, 2026 22:27
`clickhouse-test` randomizes `use_skip_indexes_on_data_read` between 0 and 1
in its random-settings rotation, which made the bugfix-validation runs of
`04117_skip_index_after_alter_modify_column` and `04118_..._replicated`
flaky: when randomized to 0, the data-read phase is bypassed entirely and
the bug (incorrect index data being applied with the new column type) does
not manifest, even on master.

Set the option explicitly in every assertion query so the data-read phase
is always exercised. Also update the comments to reflect that the active
fix is in `supportsSkipIndexesOnDataRead` (the data-read phase guard) — the
`MutationsSnapshot::getAllUpdatedColumns` change in this PR is now dead
code on master after the `AlterConversions` refactor in #100314, but is
kept for defensive correctness of the virtual override.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100526&sha=115d1948c0889f3687565fe9995a066c5ec37e31&name_0=PR&name_1=Bugfix%20validation%20%28functional%20tests%29

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`clickhouse-test` injects `max_rows_to_read = 20000000` by default. With the
default `read_overflow_mode = throw`, this causes `supportsSkipIndexesOnDataRead`
to early-return false:

    if (settings[Setting::read_overflow_mode] == OverflowMode::THROW
        && settings[Setting::max_rows_to_read])
        return false;

That bypasses the buggy data-read phase entirely on master, so the test
returned 128 (correct) even without the fix and the bugfix validation
job rejected the test with "Failed to reproduce the bug".

Set `max_rows_to_read = 0` per query so the data-read phase is exercised
on master and the bug is reliably reproduced.

Verified locally with a master binary: returns 0 (bug reproduced) with the
override, 128 (bug masked) without it.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100526&sha=44a2d11b0bfae1e919b4fa132a7e61b4cb642de0&name_0=PR&name_1=Bugfix%20validation%20%28functional%20tests%29

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…alization-error-code

# Conflicts:
#	programs/keeper-bench/Runner.cpp
#	src/Disks/DiskObjectStorage/DiskObjectStorage.cpp
#	src/Interpreters/JoinOperator.cpp
#	src/Interpreters/TableJoin.cpp
#	src/Interpreters/TableJoin.h
#	tests/clickhouse-test
#	tests/queries/0_stateless/02835_join_step_explain.sql
#	tests/queries/0_stateless/03595_convert_any_join_to_semi_or_anti.sql
After merging master, test numbers 04117 and 04118 collided with new
tests added in master (04117_mappopulateseries_int8_overflow,
04117_parser_system_query_variants, 04118_kql_make_series). Renamed
to 04141/04142 which are currently free.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Master added several `04141_*` tests, conflicting with our
`04141_skip_index_after_alter_modify_column.{sql,reference}` and
`04142_skip_index_after_alter_modify_column_replicated.{sql,reference}`.
Renumber them to `04143_*` and `04144_*` to keep them adjacent and away
from the new `04141_*`/`04142_*` files.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Apr 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 38.46% (5/13) | lost baseline coverage: 3 line(s) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov left a comment

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.

@alexey-milovidov alexey-milovidov self-assigned this Apr 30, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Apr 30, 2026
Merged via the queue into master with commit a5ea430 Apr 30, 2026
165 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-nullable-deserialization-error-code branch April 30, 2026 17:11
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 30, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this PR may need backporting to 26.3 (LTS), 26.2, 26.1, but no backport label was found.

Affected code: ReadFromMergeTree::supportsSkipIndexesOnDataRead and MutationsSnapshot::getAllUpdatedColumns — introduced in 25.9.

Why: Bug causes silent wrong results (and LOGICAL_ERROR exception in sanitizer builds) for users on default settings after ALTER MODIFY COLUMN. The use_skip_indexes_on_data_read setting (the affected feature) was introduced in 25.9 per SettingsChangesHistory.cpp:332, so it exists in 26.1+. 25.8 (LTS) predates the data-read feature and is not affected. PR has no pr-must-backport label currently.

Other supported branches (25.8) predate 25.9 and do not contain this code.

If this should be backported, consider adding pr-must-backport or a version-specific label (e.g. v26.3-must-backport). Ignore this if backporting is not applicable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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