Repository navigation
Break a Context retain cycle in the DatabaseReplicated digest finalizer - #113953
Conversation
|
Validation, condensed. Reproduced deterministically without fault injection: No coverage is lost: with
|
|
cc @tavplubix @evillique, could you review this? The digest finalizer registered on the DDL metadata transaction captured its own owning |
|
Workflow [PR], commit [c88d736] Summary: ❌
AI ReviewSummaryThis PR breaks the Final Verdict
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 0/0 (nothing coverable) · Uncovered code |
Build profile diff (arm_release)No arm_release build profile data for commit c88d736 - the build was skipped, reused from cache, or predates profile upload. |
CI finish ledger - a9b4673CI is fully finished on this head: 175 check runs, 0 queued or in progress,
Session id: cron:our-pr-ci-monitor:20260808-230000 |
|
Fixing PR for the It breaks a Not caused by this PR, and nothing to change here. Analysis: #113954 (comment) |
azat
left a comment
There was a problem hiding this comment.
Tons of text, keep only essential info, but the fix looks good
| auto context = weak_context.lock(); | ||
| if (!context) | ||
| return; |
There was a problem hiding this comment.
context cannot expire, so replace it with chassert()
There was a problem hiding this comment.
Done in f654f83, and the invariant checks out empirically, not just by reading.
I instrumented both finalizers on an ASAN build to log every lock() outcome, and drove a
replicated-DDL workload with the digest-check sampling gate forced off
(database_replicated_force_metadata_digest_check): 41 DDL entries, 38 digest checks.
assertDigestInTransactionOrInline registered 10 finalizers, 2 bodies ran with a live
context, and the lock failed 0 times. The other 8 are the leaking case, where multi
throws and the finalizer never runs at all, so nothing observes the pointer. Rebuilt with
chassert(context): identical counters, 0 assertion failures.
One caveat so the zero is not overstated: in that workload assertDigest (the
isInternalQuery site) was never registered, so its 0 is vacuous rather than a
measurement. I applied the same chassert there because the reasoning is identical, that
site's finalizer also only runs from commit, but the empirical part covers
assertDigestInTransactionOrInline only.
There was a problem hiding this comment.
This still has a real expiration path. In replicated-database DDL execution, the outer query context gets a ZooKeeperMetadataTransaction in DatabaseReplicatedTask::makeQueryContext (src/Interpreters/DDLTask.cpp:690-698). InterpreterDropQuery::executeToDatabaseImpl then creates table_context = Context::createCopy(getContext()); table_context->setInternalQuery(true); for the per-table drops (src/Interpreters/InterpreterDropQuery.cpp:520-521, :676).
That copy is an internal subquery (src/Interpreters/Context.cpp:3688-3691), so DatabaseAtomic::dropTableImpl deliberately skips txn->commit() on it (src/Databases/DatabaseAtomic.cpp:220-222), but DatabaseReplicated::dropTable still registers the finalizer on that copied context (src/Databases/DatabaseReplicated.cpp:2497-2531). DDLWorker commits the outer query context's transaction later (src/Interpreters/DDLWorker.cpp:593-598), after table_context has already gone out of scope, so weak_context.lock() can legitimately return nullptr here and the new chassert becomes reachable.
There was a problem hiding this comment.
Checked all five cited sites: they exist as described. The inference does not hold, because the copy carries no transaction.
shouldReplicateQuery returns false for a database-level DROP (DatabaseReplicated.cpp:2955-2962), so DROP DATABASE never goes through the replicated DDL log and no DatabaseReplicatedTask::makeQueryContext runs for it. The outer context therefore has no ZooKeeperMetadataTransaction for the copy to inherit, and executeToDatabaseImpl calls stopReplication() at :493 before creating the copy at :520.
Measured on an instrumented ASAN build (DROP DATABASE SYNC and non-SYNC over 5 tables plus a materialized view, and DETACH DATABASE; failpoint database_replicated_force_metadata_digest_check on): 11 DatabaseReplicated::dropTable calls, 3 table_context copies with outer_has_txn=false and copy_has_txn=false in 3 of 3, site A entering its internal branch 10 times with has_txn=false in 10 of 10. Finalizers registered on that path: 0. lock() returning null: 0. A plain replicated DROP TABLE control in the same run does reach dropTable with has_txn=true, so the counters were live.
With no transaction there is no addFinalizer call, so the claim fails at its first premise rather than at the lifetime argument. Keeping the chassert.
One thing worth separating: isInternalQuery() (Context.h:1766) and isInternalSubquery() (Context.cpp:3680) are different predicates. The skip-commit gate reads the second, assertDigest reads the first. Both were true here, so it is not what breaks the argument.
Still open, as stated in my earlier reply: site A has never been observed registering a finalizer, so its chassert rests on symmetry with site B rather than on a measurement.
|
Text trimmed: the description is down from 4.5k to 2k characters, the internal-review comment On the paste: that is the same failure mode, reached more directly than my harness does. The |
|
Rebase and squash all changes, the history is useless in this case. |
`DatabaseReplicated::assertDigest` and `assertDigestInTransactionOrInline`
register a finalizer on the DDL metadata transaction that captured
`local_context` by value, i.e. as a strong `ContextPtr`. The same `Context`
strongly owns that transaction (`ContextData::metadata_transaction`), and
`Context::initZooKeeperMetadataTransaction` asserts the owner is that very
`Context`, so the capture closed a reference cycle:
Context -> metadata_transaction -> finalizer -> ContextPtr -> the same Context
The cycle is broken only by `ZooKeeperMetadataTransaction::commit` succeeding,
which runs the finalizer and then clears it. If `current_zookeeper->multi()`
throws (a Keeper session loss, or a query killed before `commit`), the finalizer
is never cleared, `~ZooKeeperMetadataTransaction` is `= default`, and the whole
`Context` graph is retained for the lifetime of the process. Capturing a weak
reference removes the cycle at the edge that creates it.
The finalizer only ever runs from `commit`, and every `commit` caller reaches it
through `local_context->getZooKeeperMetadataTransaction()`, so the registering
`Context` is alive across the call and the lock cannot fail. A `chassert`
documents that invariant rather than a dead runtime branch.
Both call sites are inside `#if defined(DEBUG_OR_SANITIZER_BUILD)`, so a release
build never registers the finalizer and has no cycle. The visible symptom is a
`Stress test (*_asan_ubsan)` job failing with `LeakSanitizer: detected memory
leaks`, reporting zero direct and N indirect leaks whose largest object is a
`DB::Settings` copy allocated in `Context::createCopy`. All-indirect is the
signature of a retain cycle. The CI artifacts name the closure itself: an
`Indirect leak of 24 byte(s)` allocated in
`assertDigestInTransactionOrInline(...)::$_0`, 24 bytes being the captured
`this` plus the `shared_ptr`.
Co-Authored-By: Claude Fable 5 <[email protected]>
f654f83 to
c88d736
Compare
|
Rebased onto master and squashed to a single commit: |
CI finish ledger - c88d736CI is fully finished on this head: 175 check runs, 0 queued or in progress,
The fix landed 62 minutes after this job started, so this build predates it: the file at this head still lacks the
Session id: cron:our-pr-ci-monitor:20260809-183000 |
89cdcdf
Repro - https://pastila.nl/?01eb64cc/50ef5c57e055be93ad88bd986be03c79#vXR4xuaQmEQ7Srt5FyeFnw==GCM
Sanitizer report - https://pastila.nl/?0000178e/79200a19fc7bf34a10da9445d8aa1749.terminal#2hyvhihFlzkbrQ4087lBjg==GCM
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Description
Related: #113954
Stress test (*_asan_ubsan)fails withLeakSanitizer: detected memory leaks, allindirect and zero direct, the largest object being a
DB::Settingscopy fromContext::createCopy. Seen on 14+ unrelated pull requests, none on master.DatabaseReplicated::assertDigestandassertDigestInTransactionOrInlineregister afinalizer on the DDL metadata transaction that captures
local_contextas a strongContextPtr, while the sameContextowns that transaction viaContextData::metadata_transaction. That is a cycle, and only a successfulZooKeeperMetadataTransaction::commitbreaks it, by running the finalizer and clearingit. When
multi()throws, or the query is killed first, theContextgraph is retainedfor the process lifetime. All-indirect is the signature of a cycle: a chunk starts
kDirectlyLeakedand is downgraded only when another already-leaked chunk points at it.The fix captures a
ContextWeakPtr. Nothing else changes:commitruns the finalizerwhile its caller still holds the registering
Context, so the lock always succeedsthere, which is why the null case is a
chassertrather than a runtime branch.Both sites are inside
#if defined(DEBUG_OR_SANITIZER_BUILD), so release builds neverregister the finalizer.
Related:
2064-22d0, a second family withQueryTreeBuilderframes and no DDL frames, isa different retention (materialized-CTE plan self-reference) and is fixed by #113397, not
here.
Version info
26.8.1.1046(included in26.8and later)