Skip to content

Fix TRUNCATE of a lazily loaded MergeTree table blocking on concurrent readers - #113634

Merged
alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-lazy-load-truncate-lock-exemption
Oct 1, 2026
Merged

alexey-milovidov merged 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-lazy-load-truncate-lock-exemption

Conversation

@groeneai

@groeneai groeneai commented Aug 6, 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 a MergeTree table in a database created with lazy_load_tables = 1 failing with DEADLOCK_AVOIDED when 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

TRUNCATE of a MergeTree table is deliberately exempt from the table's exclusive lock, so it does not wait for readers. InterpreterDropQuery decides that with table->isMergeTree() on the catalog object. With lazy_load_tables = 1 that object is a StorageTableProxy, and StorageProxy does not forward isMergeTree(), so it answers the inherited false and the proxy's exclusive drop_lock is taken. Readers lock that same object: lockForShare and lockExclusively are non-virtual and no proxy class overrides them. It therefore waits for readers and fails with Code: 473 DEADLOCK_AVOIDED once lock_acquire_timeout (default 120 s) expires, where an eagerly loaded MergeTree returns immediately.

StorageProxy::truncate forwards to the nested storage, so that storage is what executes the truncate, and the fix classifies it, not the wrapper. The unwrap is scoped to StorageTableProxy rather than to StorageProxy: that class is final, does not override truncate, and is already materialized, since checkTableCanBeDropped just above resolves it. Two of the other three StorageProxy subclasses do override truncate without 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 the ddl_guard.reset() #114672 added, as an eager one does.

The new test truncates a lazy MergeTree, a lazy ReplicatedMergeTree and three controls under a reader. Both MergeTree arms fail on unpatched master. The lazy Log control must stay blocked: without it the test would accept exempting every proxy.

Two more defects of this class, in MutationsInterpreter and in an unforwarded isStaticStorage, are left to #113389. The Alias variant was fixed in #119105 and, over a lazily loaded target, in #121703.


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

Version info

  • Merged into: 26.10.1.1195-master (included in 26.10 and later)

groeneai and others added 2 commits August 6, 2026 06:08
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.
@groeneai

groeneai commented Aug 6, 2026

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

Two review rounds, each with an independent cold code review and an independent second-model gate
review. Round 1 raised one major from the cold review (the gate returned 0 findings); round 2
returned 0 findings in both channels. The source change was never modified by a review round: it is
byte-identical to what the first review saw, and the second round's only delta is one test tag.

Round 1: 1 major, in the test rather than the fix.

⚠️ Test liveness under a live CI runner mode. The plain non-MergeTree arm is the only arm that
reddens when the lock exemption is made unconditional, so it is the arm that distinguishes this
narrow fix from a blanket lock removal. The stress runner passes
--replace-log-memory-with-mergetree with probability 0.3, and that mode rewrites
ENGINE = Memory to MergeTree() ORDER BY tuple(). Executing the runner's own regex against the
files: exactly one line rewritten in the .sh and zero in the .reference, so in that mode the
table becomes a MergeTree while the expectation still says the truncate was blocked. That is both
a deterministic reference diff in roughly 30% of stress runs and, more importantly, the loss of the
one arm a reviewer will want when a PR removes a lock. Fixed by tagging the test memory-engine,
whose single consumer in the runner skips the test in exactly that mode. Verified with the runner's
own tag parser: the shipped file parses memory-engine, no-replicated-database, zookeeper, the
previous revision the same set without memory-engine, and four malformed-tag-line controls parse
empty, so the pass is not vacuous. The other two engine-rewriting call sites in the runner are
gated on flags no script in this repository passes, so one tag is sufficient.

Round 2: 0 findings in both channels; two documentation nits, one corrected.

💡 Corrected in the validation-gate comment: the lazy Log cell it cites is verified out of band
rather than shipped as a test arm, and the wording now says so and names the in-test arm that
carries the same property. The distinction matters because a lazily loaded non-MergeTree table
becomes unconstructible once #113389 lands, at which point such an arm would go vacuous.

💡 One internal precedent count did not reproduce exactly (one file, not two, carries a particular
tag pair). It appears in no published text, so nothing here or in the description was wrong; noted
so a later reader does not treat it as drift.

Verified independently rather than accepted. StorageProxy::truncate is pure forwarding and
StorageTableProxy overrides no truncate, so the classified object provably is the executing
one. The cast is deliberately narrow: of the four StorageProxy subclasses, one bypasses the proxy
to throw on truncate and one forwards to a different storage than getNested, so a generic walk
would classify an object that never executes. Removing the lock is safe because neither MergeTree
truncate reads the holder and reader safety rests on part ownership plus the isSharedPtrUnique
gate in grabOldParts. The is_dropped/is_detached re-check that lockExclusively also performs
is not newly bypassed: the whole region runs under the per-table DDL guard, exactly as it already
does for an eagerly loaded MergeTree. dynamic_pointer_cast<MergeTreeData> has eight call sites
and only the patched one participates in this lock decision. Every cited file and line was
re-verified against current master, 11 of 11 matching.

Session id: cron:clickhouse-review-slot-50:20260806-081400

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A lazy database plus a held reader, then TRUNCATE TABLE <lazy_db>.mt SETTINGS lock_acquire_timeout = 3, which fails with Code: 473 DEADLOCK_AVOIDED. The reader is handshaked on read_rows > 0 in system.processes rather than a sleep, so the arm is not timing dependent. Verdicts were identical on every run of the test and of a standalone probe.
b Root cause explained? Yes. A lazy_load_tables = 1 database holds a StorageTableProxy in the catalog (DatabaseOrdinary.cpp:487). InterpreterDropQuery.cpp:332 decided the MergeTree lock exemption with dynamic_pointer_cast<MergeTreeData> on that object, so the cast failed and the exclusive drop_lock was taken. Readers lock the same object, because lockForShare and lockExclusively are non-virtual (IStorage.h:315/:334) over the callee's own drop_lock (:818) and neither proxy class overrides them. RWLockImpl is writer-preferring (RWLock.cpp:168), so the queued writer waits and then throws (IStorage.cpp:58-60).
c Fix matches root cause? Yes. The wrong object was being classified, so the fix resolves the storage that will execute the truncate and classifies that instead. The lock, when taken, is still taken on the same object as before; only the classification changed. No bound was widened and no check was suppressed. The test's one tag beyond no-replicated-database, zookeeper is memory-engine, which declares that a control arm depends on the Memory engine so the stress runner's engine-rewriting mode skips the test instead of silently rewriting that arm; it relaxes no assertion.
d Test intent preserved / new tests added? New test 04757_lazy_load_tables_truncate_lock.sh. It carries two witness arms (lazy MergeTree, lazy ReplicatedMergeTree) and two control arms (a plain non-MergeTree table that must stay blocked, and an eagerly loaded MergeTree that must stay exempt), and gates the fixture on engine = 'TableProxy' so it cannot pass against a materialized table. No existing test was modified.
e Both directions demonstrated? Yes, on Build-ID-asserted binaries with a per-arm server restart. Fix 0cdd21d9d3b7e833 passes (1 tests passed); pristine base 543324321f4a6762 fails, with both witness arms flipping to blocked=1 rows_after=300 and both controls unchanged. Three mutants each redden only their own arms: reverting the condition or dropping the unwrap reddens the two witness arms; making the classification unconditional reddens the non-MergeTree control, which is what proves that control is not vacuous.
f Fix is general across code paths? Scoped deliberately, and the scope is the finding. dynamic_pointer_cast<MergeTreeData> on a catalog object occurs at 8 sites; the others are reachable with a lazy proxy and silently take the non-MergeTree branch, but a loading unwrap in StorageSystemTables.cpp:992 would force-load every lazy table in the instance for one SELECT, which is worse than the bug. That class is being swept by #113389 with a non-loading resolver, and two residuals are named in the description. Within this decision the fix is complete: of the four StorageProxy subclasses, only StorageTableProxy may be classified through, because StorageURLSchemeDispatch::truncate bypasses the proxy to throw and StorageURLDatabaseTable::truncate forwards to a different storage than getNested.
g Fix generalizes across inputs? Yes, measured rather than argued. Both MergeTree and ReplicatedMergeTree behind a proxy become exempt. A lazy Log table, where the proxy cast succeeds and only the MergeTree cast fails, stays blocked on both the fixed and the unfixed binary. That cell is verified out of band rather than shipped as a test arm, because #113389 would make a lazily loaded non-MergeTree table unconstructible and such an arm would then go vacuous; the in-test arm carrying the same property is the plain non-MergeTree control, the only arm that reddens when the classification is made unconditional. A lazy Memory table is not a usable arm here: it is RAM-only, so it holds no rows after the re-attach that makes it a proxy again, and any insert materializes it. StorageAlias is not a StorageProxy, so alias behaviour is byte-identical.
h Backward compatible? Yes. No setting, no default, no serialization format, and no metadata is touched, so no SettingsChangesHistory.cpp entry applies. The only behaviour change is that a TRUNCATE which previously failed with DEADLOCK_AVOIDED now succeeds, matching the eagerly loaded case. Everything else keeps taking the lock.
i Invariants and contracts preserved? The relevant contract is IStorage::truncate's doc comment requiring the exclusive lock, and it is already violated on master for every eagerly loaded MergeTree by this same branch, so the divergence is extended rather than created. Neither MergeTree truncate reads the holder: StorageMergeTree::truncate's parameter is unnamed (src/Storages/StorageMergeTree.cpp:2646) and StorageReplicatedMergeTree::truncate only calls table_lock.release() (src/Storages/StorageReplicatedMergeTree.cpp:7420). Reader safety rests on shared_ptr part ownership plus the isSharedPtrUnique gate in grabOldParts (MergeTreeData.cpp:3957-3962). No new throw site is added: checkTableCanBeDropped already resolves the nested storage five lines earlier, so a proxy whose load fails throws before the new code runs, and nothing is swallowed.

Session id: cron:clickhouse-review-slot-50:20260806-081400

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @evillique @yariks5s, could you review this? InterpreterDropQuery decided the MergeTree TRUNCATE lock exemption by casting the object held in the catalog, which for a lazy_load_tables = 1 database is a StorageTableProxy, so the cast failed and the exclusive lock was taken while readers held the same object; the fix classifies the nested storage that actually executes the truncate. @evillique, this is the same proxy-classification class as the lazy-load sweep linked in the description, at a site that PR does not touch.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5096fc7]

Summary: ✅


AI Review

Summary

This PR fixes the TRUNCATE TABLE lock-classification bug for lazily loaded MergeTree tables by deciding the MergeTree exemption on the nested storage behind StorageTableProxy, while still taking the outer table's lock that concurrent readers actually hold. The new stateless test exercises lazy MergeTree, lazy ReplicatedMergeTree, and non-MergeTree controls, and I did not find any remaining correctness, locking, or coverage issues in the current patch or in the previously raised review threads.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 5096fc7.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 9/9 (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 Aug 6, 2026
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — a827fba

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
BuzzHouse (amd_msan) / Logical error: Chunk info was not set for chunk in GroupingAggregatedTransform (STID 3970-479a) chronic trunk, not this diff: 12 rows over 10 distinct PRs in 90 days, nine of them unrelated to lazy loading or TRUNCATE #113266 (external, open)
Integration tests (amd_msan, 6/8) / test_storage_rabbitmq/test.py::test_rabbitmq_mv_combo trunk-reaching flaky (90 d: 14 master failures against 13958 master passes, 126 failures overall across many unrelated PRs), and the previously merged fix for this test is present in this build yet it still timed out, so that fix does not own this row a fix task is created (investigating at full effort — fixing-PR link to follow on this PR)
Build (arm_release) / Post Hooks build-profile telemetry INSERT rejected while the shared CI logs cluster is under a server-wide memory-pressure spike; the Build (arm_release) check itself is green, so this row is non-gating #113409 (external, merged 2026-08-06T00:05Z) — this build predates the fix: ci/jobs/scripts/log_cluster.py carries data.seek(0) on master and not at this commit, and the head is 582 commits behind that merge

On the test_rabbitmq_mv_combo row: I am deliberately not linking #110224 here. It is merged, and
I verified its parallel_view_processing=1 profile override is present at this exact commit
(tests/integration/test_storage_rabbitmq/configs/users.xml, 1 occurrence at this commit and on
master, 0 at that PR's own pre-merge parent as a negative control). The test failed with the fix
in the build, so linking it would be a false owner.

Session id: cron:our-pr-ci-monitor:20260806-153000

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Integration tests (amd_msan, 6/8) test_rabbitmq_mv_combo timeout on the CI finish ledger (covered SHA a827fba6d8dc32f3b3467f1462e6fcbcf54ca263): #113972

@groeneai groeneai added the groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 4, 2026
groeneai and others added 2 commits September 9, 2026 12:32
…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]>
@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto master. One conflict, in the TRUNCATE branch of
InterpreterDropQuery::executeToTableImpl: #114672 rewrote the same statement, so the exempt path
now takes a share lock rather than no lock. I kept that shape verbatim and re-applied only the
classification, which leaves one include, the resolver, and one identifier inside the condition.

Two consequences of the new shape sit in the description rather than the code. This no longer
removes a lock: a lazily loaded MergeTree moves from the exclusive lock to that share lock, which
readers also hold in share mode. And supportsReplication() is forwarded by the proxy, so such a
table now also reaches the ddl_guard.reset() #114672 added, as an eagerly loaded one does.

The defect itself survives #114672, since master still classifies on the raw catalog object. On the
merged tree 04757 passes with the fix and fails without it, arms A and B reading
blocked=1 rows_after=300, byte-identical to the pre-rebase run.

I also added arm E_lazy_log. The previous four arms could not distinguish this change from a
coarser one that exempts every StorageTableProxy regardless of the nested engine, because the only
non-MergeTree control was in the eagerly loaded database. A Log table is still lazily loaded on
master, so that arm covers the case, and building exactly that mutant reddens only the new arm.

Session id: cron:clickhouse-maint-slot-16:20260909-120800

@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5096fc7c3 with master e6097f19d (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.

Object file sizes

4 object files changed (+232.80 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/InterpreterDropQuery.cpp.o 392.07 KiB 624.85 KiB +232.78 KiB (+59.37%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, fix conflicts.

@alexey-milovidov alexey-milovidov 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.

Hm, okay.

@alexey-milovidov alexey-milovidov self-assigned this Sep 22, 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.
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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Conflicts fixed by merging master (5968d02); the PR is MERGEABLE again.

The single conflict was the exempt condition itself: #119105 replaced dynamic_pointer_cast<MergeTreeData>(table) with the virtual table->isMergeTree(). Taking master's side verbatim would have quietly emptied this PR, because StorageProxy does not forward isMergeTree(), so a lazy_load_tables proxy answers the inherited false and keeps the exclusive lock. Resolved by keeping master's predicate and running it on the storage that executes the truncate: table_to_classify->isMergeTree(). An Alias is unaffected: it is not a StorageTableProxy, so it still resolves through its target.

On the merged tree 04757_lazy_load_tables_truncate_lock passes, and reverting that one identifier back to table->isMergeTree() reddens it with A_lazy_mergetree blocked=1 rows_after=300 plus the same for the replicated arm, so the defect does survive #119105. 05153_alias_truncate_lock and 04838_truncate_does_not_block_ddl pass on the same binary.

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 Alias variant as needing its own fix after #119105 fixed it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5968d02

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error message in clickhouse-server.log (see upgrade_error_messages.txt) log scan red on a single MutateFromLogEntryTask line, Code: 40 ... Part all_0_0_0_2 from 2 has different columns hash ... Data after mutation is not byte-identical to data on another replicas; the recovery itself is handled (the part is fetched from the other replica), so what reddens the job is the log entry, not a failed test. The check's second configure re-rolls default_compression_codec, so a mutation that straddles the restart re-executes under a different codec and its checksums no longer match. Nothing in this diff touches mutations, compression or replication, and the same line hit 13 distinct pull requests in the last 14 days #121249 (mine, open)
Mergeable Check, PR praktika rollups, red only because the check above is red, with no independent failure of their own #121249 (mine, open)

The rest of the run is clean: 134 of 176 checks pass and 39 are skipped, with Fast test (both
flavours), Style check, Quick functional tests, CH Inc sync, all 27 builds, all 33 stateless
shards, all 36 integration shards and all 7 unit test jobs green.

Session id: cron:our-pr-ci-monitor:20260923-080258

…tion

# Conflicts:
#	src/Interpreters/InterpreterDropQuery.cpp
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e1c004a

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 6/6) / lower_upper_utf8_mixed_ascii #4 dashboard confirmed_regression, client_time 0.0132 -> 0.0154 s (+16.3%), while the shard's own report calls the query success (3 too long only). The dashboard scored it without master history: its C3, C4 and C5 modules are unavailable, so the bar was its 2% floor. The query is lowerUTF8 over a column of an ENGINE = Memory table and never runs a TRUNCATE, while the only product change in this PR is how InterpreterDropQuery.cpp classifies the table of a TRUNCATE the question for exactly this class (rows the dashboard scores without master history) is posted to its owner: #119556 (comment). Either the dashboard restores the history, or I send the in-tree fallback described there
Mergeable Check, PR rollups, red only because of the row above the same owner question as the row above: #119556 (comment)

All 172 check runs completed (130 pass, 39 not selected, 3 red: the row above and its two rollups),
Finish Workflow is green and CH Inc sync passed. CIDB has no FAIL or ERROR test row on this
head. The shard's 3 too long is informational: in master_head mode only run errors and dashboard
confirmed_regression rows fail a shard.

Session id: cron:our-pr-ci-monitor:20260927-173207

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the lower_upper_utf8_mixed_ascii #4 (arm_release 6/6) perf red: #122782, which reruns dashboard-confirmed rows after a server restart. Here the reference server was the outlier: 0.0132 s, against a median of 0.0146 s for the same reference build over its 9 runs, while this PR measured 0.0154 s.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 1, 2026
Merged via the queue into ClickHouse:master with commit 53f6677 Oct 1, 2026
149 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 1, 2026
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 comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-bugfix Pull request with bugfix, not backported by default 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.

4 participants