Skip to content

scheduler: avoid redundant scheduler wake on process handoff - #2329

Draft
pguyot wants to merge 1 commit into
atomvm:release-0.7from
pguyot:w22/scheduler-redundant-wake
Draft

pguyot wants to merge 1 commit into
atomvm:release-0.7from
pguyot:w22/scheduler-redundant-wake

Conversation

@pguyot

@pguyot pguyot commented Jun 3, 2026 •

Copy link
Copy Markdown
Collaborator

Continuation of:

If SMP is enabled, instead of waking the polling scheduler, grab the first ready process immediately if any.

Also simplify scheduler_make_ready a little bit to reduce the number of locks.

Since schedulers no longer poll events at every iteration, resources selected with enif_select and stopped with ERL_NIF_SELECT_STOP_SCHEDULED are now released asynchronously by the scheduler polling events, staying within the boundaries of the BEAM enif_select specification. Adjust test_file's test_gc accordingly.

These changes are made under both the "Apache 2.0" and the "GNU Lesser General
Public License 2.1 or later" license terms (dual license).

SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later

@petermm

This comment has been minimized.

@pguyot
pguyot force-pushed the w22/scheduler-redundant-wake branch 4 times, most recently from ced6470 to f2718d3 Compare June 6, 2026 06:29
@petermm

This comment has been minimized.

@pguyot
pguyot force-pushed the w22/scheduler-redundant-wake branch 5 times, most recently from 994b49f to c1ea3dc Compare June 8, 2026 19:50
@pguyot
pguyot force-pushed the w22/scheduler-redundant-wake branch from c1ea3dc to 74872d3 Compare June 29, 2026 19:59
pguyot added a commit to pguyot/AtomVM that referenced this pull request Jul 14, 2026
The esp32 receive_events loop, after running a listener -- which may
ready a process by delivering it a message -- re-blocked in
xQueueSelectFromSet with the original timeout instead of returning to
the scheduler loop. It relied on the sys_signal sentinel from
scheduler_make_ready to break out; that wake is lost when the event
queue is full (xQueueSendToBack with no timeout silently drops it), and
never sent at all on non-SMP builds with the task driver disabled,
parking the readied process until the next unrelated event or timer
tick. Drain pending events without re-blocking, then return.

This is also a prerequisite for avoiding the redundant scheduler wake on
process handoff (atomvm#2329): once scheduler_make_ready no longer wakes the
poller for a process the readying scheduler can run itself, returning
here is the only way that process gets dispatched. Observed there as
test_socket's active {tcp, Socket, Data} delivery never waking the
receiving process, whose receive then hit its 'after 10000'.

Signed-off-by: Paul Guyot <pguyot@kallisys.net>
pguyot added a commit to pguyot/AtomVM that referenced this pull request Jul 14, 2026
The esp32 receive_events loop, after running a listener -- which may
ready a process by delivering it a message -- re-blocked in
xQueueSelectFromSet with the original timeout instead of returning to
the scheduler loop. It relied on the sys_signal sentinel from
scheduler_make_ready to break out; that wake is lost when the event
queue is full (xQueueSendToBack with no timeout silently drops it), and
never sent at all on non-SMP builds with the task driver disabled,
parking the readied process until the next unrelated event or timer
tick. Drain pending events without re-blocking, then return.

This is also a prerequisite for avoiding the redundant scheduler wake on
process handoff (atomvm#2329): once scheduler_make_ready no longer wakes the
poller for a process the readying scheduler can run itself, returning
here is the only way that process gets dispatched. Observed there as
test_socket's active {tcp, Socket, Data} delivery never waking the
receiving process, whose receive then hit its 'after 10000'.

Signed-off-by: Paul Guyot <pguyot@kallisys.net>
pguyot added a commit to pguyot/AtomVM that referenced this pull request Jul 14, 2026
The esp32 receive_events loop, after running a listener -- which may
ready a process by delivering it a message -- re-blocked in
xQueueSelectFromSet with the original timeout instead of returning to
the scheduler loop. It relied on the sys_signal sentinel from
scheduler_make_ready to break out; that wake is lost when the event
queue is full (xQueueSendToBack with no timeout silently drops it), and
never sent at all on non-SMP builds with the task driver disabled,
parking the readied process until the next unrelated event or timer
tick. Drain pending events without re-blocking, then return.

This is also a prerequisite for avoiding the redundant scheduler wake on
process handoff (atomvm#2329): once scheduler_make_ready no longer wakes the
poller for a process the readying scheduler can run itself, returning
here is the only way that process gets dispatched. Observed there as
test_socket's active {tcp, Socket, Data} delivery never waking the
receiving process, whose receive then hit its 'after 10000'.

Signed-off-by: Paul Guyot <pguyot@kallisys.net>
pguyot added a commit to pguyot/AtomVM that referenced this pull request Jul 14, 2026
The esp32 receive_events loop, after running a listener -- which may
ready a process by delivering it a message -- re-blocked in
xQueueSelectFromSet with the original timeout instead of returning to
the scheduler loop. It relied on the sys_signal sentinel from
scheduler_make_ready to break out; that wake is lost when the event
queue is full (xQueueSendToBack with no timeout silently drops it), and
never sent at all on non-SMP builds with the task driver disabled,
parking the readied process until the next unrelated event or timer
tick. Drain pending events without re-blocking, then return.

This is also a prerequisite for avoiding the redundant scheduler wake on
process handoff (atomvm#2329): once scheduler_make_ready no longer wakes the
poller for a process the readying scheduler can run itself, returning
here is the only way that process gets dispatched. Observed there as
test_socket's active {tcp, Socket, Data} delivery never waking the
receiving process, whose receive then hit its 'after 10000'.

Signed-off-by: Paul Guyot <pguyot@kallisys.net>
pguyot added a commit to pguyot/AtomVM that referenced this pull request Jul 14, 2026
The esp32 receive_events loop, after running a listener -- which may
ready a process by delivering it a message -- re-blocked in
xQueueSelectFromSet with the original timeout instead of returning to
the scheduler loop. It relied on the sys_signal sentinel from
scheduler_make_ready to break out; that wake is lost when the event
queue is full (xQueueSendToBack with no timeout silently drops it), and
never sent at all on non-SMP builds with the task driver disabled,
parking the readied process until the next unrelated event or timer
tick. Drain pending events without re-blocking, then return.

This is also a prerequisite for avoiding the redundant scheduler wake on
process handoff (atomvm#2329): once scheduler_make_ready no longer wakes the
poller for a process the readying scheduler can run itself, returning
here is the only way that process gets dispatched. Observed there as
test_socket's active {tcp, Socket, Data} delivery never waking the
receiving process, whose receive then hit its 'after 10000'.

Signed-off-by: Paul Guyot <pguyot@kallisys.net>
pguyot added a commit to pguyot/AtomVM that referenced this pull request Jul 16, 2026
The esp32 receive_events loop, after running a listener -- which may
ready a process by delivering it a message -- re-blocked in
xQueueSelectFromSet with the original timeout instead of returning to
the scheduler loop. It relied on the sys_signal sentinel from
scheduler_make_ready to break out; that wake is lost when the event
queue is full (xQueueSendToBack with no timeout silently drops it), and
never sent at all on non-SMP builds with the task driver disabled,
parking the readied process until the next unrelated event or timer
tick. Drain pending events without re-blocking, then return.

This is also a prerequisite for avoiding the redundant scheduler wake on
process handoff (atomvm#2329): once scheduler_make_ready no longer wakes the
poller for a process the readying scheduler can run itself, returning
here is the only way that process gets dispatched. Observed there as
test_socket's active {tcp, Socket, Data} delivery never waking the
receiving process, whose receive then hit its 'after 10000'.

Signed-off-by: Paul Guyot <pguyot@kallisys.net>
pguyot added a commit to pguyot/AtomVM that referenced this pull request Jul 20, 2026
The esp32 receive_events loop, after running a listener -- which may
ready a process by delivering it a message -- re-blocked in
xQueueSelectFromSet with the original timeout instead of returning to
the scheduler loop. It relied on the sys_signal sentinel from
scheduler_make_ready to break out; that wake is lost when the event
queue is full (xQueueSendToBack with no timeout silently drops it), and
never sent at all on non-SMP builds with the task driver disabled,
parking the readied process until the next unrelated event or timer
tick. Drain pending events without re-blocking, then return.

This is also a prerequisite for avoiding the redundant scheduler wake on
process handoff (atomvm#2329): once scheduler_make_ready no longer wakes the
poller for a process the readying scheduler can run itself, returning
here is the only way that process gets dispatched. Observed there as
test_socket's active {tcp, Socket, Data} delivery never waking the
receiving process, whose receive then hit its 'after 10000'.

Signed-off-by: Paul Guyot <pguyot@kallisys.net>
pguyot added a commit to pguyot/AtomVM that referenced this pull request Jul 20, 2026
The esp32 receive_events loop, after running a listener -- which may
ready a process by delivering it a message -- re-blocked in
xQueueSelectFromSet with the original timeout instead of returning to
the scheduler loop. It relied on the sys_signal sentinel from
scheduler_make_ready to break out; that wake is lost when the event
queue is full (xQueueSendToBack with no timeout silently drops it), and
never sent at all on non-SMP builds with the task driver disabled,
parking the readied process until the next unrelated event or timer
tick. Drain pending events without re-blocking, then return.

This is also a prerequisite for avoiding the redundant scheduler wake on
process handoff (atomvm#2329): once scheduler_make_ready no longer wakes the
poller for a process the readying scheduler can run itself, returning
here is the only way that process gets dispatched. Observed there as
test_socket's active {tcp, Socket, Data} delivery never waking the
receiving process, whose receive then hit its 'after 10000'.

Signed-off-by: Paul Guyot <pguyot@kallisys.net>
@pguyot
pguyot force-pushed the w22/scheduler-redundant-wake branch from 74872d3 to 780c619 Compare September 25, 2026 16:37
@petermm

This comment was marked as outdated.

Significantly improve performance of ping-pong patterns by avoiding
cross-thread round trips.

scheduler_make_ready now only wakes another scheduler when a runnable
backlog already exists, as the readying thread is a scheduler that picks
the process up itself. The browser main thread is not, so emscripten's
synchronous run_script answers the caller with the _from_task variant.

On ESP32, sys_signal gives a binary semaphore in the event queue set, so
test VMs also drain it before starting.

Signed-off-by: Paul Guyot <pguyot@kallisys.net>
@pguyot
pguyot force-pushed the w22/scheduler-redundant-wake branch from 780c619 to 394f114 Compare December 5, 2026 05:51
@petermm

petermm commented Dec 5, 2026

Copy link
Copy Markdown
Contributor

amp:

PR #2329 review — SMP scheduler handoff

Recommendation: request changes. Fix the post-publication context read and keep deferred task delivery single-consumer. Restore two-process parallelism without reintroducing per-message wakes for a single runnable handoff.

Scope: the last commit, 394f114e, against its parent dd3d0ea93. The oracle independently reviewed the same commit; I checked its findings against the source. The patches below are suggestions, not changes to the PR branch.

Findings

P1 — A spawned process can be freed before the publishing scheduler reads its flags

scheduler_make_ready releases processes_spinlock after publishing ctx, then reads its Running flag while deciding whether to start a worker. On the parent revision that read happened under processes_spinlock, before publication. On this revision, assume an existing runnable backlog, two started schedulers and at least three online. Scheduler A publishes an unlinked short-lived child and pauses after unlocking. Scheduler B can consume the earlier work, dispatch the child and free its context. A resumes with waiting_scheduler == false and a spare worker slot, so the last predicate dereferences the freed context. The ordinary spawn caller holds no lifetime lock on the child here; the scheduler mutex protects worker counts, not process lifetimes.

Snapshot the flag while publishing the context and use only that snapshot after the unlock:

--- a/src/libAtomVM/scheduler.c
+++ b/src/libAtomVM/scheduler.c
@@ -411,8 +411,9 @@
     // scheduler when there is already a *runnable* backlog to parallelize.
     // ctx is not in ready_processes yet (it was just removed), and entries
     // flagged Running are signaled contexts no scheduler can dispatch, so
     // neither inflates the count.
     bool ready_backlog = scheduler_has_runnable_ready(global);
+    bool was_running = context_get_flags(ctx, Running);
 #endif
     // Move to ready queue (from waiting or running)
     // The process may be running (it would be signaled), so mark it
@@ -427,7 +428,7 @@
             if (!global->waiting_scheduler
                 && global->running_schedulers > 0
                 && global->running_schedulers < global->online_schedulers
-                && !context_get_flags(ctx, Running)) {
+                && !was_running) {
                 global->running_schedulers++;
                 smp_scheduler_start(global);
             }

Regression: In an ASan scheduler test with controlled barriers, pause A after unlocking and resume it only after B has destroyed the child and left the poller role. Keep an online slot free so the old code actually evaluates the dangling predicate. Uncoordinated spawn stress can supplement this, but a passing stress run would not rule out the race.

P2 — Two schedulers can deliver deferred task messages out of order

The non-poller fast path now leaves the condition-variable loop with work. It bypasses event polling but still reaches globalcontext_process_task_driver_queues concurrently with the poller in SMP + task-driver builds. In the message queue drain, A can detach batch 1 and pause before delivering it; the same task queues batch 2, and B detaches and delivers it first. The CAS gives each batch one owner, but reversing each detached batch only preserves order within the batch. A consumer such as a browser WebSocket controlling process can see successive messages reversed even when both sends take the deferred route. This is distinct from any pre-existing ordering issue between the direct and deferred routes.

Keep the task-driver drain under the same single-owner guard as sys_poll_events. The no-SMP path still polls and drains as before:

--- a/src/libAtomVM/scheduler.c
+++ b/src/libAtomVM/scheduler.c
@@ -296,14 +296,14 @@
             if (result == NULL && !global->scheduler_stop_all) {
                 // The poller may block waiting for events.
                 sys_poll_events(global, wait_timeout);
             } else {
                 sys_poll_events(global, SYS_POLL_EVENTS_DO_NOT_WAIT);
             }
+#ifdef AVM_TASK_DRIVER_ENABLED
+            globalcontext_process_task_driver_queues(global);
+#endif
 #ifndef AVM_NO_SMP
         }
 #endif
-#ifdef AVM_TASK_DRIVER_ENABLED
-        globalcontext_process_task_driver_queues(global);
-#endif
         SMP_MUTEX_LOCK(global->schedulers_mutex);
     } while (result == NULL);

Regression: The current test_send_message_from_task_order drains the first batch synchronously before queuing the second. Extend coverage through the scheduler: force both sends through the deferred route (the existing test uses processes_spinlock), pause the poller after it detaches message 1, enqueue 2 from the same task, and let a non-polling scheduler take runnable work. Resume the poller and assert that the receiver reads 1, then 2. Calling the drain directly from two test threads would bypass the proposed fix.

P2 — Two CPU-bound processes can alternate on one scheduler indefinitely

When an active process spawns its only child, scheduler_make_ready finds no pre-existing runnable backlog and does not start or wake a worker. At each reduction yield, scheduler_next requeues the current process, making two entries dispatchable, but advertises neither. On a cold VM the second worker is never started; if it already exists and is blocked in event polling, the active scheduler's local dispatch fast path can keep taking work without waking it. This differs from ping-pong, where the sender parks instead of requeueing itself as runnable.

One small fix is to reuse the existing wake/start policy from scheduler_next when requeueing leaves another runnable process. The spinlock is released before taking the scheduler mutex, and the single-runnable path still sends no wake. This diff is on top of the P1 fix above:

--- a/src/libAtomVM/scheduler.c
+++ b/src/libAtomVM/scheduler.c
@@ -382,16 +382,42 @@
     return result;
 }
 
+#ifndef AVM_NO_SMP
+static void scheduler_wake_for_backlog(GlobalContext *global, bool can_start)
+{
+    if (SMP_MUTEX_TRYLOCK(global->schedulers_mutex)) {
+        if (global->waiting_scheduler) {
+            sys_signal(global);
+        } else if (can_start && global->running_schedulers > 0
+            && global->running_schedulers < global->online_schedulers) {
+            global->running_schedulers++;
+            smp_scheduler_start(global);
+        }
+        SMP_MUTEX_UNLOCK(global->schedulers_mutex);
+    } else {
+        sys_signal(global);
+    }
+}
+#endif
+
 Context *scheduler_next(GlobalContext *global, Context *c)
 {
     // Remove c from running and append it at the end of ready list
     // c could already be in ready queue, if it received a message.
     SMP_SPINLOCK_LOCK(&global->processes_spinlock);
     list_remove(&c->processes_list_head);
+#ifndef AVM_NO_SMP
+    bool ready_backlog = scheduler_has_runnable_ready(global);
+#endif
     list_append(&global->ready_processes, &c->processes_list_head);
     context_update_flags(c, ~Running, NoFlags);
     SMP_SPINLOCK_UNLOCK(&global->processes_spinlock);
+#ifndef AVM_NO_SMP
+    if (ready_backlog) {
+        scheduler_wake_for_backlog(global, true);
+    }
+#endif
 
     // Schedule.
     return scheduler_run(global);
 }
@@ -422,23 +448,8 @@
     list_append(&global->ready_processes, &ctx->processes_list_head);
     SMP_SPINLOCK_UNLOCK(&global->processes_spinlock);
 #ifndef AVM_NO_SMP
     if (ready_backlog) {
-        if (SMP_MUTEX_TRYLOCK(global->schedulers_mutex)) {
-            // Start a new scheduler if none are going to take this process.
-            if (!global->waiting_scheduler
-                && global->running_schedulers > 0
-                && global->running_schedulers < global->online_schedulers
-                && !was_running) {
-                global->running_schedulers++;
-                smp_scheduler_start(global);
-            }
-            if (global->waiting_scheduler) {
-                sys_signal(global);
-            }
-            SMP_MUTEX_UNLOCK(global->schedulers_mutex);
-        } else {
-            sys_signal(global);
-        }
+        scheduler_wake_for_backlog(global, !was_running);
     }
 #elif defined(AVM_TASK_DRIVER_ENABLED)
     sys_signal(global);

Missing coverage: prime_smp starts three child workers, which can produce enough backlog to hide this regression. The following standalone probe uses the entry process as one worker and spawns exactly one child. Sample active native threads while both are computing (on macOS, ps -M -p PID); completing the probe alone is not a pass. For an automated scheduler test, assert that both scheduler threads dispatch work rather than imposing a wall-clock speedup threshold. Also cover a previously started worker parked in the poller, and recheck the original ping-pong benchmark.

--- /dev/null
+++ b/tests/erlang_tests/scheduler_two_workers.erl
@@ -0,0 +1,22 @@
+-module(scheduler_two_workers).
+-export([start/0]).
+
+start() ->
+    2 = min(2, erlang:system_info(schedulers)),
+    erlang:system_flag(schedulers_online, 2),
+    Parent = self(),
+    Deadline = erlang:monotonic_time(millisecond) + 3000,
+    spawn(fun() ->
+        burn(Deadline, 10000, 1),
+        Parent ! done
+    end),
+    burn(Deadline, 10000, 1),
+    receive done -> ok end.
+
+burn(Deadline, 0, Value) ->
+    case erlang:monotonic_time(millisecond) >= Deadline of
+        true -> Value;
+        false -> burn(Deadline, 10000, Value)
+    end;
+burn(Deadline, N, Value) ->
+    burn(Deadline, N - 1, (Value * 33 + N) rem 1048576).

Verification

  • On macOS arm64 Debug interpreter builds with SMP and task drivers enabled, the two-worker cold-start probe had two busy native scheduler threads on the parent, one on the PR head, and two with the suggested patches (three runs per build; ps -M sampled one second into each three-second run). All nine runs completed, so a completion-only assertion would have missed the regression.
  • All four review diffs applied cleanly to a scratch copy in the order shown. The patched build and the PR head both passed test-mailbox; that test does not exercise the concurrent-drain interleaving.
  • The context-lifetime and deferred-delivery findings are source-verified interleavings, not reproduced races. The parked-poller variant and ping-pong throughput were not measured. Emscripten, ESP32 and RP2 were inspected but not executed.

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.

2 participants