timed_thread_context can miss an enqueue notification and sleep with a command pending
Nobody has claimed this yet.
- Dominant language
- C++
- Stars
- 2.4k
- Forks
- 270
- Avg merge
- 3d 6h
- Merged PRs (30d)
- 39
Description
Switching unittests in our codebasis from the Asio thread pool to timed_thread_context for timeouts, I observed spurious test failures in about 1 of 10,000 runs. With AI assistence, I was able to trace the problem down to a potential issue in the context's interaction with the command_queue and can provide a two-line fix, although I am certainly not fully aware of possible performance implications or unwanted side-effects this change may have.
Summary
exec::timed_thread_context occasionally does not process a newly enqueued timer-cancellation command until its current wait_until deadline. This can make cancellation take the complete timer duration (or the scheduler's two-second idle interval), and can change which child of when_any wins.
The problem appears to be a mismatch between __intrusive_mpsc_queue::pop_front() and the timed scheduler's conditional notification policy:
pop_front()is allowed to returnnullptrwhile a producer is between updating__head_and linking the new node through__prev->next_.timed_thread_context::schedule()only notifies its worker whenpush_back()returnstrue. In the problematic interleaving,push_back()returnsfalse, so the worker goes to sleep even though the producer has now finished linking a pending command.
Reproducer
Save the attached repro.cpp, then build it against the stdexec headers:
g++ -std=c++20 -O2 -pthread -I /path/to/stdexec/include repro.cpp -o repro
./repro
An immediate just(0) races a timer returning 1; that result passes through two continues_on / when_any stages whose timers return 2 and 3. A normal iteration completes almost immediately with 0. On my machine, a timer occasionally wins after its complete 100 ms duration or after 2 s (likely the deadline of the timed_thread_context) elapsed:
wrong winner 3 in iteration 21029 after 100 ms
The iteration number and delay vary. All five consecutive 1,000,000-iteration runs reproduced the problem.
Also a simplified version without the middle and the outer sender reproduces the issue, but in a more subtle way. Just racing a 100 ms timer against just(0), I observed an unexpectedly long execution time of 2 s instead of immediate completion of the sender during runs with 1,000,000 iterations:
long duration 2000ms with winner 0 in iteration 51535
Expected behavior
The just(0) sender wins, cancellation of the losing timers is processed promptly, and the outer when_any returns 0.
Actual behavior
Occasionally a cancellation command is not processed until a scheduler deadline. A later timer then wins and the outer when_any returns 2 or 3 instead of 0.
Suspected interleaving
The relevant producer operations in __intrusive_mpsc_queue::push_back() are:
_Node* __prev = __head_.exchange(__new_node, memory_order_acq_rel);
(__prev->*_Next).store(__new_node, memory_order_release);
return __prev == &__stub_;
One possible interleaving is:
- An existing node
Ais at the consumer's tail. - A producer enqueues
B, exchanges__head_fromAtoB, and is descheduled before writingA.next = B. - The consumer observes
A.next == nullptrandA != __head_. As documented by the implementation, it interprets this as a producer being midway through an enqueue and returnsnullptr. timed_thread_context::run()treatsnullptras a drained command queue and proceeds tocv_.wait_until(...).- The producer writes
A.next = B. Because its previous head wasA, not the stub node,push_back()returnsfalse. timed_thread_context::schedule()therefore does not setready_or notify the condition variable.Bremains pending until the existing deadline wakes the worker.
Proposed fix
Notify the timed scheduler after every completed enqueue. The producer performs the notification only after the new node has been fully linked, so a worker awakened by it can retry pop_front() and observe the command.
- if (command_queue_.push_back(op))
- {
- std::scoped_lock lock{ready_mutex_};
- ready_ = true;
- cv_.notify_one();
- }
+ command_queue_.push_back(op);
+ {
+ std::scoped_lock lock{ready_mutex_};
+ ready_ = true;
+ }
+ cv_.notify_one();
An alternative would be for the consumer to retry/spin when the queue reports the transient "producer in progress" state, but pop_front() currently does not distinguish that state from a genuinely empty queue.
With the unconditional-notification change, the sender-only reproducer completed 500,000 iterations without a failure. The unpatched build reproduced in four out of five 100,000-iteration runs.
Environment
- stdexec commit:
633c87370b986735b0c8667993b5fc18bf1b3129 - Compiler: GCC 14.2.0
- OS: Linux 6.12.101, x86-64
The current main versions of timed_thread_scheduler.hpp and __intrusive_mpsc_queue.hpp appear to retain the relevant code.
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with repro.cpp, then inspect timed_thread_scheduler.hpp and __intrusive_mpsc_queue.hpp, focusing on push_back(), pop_front(), schedule(), and the worker wait path. Run the supplied stress reproducer against the current headers; done means pending cancellation commands wake the worker promptly and repeated runs no longer show delayed completion or the wrong when_any winner.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Active
- Clarity
- Clearly specified
- Newbie friendliness
- 65/100