Skip to content

Fixed a use-after-free in async callbacks scheduled from borrowed ThreadGroup scopes - #108988

Merged
azat merged 3 commits into
ClickHouse:masterfrom
filimonov:fix-borrowed-threadgroup-async-clean
Jul 8, 2026
Merged

azat merged 3 commits into
ClickHouse:masterfrom
filimonov:fix-borrowed-threadgroup-async-clean

Conversation

@filimonov

@filimonov filimonov commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

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 ThreadGroup is current.

Borrowed ThreadGroup objects used by materialized view and async insert flush paths point their performance_counters and memory_tracker to 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 ThreadGroup alive with a shared_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):

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

Fixes a memory safety issue where asynchronous work scheduled from materialized view processing could keep using query-level accounting after the query had finished.

groeneai and others added 3 commits June 30, 2026 16:54
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
@azat azat self-assigned this Jun 30, 2026
@azat azat added the can be tested Allows running workflows for external contributors label Jun 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b576ee9]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_msan, WasmEdge, parallel, 2/2) FAIL
03522_join_using_bug_78907 FAIL cidb

AI Review

Summary

This PR fixes the borrowed ThreadGroup lifetime hazard by marking borrowed groups explicitly, dropping them at async callback capture boundaries, and moving ThreadPoolCallbackRunnerUnsafe group capture to concrete task enqueue. The added gtests cover borrowed callback capture, nested borrowed groups, and scheduler-object lifetime. I did not find unresolved correctness, safety, or testing issues in the current diff.

Final Verdict

Status: ✅ Approve

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

clickhouse-gh Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.50% +0.10%
Functions 92.60% 92.60% +0.00%
Branches 77.70% 77.70% +0.00%

Changed lines: Changed C/C++ lines covered: 156/157 (99.36%) · Uncovered code

Full report · Diff report

@filimonov

filimonov commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor Author

03522_join_using_bug_78907

/// 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));

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.

Comment thread src/Common/ThreadStatus.h
explicit ThreadGroup(ThreadGroupPtr parent);
ThreadGroup(ContextPtr query_context_, ThreadGroupPtr parent);

bool isBorrowed() const;

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.

But I did not get this part, how parent thread group may be destroyed earlier?

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.

Ok I see, it is the same as first one but via MV, egh/ugh

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.

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

@alexey-milovidov

Copy link
Copy Markdown
Member

Reverted. Try again.

@alexey-milovidov

Copy link
Copy Markdown
Member

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

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 8, 2026
…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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 9, 2026
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]>
@CheSema

CheSema commented Aug 15, 2026 •

Copy link
Copy Markdown
Member

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

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…adgroup-async-clean

Fixed a use-after-free in async callbacks scheduled from borrowed `ThreadGroup` scopes
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 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.

6 participants