Repository navigation
Keep the target storage alive for a snapshot handed out by an Alias table - #120098
Conversation
…able StorageSnapshot refers to its storage through a bare reference, which is sound while the caller that took the snapshot holds a StoragePtr and consumes it inside that scope. StorageAlias is the one place that breaks the assumption: getStorageSnapshot() forwards to getTargetTable()->getStorageSnapshot(...), and getTargetTable() resolves through DatabaseCatalog and returns the owning pointer by value, so it dies at the end of the full expression. The returned snapshot then refers to the target with zero owners, while the TableNode built around it owns and share-locks the Alias instead. DatabaseCatalog::getTablesToDrop() decides a dropped table may be destroyed purely from isSharedPtrUnique(), so holding an owning StoragePtr *is* the "still in use" signal. With none held, a concurrent DROP let the background worker destroy the target while the planner was still reading it: a TSan heap-use-after-free in IStorage::getStorageID() called from calculateHashTableCacheKeys() during join reordering. Add an opt-in ownership token to StorageSnapshot, installed by the caller that already owns the storage, and opt in at the Alias boundary. The token is installed by returning a clone rather than by mutating, because one snapshot is shared between the readers of a query through the query metadata cache and the pinned snapshot of CREATE MATERIALIZED VIEW ... POPULATE; writing it in place would trade the use-after-free for a data race. The first writer wins, so an Alias-of-Alias chain keeps the innermost referent pinned instead of an intermediate alias -- an unconditional overwrite would drop the correct pin and retain the bug in a release build. Both clone() overloads carry the token, since they keep the same storage reference. Default-empty means no behavioural change for any existing snapshot: only the Alias path now defers its target's drop while a snapshot is live, which is the protocol working as intended. This generalizes MergeTreeData::SnapshotData's existing storage holder, which is why the freed table was a Distributed: a MergeTree target is already pinned through its own SnapshotData, so the gap only bit engines falling through to the base IStorage::getStorageSnapshot(). Co-Authored-By: Claude Opus 5 <[email protected]>
…he reported chain Follow-up on the same branch, tests and comments only. No behavioural change. The stateless test did not reach the code path from the report. Filter collection is decided per table expression on the storage that expression resolves to, and for an Alias that is the StorageAlias itself, never its target, so an Alias of a Distributed does not by itself make the planner build the analysis plan that carries a snapshot into join reordering. Verified with a temporary log line in calculateHashFromStep: the previous shape printed no ReadFromDummy at all. The JOIN's right side is now a View over the same right-hand table, which is another entry of the same predicate that asks for filter collection, and because that flag is query-wide it dummies every table expression including the Alias. The same instrumentation then prints ReadFromDummy over the Alias's target Distributed, a table that never appears as a table expression in the query, so the snapshot reaching the pass can only be the one the Alias handed out. A second Distributed, which would be the more direct choice, cannot be used: two Distributed table expressions in one JOIN are refused with DISTRIBUTED_IN_JOIN_SUBQUERY_DENIED under the default distributed_product_mode. The test also clamps query_plan_optimize_join_order_limit away from zero, the one value that skips join reordering entirely and which randomization picks about 5% of the time. Since a mistyped clamp line is silently ignored, the clamp was validated by reading the effective value out of system.query_log over 100 randomized runs, and by confirming that corrupting the line brings zero back. Two changed lines had no mutation coverage. The two-argument StorageSnapshot::clone is reached on an ordinary read whose table expression carries FINAL or SAMPLE, because TableNode re-wraps the snapshot through it, and StorageAlias::getStorageSnapshotWithoutData is a second producer independent of its twin. Dropping the token from either one left every existing assertion green. Both now have an arm and a negative control. Also applies the in-tree convention of writing a function name as f rather than f() to the comments this branch adds, and corrects the test header, which claimed the query neither owns nor share-locks the target: StorageAlias::read does both for the plan's lifetime. What the target lacks an owner for is the snapshot handed out at name-resolution time, because the table expression owns and locks the Alias instead.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 6 findings over 2 rounds;
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20260914-222100 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20260914-203800 |
|
Workflow [PR], commit [9ed383a] Summary: ✅
AI ReviewSummaryThis PR adds an opt-in owner token to Final Verdict✅ No actionable findings. LLVM Coverage ReportMeasured on commit 9ed383a.
Changed lines: Changed C/C++ lines covered: 97/98 (98.98%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units812 translation units recompiled, 5806 s compile time in total, 812 of them have a recent master baseline. Median compile-time ratio to the baselines is ×0.94 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
For a pr-bugfix PR that adds a tests/queries/0_stateless file, the bugfix-validation post-hook in ci/jobs/scripts/workflow_hooks/new_tests_check.py requires at least one per-arch Bugfix validation job to report OK or XFAIL, that is, it requires the functional test to reproduce the bug on master HEAD. This functional test cannot: freeing the target under a live plan needs a race with the background drop worker, and a sequential .sql cannot order that. Both per-arch jobs ran it under three sanitizer flavours each, it passed all twelve runs on the pre-fix binary, and both reported SKIPPED with "Bug does not reproduce on this arch", which the hook deliberately does not count as a validation. The unit test is the oracle for the lifetime invariant, and the hook has a branch for that case: with no functional or integration test present it consults the unit validator and blocks only if that validator refutes the test. Removing the stateless test routes this PR through the branch that matches how the defect is actually proven, instead of leaving it to claim a reproduction it never made. Its own header already said the use-after-free is asserted by the unit test rather than by it. What goes with it is shape and reachability coverage, not regression coverage. The gtest arms cover the ownership token, both clone overloads, release with the last snapshot, non-mutation of the source snapshot, the innermost-referent rule for an Alias chain, and both StorageAlias accessors, each verified to fail under a targeted mutation.
Removed the stateless test so the fix validates on the unit testFor a That is measured on this PR rather than predicted. Both per-arch jobs ran With no functional or integration test in the PR, the hook consults the unit validator instead and blocks only if that validator refutes the test. That is the branch that matches how this defect is proven here: the gtest arms are the oracle for the lifetime invariant, and each was checked to fail under a targeted mutation, including reverting either Head is now |
|
cc @nauu |
CI finish ledger - 1d9a64bEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Fix presence was measured on the tree that actually ran, not on the live head: the pin
Session id: cron:our-pr-ci-monitor:20260915-073106 |
`StorageSnapshot` keeps a bare reference to its storage, and `Alias` returned that snapshot after the temporary from `getTargetTable` was destroyed. `DataLakeCatalog` builds a new storage on every lookup, so the analyzer read freed memory under ASan in `test_alias_iceberg_catalog_cluster`. https://altinity-build-artifacts.s3.amazonaws.com/json.html?PR=2578&sha=d283c4830fe3a292b75b983c3887adc8641d6243&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%204%2F8%29 Related: #2578 Related: ClickHouse#120098 Related: #2557
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a use-after-free when a query reads through an
Aliastable whose target is dropped concurrently.StorageAliashanded out a storage snapshot that referenced the target without owning it, so the background drop worker could destroy the target while the query was still planning against it.Description
Related: #120042. ThreadSanitizer reported a
heap-use-after-free:IStorage::getStorageIDread a freedStorageDistributedfromcalculateHashTableCacheKeysduring join reordering, while the background drop worker destroyed that table.Root cause.
StorageSnapshotrefers to its storage through a bareconst IStorage &, which is sound while the caller that took the snapshot holds aStoragePtr.StorageAlias::getStorageSnapshotforwarded togetTargetTable()->getStorageSnapshot(...), andgetTargetTablereturns that owning pointer by value, so it died at the semicolon. The snapshot then referenced the target with zero owners, while theTableNodearound it owned and share-locked the alias.DatabaseCatalog::getTablesToDropgates destruction onisSharedPtrUniquealone, so an owningStoragePtris the "still in use" signal and nothing held one.Change.
StorageSnapshotgains an opt-in ownership token, supplied by the caller that already owns the storage;StorageAliasopts in. It is installed by returning a clone, not by mutating, because one snapshot is shared between the readers of a query. The first writer wins, so anAlias-of-Aliaschain pins the innermost referent. Bothcloneoverloads carry it. Default-empty, so only the alias path changes: a live snapshot defers its target's drop. This generalizesMergeTreeData::SnapshotData::storage, which is also why the freed table was aDistributed.Validation. A new gtest asserts the token pins,
clonecarries it, it is released with the last snapshot, the source snapshot stays non-owning, and a chain pins the innermost referent. Each assertion was checked to fail under a targeted mutation, including reverting eitherStorageAliasaccessor. There is no functional test: freeing the target under a live plan needs a race with the background drop worker, which a sequential.sqlcannot order; the gtest is the oracle.No frame of the report names
StorageAlias, so the alias is the inferred producer of the unowned snapshot and I have not marked #120042 closed. CI provenance, on bystander carrier PR #116234: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=116234&sha=54e041cde7890d18373ebdd4e233de871f7218ba&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29Workflow [PR]
Sync PR [sync-upstream/pr/120098]
Version info
26.10.1.215(included in26.10and later)