Repository navigation
Conversation
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]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-7:20260626-055100 |
|
cc @azat @al13n321 — could you review? A borrowed child |
|
Workflow [PR], commit [c62a4ce] Summary: ❌
AI ReviewSummaryThis PR fixes a lifetime bug in borrowed Final VerdictStatus: ✅ Approve |
CI finish ledger — f74d935Every 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
This PR adds a Session id: cron:our-pr-ci-monitor:20260626-170000 |
|
@groeneai Can you please add an additional unit test covering |
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]>
|
@cv4g Done in c62a4ce. Added Validated both directions locally (debug, ENABLE_TESTS=ON): with the two-arg ctor's |
| /// 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; |
There was a problem hiding this comment.
I don't like this fix, this can leave live leak.
Why parent group is not alive? Can we address this instead?
There was a problem hiding this comment.
@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.
|
@cv4g BTW I've discussed this with the author of #107030 (@filimonov) he suggests better fix |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 60/60 (100.00%) · Uncovered code |
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
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
Changelog category (leave one):
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
ProfileEventscounters or the memory tracker.Description
A borrowed child
ThreadGroup(createForMaterializedView/createForFlushAsyncInsertQueue) stores raw pointers into its parent group'sperformance_countersandmemory_tracker, but did not keep the parent alive. The invariant inMemoryTracker.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
MergeTreeDeduplicationLogwriter whose thread-pool scheduler captured the current group unders3_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 inProfileEvents::Counters::increment(current = current->parent) orMemoryTracker::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_ptrto 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::incrementat 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 ).