Skip to content

Add a test for stale skip index reads with apply_mutations_on_fly and apply_patch_parts off - #106988

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-skip-index-alter-modify-column-nullable-snapshot
Oct 4, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-skip-index-alter-modify-column-nullable-snapshot

Conversation

@groeneai

@groeneai groeneai commented Jun 10, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

...

Description

Test-only. The source change this PR used to carry is dropped: #112484 rejects a stale skip index granule in IMergeTreeIndex::getDeserializedFormat, which covers the same case at the deserialization boundary.

With apply_mutations_on_fly = 0 and apply_patch_parts = 0 the read snapshot omits a pending ALTER MODIFY COLUMN mutation, so that check is the only thing that keeps old granules from being decoded with the new type. The existing tests for it (04165 and its splits) reach it through KILL MUTATION, metadata-only alters and absent columns; none disables both settings. 05317 pins this route for a String to Nullable(UInt64) set index, through planning-time index analysis and the direct skip index read, and asserts that the mutation is still pending, the stale index is consulted but prunes nothing, and the read-time filter runs.

Validation: 26.7.17.7 (no #112484) fails with Code: 49 LOGICAL_ERROR; 26.8.10.6 and a master debug build pass. On master the mutation is still pending on 3 of 3 parts while the index is listed but prunes nothing, so the pass is not vacuous. It passes in 102 randomized parallel runs.


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

Version info

  • Merged into: 26.10.1.1491-master (included in 26.10 and later)

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. CREATE TABLE tg (id UInt64, value String, INDEX idx_set (value) TYPE set(0) GRANULARITY 1) ENGINE=MergeTree() ORDER BY id PARTITION BY id SETTINGS add_minmax_index_for_numeric_columns=0, min_bytes_for_wide_part=0; INSERT ... (3,'300'); SYSTEM STOP MERGES; ALTER TABLE tg MODIFY COLUMN value Nullable(UInt64) (alter_sync=0, mutations_sync=0); SELECT count() FROM tg WHERE value=300 SETTINGS apply_mutations_on_fly=0, apply_patch_parts=0 aborts the server every time on master HEAD (debug).
b Root cause explained? Yes. createStorageSnapshot set need_alter_mutations = apply_mutations_on_fly || apply_patch_parts. Both off => the pending READ_COLUMN alter mutation is filtered out of the read snapshot (addSupportedCommands) => AlterConversions::getAllUpdatedColumns() is empty => canUseIndex does not exclude the type-incompatible skip index => filterMarksUsingIndex deserializes the old String-serialized SET-index granule as Nullable(UInt64) => null map size 1, nested size 0 => LOGICAL_ERROR abort. Reached during planning via the implicit count() projection (optimizeUseAggregateProjections -> selectRangesToRead).
c Fix matches root cause? Yes. The fix makes the read snapshot always request alter mutations (need_alter_mutations = true), so pending column type changes are visible to skip-index analysis regardless of the unrelated on-fly apply flags. It targets the exact mechanism in (b), not the symptom.
d Test intent preserved / new tests added? New regression test 04151_skip_index_after_alter_modify_column_nullable.sql added. It pins apply_mutations_on_fly=0, apply_patch_parts=0 and a String -> Nullable(UInt64) change with a pending mutation, and checks the result with both flags off, with defaults, and after the mutation is materialized. Existing 04143/04144 tests (the prior fix in this area) are untouched.
e Both directions demonstrated? Yes. Without the fix (master snapshot binary): the query aborts the server (LOGICAL_ERROR, confirmed from fatal.log and locally). With the fix (rebuilt binary): the regression test prints 1 / 1 / 1 matching .reference, the server stays alive, and the trace shows Index idx_set is not used for part ... will be updated on the fly, confirming the index is now correctly excluded.
f Fix is general, not a narrow patch? Yes. The fix is at the source (snapshot construction), not a guard at the crash site, so it covers every skip-index type that would be read with an incompatible on-disk type after a pending ALTER MODIFY COLUMN, not just the SET index / Nullable case that fuzzing hit. The sibling read-path / write-path snapshots (MergeTask uses !patch_parts.empty(), MutateTask uses true) were reviewed and are correct as-is; only the query read path coupled alter-mutation visibility to the apply flags. Column data reads are unaffected (conversion uses the part's own stored type in IMergeTreeReader).

Session id: cron:clickhouse-worker-slot-6:20260610-141800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @alesapin — could you review this? The query read snapshot only requested alter (READ_COLUMN) mutations when apply_mutations_on_fly || apply_patch_parts, so with both off a pending ALTER MODIFY COLUMN type change was invisible to canUseIndex, and a stale skip index was read with the new (incompatible) type, aborting the server with a LOGICAL_ERROR. The fix makes the read snapshot always request alter mutations.

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

clickhouse-gh Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [64bf3bc]

Summary: ✅


AI Review

Summary

This PR has been reduced to a focused stateless regression test for the already-merged stale skip-index type check: it exercises both the planning-time path and the direct use_skip_indexes_on_data_read = 1 path with apply_mutations_on_fly = 0 and apply_patch_parts = 0, and it also proves the pass is non-vacuous by checking that the stale index is still consulted before rebuild and that read-time filtering resumes after MATERIALIZE INDEX. I read the current diff and the full prior thread history, and I did not find any remaining correctness, coverage, or safety issues in the test-only version of the PR.

Final Verdict
  • Status: ✅ Approve

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (updated for the fast-path fix, HEAD 6e4dd00)

# Question Answer
a Deterministic repro? Yes. Built the base commit fc73f46 (pre-fix) and ran the new test against it: the server aborts every time with Logical error: 'Sizes of nested column and null map of Nullable column are not equal after deserialization (null map size = 1, nested column size = 0)' via SerializationNullable::deserializeBinaryBulkWithMultipleStreams -> MergeTreeIndexSet::deserializeBinary -> filterMarksUsingIndex. Repro is the test SQL: ALTER ... MODIFY COLUMN value Nullable(UInt64) with alter_sync=0, mutations_sync=0, then SELECT count() ... WHERE value=300 SETTINGS apply_mutations_on_fly=0, apply_patch_parts=0.
b Root cause explained? Yes. createStorageSnapshot set need_alter_mutations = apply_mutations_on_fly || apply_patch_parts. Both off => the pending READ_COLUMN alter mutation is dropped from the read snapshot => AlterConversions::getAllUpdatedColumns() is empty => canUseIndex does not exclude the type-incompatible skip index => filterMarksUsingIndex deserializes the old String-serialized SET-index granule as Nullable(UInt64) (null map size 1, nested size 0) => LOGICAL_ERROR.
c Fix matches root cause? Yes, and it now preserves the no-alter fast path per the AI Major. need_alter_mutations is requested when a pending READ_COLUMN mutation actually exists, gated on getMutationCounters().num_alter > 0 (a cheap 3-int read), instead of unconditionally true. Reads with no pending column-type change keep need_data_mutations=false && need_alter_mutations=false, so getMutationsSnapshot still hits the empty-snapshot fast path (no mutation lock, no current_mutations_by_version scan). The replicated queue initializes seen_all_data_mutations from need_data_mutations only, so an alter-only snapshot no longer walks data-mutation entries (alter/metadata mutations carry alter_version != -1 and use the metadata branch).
d Test intent preserved / new tests added? Yes. New regression test 04151_skip_index_after_alter_modify_column_nullable.sql (unchanged from prior HEAD) pins apply_mutations_on_fly=0, apply_patch_parts=0 for a String -> Nullable(UInt64) change with a pending mutation, and checks the result with both flags off, with defaults, and after materialization.
e Both directions demonstrated? Yes. Base binary (pre-fix): server aborts with the LOGICAL_ERROR above. Fixed binary (HEAD 6e4dd00): the test prints 1/1/1 matching .reference and the server stays alive. Additionally verified the fast path is preserved: a read with apply_patch_parts=0 and a pending UPDATE (data mutation, num_alter=0) returns the correct result with the server alive. Sibling tests 03702_alter_column_modify_secondary_index_general, 03702_alter_column_update_and_delete_secondary_index_general, 03702_alter_codec_index pass and match references.
f Fix is general, not a narrow patch? Yes. The fix is at snapshot construction, not a guard at the crash site, so it covers every skip-index type read with an incompatible on-disk type after any pending ALTER MODIFY COLUMN. The gating uses the existing num_alter counter (already maintained for all alter mutations), and the symmetric replicated read path is handled too. The write/merge snapshots (MergeTask uses !patch_parts.empty(), MutateTask uses true) were reviewed and are unaffected; column data reads use the part's own stored type in IMergeTreeReader, independent of the snapshot.

Session id: cron:clickhouse-worker-slot-14:20260610-200400

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. Addressed both points in 6e4dd00.

Major (preserve the no-alter fast path). need_alter_mutations is no longer unconditional. It is now apply_mutations_on_fly || apply_patch_parts || has_alter_mutations, where has_alter_mutations = getMutationCounters().num_alter > 0 (the count of pending READ_COLUMN mutations, a cheap 3-int read under the existing lock). A read on a table with no pending column-type change keeps need_data_mutations = false and need_alter_mutations = false, so StorageMergeTree::getMutationsSnapshot still returns the empty snapshot via the !need_data_mutations && !need_alter_mutations && num_metadata <= 0 fast path, without taking the mutation lock or scanning current_mutations_by_version. Only a genuine pending READ_COLUMN/metadata mutation forces the walk.

For the replicated queue, seen_all_data_mutations is now initialized from !params.need_data_mutations only. Alter and metadata mutations always carry alter_version != -1 and are served by the metadata branch, so a snapshot needing only alter visibility no longer walks data-mutation entries (those have alter_version == -1 and are excluded by needIncludeMutationToSnapshot when need_data_mutations is false). This avoids the data-mutation traversal the review flagged.

Metadata. Reworded the changelog entry to "Fix a LOGICAL_ERROR exception ..." instead of "server crash".

Verified locally: the new test crashes the pre-fix binary with the documented LOGICAL_ERROR and passes on the fixed binary; a read with apply_patch_parts = 0 plus a pending UPDATE (no alter) returns correct results and stays on the fast path; sibling skip-index/alter tests pass.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on HEAD 6e4dd00c7256. Both failures are non-PR-caused (one known infra outage, one tracked chronic-flaky integration test). Moving to review.

Check Failure Disposition
Stateless (arm_asan_ubsan, azure, sequential) Segfault STID 0883-65ab + Server died Infra — the 2026-06-10/11 ASan secondary-allocator OOM (sanitizer_allocator_secondary.h) outage that hit many unrelated PRs and master in the same window. Not this PR.
Integration tests (amd_tsan, 1/6) test_refreshable_mat_view_replicated::test_circular_dependencies_survive_restart Known chronic flaky (14 PRs / 30d, 1 master); tracked under issue #106651. Unrelated to skip-index ALTER MODIFY COLUMN.

Fast test, Style check, and Bugfix validation are green on this HEAD.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI summary, covered HEAD 6e4dd00c

CI fully finished (Finish Workflow pass, aggregator complete, >20 min buffer). Both failures are non-PR-caused; the createStorageSnapshot skip-index fix is not implicated.

Check Failure Classification Disposition
Stateless tests (arm_asan_ubsan, azure, sequential) Segmentation fault (STID 0883-65ab), then Server died Inherited trunk corruption (multistage distributed-queries thread-teardown UAF, STID 0883-* family) Not PR-caused. This HEAD predates the master revert #107122 (merged 01:37 UTC 06-11), so it inherited the now-fixed corruption. The arm_asan_ubsan, azure, sequential check is clean on master across 55 commits since 03:00 UTC 06-11 (0 failures); the same pre-revert window shows this family on 16+ unrelated PRs as singletons. A rebase past 01:37 UTC 06-11 clears it.
Integration tests (amd_tsan, 1/6) test_refreshable_mat_view_replicated::test_circular_dependencies_survive_restart Chronic flaky (38 hits / 33 distinct PRs / 3 master in 30d) Not PR-caused (this PR only touches MergeTreeData::createStorageSnapshot). Tracked under the chronic refreshable-MV task (issue #106651).

No PR-caused failures. The fix (skip-index over a column with a pending ALTER MODIFY COLUMN type change; regression test 04151) is unaffected.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fresh independent P0 reproduction of this bug surfaced on an unrelated PR's Stress test (amd_tsan) run, reinforcing this fix:

  • The same crash class hit the data-read skip-index path (not just the planning path): Logical error: 'Too large size (9223372036854775808) passed to allocator' via MergeTreeIndexBulkGranulesSet::deserializeBinary (MergeTreeIndexSet.cpp:192) -> SerializationNullable -> SerializationNumber<char8_t>::deserializeBinaryBulk, reached through MergeTreeSkipIndexReader::read -> filterMarksUsingIndex.
  • Root cause is identical: with apply_mutations_on_fly = 0 and apply_patch_parts = 0, a pending ALTER MODIFY COLUMN is dropped from the read snapshot, so supportsSkipIndexesOnDataRead()'s hasAlterMutations() guard does not fire and the data-read phase deserializes the old-type set-index granule with the new (incompatible) type.

I verified this PR's change fixes it on current master HEAD (67a77862327), in both directions:

CREATE TABLE t (id UInt64, value String, INDEX idx (value) TYPE set(0) GRANULARITY 1)
  ENGINE = MergeTree ORDER BY id SETTINGS index_granularity = 8, min_bytes_for_wide_part = 0;
INSERT INTO t SELECT number, toString(number * 1000000000) FROM numbers(128);
SYSTEM STOP MERGES t;
ALTER TABLE t MODIFY COLUMN value Nullable(UInt64);  -- alter_sync = 0, mutations_sync = 0
SELECT count() FROM t WHERE value = 300
  SETTINGS force_data_skipping_indices = 'idx', use_skip_indexes_on_data_read = 1,
           max_rows_to_read = 0, apply_mutations_on_fly = 0, apply_patch_parts = 0;
  • Without the fix (master HEAD): garbage huge-size allocation (would use 1.00 EiB), i.e. the same abort seen in CI.
  • With the createStorageSnapshot change cherry-picked onto master HEAD: clean result, server alive.

One note for a rebase: master's ReplicatedMergeTreeQueue::getMutationsSnapshot now computes seen_all_data_mutations from hasDataMutations()/hasAlterMutations() directly (plus a part->info.isPatch() clause), so that part of this PR may need reconciling; the MergeTreeData::createStorageSnapshot change alone resolves the reproduction on current master.
Session id: cron:clickhouse-worker-slot-5:20260629-041200

@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.30% -0.10%
Functions 91.90% 91.80% -0.10%
Branches 78.50% 78.40% -0.10%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 035eeba

CI is fully finished on this head: 174 check-runs, all completed, 1 red. Every failure below has an owner.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / Server died + Logical error: Got read request from replica 2 for unknown stream ... (STID: 5217-5b3d) trunk logical error on the parallel-replicas read-coordination path, not related to this diff fixing PR #111689 (ours, open)

The two rows are one event: the coordinator abort kills the server, and Server died is the runner reporting the consequence.

Session id: cron:our-pr-ci-monitor:20260730-030000

@Ergus Ergus left a comment

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.

The regression tests is not failing over master without the fix, so the issue was already fixed or the reproduction is nor determninistic?

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

You are right. It stopped reproducing, because this PR was superseded by my own #112484.

04151 exactly as committed here, run just now:

  • 26.7.6.57 (official build): Code: 49, LOGICAL_ERROR
  • 26.8.2.7 (official build): passes, 1 1 3 1
  • master 38a9ca20767a (debug, build id ed4622ff): passes, 1 1 3 1

It is not a vacuous pass on master: the mutation is still pending on 3 of 3 parts, system.columns already reports Nullable(UInt64), and EXPLAIN indexes = 1 still lists Skip / Name: idx_value. The predicate is armed, the read just no longer mis-decodes.

The fix is 4bb044d321bcef2, "Do not deserialize a skip index whose on-disk type is stale", from #112484, merged 2026-08-15. It is in master and 26.8 and not in 26.7, which matches the three results above. It compares the part's own recorded type against the type the granule is about to be decoded with, in IMergeTreeIndex::getDeserializedFormat, and its commit message lists "the mutation is pending but dropped from the storage snapshot" as one of the cases it covers. That is precisely what this PR gates in createStorageSnapshot, so the code change here is redundant and sits at a worse layer.

Same for the other shape, UInt64 to Float64, where the old bytes reinterpret silently instead of failing to deserialize: 26.7.6.57 returns 0 where 128 is correct, 26.8.2.7 and master return 128.

Two consequences. With pr-bugfix this can no longer pass its own gate, since Bugfix validation needs the added test to fail on the master binary, which is what you saw. And only the tests are still worth anything: 04165_skip_index_stale_type_after_alter, added by #112484, never sets apply_mutations_on_fly or apply_patch_parts, so the both-flags-off combination is left unpinned.

I would close this and move those two queries into 04165 as a test-only PR. Say so if you would rather I reduce this PR to the tests instead.

@abashkeev abashkeev added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

Dear @Ergus, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

Ergus
Ergus previously requested changes Oct 2, 2026

@Ergus Ergus left a comment

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.

The main change in this PR is already on master. I think that we must drop changes.

Close this PR or reduce it to a test-only PR.

…ch_parts off

With both settings off, the read snapshot omits a pending ALTER MODIFY COLUMN
mutation, so nothing in the snapshot disables a skip index whose granules were
written with the old column type. The only remaining guard is the stale-type
check in IMergeTreeIndex::getDeserializedFormat (ClickHouse#112484). The existing tests
for that check reach it through KILL MUTATION, metadata-only alters and absent
columns; none disables both settings.

The new test covers a String -> Nullable(UInt64) set index through
planning-time index analysis and the direct skip index read. It asserts that
the mutation is still pending on all three parts, that the stale index is
consulted but prunes nothing, and, through SelectedMarks of the same direct
read before (3) and after (1) the index is rebuilt, that the read-time filter
runs. On 26.7, which lacks ClickHouse#112484, each of the two reads alone fails with the
LOGICAL_ERROR "Sizes of nested column and null map of Nullable column are not
equal after deserialization".

The source change this branch used to carry (gating need_alter_mutations in
createStorageSnapshot) is dropped: ClickHouse#112484 covers the same case at the
deserialization boundary, plus routes that gate cannot reach. The extra
ReplicatedMergeTree row in 04144 is dropped too: with alter_sync = 0 the
replica applies the new column type asynchronously, so the row often read the
old metadata and exercised nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai
groeneai force-pushed the fix-skip-index-alter-modify-column-nullable-snapshot branch from 137b450 to 64bf3bc Compare October 2, 2026 17:45
@groeneai groeneai changed the title Fix crash on skip index over a column with pending ALTER MODIFY COLUMN type change Add a test for stale skip index reads with apply_mutations_on_fly and apply_patch_parts off Oct 2, 2026
@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

Reduced to a test-only PR in 64bf3bc: the src/ change is dropped.

What is left is one test, 05317_skip_index_after_alter_modify_column_nullable. With apply_mutations_on_fly = 0 and apply_patch_parts = 0 the snapshot drops the pending MODIFY COLUMN, so the #112484 check is the only guard, and no test in the 04165 family disables both settings. It fails on 26.7.17.7 (each of its two reads alone hits the LOGICAL_ERROR) and passes on 26.8.10.6 and master. It also asserts that the mutation is still pending and that the read-time filter actually runs (SelectedMarks 3 on the stale index, 1 after the rebuild), so the master pass is not vacuous.

I also dropped the extra 04144 row: with alter_sync = 0 the replica applies the new column type asynchronously, so that row often read the old metadata and tested nothing.

@clickhouse-gh clickhouse-gh Bot added pr-ci comp-testing Test content only (no production code). and removed pr-bugfix Pull request with bugfix, not backported by default comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Oct 2, 2026
@alexey-milovidov alexey-milovidov self-assigned this Oct 4, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 4, 2026
Merged via the queue into ClickHouse:master with commit c9be6a4 Oct 4, 2026
149 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 4, 2026
@clickhouse-gh clickhouse-gh Bot added comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. and removed comp-testing Test content only (no production code). labels Nov 22, 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 comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. groeneai-origin-review-human PR origin: human review feedback on a groeneai PR pr-ci 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.

6 participants