Repository navigation
Preserve borrowed thread name and only borrow group while unwinding in ~CallbackRunnerTask - #108887
Conversation
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-1:20260630-031400 |
|
cc @Felixoid @azat — could you review this? |
|
Workflow [PR], commit [f956abe] Summary: ✅
AI ReviewSummaryThis PR now reduces to two targeted fixes around the synchronous Final Verdict
|
|
Follow-up validation gate for the bot review change (thread-name restore in Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-5:20260630-044100 |
Felixoid
left a comment
There was a problem hiding this comment.
The analyze:
Verdict: the fix is correct
The core fix is right
src/Common/threadPoolCallbackRunner.h changes ~CallbackRunnerTask() to use allow_existing_group=true.
The scenario is real. In threadPoolCallbackRunnerUnsafe:
my_pool->scheduleOrThrowOnError([my_task = std::move(task)]{ my_task->run(); }, priority);When scheduleOrThrowOnError throws (pool shutting down), the temporary lambda holding the only shared_ptr to the task is destroyed during unwinding on the scheduling thread, which already owns its own query group. The destructor then builds a ThreadGroupSwitcher.
With the old allow_existing_group=false, the constructor hits:
throw Exception(ErrorCodes::LOGICAL_ERROR, "Thread (...) is already attached to a group ...");I confirmed in src/Common/Exception.cpp:88-93 that constructing a LOGICAL_ERROR exception calls abortOnFailedAssertion at construction time when debug_or_sanitizer_build || abort_on_logical_error. So the noexcept constructor's catch (...) does not save it: the process already aborted (the exit 134 / STID 4298-42a4 abort the author cites). Passing allow_existing_group=true is the documented, intended "borrow" semantics for exactly this case (detach current group, release captures under the task group, restore). This is not a fallback that hides a bug; the old assertion was simply wrong for a destructor that can legitimately run on a group-owning thread.
Both bot follow-ups were resolved correctly
-
Thread-name leak (valid concern):
setThreadName(thread_name)renamed the borrowed query thread to the async-pool name, and the old switcher restored only the group. After cleanup the query thread would wearS3ObjStor_copy, corrupting logs/traces//proc/jemalloc attribution. The fix savesgetThreadName()before the rename and restores it in the destructor and in the constructorcatch. Correctly scoped to the borrow branch only, so normalrun()on a clean pool worker still keeps the task name (the desired behavior). -
UNKNOWNsentinel (valid concern): guarding the restore withprev_thread_name != UNKNOWNwould skip restoring a legitimately unnamed thread, leaking the pool name. The fix replaces the value guard with a dedicatedbool should_restore_prev_thread_name. Correct.
Edge cases I checked, all sound
catchvs destructor double-restore: thecatchnulls boththread_groupandprev_thread_group, so the destructor early-returns. Name is restored exactly once on every path.getThreadName()throws in ctor: it runs beforeshould_restoreis set and before detach, so thecatchleaves state untouched. No corruption.should_restoreimpliesprev_thread_group != null(both come from the same borrow branch), so the destructor's name-restore living insideif (prev_thread_group)is consistent.setThreadNameallocates: the destructor restore sits inside theLockMemoryExceptionInThreadscope, so it won't trip memory limits. Good.run()left unchanged (allow_existing_group=false): it only runs on clean pool workers, so the assertion still correctly guards real misuse there. Minimal, well-targeted change.
Minor notes (not blockers)
ThreadNameis an enum, not a free string, so restore fidelity is limited to enum-representable names; an unrecognized OS name round-trips throughUNKNOWNand gets written back as"Unknown". Irrelevant for the actual borrow callers (query threads use known enum names likeTCP_HANDLER), but worth knowing.- The inline comments are quite verbose. Accurate, just heavy. Purely stylistic.
@groeneai let's fix the CI and good to go
| /// SCOPE_EXIT_SAFE keeps a throwing capture destructor from escaping this destructor. | ||
| { | ||
| ThreadGroupSwitcher switcher(thread_group, thread_name); | ||
| ThreadGroupSwitcher switcher(thread_group, thread_name, /*allow_existing_group*/ true); |
There was a problem hiding this comment.
We can allow it only if it is unwind, similar to what WriteBuffer::isStackUnwinding() does
Also the commend is very long, please keep only essential things
There was a problem hiding this comment.
Done (73c81ae). Rebased on master; borrow now gated on std::uncaught_exceptions() > 0, so only a synchronous scheduleOrThrowOnError() drop (unwinding on the query thread) borrows the group, a non-unwinding drop still asserts. Tests updated to drop the task while unwinding. Comments trimmed here and in ThreadGroupSwitcher.
|
Changes to save/restore thread name is not reflected in PR title, please update it, keep it compact and keep only essential things in the description, it is too verbose |
CI finish ledger — bcb4a2bEvery 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
None of the above is PR-caused. @Felixoid already APPROVED the fix. Session id: cron:our-pr-ci-monitor:20260630-113000 |
|
@azat done: title now mentions the thread-name preserve/restore, and the description is trimmed to essentials. Original exception was |
|
@groeneai please rebase and compact comments/PR description even more, and look at my comments |
bcb4a2b to
1a8b0a5
Compare
|
Rebased onto master (conflict resolved). Master picked up the same |
1a8b0a5 to
73c81ae
Compare
|
Rebased on master, gated the borrow on |
|
Fix tidy |
73c81ae to
c90f01a
Compare
|
Tidy fixed in c90f01a: the two `bugprone-empty-catch` errors were the empty `catch` blocks modeling the unwinding drop path (gtest_thread_group_switcher.cpp:138,186). Now each asserts the caught exception message. `unit_tests_dbms --gtest_filter=ThreadGroupSwitcher.*` = 3/3 pass. |
|
Squash everything |
c90f01a to
593b254
Compare
|
Squashed into a single commit (593b254). Tree unchanged: 4 files, +164/-38. |
| /// Reproduces the arm_tsan stress abort (STID 4298-42a4): DROP TABLE -> | ||
| /// MergeTreeDeduplicationLog::shutdown -> WriteBufferFromS3 -> TaskTracker::add -> | ||
| /// scheduleOrThrowOnError throws -> ~CallbackRunnerTask on the query thread. | ||
| TEST(ThreadGroupSwitcher, CallbackRunnerTaskDestroyedOnGroupOwningThread) |
There was a problem hiding this comment.
I don't think we need this two tests (this and below) since we have DroppedSynchronouslyWhileAttachedToAnotherGroup added in 9307102
There was a problem hiding this comment.
Done in f956abe. Removed both CallbackRunnerTask tests (redundant with master's DroppedSynchronouslyWhileAttachedToAnotherGroup) and replaced them with one focused ThreadGroupSwitcher.RestoresBorrowedThreadName that only asserts the borrowed thread's name is restored (TCP_HANDLER and UNKNOWN), which master's test does not check. Verified it fails without the name-restore fix and passes with it.
…n ~CallbackRunnerTask The abort fix for "Thread is already attached to a group" landed in master independently. The surviving change here refines that path and fixes an observability leak it introduced: - ~CallbackRunnerTask borrows an existing group only while the stack is unwinding (std::uncaught_exceptions() > 0), so a synchronous scheduleOrThrowOnError drop reattaches the caller's group, while a non-unwinding drop still asserts. Mirrors WriteBuffer::isStackUnwinding. - ThreadGroupSwitcher now saves and restores the borrowed thread's previous name (not just its group) on the allow_existing_group path, in both the destructor and the constructor failure-recovery catch. Gated by a should_restore_prev_thread_name bool, since ThreadName::UNKNOWN is a valid previous name, not a "nothing to restore" sentinel. Without this a borrowed query thread (TCPHandler/HTTPHandler) was left wearing the async pool name, corrupting later logs, traces, /proc names and jemalloc attribution. Regression tests cover the name restore (which master's DroppedSynchronouslyWhileAttachedToAnotherGroup does not check) on both the destructor and failed-construction paths, including an initially-unnamed (UNKNOWN) borrowed thread. Found via Stress test (arm_tsan), STID 4298-42a4.
593b254 to
f956abe
Compare
| /// covers the group restore and the no-abort, but never checks the name -- which is what this PR adds. | ||
| /// Both a real previous name and UNKNOWN (initially unnamed) must be restored: UNKNOWN is a valid | ||
| /// previous name, not a "nothing to restore" sentinel, so the restore is gated by a bool, not the value. | ||
| TEST(ThreadGroupSwitcher, RestoresBorrowedThreadName) |
There was a problem hiding this comment.
Why do we need this test if we have the same checks more or less in FailedConstructionRestoresPreviousState ?
There was a problem hiding this comment.
FailedConstructionRestoresPreviousState only covers the constructor catch path, where the switch fails before construction completes and the recovery logic has to put the thread back. RestoresBorrowedThreadName is the only current test for the normal success path where the switcher fully constructs, renames the borrowed thread to S3_COPY_POOL, and then ~ThreadGroupSwitcher has to restore the previous name on scope exit. The existing shutdown regression in gtest_thread_pool_callback_runner_shutdown.cpp covers the group restore / no-abort part, but it never asserts the thread name either.
There was a problem hiding this comment.
They hit different restore sites, so neither is redundant:
FailedConstructionRestoresPreviousStateuses the failpoints, so it only exercises the constructor catch path (restore at ThreadGroupSwitcher.cpp:90). On a failed constructionthread_groupis nulled, so the destructor early-returns and its restore never runs.RestoresBorrowedThreadNameexercises the normal destructor restore (ThreadGroupSwitcher.cpp:125) after a successful borrow. This is the actual production path (~CallbackRunnerTask->~ThreadGroupSwitcher); no failpoint is involved.
Verified they are non-overlapping: neutering only the destructor restore fails RestoresBorrowedThreadName while FailedConstructionRestoresPreviousState still passes. Happy to fold them into one test if you prefer, but a single test cannot cover both the catch and the destructor restore.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 65/65 (100.00%) · Uncovered code |
…tcher-dtor-allow-existing-group Preserve borrowed thread name and only borrow group while unwinding in ~CallbackRunnerTask
Related: #108730
Related: #106462
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Description
The
~CallbackRunnerTaskabort fix (borrow the existing group when an unrun task is dropped) is now in master (9307102). Surviving change here:ThreadGroupSwitchersaves and restores the borrowed thread's name on theallow_existing_group=truepath; it was left wearing the async-pool name, leaking into logs, traces,/procnames and jemalloc attribution.~CallbackRunnerTaskgates the borrow onstd::uncaught_exceptions() > 0, so only a synchronousscheduleOrThrowOnErrorthrow (unwinding on the query thread) borrows the group; a non-unwinding drop (shutdown drain on a group-less pool worker) keeps asserting.gtest_thread_group_switcher.cpp.Originally found by Stress test (
arm_tsan), STID 4298-42a4.Version info
26.7.1.686(included in26.7and later)