feat(monitor): demonitor + per-monitor MonitorId (roadmap #5)
Monitors could be installed but never taken down. That gap was about to
bite: the gen_server call timeout we want next is the Erlang dance —
monitor the server, wait for the reply or a Down or a deadline, then
demonitor — and without a way to remove a registration, every timed-out
call would leak a monitor on the server's slot and risk a stale Down
arriving later. So this lands the cleanup primitive before anything
depends on the old shape.
The decision flagged in the roadmap ("decide the monitor API NOW") is
resolved by giving each registration a process-unique MonitorId and
returning it to the caller. monitor() now hands back a
Monitor { id, target, rx } rather than a bare Receiver<Down>: read the
notice from rx as before, and pass &Monitor to demonitor to tear exactly
that registration down. The id comes from a monotonic counter in shared
state, bumped under the same lock that does the registration, so it's
deterministic and never reused — which is what lets demonitor name one of
several monitors on the same target unambiguously. target rode along on
the struct (over the sketched {id, rx}) purely so demonitor can go
straight to the slot instead of scanning every slot for the id.
demonitor returns Option<MonitorId> rather than a bool: Some(id) when a
live registration was found and removed, None when there was nothing left
to remove — it already fired (the registration is drained on finalize),
it was a NoProc, or the slot has been reclaimed. The generation half of
the pid quietly protects that last case: a recycled slot index fails
slot_mut's generation check, so a late demonitor is a clean no-op and can
never strip a different actor's monitor that happens to share the index.
The one piece of real care is reentrancy. Removing a registration drops
the slot's Sender, and Sender::drop can unpark a parked receiver, which
re-enters the shared mutex — which is not reentrant. So demonitor moves
the sender out of the Vec under the lock and lets it drop only after the
lock is released, the same discipline finalize_actor already follows for
its monitor and supervisor sends.
Flushing a Down the target already queued isn't a separate flag; it falls
out of dropping the Monitor. demonitor(&m); drop(m) stops future notices
and discards any queued one — the gen_server-call cleanup in one move.
Storage is now Vec<(MonitorId, Sender<Down>)>. The three slot-reset sites
were left alone on purpose: they clear/rebuild the Vec, which doesn't care
about the element type, so there's no fourth reset obligation. finalize
just destructures (_, m). Because chained_spawn and yield_many register no
monitors, that Vec stays empty on the hot path — taking an empty Vec costs
the same and the notify loop runs zero times — and a before/after general
probe confirmed both medians sit within noise.
Tests cover the three behaviours that matter: a demonitored watcher gets
no Down (its channel closes), demonitoring one of several leaves the
siblings firing normally, and demonitoring after the Down has already
fired reports None.
This commit is contained in:
+19
-6
@@ -37,7 +37,7 @@ use crate::actor::{
|
||||
use crate::channel::Sender;
|
||||
use crate::context::{get_actor_sp, set_actor_sp, switch_to_actor};
|
||||
use crate::io::IoThread;
|
||||
use crate::monitor::{Down, DownReason};
|
||||
use crate::monitor::{Down, DownReason, MonitorId};
|
||||
use crate::pid::Pid;
|
||||
use crate::preempt::PREEMPTION_ENABLED;
|
||||
use crate::supervisor::Signal;
|
||||
@@ -224,10 +224,11 @@ pub(crate) struct Slot {
|
||||
pub(crate) waiters: Vec<Pid>,
|
||||
pub(crate) outcome: Option<Outcome>,
|
||||
pub(crate) supervisor_channel: Option<Sender<Signal>>,
|
||||
/// Watchers registered via `monitor()`. Each receives one `Down` when this
|
||||
/// actor terminates (drained in `finalize_actor`). Distinct from
|
||||
/// `supervisor_channel`, which is the parent's single funnel.
|
||||
pub(crate) monitors: Vec<Sender<Down>>,
|
||||
/// Watchers registered via `monitor()`, each tagged with its
|
||||
/// `MonitorId` so `demonitor` can remove exactly one. Each receives one
|
||||
/// `Down` when this actor terminates (drained in `finalize_actor`).
|
||||
/// Distinct from `supervisor_channel`, which is the parent's single funnel.
|
||||
pub(crate) monitors: Vec<(MonitorId, Sender<Down>)>,
|
||||
/// Bidirectional links (roadmap #3). Each entry is a peer whose abnormal
|
||||
/// death propagates to this actor (and vice versa — the relationship is
|
||||
/// recorded on both slots). Walked + cleared in `finalize_actor`. Reset in
|
||||
@@ -272,6 +273,10 @@ pub(crate) struct SharedState {
|
||||
/// `pending_closures[idx]` is `Some` iff the actor at slot `idx` has not
|
||||
/// yet been resumed for the first time. Grows on demand; never shrinks.
|
||||
pub(crate) pending_closures: Vec<Option<Closure>>,
|
||||
/// Monotonic source of `MonitorId`s, bumped under the shared lock by
|
||||
/// `alloc_monitor_id`. Never reused, so `demonitor` can name one of several
|
||||
/// monitors on the same target unambiguously.
|
||||
pub(crate) next_monitor_id: u64,
|
||||
}
|
||||
|
||||
impl SharedState {
|
||||
@@ -284,9 +289,17 @@ impl SharedState {
|
||||
timers: Timers::new(),
|
||||
io: None,
|
||||
pending_closures: Vec::new(), // indexed by slot index
|
||||
next_monitor_id: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Allocate the next process-unique `MonitorId`. Caller holds the shared
|
||||
/// lock (this is only reached from `monitor()` under `with_shared`).
|
||||
pub(crate) fn alloc_monitor_id(&mut self) -> MonitorId {
|
||||
self.next_monitor_id += 1;
|
||||
MonitorId(self.next_monitor_id)
|
||||
}
|
||||
|
||||
pub(crate) fn allocate_slot(&mut self) -> (u32, u32) {
|
||||
if let Some(idx) = self.free_list.pop() {
|
||||
let gen = self.slots[idx as usize].generation;
|
||||
@@ -602,7 +615,7 @@ fn finalize_actor(inner: &Arc<RuntimeInner>, pid: Pid, outcome: Outcome) {
|
||||
// Notify monitors. Sent outside the shared lock for the same reason as the
|
||||
// supervisor signal: `send` may unpark a parked receiver, which re-takes
|
||||
// the shared mutex.
|
||||
for m in monitors {
|
||||
for (_, m) in monitors {
|
||||
let _ = m.send(Down { pid, reason: down_reason });
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user