Skip to content

Fix timer thread task head race - #3774

Open
songgaoye wants to merge 4 commits into
apache:masterfrom
songgaoye:fix/timer-thread-task-head-race
Open

songgaoye wants to merge 4 commits into
apache:masterfrom
songgaoye:fix/timer-thread-task-head-race

Conversation

@songgaoye

@songgaoye songgaoye commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Issue Number: resolve

Problem Summary:

TimerThread::Bucket::consume_tasks() read _task_head without holding
Bucket::_mutex, while concurrent schedule() calls update the same linked-list
head under the mutex. This is a C++ data race.

Locking every consume_tasks() call fixes the race but regresses the sparse-bucket
fast path: the timer thread scans every bucket, most of which are empty.

An atomic empty hint alone is not sufficient. A timer scan may observe a stale
empty hint after a producer has published a task. If that task is later than the
current heap minimum, the existing earlier-deadline wakeup path does not notify
the timer, allowing the task to remain in its bucket while the timer sleeps.

What is changed and the side effects?

Changed:

  • Add an atomic _has_tasks hint to each TimerThread::Bucket.
  • Keep all _task_head accesses protected by Bucket::_mutex.
  • Use _has_tasks only as a sparse-bucket fast-path hint.
  • Detect bucket empty-to-nonempty transitions during scheduling.
  • Publish a timer wake sequence event for every empty-to-nonempty transition,
    including tasks later than the current heap minimum.
  • Snapshot _nsignals before the timer polls buckets, so a publication after
    the snapshot prevents the subsequent futex wait from sleeping on stale state.
  • Add regression coverage for sparse buckets, concurrent scheduling, and the
    deterministic scan-to-wait publication window, including a simulated stale
    empty-hint observation.

Side effects:

  • Performance effects:

    Preserves the sparse empty-bucket fast path without reading _task_head
    outside its mutex. Empty-to-nonempty bucket transitions perform one additional
    timer-sequence publication and wake attempt; subsequent insertions into an
    already nonempty bucket retain the existing low-contention path.

  • Breaking backward compatibility:

    None.


Check List:

@songgaoye
songgaoye marked this pull request as draft November 24, 2026 13:49
@songgaoye
songgaoye force-pushed the fix/timer-thread-task-head-race branch from 3ade8ac to f751874 Compare November 24, 2026 13:56
@songgaoye
songgaoye marked this pull request as ready for review November 24, 2026 13:57
@wwbmmm
wwbmmm requested a lite review from Copilot November 24, 2026 14:52

Copilot AI left a comment

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.

🟡 Changes recommended

A critical concurrency bug remains in the timer fast path: a stale empty-hint read can miss a newly published bucket task and leave the timer asleep past its deadline.

1 open issue
What changed in this PR

This PR addresses a timer-bucket task-head data race while preserving the sparse-bucket fast path through an atomic task-presence hint.

Changes:

  • Adds atomic task-presence publication and checking around bucket task consumption.
  • Keeps task-list access protected by the bucket mutex.
  • Adds regression tests for sparse buckets, delayed tasks, and concurrent scheduling.
File Description
test/​bthread_timer_thread_unittest.cpp Adds regression and concurrency tests covering sparse buckets, delayed tasks, and timer-bucket scheduling.
src/​bthread/​timer_thread.cpp Adds the atomic bucket task hint and synchronizes task-list consumption and publication.

Review effort: Lite

Comment thread src/bthread/timer_thread.cpp Resolved
Comment thread test/bthread_timer_thread_unittest.cpp Outdated
gate.release(2);

ASSERT_TRUE(WaitUntil([&completed] {
return completed.load(std::memory_order_acquire) == 2;

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.

By the time the second gate is reached, the old implementation has already fetched the wait sequence number, so posting a task here cannot detect a regression that moves the snapshot back to the end of the scan. force_empty_bucket_hint_once_for_test(0) actually skips the next scan. If the 200 ms anchor has expired by then, the timer thread will execute the anchor and then wait indefinitely on the empty heap, leaving the late task in the bucket.

}
if (earlier) {
if (earlier || result.became_nonempty) {
futex_wake_private(&_nsignals, 1);

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.

Adding the empty-bucket wakeup here invalidates the premise of periodic_wakeup_drains_buckets. The late task it submits can now wake the thread itself, so _npending == kN + 1 can hold even if the 50 ms wait limit is removed.

Comment thread test/bthread_timer_thread_unittest.cpp Outdated

EXPECT_EQ(kProducers * kTasksPerProducer,
scheduled.load(std::memory_order_relaxed));
timer_thread.stop_and_join();

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.

scheduled only counts successful enqueues. The assertion will pass even if the consumer has not yet taken an entire batch of tasks, and the subsequent stop_and_join() will prevent the remaining tasks from being returned to the resource pool.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants