Skip to content

Break a Context retain cycle in the DatabaseReplicated digest finalizer - #113953

Merged
azat merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-databasereplicated-finalizer-context-retain-cycle-2064-2dbf
Aug 9, 2026
Merged

azat merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-databasereplicated-finalizer-context-retain-cycle-2064-2dbf

Conversation

@groeneai

@groeneai groeneai commented Aug 8, 2026 •

Copy link
Copy Markdown
Collaborator

Repro - https://pastila.nl/?01eb64cc/50ef5c57e055be93ad88bd986be03c79#vXR4xuaQmEQ7Srt5FyeFnw==GCM
Sanitizer report - https://pastila.nl/?0000178e/79200a19fc7bf34a10da9445d8aa1749.terminal#2hyvhihFlzkbrQ4087lBjg==GCM

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Description

Related: #113954

Stress test (*_asan_ubsan) fails with LeakSanitizer: detected memory leaks, all
indirect and zero direct, the largest object being a DB::Settings copy from
Context::createCopy. Seen on 14+ unrelated pull requests, none on master.

DatabaseReplicated::assertDigest and assertDigestInTransactionOrInline register a
finalizer on the DDL metadata transaction that captures local_context as a strong
ContextPtr, while the same Context owns that transaction via
ContextData::metadata_transaction. That is a cycle, and only a successful
ZooKeeperMetadataTransaction::commit breaks it, by running the finalizer and clearing
it. When multi() throws, or the query is killed first, the Context graph is retained
for the process lifetime. All-indirect is the signature of a cycle: a chunk starts
kDirectlyLeaked and is downgraded only when another already-leaked chunk points at it.

The fix captures a ContextWeakPtr. Nothing else changes: commit runs the finalizer
while its caller still holds the registering Context, so the lock always succeeds
there, which is why the null case is a chassert rather than a runtime branch.

Both sites are inside #if defined(DEBUG_OR_SANITIZER_BUILD), so release builds never
register the finalizer.

Related: 2064-22d0, a second family with QueryTreeBuilder frames and no DDL frames, is
a different retention (materialized-CTE plan self-reference) and is fixed by #113397, not
here.

Version info

  • Merged into: 26.8.1.1046 (included in 26.8 and later)

@groeneai

groeneai commented Aug 8, 2026 •

Copy link
Copy Markdown
Collaborator Author

Validation, condensed.

Reproduced deterministically without fault injection: detachTablePermanently adds
remove(<zookeeper_path>/metadata/<table>) to the transaction before registering the
finalizer, so deleting that znode out of band makes multi fail ZNONODE every time. 10 of
10 DETACH ... PERMANENTLY failed at the commit, 0 at the enqueue. Pre-fix the parent commit
reports 246560 byte(s) leaked in 430 allocation(s), 0 direct, including ten copies of a
24-byte closure symbolizing to assertDigestInTransactionOrInline(...)::$_0 (24 bytes = 8 for
this plus a 16-byte shared_ptr<const Context>). Same harness with the fix: no leaks, with
the leak check confirmed running in both arms.

No coverage is lost: with database_replicated_force_metadata_digest_check removing the
sampling gate, successful internal DDL performs 18 digest checks on both binaries, no errors.

git grep -n addFinalizer -- src/ is closed at three hits: the two sites fixed here plus the
declaration. No committed regression test, because no failpoint makes commit throw, the
assertDigest* methods are private, and the only oracle is LeakSanitizer's end-of-run report,
which no in-suite test reads.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @tavplubix @evillique, could you review this? The digest finalizer registered on the DDL metadata transaction captured its own owning Context by strong pointer, so when multi() throws the finalizer is never cleared and the whole Context graph leaks for the process lifetime, which is the all-indirect LeakSanitizer report on Stress test (*_asan_ubsan).

@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c88d736]

Summary: ❌

job_name test_name status info comment
Stress test (amd_asan_ubsan) FAIL
S3_ERROR No such key thrown (see clickhouse-server.log or no_such_key_errors.txt) FAIL cidb

AI Review

Summary

This PR breaks the Context -> ZooKeeperMetadataTransaction -> finalizer -> Context retain cycle in the DatabaseReplicated digest checks by switching the finalizer capture from a strong ContextPtr to a ContextWeakPtr. I re-traced the two finalizer registration sites, the transaction commit paths, and the earlier expiry concern from the review thread, and I did not find a remaining path on c88d736 where the weak capture can expire before commit() executes the finalizer.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.80% -0.10%
Branches 78.90% 78.90% +0.00%

Changed lines: Changed C/C++ lines covered: 0/0 (nothing coverable) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

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.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a9b4673

CI is fully finished on this head: 175 check runs, 0 queued or in progress, Finish Workflow success. Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be posted here when it opens. Neither is caused by this diff, which touches only the DatabaseReplicated digest finalizer.

Check / test Reason Owner / fixing PR
Stress test (arm_asan_ubsan, s3) / Sanitizer (STID: 2064-22d0) LeakSanitizer, all-indirect. Frame-keyed check on this row shows Context::createCopy from QueryTreeBuilder::buildSelectExpression, i.e. the query-path sibling this PR explicitly does not cover (this PR fixes the makeQueryContext DDL-finalizer cycle, STID 2064-2dbf). 30d breadth 17 rows / 16 PRs / 1 master, so not specific to this branch a fix task is moved to pending (investigating at full effort, fixing-PR link to follow on this PR)
Stress test (arm_debug) / Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization (STID: 6726-59f7) pre-existing trunk abort on the skip-index read path. The wider signature has 31 rows / 28 PRs / 3 master in 30d and predates this branch #112484 (mine, open)

Session id: cron:our-pr-ci-monitor:20260808-230000

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (*_asan_ubsan) LeakSanitizer failure (STID 2064-22d0) on this PR: #113397 (not mine, open, AI-review approved).

It breaks a MaterializedCTE <-> QueryPlan reference cycle: MaterializedCTE::plan is a strong unique_ptr<QueryPlan> and the MaterializingCTEStep appended into that same plan held a strong handle back to the CTE, so a query that builds a materialized-CTE plan and then abandons it leaks the whole graph, including the Context::createCopy from QueryTreeBuilder::buildSelectExpression at the root of the reported stacks. @ alexey-milovidov attached this exact CI signature to that PR in #113397 (comment).

Not caused by this PR, and nothing to change here. Analysis: #113954 (comment)

@azat azat 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.

Tons of text, keep only essential info, but the fix looks good

Comment thread src/Databases/DatabaseReplicated.cpp Outdated
Comment on lines +1320 to +1322
auto context = weak_context.lock();
if (!context)
return;

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.

context cannot expire, so replace it with chassert()

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.

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.

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 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.

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.

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.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

Text trimmed: the description is down from 4.5k to 2k characters, the internal-review comment
is deleted, and the validation comment is down from 6.7k to 1.2k.

On the paste: that is the same failure mode, reached more directly than my harness does.
Removing /test/rdb/metadata/t from Keeper makes the transaction's unconditional
remove op fail, so multi throws No node, commit has already set state = FAILED
before multi (DDLTask.cpp:771 vs :772), and the finalizer is therefore never run and
never cleared. That is exactly the retention this PR removes. My repro does the same znode
deletion, just through DETACH ... PERMANENTLY in a loop so LeakSanitizer has several
instances to report.

The chassert change is in f654f83; the empirical check is in the review thread above.

@azat

azat commented Aug 9, 2026

Copy link
Copy Markdown
Member

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]>
@groeneai
groeneai force-pushed the fix-databasereplicated-finalizer-context-retain-cycle-2064-2dbf branch from f654f83 to c88d736 Compare August 9, 2026 13:53
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto master and squashed to a single commit: c88d736. Content is byte-identical to the approved f654f83.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c88d736

CI is fully finished on this head: 175 check runs, 0 queued or in progress, Finish Workflow success at 18:22:52Z, 87 success, 12 skipped, 1 failure. Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
Stress test (amd_asan_ubsan) / S3_ERROR No such key thrown Not caused by this diff. The blob-deleting test is 04630_merge_over_stale_packed_tmp_dir, which copies a packed part directory with cp; on a remote disk that duplicates metadata without incrementing blob refcounts, so reclaiming the stale directory deletes blobs the live part still references. Stress jobs flip the default MergeTree storage_policy to cached S3 or Azure, so its no-object-storage tag did not protect them. 14d breadth 34 rows / 31 distinct PRs / 2 master runs, and 9 rows across 5 PRs predate this branch #113978 (not mine, merged 2026-08-09T18:02:59Z)

The fix landed 62 minutes after this job started, so this build predates it: the file at this head still lacks the storage_policy = 'default' pin that #113978 adds. A fresh run on a head containing it should be green.

Build (arm_release) / Post Hooks is deliberately not a row: it reports a LogCluster query failed with code 500 inside the build-profile hook, and the check itself concluded success (check_status = success in the CI database), so it is not a failed check.

Session id: cron:our-pr-ci-monitor:20260809-183000

@azat
azat added this pull request to the merge queue Aug 9, 2026
Merged via the queue into ClickHouse:master with commit 89cdcdf Aug 9, 2026
179 of 181 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 9, 2026
@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-ci 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