Skip to content

Fix use-after-free in borrowed ThreadGroup parent counters - #108577

Closed
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-borrowed-threadgroup-uaf
Closed

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-borrowed-threadgroup-uaf

Conversation

@groeneai

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):

Fixed a use-after-free where a materialized-view / async-insert "borrowed" thread group could outlive the parent query's thread group, causing a crash while updating ProfileEvents counters or the memory tracker.

Description

A borrowed child ThreadGroup (createForMaterializedView / createForFlushAsyncInsertQueue) stores raw pointers into its parent group's performance_counters and memory_tracker, but did not keep the parent alive. The invariant in MemoryTracker.h ("Lifetime of these trackers should include lifetime of current tracker") was unenforced.

When the borrowed child is pinned past the source query's end (e.g. a per-table MergeTreeDeduplicationLog writer whose thread-pool scheduler captured the current group under s3_allow_parallel_part_upload), the parent group is freed while the child still references it. The next counter increment / attach then walks the freed parent chain in ProfileEvents::Counters::increment (current = current->parent) or MemoryTracker::setParent, reading freed memory.

Root cause was identified by @ filimonov in the instrumentation PR #107030 (ASan report: https://gist.github.com/filimonov/1ec59047c65e3a5367c5c83f6021cc27).

Fix: the borrowed child now holds a shared_ptr to its parent group, declared before the two trackers so it is destroyed after them. No reference cycle (a child references its parent only). Adds a unit test that drops the only external parent reference while a borrowed child is alive and checks the parent stays alive and increment/attach through the child does not touch freed memory.

Surfaced in CI as a sanitizer/segfault crash in ProfileEvents::Counters::increment at thread-group attach/detach (TSan amd_tsan s3: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105890&sha=3dc0e76362eb18e27f1fffcd3f61ca9f13725fe8&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20s3%20storage%2C%20sequential%2C%201%2F2%29 ; ASan Stress arm_asan_ubsan: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101549&sha=ee6992be72ffa65500f361740ec846b912eaa872&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29 ).

A "borrowed" child ThreadGroup (createForMaterializedView /
createForFlushAsyncInsertQueue) stores raw pointers into its parent
group's performance_counters and memory_tracker, but did not keep the
parent alive. The documented invariant in MemoryTracker.h ("Lifetime of
these trackers should include lifetime of current tracker") was not
enforced.

When such a child is pinned past the source query's end (for example by
a per-table MergeTreeDeduplicationLog writer whose thread-pool scheduler
captured the current group under s3_allow_parallel_part_upload), the
parent group is freed while the child still references it. The next
counter increment or attach walks the freed parent counter chain in
ProfileEvents::Counters::increment / MemoryTracker::setParent, reading
freed memory.

Fix: the borrowed child now holds a shared_ptr to its parent group, so
the parent's counters outlive the child's raw pointers into them. The
member is declared before the two trackers so it is destroyed after
them. There is no reference cycle (a child points to its parent only).

Add a unit test that drops the only external reference to the parent
while a borrowed child is alive and verifies the parent is kept alive
and that incrementing/attaching through the child does not touch freed
memory.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Unit test BorrowedThreadGroupLifetime.ChildKeepsParentAlive deterministically observes the premature free via weak_ptr (no race/sanitizer timing needed): create parent group, create borrowed child, drop the only external parent ref, assert parent_weak.expired() == false.
b Root cause explained? The borrowed-child ctors (ThreadStatusExt.cpp:126, :140) store raw pointers into the parent via performance_counters(Process, &parent->performance_counters) / memory_tracker(&parent->memory_tracker, ...) but kept no shared_ptr to the parent. When the child is pinned past the query end (dedup-log writer's captured scheduler under s3_allow_parallel_part_upload), the parent group frees while the child lives; the next increment walks current = current->parent (ProfileEvents.cpp:1768) / MemoryTracker::setParent into freed memory.
c Fix matches root cause? Yes. The child now owns a shared_ptr to its parent (parent_thread_group), so the parent's counters outlive the child's raw pointers into them — directly enforcing the documented invariant. Not a defensive guard.
d Test intent preserved / new tests added? New gtest_borrowed_thread_group_lifetime.cpp (3 cases) added; it catches exactly this regression. No existing test weakened (existing ThreadGroupSwitcher.* still passes).
e Both directions demonstrated? Yes. With fix: 3/3 pass. With the two parent_thread_group(parent) init lines reverted (rebuilt): ChildKeepsParentAlive FAILS (parent_weak.expired() true).
f Fix is general across code paths? Both borrowed-group construction sites carry the same raw-parent-pointer pattern and both are fixed (createForMaterializedView ctor and createForFlushAsyncInsertQueue ctor). These are the only two ctors that borrow raw parent counter/tracker pointers.
g Fix generalizes across inputs? The fix is on the lifetime/ownership of the parent ThreadGroup, independent of query type, storage engine (not S3-specific per the root-cause), settings values, or data — it holds for every borrowed child regardless of input.
h Backward compatible? Yes. No setting, on-disk/wire/replication format, or user-visible behavior change. Pure in-memory ownership lifetime fix.
i Invariants and contracts preserved? Restores the documented MemoryTracker.h invariant ("lifetime of these trackers should include lifetime of current tracker"). No reference cycle (child references parent only; parent never references child). parent_thread_group is declared before the two trackers, so it is destroyed after them — the raw pointers are valid for the trackers' entire lifetime. Destructors of MemoryTracker/Counters do not dereference parent, so teardown order is safe.

Session id: cron:clickhouse-worker-slot-7:20260626-055100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat @al13n321 — could you review? A borrowed child ThreadGroup (MV / async-insert) holds raw pointers into its parent group's performance_counters/memory_tracker but did not keep the parent alive; when pinned past the query end (dedup-log writer's captured scheduler) the parent frees first and counter increment / setParent reads freed memory. Fix makes the child own a shared_ptr to its parent. Root-caused by filimonov in #107030.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c62a4ce]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue
Stress test (arm_tsan) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue

AI Review

Summary

This PR fixes a lifetime bug in borrowed ThreadGroup instances by keeping the parent ThreadGroup alive while the child holds raw parent pointers in performance_counters and memory_tracker. The change is scoped to the two borrowed constructors, preserves destruction order for the raw-pointer members, and adds focused unit coverage for both borrowed construction paths plus attach/increment behavior after the external parent reference is dropped.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — f74d935

Every failure below has an owner: a fixing PR (ours 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
Stress test (amd_asan_ubsan) / Hung check failed, possible deadlock found deadlock (chronic hung-check family; unrelated to this ThreadGroup-lifetime fix) #101680 / #105905 (ours, open)
Upgrade check (amd_release) / Error message in clickhouse-server.log flaky log-noise (MutatePlainMergeTreeTask CANNOT_PARSE_TEXT "Cannot parse string 'x' as UInt64"; chronic, 0 master; unrelated to this PR) #108563 (ours, open)

This PR adds a parent_thread_group shared_ptr member to the borrowed-child ThreadGroup (fixes the parent-counter UAF); neither failure is in its changed files. Finish Workflow + Style check pass on this head.

Session id: cron:our-pr-ci-monitor:20260626-170000

@cv4g cv4g self-assigned this Jun 30, 2026
@cv4g

cv4g commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

@groeneai Can you please add an additional unit test covering ThreadGroup(ContextPtr query_context_, ThreadGroupPtr parent) too?

The fix touches two borrowed-child ThreadGroup constructors, but the
existing tests only exercised the one-arg ThreadGroup(ThreadGroupPtr)
(createForMaterializedView path). Add a case for
ThreadGroup(ContextPtr query_context_, ThreadGroupPtr parent)
(createForFlushAsyncInsertQueue path), asserting the same
parent-lifetime invariant: dropping the only external parent reference
must keep the parent alive through the child, and incrementing through
the borrowed counters must not touch freed memory.

Verified both directions: with the two-arg ctor's parent_thread_group
init reverted the new case fails (parent freed, weak_ptr expired); with
the fix all four cases pass.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

@cv4g Done in c62a4ce. Added BorrowedThreadGroupLifetime.TwoArgCtorChildKeepsParentAlive, which constructs a borrowed child via ThreadGroup(ContextPtr query_context_, ThreadGroupPtr parent) (the createForFlushAsyncInsertQueue path), drops the only external parent reference, and asserts the parent stays alive plus that incrementing through the borrowed counters does not touch freed memory.

Validated both directions locally (debug, ENABLE_TESTS=ON): with the two-arg ctor's parent_thread_group(parent) init reverted the new case fails (parent_weak.expired() is true), with the fix all four cases pass.

Comment thread src/Common/ThreadStatus.h
/// performance_counters and memory_tracker below hold RAW pointers into the parent group's
/// counters. Keep the parent alive so those pointers never dangle. Declared before the two
/// trackers so it is destroyed after them (members are destroyed in reverse order).
ThreadGroupPtr parent_thread_group;

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.

I don't like this fix, this can leave live leak.

Why parent group is not alive? Can we address this instead?

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.

@azat agreed, the shared_ptr trades the UAF for a leak: it pins the transient query group for as long as anything holds the borrowed child, so that is not the right fix.

Root cause (from the freed-by stack in filimonov's ASan report): a long-lived per-table MergeTreeDeduplicationLog writer captures getCurrentThreadGroup() in its WriteBufferFromS3 TaskTracker runner while an MV insert is current, so it pins a query-scoped borrowed child group. Nothing holds the parent (query) group except the child's raw pointer, so the parent is freed at query end while the writer still holds the child; a pool worker then attaches the borrowed child and MemoryTracker::setParent walks the freed parent chain.

So the fix belongs at the capture: a per-table / long-lived writer must not run under a transient borrowed group. My plan is to run the dedup-log writes detached from the query group (stable server group), which makes "parent not alive" moot and avoids the leak.

Could you share filimonov's suggested fix? I will implement the one you two agreed on rather than pick between equivalents.

@azat

azat commented Jun 30, 2026

Copy link
Copy Markdown
Member

@cv4g BTW I've discussed this with the author of #107030 (@filimonov) he suggests better fix

@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.60% 77.70% +0.10%

Changed lines: Changed C/C++ lines covered: 60/60 (100.00%) · Uncovered code

Full report · Diff report

@cv4g cv4g closed this Jun 30, 2026
pull Bot pushed a commit to CrazyForks/ClickHouse that referenced this pull request Jul 8, 2026
Borrowed groups keep raw accounting pointers into their parent query group, but they must not own that parent. Mark borrowed groups by construction, expose `isBorrowed`, and add `getCurrentThreadGroupForAsyncCallback` to drop borrowed groups at async boundaries.
This replaces the earlier parent-retention guard with focused tests for dropping borrowed async captures and for not extending parent `ThreadGroup` lifetime.

Capture async `ThreadGroup` per queued task
`threadPoolCallbackRunnerUnsafe` no longer stores a `ThreadGroupPtr` in the long-lived scheduler object. It captures a normalized group only when a concrete task is queued, so storing the runner in `TaskTracker` or `WriteBufferFromS3` does not pin the query group that created it.
`ThreadPoolCallbackRunnerLocal` also normalizes the group at enqueue time. Focused tests cover borrowed task enqueue, nested borrowed capture, and scheduler-object lifetime.

Related: ClickHouse#108577
Related: ClickHouse#107030
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Borrowed groups keep raw accounting pointers into their parent query group, but they must not own that parent. Mark borrowed groups by construction, expose `isBorrowed`, and add `getCurrentThreadGroupForAsyncCallback` to drop borrowed groups at async boundaries.
This replaces the earlier parent-retention guard with focused tests for dropping borrowed async captures and for not extending parent `ThreadGroup` lifetime.

Capture async `ThreadGroup` per queued task
`threadPoolCallbackRunnerUnsafe` no longer stores a `ThreadGroupPtr` in the long-lived scheduler object. It captures a normalized group only when a concrete task is queued, so storing the runner in `TaskTracker` or `WriteBufferFromS3` does not pin the query group that created it.
`ThreadPoolCallbackRunnerLocal` also normalizes the group at enqueue time. Focused tests cover borrowed task enqueue, nested borrowed capture, and scheduler-object lifetime.

Related: ClickHouse#108577
Related: ClickHouse#107030
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 pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants