Repository navigation
Do not hold the DDL guard during TRUNCATE of a replicated table - #114672
Conversation
|
Workflow [PR], commit [68392fc] Summary: ✅
AI ReviewSummaryThis PR releases the per-name PR Metadata
Findings
Tests
Final VerdictChanges requested. LLVM Coverage ReportMeasured on commit 68392fc.
Changed lines: Changed C/C++ lines covered: 25/42 (59.52%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units9 translation units recompiled, 45 s compile time in total, 9 of them have a recent master baseline. |
…the log entry wait
|
|
||
| Strings queue_entries = getZooKeeper()->getChildren(fs::path(table_zookeeper_path) / "replicas" / replica / "queue"); | ||
| Strings queue_entries; | ||
| if (getZooKeeper()->tryGetChildren(fs::path(table_zookeeper_path) / "replicas" / replica / "queue", queue_entries) |
There was a problem hiding this comment.
This only converts ZNONODE into false before the queue entry is identified. Once the queue node is found, the rest of the function still treats replica removal as success:
- if
/replicas/<replica>disappears aftergetChildren()but before the per-entrytryGet(),queue_entry_to_wait_forstays empty and wereturn trueat the "already processed" branch; - if the replica is dropped after
queue_entry_to_wait_foris selected,waitForDisappear()also returnstrueonDELETED/ZNONODE.
With the DDL guard now released during replicated TRUNCATE, concurrent DROP / DETACH can hit both windows, so alter_sync may report that a replica processed the DROP_RANGE when the queue entry only vanished with the replica. Please re-check replica liveness after the queue scan and again after waitForDisappear(), and return false if the replica disappeared during either step.
There was a problem hiding this comment.
Both windows are pre-existing and not newly reachable: for alter_sync = 1 the deferred drop cannot remove our own replica while the truncate holds the StoragePtr, and for alter_sync = 2 other replicas were never covered by our local guard. Worth its own issue, since "the replica is gone" is arguably success for a truncate.
| /// dropped or moved to another database meanwhile, the same as for ALTER TABLE ... DROP PARTITION. | ||
| /// For the rest of tables types exclusive lock is needed | ||
| if (!std::dynamic_pointer_cast<MergeTreeData>(table)) | ||
| if (std::dynamic_pointer_cast<MergeTreeData>(table)) |
There was a problem hiding this comment.
checkTableCanBeDropped() has already materialized a StorageTableProxy by the time we get here, but this branch still keys off the wrapper type instead of the storage object that lives in the catalog. In an Atomic database with lazy_load_tables = 1, replicated tables stay wrapped in StorageTableProxy, so they always take the exclusive-lock path and never satisfy the table_shared_lock condition below.
That means the headline behavior of this PR still does not happen for that supported mode: TRUNCATE TABLE continues to hold the DDL guard and block concurrent RENAME / DROP whenever the table is lazy-loaded. Please base the share-lock decision on the proxied storage as well (or explicitly narrow the contract/tests/changelog if lazy_load_tables = 1 is intentionally excluded).
There was a problem hiding this comment.
Deliberate: dropping the guard with no lock held is the worse failure, and resolving the proxy here needs castStorage from #113389, which rewrites this line. Noted the lazy_load_tables = 1 narrowing in the description.
…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]>
…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]>
…ot_block_ddl 04838_truncate_does_not_block_ddl waits for an entry to appear in system.replication_queue before issuing the RENAME that the test exists to check, but the wait counted entries of every type. SYSTEM STOP REPLICATION QUEUES blocks queue execution only (queue.actions_blocker); pulling /log into the replica's queue is a separate blocker (queue.pull_log_blocker) that the test never takes, and pullLogsToQueue copies every /log child with no filter on source_replica, so the queue can still hold the GET_PART entry that the test's own INSERT wrote. When it does, the wait is already satisfied before TRUNCATE has created anything, and the test degenerates into a race between the background TRUNCATE client's startup and the RENAME client's. A TRUNCATE that loses that race reaches the server after the table has been renamed away and dies with UNKNOWN_TABLE in InterpreterDropQuery::executeToTableImpl, before ever calling StorageReplicatedMergeTree::truncate. Nothing is truncated, the final count returns 1, and both assertions are vacuous: "RENAME is not blocked" prints with nothing to block it. That is the observed CI failure. Key the wait on type = 'DROP_RANGE', which only TRUNCATE creates here, so the RENAME genuinely races a waiting TRUNCATE. Ask the server for count() > 0 and break on the positive value, so an empty result from a failed or timed-out client keeps waiting instead of ending the wait. Assert after the loop that the entry appeared, so a predicate that can no longer be satisfied fails loudly instead of passing 30 seconds slower and silently dropping the coverage. Capture the background TRUNCATE's stderr and print it only when that client exits non-zero, so this class of failure reports its own cause instead of an unexplained row count. 03986_kill_query_mutation_sync_replicated carries the same break-on-any-nonzero wait, the only other one in the suite, and gets the same positive form. Its post-loop guard already caught genuine exhaustion but not an empty client result. Related: ClickHouse#114672 Co-Authored-By: Claude Opus 5 <[email protected]>
TRUNCATE TABLEheld the table's DDL guard while removing data, and a replicated truncate only schedules the removal, waiting for other replicas to processDROP_RANGE. Any DDL on that name — including background threads that need it — was blocked for that whole time. The guard is now released beforeIStorage::truncatefor replicated tables in databases with UUIDs, which is whatALTER TABLE ... DROP PARTITIONhas always done, and a share lock keeps the storage from being dropped or moved meanwhile. A plainMergeTreekeeps the guard, because its truncate removes the data in place and relies on being the only truncate on the table. A truncate waiting for a replica that is being removed now reports that replica as unfinished instead of failing with a Keeper error.With
lazy_load_tables = 1a replicated table is reached throughStorageTableProxy, which is not aMergeTreeData, so it keeps the guard as well. Resolving the proxy for this decision needscastStoragefrom #113389.Related: #113389
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
TRUNCATE TABLEon aReplicatedMergeTreetable no longer blocks concurrentDROP,RENAMEand other DDL queries on the same table while the data is being removed.Version info
26.9.1.957(included in26.9and later)