Skip to content

[not for merge] Instrumentation to demonstrate and catch a borrowed-ThreadGroup use-after-free in CI - #107030

Closed
filimonov wants to merge 9 commits into
ClickHouse:masterfrom
filimonov:threadgroup-uaf-detection
Closed

filimonov wants to merge 9 commits into
ClickHouse:masterfrom
filimonov:threadgroup-uaf-detection

Conversation

@filimonov

@filimonov filimonov commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Problem. A materialized-view target insert runs under a borrowed child ThreadGroup that holds raw pointers into the source query's group (memory_tracker / performance_counters). Invariant: the borrowed child must not outlive its parent. But the per-table MergeTreeDeduplicationLog writer captures whatever group is current when it is (re)created and pins it for the buffer's lifetime; a small dedup window makes it rotate on every part. The source-side writer then frees the query group while the MV-target writer is still attaching a borrowed child that names it as parent - the later parent-chain walk in MemoryTracker::setParent reads freed memory.

Findings (experiments).

  • Reproduced on master (not specific to any one storage): MV + tiny non_replicated_deduplication_window under ASan.
  • The pin is driven by s3_allow_parallel_part_upload capturing the group in the task runner — size-independent.
  • The default-window suite does not surface it naturally, so a deliberate amplifier is needed to make the race land reliably.

This PR adds (debug/sanitizer only, ON by default):

  • A deterministic borrowed-ThreadGroup lifetime checker — flags any borrowed child outliving its parent at the exact moment of the premature free (no race needed). Logged as BORROWED THREADGROUP INVARIANT VIOLATION.
  • A parent-traverse delay amplifier that widens the read-vs-free window so the actual UAF reliably lands under ASan (override via CH_BORROWED_THREADGROUP_TRAVERSE_SLEEP_MS, 0 disables).
  • A provoking stateless test (04319_borrowed_threadgroup_uaf_mv_provoke.sql). In release builds the instruments compile out and it is just a small MV-insert workload.

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

ASan report: https://gist.github.com/filimonov/1ec59047c65e3a5367c5c83f6021cc27

Adds a borrowed-ThreadGroup lifetime checker plus a parent-traverse delay
(debug/sanitizer only, ON by default) and a provoking test to surface it
in CI. No fix here.

ASan report: https://gist.github.com/filimonov/1ec59047c65e3a5367c5c83f6021cc27

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@azat azat self-assigned this Jun 10, 2026
@azat azat added the can be tested Allows running workflows for external contributors label Jun 10, 2026
@azat
azat marked this pull request as draft June 10, 2026 16:21
@clickhouse-gh

clickhouse-gh Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2ceddb7]

Summary: ✅


AI Review

Summary

This draft started as instrumentation for a borrowed ThreadGroup lifetime bug, but the current head also changes the production async-callback capture path. I found two blocker-level regressions in the current diff: callbacks scheduled from borrowed groups now lose all query scoping by dropping to nullptr, and the lifetime checker / abort() path is no longer debug/sanitizer-only despite the PR contract. The new stateless reproducer is also still weaker than the behavior the PR description claims to exercise.

PR Metadata
  • Changelog category no longer matches the current diff. CI Fix or Improvement is for CI-only/test-only changes, while this PR now changes runtime behavior in ThreadGroup / threadPoolCallbackRunner.
  • If this draft is ever promoted for merge, use Bug Fix and a non-empty changelog entry such as: Fix borrowed \ThreadGroup` capture in async callbacks used by materialized views and async inserts to avoid use-after-free in object-storage writes.`
Findings

❌ Blockers

  • [src/Common/ThreadGroupSwitcher.cpp:33] Returning nullptr for every borrowed-group async capture detaches that callback from the query entirely. In the concrete path this PR targets, QueryScope::createForFlushAsyncInsert / createForMaterializedView attach borrowed groups with a live query context, and WriteBufferFromS3 still schedules part uploads through threadPoolCallbackRunnerUnsafe. Those uploads now skip attachToGroupImpl, so they fall back to total_memory_tracker, lose query_id, and stop contributing profile events/cancellation to the originating query. The UAF is avoided by dropping all query accounting, which means borrowed-group async work can now bypass per-query limits and observability.
  • [src/Interpreters/ThreadStatusExt.cpp:137-169] The borrowed-group checker is no longer behind DEBUG_OR_SANITIZER_BUILD, so release builds now execute the registry bookkeeping and StackTrace() capture on every borrowed ThreadGroup creation and abort() the server on any lifetime violation. That contradicts both the header comment and the PR description, and it puts debug-only instrumentation plus a crash-only failure mode onto normal materialized-view / async-insert runtime paths.
Tests
  • ⚠️ [tests/queries/0_stateless/04319_borrowed_threadgroup_uaf_mv_provoke.sql:20] The stateless reproducer still uses the default local MergeTree disk and only asserts done, so it does not force the long-lived async writer path described in the PR body or any other observable borrowed-group violation. A focused regression should either route through the object-storage upload scheduler that originally pinned the borrowed group, or assert the checker signal directly instead of relying on a passing workload.
Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jun 10, 2026
Comment thread src/Interpreters/ThreadStatusExt.cpp Resolved
Address CI feedback:
- The borrowed-ThreadGroup checker only logged the violation, so the test
  could pass even when the invariant was broken (debug builds, or ASan runs
  where the racy read does not land). Now it LOG_FATALs and aborts, so CI
  catches it deterministically.
- Renumber the provoking test 05006 -> 04319 to close the test-number gap
  flagged by the style check.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
DROP TABLE IF EXISTS bt_uaf_dst;
DROP VIEW IF EXISTS bt_uaf_mv;

CREATE TABLE bt_uaf_src (x UInt64) ENGINE = MergeTree ORDER BY x

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 reproducer does not appear to exercise the path that pins the borrowed MV ThreadGroup. The tables use the default local MergeTree disk, where the deduplication log writer is WriteBufferFromFile and DiskLocal::writeFile does not capture CurrentThread::getGroup; the group capture described in the PR happens in the object-storage write scheduler when parallel upload is enabled. That means the test can still print done in debug/sanitizer builds without proving the borrowed child outlives its parent. Please force this scenario onto the storage path that captures the group, or otherwise make the test assert an observable borrowed-group violation on local disk.

@azat

azat commented Jun 30, 2026

Copy link
Copy Markdown
Member

Looks like we found this in our CI, and here is a PR - #108577
Though I don't like it

groeneai and others added 2 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]>
@groeneai

Copy link
Copy Markdown
Collaborator

@filimonov Our PR #108577 (the shared_ptr parent_thread_group fix) was closed: @ azat is right that it trades the UAF for a leak (it pins the transient query group for as long as anything holds the borrowed child). He mentioned you two agreed on a better fix.

From your ASan freed-by stack the root cause is at the capture site: threadPoolCallbackRunnerUnsafe (src/Common/threadPoolCallbackRunner.h:33) captures getCurrentThreadGroup(), so a long-lived per-table MergeTreeDeduplicationLog S3 writer pins whatever query-scoped borrowed MV group was current when its TaskTracker runner was created. The query frees that parent group at end-of-query while the writer still attaches the borrowed child, and MemoryTracker::setParent walks freed parent counters.

That points to fixing the capture (a long-lived writer should not run under a transient borrowed group), not the lifetime of the borrowed group itself. Could you share the concrete approach you and azat agreed on? I would rather implement that one than guess between equivalents, and I can carry over the deterministic gtest regression I already have (src/Common/tests/gtest_borrowed_thread_group_lifetime.cpp) if useful.

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

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator

Confirming your capture-site fix is the correct root cause: getCurrentThreadGroupForAsyncCallback() dropping borrowed groups stops a long-lived async task (the MergeTreeDeduplicationLog S3 writer's TaskTracker) from pinning a transient borrowed MV group past its parent query, so no pool worker later attaches/finalizes a borrowed child whose parent counters were already freed. That is the same capture site we flagged, generalized to all async runners, and it avoids the leak azat objected to on our #108577 (leaving that closed).

On the clickhouse-gh note for gtest_borrowed_thread_group_lifetime.cpp: ChildDoesNotKeepParentAlive and FlushAsyncInsertQueueGroupDoesNotKeepParentAlive are leftovers from our #108577 that tested the rejected shared_ptr ownership. They parent.reset() while a borrowed child is still registered, so checkAndUnregisterOnDestroy aborts in debug/sanitizer builds before EXPECT_TRUE(parent_weak.expired()) runs. Your async-capture cases already cover the safety property, so simplest is to drop those two (or child.reset() before parent.reset() if you want to keep the non-ownership assertion).

We will track this PR as the fix for the UAF family (STID 3718-4f99, 3718-48ca, 4115-4d2b; 3 PRs, 0 on master, Apr-Jun). Thanks @filimonov.

@filimonov

Copy link
Copy Markdown
Contributor Author

@groeneai this PR is not for merge (it's instrumentation just to prove that problem exists in master) this one should not be merged, fix PR is #108988

I've merged it here to prove the the fix helps.

filimonov added 2 commits July 1, 2026 15:22
The temporary `std::this_thread::sleep_for` before attaching a borrowed `ThreadGroup` helped ASan catch the use-after-free by widening the race window.

In CI corner cases this also strongly slows down `DeduplicationLog` materialized-view tests, because regular stateless runs can hit the amplified path many times and exceed the timeout.

Keep the deterministic destructor check instead: it asserts when a parent `ThreadGroup` is destroyed while a borrowed child still references it, so the parent-child invariant is caught without relying on ASan.
@filimonov

Copy link
Copy Markdown
Contributor Author

Great! Fix works, and all the real failures disappeared.

We only have 2 unit test (which were manually doing things which what intrumentation catches) - just removed those tests.

And several tests start to timeout under debug builds with small block sizes - it's because the explicit sleep were added to expand the race window. But asan / tsan did not react, so test were just timing out. Anyway that sleep is secondary compared to explicit lifetime check in destructor (it reports even w/o asan).

So i'm removing that sleep, to give one more run. Expect it to be green.

{
ThreadGroupPtr result = getCurrentThreadGroup();
if (result && result->isBorrowed())
result = nullptr;

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.

Returning nullptr here changes borrowed-group callbacks from "keep query accounting on the pool thread" to "run completely detached". QueryScope::createForFlushAsyncInsert / createForMaterializedView deliberately attach a borrowed group with a query context, and WriteBufferFromS3 still schedules part-upload work through threadPoolCallbackRunnerUnsafe. After this change those uploads skip attachToGroupImpl, so they fall back to total_memory_tracker, lose query_id, and stop contributing profile events/cancellation to the originating query. That fixes the UAF by dropping all query scoping, but it also means borrowed-group async work can now bypass per-query accounting and limits. Can we capture a safe non-borrowed ancestor (or scope this opt-out to the long-lived writer path) instead of detaching all borrowed-group callbacks?

}
/// Fail loudly instead of only logging, so CI catches the violation deterministically, including when
/// the racy use-after-free read happens not to land.
if (violated)

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 checker block is no longer gated by DEBUG_OR_SANITIZER_BUILD, so release builds now pay for the global registry + StackTrace() capture on every borrowed ThreadGroup creation and abort() the server on any lifetime violation. The header comment and PR description still describe this as debug/sanitizer-only instrumentation, but the current code ships it on the normal materialized-view / async-insert path. Please keep the production fix in the async-capture helper and put the registry/abort() path behind debug/sanitizer (or a dedicated testing setting/failpoint).

@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 157/167 (94.01%) · Uncovered code

Full report · Diff report

@azat azat closed this Jul 9, 2026
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-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants