Skip to content

Fix TRUNCATE of an Alias table with a lazily loaded target blocking on concurrent readers - #121703

Merged
nauu merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/alias-lazy-target-truncate-lock
Sep 26, 2026
Merged

nauu merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/alias-lazy-target-truncate-lock

Conversation

@groeneai

@groeneai groeneai commented Sep 23, 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):

TRUNCATE TABLE of an Alias table no longer waits for concurrent readers when the alias's target table is in a database with lazy_load_tables = 1. Previously such a statement failed with DEADLOCK_AVOIDED and the data was left in place.

Description

On 26.9, TRUNCATE TABLE <alias> whose target is in a database with lazy_load_tables = 1 fails with Code: 473 ... Possible deadlock avoided while a query reads it, and the rows remain; an eager target truncates immediately. Reported by the review bot on #113634.

Root cause. Such a target is a catalog stand-in that creates the real storage on first access, and StorageProxy does not forward isMergeTree(), so StorageAlias::isMergeTree() answered false for a lazy MergeTree and locked exclusively where a MergeTree truncate is entitled to a share lock.

Change. One file-local resolver, used by both lock decisions.

Why two sites. The alias's lock and the target's are decided separately, and each site must classify the pointer it locks, not a fresh catalog lookup a concurrent RENAME could move. Reverting either alone leaves the statement blocked, and the two then time out on different objects.

Elsewhere. The predicate's 16 other consumers are planner, insert and check decisions about a table the statement already reads or writes, so the flip aligns alias-over-lazy with alias-over-eager and loads nothing a read or plan would not. CHECK ALL TABLES now checks such an alias, as it already does an eager one.

Validation. 05153_alias_truncate_lock gains arms I (lazy MergeTree), J (lazy ReplicatedMergeTree) and K (lazy Log, a control that stays blocked). I and J go from blocked=1 rows_after=300 to blocked=0 rows_after=0, the existing arms unchanged; 50/50 randomized runs pass; a blanket "exempt every stand-in" variant reds K.

#113389 carries a base-class StorageProxy::isMergeTree() forward covering both sites; this is the narrow fix for the released symptom, as #119105 was for an eager target. A one-line comment in InterpreterDropQuery.cpp overlaps my #113634; whoever lands second resolves it. If you would rather land that forward, I will re-plumb onto it.


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

Version info

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

…n concurrent readers

`TRUNCATE TABLE <alias>` whose target table is in a database created with
`lazy_load_tables = 1` was rejected with `Code: 473 ... Possible deadlock
avoided` while any query was reading it, leaving the data in place. With an
eagerly loaded target of the same engine the identical statement returns
immediately and truncates.

A table of a `lazy_load_tables` database is kept in the catalog as a
`StorageTableProxy` stand-in that creates the real storage only in
`getNested()`, and `StorageProxy` deliberately does not forward
`isMergeTree()` so that a mere predicate cannot turn a listing into a load.
`StorageAlias::isMergeTree()` asked `tryGetTargetTable()`, which returns that
stand-in, so an alias over a lazy MergeTree answered `false`. The truncate
branch of `InterpreterDropQuery` therefore took the alias's lock exclusively
instead of the share lock a MergeTree is exempted to, and the reader holding
that same lock for share made it time out.

One file-local resolver now unwraps the stand-in, and both of the statement's
lock decisions use it: the predicate itself, and the independent decision
`StorageAlias::truncate` makes about the target's lock. The two applications
cannot be collapsed into one call, because the statement locks two different
objects and each site must classify the pointer it locks; re-deriving the
target inside `truncate` would classify a fresh catalog lookup while locking
the pointer already in hand, so a concurrent `RENAME` or `EXCHANGE` could
exempt a lock taken on a different storage. Reverting either site alone was
measured to leave the statement blocked, and the two then time out on
different objects, the alias and the target respectively.

The predicate is moved out of `StorageAlias.h` so that a header with 22
includers does not gain a dependency on `StorageTableProxy.h`. A
`StorageProxy::isMergeTree()` forward would be the broader shape but is out of
scope here: it would make a predicate materialize every lazy table, not only
aliased ones.

`05153_alias_truncate_lock` gains arms I (lazy `MergeTree`), J (lazy
`ReplicatedMergeTree`) and K (lazy `Log`). K is a control that must keep
excluding readers, so that an exemption firing for every stand-in is caught.
Its reader sits on the target rather than on the alias: with nothing holding
the alias, the only lock left that can time out is the target's, which is the
decision `StorageAlias::truncate` makes, whereas a reader of the alias would
stop at the interpreter's decision that arms I and J already cover. An
exemption applied to the truncate site alone was measured to red K, and to
leave every other arm green. The fixture asserts each target reads as
`TableProxy`, without which the arms could pass on eagerly loaded tables.

No setting, format or metadata change, so no `SettingsChangesHistory.cpp`
entry is required.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR labels Sep 23, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex). Two gate rounds, 2 findings then 0,
each preceded by my own cold read of the resulting code; one fix round between them.

# Sev Finding Verdict Evidence / action
1 ❌ Resolving the stand-in in the capability probe loads and starts the target before the target's own privilege check, at both the TRUNCATE and CHECK entrypoints DISAGREE Ordering conceded, severity not: a non-materializing probe must answer false, which is the defect rather than a remedy, and 03636_storage_alias_access_rights.sh still asserts ACCESS_DENIED for TRUNCATE TABLE (line 50) and CHECK TABLE (lines 76, 80) through an alias without target grants, identically on this branch and on its base in a 63-test A/B run. Noted, not blocking
2 ⚠️ The control arm cannot fail for the target-side lock decision: it reads through the alias, so the alias's lock times out first and the target-side decision is never reached AGREE, fixed Confirmed by the probe's own LOCKED_ON column, which named the alias: reading an alias share-locks the target as well, so a reader of the alias always trips the interpreter's decision first. The control now reads the target directly, and a mutation exempting every stand-in at the target-side decision reds only the reworked arm
3 💡 The interpreter comment named only one of the two cases in which the predicate is false AGREE, fixed It now names both a missing and a non-MergeTree target
4 💡 The predicate can now throw where it returned false, if the target cannot be loaded, and CHECK ALL TABLES selects tables without a handler AGREE, not acted on Measured rather than assumed pre-existing: an Alias already forwards about a dozen capability predicates (supportsReplication, isRemote, supportsSampling, supportsPrewhere and others) that StorageProxy resolves through the loading accessor, so isMergeTree() was the single one left unforwarded and an alias over a lazy target can already fail that way through each sibling. Noted, not blocking

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal
per finding. Findings on hunks unchanged by the fix round are auto-dropped.

@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [034fefb]

Summary: ✅


AI Review

Summary

This PR fixes the lock-mode regression for TRUNCATE TABLE on an Alias over a lazy MergeTree-family target by resolving StorageTableProxy before the isMergeTree() checks. The deadlock fix itself is plausible, but the current implementation still moves real target materialization ahead of the leaf table's authorization on TRUNCATE/CHECK paths, so I cannot approve it as-is.

Findings

❌ Blockers

  • [src/Storages/StorageAlias.cpp:69, src/Interpreters/InterpreterDropQuery.cpp:336, src/Interpreters/InterpreterCheckQuery.cpp:259] StorageAlias::isMergeTree() no longer behaves as a fail-closed capability probe: it materializes lazy targets before the target table's own TRUNCATE/CHECK authorization runs. That lets a user who can address the alias, but not the target, force startup of a lazy table and observe loader failures from the target instead of the expected ACCESS_DENIED. [dismissed by author -- https://github.com/Fix TRUNCATE of an Alias table with a lazily loaded target blocking on concurrent readers #121703#discussion_r4079601141] I still consider this real because the relevant invariant is "authorize before deriving anything from the guarded object", and StorageTableProxy::getNested() is exactly that derivation even when the eventual statement is denied.

  • [src/Storages/StorageAlias.cpp:372] The target-side lock decision in StorageAlias::truncate has the same problem on alias chains. getTargetTable(TargetAccess{..., AccessType::TRUNCATE}) authorizes only the next hop; if that hop is another Alias, resolveLazyStandIn(target_storage)->isMergeTree() recurses into the leaf and can materialize a lazy final target before that final hop's own TRUNCATE check runs. The engine already supports alias chains (05153_alias_truncate_lock.sh creates al_d_outer -> al_d_inner), so this is not a hypothetical shape.

Final Verdict
  • Status: ❌ Block
  • Minimum required actions:
    • Keep StorageAlias::isMergeTree() fail-closed on observer / pre-auth paths, or move the leaf target's authorization ahead of any load-based engine classification on the explicit TRUNCATE path.
    • Apply the same rule recursively for alias chains, not just a single alias hop.

LLVM Coverage Report

Measured on commit 034fefb.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 15/15 (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 Sep 23, 2026
@groeneai
groeneai requested review from evillique and nauu September 23, 2026 05:58
@clickhouse-gh clickhouse-gh Bot added the comp-special-table-engines Non-MergeTree table engines used to speed up/distribute execution (paper's 2nd category). label Sep 23, 2026
bool StorageAlias::isMergeTree() const
{
auto target = tryGetTargetTable();
return target && resolveLazyStandIn(target)->isMergeTree();

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.

StorageAlias::isMergeTree used to be a fail-closed capability probe, but this now materializes lazy targets via StorageTableProxy::getNested(). That happens before the target's own access check on both TRUNCATE TABLE <alias> and CHECK ALL TABLES: InterpreterDropQuery calls table->isMergeTree() before StorageAlias::truncate checks AccessType::TRUNCATE on the target, and TableCheckSource::getValidTable calls isMergeTree() before TableCheckTask or StorageAlias::getCheckTaskList perform the CHECK authorization.

So a user who can address the alias but lacks rights on the target can still force startup/materialization of a lazy table, and can observe loader failures from the target instead of the expected ACCESS_DENIED. I think the deadlock fix needs to stay in code that already has ContextPtr and has authorized the target, rather than making isMergeTree() itself call getNested().

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Measured on the branch head (88e7eda) against its base (ebb00cc), identity-asserted debug binaries. Observable: system.tables.engine, since StorageTableProxy::getName() answers the literal TableProxy until the nested storage exists; a privileged read is the positive control.

The ordering is real at the two sites you name. StorageAlias.cpp:327 is not one of them: it is reached only after getTargetTable(TargetAccess{local_context, AccessType::TRUNCATE}) at :320, so the target is authorized there already.

With a user granted only TRUNCATE ON <alias>, TRUNCATE TABLE <alias> materializes the lazy target on the branch and does not on the base. With a user granted only SHOW DATABASES, CHECK ALL TABLES does the same. In every arm the caller still gets Code: 497 ACCESS_DENIED, no data and no metadata, on both binaries.

Two results put that in context. A plain SELECT through an alias, by a user granted only SELECT ON <alias>, already materializes the lazy target on the base commit before the target's check denies it, so forcing a load through an alias is not new here. And on the base commit CHECK ALL TABLES skips an alias over a lazy MergeTree target silently, so the branch also returns that table to the check.

On the shape you suggest: no site holds a ContextPtr and has authorized the target today. The lock mode is chosen at InterpreterDropQuery.cpp:336, the target's TRUNCATE check lives in StorageAlias::truncate (StorageAlias.cpp:320), and that cannot run before the lock is held (:349). For CHECK, the filter is InterpreterCheckQuery.cpp:259 while the authorization is in TableCheckTask (:119-125), and CHECK ALL TABLES authorizes nothing per table before the filter, only SHOW DATABASES per database (:412). A probe that does not load cannot classify either: a cold StorageTableProxy caches the columns and an opaque factory, nothing about the engine.

What separates the two cases is the nature of the call site, which is what @ evillique is adding in #121332: DeferredTable::Load for an operation that names a table, as a TRUNCATE does and which loads the target one statement later anyway, and Skip for an observer walking the catalog, as getValidTable is. #113389 goes the other way and forwards isMergeTree() in StorageProxy itself, load included. I can re-plumb onto either, or resolve only an already-materialized stand-in, which drops both new arms and leaves a cold target's truncate on the exclusive-lock path. One line either way, so I would rather a reviewer picked.

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.

My preference is: keep StorageAlias::isMergeTree() fail-closed, let an explicit TRUNCATE TABLE <alias> load only after the leaf target for that hop is authorized, and keep catalog walkers like CHECK ALL TABLES on the Skip side for cold stand-ins.

That same rule still needs to hold for alias chains. In the current code StorageAlias::truncate at src/Storages/StorageAlias.cpp:372 can recurse from an authorized outer alias into a lazy leaf target via an inner alias before the leaf TRUNCATE check runs.

@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 034fefb4d70bbbec976eeaaf0b7d1372b79d36f7 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 88e7eda

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, 1/6) dashboard-verdict gate: job summary 8 too long; 1 confirmed regression(s) on the performance dashboard, while the shard's own report calls no query slower #121090 (mine, open), with #121189 (mine, open)
Mergeable Check praktika rollup of the row above #121090 (mine, open)
PR praktika rollup of the row above #121090 (mine, open)

Shards 2/6 through 6/6 all passed on this head, so this is a single-shard dashboard verdict
rather than a measured regression from this diff.

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

@PedroTadim

Copy link
Copy Markdown
Member

cc @nauu

@groeneai

Copy link
Copy Markdown
Collaborator Author

03823_lazy_load_tables in Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) is not caused by this diff: that flavour has never passed this test (0 OK / 10 FAIL over 30 days, across two PRs whose diffs are code-disjoint), while every other flavour passes it on this same head.

Fixing PR: #122047 (mine, open). It is a test-only change.

TableExclusiveLockHolder target_excl_lock;
TableLockHolder target_shared_lock;
if (target_storage->isMergeTree())
if (resolveLazyStandIn(target_storage)->isMergeTree())

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 is only post-authorization for a direct target. If target_storage is another Alias, getTargetTable(TargetAccess{..., AccessType::TRUNCATE}) at line 365 has authorized just that intermediate alias, and resolveLazyStandIn(target_storage)->isMergeTree() re-enters StorageAlias::isMergeTree() on the next hop. That can materialize a lazy leaf target before the leaf table's own TRUNCATE check runs. The engine supports such chains today; 05153_alias_truncate_lock.sh already creates al_d_outer -> al_d_inner.

So TRUNCATE TABLE through outer_alias -> inner_alias -> lazy_target still lets a user with TRUNCATE on the aliases but not on the leaf force startup or see loader failures from the leaf. The recursive alias case needs the same fail-closed treatment, or the leaf target needs to be authorized before any load-based engine classification.

@nauu
nauu added this pull request to the merge queue Sep 26, 2026
Merged via the queue into ClickHouse:master with commit 0070be3 Sep 26, 2026
176 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 26, 2026
alexey-milovidov pushed a commit to iliasabk/ClickHouse that referenced this pull request Sep 27, 2026
05153_alias_truncate_lock failed in
https://github.com/ClickHouse/ClickHouse/actions/runs/36297932393/job/108585515908
because its lazy targets were already loaded when it checked them: the
server log shows the concurrent 00076 query ab529e2a loading mt_i and
rmt_j through 05153's Alias tables between its ATTACH DATABASE and the
check.

00076 reads the column sizes of every table on the server. Excluding the
TableProxy and Alias engines in its system.tables subquery prevents the
load instead of hiding the rows: the IN set filters the tables before
any size is read. A TableProxy is a table of a lazy_load_tables database
that nothing has read yet, and reading its sizes loads it; an Alias
forwards the size read to its target, which can be such a table.

With a concurrent loop issuing 00076's query, 05153 failed 14 of 30 runs
with the old query, 11 of 30 when only TableProxy is excluded, and 0 of
30 with this change.

Related: ClickHouse#121703

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-simple-engines Lightweight single-node table engines: Log/StripeLog (append-only logs), Buffer (async batching),... label Nov 22, 2026
@clickhouse-gh clickhouse-gh Bot removed the comp-special-table-engines Non-MergeTree table engines used to speed up/distribute execution (paper's 2nd category). label Nov 22, 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-simple-engines Lightweight single-node table engines: Log/StripeLog (append-only logs), Buffer (async batching),... groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR 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