Skip to content

Fix flaky test 02669_alter_modify_to_nullable - #109205

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-02669-alter-modify-nullable-flaky
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-02669-alter-modify-nullable-flaky

Conversation

@groeneai

@groeneai groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator

Closes: #108845

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

Fixes flaky 02669_alter_modify_to_nullable (issue #108845).

The test asserts the ALTER MODIFY COLUMN s String -> Nullable(String) metadata-only optimization fires for the Default-serialized part 1 (no data rewrite, read_rows = 0) while the Sparse part 2 is fully rewritten. That optimization (MutateTask.cpp::canSkipConversionToNullable) is best-effort and is very rarely skipped under concurrency on the shared CI server, so part 1 gets fully rewritten instead (read_rows = 10000, type Nullable(String)). Data results are always correct; only the optimization-detail assertion flips.

CIDB (90 days): the metadata-only-fallback signature hit 6 unrelated PRs, 0 on master. It reproduces on Fast test, which runs with --no-random-settings --no-random-merge-tree-settings, so it is a genuine timing race, not a randomized-settings issue (CI's own --diagnose-random-settings passed 181/181 and 8/8 with the same settings).

Fix: convert the .sql to a .sh that retries the whole scenario until the optimization fires (bounded to 10 attempts, each on its own table so system.part_log stays isolated). The .reference is unchanged. A real regression (the optimization stops firing) still fails every attempt because the decision is deterministic for these inputs, so the test keeps its regression-detection power. This mirrors the existing sibling test 03221_mutation_analyzer_skip_part.sh.

The test asserts the ALTER MODIFY String -> Nullable(String) metadata-only
optimization fires for a Default-serialized part (part 1: no data rewrite,
read_rows = 0). That optimization is best-effort and is very rarely skipped
under concurrency on the shared CI server, causing part 1 to be fully
rewritten (read_rows = 10000). Data results are always correct; only the
optimization-detail assertion flips.

Convert the .sql to a .sh that retries the scenario until the optimization
fires. A real regression (the optimization stops firing) still fails every
attempt because the decision is deterministic for these inputs, so
regression-detection is preserved. Same approach as the sibling test
03221_mutation_analyzer_skip_part.sh.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Not on a single attempt (genuine ~1/9300 race; not reproducible in ~8360 local runs across isolated/parallel/heavy-load/async). But the mechanism IS deterministic: forcing canSkipConversionToNullable to return false (column statistics present, or the MODIFY batched with another mutation) reliably yields the exact CI signature (1_1_1_0_3 Nullable(String) / read_rows = 10000).
b Root cause explained? The test asserts a best-effort optimization. read_rows = 0 comes from the untouched-part clone path: when canSkipConversionToNullable skips part 1's READ_COLUMN command, commands_for_part is empty so isStorageTouchedByMutations returns no_rows and the part is cloned. Under rare concurrency the optimization is skipped, part 1 is fully rewritten, and both the type and read_rows assertions flip together.
c Fix matches root cause? Yes. The optimization is best-effort by design, so the test is made robust to a rare skip by retrying the scenario until it fires, rather than weakening any assertion or pinning a setting (settings are not the cause: Fast test runs --no-random-* and CI's --diagnose-random-settings passed 181/181 + 8/8 on the same settings).
d Test intent preserved / new tests added? Preserved. .reference is byte-identical. Verified a broken-optimization simulation (every attempt full-rewrites) exhausts all 10 attempts and produces output that differs from .reference, so the test still FAILS on a real regression.
e Both directions demonstrated? Yes. Optimization present -> 90/90 runs pass (30 + 50 no-random, 40 with randomization). Optimization broken (forced) -> output differs from reference -> test fails. Retry recovery shown: a forced attempt-1 full-rewrite is followed by a passing attempt 2, and the final output equals the metadata-only reference.
f Fix is general across code paths? N/A (test-only change; no source code modified).
g Fix generalizes across inputs? N/A (test-only change).
h Backward compatible? N/A (test-only change; no settings/format/behavior change).
i Invariants and contracts preserved? N/A (test-only change). The retry uses a unique table per attempt so system.part_log stays isolated; SYSTEM FLUSH LOGS part_log is scoped per the style rule.

Session id: cron:clickhouse-worker-slot-9:20260702-165000

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ — could you review this? It fixes flaky 02669_alter_modify_to_nullable (issue #108845) by retrying the ALTER MODIFY -> Nullable scenario until the best-effort metadata-only optimization (canSkipConversionToNullable) fires, instead of asserting it on a single attempt. The .reference is unchanged and a real regression still fails every attempt, so regression-detection is preserved. Same approach as the sibling 03221_mutation_analyzer_skip_part.sh.

@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a8c6d25]

Summary: ✅


AI Review

Summary

This PR converts 02669_alter_modify_to_nullable from a single-shot .sql test into a bounded retrying .sh test so it waits for the best-effort metadata-only String -> Nullable(String) mutation path instead of failing on a rare scheduling-dependent fallback to full rewrite. I did not find a correctness or regression-coverage issue in the new test logic: the expected .reference stays unchanged, each attempt is isolated by table name inside a per-run random database, and the test still fails if the optimization never fires.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.86% 85.88% +0.01%
Functions 91.47% 91.47% +0.00%
Branches 78.39% 78.44% +0.05%

Changed lines: No C/C++ source files changed — skipping uncovered code analysis.

Newly covered by added/modified tests: 101 line(s), 3 function(s) across 43 file(s) · Details

Top files
  • src/IO/S3/copyS3File.cpp: 10 line(s)
  • src/Functions/if.cpp: 7 line(s)
  • src/Interpreters/MergeTreeTransaction/VersionMetadataOnDisk.cpp: 7 line(s)
  • src/AggregateFunctions/AggregateFunctionQuantileExactInclusive.cpp: 5 line(s)
  • src/Processors/QueryPlan/resolveStorages.cpp: 5 line(s)

Full report

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — a8c6d25

CI fully finished and green: Finish Workflow completed, Mergeable Check + PR success, CH Inc sync passed. No failed checks and no test-level FAIL/ERROR on this head. The rewritten .sh retry-based 02669_alter_modify_to_nullable test passes across all variants.

Session id: cron:our-pr-ci-monitor:20260702-230000

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, Remind me, why it's possible that this operation is not metadata only and how does it depend on the load?

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov it is metadata-only only when the per-part READ_COLUMN can be dropped AND nothing else mutates that part in the same batch. Any of the following makes it a full rewrite instead.

canSkipConversionToNullable (MutateTask.cpp:2970) drops the READ_COLUMN only if, for the part, ALL hold:

  • command is READ_COLUMN to Nullable(T) and the part column is exactly T;
  • the column serialization KindStack is exactly {DEFAULT} (Sparse or any custom serialization disqualifies it);
  • the column has no statistics (column_desc->statistics empty).

Even when the READ_COLUMN is dropped, the clone / metadata-only path (read_rows = 0) is taken only if commands_for_part ends up empty, so isStorageTouchedByMutations returns no_rows (MutateTask.cpp:3264-3290; the interpreter early-returns no_rows on empty commands).

Load dependence: selectPartsToMutate (StorageMergeTree.cpp:1638-1707) coalesces every pending mutation version on a part into one MutateTask command list. On an idle server the standalone MODIFY is the only command, gets dropped, the part is cloned untouched (read_rows = 0). Under load, if that MODIFY is selected together with any other pending non-skippable mutation on the same part, commands_for_part is non-empty and the part is fully rewritten (read_rows = 10000), converting the column through the normal pipeline instead of the clone. Statistics on the column produce the same full rewrite deterministically.

For the test's isolated unique-table scenario I could not reproduce the CI signature in ~8300 runs (isolated, -j16, under concurrent-mutation load and memory pressure). I could force the full rewrite deterministically only by (a) leaving statistics on the column, or (b) explicitly batching a second mutation on the part. So the flake is consistent with the MODIFY being coalesced with another mutation on the loaded runner; I did not pin the exact scheduling trigger. The PR keeps the assertion but retries until the optimization fires (.reference unchanged), so a genuine regression (optimization stops firing) still fails every attempt.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, but every test is run in its own database, so other tests can't insert any mutations to be coalesced.

@alexey-milovidov alexey-milovidov self-assigned this Jul 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov you are right: in an isolated database with a single ALTER, there is nothing to coalesce, so my earlier load/coalescing explanation does not apply here. I retract it.

For this exact scenario the source part is a single part 1_1_1_0, and canSkipConversionToNullable (MutateTask.cpp:2970) has only three gates, all deterministic for these inputs:

  • serialization KindStack == {DEFAULT}: part 1 is all 'foo' (zero empty/default values), ratio 0 < ratio_of_defaults_for_sparse 0.9, so it is always Default (part 2 is mostly '', so it is Sparse and is expected to be rewritten);
  • no statistics: auto_statistics_types = '' and no STATISTICS clause, so column_desc->statistics is empty;
  • single command: one READ_COLUMN, dropped, so commands_for_part is empty and isStorageTouchedByMutations returns no_rows, so the part is cloned (read_rows = 0).

By the code, part 1 should therefore be metadata-only on every run, which matches what I observe: I could not reproduce the flip in ~8300 isolated runs (-j16, under concurrent-mutation load and memory pressure). I could only force the full rewrite by adding statistics or a second mutation on the part, neither of which the test does.

I cannot honestly pin what flips one of those gates on the rare loaded CI run, and I will not guess a mechanism. What is certain is that it is a best-effort optimization detail: query results are always correct, only read_rows for part 1 flips 0 -> 10000. The PR keeps the assertion and retries until the optimization fires (deterministic for these inputs, so it fires within a couple of attempts); a genuine regression (optimization stops firing) fails all 10 attempts. .reference is unchanged.

If you would prefer to pin the exact trigger, I can add a temporary LOG_TRACE/fail-point on the canSkipConversionToNullable == false branch and let it soak on CI to capture which gate flips.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, try to collect and correlate information from the logs of every single test failure we can find.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov I collected and correlated every failure instance (120d, CIDB). There are 6, all with one exact signature; 0 on master.

Signature (byte-identical every time): part 1_1_1_0_3 flips from String / read_rows=0 (metadata-only clone) to Nullable(String) / read_rows=10000 (full rewrite). Part 2 (Sparse) always rewrites. The data columns (20000 10435 ['','bar','foo']) are always correct. Only the part-1 optimization detail flips.

By check (report URLs):

What the logs let me correlate:

  1. 4/6 are Fast test, which applies NO settings randomization and runs each test in its own database. This is the decisive point: it kills the randomized-setting hypothesis and, as you said, there is nothing to coalesce (confirmed).
  2. The 2 randomized instances had different serialization/statistics randomization from each other (amd_debug: auto_statistics_types=countmin,minmax,uniq, nullable_serialization_version=allow_sparse, ratio_of_defaults=1.0; msan: nullable_serialization_version=basic, ratio_of_defaults=0.54), yet produced the identical flip, and both reran green under the SAME settings (181/181 and 8/8). So it is timing/load, not any setting. The test also pins ratio_of_defaults_for_sparse_serialization=0.9 and auto_statistics_types='' in CREATE TABLE, which override the randomized server values, so part-1 serialization kind (Default) and "no statistics" are deterministic regardless of randomization.
  3. For these inputs all three gates of canSkipConversionToNullable are deterministically satisfied for part 1 (all-'foo' -> Default KindStack; exact nested type match; empty statistics; single READ_COLUMN -> commands_for_part empty -> isStorageTouchedByMutations returns no rows -> clone, read_rows=0). The only common factor across all 6 is shared-server load.

What the logs do NOT show: the CIDB rows carry only the test stdout diff + settings, not clickhouse-server.log, so they do not reveal WHICH gate flipped on the failing run (serialization-kind read, statistics, or commands_for_part becoming non-empty). I cannot pin that from the reports alone, and I will not guess.

To pin it empirically I can push a temporary LOG_TRACE on the canSkipConversionToNullable==false (and the is_storage_touched.any_rows_affected for part 1) branch logging part name, kind stack, statistics, and commands_for_part size, then soak on CI until it flips. Want me to do that?

The retry-based test fix stands regardless: it asserts a best-effort optimization, keeps the data assertions, and a real regression (the optimization stops firing, which is deterministic for these inputs) fails all 10 attempts.

@alexey-milovidov

Copy link
Copy Markdown
Member

I looked into this more deeply — correlating every failure of this test over 200 days of CIDB data, the server log of a failing run, and git history. Conclusion: this test was never flaky under load. The failure signature is a canary for real regressions, and rewriting the test to retry would mask exactly what it exists to catch. So I'm closing this PR.

The signature is strictly time-clustered

The exact flip (part 1_1_1_0_3: String / read_rows = 0 → Nullable(String) / read_rows = 10000) appears in CIDB in exactly two clusters:

  • 2026-02-15..16: 4 failures, all on PR Fix ALTER MODIFY COLUMN with statistics #97041 ("Fix ALTER MODIFY COLUMN with statistics"), across 2 SHAs and 4 build types — deterministic, caused by that PR's own pre-merge bug. The test did its job and blocked it.
  • 2026-06-18..30: the 6 failures on unrelated PRs analyzed above. Zero occurrences in the ~6 months before June 18, and zero after June 30 (checked through July 12).

A constant-rate timing race cannot produce months of silence, then 6 hits in 12 days, then silence again. The other historical failures of this test all have unrelated signatures (timeouts, harness internal errors, unrelated exceptions) — the 90/120-day window used above mixed clusters and missed the time correlation.

Mechanism

The server log of the failing run on #108734 (June 29) shows part 1 took the full mutation path (tmp_mut_1_1_1_0_3; MergeTreeSequentialSource: Reading ... 10000 rows ... column s), i.e. canSkipConversionToNullable returned false. As established in this discussion, every gate of that function is deterministic for this test's inputs given a consistent (metadata snapshot, mutation commands, part) triple — so the failing runs must have observed an inconsistent triple.

That this inconsistency is real is proven by #105912 (May 27, Stress test): a SIGSEGV at offset 0x90, i.e. column_desc->statistics dereferenced through a null column_desc at this exact line, without the column ever being dropped. The enabling change is #105917 (merged June 9, present in all six failing trees): it replaced that crash with if (!column_desc) return false, silently converting the same rare inconsistency into a full rewrite — which is precisely this test's flip. That is why the signature could not exist before June 9: the same condition crashed the server instead of producing a test diff.

Why it stopped — and why ~8300 local runs found nothing

The window closed around July 1–3, coinciding with #104822 (merged July 3), which fixes #80648 by holding currently_processing_in_background_mutex across setProperties and mutation registration in StorageMergeTree::alter, so that background threads can only observe a consistent pair of (in-memory metadata, pending mutations) — exactly the drift class needed here (#106963, merged July 1 in the statistics/mutation-mismatch area, is a secondary candidate). The ~8300-run reproduction attempt was made around July 2 — on master that no longer had the bug.

Verdict

The retry rewrite's safety argument — "a real regression still fails every attempt because the decision is deterministic" — is backwards for the only failure modes this test has ever caught: a probabilistic regression (like the June window, roughly 1/400 per run) passes the retry loop on the second attempt every time and becomes invisible. The single-shot assertion is the test's entire value.

The flake is gone from master, so there is nothing to fix in the test. Useful follow-ups instead:

Issue #108845 can be closed with a pointer to this analysis.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Your analysis is correct and I agree with the closure. The single-shot assertion is the whole value of the test: it is a canary for a real, often probabilistic regression, and a retry rewrite would mask a ~1/400 case that happens to pass on attempt 2. Nothing to change in the test.

Two follow-ups:

  1. Observability of the Fix MutateTask nullptr deref on column dropped by concurrent ALTER #105917 fail-open path: Make MutateTask metadata/commands drift observable #110157. The !column_desc branch (metadata/commands drift under concurrent ALTER) now bumps a MutateTaskMetadataDriftDetected profile event and logs a warning, instead of silently degrading the metadata-only conversion into a full rewrite. It is split from the benign "column has statistics" skip. Verified via the existing Cannot start clickhouse-server #105912 failpoint (event = 1 in part_log + system.events, warning logged; 0 on a normal MODIFY).

  2. Cannot start clickhouse-server #105912-class stress SIGSEGV after Fix race between ALTER RENAME COLUMN and merge causing data loss (#80648) #104822 (merged Jul 3): I could not confirm this from CIDB. The checks table only stores per-test stdout + settings, not the server stack, so the null-column_desc deref at offset 0x90 never appears there and I cannot query it directly. What I can show: the deref path itself has been impossible since Fix MutateTask nullptr deref on column dropped by concurrent ALTER #105917 (merged May 27) regardless of Fix race between ALTER RENAME COLUMN and merge causing data loss (#80648) #104822 -- it is null-guarded, so the crash cannot recur. Fix race between ALTER RENAME COLUMN and merge causing data loss (#80648) #104822 is what removed the drift that fed it. So the SIGSEGV cannot happen; the drift that used to reach that guard should also be gone after Fix race between ALTER RENAME COLUMN and merge causing data loss (#80648) #104822. If you have a way to point me at the stress crash logs (not in CIDB), I can correlate the exact before/after.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Flaky test: 02669_alter_modify_to_nullable (ALTER MODIFY -> Nullable metadata-only optimization falls back to full rewrite)

3 participants