Skip to content

Do not hold the DDL guard during TRUNCATE of a replicated table - #114672

Merged
evillique merged 8 commits into
ClickHouse:masterfrom
evillique:truncate-do-not-hold-ddl-guard
Sep 8, 2026
Merged

evillique merged 8 commits into
ClickHouse:masterfrom
evillique:truncate-do-not-hold-ddl-guard

Conversation

@evillique

@evillique evillique commented Aug 13, 2026 •

Copy link
Copy Markdown
Member

TRUNCATE TABLE held the table's DDL guard while removing data, and a replicated truncate only schedules the removal, waiting for other replicas to process DROP_RANGE. Any DDL on that name — including background threads that need it — was blocked for that whole time. The guard is now released before IStorage::truncate for replicated tables in databases with UUIDs, which is what ALTER TABLE ... DROP PARTITION has always done, and a share lock keeps the storage from being dropped or moved meanwhile. A plain MergeTree keeps 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 = 1 a replicated table is reached through StorageTableProxy, which is not a MergeTreeData, so it keeps the guard as well. Resolving the proxy for this decision needs castStorage from #113389.

Related: #113389

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

TRUNCATE TABLE on a ReplicatedMergeTree table no longer blocks concurrent DROP, RENAME and other DDL queries on the same table while the data is being removed.

Version info

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

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [68392fc]

Summary: ✅


AI Review

Summary

This PR releases the per-name DDLGuard around replicated TRUNCATE by relying on the storage's share drop_lock, and it adds stateless coverage for concurrent rename/truncate behavior. The direction looks reasonable, but I do not think it is ready to merge yet: the new "removed replica" handling in tryWaitForReplicaToProcessLogEntry still reports success in later disappearance windows, and the PR text still advertises a broader surface than the code now implements.

PR Metadata
  • Changelog category: Improvement matches the change.
  • Changelog entry: required, but the current text overstates the scope. The code only drops the name guard for replicated tables, and tables reached through lazy_load_tables = 1 still keep the old behavior. Exact replacement: Replicated TRUNCATE TABLE on UUID-backed databases no longer keeps the table-name DDLGuard while waiting for replicated DROP_RANGE processing. Tables reached through lazy_load_tables = 1 still use the previous behavior.
Findings
  • ⚠️ [src/Storages/StorageReplicatedMergeTree.cpp:8043-8088] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/114672#discussion_r3918527754] The new "removed replica means unfinished" contract is only enforced before the queue is listed. If the replica disappears after tryGetChildren() returns or after queue_entry_to_wait_for is chosen, the function still returns true through the "already processed" branch or waitForDisappear(), so alter_sync can report that a replica processed a DROP_RANGE even though the entry only vanished with the replica. Re-check /replicas/<replica> after the queue scan and after waitForDisappear(), and return false if the replica disappeared in either window.
  • ⚠️ [src/Interpreters/InterpreterDropQuery.cpp:335-345] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/114672#discussion_r3918527765] lazy_load_tables = 1 still routes through StorageTableProxy, which fails the MergeTreeData cast and therefore keeps the DDLGuard for the full TRUNCATE. I still consider this real because it is a supported mode and the current title/changelog read like a general TRUNCATE TABLE change, not a best-effort optimization for already-materialized replicated tables. Either unwrap the proxy before deciding on the lock/guard path, or narrow the user-facing contract to replicated tables that are already materialized.
  • 💡 [src/Interpreters/InterpreterDropQuery.cpp:342-345] The code now explicitly narrows the optimization to replicated tables (table->supportsReplication()), but the PR title and changelog still describe TRUNCATE TABLE generically. Plain MergeTree keeps the old blocking behavior, so the user-facing contract should be narrowed to replicated TRUNCATE.
Tests
  • ⚠️ There is no regression that removes a replica after its queue is listed or after waitForDisappear() starts. A focused test for those two windows would prove the new tryWaitForReplicaToProcessLogEntry behavior instead of leaving the late-disappearance cases unexercised.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 68392fc.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 25/42 (59.52%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 68392fc1d with master 35a0d6f0c (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 323d42647; 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

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

Job report

@thevar1able thevar1able left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@thevar1able thevar1able self-assigned this Aug 17, 2026

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)

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.

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 after getChildren() but before the per-entry tryGet(), queue_entry_to_wait_for stays empty and we return true at the "already processed" branch;
  • if the replica is dropped after queue_entry_to_wait_for is selected, waitForDisappear() also returns true on DELETED / 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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))

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.

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).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@clickhouse-gh clickhouse-gh Bot added the comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). label Sep 4, 2026
@evillique evillique changed the title Do not hold the DDL guard during TRUNCATE Do not hold the DDL guard during TRUNCATE of a replicated table Sep 4, 2026
@clickhouse-gh clickhouse-gh Bot added comp-replication ReplicatedMergeTree* + replication log/state transitions, eventual consistency mechanics. and removed comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). labels Sep 4, 2026
@evillique
evillique added this pull request to the merge queue Sep 8, 2026
Merged via the queue into ClickHouse:master with commit f0310cf Sep 8, 2026
175 checks passed
@evillique
evillique deleted the truncate-do-not-hold-ddl-guard branch September 8, 2026 11:23
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 8, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 9, 2026
…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]>
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Sep 19, 2026
…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]>
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Sep 23, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-replication ReplicatedMergeTree* + replication log/state transitions, eventual consistency mechanics. pr-improvement Pull request with some product improvements 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.

3 participants