Skip to content

Preserve borrowed thread name and only borrow group while unwinding in ~CallbackRunnerTask - #108887

Merged
azat merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-threadgroupswitcher-dtor-allow-existing-group
Jul 8, 2026
Merged

azat merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-threadgroupswitcher-dtor-allow-existing-group

Conversation

@groeneai

@groeneai groeneai commented Jun 30, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #108730
Related: #106462

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Description

The ~CallbackRunnerTask abort fix (borrow the existing group when an unrun task is dropped) is now in master (9307102). Surviving change here:

  • ThreadGroupSwitcher saves and restores the borrowed thread's name on the allow_existing_group=true path; it was left wearing the async-pool name, leaking into logs, traces, /proc names and jemalloc attribution.
  • ~CallbackRunnerTask gates the borrow on std::uncaught_exceptions() > 0, so only a synchronous scheduleOrThrowOnError throw (unwinding on the query thread) borrows the group; a non-unwinding drop (shutdown drain on a group-less pool worker) keeps asserting.
  • Regression tests in gtest_thread_group_switcher.cpp.

Originally found by Stress test (arm_tsan), STID 4298-42a4.

Version info

  • Merged into: 26.7.1.686 (included in 26.7 and later)

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. unit_tests_dbms --gtest_filter='ThreadGroupSwitcher.CallbackRunnerTaskDestroyedOnGroupOwningThread' aborts on demand without the fix (exit 134, Logical error: 'Thread (UNKNOWN) is already attached to a group (master_thread_id N)' -- the exact STID 4298-42a4 message).
b Root cause explained? Yes. scheduleOrThrowOnError throws inside TaskTracker::add; stack unwinding destroys the CallbackRunnerTask shared_ptr synchronously on the scheduling thread, which already owns its query thread group; ~CallbackRunnerTask()'s ThreadGroupSwitcher(allow_existing_group=false) hits the "already attached to a group" guard -> LOGICAL_ERROR -> abortOnFailedAssertion aborts (debug/sanitizer build).
c Fix matches root cause? Yes. allow_existing_group=true is the documented mechanism for "borrow a thread that already owns a group" (remember + restore in dtor). It is applied to the one switcher that can run on a group-owning thread.
d Test intent preserved / new test added? Yes. New gtest CallbackRunnerTaskDestroyedOnGroupOwningThread reproduces the abort; no existing test weakened.
e Both directions demonstrated? Yes. Without fix: aborts (exit 134, exact message). With fix: passes, thread still attached to its original group. Both on Build-ID-verified binaries (bac0bdf5... without, 9527037f... with).
f Fix is general across code paths? Yes. The fix is in the single generic CallbackRunnerTask destructor used by every threadPoolCallbackRunnerUnsafe caller. run() keeps false (only ever runs on a clean pool worker). The two ThreadPoolCallbackRunnerLocal::executeCallback switchers run inside task_func, which never executes when scheduling throws (the catch sets the promise directly), so they are not affected.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A -- thread-group-lifecycle abort, independent of query inputs/datatypes.
h Backward compatible? (maintainer-approved exception only) Yes. No setting/format/protocol/metadata change. Pure cleanup-path correctness; no behavior change on the pool drain thread (null/identical group is still a no-op).
i Invariants and contracts preserved? Yes. allow_existing_group=true restores the scheduling thread's original group after the switch (verified: thread still attached to its group post-dtor). The promise is still satisfied with CANNOT_SCHEDULE_TASK. No lock/ownership change.

Session id: cron:clickhouse-worker-slot-1:20260630-031400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Felixoid @azat — could you review this? ~CallbackRunnerTask() ran its ThreadGroupSwitcher with the default allow_existing_group=false, but the destructor can run synchronously on the scheduling thread (which already owns a query group) when scheduleOrThrowOnError throws during unwinding, so it aborted with "already attached to a group" (STID 4298-42a4, arm_tsan stress). Fix passes allow_existing_group=true in the dtor; run() is unchanged. @Felixoid since you own the allow_existing_group mechanism (#106462).

@alexey-milovidov alexey-milovidov 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 [f956abe]

Summary: ✅


AI Review

Summary

This PR now reduces to two targeted fixes around the synchronous scheduleOrThrowOnError drop path: ~CallbackRunnerTask only borrows an existing group while unwinding, and ThreadGroupSwitcher restores a borrowed thread's previous name on both the destructor and constructor-failure paths. I did not find unresolved correctness or safety issues in the current diff; the existing shutdown regression plus the added ThreadGroupSwitcher tests cover the distinct group-restore and name-restore paths.

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
Comment thread src/Common/threadPoolCallbackRunner.h Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Follow-up validation gate for the bot review change (thread-name restore in ThreadGroupSwitcher):

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. unit_tests_dbms --gtest_filter='ThreadGroupSwitcher.*' reproduces the name leak on demand: a thread named TCP_HANDLER owning its group borrows the switcher under a non-UNKNOWN task name, and the name assertion fires deterministically.
b Root cause explained? Yes. The ctor's allow_existing_group=true borrow path calls setThreadName(thread_name) (ThreadGroupSwitcher.cpp:59), renaming the borrowed thread. The dtor (and the ctor failure-recovery catch) reattached prev_thread_group but never restored the name, so a borrowed query thread (e.g. a TCPHandler on the ~CallbackRunnerTask cleanup path) was left wearing the async-pool name -> wrong logs/traces//proc/jemalloc attribution.
c Fix matches root cause? Yes. Save getThreadName() on the borrow branch before the rename; restore it alongside the group in the dtor, and in the ctor catch (post_attach_failure renames before throwing and the dtor early-returns there). Directly undoes the exact setThreadName the switcher itself performed.
d Test intent preserved / new tests added? Yes. CallbackRunnerTaskDestroyedOnGroupOwningThread now names the thread TCP_HANDLER + uses task name S3_COPY_POOL (so the rename actually happens; UNKNOWN made it a no-op) and asserts getThreadName()==TCP_HANDLER after destruction. FailedConstructionRestoresPreviousState asserts the same on both failpoint paths. All prior group/abort assertions kept.
e Both directions demonstrated? Yes. Source fix reverted (tests kept), rebuilt (Build ID changed) -> both name assertions FAIL; fix restored, rebuilt (Build ID back to the with-fix value) -> 2/2 PASS.
f Fix is general across code paths? Yes. Fixed in ThreadGroupSwitcher itself, so it covers every allow_existing_group=true borrow caller (~CallbackRunnerTask, ExceptionKeepingTransform, and the MergeTree merge/mutate tasks), not just this destructor. Grep confirmed no other code attaches a group + setThreadName outside the switcher.
g Fix generalizes across inputs? Yes. The save/restore is independent of the ThreadName value; UNKNOWN is the sentinel for "nothing to restore" (clean pool worker, prev_thread_group==nullptr, or thread never had a name). Both ctor exit paths (success dtor + failure catch) and both failpoints (attach_to_group_failure before the rename, post_attach_failure after) are covered.
h Backward compatible? Yes. Internal thread-naming/observability only; no setting, on-disk, wire, replication, or metadata change. Clean pool workers (prev_thread_group==nullptr) keep the task name exactly as before -> no behavior change for the run() path.
i Invariants and contracts preserved? Yes. The name restore is symmetric with the existing group save/restore and happens under the same LockMemoryExceptionInThread scope as the group reattach. prev_thread_name is set only on the borrow branch; setThreadName is idempotent so the catch-path restore is safe even when the rename never occurred. The "properly nested" group invariant in the dtor is untouched.

Session id: cron:clickhouse-worker-slot-5:20260630-044100

Comment thread src/Common/ThreadGroupSwitcher.cpp Resolved

@Felixoid Felixoid left a comment

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.

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

  1. 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 wear S3ObjStor_copy, corrupting logs/traces//proc/jemalloc attribution. The fix saves getThreadName() before the rename and restores it in the destructor and in the constructor catch. Correctly scoped to the borrow branch only, so normal run() on a clean pool worker still keeps the task name (the desired behavior).

  2. UNKNOWN sentinel (valid concern): guarding the restore with prev_thread_name != UNKNOWN would skip restoring a legitimately unnamed thread, leaking the pool name. The fix replaces the value guard with a dedicated bool should_restore_prev_thread_name. Correct.

Edge cases I checked, all sound

  • catch vs destructor double-restore: the catch nulls both thread_group and prev_thread_group, so the destructor early-returns. Name is restored exactly once on every path.
  • getThreadName() throws in ctor: it runs before should_restore is set and before detach, so the catch leaves state untouched. No corruption.
  • should_restore implies prev_thread_group != null (both come from the same borrow branch), so the destructor's name-restore living inside if (prev_thread_group) is consistent.
  • setThreadName allocates: the destructor restore sits inside the LockMemoryExceptionInThread scope, 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)

  • ThreadName is an enum, not a free string, so restore fidelity is limited to enum-representable names; an unrecognized OS name round-trips through UNKNOWN and gets written back as "Unknown". Irrelevant for the actual borrow callers (query threads use known enum names like TCP_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

@azat azat left a comment •

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.

Also curious to know what was the original exception? I see, cannot_allocate_thread, OK

Comment thread src/Common/ThreadGroupSwitcher.cpp Resolved
Comment thread src/Common/threadPoolCallbackRunner.h Outdated
/// 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);

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.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@azat

azat commented Jun 30, 2026

Copy link
Copy Markdown
Member

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

@azat azat self-assigned this Jun 30, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — bcb4a2b

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Hung check failed, possible deadlock found deadlock (chronic trunk; a ThreadGroupSwitcher fix cannot cause a TSan shutdown deadlock) #108212 (ours, merged) / #105905 (ours, open)
Stress test (arm_tsan) / Hung check failed, possible deadlock found deadlock (chronic trunk) #108212 (ours, merged) / #105905 (ours, open)
Upgrade check (amd_release) / Error message in clickhouse-server.log flaky (background-mutation throwIf FUNCTION_THROW_IF_VALUE_IS_NON_ZERO replayed on upgrade restart and caught by the log scan; chronic, 117 unrelated PRs / 0 master) #108651 (ours, open)
CH Inc sync — CH Inc sync (private, not actionable)

None of the above is PR-caused. @Felixoid already APPROVED the fix.

Session id: cron:our-pr-ci-monitor:20260630-113000

@groeneai groeneai changed the title Fix server abort in ~CallbackRunnerTask when scheduling fails on a thread that owns a group Fix server abort in ~CallbackRunnerTask and preserve thread name when borrowing a group Jun 30, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

@azat done: title now mentions the thread-name preserve/restore, and the description is trimmed to essentials. Original exception was cannot_allocate_thread (thread-pool exhaustion / pool shutdown), as you noted.

@azat

azat commented Jul 8, 2026

Copy link
Copy Markdown
Member

@groeneai please rebase and compact comments/PR description even more, and look at my comments

@groeneai
groeneai force-pushed the fix-threadgroupswitcher-dtor-allow-existing-group branch from bcb4a2b to 1a8b0a5 Compare July 8, 2026 11:41
@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto master (conflict resolved). Master picked up the same allow_existing_group=true change independently in 9307102, so this PR now carries only its unique part: the ThreadGroupSwitcher thread-name save/restore (the should_restore_prev_thread_name bool guard) plus its regression tests. unit_tests_dbms ThreadGroupSwitcher.* = 3/3 PASS locally. HEAD 1a8b0a5.

@groeneai
groeneai force-pushed the fix-threadgroupswitcher-dtor-allow-existing-group branch from 1a8b0a5 to 73c81ae Compare July 8, 2026 12:18
@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased on master, gated the borrow on std::uncaught_exceptions() > 0 (only an unwinding drop borrows the group), trimmed the inline comments and the PR description. Replied inline on the callback-runner comment.

@groeneai groeneai changed the title Fix server abort in ~CallbackRunnerTask and preserve thread name when borrowing a group Preserve borrowed thread name and only borrow group while unwinding in ~CallbackRunnerTask Jul 8, 2026
@azat

azat commented Jul 8, 2026

Copy link
Copy Markdown
Member

Fix tidy

@groeneai
groeneai force-pushed the fix-threadgroupswitcher-dtor-allow-existing-group branch from 73c81ae to c90f01a Compare July 8, 2026 13:17
@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

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.

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-bugfix Pull request with bugfix, not backported by default labels Jul 8, 2026
@azat

azat commented Jul 8, 2026

Copy link
Copy Markdown
Member

Squash everything

@groeneai
groeneai force-pushed the fix-threadgroupswitcher-dtor-allow-existing-group branch from c90f01a to 593b254 Compare July 8, 2026 13:47
@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

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)

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.

I don't think we need this two tests (this and below) since we have DroppedSynchronouslyWhileAttachedToAnotherGroup added in 9307102

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@groeneai
groeneai force-pushed the fix-threadgroupswitcher-dtor-allow-existing-group branch from 593b254 to f956abe Compare July 8, 2026 14:47
/// 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)

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.

Why do we need this test if we have the same checks more or less in FailedConstructionRestoresPreviousState ?

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They hit different restore sites, so neither is redundant:

  • FailedConstructionRestoresPreviousState uses the failpoints, so it only exercises the constructor catch path (restore at ThreadGroupSwitcher.cpp:90). On a failed construction thread_group is nulled, so the destructor early-returns and its restore never runs.
  • RestoresBorrowedThreadName exercises 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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.80% 85.90% +0.10%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.00% +0.00%

Changed lines: Changed C/C++ lines covered: 65/65 (100.00%) · Uncovered code

Full report · Diff report

@azat
azat added this pull request to the merge queue Jul 8, 2026
Merged via the queue into ClickHouse:master with commit 679c9f7 Jul 8, 2026
175 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 8, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…tcher-dtor-allow-existing-group

Preserve borrowed thread name and only borrow group while unwinding in ~CallbackRunnerTask
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-not-for-changelog This PR should not be mentioned in the changelog 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.

5 participants