Skip to content

Fix lightweight updates lost and wrong values when reading with apply_mutations_on_fly over a pending MODIFY COLUMN - #127372

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/on-fly-patches-pending-modify
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/on-fly-patches-pending-modify

Conversation

@groeneai

@groeneai groeneai commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #126698

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):

Fixed SELECT with apply_mutations_on_fly = 1 on a table with a pending ALTER MODIFY COLUMN: lightweight UPDATEs made before the MODIFY were not applied, a lightweight UPDATE made after it could crash the server when a pending ALTER UPDATE overwrites the same column, and an ALTER UPDATE queued after the MODIFY returned wrong values for the rows it does not update.

Description

On 26.8.21.12 and 26.3.33.24, a SELECT with apply_mutations_on_fly = 1 over a pending ALTER MODIFY COLUMN drops lightweight UPDATEs made before the MODIFY, crashes (SIGSEGV) when one made after it targets a column a pending ALTER UPDATE overwrites, and returns wrong values when an ALTER UPDATE queued after the MODIFY reads the modified column:

CREATE TABLE t (id UInt64, a String, b UInt64) ENGINE = MergeTree ORDER BY id
SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1;
INSERT INTO t SELECT number, toString(number), 0 FROM numbers(10);
SYSTEM STOP MERGES t;
ALTER TABLE t UPDATE b = length(a) + 100 WHERE 1;
UPDATE t SET a = 'zz' WHERE id < 5;
ALTER TABLE t MODIFY COLUMN a LowCardinality(String) SETTINGS alter_sync = 0;
SELECT a, b FROM t ORDER BY id SETTINGS apply_mutations_on_fly = 1; -- no 'zz'

Root cause, in MergeTreeReadersChain: a column the on-fly chain overwrites stays in its on-disk type until the step that overwrites it, unless a step reads it first. That check skipped the steps queued after the MODIFY, so their ALTER UPDATE read the unconverted column. Patches whose version falls between two steps were applied only if newer than the MODIFY, and also into still-unconverted columns.

Change: the check covers every on-fly mutation step. Between steps, patches are applied to the columns in their requested type and skipped for the unconverted ones and for those the next step that references them overwrites or recomputes without reading them. The v1 patch path applies only the columns each patch group was selected for, as the v2 path does; this is the change of #126698, included verbatim.

Validation: the new test compares every on-fly read with the same read after the mutations are materialized. It fails on master (wrong rows, then an abort) and passes 50/50 with randomized settings; related tests show no new failures.


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

groeneai and others added 2 commits October 22, 2026 10:01
…pending MODIFY COLUMN

With `apply_mutations_on_fly = 1` and a pending `ALTER MODIFY COLUMN`, a column the on-fly
chain overwrites stays in its on-disk type until the step that overwrites it, unless a step
reads it first (`collectColumnsConsumedByChainActions`). Two defects in `MergeTreeReadersChain`:

- The consume scan skipped every step with `perform_alter_conversions`, which includes the
  on-fly steps queued after the `MODIFY`. Their `if(cond, expr, col)` keep-old fallback then read
  `col` unconverted: a debug abort in `FunctionIf`, wrong values on release.
- `applyPatchesAfterReader` applied only `AfterConversions` patches between steps, so every
  lightweight update older than the `MODIFY` (`BeforeConversions`) was dropped there, and it
  wrote newer patches into still-unconverted columns (abort in `updateFrom`, SIGSEGV on release).

Now the scan covers every on-fly mutation step (`mutation_version` set) with the chain-wide
overwritten set, so a skip-set column stays unconverted only when its first reference in the
whole chain is a constant-true overwrite. The readers chain precomputes, per step, the columns
still unconverted after it; `applyPatchesAfterReader` drops their patch entries (a later step
overwrites them on every row) and applies all orders for the rest, casting an older patch to
the requested type like a newer one. The v1 legacy path applies only the columns each patch
group was selected for, as the v2 `MergeOnKey` path already does; without it a v1 patch of a
converted and an unconverted column would write the unconverted one too. This is the change of
ClickHouse#126698, taken verbatim so that the two PRs merge in either order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fold the scanned-steps note into one line of the collectColumnsConsumedByChainActions doc and drop the collectColumnsUnconvertedAfterStep doc that repeats the member comment.

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

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

Pre-publication review by an independent model (engine: codex; 2 rounds, 1 finding) and an own cold review (2 rounds, 3 findings, 1 withdrawn).

# Sev Finding Verdict Evidence / action
1 ⚠️ The v1 updated_columns restriction duplicated #126698 in a different shape (applyPatchesLegacy.cpp) AGREE, fixed #126698's three hunks taken verbatim, so both PRs merge in either order
2 💡 Changelog category should be Critical Bug Fix DISAGREE That category is chosen only on a maintainer's request; Bug Fix (wrong results and a crash on 26.8 and 26.3)
3 💡 PR text did not name #126698 AGREE, fixed Related: line and one sentence in the description

Re-review of the fixed tree: 0 findings from either review.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-self-slot-58:20261022-100400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Plain SELECTs on a 10-row MergeTree table with merges stopped, no timing: the snippet in the description, plus one probe per shape (lost patch, post-MODIFY read, post-MODIFY patch on an overwritten column).
b Root cause explained? The skip-set consume scan ignored on-fly steps queued after the MODIFY, so their if fallback read the column in its on-disk type. applyPatchesAfterReader accepted only AfterConversions patches, so every patch older than the MODIFY was dropped between steps, and it wrote newer patches into still-unconverted columns.
c Fix matches root cause? Yes. The scan covers every on-fly mutation step; the after-reader application knows per step which columns are still unconverted and skips only those (their values are overwritten later on every row). No guard at the crash site, no setting.
d Test intent preserved / new tests added? New SQL test, 12 cases incl. a control, each on-fly read compared with the materialized read. No existing test changed.
e Both directions demonstrated? Master: wrong rows, then a server abort in applyPatchesAfterReader (updateFrom <- applyPatchesIndices). Fix: passes, 50/50 with randomized settings and MergeTree settings.
f Fix is general across code paths? Covers every after-reader window including the last; v1 Merge/Join patches (now restricted to the group's updated_columns) and v2 MergeOnKey (already restricted). Read-time application is unchanged. Merges and mutations build no on-fly steps, so they are unaffected.
g Fix generalizes across inputs (params/datatypes/wrappers)? String -> LowCardinality, Nullable, UInt64; Array and Map with LowCardinality values; UInt32 -> UInt64; patch format v1 and v2; an overwrite of all rows and of some rows. All give the materialized result.
h Backward compatible? (maintainer-approved exception only) Yes. No setting and no format change; only on-fly read results change, to match the materialized ones.
i Invariants and contracts preserved? After every step a column either has its requested type, or is unconverted and overwritten on every row by a later step, so its patches are discarded. Block structure and column sizes are unchanged (patches update values in place).

Session id: cron:clickhouse-impl-self-slot-57:20261022-064600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Algunenano @CurtizJ, could you review this and add the can be tested label so CI runs? With apply_mutations_on_fly = 1 over a pending MODIFY COLUMN, the skip-set consume scan now also covers the on-fly steps queued after the MODIFY, and applyPatchesAfterReader applies patches between steps except into columns still in their on-disk type, so lightweight updates older than the MODIFY are no longer lost.

@clickhouse-gh

clickhouse-gh Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9c98b41]

Summary: ✅


AI Review

Summary

Reviewed head 9c98b41ff525988de140190a874ab244f3f1f184. The PR preserves lightweight updates between on-fly mutation steps around a pending MODIFY COLUMN, including subsequent overwrites and recomputed MATERIALIZED columns, and restricts legacy patches to their selected columns. Both prior inline findings are fixed; no new actionable findings. The new regression test and the related v1 added-column regression match their references, and a mixed legacy Join/Merge fixture matches its materialized result. Broader probes also reproduce existing stale subcolumn results and NOT_FOUND_COLUMN_IN_BLOCK when mixing parent and subcolumn reads; that behavior is tracked separately in #118718 and #122372.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). labels Oct 22, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 22, 2026
…ding it

After an on-fly UPDATE overwrites a column, the column has its post-MODIFY
type, so a lightweight UPDATE older than the pending MODIFY that falls between
this step and a later step was cast to that type before it was applied. When
the later step overwrites the column on every row before reading it, the
patched value is discarded anyway, and materializing the mutations never
converts it; the on-fly read failed with CANNOT_PARSE_TEXT instead (for
example `UPDATE c = 'bad'` between `ALTER UPDATE c = '100'` and
`ALTER UPDATE c = '200'` before `MODIFY COLUMN c UInt64`).

The consume scan now returns, for every step, the columns it consumes and the
columns it overwrites. From the same first-reference rule that decides whether
an on-disk value is converted, a backward pass finds the columns whose next
referencing step overwrites them without reading them, and the after-reader
application drops their patches, as it already does for columns still in their
on-disk type. A later partial overwrite reads the old value for unmatched rows,
so such a patch is still converted, as the on-disk value is.

Reported by the automated review on the PR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
An on-fly ALTER UPDATE also emits a stage that recomputes every MATERIALIZED
column depending on its targets, but only the explicit UPDATE targets were
treated as overwritten when deciding which patches a later step discards. So a
lightweight UPDATE older than a pending MODIFY of such a column, falling
between two on-fly UPDATEs of its source, was still cast to the post-MODIFY
type after the first one, and the read failed with CANNOT_PARSE_TEXT although
the second UPDATE recomputes the value before the MODIFY needs it (for example
`m String MATERIALIZED c`, `UPDATE c = 'bad'` between `ALTER UPDATE c = '100'`
and `ALTER UPDATE c = '200'`, then `MODIFY COLUMN m UInt64`).

The consume scan now also records, for every step, the non-passthrough outputs
that are not UPDATE targets, and the backward pass treats them like overwritten
columns. The explicit-target set used to decide on-disk conversions is
unchanged.

Reported by the automated review on the PR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9c98b41ff with master 573bbb2a8 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

14 object files changed (+25.95 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeReadersChain.cpp.o 315.61 KiB 333.61 KiB +17.99 KiB (+5.70%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4ea1d73

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Cannot start clickhouse-server, Server failed to start not from this diff: a table left by the previous release's tests (test_cache_thread_pool) has a small SLRU cache disk that the check added by merged #125817 now rejects while loading metadata (Code: 36 ... must not exceed the size of each SLRU queue); seen on 13 other PRs since 2026-10-22 21:20 UTC a fix task is created (fixing-PR link to follow on this PR)
Sync - CH Inc sync (private, not actionable by me)

Mergeable Check and PR are the praktika aggregators of the rows above.

Session id: cron:our-pr-ci-monitor:20261023-050052

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PRs for the Upgrade check (amd_release) failure (a small SLRU cache disk left by the previous release's tests): #127566 (26.9) and #127567 (26.10).

groeneai and others added 2 commits November 6, 2026 13:38
…ches-pending-modify

# Conflicts:
#	src/Storages/MergeTree/MergeTreeReadersChain.cpp
#	src/Storages/MergeTree/MergeTreeReadersChain.h

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-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants