Skip to content

Fibers: fix CondVar timeout race and simplify remote wake - #681

Merged
romange merged 1 commit into
masterfrom
fibers-simplify-remote-wake
Nov 1, 2026
Merged

romange merged 1 commit into
masterfrom
fibers-simplify-remote-wake

Conversation

@romange

@romange romange commented Oct 31, 2026 •

Copy link
Copy Markdown
Owner

Summary

Fixes a race in fb2::CondVar (CondVarAny + fb2::Mutex) when a timed wait races a notify from another thread. The race already exists on master:

  1. The waiter times out.
  2. Meanwhile the notifier, holding the mutex, detaches the waiter and pushes its wake into the waiter's remote queue.
  3. The waiter's re-lock suspends in Mutex::lock() while that wake is still queued.

From there, two things can happen:

  • The notifier unlocks the mutex first. The hand-off schedules the fiber remotely a second time, and ScheduleFromRemote fires the "Already scheduled remotely" DFATAL.
  • The queued wake runs first. The fiber resumes inside Mutex::lock() while its waiter is still linked in the mutex's wait list, then destroys that linked waiter. In release builds this corrupts the list.

The same collision can happen on a single thread when a local fiber holds the mutex across the waiter's timeout and then notifies.

Changes

  • Timeout and notify race to claim a timed wait, so only one of them wakes the fiber. CondVarAny::wait_until creates its waiter with CreateClaimableWaiter(). ProcessSleep() and the notifier that pops the waiter race on a per-fiber wait_claim_ byte.
    • When the timeout wins, no activation is on its way to the waiter, so lt.lock() can suspend safely. A notifier that finds the timed-out waiter skips it, and WaitQueue::NotifyOne() moves on to the next one.
    • When the notifier wins, ProcessSleep() only drops the fiber from the sleep queue, and the notifier's wake resumes it.
    • No locking cost on one thread. A notifier on the waiter's thread uses a relaxed load and store, since ProcessSleep() runs on that thread too. Only remote notifiers and timeouts use a compare-and-swap. wait(), notifies with no waiters, and local notifies do no atomic read-modify-write.
    • wait_claim_ fills the padding byte next to flags_, so FiberInterface does not grow. It is separate from flags_ because joiners on other threads modify flags_ at any time.
    • notify_* must still be called under the caller's lock when waiters may run on other threads. Barrier::Cancel() now notifies under mtx_.
  • PullMyselfFromRemoteReadyQueue is replaced by AwaitRemoteWake(), which EventCount::wait_until uses. It suspends until the dispatcher pulls the fiber from the remote queue, instead of draining that queue inline. As a result:
    • ProcessRemoteReady() loses its active parameter, its return value and the "UB state" recovery (retries, stack traces, LOG(FATAL)).
    • EventCount::wait_until loses its clear_remote bookkeeping.
  • ScheduleFromRemote drops the unreachable IsScheduledRemotely() "revert the flags" branch. kScheduleRemote stays set from push until pull, so whoever wins the bit always finds the fiber out of the queue. The bit check itself stays as a guard against corrupting the intrusive queue.
  • ActivateSameThread uses DCHECK for the same-scheduler check.

Test plan

  • ProactorTest.CondVarTimeout (fb2::Mutex + fb2::CondVar, notifier on another thread) fails in 3 of 4 runs on master's code and passes with this change across epoll and io_uring.
  • New FiberTest.CondVarSkipsTimedOutWaiter: a local notifier holds the mutex across one waiter's timeout, then notify_one() must skip it and wake the next waiter.
  • Mutation checks: making a local notifier wake a timed-out waiter fails CondVarSkipsTimedOutWaiter; letting the timeout wake the fiber after a remote notifier claimed the wait aborts CondVarTimeout on every run.
  • Full fibers_test passes (155 tests). The condvar, timeout, mutex and barrier tests passed 87 repeated iterations with no failures.
  • ctest -L CI was not rerun after the claim rework. On the earlier spinlock version it passed except IoTest.ProcReader, which flakes under -j4 load (major page faults) and passes alone.
  • pre-commit passes.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 9ea57d52-6f33-4017-abfc-3eaebc6a94db
Commits

Reviewing files that changed from the base of the PR and between 62e72f2 and 1e90704.

Files selected for processing: 8
  • util/fibers/detail/fiber_interface.cc
  • util/fibers/detail/fiber_interface.h
  • util/fibers/detail/scheduler.cc
  • util/fibers/detail/wait_queue.cc
  • util/fibers/detail/wait_queue.h
  • util/fibers/fibers_test.cc
  • util/fibers/synchronization.cc
  • util/fibers/synchronization.h

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

Walkthrough

Fiber wait claims arbitrate notifications against timeouts. Wait-queue notification skips timed-out waiters. Scheduler and synchronization code update remote-wake handling, and new tests exercise timed condition-variable waits during notifications.

Changes: Fiber wait and remote wake handling

Layer / File(s) Summary
Notification and timeout claims
util/fibers/detail/fiber_interface.h, util/fibers/detail/fiber_interface.cc, util/fibers/detail/wait_queue.h, util/fibers/detail/wait_queue.cc
FiberInterface adds claimable wait states for notification and timeout. Waiter::Notify reports whether notification succeeded, and NotifyOne skips waiters whose notification fails.
Timed wait integration
util/fibers/synchronization.h, util/fibers/synchronization.cc, util/fibers/detail/scheduler.cc, util/fibers/fibers_test.cc
CondVarAny::wait_until uses a claimable waiter and resolves queue cleanup after reacquiring the lock. ProcessSleep skips wake-up when a notifier claimed the wait. Tests cover an expired waiter followed by an untimed waiter and repeated notifications during timed waits.
Remote activation processing
util/fibers/detail/fiber_interface.h, util/fibers/detail/fiber_interface.cc, util/fibers/detail/scheduler.h, util/fibers/detail/scheduler.cc, util/fibers/epoll_proactor.cc, util/fibers/uring_proactor.cc, util/fibers/synchronization.cc
AwaitRemoteWake replaces PullMyselfFromRemoteReadyQueue. ProcessRemoteReady no longer takes an active fiber or returns a result. Both proactor main loops call the updated method. EventCount::wait_until calls AwaitRemoteWake after unlocking.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Suggested reviewers: kostasrim

Merge Risk: Minimal · previous review 1e907

No actionable merge-blocking defect was established in the inspected wait and notification paths. The change is mergeable after normal checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 25.93% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly and concisely identifies the CondVar timeout race fix and remote-wake simplification, which are the main changes.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description directly explains the timed condition-variable race and the implemented wait-claim, remote-wake, scheduler, wait-queue, and test changes.
Full details: Docstring Coverage

Explanation

Docstring coverage is 25.93% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 27 functions across 11 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches
Generate docstrings
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Fix fiber condition-variable timeout race and simplify remote wakes

🐞 Bug fix 🕐 40+ Minutes

Grey Divider

AI Description

• Prevent timed-out condition-variable waiters from relocking while a remote notification remains
 pending.
• Let dispatchers consume remote wakes instead of draining the queue from a waiting fiber.
• Add a cross-thread regression test for timed waits racing notifications.
Diagram

graph TD
  W["Timed waiter"] --> C["CondVar queue"] --> T{"Still linked?"}
  T -->|"No"| A["Await remote wake"] --> M["Relock mutex"]
  T -->|"Yes"| M
  N["Remote notifier"] --> C --> R["Remote queue"] --> D["Dispatcher"] --> A
Loading
High-Level Assessment

The internal queue lock and dispatcher-owned remote-wake consumption address the race without requiring the caller's lock during timeout cleanup. Retaining inline remote-queue draining would preserve the scheduler complexity this change removes.

Files changed (9) +106 / -129

Bug fix (4) +70 / -124
fiber_interface.ccWait for dispatcher-owned remote activation +8/-16

Wait for dispatcher-owned remote activation

• Replaces inline remote-queue draining with suspension until the dispatcher consumes a pending wake. Changes the same-scheduler activation check to DCHECK.

util/fibers/detail/fiber_interface.cc

scheduler.ccSimplify remote scheduling and dispatcher processing +30/-71

Simplify remote scheduling and dispatcher processing

• Removes the unreachable remote-scheduling flag rollback. Makes ProcessRemoteReady dispatcher-only and removes its active-fiber recovery path.

util/fibers/detail/scheduler.cc

synchronization.ccConsume pending wakes before timed-wait relocking +14/-27

Consume pending wakes before timed-wait relocking

• EventCount now awaits a pending remote wake after queue cleanup. CondVarAny removes a timed-out waiter under its internal lock and awaits any detached notification before the caller relocks.

util/fibers/synchronization.cc

synchronization.hProtect CondVarAny waiters and reorder timeout cleanup +18/-10

Protect CondVarAny waiters and reorder timeout cleanup

• Adds a spinlock around the condition-variable wait queue. Timed waits now complete queue and remote-wake cleanup before reacquiring the external lock.

util/fibers/synchronization.h

Refactor (4) +9 / -5
fiber_interface.hDeclare the remote-wake wait contract +4/-1

Declare the remote-wake wait contract

• Replaces PullMyselfFromRemoteReadyQueue with AwaitRemoteWake and documents when a resumed fiber must call it.

util/fibers/detail/fiber_interface.h

scheduler.hRestrict remote-ready processing to the dispatcher +3/-2

Restrict remote-ready processing to the dispatcher

• Changes ProcessRemoteReady to a no-argument, void method and documents its dispatcher-only contract.

util/fibers/detail/scheduler.h

epoll_proactor.ccAdopt the dispatcher-only remote-ready call +1/-1

Adopt the dispatcher-only remote-ready call

• Updates the epoll loop to use the simplified ProcessRemoteReady interface.

util/fibers/epoll_proactor.cc

uring_proactor.ccAdopt the dispatcher-only remote-ready call +1/-1

Adopt the dispatcher-only remote-ready call

• Updates the io_uring loop to use the simplified ProcessRemoteReady interface.

util/fibers/uring_proactor.cc

Tests (1) +27 / -0
fibers_test.ccExercise condition-variable timeout and notify races +27/-0

Exercise condition-variable timeout and notify races

• Adds a proactor test that repeatedly races a timed CondVar wait against notifications from a fiber on another thread.

util/fibers/fibers_test.cc

@qodo-code-review

qodo-code-review Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Woken timed waiters touch a freed condvar ✓ Resolved
Description
wait_until now calls PostWaitTimeout, which takes the condition variable's own lock_, every
time WaitUntil returns. That happens before the caller's lock is reacquired, even when a notifier
has already unlinked the waiter. Code that follows the standard condition-variable rule ("safe to
destroy once every waiter has been notified") can run notify_all(); unlock; delete cv on another
thread. The woken fiber then spin-locks memory that has already been freed. Before this change, a
notified waiter only read its stack-local Waiter and never touched the condvar after waking.
Code

util/fibers/synchronization.cc[R94-97]

+std::cv_status CondVarAny::PostWaitTimeout(detail::Waiter* waiter, bool timed_out) {
+  {
+    std::unique_lock lk(lock_);
+    if (waiter->IsLinked()) {
Relevance

●●● Strong

Recent synchronization and lifetime safety bugs are accepted; this identifies a concrete condvar
use-after-free regression.

PR-#649
PR-#666

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Old PostWaitTimeout ran under lt and touched wait_queue_ only when waiter.IsLinked(), which
a notified waiter is not. New PostWaitTimeout always runs std::unique_lock lk(lock_) on the
CondVarAny, and wait_until now calls it before lt.lock() (synchronization.h). So in the window
between being woken and reacquiring lt, a notified waiter still touches condvar memory. The header
comments only require that notify_* be called under the caller's mutex. Nothing says the condvar
must stay alive until woken waiters have reacquired the lock.

util/fibers/synchronization.cc[94-108]
util/fibers/synchronization.h[627-646]
util/fibers/synchronization.h[64-96]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`CondVarAny::PostWaitTimeout` always locks the condvar's `lock_` after the waiter wakes and before it reacquires the caller's lock. That stops the standard notify-then-destroy pattern from being safe.

## Fix Focus Areas
- util/fibers/synchronization.cc[94-108]
- util/fibers/synchronization.h[64-96]

## Recommended Fix
Preferred: check `waiter->IsLinked()` without the lock (an acquire load) and take `lock_` only when it might still be linked. A waiter that the notifier has already unlinked can then go straight to `AwaitRemoteWake()` without touching condvar memory. This needs an acquire/release pairing on the unlink, for example a release store of a 'notified' flag in the Waiter.

If that is not practical, add a clear comment on `CondVarAny` saying it must outlive every waiter until that waiter has returned from `wait_until`, which is stricter than `std::condition_variable`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context sources
✅ Compliance rules (platform): 11 rules
✅ Cross-repo context — repo relationships
  Explored: repo: dragonflydb/dragonfly (sha: 1d2c21aa) — View relationship
Review mode: Auto: 🧠 Deep: Concurrency fix spans scheduler, synchronization, and multiple dispatcher paths.

Grey Divider

Tip of the day
💡 Did you know, you can show, collapse, or hide each part of a finding: code, evidence, and all

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread util/fibers/synchronization.cc Resolved
@augmentcode

augmentcode Bot commented Oct 31, 2026

Copy link
Copy Markdown
🤖 Augment PR Summary

Summary: Fixes condition-variable timeout races with cross-thread notifications that could cause duplicate scheduling or wait-list corruption.

  • Adds an internal spinlock to protect CondVarAny wait queues during waits and notifications.
  • Removes timed-out waiters before reacquiring the caller's lock.
  • Consumes pending remote wakes before mutex reacquisition can suspend.
  • Replaces PullMyselfFromRemoteReadyQueue() with AwaitRemoteWake().
  • Leaves remote-queue draining to the dispatcher instead of draining inline.
  • Simplifies EventCount timeout cleanup and removes remote-drain recovery bookkeeping.
  • Removes a redundant remote-scheduling branch while retaining the duplicate-enqueue guard.
  • Updates default, epoll, and io_uring dispatchers to the simplified queue-processing API.
  • Adds a parameterized CondVarTimeout regression stress test using Mutex and CondVar.

🤖 Was this summary useful? React with 👍 or 👎

@augmentcode augmentcode Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Review completed. No suggestions at this time.

Comment augment review to trigger a new review at any time.

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

Both notification methods call FiberActive() even when the queue is empty, unnecessarily initializing fiber infrastructure and retaining a 32 KiB dispatcher stack until thread exit.

1 open issue
What changed in this PR

This PR fixes a condition-variable timeout race in Helio’s fiber synchronization by handling pending remote notifications before re-locking the caller’s mutex.

Changes:

  • Protect condition-variable wait queues with an internal spinlock and clean up timed-out waits before re-locking.
  • Replace inline remote-queue draining with dispatcher-managed wake handling.
  • Add a regression test for concurrent condition-variable timeouts and notifications.
File Description
util/​fibers/​uring_proactor.cc Update the remote-ready processing call.
util/​fibers/​synchronization.h Guard condition-variable queues and reorder timeout cleanup.
util/​fibers/​synchronization.cc Update timeout cleanup to await pending remote wakes.
util/​fibers/​fibers_test.cc Add the condition-variable timeout race regression test.
util/​fibers/​epoll_proactor.cc Update the remote-ready processing call.
util/​fibers/​detail/​scheduler.h Simplify the remote-ready processing interface.
util/​fibers/​detail/​scheduler.cc Simplify remote scheduling and dispatcher queue processing.
util/​fibers/​detail/​fiber_interface.h Declare and document AwaitRemoteWake().
util/​fibers/​detail/​fiber_interface.cc Implement wake awaiting and adjust the scheduler assertion.

Review effort: Balanced

Comment thread util/fibers/synchronization.h Resolved

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.

🔵 Needs a closer look

Changes to cross-thread wake consumption and intrusive waiter lifetimes require human validation of timeout, notification, and relock invariants under stress across the default dispatcher, epoll, and io_uring.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

romange added a commit that referenced this pull request Oct 31, 2026
- When the remote check fires, Preempt() switches to the dispatcher again
  instead of pulling remote fibers itself. It sets round_robin_run_.end_round,
  so the dispatcher ends the round and returns to its loop. There it pulls the
  remote queue and also submits and reaps I/O before it starts the next round.
  Pulling in Preempt() alone left I/O completions waiting until the round ended.
- Only the dispatcher pulls remote fibers again, so the self-pull handling in
  Preempt() and the RemoteWakeBeforeSuspend test are gone. The comments on
  ProcessRemoteReady() and AwaitRemoteWake() are back to their #681 wording.
- Config::remote_check_cycles replaces remote_check_usec, so Preempt() compares
  without converting units. The constructor converts the flag once. Before
  CycleClock::InitOnce(), the conversion gives 0, which disables the check.
- round_robin_run_.yields is now uint32_t, and it shares a word with end_round.

fibers_test passes with --scheduler_remote_queue_check_usec=0 and =1.
ctest -L CI passes, also with the flag's default set to 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@romange
romange requested a balanced review from Copilot October 31, 2026 16:50

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.

🔵 Needs a closer look

Changes to cross-thread timeout/wakeup and queue ownership invariants require human concurrency review and runtime race/stress validation of contested interleavings unavailable in this source-only review.

No open issues 🎉

Review effort: Balanced

@romange
romange force-pushed the fibers-simplify-remote-wake branch from 1e90704 to 0f33e6c Compare October 31, 2026 21:28
romange added a commit that referenced this pull request Oct 31, 2026
…o fibers-remote-check

Conflicts were resolved by taking the squashed #681 (0f33e6c) and
reapplying this branch's own changes (scheduler remote check) on top.
fibers_test passes 156/156 with --scheduler_remote_queue_check_usec at
0 and 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Roman Gershman <romange@gmail.com>
@romange
romange force-pushed the fibers-simplify-remote-wake branch from 0f33e6c to f6b1a9f Compare November 1, 2026 06:01
- Fix a race in fb2::CondVar (CondVarAny + fb2::Mutex). When a timed wait
  timed out while a notifier on another thread detached it, the waiter's
  relock could suspend in Mutex::lock() with the notifier's wake still
  queued. That either scheduled the fiber remotely twice (DFATAL) or
  resumed it inside Mutex::lock() and destroyed a still-linked waiter.
  A local fiber holding the mutex across the timeout could cause the
  same collision.
- The timeout and the notifier now race to claim a timed wait, so only
  one of them wakes the fiber. CondVarAny::wait_until uses
  CreateClaimableWaiter(); ProcessSleep() and the notifier race on a
  per-fiber wait_claim_ byte, and WaitQueue::NotifyOne() skips waiters
  whose wait timed out. A notifier on the waiter's thread uses a relaxed
  load and store, so local wait and notify do no atomic
  read-modify-write; only remote notifiers and timeouts use a CAS.
- wait_claim_ fills the padding byte next to flags_, so FiberInterface
  does not grow. It is separate from flags_, which joiners on other
  threads modify at any time.
- notify_one()/notify_all() must be called under the mutex when waiters
  may run on other threads; Barrier::Cancel() now notifies under mtx_.
  CondVarAny notify skips FiberActive() when nobody waits.
- Replace PullMyselfFromRemoteReadyQueue with AwaitRemoteWake(), used by
  EventCount::wait_until: it suspends until the dispatcher pulls the
  fiber from the remote queue. ProcessRemoteReady() loses its parameter,
  its return value and the "UB state" recovery, ScheduleFromRemote drops
  its unreachable revert branch, and ActivateSameThread uses DCHECK.
- Add ProactorTest.CondVarTimeout, which failed in 3 of 4 runs before
  the fix, and FiberTest.CondVarSkipsTimedOutWaiter. fibers_test passes,
  mutation checks confirm the tests cover the claim, and the condvar and
  timeout tests passed 87 stress iterations.

Signed-off-by: Roman Gershman <romange@gmail.com>
@romange
romange force-pushed the fibers-simplify-remote-wake branch from f6b1a9f to f6cce89 Compare November 1, 2026 09:10

@dranikpg dranikpg left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Actually simplifies lots of stuff

@romange
romange merged commit 51e8bcc into master Nov 1, 2026
12 checks passed
@romange
romange deleted the fibers-simplify-remote-wake branch November 1, 2026 09:27
romange added a commit that referenced this pull request Nov 1, 2026
…-remote-check

* 'master' of https://github.com/romange/helio:
  Fibers: fix CondVar timeout race and simplify remote wake (#681)

# Conflicts:
#	util/fibers/detail/scheduler.cc
romange added a commit that referenced this pull request Nov 1, 2026
A fiber woken from another thread waits in the remote ready queue until the
dispatcher's turn comes. The dispatcher runs only after every fiber that was
ready ahead of it, so under load a cross-thread hand-off can wait a whole round,
and so can I/O completions.

- Add Scheduler::Config::remote_check_cycles. A fiber may switch out at least
  that long after remote fibers were last pulled, while more are waiting. Then
  Preempt() takes the dispatcher out of the ready queue, sets
  round_robin_run_.end_round and switches to it. The dispatcher ends the round
  and returns to its loop, which pulls the remote queue and processes I/O
  completions and submissions before the next round. The dispatcher's pull
  resets the timer, so this happens at most once per interval.
- The setting is per scheduler and is changed with UpdateConfig(), in cycles,
  so Preempt() compares it without converting units. New schedulers take their
  default from --scheduler_remote_queue_check_usec, converted once in the
  constructor. Before CycleClock::InitOnce(), that conversion gives 0, which
  disables the check. 0, the default, keeps the current behavior.
- round_robin_run_.yields is now uint32_t.
- Add FiberTest.RemoteWakeCheckInterval, which checks the run order with the
  check off and on.
- Restore the ScheduleFromRemote comment that explains why kScheduleRemote can
  not be set there. Merging #679 and #681 brought back an older comment saying
  the call is made under a WaitQueue lock, which ParkNode wakes are not.

fibers_test passes with --scheduler_remote_queue_check_usec=0 and =1.
ctest -L CI passes, also with the flag's default set to 1.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Signed-off-by: Roman Gershman <romange@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
romange added a commit that referenced this pull request Nov 1, 2026
Resolve conflicts with the rebased base, which adds wake-to-front (#679) and
the CondVar timeout fix (#681):
- scheduler.{h,cc}: keep poll_min/poll_max/poll_min_events, ShouldPollEarly()
  and the direct handoff in place of remote_check_cycles; take the base's
  ScheduleFromRemote(to_front) and kWakeToFront handling.
- fiber_interface.{h,cc}: take the base's versions.
- fibers_test.cc: keep RemoteWakeCheckInterval on poll_min_cycles.

fibers_test and fiber_socket_test pass in debug and release, also with
--scheduler_poll_min_usec=0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
romange added a commit that referenced this pull request Nov 1, 2026
A fiber woken from another thread waits in the remote ready queue until the
dispatcher's turn comes. The dispatcher runs only after every fiber that was
ready ahead of it, so under load a cross-thread hand-off can wait a whole round,
and so can I/O completions.

- Add Scheduler::Config::remote_check_cycles. A fiber may switch out at least
  that long after remote fibers were last pulled, while more are waiting. Then
  Preempt() calls EndRoundEarly(), which takes the dispatcher out of the ready
  queue, sets round_robin_run_.end_round and switches to it. The dispatcher
  ends the round and returns to its loop, which pulls the remote queue and
  processes I/O completions and submissions before the next round. The
  dispatcher's pull resets the timer, so this happens at most once per
  interval.
- EndRoundEarly() is a separate function because Preempt() runs on the stack
  of every fiber that switches out. Inline, the branch grew Preempt()'s frame
  from 1216 to 1824 bytes in the unoptimized ASAN build, and
  FiberTest.StackSize overflowed its 8000-byte fiber stack on arm64. Now the
  frame is 1280 bytes.
- The setting is per scheduler and is changed with UpdateConfig(), in cycles,
  so Preempt() compares it without converting units. New schedulers take their
  default from --scheduler_remote_queue_check_usec, converted once in the
  constructor. Before CycleClock::InitOnce(), that conversion gives 0, which
  disables the check. 0, the default, keeps the current behavior.
- Add Scheduler::config(), a read-only getter.
- round_robin_run_.yields is now uint32_t.
- Add FiberTest.RemoteWakeCheckInterval, which checks the run order with the
  check off and on, and restores the scheduler's previous interval.
- Restore the ScheduleFromRemote comment that explains why kScheduleRemote can
  not be set there. Merging #679 and #681 brought back an older comment saying
  the call is made under a WaitQueue lock, which ParkNode wakes are not.
- Add a TODO in InitStackBottom: since #680, stack pages are faulted in on
  first use, which may cost stack locality.

fibers_test passes with --scheduler_remote_queue_check_usec=0 and =1, in the
debug build and in an ASAN build configured like CI.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Signed-off-by: Roman Gershman <romange@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
romange added a commit that referenced this pull request Nov 1, 2026
A fiber woken from another thread waits in the remote ready queue until the
dispatcher's turn comes. The dispatcher runs only after every fiber that was
ready ahead of it, so under load a cross-thread hand-off can wait a whole round,
and so can I/O completions.

- Add Scheduler::Config::remote_check_cycles. A fiber may switch out at least
  that long after remote fibers were last pulled, while more are waiting. Then
  Preempt() calls EndRoundEarly(), which takes the dispatcher out of the ready
  queue, sets round_robin_run_.end_round and switches to it. The dispatcher
  ends the round and returns to its loop, which pulls the remote queue and
  processes I/O completions and submissions before the next round. The
  dispatcher's pull resets the timer, so this happens at most once per
  interval.
- EndRoundEarly() is a separate function because Preempt() runs on the stack
  of every fiber that switches out. Inline, the branch grew Preempt()'s frame
  from 1216 to 1824 bytes in the unoptimized ASAN build, and
  FiberTest.StackSize overflowed its 8000-byte fiber stack on arm64. Now the
  frame is 1280 bytes.
- The setting is per scheduler and is changed with UpdateConfig(), in cycles,
  so Preempt() compares it without converting units. New schedulers take their
  default from --scheduler_remote_queue_check_usec, converted once in the
  constructor. Before CycleClock::InitOnce(), that conversion gives 0, which
  disables the check. 0, the default, keeps the current behavior.
- Add Scheduler::config(), a read-only getter.
- round_robin_run_.yields is now uint32_t.
- Add FiberTest.RemoteWakeCheckInterval, which checks the run order with the
  check off and on, and restores the scheduler's previous interval.
- Restore the ScheduleFromRemote comment that explains why kScheduleRemote can
  not be set there. Merging #679 and #681 brought back an older comment saying
  the call is made under a WaitQueue lock, which ParkNode wakes are not.
- Add a TODO in InitStackBottom: since #680, stack pages are faulted in on
  first use, which may cost stack locality.

fibers_test passes with --scheduler_remote_queue_check_usec=0 and =1, in the
debug build and in an ASAN build configured like CI.

Signed-off-by: Roman Gershman <romange@gmail.com>
romange added a commit that referenced this pull request Nov 1, 2026
A fiber woken from another thread waits in the remote ready queue until the
dispatcher's turn comes. The dispatcher runs only after every fiber that was
ready ahead of it, so under load a cross-thread hand-off can wait a whole round,
and so can I/O completions.

- Add Scheduler::Config::remote_check_cycles. A fiber may switch out at least
  that long after remote fibers were last pulled, while more are waiting. Then
  Preempt() calls EndRoundEarly(), which takes the dispatcher out of the ready
  queue, sets round_robin_run_.end_round and switches to it. The dispatcher
  ends the round and returns to its loop, which pulls the remote queue and
  processes I/O completions and submissions before the next round. The
  dispatcher's pull resets the timer, so this happens at most once per
  interval.
- EndRoundEarly() is a separate function because Preempt() runs on the stack
  of every fiber that switches out. Inline, the branch grew Preempt()'s frame
  from 1216 to 1824 bytes in the unoptimized ASAN build, and
  FiberTest.StackSize overflowed its 8000-byte fiber stack on arm64. Now the
  frame is 1280 bytes.
- The setting is per scheduler and is changed with UpdateConfig(), in cycles,
  so Preempt() compares it without converting units. New schedulers take their
  default from --scheduler_remote_queue_check_usec, converted once in the
  constructor. Before CycleClock::InitOnce(), that conversion gives 0, which
  disables the check. 0, the default, keeps the current behavior.
- Add Scheduler::config(), a read-only getter.
- round_robin_run_.yields is now uint32_t.
- Add FiberTest.RemoteWakeCheckInterval, which checks the run order with the
  check off and on, and restores the scheduler's previous interval.
- Restore the ScheduleFromRemote comment that explains why kScheduleRemote can
  not be set there. Merging #679 and #681 brought back an older comment saying
  the call is made under a WaitQueue lock, which ParkNode wakes are not.
- Add a TODO in InitStackBottom: since #680, stack pages are faulted in on
  first use, which may cost stack locality.
- Finish DNS callback result writes before signaling a copied Done object,
  preventing the requesting fiber from destroying callback arguments while
  they are still in use. Done also handles synchronous c-ares completion.
- Snapshot DNS socket descriptors before processing responses, since c-ares
  can insert sockets and rehash the socket-state map during callbacks. Skip
  sockets removed while earlier responses are processed.
- Free c-ares address-info results and add an immediate-completion regression
  test for IPv4, IPv6 and synchronous lookup failure.

fibers_test passes with --scheduler_remote_queue_check_usec=0 and =1, in the
debug build and in an ASAN build configured like CI.
The DNS regression and all 29 CI tests pass in the debug build.

Signed-off-by: Roman Gershman <romange@gmail.com>
romange added a commit that referenced this pull request Nov 1, 2026
The dispatcher polls for remote wakes, brief tasks and I/O events between
rounds, and a round lasts until every fiber that was ready when it started
switches out. Under load, a cross-thread hand-off, a brief task or an I/O
completion can wait a whole round.

- Add Scheduler::Config::poll_min_cycles, poll_max_cycles and
  poll_min_events, with the flags --scheduler_poll_min_usec (0),
  --scheduler_poll_max_usec (200) and --scheduler_poll_min_events (16). A
  fiber that switches out at least poll_min_cycles after the last poll ends
  the round if remotely woken fibers or brief tasks wait, if at least
  poll_min_events I/O events wait, or if any I/O event waits and
  poll_max_cycles passed since the last poll. --scheduler_poll_min_usec
  defaults to 0, which keeps the current behavior.
- To end the round, Preempt() calls EndRoundEarly(), which takes the
  dispatcher out of the ready queue, sets round_robin_run_.end_round and
  switches to it. The dispatcher returns to its loop, which pulls remote wakes
  and processes tasks and I/O before the next round. ProcessRemoteReady()
  resets the timer. Preempt() does this only while RunReadyFibersInternal()
  runs a normal round, where the dispatcher waits for its turn in the ready
  queue.
- Add Scheduler::ShouldPollEarly() and DispatchPolicy::GetPendingWork().
  ProactorBase reports queued tasks. The uring proactor adds unsubmitted
  SQEs, ready CQEs, and one event if the kernel flags pending task work or a
  CQ overflow; these are memory loads, without a syscall. epoll can not count
  ready events without epoll_wait, so it reports one; unless poll_min_events
  is 1, it polls early at most once per poll_max_cycles.
- EndRoundEarly() and ShouldPollEarly() are separate functions because
  Preempt() runs on the stack of every fiber that switches out. Inline, the
  early-switch code grew Preempt()'s frame from 1216 to 1824 bytes in the
  unoptimized ASAN build, and FiberTest.StackSize overflowed its 8000-byte
  fiber stack on arm64. Now the frame is 1248 bytes.
- The settings are per scheduler and are changed with UpdateConfig(), in
  cycles. New schedulers take their defaults from the flags, converted once
  in the constructor. Before CycleClock::InitOnce(), poll_min_cycles
  converts to 0, which disables early polls.
- Add Scheduler::config(), a read-only getter.
- round_robin_run_.yields is now uint32_t.
- Add FiberTest.RemoteWakeCheckInterval, which checks the run order with
  early polls off and on, and restores the scheduler's previous setting.
- Restore the ScheduleFromRemote comment that explains why kScheduleRemote
  can not be set there. Merging #679 and #681 brought back an older comment
  saying the call is made under a WaitQueue lock, which ParkNode wakes are
  not.
- Add two TODOs. In InitStackBottom: since #680, stack pages are faulted in
  on first use, which may cost stack locality. In the uring loop: under load,
  sleeping fibers wake only after completions, at most once per 2.5ms.

fibers_test passes with --scheduler_poll_min_usec=0 and =1, in the debug
build and in an ASAN build configured like CI.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Signed-off-by: Roman Gershman <romange@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
romange added a commit that referenced this pull request Nov 6, 2026
The dispatcher polls for remote wakes, brief tasks and I/O events between
rounds, and a round lasts until every fiber that was ready when it started
switches out. Under load, a cross-thread hand-off, a brief task or an I/O
completion can wait a whole round.

- Add Scheduler::Config::poll_min_cycles, poll_max_cycles and
  poll_min_events, with the flags --scheduler_poll_min_usec (0),
  --scheduler_poll_max_usec (200) and --scheduler_poll_min_events (16). A
  fiber that switches out at least poll_min_cycles after the last poll ends
  the round if remotely woken fibers or brief tasks wait, if at least
  poll_min_events I/O events wait, or if any I/O event waits and
  poll_max_cycles passed since the last poll. --scheduler_poll_min_usec
  defaults to 0, which keeps the current behavior.
- To end the round, Preempt() calls EndRoundEarly(), which takes the
  dispatcher out of the ready queue, sets round_robin_run_.end_round and
  switches to it. The dispatcher returns to its loop, which pulls remote wakes
  and processes tasks and I/O before the next round. ProcessRemoteReady()
  resets the timer. Preempt() does this only while RunReadyFibersInternal()
  runs a normal round, where the dispatcher waits for its turn in the ready
  queue.
- Add Scheduler::ShouldPollEarly() and DispatchPolicy::GetPendingWork().
  ProactorBase reports queued tasks. The uring proactor adds unsubmitted
  SQEs, ready CQEs, and one event if the kernel flags pending task work or a
  CQ overflow; these are memory loads, without a syscall. epoll can not count
  ready events without epoll_wait, so it reports one; unless poll_min_events
  is 1, it polls early at most once per poll_max_cycles.
- EndRoundEarly() and ShouldPollEarly() are separate functions because
  Preempt() runs on the stack of every fiber that switches out. Inline, the
  early-switch code grew Preempt()'s frame from 1216 to 1824 bytes in the
  unoptimized ASAN build, and FiberTest.StackSize overflowed its 8000-byte
  fiber stack on arm64. Now the frame is 1248 bytes.
- The settings are per scheduler and are changed with UpdateConfig(), in
  cycles. New schedulers take their defaults from the flags, converted once
  in the constructor. Before CycleClock::InitOnce(), poll_min_cycles
  converts to 0, which disables early polls.
- Add Scheduler::config(), a read-only getter.
- round_robin_run_.yields is now uint32_t.
- Add FiberTest.RemoteWakeCheckInterval, which checks the run order with
  early polls off and on, and restores the scheduler's previous setting.
- Restore the ScheduleFromRemote comment that explains why kScheduleRemote
  can not be set there. Merging #679 and #681 brought back an older comment
  saying the call is made under a WaitQueue lock, which ParkNode wakes are
  not.
- Add two TODOs. In InitStackBottom: since #680, stack pages are faulted in
  on first use, which may cost stack locality. In the uring loop: under load,
  sleeping fibers wake only after completions, at most once per 2.5ms.

fibers_test passes with --scheduler_poll_min_usec=0 and =1, in the debug
build and in an ASAN build configured like CI.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Signed-off-by: Roman Gershman <romange@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
romange added a commit that referenced this pull request Nov 9, 2026
…682)

* Fibers: optionally end the round early to poll remote wakes and I/O

The dispatcher polls for remote wakes, brief tasks and I/O events between
rounds, and a round lasts until every fiber that was ready when it started
switches out. Under load, a cross-thread hand-off, a brief task or an I/O
completion can wait a whole round.

- Add Scheduler::Config::poll_min_cycles, poll_max_cycles and
  poll_min_events, with the flags --scheduler_poll_min_usec (0),
  --scheduler_poll_max_usec (200) and --scheduler_poll_min_events (16). A
  fiber that switches out at least poll_min_cycles after the last poll ends
  the round if remotely woken fibers or brief tasks wait, if at least
  poll_min_events I/O events wait, or if any I/O event waits and
  poll_max_cycles passed since the last poll. --scheduler_poll_min_usec
  defaults to 0, which keeps the current behavior.
- To end the round, Preempt() calls EndRoundEarly(), which takes the
  dispatcher out of the ready queue, sets round_robin_run_.end_round and
  switches to it. The dispatcher returns to its loop, which pulls remote wakes
  and processes tasks and I/O before the next round. ProcessRemoteReady()
  resets the timer. Preempt() does this only while RunReadyFibersInternal()
  runs a normal round, where the dispatcher waits for its turn in the ready
  queue.
- Add Scheduler::ShouldPollEarly() and DispatchPolicy::GetPendingWork().
  ProactorBase reports queued tasks. The uring proactor adds unsubmitted
  SQEs, ready CQEs, and one event if the kernel flags pending task work or a
  CQ overflow; these are memory loads, without a syscall. epoll can not count
  ready events without epoll_wait, so it reports one; unless poll_min_events
  is 1, it polls early at most once per poll_max_cycles.
- EndRoundEarly() and ShouldPollEarly() are separate functions because
  Preempt() runs on the stack of every fiber that switches out. Inline, the
  early-switch code grew Preempt()'s frame from 1216 to 1824 bytes in the
  unoptimized ASAN build, and FiberTest.StackSize overflowed its 8000-byte
  fiber stack on arm64. Now the frame is 1248 bytes.
- The settings are per scheduler and are changed with UpdateConfig(), in
  cycles. New schedulers take their defaults from the flags, converted once
  in the constructor. Before CycleClock::InitOnce(), poll_min_cycles
  converts to 0, which disables early polls.
- Add Scheduler::config(), a read-only getter.
- round_robin_run_.yields is now uint32_t.
- Add FiberTest.RemoteWakeCheckInterval, which checks the run order with
  early polls off and on, and restores the scheduler's previous setting.
- Restore the ScheduleFromRemote comment that explains why kScheduleRemote
  can not be set there. Merging #679 and #681 brought back an older comment
  saying the call is made under a WaitQueue lock, which ParkNode wakes are
  not.
- Add two TODOs. In InitStackBottom: since #680, stack pages are faulted in
  on first use, which may cost stack locality. In the uring loop: under load,
  sleeping fibers wake only after completions, at most once per 2.5ms.

fibers_test passes with --scheduler_poll_min_usec=0 and =1, in the debug
build and in an ASAN build configured like CI.

- Gate early-poll work inspection in Preempt when disabled or not yet due.
- Reuse the scheduling timestamp for ready-queue and switch accounting.
- Refresh timestamps after suspend hooks to retain runtime attribution.
- Cover non-due polling and suspend-hook accounting; all 29 CI tests and
  the full fiber suite with early polling enabled pass.

- Separate queued submissions from completion events and flush them at the
  configured minimum interval without switching to the dispatcher.
- Keep completion callbacks on the dispatcher and fall back to it when
  submissions are partial or the ring is busy.
- Share submission handling across workers, full SQs, and the dispatcher,
  preserving deferred kernel task work and submission accounting.
- Cover disabled, not-yet-due, and batched worker flushing; all 29 CI tests
  and enabled-flushing fiber, socket, and file suites pass.
- Add opt-in yield-ring and response-handoff benchmarks, documenting that
  handoff timing includes responses observed without suspending. Both
  benchmarks run successfully with early polling disabled and enabled.

Signed-off-by: Roman Gershman <roman@dragonflydb.io>

---------

Signed-off-by: Roman Gershman <romange@gmail.com>
Signed-off-by: Roman Gershman <roman@dragonflydb.io>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
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