Repository navigation
Fix TRUNCATE of a lazily loaded MergeTree table blocking on concurrent readers - #113634
Conversation
TRUNCATE of a MergeTree table deliberately skips the table's exclusive lock, so it does not wait for concurrent readers. InterpreterDropQuery decided that exemption with dynamic_pointer_cast<MergeTreeData> on the object held in the catalog. A database created with lazy_load_tables = 1 holds a StorageTableProxy there, so the cast failed, the exemption was missed, and the proxy's exclusive drop_lock was taken. Readers lock the same object, because lockForShare and lockExclusively are non-virtual over the callee's own drop_lock and neither proxy class overrides them, and RWLockImpl is writer-preferring. The truncate therefore waited for readers and failed with DEADLOCK_AVOIDED once lock_acquire_timeout expired, where the same statement against an eagerly loaded MergeTree returns immediately. StorageProxy::truncate forwards to the nested storage, so the engine that executes the truncate is the nested one, and the wrapper is simply the wrong object to classify. Resolve it once, at that call site, before the cast. The lock is still taken on the same object as before; only the classification changes. The cast is scoped to StorageTableProxy rather than to StorageProxy on purpose. That class is final, contains no truncate override, and is already materialized at this point because checkTableCanBeDropped five lines earlier resolves it unconditionally, so the classified object provably is the executing one. Two of the other three StorageProxy subclasses override truncate without forwarding: StorageURLSchemeDispatch bypasses the proxy to throw, and StorageURLDatabaseTable forwards to getNestedForWrite, a different storage than getNested. A generic walk would therefore classify an object that never executes. Neither would change the outcome today, since both wrap non-MergeTree storages, but the mechanism would be unsound by construction. This removes a lock, so the reader-side argument matters. Neither MergeTree truncate implementation reads the holder: StorageMergeTree::truncate leaves the parameter unnamed and StorageReplicatedMergeTree::truncate only releases it. MergeTree synchronizes truncation itself, and reader safety rests on shared_ptr part ownership plus the isSharedPtrUnique gate in grabOldParts, not on drop_lock. IStorage::truncate is documented as requiring the exclusive lock; that divergence already exists on master for every eagerly loaded MergeTree through this same branch, and is extended rather than created. Two defects of the same class are left alone here, since ClickHouse#113389 is sweeping that class with a non-loading resolver: MutationsInterpreter rejects ALTER ... IN PARTITION on such a table, and an unforwarded isStaticStorage leaves the read-only guard ineffective for it. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The stress runner has a mode that rewrites Log and Memory table engines to MergeTree (`--replace-log-memory-with-mergetree`, passed with probability 0.3). Executing that rewrite against this test changes exactly one line, the control arm's `ENGINE = Memory`, and leaves the reference file untouched, so in that mode the arm would assert a Memory table's behaviour against a MergeTree. Two things break. The reference no longer matches, because the rewritten table is correctly exempted from the lock and prints `blocked=0 rows_after=0`. More importantly the test stops discriminating: that arm is the only one that fails if the lock exemption is made unconditional instead of being decided per storage, which is the property worth pinning in a change that removes a lock. The runner already provides the mechanism for this: a test tagged `memory-engine` is skipped when the rewriting mode is active. The tag is inert otherwise, since its only consumer is guarded by that flag.
Internal second-model review (click to expand)Two review rounds, each with an independent cold code review and an independent second-model gate Round 1: 1 major, in the test rather than the fix.
Round 2: 0 findings in both channels; two documentation nits, one corrected. 💡 Corrected in the validation-gate comment: the lazy 💡 One internal precedent count did not reproduce exactly (one file, not two, carries a particular Verified independently rather than accepted. Session id: cron:clickhouse-review-slot-50:20260806-081400 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-50:20260806-081400 |
|
cc @evillique @yariks5s, could you review this? |
|
Workflow [PR], commit [5096fc7] Summary: ✅
AI ReviewSummaryThis PR fixes the Final VerdictStatus: ✅ Approve LLVM Coverage ReportMeasured on commit 5096fc7.
Changed lines: Changed C/C++ lines covered: 9/9 (100.00%) · Uncovered code |
CI finish ledger — a827fbaEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
On the Session id: cron:our-pr-ci-monitor:20260806-153000 |
|
Fixing PR for the |
…tion Resolves one conflict, in the TRUNCATE branch of InterpreterDropQuery::executeToTableImpl. Master's ClickHouse#114672 rewrote the same statement this branch changes. It used to be a plain exemption, where a MergeTree took no lock at all; it now takes a share lock instead, and only the other engines take the exclusive one. The two sides therefore conflicted on the condition itself: this branch had inverted nothing and only replaced the classified object, while master inverted the test and added an else branch. Kept master's shape verbatim, including the new share lock, its comment and the ddl_guard.reset() that follows, and re-applied only this branch's contribution to it: the cast is performed on the storage that executes the truncate rather than on the object held in the catalog, so a lazy_load_tables database's StorageTableProxy is classified by its nested engine. The delta against master is now one include, the resolver, and one identifier inside the condition. Two consequences of the new shape are worth stating, since they change this branch's argument rather than its code: The change no longer removes a lock. A lazily loaded MergeTree moves from the exclusive lock to the share lock that master now takes for the eager case, which is what stops it blocking readers, since readers hold that same lock in share mode. The reader-side argument this branch had to make is consequently master's own argument, and the divergence from the IStorage::truncate doc comment is no longer extended by it. supportsReplication() is forwarded by StorageProxy, so with the classification fixed, a lazily loaded ReplicatedMergeTree now also reaches master's new ddl_guard.reset(). That is the same treatment an eagerly loaded one gets, and it is reachable only because the share lock is now held, which is the condition master gates it on. Co-Authored-By: Claude Opus 5 <[email protected]>
The four existing arms cannot distinguish the classification this change makes from a coarser one that exempts every StorageTableProxy regardless of the engine behind it. Arms A and B are lazy MergeTree proxies, and the non-MergeTree control is in the eagerly loaded database, so exempting all proxies leaves every expected line unchanged while dropping the exclusive lock that a lazy Log, Set or Join table still needs. Verified by building exactly that mutant: only the new arm reddens, and the other four are byte-identical. A Log table is still lazily loaded on master, since shouldLazyLoad excludes only views, dictionaries, TimeSeries tables, table functions, push sources that feed a materialized view, and restore mode. Such a table reads back as TableProxy after a reattach, and its truncate is classified by the nested StorageLog and blocks. The table joins the engine listing above the arms, and that assertion carries weight rather than describing the fixture. An eagerly loaded Log reaches the exclusive lock for the same reason a proxied one does, so the arm keeps passing if the table stops being a proxy, having quietly stopped covering a proxy at all. Asserting the engine means that if lazy loading is ever restricted to the MergeTree family, this test fails and says so, which retires the arm as unreachable instead of leaving it as decoration. log-engine joins the tags line: the runner rewrites Log as well as Memory in the mode those tags gate, so the declaration now matches what the test actually depends on rather than resting on the other arm's engine. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Rebased onto master. One conflict, in the Two consequences of the new shape sit in the description rather than the code. This no longer The defect itself survives #114672, since master still classifies on the raw catalog object. On the I also added arm Session id: cron:clickhouse-maint-slot-16:20260909-120800 |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes4 object files changed (+232.80 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units7 translation units recompiled, 15 s compile time in total, 7 of them have a recent master baseline. |
…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, fix conflicts. |
…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.
The master merge replaced `dynamic_pointer_cast<MergeTreeData>(table)` with the virtual `table->isMergeTree()`, so the header's account of the defect named a cast that no longer exists. The invariant it is really about is unchanged and holds under either spelling: the exemption was decided on the catalog wrapper instead of on the nested storage that runs the truncate.
|
Conflicts fixed by merging master ( The single conflict was the exempt condition itself: #119105 replaced On the merged tree I also corrected two sentences the merge made stale: the test header and the description both still described the removed cast, and the description still listed the |
CI finish ledger - 5968d02Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The rest of the run is clean: 134 of 176 checks pass and 39 are skipped, with Session id: cron:our-pr-ci-monitor:20260923-080258 |
…tion # Conflicts: # src/Interpreters/InterpreterDropQuery.cpp
CI finish ledger - e1c004aEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 172 check runs completed (130 pass, 39 not selected, 3 red: the row above and its two rollups), Session id: cron:our-pr-ci-monitor:20260927-173207 |
|
Fixing PR for the |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
TRUNCATE TABLEof aMergeTreetable in a database created withlazy_load_tables = 1failing withDEADLOCK_AVOIDEDwhen the table is being read concurrently. Such a table is now exempt from the exclusive lock, as it already is when the database loads tables eagerly.Description
TRUNCATEof aMergeTreetable is deliberately exempt from the table's exclusive lock, so it does not wait for readers.InterpreterDropQuerydecides that withtable->isMergeTree()on the catalog object. Withlazy_load_tables = 1that object is aStorageTableProxy, andStorageProxydoes not forwardisMergeTree(), so it answers the inheritedfalseand the proxy's exclusivedrop_lockis taken. Readers lock that same object:lockForShareandlockExclusivelyare non-virtual and no proxy class overrides them. It therefore waits for readers and fails withCode: 473 DEADLOCK_AVOIDEDoncelock_acquire_timeout(default 120 s) expires, where an eagerly loadedMergeTreereturns immediately.StorageProxy::truncateforwards to the nested storage, so that storage is what executes the truncate, and the fix classifies it, not the wrapper. The unwrap is scoped toStorageTableProxyrather than toStorageProxy: that class isfinal, does not overridetruncate, and is already materialized, sincecheckTableCanBeDroppedjust above resolves it. Two of the other threeStorageProxysubclasses do overridetruncatewithout forwarding, so a generic walk could classify an object that never executes.Since #114672 the exempt branch takes a share lock, not none, so no lock is removed here: the table moves from the exclusive lock to that share lock, which readers also hold. The proxy forwards
supportsReplication(), so such a table now also reaches theddl_guard.reset()#114672 added, as an eager one does.The new test truncates a lazy
MergeTree, a lazyReplicatedMergeTreeand three controls under a reader. BothMergeTreearms fail on unpatched master. The lazyLogcontrol must stay blocked: without it the test would accept exempting every proxy.Two more defects of this class, in
MutationsInterpreterand in an unforwardedisStaticStorage, are left to #113389. TheAliasvariant was fixed in #119105 and, over a lazily loaded target, in #121703.Workflow [PR]
Sync PR [sync-upstream/pr/113634]
Version info
26.10.1.1195-master(included in26.10and later)