Repository navigation
Fix TRUNCATE of an Alias table over a MergeTree blocking on concurrent readers - #119105
Conversation
…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]>
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
|
|
cc @evillique @nauu, could you review this? |
|
Workflow [PR], commit [9e05001] Summary: ✅
AI ReviewSummaryThis PR fixes the main deadlock symptom for Findings❌ Blockers
Final VerdictRequest changes. LLVM Coverage ReportMeasured on commit 9e05001.
Changed lines: Changed C/C++ lines covered: 13/13 (100.00%) · Uncovered code |
| 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()) |
There was a problem hiding this comment.
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
uhasTRUNCATEon aliasa, but not on its target. - Another session is running a long
SELECTfroma, so it already holds the alias's share lock. - If
a -> MergeTree, this branch takes the alias's share lock too and reachesStorageAlias::truncate, which then fails immediately withACCESS_DENIEDon the target. - If
a -> Memory, this branch tries to take the alias's exclusive lock first, waits behind that reader, and times out withDEADLOCK_AVOIDEDbefore 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.
There was a problem hiding this comment.
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:
- The observation needs a reader authorized on the target, and
ucannot be that reader. WithGRANT SELECT, TRUNCATE ON db.al_mtand 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. - A lock-timing channel on this statement already exists on master (row 1, master:
473with a reader,497without), and master already answersuwith 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 thatuhas one. - The engine dependence is the contract of the change, and master already ships it for the direct spelling: the
MergeTreeshare-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 whetherTRUNCATEwaits 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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units8 translation units recompiled, 20 s compile time in total, 8 of them have a recent master baseline. |
|
cc @nauu |
908d59f
`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]>
…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.
|
Backport labels have been automatically added based on https://github.com/clickhouse/clickhouse-core-incidents/issues/2167 Labels added:
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. |
Cherry pick #119105 to 26.8: Fix `TRUNCATE` of an `Alias` table over a `MergeTree` blocking on concurrent readers
…MergeTree` blocking on concurrent readers
Cherry pick #119105 to 26.7: Fix `TRUNCATE` of an `Alias` table over a `MergeTree` blocking on concurrent readers
…MergeTree` blocking on concurrent readers
Cherry pick #119105 to 26.9: Fix `TRUNCATE` of an `Alias` table over a `MergeTree` blocking on concurrent readers
…MergeTree` blocking on concurrent readers
Backport #119105 to 26.8: Fix `TRUNCATE` of an `Alias` table over a `MergeTree` blocking on concurrent readers
Backport #119105 to 26.9: Fix `TRUNCATE` of an `Alias` table over a `MergeTree` blocking on concurrent readers
Backport #119105 to 26.7: Fix `TRUNCATE` of an `Alias` table over a `MergeTree` blocking on concurrent readers
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
TRUNCATE TABLEof anAliastable whose target is aMergeTreefailing withDEADLOCK_AVOIDEDwhen the alias is being read concurrently, while the same statement against the target table succeeds immediately. The lock forTRUNCATEis now chosen and taken on the table that executes the truncate, so anAliasfollows its target's engine.Description
Reported by a review bot on #113634: #113634 (comment)
TRUNCATEof aMergeTreeis exempt from the table's exclusive lock, so it does not wait for readers;InterpreterDropQuerydecided that withdynamic_pointer_cast<MergeTreeData>on the catalog object. AStorageAliasholds only its target's name, so the cast always failed and the alias's own exclusivedrop_lockwas taken. A reader of the alias holds that same object's share lock, sincelockForShare/lockExclusivelyare non-virtual. SoTRUNCATE TABLE <alias>waited for the reader and then failed withCode: 473 DEADLOCK_AVOIDED, leaving the data in place.The same decision was wrong twice:
table->isMergeTree(), the virtualStorageAliasalready answers by resolving its target. It has two overrides tree-wide, so for every other storage this is the old cast, and it resolves withtryGetTargetTable(), so a missing or not-yet-loaded target answersfalseand keeps today's exclusive lock.StorageAlias::truncateforwarded the alias's holder to the target and locked nothing on it, thoughIStorage::truncateis 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 foralter.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
TRUNCATEthrough an alias whose target is a non-MergeTree engine now waits for that target's own readers, asTRUNCATE <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 toMemory, which must stay blocked, so this is no blanket lock removal.Not fixed here:
alias -> not-yet-loaded targetunderlazy_load_tables, which #113634 and #113389 own.Workflow [PR]
Sync PR [sync-upstream/pr/119105]
Version info
26.10.1.230-master(included in26.10and later)26.9.16.6,26.8.24.5,26.7.28.11