Repository navigation
Fix TRUNCATE of an Alias table with a lazily loaded target blocking on concurrent readers - #121703
Conversation
…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]>
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,
Severity: ❌ blocker / |
|
Workflow [PR], commit [034fefb] Summary: ✅
AI ReviewSummaryThis PR fixes the lock-mode regression for Findings❌ Blockers
Final Verdict
LLVM Coverage ReportMeasured on commit 034fefb.
Changed lines: Changed C/C++ lines covered: 15/15 (100.00%) · Uncovered code |
| bool StorageAlias::isMergeTree() const | ||
| { | ||
| auto target = tryGetTargetTable(); | ||
| return target && resolveLazyStandIn(target)->isMergeTree(); |
There was a problem hiding this comment.
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().
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger - 88e7edaEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Shards 2/6 through 6/6 all passed on this head, so this is a single-shard dashboard verdict Session id: cron:our-pr-ci-monitor:20260923-190314 |
|
cc @nauu |
|
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()) |
There was a problem hiding this comment.
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.
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]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
TRUNCATE TABLEof anAliastable no longer waits for concurrent readers when the alias's target table is in a database withlazy_load_tables = 1. Previously such a statement failed withDEADLOCK_AVOIDEDand the data was left in place.Description
On 26.9,
TRUNCATE TABLE <alias>whose target is in a database withlazy_load_tables = 1fails withCode: 473 ... Possible deadlock avoidedwhile 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
StorageProxydoes not forwardisMergeTree(), soStorageAlias::isMergeTree()answeredfalsefor 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
RENAMEcould 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 TABLESnow checks such an alias, as it already does an eager one.Validation.
05153_alias_truncate_lockgains arms I (lazyMergeTree), J (lazyReplicatedMergeTree) and K (lazyLog, a control that stays blocked). I and J go fromblocked=1 rows_after=300toblocked=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 inInterpreterDropQuery.cppoverlaps 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
26.10.1.758-master(included in26.10and later)