Repository navigation
Fixed a use-after-free in async callbacks scheduled from borrowed ThreadGroup scopes - #108988
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]>
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]>
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
|
Workflow [PR], commit [b576ee9] Summary: ❌
AI ReviewSummaryThis PR fixes the borrowed Final VerdictStatus: ✅ Approve |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 156/157 (99.36%) · Uncovered code |
|
| /// Capture the current `ThreadGroup` at enqueue time. The runner object can be stored longer | ||
| /// than the query, and the worker thread has its own current group, so neither is a safe source. | ||
| auto captured_thread_group = getCurrentThreadGroupForAsyncCallback(); | ||
| auto task = std::make_shared<detail::CallbackRunnerTask<Result, Callback>>(std::move(captured_thread_group), thread_name, std::move(callback)); |
There was a problem hiding this comment.
| explicit ThreadGroup(ThreadGroupPtr parent); | ||
| ThreadGroup(ContextPtr query_context_, ThreadGroupPtr parent); | ||
|
|
||
| bool isBorrowed() const; |
There was a problem hiding this comment.
But I did not get this part, how parent thread group may be destroyed earlier?
There was a problem hiding this comment.
Ok I see, it is the same as first one but via MV, egh/ugh
There was a problem hiding this comment.
@azat, we don't allow writing non-obvious code. Every piece of code must be trivial to understand. Add comments to make it trivial. The more comments, the better.
9fc0f02
|
Reverted. Try again. |
|
@filimonov @azat, we don't allow merging with failing tests: 03522_join_using_bug_78907. Next time be more careful and don't rush. Always fix the tests first. |
…ueue-time group capture Strengthen the test to actually guard the non-borrowed enqueue-time capture contract from ClickHouse#108988: before enabling the fault injector, schedule a task that succeeds and assert getCurrentThreadGroup() inside the worker callback equals the enqueue-time group. The synchronous-drop path alone cannot distinguish a regressed nullptr capture (the drop runs on the scheduling thread already attached to the enqueue group, so ThreadGroupSwitcher(nullptr) is a no-op); the run-path check observes the group on the pool worker thread, where a detached worker reporting nullptr exposes the regression. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pick up revert PR ClickHouse#109851 (reverts ClickHouse#108988) which fixes the ThreadPoolCallbackRunner.DroppedSynchronouslyWhileAttachedToAnotherGroup unit test regression that was failing on our pre-revert build head. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Actually this code is really dangerous. It only works when that group is not captured by some async/background job. I think it would be better if we store shared ptr on a parent group. That simple but robust approach make is easier to implement truly hierarchal thread group which are useful in other things too. Like here #97302 UPD: #114940 -- is good fix |
…adgroup-async-clean Fixed a use-after-free in async callbacks scheduled from borrowed `ThreadGroup` scopes
Related: #107030
Related: #108577
CI: 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
Fixes a use-after-free risk in asynchronous work scheduled while a borrowed
ThreadGroupis current.Borrowed
ThreadGroupobjects used by materialized view and async insert flush paths point theirperformance_countersandmemory_trackerto the parent query group, so they are valid only while that parent group is alive. Async callbacks could capture such a borrowed group and later attach it on a pool thread after the parent query group had finished.Instead of keeping the parent
ThreadGroupalive with ashared_ptr, this change keeps borrowed accounting scoped. Borrowed groups are marked explicitly, async callback capture drops borrowed groups, and thread pool callback runners capture the normalized group at task enqueue time rather than when a potentially long-lived runner object is created.This preserves synchronous borrowed accounting, but async work started from a borrowed scope runs under normal thread/global accounting instead of writing into, or prolonging the lifetime of, an already finished query group.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes a memory safety issue where asynchronous work scheduled from materialized view processing could keep using query-level accounting after the query had finished.