Skip to content

Fix TRUNCATE of an Alias table over a MergeTree blocking on concurrent readers - #119105

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-alias-truncate-lock-classification
Sep 19, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-alias-truncate-lock-classification

Conversation

@groeneai

@groeneai groeneai commented Sep 9, 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):

Fixed TRUNCATE TABLE of an Alias table whose target is a MergeTree failing with DEADLOCK_AVOIDED when the alias is being read concurrently, while the same statement against the target table succeeds immediately. The lock for TRUNCATE is now chosen and taken on the table that executes the truncate, so an Alias follows its target's engine.

Description

Reported by a review bot on #113634: #113634 (comment)

TRUNCATE of a MergeTree is exempt from the table's exclusive lock, so it does not wait for readers; InterpreterDropQuery decided that with dynamic_pointer_cast<MergeTreeData> on the catalog object. A StorageAlias holds only its target's name, so the cast always failed and the alias's own exclusive drop_lock was taken. A reader of the alias holds that same object's share lock, since lockForShare/lockExclusively are non-virtual. So TRUNCATE TABLE <alias> waited for the reader and then failed with Code: 473 DEADLOCK_AVOIDED, leaving the data in place.

The same decision was wrong twice:

  • The interpreter now asks table->isMergeTree(), the virtual StorageAlias already answers by resolving its target. It has two overrides tree-wide, so for every other storage this is the old cast, and it resolves with tryGetTargetTable(), so a missing or not-yet-loaded target answers false and keeps today's exclusive lock.
  • StorageAlias::truncate forwarded the alias's holder to the target and locked nothing on it, though IStorage::truncate is documented as having to be called under one. It now resolves the target once, applies the same rule to it, locks it, and passes that holder down, as Fix race between ALTER and RENAME/EXCHANGE TABLES #103044 does for alter.

That lock is the callee's precondition and parity with the direct statement, not a lifetime mechanism; #112915 owns the use-after-free separately and no longer touches this file.

Behaviour change: a TRUNCATE through an alias whose target is a non-MergeTree engine now waits for that target's own readers, as TRUNCATE <target> already did. That previous success was racy.

Four of the new test's arms fail on unpatched master. It also covers ReplicatedMergeTree, an alias chain, a dangling alias, and an alias to Memory, which must stay blocked, so this is no blanket lock removal.

Not fixed here: alias -> not-yet-loaded target under lazy_load_tables, which #113634 and #113389 own.


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

Version info

  • Merged into: 26.10.1.230-master (included in 26.10 and later)
  • Backported to: 26.9.16.6, 26.8.24.5, 26.7.28.11

…cate

TRUNCATE of a MergeTree is deliberately exempt from the table's exclusive lock,
so it does not wait for readers. InterpreterDropQuery decided that with
dynamic_pointer_cast<MergeTreeData> on the catalog object. A StorageAlias stores
only the target's database and table names (StorageAlias.cpp:39-49), so the cast
always failed and the alias's own exclusive drop_lock was taken. A reader of the
alias holds that same object's share lock, because Analyzer/TableNode.cpp:85
calls lockForShare through a StoragePtr while IStorage::lockForShare and
lockExclusively are non-virtual (IStorage.h:347, :366): StorageAlias.h:247
declares a name-hiding overload taking std::chrono::milliseconds instead of
Poco::Timespan, which an IStorage-typed call never reaches, and lockExclusively
is not hidden at all. So

    CREATE TABLE al ENGINE = Alias('db', 'mt');   -- mt is a MergeTree
    SELECT sum(sleepEachRow(0.2)) FROM al;        -- concurrently
    TRUNCATE TABLE al;

waited for the reader and then failed with Code: 473 DEADLOCK_AVOIDED, leaving
the data in place, while TRUNCATE TABLE mt returned immediately, so which of two
names the user typed decided whether a valid statement was rejected. Measured on
this base: the alias arms report blocked=1 rows_after=300, the direct arm
blocked=0 rows_after=0.

The same decision was wrong twice, so both halves change.

The interpreter now asks table->isMergeTree(), the virtual that expresses "this
storage is a MergeTree" and that StorageAlias already answers by resolving its
target (StorageAlias.h:30). That is not a behaviour change anywhere else:
isMergeTree() has exactly two overrides in the tree, StorageAlias.h:30 and
MergeTreeData.h:567, and the latter is an unconditional true with no #if, so for
every storage except StorageAlias the new predicate is definitionally the old
cast. It resolves with tryGetTargetTable(), which runs no access check and does
not throw, so a dangling target and a not-yet-loaded one (a StorageTableProxy,
which does not forward isMergeTree()) both answer false and keep today's
exclusive lock. getTargetTable() would have been wrong here: it runs
checkAccess(TRUNCATE, ...) and throws UNKNOWN_TABLE, which inside lock selection
would move an access failure ahead of the lock and change error ordering.

StorageAlias::truncate forwarded the alias's lock holder into
target->truncate(...) and took nothing on the target, so the object that executes
the truncate was never locked, and it was resolved a second time while the DDL
guard pinned only the alias's name. It now resolves the target once, applies the
same MergeTree rule to that resolved object, takes that lock, and passes that
holder down, which is what StorageAlias::read (:218) and updateLightweight (:339)
already do. That is also what makes the interpreter's hint safe to act on: were
the hint stale in the dangerous direction (classified a MergeTree, executes
something else, reachable only via EXCHANGE TABLES between the two resolutions),
the target now takes its own exclusive lock and a reader that arrived through the
alias holds that target's share lock, so it is excluded; a reader that arrived
before the exchange holds the old target's lock and is not reading the object
being truncated.

One behaviour change follows from the second half and is deliberate: a TRUNCATE
issued through an alias whose target is a non-MergeTree engine now waits for that
target's own readers and can fail with DEADLOCK_AVOIDED where it previously
proceeded. That previous success was racy, since it is the window
StorageEmbeddedRocksDB::truncate closes the DB and remove_all's its directory
into, and TRUNCATE <target> already behaves this way, so this aligns the two
names rather than inventing a rule.

The sibling decision at InterpreterDropQuery.cpp:344 follows the same
classification, so ddl_guard.reset() now also fires for an alias over a
replicated MergeTree, because StorageAlias::supportsReplication() is already
forwarded (StorageAlias.h:178-182). That is what ClickHouse#114672 shipped for the direct
replicated case.

The new test starts a reader, then truncates under it, and reports whether the
truncate was blocked. Its alias-to-MergeTree, alias-to-ReplicatedMergeTree and
alias-chain arms fail on unpatched master. The alias-to-Memory arm must stay
blocked, so the test rejects exempting every alias rather than following the
target, and the arm whose reader sits on a non-MergeTree target pins the second
half: without it that target is never locked at all.

Not addressed here, and left with its owners: an alias whose target has not been
loaded yet under lazy_load_tables, which is the StorageTableProxy hop that
ClickHouse#113634 and ClickHouse#113389 cover.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR labels Sep 9, 2026
@groeneai

groeneai commented Sep 9, 2026

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

An independent model reviewed this cold before publication. Two findings, both disagreed with evidence.

❌ Blocker: "the lock classification exposes the target engine before TRUNCATE access on the target is verified." The mechanism holds, but the engine dependence is this change's contract rather than a slip in it: a lock that follows the target's engine is observable as the target's engine, so the finding cannot be met without dropping the fix. #114672 already made the same split observable on the direct spelling. The proposed remedy, authorizing the whole resolved chain first, has no in-tree primitive: StorageAlias::isTargetTableGranted is one hop by construction, so on a -> b -> mt it leaks the same bit one hop deeper. Bound: no escalation and no data access, the truncate still fails ACCESS_DENIED, and the concurrent reader the observation needs cannot be created by a caller lacking SELECT on the target.

⚠️ Major: "the test cannot distinguish the MergeTree target's share lock from taking no lock." Both directions of that classification do have measured killers: always-exclusive reddens the three alias-to-MergeTree arms plus the target-reader arm, while no-lock and always-share both redden the non-MergeTree arm. The residual is only "share rather than nothing", whose counterparty is lockExclusively, which nothing takes in a database with a UUID: DROP and DETACH take it only when the database has none, and 04838_truncate_does_not_block_ddl.sh asserts a RENAME is not blocked. Pinning it deterministically would need a new failpoint inside StorageMergeTree::truncate.

@clickhouse-gh clickhouse-gh Bot closed this Sep 9, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 9, 2026
@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @evillique @nauu, could you review this? InterpreterDropQuery classified the TRUNCATE lock with dynamic_pointer_cast<MergeTreeData> on the catalog object, which an Alias can never satisfy, so a valid TRUNCATE of an alias over a MergeTree took the alias's exclusive lock and timed out against its own readers. The classification now uses IStorage::isMergeTree(), and StorageAlias::truncate takes that lock on the resolved target instead of forwarding the alias's holder, which is the shape #103044 uses for alter.

@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9e05001]

Summary: ✅


AI Review

Summary

This PR fixes the main deadlock symptom for TRUNCATE through Alias tables by making the lock choice follow the target engine and by taking the truncate-time lock on the storage that actually executes the operation. The concurrency fix itself looks coherent, but the new outer isMergeTree() probe makes the target engine observable before the target-side TRUNCATE access check runs, so I cannot approve it as-is.

Findings

❌ Blockers

  • [src/Interpreters/InterpreterDropQuery.cpp:336] [dismissed by author -- https://github.com/Fix TRUNCATE of an Alias table over a MergeTree blocking on concurrent readers #119105#issuecomment-5609004583] TRUNCATE TABLE <alias> now changes its outer lock mode from the resolved target engine before StorageAlias::truncate verifies AccessType::TRUNCATE on that target. A user who can truncate the alias but not the target can distinguish Alias -> MergeTree from Alias -> Memory by racing against another session that is reading the alias: the MergeTree case takes the alias's share lock and reaches ACCESS_DENIED immediately, while the non-MergeTree case first waits on the alias reader and times out with DEADLOCK_AVOIDED. The dismissal argues that another reader is required, but the current code still makes protected target metadata observable before authorization.
    Suggested fix: make the lock-kind decision come from a target-authorized path, e.g. a virtual helper used by InterpreterDropQuery that resolves aliases under AccessType::TRUNCATE and returns the required lock kind only after the full target chain has been authorized.
Final Verdict

Request changes.

LLVM Coverage Report

Measured on commit 9e05001.

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

Changed lines: Changed C/C++ lines covered: 13/13 (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 9, 2026
if (std::dynamic_pointer_cast<MergeTreeData>(table))
/// An `Alias` runs the truncate on its target, so the exemption follows the target:
/// `isMergeTree()` resolves it, and is false while it is missing or not loaded yet.
if (table->isMergeTree())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Choosing the TRUNCATE lock mode from table->isMergeTree() here makes the resolved target engine observable before StorageAlias::truncate performs the target-side AccessType::TRUNCATE check.

Concrete trace:

  • User u has TRUNCATE on alias a, but not on its target.
  • Another session is running a long SELECT from a, so it already holds the alias's share lock.
  • If a -> MergeTree, this branch takes the alias's share lock too and reaches StorageAlias::truncate, which then fails immediately with ACCESS_DENIED on the target.
  • If a -> Memory, this branch tries to take the alias's exclusive lock first, waits behind that reader, and times out with DEADLOCK_AVOIDED before the target access check runs.

So the new behavior leaks protected target metadata through timing / error shape. The lock-kind decision needs to come from a target-authorized path instead of from isMergeTree() on the alias object.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed by measurement, and the split is new here. Debug builds of this branch (9e05001, Build ID 9d6e11a0...) and of master (533e934c), one server each, user u holding only GRANT TRUNCATE on the two aliases, SETTINGS lock_acquire_timeout = 3 (scratch database shown as db in the quotes below):

TRUNCATE run by u master this PR
alias -> MergeTree, authorized reader on the alias 473 after 3230 ms 497 ... grant TRUNCATE ON db.mt after 244 ms
alias -> Memory, authorized reader on the alias 473 after 3077 ms 473 after 3098 ms
alias -> MergeTree, no reader 497 after 112 ms 497 after 80 ms
alias -> Memory, no reader 497 after 78 ms 497 after 74 ms

No rows are removed in any of the four arms, on either binary. Three measured bounds are why I am not changing the classification in this PR:

  1. The observation needs a reader authorized on the target, and u cannot be that reader. With GRANT SELECT, TRUNCATE ON db.al_mt and nothing on the target, his own read is refused: Not enough privileges. To execute this query, it's necessary to have the grant SELECT for at least one column on db.al_mt. Rows 3 and 4 show that with no reader in flight both engines answer identically.
  2. A lock-timing channel on this statement already exists on master (row 1, master: 473 with a reader, 497 without), and master already answers u with the target's fully qualified name: it's necessary to have the grant TRUNCATE ON db.mt. What this PR changes is which bit that channel carries, not that u has one.
  3. The engine dependence is the contract of the change, and master already ships it for the direct spelling: the MergeTree share-lock exemption on these lines came in with Do not hold the DDL guard during TRUNCATE of a replicated table #114672 (2026-08-14), so whether TRUNCATE waits for readers already reports the engine family of the table addressed.

Removing the residual bit means choosing the lock only after the target's TRUNCATE grant has been checked. That needs a new IStorage hook rather than isTargetTableGranted, which is one hop by construction, so on a -> b -> mt it moves the bit one hop deeper instead of removing it, and it turns that user's error under contention from 473 into 497. That is an ordering change in the Alias access surface rather than the lock classification this PR corrects, so I have left it out. If a maintainer prefers that ordering, I will make it a separate change.

@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9e05001f8 with master 4d7f75efa (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

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

Job report

@PedroTadim

Copy link
Copy Markdown
Member

cc @nauu

@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit 908d59f Sep 19, 2026
174 of 344 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 19, 2026
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Sep 22, 2026
`TRUNCATE ALL TABLES FROM db` collects every table whose `supportsTruncate()` is
true and truncates each in its own thread-pool task, all of them sharing one
`table_context` and therefore one query id. An `Alias` is a name without data, so
an alias entry and its target entry converge on a single storage: the target's
task takes that storage's `drop_lock` in WRITE mode, and the alias's task takes
the same lock again inside `StorageAlias::truncate`. `RWLockImpl::getLock`
rejects a second acquisition of a write-held lock by a query id that already owns
it, so the statement raises `LOGICAL_ERROR: RWLock is already locked in exclusive
mode`, aborting debug and sanitizer builds and surfacing as `Code: 49` in
release. Only a non-MergeTree target is affected: with a MergeTree target both
acquisitions are read locks, which `RWLockImpl` ref-counts.

`StorageAlias` now reports `supportsTruncate() == false`, the hook whose own
documentation names this class of storage ("storages without their own data").
That removes the convergence for every alias shape at once, alias plus target,
several aliases to one target, alias chains, and an alias whose target is gone,
without touching an explicit `TRUNCATE TABLE <alias>`, whose branch in
`executeToTableImpl` never consults the predicate. `StorageURL` already makes
exactly this split.

Two further behaviours are corrected by the same line: an `Alias` whose target is
missing no longer makes the whole statement fail with `UNKNOWN_TABLE`, and a
target living in another database is no longer truncated by a statement that did
not name that database.

Measured on this tree: 20 of 20 runs of the new test abort before the change and
0 of 20 after, while the same fixture with a MergeTree target does not reproduce
on the unfixed binary.

Reported in ClickHouse#121129; the second target acquisition was added in ClickHouse#119105. Found by
BuzzHouse on master, sha e6b360b.

Co-Authored-By: Claude Opus 5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 23, 2026
…tion

One conflict, in the TRUNCATE branch of InterpreterDropQuery::executeToTableImpl.
Master replaced the `dynamic_pointer_cast<MergeTreeData>(table)` test with the
virtual `table->isMergeTree()` in ClickHouse#119105, which taught `StorageAlias` to resolve
its target. `StorageProxy` still does not forward that predicate, so a
`lazy_load_tables` database's `StorageTableProxy` answers the inherited default
`false` and a lazy MergeTree keeps taking the exclusive lock.

Resolved by keeping this branch's unwrap and adopting master's predicate:
`table_to_classify->isMergeTree()`. For every storage that is not a
`StorageTableProxy`, including an `Alias`, `table_to_classify` is `table`, so
master's behaviour is unchanged; for the lazy proxy the predicate now runs on the
nested storage that actually executes the truncate. Master's own
`#include <Storages/MergeTree/MergeTreeData.h>` removal is kept: the cast is gone.
@watson-ch

watson-ch Bot commented Oct 10, 2026

Copy link
Copy Markdown

Backport labels have been automatically added based on https://github.com/clickhouse/clickhouse-core-incidents/issues/2167

Labels added:

  • v26.6-must-backport

These labels ensure backport PRs are properly created for each affected release version. The release automation will create backport PRs as needed based on these labels.

@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 10, 2026
robot-clickhouse-ci-2 added a commit that referenced this pull request Oct 10, 2026
Cherry pick #119105 to 26.8: Fix `TRUNCATE` of an `Alias` table over a `MergeTree` blocking on concurrent readers
robot-clickhouse added a commit that referenced this pull request Oct 10, 2026
…MergeTree` blocking on concurrent readers
robot-ch-test-poll added a commit that referenced this pull request Oct 10, 2026
Cherry pick #119105 to 26.7: Fix `TRUNCATE` of an `Alias` table over a `MergeTree` blocking on concurrent readers
robot-clickhouse added a commit that referenced this pull request Oct 10, 2026
…MergeTree` blocking on concurrent readers
robot-ch-test-poll added a commit that referenced this pull request Oct 10, 2026
Cherry pick #119105 to 26.9: Fix `TRUNCATE` of an `Alias` table over a `MergeTree` blocking on concurrent readers
robot-clickhouse added a commit that referenced this pull request Oct 10, 2026
…MergeTree` blocking on concurrent readers
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 10, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 10, 2026
Backport #119105 to 26.8: Fix `TRUNCATE` of an `Alias` table over a `MergeTree` blocking on concurrent readers
clickhouse-gh Bot added a commit that referenced this pull request Oct 10, 2026
Backport #119105 to 26.9: Fix `TRUNCATE` of an `Alias` table over a `MergeTree` blocking on concurrent readers
clickhouse-gh Bot added a commit that referenced this pull request Oct 12, 2026
Backport #119105 to 26.7: Fix `TRUNCATE` of an `Alias` table over a `MergeTree` blocking on concurrent readers
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-review-bot PR origin: review-bot finding on a groeneai PR 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.6-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants