5 Commits
Author SHA1 Message Date
smarm-agent 095dead8b1 release: v0.8.1
Fix: try_select / try_select_timeout no longer lose an fd wake when the
actor is preempted between registering its arms and parking (and through
them wait_readable_timeout / wait_writable_timeout). No API changes.
2026-10-18 09:20:36 +02:00
smarm-agent e25b27cfe0 docs: the root-exit sweep does not reach children of a still-live parent
The sweep's trace comment claimed a forgotten actor "costs only a slot,
never a hung run". Not so for a non-trapping child of a parent still live
at sweep time: it is skipped, stopping the parent does not reach it, and
if it loops until told otherwise the run never ends (the try_spawn race
test hit this). Comment corrected; the ROADMAP item on post-sweep spawns
now covers existing children too. Behaviour unchanged.
2026-10-18 09:20:15 +02:00
smarm-agent 164a83eb73 test(try_spawn): gate the racers, and never hang on a failed race
racing_try_spawns_claim_exactly_the_free_slots failed ~1 in 4 runs on a
2-vCPU box (same rate on v0.8.0). With 4 scheduler threads the first
spawner started claiming while root was still spawning the rest, so the
precondition "every spawner holds its slot before the race" was false:
root's own spawn hit the full table and panicked.

When root panicked with a spawner still mid-race, the run hung instead of
failing: that spawner's holders sit under a live parent at root exit, so
the sweep skips them, and they spin on `release` forever.

Spawners now wait on a start gate that root opens after spawning all of
them, and a drop guard sets `release` if root unwinds. 400/400 passes
(200 idle, 200 under CPU load).
2026-10-18 09:20:15 +02:00
smarm-agent 2baf73cbfe docs(roadmap): register-to-park is a NoPreempt region; log the timeout-delay siblings
Gotcha: RunningNotified only covers a wake that lands while the waiter is
still Running. A waiter preempted between begin_wait and park_current is
Queued, and unpark on a Queued word is a no-op, so the NoPreempt guard is
what makes the window safe (the select fix in the previous commit).

Medium-priority item: recv_timeout and Mutex::lock_timeout have the same
shape without the guard; their wake is delayed to the timeout rather than
lost. Not fixed here.
2026-10-18 08:39:42 +02:00
smarm-agent 495acc0c47 fix(select): no preemption between arm registration and park
try_select / try_select_timeout registered their arms under the current
park-epoch, then did more work (allocating the timeout target, inserting
the timer) before park_current. A preemption in that window leaves the
actor Queued, and StateWord::unpark treats a Queued actor as a no-op: an
fd arm's one-shot registration consumed by the epoll thread there is a
lost wake, and the actor sleeps until its timeout (or forever, in
try_select). wait_fd already guards the same window with NoPreempt.

Seen in urus under CPU pressure: ~1 in 10^4 keep-alive requests stalled
for the full keep-alive timeout with the request unread in the socket
(wait_readable_timeout -> try_select_timeout). The new test forces the
interleaving deterministically (alloc_interval 1, 1-cycle timeslice, one
scheduler, writer holding the thread): both select paths lost the wake
every time before; all pass now, as does the rest of the suite.
2026-10-18 08:39:42 +02:00
6 changed files with 126 additions and 5 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "smarm"
version = "0.8.0"
version = "0.8.1"
edition = "2021"
rust-version = "1.95"
+24 -1
View File
@@ -215,6 +215,15 @@ turns idle into periodic wakeups), or (b) park the branch on a condvar/futex
the AllDone path signals — and at that point consider making the condvar the
idle primitive for the no-io runtime generally (a cross-thread unpark could
signal it too, see below). Decide before any no-io deployment.
#### Wake delayed to timeout: `recv_timeout`, `lock_timeout`
Same register-then-`insert_wait_timer`-then-park shape as the pre-fix `select`
paths, without `NoPreempt`. The wake isn't lost outright (the timer still
fires) but a send or grant landing in the window waits out the whole timeout;
for `Mutex::lock_timeout` that leaves the lock held-but-unused and stalls
every other waiter too. `insert_wait_timer` also allocates under the `timers`
mutex. Fix per site is the `select` one; to close the class, either give
`begin_wait` a guard-returning form, or let `unpark` on a Queued word with a
matching epoch record the notification so the next park returns at once.
#### Cross-thread unpark
`RuntimeInner::enqueue` does not wake idle sibling schedulers — only io
completions write the wake pipe. Mid-flight this is masked (the enqueuing
@@ -295,7 +304,13 @@ outright — `join` what you need finished. No forcing sweep follows.
kill); OTP would deliver a trappable `killed`. Chosen for boundedness.
- A root-exit shutdown reaches only actors live *at that instant*; a
non-trapping forest root that spawns before it unwinds leaves that spawn
to itself (Erlang: an unlinked spawn is nobody's child).
to itself (Erlang: an unlinked spawn is nobody's child). The same holds
for children it already had: they sit under a live parent at sweep time,
so they are skipped, and stopping the parent does not reach them. A child
that loops until told otherwise then keeps the run alive (seen as a hang in
`try_spawn`'s race test whenever its root panicked mid-race). Closing it
means sweeping a forest root's live children when it finalizes after root
exit; that changes teardown semantics, so it is not done yet.
- **Supervisor start *order* is not start *readiness*.** `start_child`
spawns and moves straight on, so an earlier child is merely *scheduled*,
not initialised, when a later sibling starts. A later child that resolves
@@ -342,6 +357,14 @@ outright — `join` what you need finished. No forcing sweep follows.
waker, decide which form it is — if its registration handle can outlive
the wait it was created for, it MUST be epoch-stamped; a wait that can
exit without parking MUST `retire_wait` first (see slot_state.rs).
- **Register-to-park is a `NoPreempt` region.** From `begin_wait` through
`park_current`, hold `NoPreempt` (as `wait_fd`, `sleep`, `block_on_io` and
both `select` paths do). `RunningNotified` absorbs a wake that lands while
the waiter is still *Running*; a waiter preempted in the window is *Queued*,
and `unpark` on a Queued word is a no-op. A one-shot registration (an fd
arm) consumed there is a lost wake: the waiter parks with nothing left to
wake it but its timer, if it has one. Allocation is a preemption point, so
"nothing in between can yield" is not a safe assumption without the guard.
- **`select` exists; a unified per-process mailbox still does not.** The
supervisor keeps its single `supervisor_channel` funnel; `recv_match`
stays per-channel. `select` composes channels at the wait, not into one
+6
View File
@@ -660,6 +660,9 @@ pub fn try_select(arms: &[&dyn Selectable]) -> std::io::Result<usize> {
None => panic!("smarm: select() called outside an actor"),
};
loop {
// Register-to-park must not be a preemption point: a Queued actor drops `unpark_at`,
// so a one-shot fd registration consumed in the window is a lost wake. As in `wait_fd`.
let _np = crate::scheduler::NoPreempt::enter();
let epoch = crate::scheduler::begin_wait();
if let Some(i) = register_arms(me, epoch, arms)? {
return Ok(i);
@@ -815,6 +818,9 @@ pub fn try_select_timeout(
Some(me) => me,
None => panic!("smarm: select_timeout() called outside an actor"),
};
// Prep-to-park region (see `try_select`): the timeout target allocation and the timer
// insert below must not be preemption points while the arms are registered.
let _np = crate::scheduler::NoPreempt::enter();
let epoch = crate::scheduler::begin_wait();
if let Some(i) = register_arms(me, epoch, arms)? {
return Ok(Some(i)); // ready now: the timer was never armed
+4 -3
View File
@@ -2116,9 +2116,10 @@ fn shutdown_forest_roots(inner: &Arc<RuntimeInner>, root: Pid) {
.is_some_and(|ps| ps.is_live_for(parent));
if !parent_live {
// `_probe` so the trace can say what each leftover was: under
// `smarm-trace` every swept actor is a `root_sweep` line — the
// visibility that makes "a forgotten actor costs only a slot, never
// a hung run" a checkable claim rather than a hope.
// `smarm-trace` every swept actor is a `root_sweep` line. Only
// forest roots are swept: a non-trapping child of a parent still
// live here is never addressed, and if it never exits on its own
// it keeps the run alive after that parent is stopped.
let found = crate::scheduler::request_shutdown_inner_probe(inner, pid, root);
#[cfg_attr(not(feature = "smarm-trace"), allow(unused_variables))]
if let Some(trapping) = found {
+72
View File
@@ -0,0 +1,72 @@
//! Regression: a readiness wake landing while a selecting actor is preempted between
//! registering its arms and parking must not be lost. `alloc_interval(1)` and a 1-cycle
//! timeslice make every allocation preempt, so the window is hit on every run.
use std::os::fd::RawFd;
use std::time::{Duration, Instant};
fn pipe() -> (RawFd, RawFd) {
let mut fds = [0; 2];
let r = unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_NONBLOCK | libc::O_CLOEXEC) };
assert_eq!(r, 0);
(fds[0], fds[1])
}
fn run_case(wait: fn(RawFd) -> bool) {
let rt = smarm::init(
smarm::Config::exact(1)
.alloc_interval(1)
.timeslice_cycles(1),
);
rt.run(move || {
let mut worst = Duration::ZERO;
for _ in 0..10 {
let (r, w) = pipe();
let writer = smarm::spawn(move || {
let b = [1u8];
assert_eq!(unsafe { libc::write(w, b.as_ptr() as *const _, 1) }, 1);
// Hold the only scheduler thread (an OS-level sleep, not a park) so the reader
// stays Queued while the epoll thread consumes the readiness and wakes it.
std::thread::sleep(Duration::from_millis(20));
});
let t0 = Instant::now();
assert!(wait(r), "wait reported a timeout with the pipe readable");
worst = worst.max(t0.elapsed());
writer.join().unwrap();
unsafe {
libc::close(r);
libc::close(w);
}
}
// A lost wake usually still returns `true`: the timeout path re-polls the fd, finds
// it readable, and reports ready. So the latency bound is the real check.
assert!(
worst < Duration::from_millis(500),
"worst wake latency {worst:?}: the readiness wake was lost (waited out the timeout)"
);
});
}
#[test]
fn wait_readable_timeout_survives_preemption_before_park() {
run_case(|fd| smarm::wait_readable_timeout(fd, Duration::from_secs(2)).unwrap());
}
#[test]
fn select_with_fd_arm_survives_preemption_before_park() {
run_case(|fd| {
let arm = smarm::FdArm::readable(fd);
smarm::try_select_timeout(&[&arm], Duration::from_secs(2))
.unwrap()
.is_some()
});
}
#[test]
fn wait_readable_survives_preemption_before_park() {
// The guarded path, as a control: wait_fd holds NoPreempt across register-to-park.
run_case(|fd| {
smarm::wait_readable(fd).unwrap();
true
});
}
+19
View File
@@ -12,6 +12,14 @@ use smarm::{spawn, try_spawn, try_spawn_under_with, yield_now, SpawnError, Spawn
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
struct SetOnDrop(Arc<AtomicBool>);
impl Drop for SetOnDrop {
fn drop(&mut self) {
self.0.store(true, Ordering::Release);
}
}
/// A child that holds its slot until `release` flips, without parking
/// machinery: busy-yield keeps the scheduler moving and the slot occupied.
fn holder(release: Arc<AtomicBool>) -> impl FnOnce() + Send + 'static {
@@ -130,6 +138,12 @@ fn racing_try_spawns_claim_exactly_the_free_slots() {
const SPAWNERS: usize = 4;
smarm::runtime::init(Config::exact(4).max_actors(MAX)).run(|| {
let release = Arc::new(AtomicBool::new(false));
// A failing assert below must fail the test, not hang it: holders spawned by a
// still-running spawner are not reached by the root-exit sweep.
let _release_on_unwind = SetOnDrop(release.clone());
// Racers start only once every spawner holds its slot; otherwise the first ones
// can drain the table while root is still spawning the rest.
let go = Arc::new(AtomicBool::new(false));
let won = Arc::new(AtomicUsize::new(0));
let done = Arc::new(AtomicUsize::new(0));
@@ -144,9 +158,13 @@ fn racing_try_spawns_claim_exactly_the_free_slots() {
let mut spawners = Vec::new();
for _ in 0..SPAWNERS {
let release = release.clone();
let go = go.clone();
let won = won.clone();
let done = done.clone();
spawners.push(spawn(move || {
while !go.load(Ordering::Acquire) {
yield_now();
}
loop {
match try_spawn(holder(release.clone())) {
Ok(h) => {
@@ -160,6 +178,7 @@ fn racing_try_spawns_claim_exactly_the_free_slots() {
done.fetch_add(1, Ordering::AcqRel);
}));
}
go.store(true, Ordering::Release);
// Wait for every racer to hit AtCapacity.
while done.load(Ordering::Acquire) < SPAWNERS {
yield_now();