Skip to content

Fix a crash on ALTER TABLE ... MATERIALIZE TTL over a non-MergeTree table - #117181

Merged
qoega merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-materialize-ttl-alias-null-deref
Aug 31, 2026
Merged

qoega merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-materialize-ttl-alias-null-deref

Conversation

@groeneai

@groeneai groeneai commented Aug 30, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #117327
Related: #115287

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 a crash when executing ALTER TABLE ... MATERIALIZE TTL on a table that is not a MergeTree but whose metadata carries a TTL. Two engines can be in that state: Alias, when its target has a TTL, and MaterializedView, when it declares a TTL on a column of its own. Closes #117327.

Description

ALTER TABLE ... MATERIALIZE TTL terminated the server with SIGSEGV. Reachable with default settings.

Found by the AST fuzzer:

Root cause. MutationsInterpreter::Source::getMergeTreeData is a dynamic_cast, so it returns nullptr for any storage that is not a MergeTreeData. The MATERIALIZE_TTL arm dereferenced it as the left operand of the &&, so hasOnlyRowsTTL could not short-circuit it and a column TTL alone was enough. Reading storage_settings off it then makes MultiVersion::get lock a mutex at an invalid address. The fault is on the mutation validation path, before the mutation is planned.

Change. One null term, leftmost so it short-circuits, matching the sibling guards in this function. It sits at the point of use, so it covers whatever reaches the line, not a list of engines. Two reach it today: an Alias table, which returns its target's metadata, and a materialized view declaring a TTL on a column of its own.

For a non-MergeTree source the flag now reads false, which is not observable. The stages built on that path are discarded, and the real mutation is planned separately from the target's MergeTreeData, where the setting is read correctly. On a ttl_only_drop_parts rows-TTL table, a direct mutation and one through an alias give identical rows, sums and active parts.

Validation. New stateless test, one arm per affected storage plus a negative arm that still raises INCORRECT_QUERY. The oracle is a completed mutation in system.mutations, which a background TTL merge cannot produce; per-arm sensitivity was checked by deleting each statement in turn. The crash appears and disappears across the change on Build-ID-verified binaries, 50 randomized runs pass, and the materialize_ttl, storage_alias and modify_comment families all pass.


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

Version info

  • Merged into: 26.9.1.445 (included in 26.9 and later)

…able

`MutationsInterpreter::Source::getMergeTreeData` is a `dynamic_cast`, so it
returns `nullptr` for any storage that is not a `MergeTreeData`. The
`MATERIALIZE TTL` arm dereferenced it with no null check, and the dereference
was the left operand of the `&&`, so `hasOnlyRowsTTL` could not short-circuit
it: a column TTL alone was enough. Reading `storage_settings` off the null
pointer makes `MultiVersion::get` lock a `std::mutex` at an invalid address.
The fault is on the `validate` path, with `dry_run` true, and needs no
non-default setting.

Two storages get past the `hasAnyTTL` check at `:1410` while not being a
`MergeTreeData`, and both were measured to fault at the same frame:

* `StorageAlias`, which forwards `checkMutationIsPossible` to its target
  (`StorageAlias.h:105`) and returns the target's metadata verbatim
  (`StorageAlias.h:124-131`).
* `StorageMaterializedView`, which forwards the same check
  (`StorageMaterializedView.cpp:867-871`) and can carry a TTL on a column of
  its own declaration. `AlterCommands::apply` re-derives the column TTL map
  from the column list on any alter (`AlterCommands.cpp:1806-1826`) and the
  view persists it (`StorageMaterializedView.cpp:803` and `:824`).

The view is not reached through its target's TTL: `getInMemoryMetadataPtr`
grafts only the target's virtual columns onto the view's own metadata
(`StorageMaterializedView.cpp:360-381`), so the target's TTL is invisible
through it. It is reached through the view's own column TTL instead.
`StorageMemory` cannot hold a TTL, and `StorageEmbeddedRocksDB` accepts only
UPDATE and DELETE. The guard sits at the point of use, so it covers any storage
that reaches the line rather than these two specifically.

Found by the AST fuzzer: check "AST fuzzer (amd_debug, targeted)", STID
2809-3ce4, `Address: 0x4c8`.

Every other site in this file that can see a null `MergeTreeData` already
handled it. Line 1415 was the only outlier, and the added term has the same
shape as the guard at the `index_granularity_bytes` site.

Defaulting the flag to false for a non-`MergeTree` source changes nothing
observable. The stages computed on the `validate` path are discarded, and the
real mutation is planned by a fresh `MutationsInterpreter` built from the
`MergeTreeData &` constructor, where the setting is read correctly. Comparing a
direct mutation against one through an alias on a `ttl_only_drop_parts`
rows-TTL table gives identical rows, sums and active parts.

The test asserts one completed mutation per storage rather than the value the
TTL produces. An expired TTL is also applied by a background TTL merge, which
creates no mutation, so asserting the value would hold even if the mutation
never ran.

No comment is added at the guard: the sibling guards in this function carry
none, and the reasoning belongs here.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Aug 30, 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). Two review rounds with one
fix round between them: round 1 produced 2 findings, round 2 produced 0 on the same change
map. Four further findings are mine, from a cold read done before seeing the author's
evidence.

# Sev Finding Verdict Evidence / action
1 ⚠️ The Alias engine is not the only storage that can reach the faulting line, so the original "only" claim was unproven (mine) AGREE, fixed @ d24d8c8 Traced a second route: a materialized view can declare a TTL on a column of its own, which AlterCommands::apply turns into metadata on any later alter. Then measured it: the same SIGSEGV, same frames, and rc=0 after the fix. A second test arm covers it and the changelog entry names both engines. CREATE MATERIALIZED VIEW reaches this state because StorageFactory.cpp:104-107 routes views past the supports_ttl gate at :183-186.
2 ⚠️ The positive arm asserted the value the TTL produces, which does not prove the mutation ran AGREE, fixed @ d24d8c8 Confirmed by measurement, and worse than claimed: with no ALTER at all the value still changes within seconds, because a background TTL merge applies an expired TTL and creates no mutation. The oracle is now one completed mutation per storage in system.mutations, which that merge cannot produce, and per-arm sensitivity was checked by deleting each statement in turn.
3 ⚠️ The category should be Critical Bug Fix (crash, data loss, RBAC) DISAGREE That category auto-adds pr-must-backport (ci/jobs/scripts/workflow_hooks/pr_labels_and_category.py:99-100 and :266-269), so selecting it would unilaterally trigger release-branch backports. That is a maintainer decision, so I am leaving the category as Bug Fix and will ask for the backport label in this thread once this is merged.
4 💡 No visible provenance link in the rendered body (mine) AGREE, fixed The upstream Closes:/Related: block is an HTML comment and does not render, so a visible Related: line was added.
5 💡 The scope paragraph proved completeness by a census that does not hold (mine) AGREE, fixed Rewritten to claim no completeness by inference. It leads with the guard being at the point of use, so it covers whatever reaches the line, and only then names the two storages that reach it today, both of which were executed rather than argued.
6 💡 The test file name says storage_alias but the file now also covers a materialized view (mine) AGREE, not blocking Noted rather than renamed: the file had already passed 50 randomized runs under that name, and its leading comment describes both carriers.

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

Session id: cron:clickhouse-review-slot-9:20260830-180300

@clickhouse-gh clickhouse-gh Bot closed this Aug 30, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [be876bc]

Summary: ✅


AI Review

Summary

This PR fixes the null dereference in MutationsInterpreter::prepare when ALTER TABLE ... MATERIALIZE TTL is validated against non-MergeTree wrappers such as Alias and MaterializedView, and the new stateless test covers both currently reachable carriers. I did not find a remaining correctness issue in the code change itself; the only outstanding point is PR metadata severity.

Findings

💡 Nits

  • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/117181#issuecomment-5470518717] The PR template's Changelog category should be Critical Bug Fix (crash, data loss, RBAC), not Bug Fix. This fixes a user-triggerable server SIGSEGV on default settings in an official stable release, which matches the template's critical category even if backport scope is decided separately.
Final Verdict

Code change looks correct. No new inline blockers or majors from the current diff; only the changelog-category nit above remains.

LLVM Coverage Report

Measured on commit be876bc.

Metric Baseline Current Δ
Lines 88.60% 88.60% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 80.90% 80.90% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% and not a rate, on both carriers. Alias: CREATE TABLE t (d Date, v UInt64 TTL d + INTERVAL 1 DAY) ENGINE = MergeTree ORDER BY tuple(); CREATE TABLE a ENGINE = Alias(t); INSERT INTO t VALUES ('2000-01-01', 42); ALTER TABLE a MATERIALIZE TTL SETTINGS mutations_sync = 2;. View: the same MATERIALIZE TTL on a materialized view declaring v UInt64 TTL d + INTERVAL 1 DAY in its own column list, after any alter that re-applies that column list. Both give SIGSEGV (rc 139) on a pristine build, in clickhouse local and against a server.
b Root cause explained? Yes. Source::getMergeTreeData is a dynamic_cast, so it yields nullptr for a non-MergeTreeData storage. The MATERIALIZE_TTL arm dereferenced it unguarded, as the left operand of the &&, so hasOnlyRowsTTL could not short-circuit it. Reading storage_settings off null makes MultiVersion::get lock a mutex at an invalid address. A non-MergeTreeData storage gets past the hasAnyTTL check at :1411 two ways: by returning another table's metadata (Alias), or by carrying a TTL on a column of its own (materialized view).
c Fix matches root cause? Yes. The defect is the missing guard itself, not a symptom: the accessor is nullable by construction and every other consumer in the file already handles null. The added term is the same shape as the in-file precedent at :1244.
d Test intent preserved / new tests added? New stateless test, three arms: one per carrier, plus an alias over a TTL-less target still raising INCORRECT_QUERY so the fix cannot silently swallow the :1411 guard. The oracle is one completed mutation per carrier in system.mutations. It deliberately does not assert the value the TTL produces: a background TTL merge produces that value with no mutation at all, which I measured, so such an assertion would hold even if the mutation never ran. Sensitivity is proved rather than assumed: deleting either MATERIALIZE TTL, or the alter the view arm depends on, makes the test fail, each in its own line.
e Both directions demonstrated? Yes, on Build-ID-verified binaries (d4efb005... before, 1159855474... after), for both carriers. Before: SIGSEGV at MutationsInterpreter.cpp:1415, getSettings (this=0x0), dry_run=true, Address: 0x4c8 identical to the fuzzer report; the final test run against a pre-fix server ends server died. After: the test passes through the real runner, 50 randomized runs green.
f Fix is general across code paths? Yes, both dimensions swept. In this file every site that can see a null MergeTreeData already handled it and :1415 was the sole outlier; the accessor has no consumer outside its translation unit, and the same-named ReadFromMergeTree::getMergeTreeData returns a reference that cannot be null. Across storages, ten override checkMutationIsPossible and two of them can reach the line, both now covered by a test arm. The guard is unconditional and sits at the point of use, so it covers any storage reaching the line rather than an enumerated list.
g Fix generalizes across inputs (params/datatypes/wrappers)? The null is a storage pointer, not a column value, so Nullable / LowCardinality / Array / Map / Const wrappers are irrelevant by construction. The input dimension that matters is which storage, covered in (f). I also exercised the settings dimension: ttl_only_drop_parts on and off, and rows TTL versus column TTL.
h Backward compatible? (maintainer-approved exception only) Yes, trivially. No setting, default, format or on-disk change, so no SettingsChangesHistory.cpp entry and no versioning. The only behaviour delta is that a query which used to terminate the server now succeeds.
i Invariants and contracts preserved? Yes. The invariant restored is that Source::getMergeTreeData is nullable and every consumer must handle null. suitable_for_ttl_optimization is read once, and for every MergeTree caller the new term is true by construction so the value is unchanged, which I verified by comparing a direct mutation against one through an alias on the ttl_only_drop_parts shape (identical rows, sums and active parts). The false default is also the fail-safe direction for validation, since it routes to the dependency branches that analyse more expressions than the recalculate-only branch. No lock, ownership or lifetime is touched.

Session id: cron:clickhouse-impl-slot-5:20260830-173200

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 30, 2026
@PedroTadim PedroTadim self-assigned this Aug 30, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @scanhex12 @davenger, could you review this? MutationsInterpreter::Source::getMergeTreeData is a dynamic_cast, and the MATERIALIZE TTL arm dereferenced it as the left operand of the &&, so ALTER TABLE ... MATERIALIZE TTL over an Alias table or a materialized view whose metadata carries a TTL terminated the server with SIGSEGV on the mutation validation path.

@clickhouse-gh

clickhouse-gh Bot commented Aug 30, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d24d8c89e with master d469feea5 (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

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

Job report

@qoega qoega self-assigned this Aug 31, 2026
@qoega
qoega added this pull request to the merge queue Aug 31, 2026
Merged via the queue into ClickHouse:master with commit c516e11 Aug 31, 2026
175 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 31, 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 groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect 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.

ALTER TABLE <alias> MATERIALIZE TTL on the experimental Alias table engine SEGVs via MergeTreeData::getSettings null-deref

5 participants