repro.cpp
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 return nullptr while a producer is between updating __head_ and linking the new node through __prev->next_.
timed_thread_context::schedule() only notifies its worker when push_back() returns true. In the problematic interleaving, push_back() returns false, 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
A is at the consumer's tail.
- A producer enqueues
B, exchanges __head_ from A to B, and is descheduled before writing A.next = B.
- The consumer observes
A.next == nullptr and A != __head_. As documented by the implementation, it interprets this as a producer being midway through an enqueue and returns nullptr.
timed_thread_context::run() treats nullptr as a drained command queue and proceeds to cv_.wait_until(...).
- The producer writes
A.next = B. Because its previous head was A, not the stub node, push_back() returns false.
timed_thread_context::schedule() therefore does not set ready_ or notify the condition variable. B remains 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.
repro.cpp
Switching unittests in our codebasis from the Asio thread pool to
timed_thread_contextfor 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 thecommand_queueand 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_contextoccasionally does not process a newly enqueued timer-cancellation command until its currentwait_untildeadline. This can make cancellation take the complete timer duration (or the scheduler's two-second idle interval), and can change which child ofwhen_anywins.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:An immediate
just(0)races a timer returning1; that result passes through twocontinues_on/when_anystages whose timers return2and3. A normal iteration completes almost immediately with0. On my machine, a timer occasionally wins after its complete 100 ms duration or after 2 s (likely the deadline of thetimed_thread_context) elapsed:The iteration number and delay vary. All five consecutive 1,000,000-iteration runs reproduced the problem.
Also a simplified version without the
middleand theoutersender reproduces the issue, but in a more subtle way. Just racing a 100 ms timer againstjust(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:Expected behavior
The
just(0)sender wins, cancellation of the losing timers is processed promptly, and the outerwhen_anyreturns0.Actual behavior
Occasionally a cancellation command is not processed until a scheduler deadline. A later timer then wins and the outer
when_anyreturns2or3instead of0.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:
Ais at the consumer's tail.B, exchanges__head_fromAtoB, and is descheduled before writingA.next = B.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(...).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.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
633c87370b986735b0c8667993b5fc18bf1b3129The current
mainversions oftimed_thread_scheduler.hppand__intrusive_mpsc_queue.hppappear to retain the relevant code.