Skip to content

Fix a crash reading a table with lightweight updates when a sorting key column has a DEFAULT - #119540

Merged
tuanpach merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-lwu-sort-key-column-default-null-deref
Sep 14, 2026
Merged

tuanpach merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-lwu-sort-key-column-default-null-deref

Conversation

@groeneai

@groeneai groeneai commented Sep 11, 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 a crash when reading a table with active lightweight updates whose sorting key contains a column that is missing in the data part and has a DEFAULT expression.

Description

A SELECT on a table with active lightweight updates crashes with a SIGSEGV when the sorting key contains a column that is missing in the data part and has a DEFAULT (or MATERIALIZED) expression.

Such a column is deliberately a null placeholder until the missing-defaults pass fills it. executeSortingKeyExpressions materializes the patch key columns for the first reader only, while injectPatchColumns leaves them requested on later steps as well. After PREWHERE the column is null again, addPatchVirtuals keeps the placeholder because its guard tests presence rather than materialization, and getBlockWithSortingKey dereferenced it unconditionally.

The correct, normalized keys are already cached row-aligned in ReadResult::columns_for_patches, which the caller already holds. It is now threaded into getBlockWithSortingKey as a dedicated key_columns block, and every sorting-key column is taken from it. No block is mutated, so output values are unchanged; only which column the key comparison reads changes. That cached key is also the right identity: the patch part's key is computed from the source snapshot before the update's SET is applied, and so is the cached one.

Reproduced deterministically on master and verified in both directions with a mutation check, expression sort keys included. No result changes across 112 lightweight-update and patch-part tests; 100/100 runs of the extended test.

One narrow shape is left alone. When a sorting-key column's DEFAULT reads a column that the same update writes and the first read step does not read, the cached key cannot match the patch part's key, so the patch silently does not apply where the query previously aborted. That lightweight-vs-heavy disagreement is pre-existing on master and is the class #118630 addresses.

Measured base vs fix for that shape

Sorting-key column b UInt64 DEFAULT vnum + 1000, where the same lightweight UPDATE also writes vnum and a second column w that is missing from the base part. Twin table mutated with the equivalent ALTER TABLE ... UPDATE.

base, single-step read:  lwu -> w patched, b = 1001    heavy -> b = 1007
base, multi-step read:   crash (the bug this PR fixes)
fix,  single-step read:  identical to base
fix,  multi-step read:   no crash, patch not applied (w = 'wdef', vnum = 1, b = 1000)

Affected releases: 26.8.x.

Related: the first-reader half of this fix, commit 72d4b5c97517f1f10334a8d9bcd54a5fa59813b4.
CI report for the sighting: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=117817&sha=80365e1c3236fc29de7cfe28baa5138fbd8f7a17&name_0=PR


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

Version info

  • Merged into: 26.9.1.1440 (included in 26.9 and later)
  • Backported to: 26.8.4.10

A SELECT on a table with active lightweight updates crashed with a SIGSEGV
when the sorting key contained a column that is missing in the data part and
has a DEFAULT or MATERIALIZED expression.

Such a column is deliberately a null ColumnPtr at that stage: fillMissingColumns
leaves it null so that evaluateMissingDefaults can compute it later.
executeSortingKeyExpressions materializes the sort-key columns of MergeOnKey
patches, but it runs from readPatches for the first reader only, while
injectPatchColumns adds the patch key columns to the first read step without
removing them from the later ones. On a read step after PREWHERE the column is
therefore requested again and left null, addPatchVirtuals declines to replace it
because its guard tests whether the name is present rather than whether the
element is materialized, and getBlockWithSortingKey then called
convertToFullColumnIfConst through the null pointer.

The correct, already normalized and row-aligned comparison keys are cached in
ReadResult::columns_for_patches, and both applyPatches call sites already pass
that block down as additional_columns. Thread it into getBlockWithSortingKey as
a dedicated key_columns block and take every sorting-key column from it, so the
per-step path and the after-reader path are both covered. getByName is used
without a fallback: a silent fallback to the result block would restore exactly
the behaviour this removes for any future path where the cache is not populated.

No block is mutated, so output values are unchanged on every path; only which
column the key comparison reads changes. That cached key is also the correct
identity rather than merely a non-null one. A patch part's key columns are
written by the patch mutation as plain READ_COLUMN commands with
recalculate_dependencies_of_updated_columns = false, so they hold the values
from the source snapshot, before that same update's SET was applied; the read
side's cached key is likewise evaluated before any patch is applied. Reading the
key back from the result block after evaluateMissingDefaults could instead
compare against a default computed from already patched inputs.

Related: 72d4b5c

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 11, 2026
@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 gate findings plus 2 from my own
cold review of the resulting code). Bounded: 4 design rounds before implementation, 1 full
post-implementation pass, 0 fix rounds.

# Sev Finding Verdict Evidence / action
1 ❌ Taking the key from the cache unconditionally can silently skip a lightweight update when a missing sorting-key column's DEFAULT reads a column absent from the first read step (applyPatches.cpp:316-323) DISAGREE Mechanism confirmed and measured, severity and ownership refuted. The mismatching key value is computed one layer above this diff and is unchanged by it: injectPatchColumns (MergeTreeBlockReadUtils.cpp:454-464) injects only the key columns, not the transitive DEFAULT dependency closure, and inplaceBlockConversions.cpp:139-155 substitutes the absent dependency's type default. 72d4b5c9 then writes that key permanently into ReadResult::columns (MergeTreeReadersChain.cpp:644-648), so it exists with or without this change. Reverting this diff restores the SIGSEGV, not a correct result: the null placeholder is dereferenced at the AfterConversions pass before any pass could reach a correctly evaluated key. This diff chooses which side supplies the key, and both sides are pre-SET by construction (MergeTreeData.cpp:13006-13031, :13038). The suggested remedy edits MergeTreeBlockReadUtils.cpp:454-464, which is a hunk of #118630, so it belongs there. Disclosed in ### Description with the measured table
2 ⚠️ The residual disclosure understated the change: it described only the pre-existing lightweight-versus-heavy disagreement, not the observable transition AGREE, fixed in the PR body The body now states plainly that in that shape the patch silently does not apply where the query previously aborted, and carries the measured base-versus-fix table
3 💡 The category should be Critical Bug Fix because the failure is a SIGSEGV DISAGREE Critical Bug Fix is not selected proactively; it is used when a maintainer asks for it, and no maintainer has asked here. The surviving category line is byte-identical to the current upstream template

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Noted, not blocking: addPatchVirtuals keeps its presence guard rather than a materialization
guard. Repairing it there would overlay a slot that evaluateMissingDefaults legitimately owns and
would change output defaults, so the key comparison is routed around it instead.

Session id: cron:clickhouse-review-slot-8:20260911-193400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A single clickhouse local run of the extended 04626_lwu_sort_key_column_with_default crashes 100% of the time at base master; it is not a rate. The reddening query is SELECT sum(b = a + 100), countIf(v = 'bar') FROM t_lwu_key_column_default PREWHERE a >= 50.
b Root cause explained? Yes. A sorting-key column missing in the part with a DEFAULT is left as a null placeholder by fillMissingColumns. executeSortingKeyExpressions materializes the patch key columns for the first reader only, while injectPatchColumns also leaves the column requested on later steps; on a step after PREWHERE it is null again, addPatchVirtuals keeps it because its guard tests presence rather than materialization, and getBlockWithSortingKey dereferenced it unconditionally at applyPatches.cpp:328. The local stack matches the CI stack frame for frame, on the AfterConversions pass of a later chain step.
c Fix matches root cause? Yes. The key is taken from ReadResult::columns_for_patches, the row-aligned cache that exists for exactly this purpose, instead of from the result block. No null guard, no skipped column, no widened bound, no no-random-* tag. getByName throws rather than falling back silently.
d Test intent preserved / new tests added? Yes. The existing assertions in 04626_lwu_sort_key_column_with_default are untouched; the change adds one query and one reference line to that file rather than a new test file. A mutation check confirms the new query fails when the fixed line is reverted.
e Both directions demonstrated? Yes. Base build: Assertion 'px != 0' failed in boost::intrusive_ptr<const DB::IColumn>::operator-> (rc 134). With the fix: 5000 5000 and the file passes. Mutant (key read back from the result block): crashes again at the same site. All three arms have distinct verified Build IDs.
f Fix is general across code paths? Yes. Both applyPatches call sites already pass result.columns_for_patches, so the per-step path and the after-reader path are fixed by the same change. The legacy Merge/Join modes key on _part/_part_offset/_block_number/_block_offset, none of which can carry a default expression. The merge path was confirmed by inspection to build a single range reader (moveAllColumnsFromPrewhere), so the later-step configuration cannot arise there. Fixed at the key supply, not guarded at the crash site.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. MATERIALIZED reproduces the same crash at base and passes with the fix. An expression sort key (ORDER BY (a, cityHash64(b))) was checked as a negative control and raises no NOT_FOUND_COLUMN_IN_BLOCK before or after. Deferred updated columns, and key defaults reading a non-updated column, were measured identical on both arms. The normalization loop still strips Const and LowCardinality on every key column.
h Backward compatible? (maintainer-approved exception only) Yes. No new setting, no default change, no format or version change, so no SettingsChangesHistory.cpp entry is needed. The signature change is internal and has a single caller.
i Invariants and contracts preserved? Yes. No block is mutated, so block structure, row counts and output columns are unchanged on every path, including error and early-return paths. Row alignment between the key cache and the result block is enforced by ReadResult::checkInternalConsistency, which throws on every filter application rather than asserting. The _block_number / _block_offset inserts still read the result block, where they are guaranteed present and non-null.

Session id: cron:clickhouse-impl-slot-4:20260911-180400

@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [769e4d5]

Summary: ✅


AI Review

Summary

This PR switches MergeOnKey patch comparisons to the precomputed ReadResult::columns_for_patches cache instead of the mutable result block, which closes the null dereference on multi-step reads when a missing sort-key column is seen as a placeholder again after PREWHERE. I did not find an unresolved correctness, testing, or PR-metadata issue in the current diff.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 769e4d5.

Metric Baseline Current Δ
Lines 89.00% 88.90% -0.10%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

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

Full report · Diff report

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

Copy link
Copy Markdown
Collaborator Author

cc @Michicosun @Algunenano, could you review this? A sorting-key column that is missing in the part and has a DEFAULT is deliberately left as a null placeholder, and on a read step after PREWHERE the MergeOnKey patch key comparison dereferenced that placeholder; the key is now taken from the row-aligned ReadResult::columns_for_patches cache, which is also the pre-SET identity the patch part is actually sorted by.

@clickhouse-gh clickhouse-gh Bot added the comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). label Sep 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 769e4d5f9 with master dc740cbb2 (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.

Compile time of recompiled translation units

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

Job report

@tuanpach tuanpach self-assigned this Sep 14, 2026
@tuanpach
tuanpach added this pull request to the merge queue Sep 14, 2026
Merged via the queue into ClickHouse:master with commit 17d2f0a Sep 14, 2026
174 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 14, 2026
@PedroTadim

Copy link
Copy Markdown
Member

Backporting to 26.8 to fix SEGV

@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 14, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 14, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 14, 2026
…t updates when a sorting key column has a DEFAULT
clickhouse-gh Bot added a commit that referenced this pull request Sep 14, 2026
Backport #119540 to 26.8: Fix a crash reading a table with lightweight updates when a sorting key column has a DEFAULT
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @tuanpach — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Verified the finding, and it is not caused by this PR. I built current master with and without this PR's source change reverted (build ids ff03c841... and f2f0fabb...); the wrong result is byte-identical on both. This PR does not touch MergeTreeBlockReadUtils.cpp, and git log -L attributes the code at fault to the original Lightweight Updates v2 work (a5327c66fe8c0, 7c446b93c11cb). So nothing is needed here or on the 26.8 backport.

The defect itself does reproduce on master and is a silent wrong result, so I am picking it up. Evidence and fix direction are in #120401.

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). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants