Repository navigation
[not for merge] Instrumentation to demonstrate and catch a borrowed-ThreadGroup use-after-free in CI - #107030
[not for merge] Instrumentation to demonstrate and catch a borrowed-ThreadGroup use-after-free in CI#107030filimonov wants to merge 9 commits into
ThreadGroup use-after-free in CI#107030Conversation
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]>
|
Workflow [PR], commit [2ceddb7] Summary: ✅
AI ReviewSummaryThis draft started as instrumentation for a borrowed PR Metadata
Findings❌ Blockers
Tests
Final VerdictChanges requested. |
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 |
There was a problem hiding this comment.
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.
Fix arm_tidy build failure: cppcoreguidelines-init-variables flagged the uninitialized `bool is_borrowed` (treated as -Werror in the tidy build). CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107030&sha=24b2216209bc14e3bc52e34e9b76c146237a2a4c&name_0=PR&name_1=Build%20%28arm_tidy%29 PR: ClickHouse#107030 Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Looks like we found this in our CI, and here is a PR - #108577 |
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]>
|
@filimonov Our PR #108577 (the From your ASan freed-by stack the root cause is at the capture site: 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 ( |
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
|
Confirming your capture-site fix is the correct root cause: On the clickhouse-gh note for 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. |
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.
|
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; |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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).
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 157/167 (94.01%) · 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
Problem. A materialized-view target insert runs under a borrowed child
ThreadGroupthat 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-tableMergeTreeDeduplicationLogwriter 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 inMemoryTracker::setParentreads freed memory.Findings (experiments).
master(not specific to any one storage): MV + tinynon_replicated_deduplication_windowunder ASan.s3_allow_parallel_part_uploadcapturing the group in the task runner — size-independent.This PR adds (debug/sanitizer only, ON by default):
ThreadGrouplifetime checker — flags any borrowed child outliving its parent at the exact moment of the premature free (no race needed). Logged asBORROWED THREADGROUP INVARIANT VIOLATION.CH_BORROWED_THREADGROUP_TRAVERSE_SLEEP_MS,0disables).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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
ASan report: https://gist.github.com/filimonov/1ec59047c65e3a5367c5c83f6021cc27